Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/time.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <sha1.h>
32 #include <signal.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <unistd.h>
37 #include <libgen.h>
38 #include <time.h>
39 #include <paths.h>
40 #include <regex.h>
41 #include <getopt.h>
42 #include <util.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_path.h"
50 #include "got_cancel.h"
51 #include "got_worktree.h"
52 #include "got_diff.h"
53 #include "got_commit_graph.h"
54 #include "got_fetch.h"
55 #include "got_send.h"
56 #include "got_blame.h"
57 #include "got_privsep.h"
58 #include "got_opentemp.h"
59 #include "got_gotconfig.h"
60 #include "got_dial.h"
61 #include "got_patch.h"
62 #include "got_sigs.h"
63 #include "got_date.h"
65 #ifndef nitems
66 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
67 #endif
69 static volatile sig_atomic_t sigint_received;
70 static volatile sig_atomic_t sigpipe_received;
72 static void
73 catch_sigint(int signo)
74 {
75 sigint_received = 1;
76 }
78 static void
79 catch_sigpipe(int signo)
80 {
81 sigpipe_received = 1;
82 }
85 struct got_cmd {
86 const char *cmd_name;
87 const struct got_error *(*cmd_main)(int, char *[]);
88 void (*cmd_usage)(void);
89 const char *cmd_alias;
90 };
92 __dead static void usage(int, int);
93 __dead static void usage_import(void);
94 __dead static void usage_clone(void);
95 __dead static void usage_fetch(void);
96 __dead static void usage_checkout(void);
97 __dead static void usage_update(void);
98 __dead static void usage_log(void);
99 __dead static void usage_diff(void);
100 __dead static void usage_blame(void);
101 __dead static void usage_tree(void);
102 __dead static void usage_status(void);
103 __dead static void usage_ref(void);
104 __dead static void usage_branch(void);
105 __dead static void usage_tag(void);
106 __dead static void usage_add(void);
107 __dead static void usage_remove(void);
108 __dead static void usage_patch(void);
109 __dead static void usage_revert(void);
110 __dead static void usage_commit(void);
111 __dead static void usage_send(void);
112 __dead static void usage_cherrypick(void);
113 __dead static void usage_backout(void);
114 __dead static void usage_rebase(void);
115 __dead static void usage_histedit(void);
116 __dead static void usage_integrate(void);
117 __dead static void usage_merge(void);
118 __dead static void usage_stage(void);
119 __dead static void usage_unstage(void);
120 __dead static void usage_cat(void);
121 __dead static void usage_info(void);
123 static const struct got_error* cmd_import(int, char *[]);
124 static const struct got_error* cmd_clone(int, char *[]);
125 static const struct got_error* cmd_fetch(int, char *[]);
126 static const struct got_error* cmd_checkout(int, char *[]);
127 static const struct got_error* cmd_update(int, char *[]);
128 static const struct got_error* cmd_log(int, char *[]);
129 static const struct got_error* cmd_diff(int, char *[]);
130 static const struct got_error* cmd_blame(int, char *[]);
131 static const struct got_error* cmd_tree(int, char *[]);
132 static const struct got_error* cmd_status(int, char *[]);
133 static const struct got_error* cmd_ref(int, char *[]);
134 static const struct got_error* cmd_branch(int, char *[]);
135 static const struct got_error* cmd_tag(int, char *[]);
136 static const struct got_error* cmd_add(int, char *[]);
137 static const struct got_error* cmd_remove(int, char *[]);
138 static const struct got_error* cmd_patch(int, char *[]);
139 static const struct got_error* cmd_revert(int, char *[]);
140 static const struct got_error* cmd_commit(int, char *[]);
141 static const struct got_error* cmd_send(int, char *[]);
142 static const struct got_error* cmd_cherrypick(int, char *[]);
143 static const struct got_error* cmd_backout(int, char *[]);
144 static const struct got_error* cmd_rebase(int, char *[]);
145 static const struct got_error* cmd_histedit(int, char *[]);
146 static const struct got_error* cmd_integrate(int, char *[]);
147 static const struct got_error* cmd_merge(int, char *[]);
148 static const struct got_error* cmd_stage(int, char *[]);
149 static const struct got_error* cmd_unstage(int, char *[]);
150 static const struct got_error* cmd_cat(int, char *[]);
151 static const struct got_error* cmd_info(int, char *[]);
153 static const struct got_cmd got_commands[] = {
154 { "import", cmd_import, usage_import, "im" },
155 { "clone", cmd_clone, usage_clone, "cl" },
156 { "fetch", cmd_fetch, usage_fetch, "fe" },
157 { "checkout", cmd_checkout, usage_checkout, "co" },
158 { "update", cmd_update, usage_update, "up" },
159 { "log", cmd_log, usage_log, "" },
160 { "diff", cmd_diff, usage_diff, "di" },
161 { "blame", cmd_blame, usage_blame, "bl" },
162 { "tree", cmd_tree, usage_tree, "tr" },
163 { "status", cmd_status, usage_status, "st" },
164 { "ref", cmd_ref, usage_ref, "" },
165 { "branch", cmd_branch, usage_branch, "br" },
166 { "tag", cmd_tag, usage_tag, "" },
167 { "add", cmd_add, usage_add, "" },
168 { "remove", cmd_remove, usage_remove, "rm" },
169 { "patch", cmd_patch, usage_patch, "pa" },
170 { "revert", cmd_revert, usage_revert, "rv" },
171 { "commit", cmd_commit, usage_commit, "ci" },
172 { "send", cmd_send, usage_send, "se" },
173 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
174 { "backout", cmd_backout, usage_backout, "bo" },
175 { "rebase", cmd_rebase, usage_rebase, "rb" },
176 { "histedit", cmd_histedit, usage_histedit, "he" },
177 { "integrate", cmd_integrate, usage_integrate,"ig" },
178 { "merge", cmd_merge, usage_merge, "mg" },
179 { "stage", cmd_stage, usage_stage, "sg" },
180 { "unstage", cmd_unstage, usage_unstage, "ug" },
181 { "cat", cmd_cat, usage_cat, "" },
182 { "info", cmd_info, usage_info, "" },
183 };
185 static void
186 list_commands(FILE *fp)
188 size_t i;
190 fprintf(fp, "commands:");
191 for (i = 0; i < nitems(got_commands); i++) {
192 const struct got_cmd *cmd = &got_commands[i];
193 fprintf(fp, " %s", cmd->cmd_name);
195 fputc('\n', fp);
198 __dead static void
199 option_conflict(char a, char b)
201 errx(1, "-%c and -%c options are mutually exclusive", a, b);
204 int
205 main(int argc, char *argv[])
207 const struct got_cmd *cmd;
208 size_t i;
209 int ch;
210 int hflag = 0, Vflag = 0;
211 static const struct option longopts[] = {
212 { "version", no_argument, NULL, 'V' },
213 { NULL, 0, NULL, 0 }
214 };
216 setlocale(LC_CTYPE, "");
218 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
219 switch (ch) {
220 case 'h':
221 hflag = 1;
222 break;
223 case 'V':
224 Vflag = 1;
225 break;
226 default:
227 usage(hflag, 1);
228 /* NOTREACHED */
232 argc -= optind;
233 argv += optind;
234 optind = 1;
235 optreset = 1;
237 if (Vflag) {
238 got_version_print_str();
239 return 0;
242 if (argc <= 0)
243 usage(hflag, hflag ? 0 : 1);
245 signal(SIGINT, catch_sigint);
246 signal(SIGPIPE, catch_sigpipe);
248 for (i = 0; i < nitems(got_commands); i++) {
249 const struct got_error *error;
251 cmd = &got_commands[i];
253 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
254 strcmp(cmd->cmd_alias, argv[0]) != 0)
255 continue;
257 if (hflag)
258 cmd->cmd_usage();
260 error = cmd->cmd_main(argc, argv);
261 if (error && error->code != GOT_ERR_CANCELLED &&
262 error->code != GOT_ERR_PRIVSEP_EXIT &&
263 !(sigpipe_received &&
264 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
265 !(sigint_received &&
266 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
267 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
268 return 1;
271 return 0;
274 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
275 list_commands(stderr);
276 return 1;
279 __dead static void
280 usage(int hflag, int status)
282 FILE *fp = (status == 0) ? stdout : stderr;
284 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
285 getprogname());
286 if (hflag)
287 list_commands(fp);
288 exit(status);
291 static const struct got_error *
292 get_editor(char **abspath)
294 const struct got_error *err = NULL;
295 const char *editor;
297 *abspath = NULL;
299 editor = getenv("VISUAL");
300 if (editor == NULL)
301 editor = getenv("EDITOR");
303 if (editor) {
304 err = got_path_find_prog(abspath, editor);
305 if (err)
306 return err;
309 if (*abspath == NULL) {
310 *abspath = strdup("/bin/ed");
311 if (*abspath == NULL)
312 return got_error_from_errno("strdup");
315 return NULL;
318 static const struct got_error *
319 apply_unveil(const char *repo_path, int repo_read_only,
320 const char *worktree_path)
322 const struct got_error *err;
324 #ifdef PROFILE
325 if (unveil("gmon.out", "rwc") != 0)
326 return got_error_from_errno2("unveil", "gmon.out");
327 #endif
328 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
329 return got_error_from_errno2("unveil", repo_path);
331 if (worktree_path && unveil(worktree_path, "rwc") != 0)
332 return got_error_from_errno2("unveil", worktree_path);
334 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
335 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
337 err = got_privsep_unveil_exec_helpers();
338 if (err != NULL)
339 return err;
341 if (unveil(NULL, NULL) != 0)
342 return got_error_from_errno("unveil");
344 return NULL;
347 __dead static void
348 usage_import(void)
350 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
351 "[-r repository-path] directory\n", getprogname());
352 exit(1);
355 static int
356 spawn_editor(const char *editor, const char *file)
358 pid_t pid;
359 sig_t sighup, sigint, sigquit;
360 int st = -1;
362 sighup = signal(SIGHUP, SIG_IGN);
363 sigint = signal(SIGINT, SIG_IGN);
364 sigquit = signal(SIGQUIT, SIG_IGN);
366 switch (pid = fork()) {
367 case -1:
368 goto doneediting;
369 case 0:
370 execl(editor, editor, file, (char *)NULL);
371 _exit(127);
374 while (waitpid(pid, &st, 0) == -1)
375 if (errno != EINTR)
376 break;
378 doneediting:
379 (void)signal(SIGHUP, sighup);
380 (void)signal(SIGINT, sigint);
381 (void)signal(SIGQUIT, sigquit);
383 if (!WIFEXITED(st)) {
384 errno = EINTR;
385 return -1;
388 return WEXITSTATUS(st);
391 static const struct got_error *
392 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
393 const char *initial_content, size_t initial_content_len,
394 int require_modification)
396 const struct got_error *err = NULL;
397 char *line = NULL;
398 size_t linesize = 0;
399 struct stat st, st2;
400 FILE *fp = NULL;
401 size_t len, logmsg_len;
402 char *initial_content_stripped = NULL, *buf = NULL, *s;
404 *logmsg = NULL;
406 if (stat(logmsg_path, &st) == -1)
407 return got_error_from_errno2("stat", logmsg_path);
409 if (spawn_editor(editor, logmsg_path) == -1)
410 return got_error_from_errno("failed spawning editor");
412 if (stat(logmsg_path, &st2) == -1)
413 return got_error_from_errno("stat");
415 if (require_modification &&
416 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
417 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
418 "no changes made to commit message, aborting");
420 /*
421 * Set up a stripped version of the initial content without comments
422 * and blank lines. We need this in order to check if the message
423 * has in fact been edited.
424 */
425 initial_content_stripped = malloc(initial_content_len + 1);
426 if (initial_content_stripped == NULL)
427 return got_error_from_errno("malloc");
428 initial_content_stripped[0] = '\0';
430 buf = strdup(initial_content);
431 if (buf == NULL) {
432 err = got_error_from_errno("strdup");
433 goto done;
435 s = buf;
436 len = 0;
437 while ((line = strsep(&s, "\n")) != NULL) {
438 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
439 continue; /* remove comments and leading empty lines */
440 len = strlcat(initial_content_stripped, line,
441 initial_content_len + 1);
442 if (len >= initial_content_len + 1) {
443 err = got_error(GOT_ERR_NO_SPACE);
444 goto done;
447 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
448 initial_content_stripped[len - 1] = '\0';
449 len--;
452 logmsg_len = st2.st_size;
453 *logmsg = malloc(logmsg_len + 1);
454 if (*logmsg == NULL)
455 return got_error_from_errno("malloc");
456 (*logmsg)[0] = '\0';
458 fp = fopen(logmsg_path, "re");
459 if (fp == NULL) {
460 err = got_error_from_errno("fopen");
461 goto done;
464 len = 0;
465 while (getline(&line, &linesize, fp) != -1) {
466 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
467 continue; /* remove comments and leading empty lines */
468 len = strlcat(*logmsg, line, logmsg_len + 1);
469 if (len >= logmsg_len + 1) {
470 err = got_error(GOT_ERR_NO_SPACE);
471 goto done;
474 free(line);
475 if (ferror(fp)) {
476 err = got_ferror(fp, GOT_ERR_IO);
477 goto done;
479 while (len > 0 && (*logmsg)[len - 1] == '\n') {
480 (*logmsg)[len - 1] = '\0';
481 len--;
484 if (len == 0) {
485 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
486 "commit message cannot be empty, aborting");
487 goto done;
489 if (require_modification &&
490 strcmp(*logmsg, initial_content_stripped) == 0)
491 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
492 "no changes made to commit message, aborting");
493 done:
494 free(initial_content_stripped);
495 free(buf);
496 if (fp && fclose(fp) == EOF && err == NULL)
497 err = got_error_from_errno("fclose");
498 if (err) {
499 free(*logmsg);
500 *logmsg = NULL;
502 return err;
505 static const struct got_error *
506 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
507 const char *path_dir, const char *branch_name)
509 char *initial_content = NULL;
510 const struct got_error *err = NULL;
511 int initial_content_len;
512 int fd = -1;
514 initial_content_len = asprintf(&initial_content,
515 "\n# %s to be imported to branch %s\n", path_dir,
516 branch_name);
517 if (initial_content_len == -1)
518 return got_error_from_errno("asprintf");
520 err = got_opentemp_named_fd(logmsg_path, &fd,
521 GOT_TMPDIR_STR "/got-importmsg", "");
522 if (err)
523 goto done;
525 if (write(fd, initial_content, initial_content_len) == -1) {
526 err = got_error_from_errno2("write", *logmsg_path);
527 goto done;
530 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
531 initial_content_len, 1);
532 done:
533 if (fd != -1 && close(fd) == -1 && err == NULL)
534 err = got_error_from_errno2("close", *logmsg_path);
535 free(initial_content);
536 if (err) {
537 free(*logmsg_path);
538 *logmsg_path = NULL;
540 return err;
543 static const struct got_error *
544 import_progress(void *arg, const char *path)
546 printf("A %s\n", path);
547 return NULL;
550 static const struct got_error *
551 valid_author(const char *author)
553 const char *email = author;
555 /*
556 * Git' expects the author (or committer) to be in the form
557 * "name <email>", which are mostly free form (see the
558 * "committer" description in git-fast-import(1)). We're only
559 * doing this to avoid git's object parser breaking on commits
560 * we create.
561 */
563 while (*author && *author != '\n' && *author != '<' && *author != '>')
564 author++;
565 if (author != email && *author == '<' && *(author - 1) != ' ')
566 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
567 "between author name and email required", email);
568 if (*author++ != '<')
569 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
570 while (*author && *author != '\n' && *author != '<' && *author != '>')
571 author++;
572 if (strcmp(author, ">") != 0)
573 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
574 return NULL;
577 static const struct got_error *
578 get_author(char **author, struct got_repository *repo,
579 struct got_worktree *worktree)
581 const struct got_error *err = NULL;
582 const char *got_author = NULL, *name, *email;
583 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
585 *author = NULL;
587 if (worktree)
588 worktree_conf = got_worktree_get_gotconfig(worktree);
589 repo_conf = got_repo_get_gotconfig(repo);
591 /*
592 * Priority of potential author information sources, from most
593 * significant to least significant:
594 * 1) work tree's .got/got.conf file
595 * 2) repository's got.conf file
596 * 3) repository's git config file
597 * 4) environment variables
598 * 5) global git config files (in user's home directory or /etc)
599 */
601 if (worktree_conf)
602 got_author = got_gotconfig_get_author(worktree_conf);
603 if (got_author == NULL)
604 got_author = got_gotconfig_get_author(repo_conf);
605 if (got_author == NULL) {
606 name = got_repo_get_gitconfig_author_name(repo);
607 email = got_repo_get_gitconfig_author_email(repo);
608 if (name && email) {
609 if (asprintf(author, "%s <%s>", name, email) == -1)
610 return got_error_from_errno("asprintf");
611 return NULL;
614 got_author = getenv("GOT_AUTHOR");
615 if (got_author == NULL) {
616 name = got_repo_get_global_gitconfig_author_name(repo);
617 email = got_repo_get_global_gitconfig_author_email(
618 repo);
619 if (name && email) {
620 if (asprintf(author, "%s <%s>", name, email)
621 == -1)
622 return got_error_from_errno("asprintf");
623 return NULL;
625 /* TODO: Look up user in password database? */
626 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
630 *author = strdup(got_author);
631 if (*author == NULL)
632 return got_error_from_errno("strdup");
634 err = valid_author(*author);
635 if (err) {
636 free(*author);
637 *author = NULL;
639 return err;
642 static const struct got_error *
643 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
644 struct got_worktree *worktree)
646 const char *got_allowed_signers = NULL;
647 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
649 *allowed_signers = NULL;
651 if (worktree)
652 worktree_conf = got_worktree_get_gotconfig(worktree);
653 repo_conf = got_repo_get_gotconfig(repo);
655 /*
656 * Priority of potential author information sources, from most
657 * significant to least significant:
658 * 1) work tree's .got/got.conf file
659 * 2) repository's got.conf file
660 */
662 if (worktree_conf)
663 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
664 worktree_conf);
665 if (got_allowed_signers == NULL)
666 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
667 repo_conf);
669 if (got_allowed_signers) {
670 *allowed_signers = strdup(got_allowed_signers);
671 if (*allowed_signers == NULL)
672 return got_error_from_errno("strdup");
674 return NULL;
677 static const struct got_error *
678 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
679 struct got_worktree *worktree)
681 const char *got_revoked_signers = NULL;
682 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
684 *revoked_signers = NULL;
686 if (worktree)
687 worktree_conf = got_worktree_get_gotconfig(worktree);
688 repo_conf = got_repo_get_gotconfig(repo);
690 /*
691 * Priority of potential author information sources, from most
692 * significant to least significant:
693 * 1) work tree's .got/got.conf file
694 * 2) repository's got.conf file
695 */
697 if (worktree_conf)
698 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
699 worktree_conf);
700 if (got_revoked_signers == NULL)
701 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
702 repo_conf);
704 if (got_revoked_signers) {
705 *revoked_signers = strdup(got_revoked_signers);
706 if (*revoked_signers == NULL)
707 return got_error_from_errno("strdup");
709 return NULL;
712 static const struct got_error *
713 get_signer_id(char **signer_id, struct got_repository *repo,
714 struct got_worktree *worktree)
716 const char *got_signer_id = NULL;
717 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
719 *signer_id = NULL;
721 if (worktree)
722 worktree_conf = got_worktree_get_gotconfig(worktree);
723 repo_conf = got_repo_get_gotconfig(repo);
725 /*
726 * Priority of potential author information sources, from most
727 * significant to least significant:
728 * 1) work tree's .got/got.conf file
729 * 2) repository's got.conf file
730 */
732 if (worktree_conf)
733 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
734 if (got_signer_id == NULL)
735 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
737 if (got_signer_id) {
738 *signer_id = strdup(got_signer_id);
739 if (*signer_id == NULL)
740 return got_error_from_errno("strdup");
742 return NULL;
745 static const struct got_error *
746 get_gitconfig_path(char **gitconfig_path)
748 const char *homedir = getenv("HOME");
750 *gitconfig_path = NULL;
751 if (homedir) {
752 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
753 return got_error_from_errno("asprintf");
756 return NULL;
759 static const struct got_error *
760 cmd_import(int argc, char *argv[])
762 const struct got_error *error = NULL;
763 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
764 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
765 const char *branch_name = NULL;
766 char *id_str = NULL, *logmsg_path = NULL;
767 char refname[PATH_MAX] = "refs/heads/";
768 struct got_repository *repo = NULL;
769 struct got_reference *branch_ref = NULL, *head_ref = NULL;
770 struct got_object_id *new_commit_id = NULL;
771 int ch, n = 0;
772 struct got_pathlist_head ignores;
773 struct got_pathlist_entry *pe;
774 int preserve_logmsg = 0;
775 int *pack_fds = NULL;
777 TAILQ_INIT(&ignores);
779 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
780 switch (ch) {
781 case 'b':
782 branch_name = optarg;
783 break;
784 case 'I':
785 if (optarg[0] == '\0')
786 break;
787 error = got_pathlist_insert(&pe, &ignores, optarg,
788 NULL);
789 if (error)
790 goto done;
791 break;
792 case 'm':
793 logmsg = strdup(optarg);
794 if (logmsg == NULL) {
795 error = got_error_from_errno("strdup");
796 goto done;
798 break;
799 case 'r':
800 repo_path = realpath(optarg, NULL);
801 if (repo_path == NULL) {
802 error = got_error_from_errno2("realpath",
803 optarg);
804 goto done;
806 break;
807 default:
808 usage_import();
809 /* NOTREACHED */
813 argc -= optind;
814 argv += optind;
816 #ifndef PROFILE
817 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
818 "unveil",
819 NULL) == -1)
820 err(1, "pledge");
821 #endif
822 if (argc != 1)
823 usage_import();
825 if (repo_path == NULL) {
826 repo_path = getcwd(NULL, 0);
827 if (repo_path == NULL)
828 return got_error_from_errno("getcwd");
830 got_path_strip_trailing_slashes(repo_path);
831 error = get_gitconfig_path(&gitconfig_path);
832 if (error)
833 goto done;
834 error = got_repo_pack_fds_open(&pack_fds);
835 if (error != NULL)
836 goto done;
837 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
838 if (error)
839 goto done;
841 error = get_author(&author, repo, NULL);
842 if (error)
843 return error;
845 /*
846 * Don't let the user create a branch name with a leading '-'.
847 * While technically a valid reference name, this case is usually
848 * an unintended typo.
849 */
850 if (branch_name && branch_name[0] == '-')
851 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
853 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
854 if (error && error->code != GOT_ERR_NOT_REF)
855 goto done;
857 if (branch_name)
858 n = strlcat(refname, branch_name, sizeof(refname));
859 else if (head_ref && got_ref_is_symbolic(head_ref))
860 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
861 sizeof(refname));
862 else
863 n = strlcat(refname, "main", sizeof(refname));
864 if (n >= sizeof(refname)) {
865 error = got_error(GOT_ERR_NO_SPACE);
866 goto done;
869 error = got_ref_open(&branch_ref, repo, refname, 0);
870 if (error) {
871 if (error->code != GOT_ERR_NOT_REF)
872 goto done;
873 } else {
874 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
875 "import target branch already exists");
876 goto done;
879 path_dir = realpath(argv[0], NULL);
880 if (path_dir == NULL) {
881 error = got_error_from_errno2("realpath", argv[0]);
882 goto done;
884 got_path_strip_trailing_slashes(path_dir);
886 /*
887 * unveil(2) traverses exec(2); if an editor is used we have
888 * to apply unveil after the log message has been written.
889 */
890 if (logmsg == NULL || strlen(logmsg) == 0) {
891 error = get_editor(&editor);
892 if (error)
893 goto done;
894 free(logmsg);
895 error = collect_import_msg(&logmsg, &logmsg_path, editor,
896 path_dir, refname);
897 if (error) {
898 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
899 logmsg_path != NULL)
900 preserve_logmsg = 1;
901 goto done;
905 if (unveil(path_dir, "r") != 0) {
906 error = got_error_from_errno2("unveil", path_dir);
907 if (logmsg_path)
908 preserve_logmsg = 1;
909 goto done;
912 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
913 if (error) {
914 if (logmsg_path)
915 preserve_logmsg = 1;
916 goto done;
919 error = got_repo_import(&new_commit_id, path_dir, logmsg,
920 author, &ignores, repo, import_progress, NULL);
921 if (error) {
922 if (logmsg_path)
923 preserve_logmsg = 1;
924 goto done;
927 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
928 if (error) {
929 if (logmsg_path)
930 preserve_logmsg = 1;
931 goto done;
934 error = got_ref_write(branch_ref, repo);
935 if (error) {
936 if (logmsg_path)
937 preserve_logmsg = 1;
938 goto done;
941 error = got_object_id_str(&id_str, new_commit_id);
942 if (error) {
943 if (logmsg_path)
944 preserve_logmsg = 1;
945 goto done;
948 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
949 if (error) {
950 if (error->code != GOT_ERR_NOT_REF) {
951 if (logmsg_path)
952 preserve_logmsg = 1;
953 goto done;
956 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
957 branch_ref);
958 if (error) {
959 if (logmsg_path)
960 preserve_logmsg = 1;
961 goto done;
964 error = got_ref_write(head_ref, repo);
965 if (error) {
966 if (logmsg_path)
967 preserve_logmsg = 1;
968 goto done;
972 printf("Created branch %s with commit %s\n",
973 got_ref_get_name(branch_ref), id_str);
974 done:
975 if (pack_fds) {
976 const struct got_error *pack_err =
977 got_repo_pack_fds_close(pack_fds);
978 if (error == NULL)
979 error = pack_err;
981 if (preserve_logmsg) {
982 fprintf(stderr, "%s: log message preserved in %s\n",
983 getprogname(), logmsg_path);
984 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
985 error = got_error_from_errno2("unlink", logmsg_path);
986 free(logmsg);
987 free(logmsg_path);
988 free(repo_path);
989 free(editor);
990 free(new_commit_id);
991 free(id_str);
992 free(author);
993 free(gitconfig_path);
994 if (branch_ref)
995 got_ref_close(branch_ref);
996 if (head_ref)
997 got_ref_close(head_ref);
998 return error;
1001 __dead static void
1002 usage_clone(void)
1004 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1005 "repository-URL [directory]\n", getprogname());
1006 exit(1);
1009 struct got_fetch_progress_arg {
1010 char last_scaled_size[FMT_SCALED_STRSIZE];
1011 int last_p_indexed;
1012 int last_p_resolved;
1013 int verbosity;
1015 struct got_repository *repo;
1017 int create_configs;
1018 int configs_created;
1019 struct {
1020 struct got_pathlist_head *symrefs;
1021 struct got_pathlist_head *wanted_branches;
1022 struct got_pathlist_head *wanted_refs;
1023 const char *proto;
1024 const char *host;
1025 const char *port;
1026 const char *remote_repo_path;
1027 const char *git_url;
1028 int fetch_all_branches;
1029 int mirror_references;
1030 } config_info;
1033 /* XXX forward declaration */
1034 static const struct got_error *
1035 create_config_files(const char *proto, const char *host, const char *port,
1036 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1037 int mirror_references, struct got_pathlist_head *symrefs,
1038 struct got_pathlist_head *wanted_branches,
1039 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1041 static const struct got_error *
1042 fetch_progress(void *arg, const char *message, off_t packfile_size,
1043 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1045 const struct got_error *err = NULL;
1046 struct got_fetch_progress_arg *a = arg;
1047 char scaled_size[FMT_SCALED_STRSIZE];
1048 int p_indexed, p_resolved;
1049 int print_size = 0, print_indexed = 0, print_resolved = 0;
1052 * In order to allow a failed clone to be resumed with 'got fetch'
1053 * we try to create configuration files as soon as possible.
1054 * Once the server has sent information about its default branch
1055 * we have all required information.
1057 if (a->create_configs && !a->configs_created &&
1058 !TAILQ_EMPTY(a->config_info.symrefs)) {
1059 err = create_config_files(a->config_info.proto,
1060 a->config_info.host, a->config_info.port,
1061 a->config_info.remote_repo_path,
1062 a->config_info.git_url,
1063 a->config_info.fetch_all_branches,
1064 a->config_info.mirror_references,
1065 a->config_info.symrefs,
1066 a->config_info.wanted_branches,
1067 a->config_info.wanted_refs, a->repo);
1068 if (err)
1069 return err;
1070 a->configs_created = 1;
1073 if (a->verbosity < 0)
1074 return NULL;
1076 if (message && message[0] != '\0') {
1077 printf("\rserver: %s", message);
1078 fflush(stdout);
1079 return NULL;
1082 if (packfile_size > 0 || nobj_indexed > 0) {
1083 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1084 (a->last_scaled_size[0] == '\0' ||
1085 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1086 print_size = 1;
1087 if (strlcpy(a->last_scaled_size, scaled_size,
1088 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1089 return got_error(GOT_ERR_NO_SPACE);
1091 if (nobj_indexed > 0) {
1092 p_indexed = (nobj_indexed * 100) / nobj_total;
1093 if (p_indexed != a->last_p_indexed) {
1094 a->last_p_indexed = p_indexed;
1095 print_indexed = 1;
1096 print_size = 1;
1099 if (nobj_resolved > 0) {
1100 p_resolved = (nobj_resolved * 100) /
1101 (nobj_total - nobj_loose);
1102 if (p_resolved != a->last_p_resolved) {
1103 a->last_p_resolved = p_resolved;
1104 print_resolved = 1;
1105 print_indexed = 1;
1106 print_size = 1;
1111 if (print_size || print_indexed || print_resolved)
1112 printf("\r");
1113 if (print_size)
1114 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1115 if (print_indexed)
1116 printf("; indexing %d%%", p_indexed);
1117 if (print_resolved)
1118 printf("; resolving deltas %d%%", p_resolved);
1119 if (print_size || print_indexed || print_resolved)
1120 fflush(stdout);
1122 return NULL;
1125 static const struct got_error *
1126 create_symref(const char *refname, struct got_reference *target_ref,
1127 int verbosity, struct got_repository *repo)
1129 const struct got_error *err;
1130 struct got_reference *head_symref;
1132 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1133 if (err)
1134 return err;
1136 err = got_ref_write(head_symref, repo);
1137 if (err == NULL && verbosity > 0) {
1138 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1139 got_ref_get_name(target_ref));
1141 got_ref_close(head_symref);
1142 return err;
1145 static const struct got_error *
1146 list_remote_refs(struct got_pathlist_head *symrefs,
1147 struct got_pathlist_head *refs)
1149 const struct got_error *err;
1150 struct got_pathlist_entry *pe;
1152 TAILQ_FOREACH(pe, symrefs, entry) {
1153 const char *refname = pe->path;
1154 const char *targetref = pe->data;
1156 printf("%s: %s\n", refname, targetref);
1159 TAILQ_FOREACH(pe, refs, entry) {
1160 const char *refname = pe->path;
1161 struct got_object_id *id = pe->data;
1162 char *id_str;
1164 err = got_object_id_str(&id_str, id);
1165 if (err)
1166 return err;
1167 printf("%s: %s\n", refname, id_str);
1168 free(id_str);
1171 return NULL;
1174 static const struct got_error *
1175 create_ref(const char *refname, struct got_object_id *id,
1176 int verbosity, struct got_repository *repo)
1178 const struct got_error *err = NULL;
1179 struct got_reference *ref;
1180 char *id_str;
1182 err = got_object_id_str(&id_str, id);
1183 if (err)
1184 return err;
1186 err = got_ref_alloc(&ref, refname, id);
1187 if (err)
1188 goto done;
1190 err = got_ref_write(ref, repo);
1191 got_ref_close(ref);
1193 if (err == NULL && verbosity >= 0)
1194 printf("Created reference %s: %s\n", refname, id_str);
1195 done:
1196 free(id_str);
1197 return err;
1200 static int
1201 match_wanted_ref(const char *refname, const char *wanted_ref)
1203 if (strncmp(refname, "refs/", 5) != 0)
1204 return 0;
1205 refname += 5;
1208 * Prevent fetching of references that won't make any
1209 * sense outside of the remote repository's context.
1211 if (strncmp(refname, "got/", 4) == 0)
1212 return 0;
1213 if (strncmp(refname, "remotes/", 8) == 0)
1214 return 0;
1216 if (strncmp(wanted_ref, "refs/", 5) == 0)
1217 wanted_ref += 5;
1219 /* Allow prefix match. */
1220 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1221 return 1;
1223 /* Allow exact match. */
1224 return (strcmp(refname, wanted_ref) == 0);
1227 static int
1228 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1230 struct got_pathlist_entry *pe;
1232 TAILQ_FOREACH(pe, wanted_refs, entry) {
1233 if (match_wanted_ref(refname, pe->path))
1234 return 1;
1237 return 0;
1240 static const struct got_error *
1241 create_wanted_ref(const char *refname, struct got_object_id *id,
1242 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1244 const struct got_error *err;
1245 char *remote_refname;
1247 if (strncmp("refs/", refname, 5) == 0)
1248 refname += 5;
1250 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1251 remote_repo_name, refname) == -1)
1252 return got_error_from_errno("asprintf");
1254 err = create_ref(remote_refname, id, verbosity, repo);
1255 free(remote_refname);
1256 return err;
1259 static const struct got_error *
1260 create_gotconfig(const char *proto, const char *host, const char *port,
1261 const char *remote_repo_path, const char *default_branch,
1262 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1263 struct got_pathlist_head *wanted_refs, int mirror_references,
1264 struct got_repository *repo)
1266 const struct got_error *err = NULL;
1267 char *gotconfig_path = NULL;
1268 char *gotconfig = NULL;
1269 FILE *gotconfig_file = NULL;
1270 const char *branchname = NULL;
1271 char *branches = NULL, *refs = NULL;
1272 ssize_t n;
1274 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1275 struct got_pathlist_entry *pe;
1276 TAILQ_FOREACH(pe, wanted_branches, entry) {
1277 char *s;
1278 branchname = pe->path;
1279 if (strncmp(branchname, "refs/heads/", 11) == 0)
1280 branchname += 11;
1281 if (asprintf(&s, "%s\"%s\" ",
1282 branches ? branches : "", branchname) == -1) {
1283 err = got_error_from_errno("asprintf");
1284 goto done;
1286 free(branches);
1287 branches = s;
1289 } else if (!fetch_all_branches && default_branch) {
1290 branchname = default_branch;
1291 if (strncmp(branchname, "refs/heads/", 11) == 0)
1292 branchname += 11;
1293 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1294 err = got_error_from_errno("asprintf");
1295 goto done;
1298 if (!TAILQ_EMPTY(wanted_refs)) {
1299 struct got_pathlist_entry *pe;
1300 TAILQ_FOREACH(pe, wanted_refs, entry) {
1301 char *s;
1302 const char *refname = pe->path;
1303 if (strncmp(refname, "refs/", 5) == 0)
1304 branchname += 5;
1305 if (asprintf(&s, "%s\"%s\" ",
1306 refs ? refs : "", refname) == -1) {
1307 err = got_error_from_errno("asprintf");
1308 goto done;
1310 free(refs);
1311 refs = s;
1315 /* Create got.conf(5). */
1316 gotconfig_path = got_repo_get_path_gotconfig(repo);
1317 if (gotconfig_path == NULL) {
1318 err = got_error_from_errno("got_repo_get_path_gotconfig");
1319 goto done;
1321 gotconfig_file = fopen(gotconfig_path, "ae");
1322 if (gotconfig_file == NULL) {
1323 err = got_error_from_errno2("fopen", gotconfig_path);
1324 goto done;
1326 if (asprintf(&gotconfig,
1327 "remote \"%s\" {\n"
1328 "\tserver %s\n"
1329 "\tprotocol %s\n"
1330 "%s%s%s"
1331 "\trepository \"%s\"\n"
1332 "%s%s%s"
1333 "%s%s%s"
1334 "%s"
1335 "%s"
1336 "}\n",
1337 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1338 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1339 remote_repo_path, branches ? "\tbranch { " : "",
1340 branches ? branches : "", branches ? "}\n" : "",
1341 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1342 mirror_references ? "\tmirror_references yes\n" : "",
1343 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1344 err = got_error_from_errno("asprintf");
1345 goto done;
1347 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1348 if (n != strlen(gotconfig)) {
1349 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1350 goto done;
1353 done:
1354 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1355 err = got_error_from_errno2("fclose", gotconfig_path);
1356 free(gotconfig_path);
1357 free(branches);
1358 return err;
1361 static const struct got_error *
1362 create_gitconfig(const char *git_url, const char *default_branch,
1363 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1364 struct got_pathlist_head *wanted_refs, int mirror_references,
1365 struct got_repository *repo)
1367 const struct got_error *err = NULL;
1368 char *gitconfig_path = NULL;
1369 char *gitconfig = NULL;
1370 FILE *gitconfig_file = NULL;
1371 char *branches = NULL, *refs = NULL;
1372 const char *branchname;
1373 ssize_t n;
1375 /* Create a config file Git can understand. */
1376 gitconfig_path = got_repo_get_path_gitconfig(repo);
1377 if (gitconfig_path == NULL) {
1378 err = got_error_from_errno("got_repo_get_path_gitconfig");
1379 goto done;
1381 gitconfig_file = fopen(gitconfig_path, "ae");
1382 if (gitconfig_file == NULL) {
1383 err = got_error_from_errno2("fopen", gitconfig_path);
1384 goto done;
1386 if (fetch_all_branches) {
1387 if (mirror_references) {
1388 if (asprintf(&branches,
1389 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1390 err = got_error_from_errno("asprintf");
1391 goto done;
1393 } else if (asprintf(&branches,
1394 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1395 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1396 err = got_error_from_errno("asprintf");
1397 goto done;
1399 } else if (!TAILQ_EMPTY(wanted_branches)) {
1400 struct got_pathlist_entry *pe;
1401 TAILQ_FOREACH(pe, wanted_branches, entry) {
1402 char *s;
1403 branchname = pe->path;
1404 if (strncmp(branchname, "refs/heads/", 11) == 0)
1405 branchname += 11;
1406 if (mirror_references) {
1407 if (asprintf(&s,
1408 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1409 branches ? branches : "",
1410 branchname, branchname) == -1) {
1411 err = got_error_from_errno("asprintf");
1412 goto done;
1414 } else if (asprintf(&s,
1415 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1416 branches ? branches : "",
1417 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1418 branchname) == -1) {
1419 err = got_error_from_errno("asprintf");
1420 goto done;
1422 free(branches);
1423 branches = s;
1425 } else {
1427 * If the server specified a default branch, use just that one.
1428 * Otherwise fall back to fetching all branches on next fetch.
1430 if (default_branch) {
1431 branchname = default_branch;
1432 if (strncmp(branchname, "refs/heads/", 11) == 0)
1433 branchname += 11;
1434 } else
1435 branchname = "*"; /* fall back to all branches */
1436 if (mirror_references) {
1437 if (asprintf(&branches,
1438 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1439 branchname, branchname) == -1) {
1440 err = got_error_from_errno("asprintf");
1441 goto done;
1443 } else if (asprintf(&branches,
1444 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1445 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1446 branchname) == -1) {
1447 err = got_error_from_errno("asprintf");
1448 goto done;
1451 if (!TAILQ_EMPTY(wanted_refs)) {
1452 struct got_pathlist_entry *pe;
1453 TAILQ_FOREACH(pe, wanted_refs, entry) {
1454 char *s;
1455 const char *refname = pe->path;
1456 if (strncmp(refname, "refs/", 5) == 0)
1457 refname += 5;
1458 if (mirror_references) {
1459 if (asprintf(&s,
1460 "%s\tfetch = refs/%s:refs/%s\n",
1461 refs ? refs : "", refname, refname) == -1) {
1462 err = got_error_from_errno("asprintf");
1463 goto done;
1465 } else if (asprintf(&s,
1466 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1467 refs ? refs : "",
1468 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1469 refname) == -1) {
1470 err = got_error_from_errno("asprintf");
1471 goto done;
1473 free(refs);
1474 refs = s;
1478 if (asprintf(&gitconfig,
1479 "[remote \"%s\"]\n"
1480 "\turl = %s\n"
1481 "%s"
1482 "%s"
1483 "\tfetch = refs/tags/*:refs/tags/*\n",
1484 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1485 refs ? refs : "") == -1) {
1486 err = got_error_from_errno("asprintf");
1487 goto done;
1489 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1490 if (n != strlen(gitconfig)) {
1491 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1492 goto done;
1494 done:
1495 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1496 err = got_error_from_errno2("fclose", gitconfig_path);
1497 free(gitconfig_path);
1498 free(branches);
1499 return err;
1502 static const struct got_error *
1503 create_config_files(const char *proto, const char *host, const char *port,
1504 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1505 int mirror_references, struct got_pathlist_head *symrefs,
1506 struct got_pathlist_head *wanted_branches,
1507 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1509 const struct got_error *err = NULL;
1510 const char *default_branch = NULL;
1511 struct got_pathlist_entry *pe;
1514 * If we asked for a set of wanted branches then use the first
1515 * one of those.
1517 if (!TAILQ_EMPTY(wanted_branches)) {
1518 pe = TAILQ_FIRST(wanted_branches);
1519 default_branch = pe->path;
1520 } else {
1521 /* First HEAD ref listed by server is the default branch. */
1522 TAILQ_FOREACH(pe, symrefs, entry) {
1523 const char *refname = pe->path;
1524 const char *target = pe->data;
1526 if (strcmp(refname, GOT_REF_HEAD) != 0)
1527 continue;
1529 default_branch = target;
1530 break;
1534 /* Create got.conf(5). */
1535 err = create_gotconfig(proto, host, port, remote_repo_path,
1536 default_branch, fetch_all_branches, wanted_branches,
1537 wanted_refs, mirror_references, repo);
1538 if (err)
1539 return err;
1541 /* Create a config file Git can understand. */
1542 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1543 wanted_branches, wanted_refs, mirror_references, repo);
1546 static const struct got_error *
1547 cmd_clone(int argc, char *argv[])
1549 const struct got_error *error = NULL;
1550 const char *uri, *dirname;
1551 char *proto, *host, *port, *repo_name, *server_path;
1552 char *default_destdir = NULL, *id_str = NULL;
1553 const char *repo_path;
1554 struct got_repository *repo = NULL;
1555 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1556 struct got_pathlist_entry *pe;
1557 struct got_object_id *pack_hash = NULL;
1558 int ch, fetchfd = -1, fetchstatus;
1559 pid_t fetchpid = -1;
1560 struct got_fetch_progress_arg fpa;
1561 char *git_url = NULL;
1562 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1563 int list_refs_only = 0;
1564 int *pack_fds = NULL;
1566 TAILQ_INIT(&refs);
1567 TAILQ_INIT(&symrefs);
1568 TAILQ_INIT(&wanted_branches);
1569 TAILQ_INIT(&wanted_refs);
1571 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1572 switch (ch) {
1573 case 'a':
1574 fetch_all_branches = 1;
1575 break;
1576 case 'b':
1577 error = got_pathlist_append(&wanted_branches,
1578 optarg, NULL);
1579 if (error)
1580 return error;
1581 break;
1582 case 'l':
1583 list_refs_only = 1;
1584 break;
1585 case 'm':
1586 mirror_references = 1;
1587 break;
1588 case 'q':
1589 verbosity = -1;
1590 break;
1591 case 'R':
1592 error = got_pathlist_append(&wanted_refs,
1593 optarg, NULL);
1594 if (error)
1595 return error;
1596 break;
1597 case 'v':
1598 if (verbosity < 0)
1599 verbosity = 0;
1600 else if (verbosity < 3)
1601 verbosity++;
1602 break;
1603 default:
1604 usage_clone();
1605 break;
1608 argc -= optind;
1609 argv += optind;
1611 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1612 option_conflict('a', 'b');
1613 if (list_refs_only) {
1614 if (!TAILQ_EMPTY(&wanted_branches))
1615 option_conflict('l', 'b');
1616 if (fetch_all_branches)
1617 option_conflict('l', 'a');
1618 if (mirror_references)
1619 option_conflict('l', 'm');
1620 if (!TAILQ_EMPTY(&wanted_refs))
1621 option_conflict('l', 'R');
1624 uri = argv[0];
1626 if (argc == 1)
1627 dirname = NULL;
1628 else if (argc == 2)
1629 dirname = argv[1];
1630 else
1631 usage_clone();
1633 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1634 &repo_name, uri);
1635 if (error)
1636 goto done;
1638 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1639 host, port ? ":" : "", port ? port : "",
1640 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1641 error = got_error_from_errno("asprintf");
1642 goto done;
1645 if (strcmp(proto, "git") == 0) {
1646 #ifndef PROFILE
1647 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1648 "sendfd dns inet unveil", NULL) == -1)
1649 err(1, "pledge");
1650 #endif
1651 } else if (strcmp(proto, "git+ssh") == 0 ||
1652 strcmp(proto, "ssh") == 0) {
1653 #ifndef PROFILE
1654 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1655 "sendfd unveil", NULL) == -1)
1656 err(1, "pledge");
1657 #endif
1658 } else if (strcmp(proto, "http") == 0 ||
1659 strcmp(proto, "git+http") == 0) {
1660 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1661 goto done;
1662 } else {
1663 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1664 goto done;
1666 if (dirname == NULL) {
1667 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1668 error = got_error_from_errno("asprintf");
1669 goto done;
1671 repo_path = default_destdir;
1672 } else
1673 repo_path = dirname;
1675 if (!list_refs_only) {
1676 error = got_path_mkdir(repo_path);
1677 if (error &&
1678 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1679 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1680 goto done;
1681 if (!got_path_dir_is_empty(repo_path)) {
1682 error = got_error_path(repo_path,
1683 GOT_ERR_DIR_NOT_EMPTY);
1684 goto done;
1688 error = got_dial_apply_unveil(proto);
1689 if (error)
1690 goto done;
1692 error = apply_unveil(repo_path, 0, NULL);
1693 if (error)
1694 goto done;
1696 if (verbosity >= 0)
1697 printf("Connecting to %s\n", git_url);
1699 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1700 server_path, verbosity);
1701 if (error)
1702 goto done;
1704 if (!list_refs_only) {
1705 error = got_repo_init(repo_path, NULL);
1706 if (error)
1707 goto done;
1708 error = got_repo_pack_fds_open(&pack_fds);
1709 if (error != NULL)
1710 goto done;
1711 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1712 if (error)
1713 goto done;
1716 fpa.last_scaled_size[0] = '\0';
1717 fpa.last_p_indexed = -1;
1718 fpa.last_p_resolved = -1;
1719 fpa.verbosity = verbosity;
1720 fpa.create_configs = 1;
1721 fpa.configs_created = 0;
1722 fpa.repo = repo;
1723 fpa.config_info.symrefs = &symrefs;
1724 fpa.config_info.wanted_branches = &wanted_branches;
1725 fpa.config_info.wanted_refs = &wanted_refs;
1726 fpa.config_info.proto = proto;
1727 fpa.config_info.host = host;
1728 fpa.config_info.port = port;
1729 fpa.config_info.remote_repo_path = server_path;
1730 fpa.config_info.git_url = git_url;
1731 fpa.config_info.fetch_all_branches = fetch_all_branches;
1732 fpa.config_info.mirror_references = mirror_references;
1733 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1734 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1735 fetch_all_branches, &wanted_branches, &wanted_refs,
1736 list_refs_only, verbosity, fetchfd, repo,
1737 fetch_progress, &fpa);
1738 if (error)
1739 goto done;
1741 if (list_refs_only) {
1742 error = list_remote_refs(&symrefs, &refs);
1743 goto done;
1746 if (pack_hash == NULL) {
1747 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1748 "server sent an empty pack file");
1749 goto done;
1751 error = got_object_id_str(&id_str, pack_hash);
1752 if (error)
1753 goto done;
1754 if (verbosity >= 0)
1755 printf("\nFetched %s.pack\n", id_str);
1756 free(id_str);
1758 /* Set up references provided with the pack file. */
1759 TAILQ_FOREACH(pe, &refs, entry) {
1760 const char *refname = pe->path;
1761 struct got_object_id *id = pe->data;
1762 char *remote_refname;
1764 if (is_wanted_ref(&wanted_refs, refname) &&
1765 !mirror_references) {
1766 error = create_wanted_ref(refname, id,
1767 GOT_FETCH_DEFAULT_REMOTE_NAME,
1768 verbosity - 1, repo);
1769 if (error)
1770 goto done;
1771 continue;
1774 error = create_ref(refname, id, verbosity - 1, repo);
1775 if (error)
1776 goto done;
1778 if (mirror_references)
1779 continue;
1781 if (strncmp("refs/heads/", refname, 11) != 0)
1782 continue;
1784 if (asprintf(&remote_refname,
1785 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1786 refname + 11) == -1) {
1787 error = got_error_from_errno("asprintf");
1788 goto done;
1790 error = create_ref(remote_refname, id, verbosity - 1, repo);
1791 free(remote_refname);
1792 if (error)
1793 goto done;
1796 /* Set the HEAD reference if the server provided one. */
1797 TAILQ_FOREACH(pe, &symrefs, entry) {
1798 struct got_reference *target_ref;
1799 const char *refname = pe->path;
1800 const char *target = pe->data;
1801 char *remote_refname = NULL, *remote_target = NULL;
1803 if (strcmp(refname, GOT_REF_HEAD) != 0)
1804 continue;
1806 error = got_ref_open(&target_ref, repo, target, 0);
1807 if (error) {
1808 if (error->code == GOT_ERR_NOT_REF) {
1809 error = NULL;
1810 continue;
1812 goto done;
1815 error = create_symref(refname, target_ref, verbosity, repo);
1816 got_ref_close(target_ref);
1817 if (error)
1818 goto done;
1820 if (mirror_references)
1821 continue;
1823 if (strncmp("refs/heads/", target, 11) != 0)
1824 continue;
1826 if (asprintf(&remote_refname,
1827 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1828 refname) == -1) {
1829 error = got_error_from_errno("asprintf");
1830 goto done;
1832 if (asprintf(&remote_target,
1833 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1834 target + 11) == -1) {
1835 error = got_error_from_errno("asprintf");
1836 free(remote_refname);
1837 goto done;
1839 error = got_ref_open(&target_ref, repo, remote_target, 0);
1840 if (error) {
1841 free(remote_refname);
1842 free(remote_target);
1843 if (error->code == GOT_ERR_NOT_REF) {
1844 error = NULL;
1845 continue;
1847 goto done;
1849 error = create_symref(remote_refname, target_ref,
1850 verbosity - 1, repo);
1851 free(remote_refname);
1852 free(remote_target);
1853 got_ref_close(target_ref);
1854 if (error)
1855 goto done;
1857 if (pe == NULL) {
1859 * We failed to set the HEAD reference. If we asked for
1860 * a set of wanted branches use the first of one of those
1861 * which could be fetched instead.
1863 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1864 const char *target = pe->path;
1865 struct got_reference *target_ref;
1867 error = got_ref_open(&target_ref, repo, target, 0);
1868 if (error) {
1869 if (error->code == GOT_ERR_NOT_REF) {
1870 error = NULL;
1871 continue;
1873 goto done;
1876 error = create_symref(GOT_REF_HEAD, target_ref,
1877 verbosity, repo);
1878 got_ref_close(target_ref);
1879 if (error)
1880 goto done;
1881 break;
1884 if (!fpa.configs_created && pe != NULL) {
1885 error = create_config_files(fpa.config_info.proto,
1886 fpa.config_info.host, fpa.config_info.port,
1887 fpa.config_info.remote_repo_path,
1888 fpa.config_info.git_url,
1889 fpa.config_info.fetch_all_branches,
1890 fpa.config_info.mirror_references,
1891 fpa.config_info.symrefs,
1892 fpa.config_info.wanted_branches,
1893 fpa.config_info.wanted_refs, fpa.repo);
1894 if (error)
1895 goto done;
1899 if (verbosity >= 0)
1900 printf("Created %s repository '%s'\n",
1901 mirror_references ? "mirrored" : "cloned", repo_path);
1902 done:
1903 if (pack_fds) {
1904 const struct got_error *pack_err =
1905 got_repo_pack_fds_close(pack_fds);
1906 if (error == NULL)
1907 error = pack_err;
1909 if (fetchpid > 0) {
1910 if (kill(fetchpid, SIGTERM) == -1)
1911 error = got_error_from_errno("kill");
1912 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1913 error = got_error_from_errno("waitpid");
1915 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1916 error = got_error_from_errno("close");
1917 if (repo) {
1918 const struct got_error *close_err = got_repo_close(repo);
1919 if (error == NULL)
1920 error = close_err;
1922 TAILQ_FOREACH(pe, &refs, entry) {
1923 free((void *)pe->path);
1924 free(pe->data);
1926 got_pathlist_free(&refs);
1927 TAILQ_FOREACH(pe, &symrefs, entry) {
1928 free((void *)pe->path);
1929 free(pe->data);
1931 got_pathlist_free(&symrefs);
1932 got_pathlist_free(&wanted_branches);
1933 got_pathlist_free(&wanted_refs);
1934 free(pack_hash);
1935 free(proto);
1936 free(host);
1937 free(port);
1938 free(server_path);
1939 free(repo_name);
1940 free(default_destdir);
1941 free(git_url);
1942 return error;
1945 static const struct got_error *
1946 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1947 int replace_tags, int verbosity, struct got_repository *repo)
1949 const struct got_error *err = NULL;
1950 char *new_id_str = NULL;
1951 struct got_object_id *old_id = NULL;
1953 err = got_object_id_str(&new_id_str, new_id);
1954 if (err)
1955 goto done;
1957 if (!replace_tags &&
1958 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1959 err = got_ref_resolve(&old_id, repo, ref);
1960 if (err)
1961 goto done;
1962 if (got_object_id_cmp(old_id, new_id) == 0)
1963 goto done;
1964 if (verbosity >= 0) {
1965 printf("Rejecting update of existing tag %s: %s\n",
1966 got_ref_get_name(ref), new_id_str);
1968 goto done;
1971 if (got_ref_is_symbolic(ref)) {
1972 if (verbosity >= 0) {
1973 printf("Replacing reference %s: %s\n",
1974 got_ref_get_name(ref),
1975 got_ref_get_symref_target(ref));
1977 err = got_ref_change_symref_to_ref(ref, new_id);
1978 if (err)
1979 goto done;
1980 err = got_ref_write(ref, repo);
1981 if (err)
1982 goto done;
1983 } else {
1984 err = got_ref_resolve(&old_id, repo, ref);
1985 if (err)
1986 goto done;
1987 if (got_object_id_cmp(old_id, new_id) == 0)
1988 goto done;
1990 err = got_ref_change_ref(ref, new_id);
1991 if (err)
1992 goto done;
1993 err = got_ref_write(ref, repo);
1994 if (err)
1995 goto done;
1998 if (verbosity >= 0)
1999 printf("Updated %s: %s\n", got_ref_get_name(ref),
2000 new_id_str);
2001 done:
2002 free(old_id);
2003 free(new_id_str);
2004 return err;
2007 static const struct got_error *
2008 update_symref(const char *refname, struct got_reference *target_ref,
2009 int verbosity, struct got_repository *repo)
2011 const struct got_error *err = NULL, *unlock_err;
2012 struct got_reference *symref;
2013 int symref_is_locked = 0;
2015 err = got_ref_open(&symref, repo, refname, 1);
2016 if (err) {
2017 if (err->code != GOT_ERR_NOT_REF)
2018 return err;
2019 err = got_ref_alloc_symref(&symref, refname, target_ref);
2020 if (err)
2021 goto done;
2023 err = got_ref_write(symref, repo);
2024 if (err)
2025 goto done;
2027 if (verbosity >= 0)
2028 printf("Created reference %s: %s\n",
2029 got_ref_get_name(symref),
2030 got_ref_get_symref_target(symref));
2031 } else {
2032 symref_is_locked = 1;
2034 if (strcmp(got_ref_get_symref_target(symref),
2035 got_ref_get_name(target_ref)) == 0)
2036 goto done;
2038 err = got_ref_change_symref(symref,
2039 got_ref_get_name(target_ref));
2040 if (err)
2041 goto done;
2043 err = got_ref_write(symref, repo);
2044 if (err)
2045 goto done;
2047 if (verbosity >= 0)
2048 printf("Updated %s: %s\n", got_ref_get_name(symref),
2049 got_ref_get_symref_target(symref));
2052 done:
2053 if (symref_is_locked) {
2054 unlock_err = got_ref_unlock(symref);
2055 if (unlock_err && err == NULL)
2056 err = unlock_err;
2058 got_ref_close(symref);
2059 return err;
2062 __dead static void
2063 usage_fetch(void)
2065 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2066 "[-R reference] [-r repository-path] [remote-repository]\n",
2067 getprogname());
2068 exit(1);
2071 static const struct got_error *
2072 delete_missing_ref(struct got_reference *ref,
2073 int verbosity, struct got_repository *repo)
2075 const struct got_error *err = NULL;
2076 struct got_object_id *id = NULL;
2077 char *id_str = NULL;
2079 if (got_ref_is_symbolic(ref)) {
2080 err = got_ref_delete(ref, repo);
2081 if (err)
2082 return err;
2083 if (verbosity >= 0) {
2084 printf("Deleted %s: %s\n",
2085 got_ref_get_name(ref),
2086 got_ref_get_symref_target(ref));
2088 } else {
2089 err = got_ref_resolve(&id, repo, ref);
2090 if (err)
2091 return err;
2092 err = got_object_id_str(&id_str, id);
2093 if (err)
2094 goto done;
2096 err = got_ref_delete(ref, repo);
2097 if (err)
2098 goto done;
2099 if (verbosity >= 0) {
2100 printf("Deleted %s: %s\n",
2101 got_ref_get_name(ref), id_str);
2104 done:
2105 free(id);
2106 free(id_str);
2107 return NULL;
2110 static const struct got_error *
2111 delete_missing_refs(struct got_pathlist_head *their_refs,
2112 struct got_pathlist_head *their_symrefs,
2113 const struct got_remote_repo *remote,
2114 int verbosity, struct got_repository *repo)
2116 const struct got_error *err = NULL, *unlock_err;
2117 struct got_reflist_head my_refs;
2118 struct got_reflist_entry *re;
2119 struct got_pathlist_entry *pe;
2120 char *remote_namespace = NULL;
2121 char *local_refname = NULL;
2123 TAILQ_INIT(&my_refs);
2125 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2126 == -1)
2127 return got_error_from_errno("asprintf");
2129 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2130 if (err)
2131 goto done;
2133 TAILQ_FOREACH(re, &my_refs, entry) {
2134 const char *refname = got_ref_get_name(re->ref);
2135 const char *their_refname;
2137 if (remote->mirror_references) {
2138 their_refname = refname;
2139 } else {
2140 if (strncmp(refname, remote_namespace,
2141 strlen(remote_namespace)) == 0) {
2142 if (strcmp(refname + strlen(remote_namespace),
2143 GOT_REF_HEAD) == 0)
2144 continue;
2145 if (asprintf(&local_refname, "refs/heads/%s",
2146 refname + strlen(remote_namespace)) == -1) {
2147 err = got_error_from_errno("asprintf");
2148 goto done;
2150 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2151 continue;
2153 their_refname = local_refname;
2156 TAILQ_FOREACH(pe, their_refs, entry) {
2157 if (strcmp(their_refname, pe->path) == 0)
2158 break;
2160 if (pe != NULL)
2161 continue;
2163 TAILQ_FOREACH(pe, their_symrefs, entry) {
2164 if (strcmp(their_refname, pe->path) == 0)
2165 break;
2167 if (pe != NULL)
2168 continue;
2170 err = delete_missing_ref(re->ref, verbosity, repo);
2171 if (err)
2172 break;
2174 if (local_refname) {
2175 struct got_reference *ref;
2176 err = got_ref_open(&ref, repo, local_refname, 1);
2177 if (err) {
2178 if (err->code != GOT_ERR_NOT_REF)
2179 break;
2180 free(local_refname);
2181 local_refname = NULL;
2182 continue;
2184 err = delete_missing_ref(ref, verbosity, repo);
2185 if (err)
2186 break;
2187 unlock_err = got_ref_unlock(ref);
2188 got_ref_close(ref);
2189 if (unlock_err && err == NULL) {
2190 err = unlock_err;
2191 break;
2194 free(local_refname);
2195 local_refname = NULL;
2198 done:
2199 got_ref_list_free(&my_refs);
2200 free(remote_namespace);
2201 free(local_refname);
2202 return err;
2205 static const struct got_error *
2206 update_wanted_ref(const char *refname, struct got_object_id *id,
2207 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2209 const struct got_error *err, *unlock_err;
2210 char *remote_refname;
2211 struct got_reference *ref;
2213 if (strncmp("refs/", refname, 5) == 0)
2214 refname += 5;
2216 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2217 remote_repo_name, refname) == -1)
2218 return got_error_from_errno("asprintf");
2220 err = got_ref_open(&ref, repo, remote_refname, 1);
2221 if (err) {
2222 if (err->code != GOT_ERR_NOT_REF)
2223 goto done;
2224 err = create_ref(remote_refname, id, verbosity, repo);
2225 } else {
2226 err = update_ref(ref, id, 0, verbosity, repo);
2227 unlock_err = got_ref_unlock(ref);
2228 if (unlock_err && err == NULL)
2229 err = unlock_err;
2230 got_ref_close(ref);
2232 done:
2233 free(remote_refname);
2234 return err;
2237 static const struct got_error *
2238 delete_ref(struct got_repository *repo, struct got_reference *ref)
2240 const struct got_error *err = NULL;
2241 struct got_object_id *id = NULL;
2242 char *id_str = NULL;
2243 const char *target;
2245 if (got_ref_is_symbolic(ref)) {
2246 target = got_ref_get_symref_target(ref);
2247 } else {
2248 err = got_ref_resolve(&id, repo, ref);
2249 if (err)
2250 goto done;
2251 err = got_object_id_str(&id_str, id);
2252 if (err)
2253 goto done;
2254 target = id_str;
2257 err = got_ref_delete(ref, repo);
2258 if (err)
2259 goto done;
2261 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2262 done:
2263 free(id);
2264 free(id_str);
2265 return err;
2268 static const struct got_error *
2269 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2271 const struct got_error *err = NULL;
2272 struct got_reflist_head refs;
2273 struct got_reflist_entry *re;
2274 char *prefix;
2276 TAILQ_INIT(&refs);
2278 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2279 err = got_error_from_errno("asprintf");
2280 goto done;
2282 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2283 if (err)
2284 goto done;
2286 TAILQ_FOREACH(re, &refs, entry)
2287 delete_ref(repo, re->ref);
2288 done:
2289 got_ref_list_free(&refs);
2290 return err;
2293 static const struct got_error *
2294 cmd_fetch(int argc, char *argv[])
2296 const struct got_error *error = NULL, *unlock_err;
2297 char *cwd = NULL, *repo_path = NULL;
2298 const char *remote_name;
2299 char *proto = NULL, *host = NULL, *port = NULL;
2300 char *repo_name = NULL, *server_path = NULL;
2301 const struct got_remote_repo *remotes, *remote = NULL;
2302 int nremotes;
2303 char *id_str = NULL;
2304 struct got_repository *repo = NULL;
2305 struct got_worktree *worktree = NULL;
2306 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2307 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2308 struct got_pathlist_entry *pe;
2309 struct got_object_id *pack_hash = NULL;
2310 int i, ch, fetchfd = -1, fetchstatus;
2311 pid_t fetchpid = -1;
2312 struct got_fetch_progress_arg fpa;
2313 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2314 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2315 int *pack_fds = NULL;
2317 TAILQ_INIT(&refs);
2318 TAILQ_INIT(&symrefs);
2319 TAILQ_INIT(&wanted_branches);
2320 TAILQ_INIT(&wanted_refs);
2322 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2323 switch (ch) {
2324 case 'a':
2325 fetch_all_branches = 1;
2326 break;
2327 case 'b':
2328 error = got_pathlist_append(&wanted_branches,
2329 optarg, NULL);
2330 if (error)
2331 return error;
2332 break;
2333 case 'd':
2334 delete_refs = 1;
2335 break;
2336 case 'l':
2337 list_refs_only = 1;
2338 break;
2339 case 'q':
2340 verbosity = -1;
2341 break;
2342 case 'R':
2343 error = got_pathlist_append(&wanted_refs,
2344 optarg, NULL);
2345 if (error)
2346 return error;
2347 break;
2348 case 'r':
2349 repo_path = realpath(optarg, NULL);
2350 if (repo_path == NULL)
2351 return got_error_from_errno2("realpath",
2352 optarg);
2353 got_path_strip_trailing_slashes(repo_path);
2354 break;
2355 case 't':
2356 replace_tags = 1;
2357 break;
2358 case 'v':
2359 if (verbosity < 0)
2360 verbosity = 0;
2361 else if (verbosity < 3)
2362 verbosity++;
2363 break;
2364 case 'X':
2365 delete_remote = 1;
2366 break;
2367 default:
2368 usage_fetch();
2369 break;
2372 argc -= optind;
2373 argv += optind;
2375 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2376 option_conflict('a', 'b');
2377 if (list_refs_only) {
2378 if (!TAILQ_EMPTY(&wanted_branches))
2379 option_conflict('l', 'b');
2380 if (fetch_all_branches)
2381 option_conflict('l', 'a');
2382 if (delete_refs)
2383 option_conflict('l', 'd');
2384 if (delete_remote)
2385 option_conflict('l', 'X');
2387 if (delete_remote) {
2388 if (fetch_all_branches)
2389 option_conflict('X', 'a');
2390 if (!TAILQ_EMPTY(&wanted_branches))
2391 option_conflict('X', 'b');
2392 if (delete_refs)
2393 option_conflict('X', 'd');
2394 if (replace_tags)
2395 option_conflict('X', 't');
2396 if (!TAILQ_EMPTY(&wanted_refs))
2397 option_conflict('X', 'R');
2400 if (argc == 0) {
2401 if (delete_remote)
2402 errx(1, "-X option requires a remote name");
2403 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2404 } else if (argc == 1)
2405 remote_name = argv[0];
2406 else
2407 usage_fetch();
2409 cwd = getcwd(NULL, 0);
2410 if (cwd == NULL) {
2411 error = got_error_from_errno("getcwd");
2412 goto done;
2415 error = got_repo_pack_fds_open(&pack_fds);
2416 if (error != NULL)
2417 goto done;
2419 if (repo_path == NULL) {
2420 error = got_worktree_open(&worktree, cwd);
2421 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2422 goto done;
2423 else
2424 error = NULL;
2425 if (worktree) {
2426 repo_path =
2427 strdup(got_worktree_get_repo_path(worktree));
2428 if (repo_path == NULL)
2429 error = got_error_from_errno("strdup");
2430 if (error)
2431 goto done;
2432 } else {
2433 repo_path = strdup(cwd);
2434 if (repo_path == NULL) {
2435 error = got_error_from_errno("strdup");
2436 goto done;
2441 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2442 if (error)
2443 goto done;
2445 if (delete_remote) {
2446 error = delete_refs_for_remote(repo, remote_name);
2447 goto done; /* nothing else to do */
2450 if (worktree) {
2451 worktree_conf = got_worktree_get_gotconfig(worktree);
2452 if (worktree_conf) {
2453 got_gotconfig_get_remotes(&nremotes, &remotes,
2454 worktree_conf);
2455 for (i = 0; i < nremotes; i++) {
2456 if (strcmp(remotes[i].name, remote_name) == 0) {
2457 remote = &remotes[i];
2458 break;
2463 if (remote == NULL) {
2464 repo_conf = got_repo_get_gotconfig(repo);
2465 if (repo_conf) {
2466 got_gotconfig_get_remotes(&nremotes, &remotes,
2467 repo_conf);
2468 for (i = 0; i < nremotes; i++) {
2469 if (strcmp(remotes[i].name, remote_name) == 0) {
2470 remote = &remotes[i];
2471 break;
2476 if (remote == NULL) {
2477 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2478 for (i = 0; i < nremotes; i++) {
2479 if (strcmp(remotes[i].name, remote_name) == 0) {
2480 remote = &remotes[i];
2481 break;
2485 if (remote == NULL) {
2486 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2487 goto done;
2490 if (TAILQ_EMPTY(&wanted_branches)) {
2491 if (!fetch_all_branches)
2492 fetch_all_branches = remote->fetch_all_branches;
2493 for (i = 0; i < remote->nfetch_branches; i++) {
2494 got_pathlist_append(&wanted_branches,
2495 remote->fetch_branches[i], NULL);
2498 if (TAILQ_EMPTY(&wanted_refs)) {
2499 for (i = 0; i < remote->nfetch_refs; i++) {
2500 got_pathlist_append(&wanted_refs,
2501 remote->fetch_refs[i], NULL);
2505 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2506 &repo_name, remote->fetch_url);
2507 if (error)
2508 goto done;
2510 if (strcmp(proto, "git") == 0) {
2511 #ifndef PROFILE
2512 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2513 "sendfd dns inet unveil", NULL) == -1)
2514 err(1, "pledge");
2515 #endif
2516 } else if (strcmp(proto, "git+ssh") == 0 ||
2517 strcmp(proto, "ssh") == 0) {
2518 #ifndef PROFILE
2519 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2520 "sendfd unveil", NULL) == -1)
2521 err(1, "pledge");
2522 #endif
2523 } else if (strcmp(proto, "http") == 0 ||
2524 strcmp(proto, "git+http") == 0) {
2525 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2526 goto done;
2527 } else {
2528 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2529 goto done;
2532 error = got_dial_apply_unveil(proto);
2533 if (error)
2534 goto done;
2536 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2537 if (error)
2538 goto done;
2540 if (verbosity >= 0) {
2541 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2542 remote->name, proto, host,
2543 port ? ":" : "", port ? port : "",
2544 *server_path == '/' ? "" : "/", server_path);
2547 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2548 server_path, verbosity);
2549 if (error)
2550 goto done;
2552 fpa.last_scaled_size[0] = '\0';
2553 fpa.last_p_indexed = -1;
2554 fpa.last_p_resolved = -1;
2555 fpa.verbosity = verbosity;
2556 fpa.repo = repo;
2557 fpa.create_configs = 0;
2558 fpa.configs_created = 0;
2559 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2560 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2561 remote->mirror_references, fetch_all_branches, &wanted_branches,
2562 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2563 fetch_progress, &fpa);
2564 if (error)
2565 goto done;
2567 if (list_refs_only) {
2568 error = list_remote_refs(&symrefs, &refs);
2569 goto done;
2572 if (pack_hash == NULL) {
2573 if (verbosity >= 0)
2574 printf("Already up-to-date\n");
2575 } else if (verbosity >= 0) {
2576 error = got_object_id_str(&id_str, pack_hash);
2577 if (error)
2578 goto done;
2579 printf("\nFetched %s.pack\n", id_str);
2580 free(id_str);
2581 id_str = NULL;
2584 /* Update references provided with the pack file. */
2585 TAILQ_FOREACH(pe, &refs, entry) {
2586 const char *refname = pe->path;
2587 struct got_object_id *id = pe->data;
2588 struct got_reference *ref;
2589 char *remote_refname;
2591 if (is_wanted_ref(&wanted_refs, refname) &&
2592 !remote->mirror_references) {
2593 error = update_wanted_ref(refname, id,
2594 remote->name, verbosity, repo);
2595 if (error)
2596 goto done;
2597 continue;
2600 if (remote->mirror_references ||
2601 strncmp("refs/tags/", refname, 10) == 0) {
2602 error = got_ref_open(&ref, repo, refname, 1);
2603 if (error) {
2604 if (error->code != GOT_ERR_NOT_REF)
2605 goto done;
2606 error = create_ref(refname, id, verbosity,
2607 repo);
2608 if (error)
2609 goto done;
2610 } else {
2611 error = update_ref(ref, id, replace_tags,
2612 verbosity, repo);
2613 unlock_err = got_ref_unlock(ref);
2614 if (unlock_err && error == NULL)
2615 error = unlock_err;
2616 got_ref_close(ref);
2617 if (error)
2618 goto done;
2620 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2621 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2622 remote_name, refname + 11) == -1) {
2623 error = got_error_from_errno("asprintf");
2624 goto done;
2627 error = got_ref_open(&ref, repo, remote_refname, 1);
2628 if (error) {
2629 if (error->code != GOT_ERR_NOT_REF)
2630 goto done;
2631 error = create_ref(remote_refname, id,
2632 verbosity, repo);
2633 if (error)
2634 goto done;
2635 } else {
2636 error = update_ref(ref, id, replace_tags,
2637 verbosity, repo);
2638 unlock_err = got_ref_unlock(ref);
2639 if (unlock_err && error == NULL)
2640 error = unlock_err;
2641 got_ref_close(ref);
2642 if (error)
2643 goto done;
2646 /* Also create a local branch if none exists yet. */
2647 error = got_ref_open(&ref, repo, refname, 1);
2648 if (error) {
2649 if (error->code != GOT_ERR_NOT_REF)
2650 goto done;
2651 error = create_ref(refname, id, verbosity,
2652 repo);
2653 if (error)
2654 goto done;
2655 } else {
2656 unlock_err = got_ref_unlock(ref);
2657 if (unlock_err && error == NULL)
2658 error = unlock_err;
2659 got_ref_close(ref);
2663 if (delete_refs) {
2664 error = delete_missing_refs(&refs, &symrefs, remote,
2665 verbosity, repo);
2666 if (error)
2667 goto done;
2670 if (!remote->mirror_references) {
2671 /* Update remote HEAD reference if the server provided one. */
2672 TAILQ_FOREACH(pe, &symrefs, entry) {
2673 struct got_reference *target_ref;
2674 const char *refname = pe->path;
2675 const char *target = pe->data;
2676 char *remote_refname = NULL, *remote_target = NULL;
2678 if (strcmp(refname, GOT_REF_HEAD) != 0)
2679 continue;
2681 if (strncmp("refs/heads/", target, 11) != 0)
2682 continue;
2684 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2685 remote->name, refname) == -1) {
2686 error = got_error_from_errno("asprintf");
2687 goto done;
2689 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2690 remote->name, target + 11) == -1) {
2691 error = got_error_from_errno("asprintf");
2692 free(remote_refname);
2693 goto done;
2696 error = got_ref_open(&target_ref, repo, remote_target,
2697 0);
2698 if (error) {
2699 free(remote_refname);
2700 free(remote_target);
2701 if (error->code == GOT_ERR_NOT_REF) {
2702 error = NULL;
2703 continue;
2705 goto done;
2707 error = update_symref(remote_refname, target_ref,
2708 verbosity, repo);
2709 free(remote_refname);
2710 free(remote_target);
2711 got_ref_close(target_ref);
2712 if (error)
2713 goto done;
2716 done:
2717 if (fetchpid > 0) {
2718 if (kill(fetchpid, SIGTERM) == -1)
2719 error = got_error_from_errno("kill");
2720 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2721 error = got_error_from_errno("waitpid");
2723 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2724 error = got_error_from_errno("close");
2725 if (repo) {
2726 const struct got_error *close_err = got_repo_close(repo);
2727 if (error == NULL)
2728 error = close_err;
2730 if (worktree)
2731 got_worktree_close(worktree);
2732 if (pack_fds) {
2733 const struct got_error *pack_err =
2734 got_repo_pack_fds_close(pack_fds);
2735 if (error == NULL)
2736 error = pack_err;
2738 TAILQ_FOREACH(pe, &refs, entry) {
2739 free((void *)pe->path);
2740 free(pe->data);
2742 got_pathlist_free(&refs);
2743 TAILQ_FOREACH(pe, &symrefs, entry) {
2744 free((void *)pe->path);
2745 free(pe->data);
2747 got_pathlist_free(&symrefs);
2748 got_pathlist_free(&wanted_branches);
2749 got_pathlist_free(&wanted_refs);
2750 free(id_str);
2751 free(cwd);
2752 free(repo_path);
2753 free(pack_hash);
2754 free(proto);
2755 free(host);
2756 free(port);
2757 free(server_path);
2758 free(repo_name);
2759 return error;
2763 __dead static void
2764 usage_checkout(void)
2766 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2767 "[-p path-prefix] repository-path [work-tree-path]\n",
2768 getprogname());
2769 exit(1);
2772 static void
2773 show_worktree_base_ref_warning(void)
2775 fprintf(stderr, "%s: warning: could not create a reference "
2776 "to the work tree's base commit; the commit could be "
2777 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2778 "repository writable and running 'got update' will prevent this\n",
2779 getprogname());
2782 struct got_checkout_progress_arg {
2783 const char *worktree_path;
2784 int had_base_commit_ref_error;
2785 int verbosity;
2788 static const struct got_error *
2789 checkout_progress(void *arg, unsigned char status, const char *path)
2791 struct got_checkout_progress_arg *a = arg;
2793 /* Base commit bump happens silently. */
2794 if (status == GOT_STATUS_BUMP_BASE)
2795 return NULL;
2797 if (status == GOT_STATUS_BASE_REF_ERR) {
2798 a->had_base_commit_ref_error = 1;
2799 return NULL;
2802 while (path[0] == '/')
2803 path++;
2805 if (a->verbosity >= 0)
2806 printf("%c %s/%s\n", status, a->worktree_path, path);
2808 return NULL;
2811 static const struct got_error *
2812 check_cancelled(void *arg)
2814 if (sigint_received || sigpipe_received)
2815 return got_error(GOT_ERR_CANCELLED);
2816 return NULL;
2819 static const struct got_error *
2820 check_linear_ancestry(struct got_object_id *commit_id,
2821 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2822 struct got_repository *repo)
2824 const struct got_error *err = NULL;
2825 struct got_object_id *yca_id;
2827 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2828 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2829 if (err)
2830 return err;
2832 if (yca_id == NULL)
2833 return got_error(GOT_ERR_ANCESTRY);
2836 * Require a straight line of history between the target commit
2837 * and the work tree's base commit.
2839 * Non-linear situations such as this require a rebase:
2841 * (commit) D F (base_commit)
2842 * \ /
2843 * C E
2844 * \ /
2845 * B (yca)
2846 * |
2847 * A
2849 * 'got update' only handles linear cases:
2850 * Update forwards in time: A (base/yca) - B - C - D (commit)
2851 * Update backwards in time: D (base) - C - B - A (commit/yca)
2853 if (allow_forwards_in_time_only) {
2854 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2855 return got_error(GOT_ERR_ANCESTRY);
2856 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2857 got_object_id_cmp(base_commit_id, yca_id) != 0)
2858 return got_error(GOT_ERR_ANCESTRY);
2860 free(yca_id);
2861 return NULL;
2864 static const struct got_error *
2865 check_same_branch(struct got_object_id *commit_id,
2866 struct got_reference *head_ref, struct got_object_id *yca_id,
2867 struct got_repository *repo)
2869 const struct got_error *err = NULL;
2870 struct got_commit_graph *graph = NULL;
2871 struct got_object_id *head_commit_id = NULL;
2872 int is_same_branch = 0;
2874 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2875 if (err)
2876 goto done;
2878 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2879 is_same_branch = 1;
2880 goto done;
2882 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2883 is_same_branch = 1;
2884 goto done;
2887 err = got_commit_graph_open(&graph, "/", 1);
2888 if (err)
2889 goto done;
2891 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2892 check_cancelled, NULL);
2893 if (err)
2894 goto done;
2896 for (;;) {
2897 struct got_object_id id;
2899 err = got_commit_graph_iter_next(&id, graph, repo,
2900 check_cancelled, NULL);
2901 if (err) {
2902 if (err->code == GOT_ERR_ITER_COMPLETED)
2903 err = NULL;
2904 break;
2907 if (yca_id && got_object_id_cmp(&id, yca_id) == 0)
2908 break;
2909 if (got_object_id_cmp(&id, commit_id) == 0) {
2910 is_same_branch = 1;
2911 break;
2914 done:
2915 if (graph)
2916 got_commit_graph_close(graph);
2917 free(head_commit_id);
2918 if (!err && !is_same_branch)
2919 err = got_error(GOT_ERR_ANCESTRY);
2920 return err;
2923 static const struct got_error *
2924 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2926 static char msg[512];
2927 const char *branch_name;
2929 if (got_ref_is_symbolic(ref))
2930 branch_name = got_ref_get_symref_target(ref);
2931 else
2932 branch_name = got_ref_get_name(ref);
2934 if (strncmp("refs/heads/", branch_name, 11) == 0)
2935 branch_name += 11;
2937 snprintf(msg, sizeof(msg),
2938 "target commit is not contained in branch '%s'; "
2939 "the branch to use must be specified with -b; "
2940 "if necessary a new branch can be created for "
2941 "this commit with 'got branch -c %s BRANCH_NAME'",
2942 branch_name, commit_id_str);
2944 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2947 static const struct got_error *
2948 cmd_checkout(int argc, char *argv[])
2950 const struct got_error *error = NULL;
2951 struct got_repository *repo = NULL;
2952 struct got_reference *head_ref = NULL, *ref = NULL;
2953 struct got_worktree *worktree = NULL;
2954 char *repo_path = NULL;
2955 char *worktree_path = NULL;
2956 const char *path_prefix = "";
2957 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2958 char *commit_id_str = NULL;
2959 struct got_object_id *commit_id = NULL;
2960 char *cwd = NULL;
2961 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2962 struct got_pathlist_head paths;
2963 struct got_checkout_progress_arg cpa;
2964 int *pack_fds = NULL;
2966 TAILQ_INIT(&paths);
2968 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2969 switch (ch) {
2970 case 'b':
2971 branch_name = optarg;
2972 break;
2973 case 'c':
2974 commit_id_str = strdup(optarg);
2975 if (commit_id_str == NULL)
2976 return got_error_from_errno("strdup");
2977 break;
2978 case 'E':
2979 allow_nonempty = 1;
2980 break;
2981 case 'p':
2982 path_prefix = optarg;
2983 break;
2984 case 'q':
2985 verbosity = -1;
2986 break;
2987 default:
2988 usage_checkout();
2989 /* NOTREACHED */
2993 argc -= optind;
2994 argv += optind;
2996 #ifndef PROFILE
2997 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2998 "unveil", NULL) == -1)
2999 err(1, "pledge");
3000 #endif
3001 if (argc == 1) {
3002 char *base, *dotgit;
3003 const char *path;
3004 repo_path = realpath(argv[0], NULL);
3005 if (repo_path == NULL)
3006 return got_error_from_errno2("realpath", argv[0]);
3007 cwd = getcwd(NULL, 0);
3008 if (cwd == NULL) {
3009 error = got_error_from_errno("getcwd");
3010 goto done;
3012 if (path_prefix[0])
3013 path = path_prefix;
3014 else
3015 path = repo_path;
3016 error = got_path_basename(&base, path);
3017 if (error)
3018 goto done;
3019 dotgit = strstr(base, ".git");
3020 if (dotgit)
3021 *dotgit = '\0';
3022 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3023 error = got_error_from_errno("asprintf");
3024 free(base);
3025 goto done;
3027 free(base);
3028 } else if (argc == 2) {
3029 repo_path = realpath(argv[0], NULL);
3030 if (repo_path == NULL) {
3031 error = got_error_from_errno2("realpath", argv[0]);
3032 goto done;
3034 worktree_path = realpath(argv[1], NULL);
3035 if (worktree_path == NULL) {
3036 if (errno != ENOENT) {
3037 error = got_error_from_errno2("realpath",
3038 argv[1]);
3039 goto done;
3041 worktree_path = strdup(argv[1]);
3042 if (worktree_path == NULL) {
3043 error = got_error_from_errno("strdup");
3044 goto done;
3047 } else
3048 usage_checkout();
3050 got_path_strip_trailing_slashes(repo_path);
3051 got_path_strip_trailing_slashes(worktree_path);
3053 error = got_repo_pack_fds_open(&pack_fds);
3054 if (error != NULL)
3055 goto done;
3057 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3058 if (error != NULL)
3059 goto done;
3061 /* Pre-create work tree path for unveil(2) */
3062 error = got_path_mkdir(worktree_path);
3063 if (error) {
3064 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3065 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3066 goto done;
3067 if (!allow_nonempty &&
3068 !got_path_dir_is_empty(worktree_path)) {
3069 error = got_error_path(worktree_path,
3070 GOT_ERR_DIR_NOT_EMPTY);
3071 goto done;
3075 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3076 if (error)
3077 goto done;
3079 error = got_ref_open(&head_ref, repo, branch_name, 0);
3080 if (error != NULL)
3081 goto done;
3083 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3084 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3085 goto done;
3087 error = got_worktree_open(&worktree, worktree_path);
3088 if (error != NULL)
3089 goto done;
3091 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3092 path_prefix);
3093 if (error != NULL)
3094 goto done;
3095 if (!same_path_prefix) {
3096 error = got_error(GOT_ERR_PATH_PREFIX);
3097 goto done;
3100 if (commit_id_str) {
3101 struct got_reflist_head refs;
3102 TAILQ_INIT(&refs);
3103 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3104 NULL);
3105 if (error)
3106 goto done;
3107 error = got_repo_match_object_id(&commit_id, NULL,
3108 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3109 got_ref_list_free(&refs);
3110 if (error)
3111 goto done;
3112 error = check_linear_ancestry(commit_id,
3113 got_worktree_get_base_commit_id(worktree), 0, repo);
3114 if (error != NULL) {
3115 if (error->code == GOT_ERR_ANCESTRY) {
3116 error = checkout_ancestry_error(
3117 head_ref, commit_id_str);
3119 goto done;
3121 error = check_same_branch(commit_id, head_ref, NULL, repo);
3122 if (error) {
3123 if (error->code == GOT_ERR_ANCESTRY) {
3124 error = checkout_ancestry_error(
3125 head_ref, commit_id_str);
3127 goto done;
3129 error = got_worktree_set_base_commit_id(worktree, repo,
3130 commit_id);
3131 if (error)
3132 goto done;
3133 /* Expand potentially abbreviated commit ID string. */
3134 free(commit_id_str);
3135 error = got_object_id_str(&commit_id_str, commit_id);
3136 if (error)
3137 goto done;
3138 } else {
3139 commit_id = got_object_id_dup(
3140 got_worktree_get_base_commit_id(worktree));
3141 if (commit_id == NULL) {
3142 error = got_error_from_errno("got_object_id_dup");
3143 goto done;
3145 error = got_object_id_str(&commit_id_str, commit_id);
3146 if (error)
3147 goto done;
3150 error = got_pathlist_append(&paths, "", NULL);
3151 if (error)
3152 goto done;
3153 cpa.worktree_path = worktree_path;
3154 cpa.had_base_commit_ref_error = 0;
3155 cpa.verbosity = verbosity;
3156 error = got_worktree_checkout_files(worktree, &paths, repo,
3157 checkout_progress, &cpa, check_cancelled, NULL);
3158 if (error != NULL)
3159 goto done;
3161 if (got_ref_is_symbolic(head_ref)) {
3162 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3163 if (error)
3164 goto done;
3165 refname = got_ref_get_name(ref);
3166 } else
3167 refname = got_ref_get_name(head_ref);
3168 printf("Checked out %s: %s\n", refname, commit_id_str);
3169 printf("Now shut up and hack\n");
3170 if (cpa.had_base_commit_ref_error)
3171 show_worktree_base_ref_warning();
3172 done:
3173 if (pack_fds) {
3174 const struct got_error *pack_err =
3175 got_repo_pack_fds_close(pack_fds);
3176 if (error == NULL)
3177 error = pack_err;
3179 if (head_ref)
3180 got_ref_close(head_ref);
3181 if (ref)
3182 got_ref_close(ref);
3183 got_pathlist_free(&paths);
3184 free(commit_id_str);
3185 free(commit_id);
3186 free(repo_path);
3187 free(worktree_path);
3188 free(cwd);
3189 return error;
3192 struct got_update_progress_arg {
3193 int did_something;
3194 int conflicts;
3195 int obstructed;
3196 int not_updated;
3197 int missing;
3198 int not_deleted;
3199 int unversioned;
3200 int verbosity;
3203 static void
3204 print_update_progress_stats(struct got_update_progress_arg *upa)
3206 if (!upa->did_something)
3207 return;
3209 if (upa->conflicts > 0)
3210 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3211 if (upa->obstructed > 0)
3212 printf("File paths obstructed by a non-regular file: %d\n",
3213 upa->obstructed);
3214 if (upa->not_updated > 0)
3215 printf("Files not updated because of existing merge "
3216 "conflicts: %d\n", upa->not_updated);
3220 * The meaning of some status codes differs between merge-style operations and
3221 * update operations. For example, the ! status code means "file was missing"
3222 * if changes were merged into the work tree, and "missing file was restored"
3223 * if the work tree was updated. This function should be used by any operation
3224 * which merges changes into the work tree without updating the work tree.
3226 static void
3227 print_merge_progress_stats(struct got_update_progress_arg *upa)
3229 if (!upa->did_something)
3230 return;
3232 if (upa->conflicts > 0)
3233 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3234 if (upa->obstructed > 0)
3235 printf("File paths obstructed by a non-regular file: %d\n",
3236 upa->obstructed);
3237 if (upa->missing > 0)
3238 printf("Files which had incoming changes but could not be "
3239 "found in the work tree: %d\n", upa->missing);
3240 if (upa->not_deleted > 0)
3241 printf("Files not deleted due to differences in deleted "
3242 "content: %d\n", upa->not_deleted);
3243 if (upa->unversioned > 0)
3244 printf("Files not merged because an unversioned file was "
3245 "found in the work tree: %d\n", upa->unversioned);
3248 __dead static void
3249 usage_update(void)
3251 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3252 "[path ...]\n", getprogname());
3253 exit(1);
3256 static const struct got_error *
3257 update_progress(void *arg, unsigned char status, const char *path)
3259 struct got_update_progress_arg *upa = arg;
3261 if (status == GOT_STATUS_EXISTS ||
3262 status == GOT_STATUS_BASE_REF_ERR)
3263 return NULL;
3265 upa->did_something = 1;
3267 /* Base commit bump happens silently. */
3268 if (status == GOT_STATUS_BUMP_BASE)
3269 return NULL;
3271 if (status == GOT_STATUS_CONFLICT)
3272 upa->conflicts++;
3273 if (status == GOT_STATUS_OBSTRUCTED)
3274 upa->obstructed++;
3275 if (status == GOT_STATUS_CANNOT_UPDATE)
3276 upa->not_updated++;
3277 if (status == GOT_STATUS_MISSING)
3278 upa->missing++;
3279 if (status == GOT_STATUS_CANNOT_DELETE)
3280 upa->not_deleted++;
3281 if (status == GOT_STATUS_UNVERSIONED)
3282 upa->unversioned++;
3284 while (path[0] == '/')
3285 path++;
3286 if (upa->verbosity >= 0)
3287 printf("%c %s\n", status, path);
3289 return NULL;
3292 static const struct got_error *
3293 switch_head_ref(struct got_reference *head_ref,
3294 struct got_object_id *commit_id, struct got_worktree *worktree,
3295 struct got_repository *repo)
3297 const struct got_error *err = NULL;
3298 char *base_id_str;
3299 int ref_has_moved = 0;
3301 /* Trivial case: switching between two different references. */
3302 if (strcmp(got_ref_get_name(head_ref),
3303 got_worktree_get_head_ref_name(worktree)) != 0) {
3304 printf("Switching work tree from %s to %s\n",
3305 got_worktree_get_head_ref_name(worktree),
3306 got_ref_get_name(head_ref));
3307 return got_worktree_set_head_ref(worktree, head_ref);
3310 err = check_linear_ancestry(commit_id,
3311 got_worktree_get_base_commit_id(worktree), 0, repo);
3312 if (err) {
3313 if (err->code != GOT_ERR_ANCESTRY)
3314 return err;
3315 ref_has_moved = 1;
3317 if (!ref_has_moved)
3318 return NULL;
3320 /* Switching to a rebased branch with the same reference name. */
3321 err = got_object_id_str(&base_id_str,
3322 got_worktree_get_base_commit_id(worktree));
3323 if (err)
3324 return err;
3325 printf("Reference %s now points at a different branch\n",
3326 got_worktree_get_head_ref_name(worktree));
3327 printf("Switching work tree from %s to %s\n", base_id_str,
3328 got_worktree_get_head_ref_name(worktree));
3329 return NULL;
3332 static const struct got_error *
3333 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3335 const struct got_error *err;
3336 int in_progress;
3338 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3339 if (err)
3340 return err;
3341 if (in_progress)
3342 return got_error(GOT_ERR_REBASING);
3344 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3345 if (err)
3346 return err;
3347 if (in_progress)
3348 return got_error(GOT_ERR_HISTEDIT_BUSY);
3350 return NULL;
3353 static const struct got_error *
3354 check_merge_in_progress(struct got_worktree *worktree,
3355 struct got_repository *repo)
3357 const struct got_error *err;
3358 int in_progress;
3360 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3361 if (err)
3362 return err;
3363 if (in_progress)
3364 return got_error(GOT_ERR_MERGE_BUSY);
3366 return NULL;
3369 static const struct got_error *
3370 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3371 char *argv[], struct got_worktree *worktree)
3373 const struct got_error *err = NULL;
3374 char *path;
3375 struct got_pathlist_entry *new;
3376 int i;
3378 if (argc == 0) {
3379 path = strdup("");
3380 if (path == NULL)
3381 return got_error_from_errno("strdup");
3382 return got_pathlist_append(paths, path, NULL);
3385 for (i = 0; i < argc; i++) {
3386 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3387 if (err)
3388 break;
3389 err = got_pathlist_insert(&new, paths, path, NULL);
3390 if (err || new == NULL /* duplicate */) {
3391 free(path);
3392 if (err)
3393 break;
3397 return err;
3400 static const struct got_error *
3401 wrap_not_worktree_error(const struct got_error *orig_err,
3402 const char *cmdname, const char *path)
3404 const struct got_error *err;
3405 struct got_repository *repo;
3406 static char msg[512];
3407 int *pack_fds = NULL;
3409 err = got_repo_pack_fds_open(&pack_fds);
3410 if (err)
3411 return err;
3413 err = got_repo_open(&repo, path, NULL, pack_fds);
3414 if (err)
3415 return orig_err;
3417 snprintf(msg, sizeof(msg),
3418 "'got %s' needs a work tree in addition to a git repository\n"
3419 "Work trees can be checked out from this Git repository with "
3420 "'got checkout'.\n"
3421 "The got(1) manual page contains more information.", cmdname);
3422 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3423 got_repo_close(repo);
3424 if (pack_fds) {
3425 const struct got_error *pack_err =
3426 got_repo_pack_fds_close(pack_fds);
3427 if (err == NULL)
3428 err = pack_err;
3430 return err;
3433 static const struct got_error *
3434 cmd_update(int argc, char *argv[])
3436 const struct got_error *error = NULL;
3437 struct got_repository *repo = NULL;
3438 struct got_worktree *worktree = NULL;
3439 char *worktree_path = NULL;
3440 struct got_object_id *commit_id = NULL;
3441 char *commit_id_str = NULL;
3442 const char *branch_name = NULL;
3443 struct got_reference *head_ref = NULL;
3444 struct got_pathlist_head paths;
3445 struct got_pathlist_entry *pe;
3446 int ch, verbosity = 0;
3447 struct got_update_progress_arg upa;
3448 int *pack_fds = NULL;
3450 TAILQ_INIT(&paths);
3452 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3453 switch (ch) {
3454 case 'b':
3455 branch_name = optarg;
3456 break;
3457 case 'c':
3458 commit_id_str = strdup(optarg);
3459 if (commit_id_str == NULL)
3460 return got_error_from_errno("strdup");
3461 break;
3462 case 'q':
3463 verbosity = -1;
3464 break;
3465 default:
3466 usage_update();
3467 /* NOTREACHED */
3471 argc -= optind;
3472 argv += optind;
3474 #ifndef PROFILE
3475 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3476 "unveil", NULL) == -1)
3477 err(1, "pledge");
3478 #endif
3479 worktree_path = getcwd(NULL, 0);
3480 if (worktree_path == NULL) {
3481 error = got_error_from_errno("getcwd");
3482 goto done;
3485 error = got_repo_pack_fds_open(&pack_fds);
3486 if (error != NULL)
3487 goto done;
3489 error = got_worktree_open(&worktree, worktree_path);
3490 if (error) {
3491 if (error->code == GOT_ERR_NOT_WORKTREE)
3492 error = wrap_not_worktree_error(error, "update",
3493 worktree_path);
3494 goto done;
3497 error = check_rebase_or_histedit_in_progress(worktree);
3498 if (error)
3499 goto done;
3501 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3502 NULL, pack_fds);
3503 if (error != NULL)
3504 goto done;
3506 error = apply_unveil(got_repo_get_path(repo), 0,
3507 got_worktree_get_root_path(worktree));
3508 if (error)
3509 goto done;
3511 error = check_merge_in_progress(worktree, repo);
3512 if (error)
3513 goto done;
3515 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3516 if (error)
3517 goto done;
3519 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3520 got_worktree_get_head_ref_name(worktree), 0);
3521 if (error != NULL)
3522 goto done;
3523 if (commit_id_str == NULL) {
3524 error = got_ref_resolve(&commit_id, repo, head_ref);
3525 if (error != NULL)
3526 goto done;
3527 error = got_object_id_str(&commit_id_str, commit_id);
3528 if (error != NULL)
3529 goto done;
3530 } else {
3531 struct got_reflist_head refs;
3532 TAILQ_INIT(&refs);
3533 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3534 NULL);
3535 if (error)
3536 goto done;
3537 error = got_repo_match_object_id(&commit_id, NULL,
3538 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3539 got_ref_list_free(&refs);
3540 free(commit_id_str);
3541 commit_id_str = NULL;
3542 if (error)
3543 goto done;
3544 error = got_object_id_str(&commit_id_str, commit_id);
3545 if (error)
3546 goto done;
3549 if (branch_name) {
3550 struct got_object_id *head_commit_id;
3551 TAILQ_FOREACH(pe, &paths, entry) {
3552 if (pe->path_len == 0)
3553 continue;
3554 error = got_error_msg(GOT_ERR_BAD_PATH,
3555 "switching between branches requires that "
3556 "the entire work tree gets updated");
3557 goto done;
3559 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3560 if (error)
3561 goto done;
3562 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3563 repo);
3564 free(head_commit_id);
3565 if (error != NULL)
3566 goto done;
3567 error = check_same_branch(commit_id, head_ref, NULL, repo);
3568 if (error)
3569 goto done;
3570 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3571 if (error)
3572 goto done;
3573 } else {
3574 error = check_linear_ancestry(commit_id,
3575 got_worktree_get_base_commit_id(worktree), 0, repo);
3576 if (error != NULL) {
3577 if (error->code == GOT_ERR_ANCESTRY)
3578 error = got_error(GOT_ERR_BRANCH_MOVED);
3579 goto done;
3581 error = check_same_branch(commit_id, head_ref, NULL, repo);
3582 if (error)
3583 goto done;
3586 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3587 commit_id) != 0) {
3588 error = got_worktree_set_base_commit_id(worktree, repo,
3589 commit_id);
3590 if (error)
3591 goto done;
3594 memset(&upa, 0, sizeof(upa));
3595 upa.verbosity = verbosity;
3596 error = got_worktree_checkout_files(worktree, &paths, repo,
3597 update_progress, &upa, check_cancelled, NULL);
3598 if (error != NULL)
3599 goto done;
3601 if (upa.did_something) {
3602 printf("Updated to %s: %s\n",
3603 got_worktree_get_head_ref_name(worktree), commit_id_str);
3604 } else
3605 printf("Already up-to-date\n");
3607 print_update_progress_stats(&upa);
3608 done:
3609 if (pack_fds) {
3610 const struct got_error *pack_err =
3611 got_repo_pack_fds_close(pack_fds);
3612 if (error == NULL)
3613 error = pack_err;
3615 free(worktree_path);
3616 TAILQ_FOREACH(pe, &paths, entry)
3617 free((char *)pe->path);
3618 got_pathlist_free(&paths);
3619 free(commit_id);
3620 free(commit_id_str);
3621 return error;
3624 static const struct got_error *
3625 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3626 const char *path, int diff_context, int ignore_whitespace,
3627 int force_text_diff, int show_diffstat, struct got_repository *repo,
3628 FILE *outfile)
3630 const struct got_error *err = NULL;
3631 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3632 FILE *f1 = NULL, *f2 = NULL;
3633 int fd1 = -1, fd2 = -1;
3635 fd1 = got_opentempfd();
3636 if (fd1 == -1)
3637 return got_error_from_errno("got_opentempfd");
3638 fd2 = got_opentempfd();
3639 if (fd2 == -1) {
3640 err = got_error_from_errno("got_opentempfd");
3641 goto done;
3644 if (blob_id1) {
3645 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3646 fd1);
3647 if (err)
3648 goto done;
3651 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3652 if (err)
3653 goto done;
3655 f1 = got_opentemp();
3656 if (f1 == NULL) {
3657 err = got_error_from_errno("got_opentemp");
3658 goto done;
3660 f2 = got_opentemp();
3661 if (f2 == NULL) {
3662 err = got_error_from_errno("got_opentemp");
3663 goto done;
3666 while (path[0] == '/')
3667 path++;
3668 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3669 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3670 force_text_diff, show_diffstat, NULL, outfile);
3671 done:
3672 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3673 err = got_error_from_errno("close");
3674 if (blob1)
3675 got_object_blob_close(blob1);
3676 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3677 err = got_error_from_errno("close");
3678 got_object_blob_close(blob2);
3679 if (f1 && fclose(f1) == EOF && err == NULL)
3680 err = got_error_from_errno("fclose");
3681 if (f2 && fclose(f2) == EOF && err == NULL)
3682 err = got_error_from_errno("fclose");
3683 return err;
3686 static const struct got_error *
3687 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3688 const char *path, int diff_context, int ignore_whitespace,
3689 int force_text_diff, struct got_repository *repo, FILE *outfile)
3691 const struct got_error *err = NULL;
3692 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3693 struct got_diff_blob_output_unidiff_arg arg;
3694 FILE *f1 = NULL, *f2 = NULL;
3695 int fd1 = -1, fd2 = -1;
3697 if (tree_id1) {
3698 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3699 if (err)
3700 goto done;
3701 fd1 = got_opentempfd();
3702 if (fd1 == -1) {
3703 err = got_error_from_errno("got_opentempfd");
3704 goto done;
3708 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3709 if (err)
3710 goto done;
3712 f1 = got_opentemp();
3713 if (f1 == NULL) {
3714 err = got_error_from_errno("got_opentemp");
3715 goto done;
3718 f2 = got_opentemp();
3719 if (f2 == NULL) {
3720 err = got_error_from_errno("got_opentemp");
3721 goto done;
3723 fd2 = got_opentempfd();
3724 if (fd2 == -1) {
3725 err = got_error_from_errno("got_opentempfd");
3726 goto done;
3728 arg.diff_context = diff_context;
3729 arg.ignore_whitespace = ignore_whitespace;
3730 arg.force_text_diff = force_text_diff;
3731 arg.show_diffstat = 0;
3732 arg.diffstat = NULL;
3733 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3734 arg.outfile = outfile;
3735 arg.lines = NULL;
3736 arg.nlines = 0;
3737 while (path[0] == '/')
3738 path++;
3739 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3740 got_diff_blob_output_unidiff, &arg, 1);
3741 done:
3742 if (tree1)
3743 got_object_tree_close(tree1);
3744 if (tree2)
3745 got_object_tree_close(tree2);
3746 if (f1 && fclose(f1) == EOF && err == NULL)
3747 err = got_error_from_errno("fclose");
3748 if (f2 && fclose(f2) == EOF && err == NULL)
3749 err = got_error_from_errno("fclose");
3750 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3751 err = got_error_from_errno("close");
3752 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3753 err = got_error_from_errno("close");
3754 return err;
3757 static const struct got_error *
3758 get_changed_paths(struct got_pathlist_head *paths,
3759 struct got_commit_object *commit, struct got_repository *repo,
3760 struct got_diffstat_cb_arg *dsa)
3762 const struct got_error *err = NULL;
3763 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3764 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3765 struct got_object_qid *qid;
3766 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3767 FILE *f1 = NULL, *f2 = NULL;
3768 int fd1 = -1, fd2 = -1;
3770 if (dsa) {
3771 cb = got_diff_tree_compute_diffstat;
3773 f1 = got_opentemp();
3774 if (f1 == NULL) {
3775 err = got_error_from_errno("got_opentemp");
3776 goto done;
3778 f2 = got_opentemp();
3779 if (f2 == NULL) {
3780 err = got_error_from_errno("got_opentemp");
3781 goto done;
3783 fd1 = got_opentempfd();
3784 if (fd1 == -1) {
3785 err = got_error_from_errno("got_opentempfd");
3786 goto done;
3788 fd2 = got_opentempfd();
3789 if (fd2 == -1) {
3790 err = got_error_from_errno("got_opentempfd");
3791 goto done;
3795 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3796 if (qid != NULL) {
3797 struct got_commit_object *pcommit;
3798 err = got_object_open_as_commit(&pcommit, repo,
3799 &qid->id);
3800 if (err)
3801 return err;
3803 tree_id1 = got_object_id_dup(
3804 got_object_commit_get_tree_id(pcommit));
3805 if (tree_id1 == NULL) {
3806 got_object_commit_close(pcommit);
3807 return got_error_from_errno("got_object_id_dup");
3809 got_object_commit_close(pcommit);
3813 if (tree_id1) {
3814 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3815 if (err)
3816 goto done;
3819 tree_id2 = got_object_commit_get_tree_id(commit);
3820 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3821 if (err)
3822 goto done;
3824 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3825 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3826 done:
3827 if (tree1)
3828 got_object_tree_close(tree1);
3829 if (tree2)
3830 got_object_tree_close(tree2);
3831 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3832 err = got_error_from_errno("close");
3833 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3834 err = got_error_from_errno("close");
3835 if (f1 && fclose(f1) == EOF && err == NULL)
3836 err = got_error_from_errno("fclose");
3837 if (f2 && fclose(f2) == EOF && err == NULL)
3838 err = got_error_from_errno("fclose");
3839 free(tree_id1);
3840 return err;
3843 static const struct got_error *
3844 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3845 const char *path, int diff_context, struct got_repository *repo,
3846 FILE *outfile)
3848 const struct got_error *err = NULL;
3849 struct got_commit_object *pcommit = NULL;
3850 char *id_str1 = NULL, *id_str2 = NULL;
3851 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3852 struct got_object_qid *qid;
3854 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3855 if (qid != NULL) {
3856 err = got_object_open_as_commit(&pcommit, repo,
3857 &qid->id);
3858 if (err)
3859 return err;
3860 err = got_object_id_str(&id_str1, &qid->id);
3861 if (err)
3862 goto done;
3865 err = got_object_id_str(&id_str2, id);
3866 if (err)
3867 goto done;
3869 if (path && path[0] != '\0') {
3870 int obj_type;
3871 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3872 if (err)
3873 goto done;
3874 if (pcommit) {
3875 err = got_object_id_by_path(&obj_id1, repo,
3876 pcommit, path);
3877 if (err) {
3878 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3879 free(obj_id2);
3880 goto done;
3884 err = got_object_get_type(&obj_type, repo, obj_id2);
3885 if (err) {
3886 free(obj_id2);
3887 goto done;
3889 fprintf(outfile,
3890 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3891 fprintf(outfile, "commit - %s\n",
3892 id_str1 ? id_str1 : "/dev/null");
3893 fprintf(outfile, "commit + %s\n", id_str2);
3894 switch (obj_type) {
3895 case GOT_OBJ_TYPE_BLOB:
3896 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3897 0, 0, 0, repo, outfile);
3898 break;
3899 case GOT_OBJ_TYPE_TREE:
3900 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3901 0, 0, repo, outfile);
3902 break;
3903 default:
3904 err = got_error(GOT_ERR_OBJ_TYPE);
3905 break;
3907 free(obj_id1);
3908 free(obj_id2);
3909 } else {
3910 obj_id2 = got_object_commit_get_tree_id(commit);
3911 if (pcommit)
3912 obj_id1 = got_object_commit_get_tree_id(pcommit);
3913 fprintf(outfile,
3914 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3915 fprintf(outfile, "commit - %s\n",
3916 id_str1 ? id_str1 : "/dev/null");
3917 fprintf(outfile, "commit + %s\n", id_str2);
3918 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3919 repo, outfile);
3921 done:
3922 free(id_str1);
3923 free(id_str2);
3924 if (pcommit)
3925 got_object_commit_close(pcommit);
3926 return err;
3929 static char *
3930 get_datestr(time_t *time, char *datebuf)
3932 struct tm mytm, *tm;
3933 char *p, *s;
3935 tm = gmtime_r(time, &mytm);
3936 if (tm == NULL)
3937 return NULL;
3938 s = asctime_r(tm, datebuf);
3939 if (s == NULL)
3940 return NULL;
3941 p = strchr(s, '\n');
3942 if (p)
3943 *p = '\0';
3944 return s;
3947 static const struct got_error *
3948 match_commit(int *have_match, struct got_object_id *id,
3949 struct got_commit_object *commit, regex_t *regex)
3951 const struct got_error *err = NULL;
3952 regmatch_t regmatch;
3953 char *id_str = NULL, *logmsg = NULL;
3955 *have_match = 0;
3957 err = got_object_id_str(&id_str, id);
3958 if (err)
3959 return err;
3961 err = got_object_commit_get_logmsg(&logmsg, commit);
3962 if (err)
3963 goto done;
3965 if (regexec(regex, got_object_commit_get_author(commit), 1,
3966 &regmatch, 0) == 0 ||
3967 regexec(regex, got_object_commit_get_committer(commit), 1,
3968 &regmatch, 0) == 0 ||
3969 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3970 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3971 *have_match = 1;
3972 done:
3973 free(id_str);
3974 free(logmsg);
3975 return err;
3978 static void
3979 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3980 regex_t *regex)
3982 regmatch_t regmatch;
3983 struct got_pathlist_entry *pe;
3985 *have_match = 0;
3987 TAILQ_FOREACH(pe, changed_paths, entry) {
3988 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3989 *have_match = 1;
3990 break;
3995 static const struct got_error *
3996 match_patch(int *have_match, struct got_commit_object *commit,
3997 struct got_object_id *id, const char *path, int diff_context,
3998 struct got_repository *repo, regex_t *regex, FILE *f)
4000 const struct got_error *err = NULL;
4001 char *line = NULL;
4002 size_t linesize = 0;
4003 regmatch_t regmatch;
4005 *have_match = 0;
4007 err = got_opentemp_truncate(f);
4008 if (err)
4009 return err;
4011 err = print_patch(commit, id, path, diff_context, repo, f);
4012 if (err)
4013 goto done;
4015 if (fseeko(f, 0L, SEEK_SET) == -1) {
4016 err = got_error_from_errno("fseeko");
4017 goto done;
4020 while (getline(&line, &linesize, f) != -1) {
4021 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4022 *have_match = 1;
4023 break;
4026 done:
4027 free(line);
4028 return err;
4031 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4033 static const struct got_error*
4034 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4035 struct got_object_id *id, struct got_repository *repo,
4036 int local_only)
4038 static const struct got_error *err = NULL;
4039 struct got_reflist_entry *re;
4040 char *s;
4041 const char *name;
4043 *refs_str = NULL;
4045 TAILQ_FOREACH(re, refs, entry) {
4046 struct got_tag_object *tag = NULL;
4047 struct got_object_id *ref_id;
4048 int cmp;
4050 name = got_ref_get_name(re->ref);
4051 if (strcmp(name, GOT_REF_HEAD) == 0)
4052 continue;
4053 if (strncmp(name, "refs/", 5) == 0)
4054 name += 5;
4055 if (strncmp(name, "got/", 4) == 0)
4056 continue;
4057 if (strncmp(name, "heads/", 6) == 0)
4058 name += 6;
4059 if (strncmp(name, "remotes/", 8) == 0) {
4060 if (local_only)
4061 continue;
4062 name += 8;
4063 s = strstr(name, "/" GOT_REF_HEAD);
4064 if (s != NULL && s[strlen(s)] == '\0')
4065 continue;
4067 err = got_ref_resolve(&ref_id, repo, re->ref);
4068 if (err)
4069 break;
4070 if (strncmp(name, "tags/", 5) == 0) {
4071 err = got_object_open_as_tag(&tag, repo, ref_id);
4072 if (err) {
4073 if (err->code != GOT_ERR_OBJ_TYPE) {
4074 free(ref_id);
4075 break;
4077 /* Ref points at something other than a tag. */
4078 err = NULL;
4079 tag = NULL;
4082 cmp = got_object_id_cmp(tag ?
4083 got_object_tag_get_object_id(tag) : ref_id, id);
4084 free(ref_id);
4085 if (tag)
4086 got_object_tag_close(tag);
4087 if (cmp != 0)
4088 continue;
4089 s = *refs_str;
4090 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4091 s ? ", " : "", name) == -1) {
4092 err = got_error_from_errno("asprintf");
4093 free(s);
4094 *refs_str = NULL;
4095 break;
4097 free(s);
4100 return err;
4103 static const struct got_error *
4104 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4105 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4107 const struct got_error *err = NULL;
4108 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4109 char *comma, *s, *nl;
4110 struct got_reflist_head *refs;
4111 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4112 struct tm tm;
4113 time_t committer_time;
4115 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4116 if (refs) {
4117 err = build_refs_str(&ref_str, refs, id, repo, 1);
4118 if (err)
4119 return err;
4121 /* Display the first matching ref only. */
4122 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4123 *comma = '\0';
4126 if (ref_str == NULL) {
4127 err = got_object_id_str(&id_str, id);
4128 if (err)
4129 return err;
4132 committer_time = got_object_commit_get_committer_time(commit);
4133 if (gmtime_r(&committer_time, &tm) == NULL) {
4134 err = got_error_from_errno("gmtime_r");
4135 goto done;
4137 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4138 err = got_error(GOT_ERR_NO_SPACE);
4139 goto done;
4142 err = got_object_commit_get_logmsg(&logmsg0, commit);
4143 if (err)
4144 goto done;
4146 s = logmsg0;
4147 while (isspace((unsigned char)s[0]))
4148 s++;
4150 nl = strchr(s, '\n');
4151 if (nl) {
4152 *nl = '\0';
4155 if (ref_str)
4156 printf("%s%-7s %s\n", datebuf, ref_str, s);
4157 else
4158 printf("%s%.7s %s\n", datebuf, id_str, s);
4160 if (fflush(stdout) != 0 && err == NULL)
4161 err = got_error_from_errno("fflush");
4162 done:
4163 free(id_str);
4164 free(ref_str);
4165 free(logmsg0);
4166 return err;
4169 static const struct got_error *
4170 print_diffstat(struct got_diffstat_cb_arg *dsa, struct got_pathlist_head *paths,
4171 const char *header)
4173 struct got_pathlist_entry *pe;
4175 if (header != NULL)
4176 printf("%s\n", header);
4178 TAILQ_FOREACH(pe, paths, entry) {
4179 struct got_diff_changed_path *cp = pe->data;
4180 int pad = dsa->max_path_len - pe->path_len + 1;
4182 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4183 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4185 printf("\n%d file%s changed, %d insertions(+), %d deletions(-)\n\n",
4186 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins, dsa->del);
4188 if (fflush(stdout) != 0)
4189 return got_error_from_errno("fflush");
4191 return NULL;
4194 static const struct got_error *
4195 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4196 struct got_repository *repo, const char *path,
4197 struct got_pathlist_head *changed_paths, struct got_diffstat_cb_arg *dsa,
4198 int show_patch, int diff_context,
4199 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str)
4201 const struct got_error *err = NULL;
4202 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4203 char datebuf[26];
4204 time_t committer_time;
4205 const char *author, *committer;
4206 char *refs_str = NULL;
4208 err = got_object_id_str(&id_str, id);
4209 if (err)
4210 return err;
4212 if (custom_refs_str == NULL) {
4213 struct got_reflist_head *refs;
4214 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4215 if (refs) {
4216 err = build_refs_str(&refs_str, refs, id, repo, 0);
4217 if (err)
4218 goto done;
4222 printf(GOT_COMMIT_SEP_STR);
4223 if (custom_refs_str)
4224 printf("commit %s (%s)\n", id_str, custom_refs_str);
4225 else
4226 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4227 refs_str ? refs_str : "", refs_str ? ")" : "");
4228 free(id_str);
4229 id_str = NULL;
4230 free(refs_str);
4231 refs_str = NULL;
4232 printf("from: %s\n", got_object_commit_get_author(commit));
4233 author = got_object_commit_get_author(commit);
4234 committer = got_object_commit_get_committer(commit);
4235 if (strcmp(author, committer) != 0)
4236 printf("via: %s\n", committer);
4237 committer_time = got_object_commit_get_committer_time(commit);
4238 datestr = get_datestr(&committer_time, datebuf);
4239 if (datestr)
4240 printf("date: %s UTC\n", datestr);
4241 if (got_object_commit_get_nparents(commit) > 1) {
4242 const struct got_object_id_queue *parent_ids;
4243 struct got_object_qid *qid;
4244 int n = 1;
4245 parent_ids = got_object_commit_get_parent_ids(commit);
4246 STAILQ_FOREACH(qid, parent_ids, entry) {
4247 err = got_object_id_str(&id_str, &qid->id);
4248 if (err)
4249 goto done;
4250 printf("parent %d: %s\n", n++, id_str);
4251 free(id_str);
4252 id_str = NULL;
4256 err = got_object_commit_get_logmsg(&logmsg0, commit);
4257 if (err)
4258 goto done;
4260 logmsg = logmsg0;
4261 do {
4262 line = strsep(&logmsg, "\n");
4263 if (line)
4264 printf(" %s\n", line);
4265 } while (line);
4266 free(logmsg0);
4268 if (dsa && changed_paths) {
4269 err = print_diffstat(dsa, changed_paths, NULL);
4270 if (err)
4271 goto done;
4272 } else if (changed_paths) {
4273 struct got_pathlist_entry *pe;
4275 TAILQ_FOREACH(pe, changed_paths, entry) {
4276 struct got_diff_changed_path *cp = pe->data;
4278 printf(" %c %s\n", cp->status, pe->path);
4280 printf("\n");
4282 if (show_patch) {
4283 err = print_patch(commit, id, path, diff_context, repo, stdout);
4284 if (err == 0)
4285 printf("\n");
4288 if (fflush(stdout) != 0 && err == NULL)
4289 err = got_error_from_errno("fflush");
4290 done:
4291 free(id_str);
4292 free(refs_str);
4293 return err;
4296 static const struct got_error *
4297 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4298 struct got_repository *repo, const char *path, int show_changed_paths,
4299 int show_diffstat, int show_patch, const char *search_pattern,
4300 int diff_context, int limit, int log_branches, int reverse_display_order,
4301 struct got_reflist_object_id_map *refs_idmap, int one_line,
4302 FILE *tmpfile)
4304 const struct got_error *err;
4305 struct got_commit_graph *graph;
4306 regex_t regex;
4307 int have_match;
4308 struct got_object_id_queue reversed_commits;
4309 struct got_object_qid *qid;
4310 struct got_commit_object *commit;
4311 struct got_pathlist_head changed_paths;
4312 struct got_pathlist_entry *pe;
4314 STAILQ_INIT(&reversed_commits);
4315 TAILQ_INIT(&changed_paths);
4317 if (search_pattern && regcomp(&regex, search_pattern,
4318 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4319 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4321 err = got_commit_graph_open(&graph, path, !log_branches);
4322 if (err)
4323 return err;
4324 err = got_commit_graph_iter_start(graph, root_id, repo,
4325 check_cancelled, NULL);
4326 if (err)
4327 goto done;
4328 for (;;) {
4329 struct got_object_id id;
4330 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4331 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4333 if (sigint_received || sigpipe_received)
4334 break;
4336 err = got_commit_graph_iter_next(&id, graph, repo,
4337 check_cancelled, NULL);
4338 if (err) {
4339 if (err->code == GOT_ERR_ITER_COMPLETED)
4340 err = NULL;
4341 break;
4344 err = got_object_open_as_commit(&commit, repo, &id);
4345 if (err)
4346 break;
4348 if ((show_changed_paths || show_diffstat) &&
4349 !reverse_display_order) {
4350 err = get_changed_paths(&changed_paths, commit, repo,
4351 show_diffstat ? &dsa : NULL);
4352 if (err)
4353 break;
4356 if (search_pattern) {
4357 err = match_commit(&have_match, &id, commit, &regex);
4358 if (err) {
4359 got_object_commit_close(commit);
4360 break;
4362 if (have_match == 0 && show_changed_paths)
4363 match_changed_paths(&have_match,
4364 &changed_paths, &regex);
4365 if (have_match == 0 && show_patch) {
4366 err = match_patch(&have_match, commit, &id,
4367 path, diff_context, repo, &regex,
4368 tmpfile);
4369 if (err)
4370 break;
4372 if (have_match == 0) {
4373 got_object_commit_close(commit);
4374 TAILQ_FOREACH(pe, &changed_paths, entry) {
4375 free((char *)pe->path);
4376 free(pe->data);
4378 got_pathlist_free(&changed_paths);
4379 continue;
4383 if (reverse_display_order) {
4384 err = got_object_qid_alloc(&qid, &id);
4385 if (err)
4386 break;
4387 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4388 got_object_commit_close(commit);
4389 } else {
4390 if (one_line)
4391 err = print_commit_oneline(commit, &id,
4392 repo, refs_idmap);
4393 else
4394 err = print_commit(commit, &id, repo, path,
4395 (show_changed_paths || show_diffstat) ?
4396 &changed_paths : NULL,
4397 show_diffstat ? &dsa : NULL, show_patch,
4398 diff_context, refs_idmap, NULL);
4399 got_object_commit_close(commit);
4400 if (err)
4401 break;
4403 if ((limit && --limit == 0) ||
4404 (end_id && got_object_id_cmp(&id, end_id) == 0))
4405 break;
4407 TAILQ_FOREACH(pe, &changed_paths, entry) {
4408 free((char *)pe->path);
4409 free(pe->data);
4411 got_pathlist_free(&changed_paths);
4413 if (reverse_display_order) {
4414 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4415 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4416 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4418 err = got_object_open_as_commit(&commit, repo,
4419 &qid->id);
4420 if (err)
4421 break;
4422 if (show_changed_paths || show_diffstat) {
4423 err = get_changed_paths(&changed_paths,
4424 commit, repo, show_diffstat ? &dsa : NULL);
4425 if (err)
4426 break;
4428 if (one_line)
4429 err = print_commit_oneline(commit, &qid->id,
4430 repo, refs_idmap);
4431 else
4432 err = print_commit(commit, &qid->id, repo, path,
4433 (show_changed_paths || show_diffstat) ?
4434 &changed_paths : NULL,
4435 show_diffstat ? &dsa : NULL, show_patch,
4436 diff_context, refs_idmap, NULL);
4437 got_object_commit_close(commit);
4438 if (err)
4439 break;
4440 TAILQ_FOREACH(pe, &changed_paths, entry) {
4441 free((char *)pe->path);
4442 free(pe->data);
4444 got_pathlist_free(&changed_paths);
4447 done:
4448 while (!STAILQ_EMPTY(&reversed_commits)) {
4449 qid = STAILQ_FIRST(&reversed_commits);
4450 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4451 got_object_qid_free(qid);
4453 TAILQ_FOREACH(pe, &changed_paths, entry) {
4454 free((char *)pe->path);
4455 free(pe->data);
4457 got_pathlist_free(&changed_paths);
4458 if (search_pattern)
4459 regfree(&regex);
4460 got_commit_graph_close(graph);
4461 return err;
4464 __dead static void
4465 usage_log(void)
4467 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4468 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4469 "[path]\n", getprogname());
4470 exit(1);
4473 static int
4474 get_default_log_limit(void)
4476 const char *got_default_log_limit;
4477 long long n;
4478 const char *errstr;
4480 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4481 if (got_default_log_limit == NULL)
4482 return 0;
4483 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4484 if (errstr != NULL)
4485 return 0;
4486 return n;
4489 static const struct got_error *
4490 cmd_log(int argc, char *argv[])
4492 const struct got_error *error;
4493 struct got_repository *repo = NULL;
4494 struct got_worktree *worktree = NULL;
4495 struct got_object_id *start_id = NULL, *end_id = NULL;
4496 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4497 const char *start_commit = NULL, *end_commit = NULL;
4498 const char *search_pattern = NULL;
4499 int diff_context = -1, ch;
4500 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4501 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4502 const char *errstr;
4503 struct got_reflist_head refs;
4504 struct got_reflist_object_id_map *refs_idmap = NULL;
4505 FILE *tmpfile = NULL;
4506 int *pack_fds = NULL;
4508 TAILQ_INIT(&refs);
4510 #ifndef PROFILE
4511 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4512 NULL)
4513 == -1)
4514 err(1, "pledge");
4515 #endif
4517 limit = get_default_log_limit();
4519 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4520 switch (ch) {
4521 case 'b':
4522 log_branches = 1;
4523 break;
4524 case 'C':
4525 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4526 &errstr);
4527 if (errstr != NULL)
4528 errx(1, "number of context lines is %s: %s",
4529 errstr, optarg);
4530 break;
4531 case 'c':
4532 start_commit = optarg;
4533 break;
4534 case 'd':
4535 show_diffstat = 1;
4536 break;
4537 case 'l':
4538 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4539 if (errstr != NULL)
4540 errx(1, "number of commits is %s: %s",
4541 errstr, optarg);
4542 break;
4543 case 'P':
4544 show_changed_paths = 1;
4545 break;
4546 case 'p':
4547 show_patch = 1;
4548 break;
4549 case 'R':
4550 reverse_display_order = 1;
4551 break;
4552 case 'r':
4553 repo_path = realpath(optarg, NULL);
4554 if (repo_path == NULL)
4555 return got_error_from_errno2("realpath",
4556 optarg);
4557 got_path_strip_trailing_slashes(repo_path);
4558 break;
4559 case 'S':
4560 search_pattern = optarg;
4561 break;
4562 case 's':
4563 one_line = 1;
4564 break;
4565 case 'x':
4566 end_commit = optarg;
4567 break;
4568 default:
4569 usage_log();
4570 /* NOTREACHED */
4574 argc -= optind;
4575 argv += optind;
4577 if (diff_context == -1)
4578 diff_context = 3;
4579 else if (!show_patch)
4580 errx(1, "-C requires -p");
4582 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4583 errx(1, "cannot use -s with -d, -p or -P");
4585 cwd = getcwd(NULL, 0);
4586 if (cwd == NULL) {
4587 error = got_error_from_errno("getcwd");
4588 goto done;
4591 error = got_repo_pack_fds_open(&pack_fds);
4592 if (error != NULL)
4593 goto done;
4595 if (repo_path == NULL) {
4596 error = got_worktree_open(&worktree, cwd);
4597 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4598 goto done;
4599 error = NULL;
4602 if (argc == 1) {
4603 if (worktree) {
4604 error = got_worktree_resolve_path(&path, worktree,
4605 argv[0]);
4606 if (error)
4607 goto done;
4608 } else {
4609 path = strdup(argv[0]);
4610 if (path == NULL) {
4611 error = got_error_from_errno("strdup");
4612 goto done;
4615 } else if (argc != 0)
4616 usage_log();
4618 if (repo_path == NULL) {
4619 repo_path = worktree ?
4620 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4622 if (repo_path == NULL) {
4623 error = got_error_from_errno("strdup");
4624 goto done;
4627 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4628 if (error != NULL)
4629 goto done;
4631 error = apply_unveil(got_repo_get_path(repo), 1,
4632 worktree ? got_worktree_get_root_path(worktree) : NULL);
4633 if (error)
4634 goto done;
4636 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4637 if (error)
4638 goto done;
4640 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4641 if (error)
4642 goto done;
4644 if (start_commit == NULL) {
4645 struct got_reference *head_ref;
4646 struct got_commit_object *commit = NULL;
4647 error = got_ref_open(&head_ref, repo,
4648 worktree ? got_worktree_get_head_ref_name(worktree)
4649 : GOT_REF_HEAD, 0);
4650 if (error != NULL)
4651 goto done;
4652 error = got_ref_resolve(&start_id, repo, head_ref);
4653 got_ref_close(head_ref);
4654 if (error != NULL)
4655 goto done;
4656 error = got_object_open_as_commit(&commit, repo,
4657 start_id);
4658 if (error != NULL)
4659 goto done;
4660 got_object_commit_close(commit);
4661 } else {
4662 error = got_repo_match_object_id(&start_id, NULL,
4663 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4664 if (error != NULL)
4665 goto done;
4667 if (end_commit != NULL) {
4668 error = got_repo_match_object_id(&end_id, NULL,
4669 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4670 if (error != NULL)
4671 goto done;
4674 if (worktree) {
4676 * If a path was specified on the command line it was resolved
4677 * to a path in the work tree above. Prepend the work tree's
4678 * path prefix to obtain the corresponding in-repository path.
4680 if (path) {
4681 const char *prefix;
4682 prefix = got_worktree_get_path_prefix(worktree);
4683 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4684 (path[0] != '\0') ? "/" : "", path) == -1) {
4685 error = got_error_from_errno("asprintf");
4686 goto done;
4689 } else
4690 error = got_repo_map_path(&in_repo_path, repo,
4691 path ? path : "");
4692 if (error != NULL)
4693 goto done;
4694 if (in_repo_path) {
4695 free(path);
4696 path = in_repo_path;
4699 if (worktree) {
4700 /* Release work tree lock. */
4701 got_worktree_close(worktree);
4702 worktree = NULL;
4705 if (search_pattern && show_patch) {
4706 tmpfile = got_opentemp();
4707 if (tmpfile == NULL) {
4708 error = got_error_from_errno("got_opentemp");
4709 goto done;
4713 error = print_commits(start_id, end_id, repo, path ? path : "",
4714 show_changed_paths, show_diffstat, show_patch, search_pattern,
4715 diff_context, limit, log_branches, reverse_display_order,
4716 refs_idmap, one_line, tmpfile);
4717 done:
4718 free(path);
4719 free(repo_path);
4720 free(cwd);
4721 if (worktree)
4722 got_worktree_close(worktree);
4723 if (repo) {
4724 const struct got_error *close_err = got_repo_close(repo);
4725 if (error == NULL)
4726 error = close_err;
4728 if (pack_fds) {
4729 const struct got_error *pack_err =
4730 got_repo_pack_fds_close(pack_fds);
4731 if (error == NULL)
4732 error = pack_err;
4734 if (refs_idmap)
4735 got_reflist_object_id_map_free(refs_idmap);
4736 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4737 error = got_error_from_errno("fclose");
4738 got_ref_list_free(&refs);
4739 return error;
4742 __dead static void
4743 usage_diff(void)
4745 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4746 "[-r repository-path] [object1 object2 | path ...]\n",
4747 getprogname());
4748 exit(1);
4751 struct print_diff_arg {
4752 struct got_repository *repo;
4753 struct got_worktree *worktree;
4754 struct got_diffstat_cb_arg *diffstat;
4755 int diff_context;
4756 const char *id_str;
4757 int header_shown;
4758 int diff_staged;
4759 enum got_diff_algorithm diff_algo;
4760 int ignore_whitespace;
4761 int force_text_diff;
4762 int show_diffstat;
4763 FILE *f1;
4764 FILE *f2;
4765 FILE *outfile;
4769 * Create a file which contains the target path of a symlink so we can feed
4770 * it as content to the diff engine.
4772 static const struct got_error *
4773 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4774 const char *abspath)
4776 const struct got_error *err = NULL;
4777 char target_path[PATH_MAX];
4778 ssize_t target_len, outlen;
4780 *fd = -1;
4782 if (dirfd != -1) {
4783 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4784 if (target_len == -1)
4785 return got_error_from_errno2("readlinkat", abspath);
4786 } else {
4787 target_len = readlink(abspath, target_path, PATH_MAX);
4788 if (target_len == -1)
4789 return got_error_from_errno2("readlink", abspath);
4792 *fd = got_opentempfd();
4793 if (*fd == -1)
4794 return got_error_from_errno("got_opentempfd");
4796 outlen = write(*fd, target_path, target_len);
4797 if (outlen == -1) {
4798 err = got_error_from_errno("got_opentempfd");
4799 goto done;
4802 if (lseek(*fd, 0, SEEK_SET) == -1) {
4803 err = got_error_from_errno2("lseek", abspath);
4804 goto done;
4806 done:
4807 if (err) {
4808 close(*fd);
4809 *fd = -1;
4811 return err;
4814 static const struct got_error *
4815 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4816 const char *path, struct got_object_id *blob_id,
4817 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4818 int dirfd, const char *de_name)
4820 struct print_diff_arg *a = arg;
4821 const struct got_error *err = NULL;
4822 struct got_blob_object *blob1 = NULL;
4823 int fd = -1, fd1 = -1, fd2 = -1;
4824 FILE *f2 = NULL;
4825 char *abspath = NULL, *label1 = NULL;
4826 struct stat sb;
4827 off_t size1 = 0;
4828 int f2_exists = 0;
4830 memset(&sb, 0, sizeof(sb));
4832 if (a->diff_staged) {
4833 if (staged_status != GOT_STATUS_MODIFY &&
4834 staged_status != GOT_STATUS_ADD &&
4835 staged_status != GOT_STATUS_DELETE)
4836 return NULL;
4837 } else {
4838 if (staged_status == GOT_STATUS_DELETE)
4839 return NULL;
4840 if (status == GOT_STATUS_NONEXISTENT)
4841 return got_error_set_errno(ENOENT, path);
4842 if (status != GOT_STATUS_MODIFY &&
4843 status != GOT_STATUS_ADD &&
4844 status != GOT_STATUS_DELETE &&
4845 status != GOT_STATUS_CONFLICT)
4846 return NULL;
4849 err = got_opentemp_truncate(a->f1);
4850 if (err)
4851 return got_error_from_errno("got_opentemp_truncate");
4852 err = got_opentemp_truncate(a->f2);
4853 if (err)
4854 return got_error_from_errno("got_opentemp_truncate");
4856 if (!a->header_shown) {
4857 if (fprintf(a->outfile, "diff %s%s\n",
4858 a->diff_staged ? "-s " : "",
4859 got_worktree_get_root_path(a->worktree)) < 0) {
4860 err = got_error_from_errno("fprintf");
4861 goto done;
4863 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4864 err = got_error_from_errno("fprintf");
4865 goto done;
4867 if (fprintf(a->outfile, "path + %s%s\n",
4868 got_worktree_get_root_path(a->worktree),
4869 a->diff_staged ? " (staged changes)" : "") < 0) {
4870 err = got_error_from_errno("fprintf");
4871 goto done;
4873 a->header_shown = 1;
4876 if (a->diff_staged) {
4877 const char *label1 = NULL, *label2 = NULL;
4878 switch (staged_status) {
4879 case GOT_STATUS_MODIFY:
4880 label1 = path;
4881 label2 = path;
4882 break;
4883 case GOT_STATUS_ADD:
4884 label2 = path;
4885 break;
4886 case GOT_STATUS_DELETE:
4887 label1 = path;
4888 break;
4889 default:
4890 return got_error(GOT_ERR_FILE_STATUS);
4892 fd1 = got_opentempfd();
4893 if (fd1 == -1) {
4894 err = got_error_from_errno("got_opentempfd");
4895 goto done;
4897 fd2 = got_opentempfd();
4898 if (fd2 == -1) {
4899 err = got_error_from_errno("got_opentempfd");
4900 goto done;
4902 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4903 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4904 a->diff_algo, a->diff_context, a->ignore_whitespace,
4905 a->force_text_diff, a->show_diffstat, a->diffstat, a->repo,
4906 a->outfile);
4907 goto done;
4910 fd1 = got_opentempfd();
4911 if (fd1 == -1) {
4912 err = got_error_from_errno("got_opentempfd");
4913 goto done;
4916 if (staged_status == GOT_STATUS_ADD ||
4917 staged_status == GOT_STATUS_MODIFY) {
4918 char *id_str;
4919 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4920 8192, fd1);
4921 if (err)
4922 goto done;
4923 err = got_object_id_str(&id_str, staged_blob_id);
4924 if (err)
4925 goto done;
4926 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4927 err = got_error_from_errno("asprintf");
4928 free(id_str);
4929 goto done;
4931 free(id_str);
4932 } else if (status != GOT_STATUS_ADD) {
4933 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4934 fd1);
4935 if (err)
4936 goto done;
4939 if (status != GOT_STATUS_DELETE) {
4940 if (asprintf(&abspath, "%s/%s",
4941 got_worktree_get_root_path(a->worktree), path) == -1) {
4942 err = got_error_from_errno("asprintf");
4943 goto done;
4946 if (dirfd != -1) {
4947 fd = openat(dirfd, de_name,
4948 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4949 if (fd == -1) {
4950 if (!got_err_open_nofollow_on_symlink()) {
4951 err = got_error_from_errno2("openat",
4952 abspath);
4953 goto done;
4955 err = get_symlink_target_file(&fd, dirfd,
4956 de_name, abspath);
4957 if (err)
4958 goto done;
4960 } else {
4961 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4962 if (fd == -1) {
4963 if (!got_err_open_nofollow_on_symlink()) {
4964 err = got_error_from_errno2("open",
4965 abspath);
4966 goto done;
4968 err = get_symlink_target_file(&fd, dirfd,
4969 de_name, abspath);
4970 if (err)
4971 goto done;
4974 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
4975 err = got_error_from_errno2("fstatat", abspath);
4976 goto done;
4978 f2 = fdopen(fd, "r");
4979 if (f2 == NULL) {
4980 err = got_error_from_errno2("fdopen", abspath);
4981 goto done;
4983 fd = -1;
4984 f2_exists = 1;
4987 if (blob1) {
4988 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4989 a->f1, blob1);
4990 if (err)
4991 goto done;
4994 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
4995 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
4996 a->ignore_whitespace, a->force_text_diff, a->show_diffstat,
4997 a->diffstat, a->outfile);
4998 done:
4999 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5000 err = got_error_from_errno("close");
5001 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5002 err = got_error_from_errno("close");
5003 if (blob1)
5004 got_object_blob_close(blob1);
5005 if (fd != -1 && close(fd) == -1 && err == NULL)
5006 err = got_error_from_errno("close");
5007 if (f2 && fclose(f2) == EOF && err == NULL)
5008 err = got_error_from_errno("fclose");
5009 free(abspath);
5010 return err;
5013 static const struct got_error *
5014 printfile(FILE *f)
5016 char buf[8192];
5017 size_t r;
5019 if (fseeko(f, 0L, SEEK_SET) == -1)
5020 return got_error_from_errno("fseek");
5022 for (;;) {
5023 r = fread(buf, 1, sizeof(buf), f);
5024 if (r == 0) {
5025 if (ferror(f))
5026 return got_error_from_errno("fread");
5027 if (feof(f))
5028 break;
5030 if (fwrite(buf, 1, r, stdout) != r)
5031 return got_ferror(stdout, GOT_ERR_IO);
5034 return NULL;
5037 static const struct got_error *
5038 cmd_diff(int argc, char *argv[])
5040 const struct got_error *error;
5041 struct got_repository *repo = NULL;
5042 struct got_worktree *worktree = NULL;
5043 char *cwd = NULL, *repo_path = NULL;
5044 const char *commit_args[2] = { NULL, NULL };
5045 int ncommit_args = 0;
5046 struct got_object_id *ids[2] = { NULL, NULL };
5047 char *labels[2] = { NULL, NULL };
5048 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5049 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5050 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5051 const char *errstr;
5052 struct got_reflist_head refs;
5053 struct got_pathlist_head diffstat_paths, paths;
5054 struct got_pathlist_entry *pe;
5055 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5056 int fd1 = -1, fd2 = -1;
5057 int *pack_fds = NULL;
5058 struct got_diffstat_cb_arg dsa;
5060 memset(&dsa, 0, sizeof(dsa));
5062 TAILQ_INIT(&refs);
5063 TAILQ_INIT(&paths);
5064 TAILQ_INIT(&diffstat_paths);
5066 #ifndef PROFILE
5067 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5068 NULL) == -1)
5069 err(1, "pledge");
5070 #endif
5072 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5073 switch (ch) {
5074 case 'a':
5075 force_text_diff = 1;
5076 break;
5077 case 'C':
5078 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5079 &errstr);
5080 if (errstr != NULL)
5081 errx(1, "number of context lines is %s: %s",
5082 errstr, optarg);
5083 break;
5084 case 'c':
5085 if (ncommit_args >= 2)
5086 errx(1, "too many -c options used");
5087 commit_args[ncommit_args++] = optarg;
5088 break;
5089 case 'd':
5090 show_diffstat = 1;
5091 break;
5092 case 'P':
5093 force_path = 1;
5094 break;
5095 case 'r':
5096 repo_path = realpath(optarg, NULL);
5097 if (repo_path == NULL)
5098 return got_error_from_errno2("realpath",
5099 optarg);
5100 got_path_strip_trailing_slashes(repo_path);
5101 rflag = 1;
5102 break;
5103 case 's':
5104 diff_staged = 1;
5105 break;
5106 case 'w':
5107 ignore_whitespace = 1;
5108 break;
5109 default:
5110 usage_diff();
5111 /* NOTREACHED */
5115 argc -= optind;
5116 argv += optind;
5118 cwd = getcwd(NULL, 0);
5119 if (cwd == NULL) {
5120 error = got_error_from_errno("getcwd");
5121 goto done;
5124 error = got_repo_pack_fds_open(&pack_fds);
5125 if (error != NULL)
5126 goto done;
5128 if (repo_path == NULL) {
5129 error = got_worktree_open(&worktree, cwd);
5130 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5131 goto done;
5132 else
5133 error = NULL;
5134 if (worktree) {
5135 repo_path =
5136 strdup(got_worktree_get_repo_path(worktree));
5137 if (repo_path == NULL) {
5138 error = got_error_from_errno("strdup");
5139 goto done;
5141 } else {
5142 repo_path = strdup(cwd);
5143 if (repo_path == NULL) {
5144 error = got_error_from_errno("strdup");
5145 goto done;
5150 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5151 free(repo_path);
5152 if (error != NULL)
5153 goto done;
5155 if (show_diffstat) {
5156 dsa.paths = &diffstat_paths;
5157 dsa.force_text = force_text_diff;
5158 dsa.ignore_ws = ignore_whitespace;
5159 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5162 if (rflag || worktree == NULL || ncommit_args > 0) {
5163 if (force_path) {
5164 error = got_error_msg(GOT_ERR_NOT_IMPL,
5165 "-P option can only be used when diffing "
5166 "a work tree");
5167 goto done;
5169 if (diff_staged) {
5170 error = got_error_msg(GOT_ERR_NOT_IMPL,
5171 "-s option can only be used when diffing "
5172 "a work tree");
5173 goto done;
5177 error = apply_unveil(got_repo_get_path(repo), 1,
5178 worktree ? got_worktree_get_root_path(worktree) : NULL);
5179 if (error)
5180 goto done;
5182 if ((!force_path && argc == 2) || ncommit_args > 0) {
5183 int obj_type = (ncommit_args > 0 ?
5184 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5185 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5186 NULL);
5187 if (error)
5188 goto done;
5189 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5190 const char *arg;
5191 if (ncommit_args > 0)
5192 arg = commit_args[i];
5193 else
5194 arg = argv[i];
5195 error = got_repo_match_object_id(&ids[i], &labels[i],
5196 arg, obj_type, &refs, repo);
5197 if (error) {
5198 if (error->code != GOT_ERR_NOT_REF &&
5199 error->code != GOT_ERR_NO_OBJ)
5200 goto done;
5201 if (ncommit_args > 0)
5202 goto done;
5203 error = NULL;
5204 break;
5209 f1 = got_opentemp();
5210 if (f1 == NULL) {
5211 error = got_error_from_errno("got_opentemp");
5212 goto done;
5215 f2 = got_opentemp();
5216 if (f2 == NULL) {
5217 error = got_error_from_errno("got_opentemp");
5218 goto done;
5221 outfile = got_opentemp();
5222 if (outfile == NULL) {
5223 error = got_error_from_errno("got_opentemp");
5224 goto done;
5227 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5228 struct print_diff_arg arg;
5229 char *id_str;
5231 if (worktree == NULL) {
5232 if (argc == 2 && ids[0] == NULL) {
5233 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5234 goto done;
5235 } else if (argc == 2 && ids[1] == NULL) {
5236 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5237 goto done;
5238 } else if (argc > 0) {
5239 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5240 "%s", "specified paths cannot be resolved");
5241 goto done;
5242 } else {
5243 error = got_error(GOT_ERR_NOT_WORKTREE);
5244 goto done;
5248 error = get_worktree_paths_from_argv(&paths, argc, argv,
5249 worktree);
5250 if (error)
5251 goto done;
5253 error = got_object_id_str(&id_str,
5254 got_worktree_get_base_commit_id(worktree));
5255 if (error)
5256 goto done;
5257 arg.repo = repo;
5258 arg.worktree = worktree;
5259 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5260 arg.diff_context = diff_context;
5261 arg.id_str = id_str;
5262 arg.header_shown = 0;
5263 arg.diff_staged = diff_staged;
5264 arg.ignore_whitespace = ignore_whitespace;
5265 arg.force_text_diff = force_text_diff;
5266 arg.show_diffstat = show_diffstat;
5267 arg.diffstat = &dsa;
5268 arg.f1 = f1;
5269 arg.f2 = f2;
5270 arg.outfile = outfile;
5272 error = got_worktree_status(worktree, &paths, repo, 0,
5273 print_diff, &arg, check_cancelled, NULL);
5274 free(id_str);
5275 if (error)
5276 goto done;
5278 if (show_diffstat && dsa.nfiles > 0) {
5279 char *header;
5281 if (asprintf(&header, "diffstat %s%s",
5282 diff_staged ? "-s " : "",
5283 got_worktree_get_root_path(worktree)) == -1)
5284 goto done;
5286 error = print_diffstat(&dsa, &diffstat_paths, header);
5287 free(header);
5288 if (error)
5289 goto done;
5292 error = printfile(outfile);
5293 goto done;
5296 if (ncommit_args == 1) {
5297 struct got_commit_object *commit;
5298 error = got_object_open_as_commit(&commit, repo, ids[0]);
5299 if (error)
5300 goto done;
5302 labels[1] = labels[0];
5303 ids[1] = ids[0];
5304 if (got_object_commit_get_nparents(commit) > 0) {
5305 const struct got_object_id_queue *pids;
5306 struct got_object_qid *pid;
5307 pids = got_object_commit_get_parent_ids(commit);
5308 pid = STAILQ_FIRST(pids);
5309 ids[0] = got_object_id_dup(&pid->id);
5310 if (ids[0] == NULL) {
5311 error = got_error_from_errno(
5312 "got_object_id_dup");
5313 got_object_commit_close(commit);
5314 goto done;
5316 error = got_object_id_str(&labels[0], ids[0]);
5317 if (error) {
5318 got_object_commit_close(commit);
5319 goto done;
5321 } else {
5322 ids[0] = NULL;
5323 labels[0] = strdup("/dev/null");
5324 if (labels[0] == NULL) {
5325 error = got_error_from_errno("strdup");
5326 got_object_commit_close(commit);
5327 goto done;
5331 got_object_commit_close(commit);
5334 if (ncommit_args == 0 && argc > 2) {
5335 error = got_error_msg(GOT_ERR_BAD_PATH,
5336 "path arguments cannot be used when diffing two objects");
5337 goto done;
5340 if (ids[0]) {
5341 error = got_object_get_type(&type1, repo, ids[0]);
5342 if (error)
5343 goto done;
5346 error = got_object_get_type(&type2, repo, ids[1]);
5347 if (error)
5348 goto done;
5349 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5350 error = got_error(GOT_ERR_OBJ_TYPE);
5351 goto done;
5353 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5354 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5355 "path arguments cannot be used when diffing blobs");
5356 goto done;
5359 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5360 char *in_repo_path;
5361 struct got_pathlist_entry *new;
5362 if (worktree) {
5363 const char *prefix;
5364 char *p;
5365 error = got_worktree_resolve_path(&p, worktree,
5366 argv[i]);
5367 if (error)
5368 goto done;
5369 prefix = got_worktree_get_path_prefix(worktree);
5370 while (prefix[0] == '/')
5371 prefix++;
5372 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5373 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5374 p) == -1) {
5375 error = got_error_from_errno("asprintf");
5376 free(p);
5377 goto done;
5379 free(p);
5380 } else {
5381 char *mapped_path, *s;
5382 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5383 if (error)
5384 goto done;
5385 s = mapped_path;
5386 while (s[0] == '/')
5387 s++;
5388 in_repo_path = strdup(s);
5389 if (in_repo_path == NULL) {
5390 error = got_error_from_errno("asprintf");
5391 free(mapped_path);
5392 goto done;
5394 free(mapped_path);
5397 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5398 if (error || new == NULL /* duplicate */)
5399 free(in_repo_path);
5400 if (error)
5401 goto done;
5404 if (worktree) {
5405 /* Release work tree lock. */
5406 got_worktree_close(worktree);
5407 worktree = NULL;
5410 fd1 = got_opentempfd();
5411 if (fd1 == -1) {
5412 error = got_error_from_errno("got_opentempfd");
5413 goto done;
5416 fd2 = got_opentempfd();
5417 if (fd2 == -1) {
5418 error = got_error_from_errno("got_opentempfd");
5419 goto done;
5422 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5423 case GOT_OBJ_TYPE_BLOB:
5424 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5425 fd1, fd2, ids[0], ids[1], NULL, NULL,
5426 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5427 ignore_whitespace, force_text_diff, show_diffstat,
5428 show_diffstat ? &dsa : NULL, repo, outfile);
5429 break;
5430 case GOT_OBJ_TYPE_TREE:
5431 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5432 ids[0], ids[1], &paths, "", "",
5433 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5434 ignore_whitespace, force_text_diff, show_diffstat,
5435 show_diffstat ? &dsa : NULL, repo, outfile);
5436 break;
5437 case GOT_OBJ_TYPE_COMMIT:
5438 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5439 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5440 fd1, fd2, ids[0], ids[1], &paths,
5441 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5442 ignore_whitespace, force_text_diff, show_diffstat,
5443 show_diffstat ? &dsa : NULL, repo, outfile);
5444 break;
5445 default:
5446 error = got_error(GOT_ERR_OBJ_TYPE);
5448 if (error)
5449 goto done;
5451 if (show_diffstat && dsa.nfiles > 0) {
5452 char *header = NULL;
5454 if (asprintf(&header, "diffstat %s %s",
5455 labels[0], labels[1]) == -1)
5456 goto done;
5458 error = print_diffstat(&dsa, &diffstat_paths, header);
5459 free(header);
5460 if (error)
5461 goto done;
5464 error = printfile(outfile);
5466 done:
5467 free(labels[0]);
5468 free(labels[1]);
5469 free(ids[0]);
5470 free(ids[1]);
5471 if (worktree)
5472 got_worktree_close(worktree);
5473 if (repo) {
5474 const struct got_error *close_err = got_repo_close(repo);
5475 if (error == NULL)
5476 error = close_err;
5478 if (pack_fds) {
5479 const struct got_error *pack_err =
5480 got_repo_pack_fds_close(pack_fds);
5481 if (error == NULL)
5482 error = pack_err;
5484 TAILQ_FOREACH(pe, &paths, entry)
5485 free((char *)pe->path);
5486 got_pathlist_free(&paths);
5487 TAILQ_FOREACH(pe, &diffstat_paths, entry) {
5488 free((char *)pe->path);
5489 free(pe->data);
5491 got_pathlist_free(&diffstat_paths);
5492 got_ref_list_free(&refs);
5493 if (outfile && fclose(outfile) == EOF && error == NULL)
5494 error = got_error_from_errno("fclose");
5495 if (f1 && fclose(f1) == EOF && error == NULL)
5496 error = got_error_from_errno("fclose");
5497 if (f2 && fclose(f2) == EOF && error == NULL)
5498 error = got_error_from_errno("fclose");
5499 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5500 error = got_error_from_errno("close");
5501 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5502 error = got_error_from_errno("close");
5503 return error;
5506 __dead static void
5507 usage_blame(void)
5509 fprintf(stderr,
5510 "usage: %s blame [-c commit] [-r repository-path] path\n",
5511 getprogname());
5512 exit(1);
5515 struct blame_line {
5516 int annotated;
5517 char *id_str;
5518 char *committer;
5519 char datebuf[11]; /* YYYY-MM-DD + NUL */
5522 struct blame_cb_args {
5523 struct blame_line *lines;
5524 int nlines;
5525 int nlines_prec;
5526 int lineno_cur;
5527 off_t *line_offsets;
5528 FILE *f;
5529 struct got_repository *repo;
5532 static const struct got_error *
5533 blame_cb(void *arg, int nlines, int lineno,
5534 struct got_commit_object *commit, struct got_object_id *id)
5536 const struct got_error *err = NULL;
5537 struct blame_cb_args *a = arg;
5538 struct blame_line *bline;
5539 char *line = NULL;
5540 size_t linesize = 0;
5541 off_t offset;
5542 struct tm tm;
5543 time_t committer_time;
5545 if (nlines != a->nlines ||
5546 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5547 return got_error(GOT_ERR_RANGE);
5549 if (sigint_received)
5550 return got_error(GOT_ERR_ITER_COMPLETED);
5552 if (lineno == -1)
5553 return NULL; /* no change in this commit */
5555 /* Annotate this line. */
5556 bline = &a->lines[lineno - 1];
5557 if (bline->annotated)
5558 return NULL;
5559 err = got_object_id_str(&bline->id_str, id);
5560 if (err)
5561 return err;
5563 bline->committer = strdup(got_object_commit_get_committer(commit));
5564 if (bline->committer == NULL) {
5565 err = got_error_from_errno("strdup");
5566 goto done;
5569 committer_time = got_object_commit_get_committer_time(commit);
5570 if (gmtime_r(&committer_time, &tm) == NULL)
5571 return got_error_from_errno("gmtime_r");
5572 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5573 &tm) == 0) {
5574 err = got_error(GOT_ERR_NO_SPACE);
5575 goto done;
5577 bline->annotated = 1;
5579 /* Print lines annotated so far. */
5580 bline = &a->lines[a->lineno_cur - 1];
5581 if (!bline->annotated)
5582 goto done;
5584 offset = a->line_offsets[a->lineno_cur - 1];
5585 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5586 err = got_error_from_errno("fseeko");
5587 goto done;
5590 while (a->lineno_cur <= a->nlines && bline->annotated) {
5591 char *smallerthan, *at, *nl, *committer;
5592 size_t len;
5594 if (getline(&line, &linesize, a->f) == -1) {
5595 if (ferror(a->f))
5596 err = got_error_from_errno("getline");
5597 break;
5600 committer = bline->committer;
5601 smallerthan = strchr(committer, '<');
5602 if (smallerthan && smallerthan[1] != '\0')
5603 committer = smallerthan + 1;
5604 at = strchr(committer, '@');
5605 if (at)
5606 *at = '\0';
5607 len = strlen(committer);
5608 if (len >= 9)
5609 committer[8] = '\0';
5611 nl = strchr(line, '\n');
5612 if (nl)
5613 *nl = '\0';
5614 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5615 bline->id_str, bline->datebuf, committer, line);
5617 a->lineno_cur++;
5618 bline = &a->lines[a->lineno_cur - 1];
5620 done:
5621 free(line);
5622 return err;
5625 static const struct got_error *
5626 cmd_blame(int argc, char *argv[])
5628 const struct got_error *error;
5629 struct got_repository *repo = NULL;
5630 struct got_worktree *worktree = NULL;
5631 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5632 char *link_target = NULL;
5633 struct got_object_id *obj_id = NULL;
5634 struct got_object_id *commit_id = NULL;
5635 struct got_commit_object *commit = NULL;
5636 struct got_blob_object *blob = NULL;
5637 char *commit_id_str = NULL;
5638 struct blame_cb_args bca;
5639 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5640 off_t filesize;
5641 int *pack_fds = NULL;
5642 FILE *f1 = NULL, *f2 = NULL;
5644 fd1 = got_opentempfd();
5645 if (fd1 == -1)
5646 return got_error_from_errno("got_opentempfd");
5648 memset(&bca, 0, sizeof(bca));
5650 #ifndef PROFILE
5651 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5652 NULL) == -1)
5653 err(1, "pledge");
5654 #endif
5656 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5657 switch (ch) {
5658 case 'c':
5659 commit_id_str = optarg;
5660 break;
5661 case 'r':
5662 repo_path = realpath(optarg, NULL);
5663 if (repo_path == NULL)
5664 return got_error_from_errno2("realpath",
5665 optarg);
5666 got_path_strip_trailing_slashes(repo_path);
5667 break;
5668 default:
5669 usage_blame();
5670 /* NOTREACHED */
5674 argc -= optind;
5675 argv += optind;
5677 if (argc == 1)
5678 path = argv[0];
5679 else
5680 usage_blame();
5682 cwd = getcwd(NULL, 0);
5683 if (cwd == NULL) {
5684 error = got_error_from_errno("getcwd");
5685 goto done;
5688 error = got_repo_pack_fds_open(&pack_fds);
5689 if (error != NULL)
5690 goto done;
5692 if (repo_path == NULL) {
5693 error = got_worktree_open(&worktree, cwd);
5694 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5695 goto done;
5696 else
5697 error = NULL;
5698 if (worktree) {
5699 repo_path =
5700 strdup(got_worktree_get_repo_path(worktree));
5701 if (repo_path == NULL) {
5702 error = got_error_from_errno("strdup");
5703 if (error)
5704 goto done;
5706 } else {
5707 repo_path = strdup(cwd);
5708 if (repo_path == NULL) {
5709 error = got_error_from_errno("strdup");
5710 goto done;
5715 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5716 if (error != NULL)
5717 goto done;
5719 if (worktree) {
5720 const char *prefix = got_worktree_get_path_prefix(worktree);
5721 char *p;
5723 error = got_worktree_resolve_path(&p, worktree, path);
5724 if (error)
5725 goto done;
5726 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5727 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5728 p) == -1) {
5729 error = got_error_from_errno("asprintf");
5730 free(p);
5731 goto done;
5733 free(p);
5734 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5735 } else {
5736 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5737 if (error)
5738 goto done;
5739 error = got_repo_map_path(&in_repo_path, repo, path);
5741 if (error)
5742 goto done;
5744 if (commit_id_str == NULL) {
5745 struct got_reference *head_ref;
5746 error = got_ref_open(&head_ref, repo, worktree ?
5747 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5748 if (error != NULL)
5749 goto done;
5750 error = got_ref_resolve(&commit_id, repo, head_ref);
5751 got_ref_close(head_ref);
5752 if (error != NULL)
5753 goto done;
5754 } else {
5755 struct got_reflist_head refs;
5756 TAILQ_INIT(&refs);
5757 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5758 NULL);
5759 if (error)
5760 goto done;
5761 error = got_repo_match_object_id(&commit_id, NULL,
5762 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5763 got_ref_list_free(&refs);
5764 if (error)
5765 goto done;
5768 if (worktree) {
5769 /* Release work tree lock. */
5770 got_worktree_close(worktree);
5771 worktree = NULL;
5774 error = got_object_open_as_commit(&commit, repo, commit_id);
5775 if (error)
5776 goto done;
5778 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5779 commit, repo);
5780 if (error)
5781 goto done;
5783 error = got_object_id_by_path(&obj_id, repo, commit,
5784 link_target ? link_target : in_repo_path);
5785 if (error)
5786 goto done;
5788 error = got_object_get_type(&obj_type, repo, obj_id);
5789 if (error)
5790 goto done;
5792 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5793 error = got_error_path(link_target ? link_target : in_repo_path,
5794 GOT_ERR_OBJ_TYPE);
5795 goto done;
5798 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5799 if (error)
5800 goto done;
5801 bca.f = got_opentemp();
5802 if (bca.f == NULL) {
5803 error = got_error_from_errno("got_opentemp");
5804 goto done;
5806 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5807 &bca.line_offsets, bca.f, blob);
5808 if (error || bca.nlines == 0)
5809 goto done;
5811 /* Don't include \n at EOF in the blame line count. */
5812 if (bca.line_offsets[bca.nlines - 1] == filesize)
5813 bca.nlines--;
5815 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5816 if (bca.lines == NULL) {
5817 error = got_error_from_errno("calloc");
5818 goto done;
5820 bca.lineno_cur = 1;
5821 bca.nlines_prec = 0;
5822 i = bca.nlines;
5823 while (i > 0) {
5824 i /= 10;
5825 bca.nlines_prec++;
5827 bca.repo = repo;
5829 fd2 = got_opentempfd();
5830 if (fd2 == -1) {
5831 error = got_error_from_errno("got_opentempfd");
5832 goto done;
5834 fd3 = got_opentempfd();
5835 if (fd3 == -1) {
5836 error = got_error_from_errno("got_opentempfd");
5837 goto done;
5839 f1 = got_opentemp();
5840 if (f1 == NULL) {
5841 error = got_error_from_errno("got_opentemp");
5842 goto done;
5844 f2 = got_opentemp();
5845 if (f2 == NULL) {
5846 error = got_error_from_errno("got_opentemp");
5847 goto done;
5849 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5850 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5851 check_cancelled, NULL, fd2, fd3, f1, f2);
5852 done:
5853 free(in_repo_path);
5854 free(link_target);
5855 free(repo_path);
5856 free(cwd);
5857 free(commit_id);
5858 free(obj_id);
5859 if (commit)
5860 got_object_commit_close(commit);
5862 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5863 error = got_error_from_errno("close");
5864 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5865 error = got_error_from_errno("close");
5866 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5867 error = got_error_from_errno("close");
5868 if (f1 && fclose(f1) == EOF && error == NULL)
5869 error = got_error_from_errno("fclose");
5870 if (f2 && fclose(f2) == EOF && error == NULL)
5871 error = got_error_from_errno("fclose");
5873 if (blob)
5874 got_object_blob_close(blob);
5875 if (worktree)
5876 got_worktree_close(worktree);
5877 if (repo) {
5878 const struct got_error *close_err = got_repo_close(repo);
5879 if (error == NULL)
5880 error = close_err;
5882 if (pack_fds) {
5883 const struct got_error *pack_err =
5884 got_repo_pack_fds_close(pack_fds);
5885 if (error == NULL)
5886 error = pack_err;
5888 if (bca.lines) {
5889 for (i = 0; i < bca.nlines; i++) {
5890 struct blame_line *bline = &bca.lines[i];
5891 free(bline->id_str);
5892 free(bline->committer);
5894 free(bca.lines);
5896 free(bca.line_offsets);
5897 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5898 error = got_error_from_errno("fclose");
5899 return error;
5902 __dead static void
5903 usage_tree(void)
5905 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5906 "[path]\n", getprogname());
5907 exit(1);
5910 static const struct got_error *
5911 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5912 const char *root_path, struct got_repository *repo)
5914 const struct got_error *err = NULL;
5915 int is_root_path = (strcmp(path, root_path) == 0);
5916 const char *modestr = "";
5917 mode_t mode = got_tree_entry_get_mode(te);
5918 char *link_target = NULL;
5920 path += strlen(root_path);
5921 while (path[0] == '/')
5922 path++;
5924 if (got_object_tree_entry_is_submodule(te))
5925 modestr = "$";
5926 else if (S_ISLNK(mode)) {
5927 int i;
5929 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5930 if (err)
5931 return err;
5932 for (i = 0; i < strlen(link_target); i++) {
5933 if (!isprint((unsigned char)link_target[i]))
5934 link_target[i] = '?';
5937 modestr = "@";
5939 else if (S_ISDIR(mode))
5940 modestr = "/";
5941 else if (mode & S_IXUSR)
5942 modestr = "*";
5944 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5945 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5946 link_target ? " -> ": "", link_target ? link_target : "");
5948 free(link_target);
5949 return NULL;
5952 static const struct got_error *
5953 print_tree(const char *path, struct got_commit_object *commit,
5954 int show_ids, int recurse, const char *root_path,
5955 struct got_repository *repo)
5957 const struct got_error *err = NULL;
5958 struct got_object_id *tree_id = NULL;
5959 struct got_tree_object *tree = NULL;
5960 int nentries, i;
5962 err = got_object_id_by_path(&tree_id, repo, commit, path);
5963 if (err)
5964 goto done;
5966 err = got_object_open_as_tree(&tree, repo, tree_id);
5967 if (err)
5968 goto done;
5969 nentries = got_object_tree_get_nentries(tree);
5970 for (i = 0; i < nentries; i++) {
5971 struct got_tree_entry *te;
5972 char *id = NULL;
5974 if (sigint_received || sigpipe_received)
5975 break;
5977 te = got_object_tree_get_entry(tree, i);
5978 if (show_ids) {
5979 char *id_str;
5980 err = got_object_id_str(&id_str,
5981 got_tree_entry_get_id(te));
5982 if (err)
5983 goto done;
5984 if (asprintf(&id, "%s ", id_str) == -1) {
5985 err = got_error_from_errno("asprintf");
5986 free(id_str);
5987 goto done;
5989 free(id_str);
5991 err = print_entry(te, id, path, root_path, repo);
5992 free(id);
5993 if (err)
5994 goto done;
5996 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5997 char *child_path;
5998 if (asprintf(&child_path, "%s%s%s", path,
5999 path[0] == '/' && path[1] == '\0' ? "" : "/",
6000 got_tree_entry_get_name(te)) == -1) {
6001 err = got_error_from_errno("asprintf");
6002 goto done;
6004 err = print_tree(child_path, commit, show_ids, 1,
6005 root_path, repo);
6006 free(child_path);
6007 if (err)
6008 goto done;
6011 done:
6012 if (tree)
6013 got_object_tree_close(tree);
6014 free(tree_id);
6015 return err;
6018 static const struct got_error *
6019 cmd_tree(int argc, char *argv[])
6021 const struct got_error *error;
6022 struct got_repository *repo = NULL;
6023 struct got_worktree *worktree = NULL;
6024 const char *path, *refname = NULL;
6025 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6026 struct got_object_id *commit_id = NULL;
6027 struct got_commit_object *commit = NULL;
6028 char *commit_id_str = NULL;
6029 int show_ids = 0, recurse = 0;
6030 int ch;
6031 int *pack_fds = NULL;
6033 #ifndef PROFILE
6034 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6035 NULL) == -1)
6036 err(1, "pledge");
6037 #endif
6039 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6040 switch (ch) {
6041 case 'c':
6042 commit_id_str = optarg;
6043 break;
6044 case 'i':
6045 show_ids = 1;
6046 break;
6047 case 'R':
6048 recurse = 1;
6049 break;
6050 case 'r':
6051 repo_path = realpath(optarg, NULL);
6052 if (repo_path == NULL)
6053 return got_error_from_errno2("realpath",
6054 optarg);
6055 got_path_strip_trailing_slashes(repo_path);
6056 break;
6057 default:
6058 usage_tree();
6059 /* NOTREACHED */
6063 argc -= optind;
6064 argv += optind;
6066 if (argc == 1)
6067 path = argv[0];
6068 else if (argc > 1)
6069 usage_tree();
6070 else
6071 path = NULL;
6073 cwd = getcwd(NULL, 0);
6074 if (cwd == NULL) {
6075 error = got_error_from_errno("getcwd");
6076 goto done;
6079 error = got_repo_pack_fds_open(&pack_fds);
6080 if (error != NULL)
6081 goto done;
6083 if (repo_path == NULL) {
6084 error = got_worktree_open(&worktree, cwd);
6085 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6086 goto done;
6087 else
6088 error = NULL;
6089 if (worktree) {
6090 repo_path =
6091 strdup(got_worktree_get_repo_path(worktree));
6092 if (repo_path == NULL)
6093 error = got_error_from_errno("strdup");
6094 if (error)
6095 goto done;
6096 } else {
6097 repo_path = strdup(cwd);
6098 if (repo_path == NULL) {
6099 error = got_error_from_errno("strdup");
6100 goto done;
6105 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6106 if (error != NULL)
6107 goto done;
6109 if (worktree) {
6110 const char *prefix = got_worktree_get_path_prefix(worktree);
6111 char *p;
6113 if (path == NULL)
6114 path = "";
6115 error = got_worktree_resolve_path(&p, worktree, path);
6116 if (error)
6117 goto done;
6118 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6119 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6120 p) == -1) {
6121 error = got_error_from_errno("asprintf");
6122 free(p);
6123 goto done;
6125 free(p);
6126 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6127 if (error)
6128 goto done;
6129 } else {
6130 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6131 if (error)
6132 goto done;
6133 if (path == NULL)
6134 path = "/";
6135 error = got_repo_map_path(&in_repo_path, repo, path);
6136 if (error != NULL)
6137 goto done;
6140 if (commit_id_str == NULL) {
6141 struct got_reference *head_ref;
6142 if (worktree)
6143 refname = got_worktree_get_head_ref_name(worktree);
6144 else
6145 refname = GOT_REF_HEAD;
6146 error = got_ref_open(&head_ref, repo, refname, 0);
6147 if (error != NULL)
6148 goto done;
6149 error = got_ref_resolve(&commit_id, repo, head_ref);
6150 got_ref_close(head_ref);
6151 if (error != NULL)
6152 goto done;
6153 } else {
6154 struct got_reflist_head refs;
6155 TAILQ_INIT(&refs);
6156 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6157 NULL);
6158 if (error)
6159 goto done;
6160 error = got_repo_match_object_id(&commit_id, NULL,
6161 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6162 got_ref_list_free(&refs);
6163 if (error)
6164 goto done;
6167 if (worktree) {
6168 /* Release work tree lock. */
6169 got_worktree_close(worktree);
6170 worktree = NULL;
6173 error = got_object_open_as_commit(&commit, repo, commit_id);
6174 if (error)
6175 goto done;
6177 error = print_tree(in_repo_path, commit, show_ids, recurse,
6178 in_repo_path, repo);
6179 done:
6180 free(in_repo_path);
6181 free(repo_path);
6182 free(cwd);
6183 free(commit_id);
6184 if (commit)
6185 got_object_commit_close(commit);
6186 if (worktree)
6187 got_worktree_close(worktree);
6188 if (repo) {
6189 const struct got_error *close_err = got_repo_close(repo);
6190 if (error == NULL)
6191 error = close_err;
6193 if (pack_fds) {
6194 const struct got_error *pack_err =
6195 got_repo_pack_fds_close(pack_fds);
6196 if (error == NULL)
6197 error = pack_err;
6199 return error;
6202 __dead static void
6203 usage_status(void)
6205 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6206 "[-s status-codes] [path ...]\n", getprogname());
6207 exit(1);
6210 struct got_status_arg {
6211 char *status_codes;
6212 int suppress;
6215 static const struct got_error *
6216 print_status(void *arg, unsigned char status, unsigned char staged_status,
6217 const char *path, struct got_object_id *blob_id,
6218 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6219 int dirfd, const char *de_name)
6221 struct got_status_arg *st = arg;
6223 if (status == staged_status && (status == GOT_STATUS_DELETE))
6224 status = GOT_STATUS_NO_CHANGE;
6225 if (st != NULL && st->status_codes) {
6226 size_t ncodes = strlen(st->status_codes);
6227 int i, j = 0;
6229 for (i = 0; i < ncodes ; i++) {
6230 if (st->suppress) {
6231 if (status == st->status_codes[i] ||
6232 staged_status == st->status_codes[i]) {
6233 j++;
6234 continue;
6236 } else {
6237 if (status == st->status_codes[i] ||
6238 staged_status == st->status_codes[i])
6239 break;
6243 if (st->suppress && j == 0)
6244 goto print;
6246 if (i == ncodes)
6247 return NULL;
6249 print:
6250 printf("%c%c %s\n", status, staged_status, path);
6251 return NULL;
6254 static const struct got_error *
6255 cmd_status(int argc, char *argv[])
6257 const struct got_error *error = NULL;
6258 struct got_repository *repo = NULL;
6259 struct got_worktree *worktree = NULL;
6260 struct got_status_arg st;
6261 char *cwd = NULL;
6262 struct got_pathlist_head paths;
6263 struct got_pathlist_entry *pe;
6264 int ch, i, no_ignores = 0;
6265 int *pack_fds = NULL;
6267 TAILQ_INIT(&paths);
6269 memset(&st, 0, sizeof(st));
6270 st.status_codes = NULL;
6271 st.suppress = 0;
6273 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6274 switch (ch) {
6275 case 'I':
6276 no_ignores = 1;
6277 break;
6278 case 'S':
6279 if (st.status_codes != NULL && st.suppress == 0)
6280 option_conflict('S', 's');
6281 st.suppress = 1;
6282 /* fallthrough */
6283 case 's':
6284 for (i = 0; i < strlen(optarg); i++) {
6285 switch (optarg[i]) {
6286 case GOT_STATUS_MODIFY:
6287 case GOT_STATUS_ADD:
6288 case GOT_STATUS_DELETE:
6289 case GOT_STATUS_CONFLICT:
6290 case GOT_STATUS_MISSING:
6291 case GOT_STATUS_OBSTRUCTED:
6292 case GOT_STATUS_UNVERSIONED:
6293 case GOT_STATUS_MODE_CHANGE:
6294 case GOT_STATUS_NONEXISTENT:
6295 break;
6296 default:
6297 errx(1, "invalid status code '%c'",
6298 optarg[i]);
6301 if (ch == 's' && st.suppress)
6302 option_conflict('s', 'S');
6303 st.status_codes = optarg;
6304 break;
6305 default:
6306 usage_status();
6307 /* NOTREACHED */
6311 argc -= optind;
6312 argv += optind;
6314 #ifndef PROFILE
6315 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6316 NULL) == -1)
6317 err(1, "pledge");
6318 #endif
6319 cwd = getcwd(NULL, 0);
6320 if (cwd == NULL) {
6321 error = got_error_from_errno("getcwd");
6322 goto done;
6325 error = got_repo_pack_fds_open(&pack_fds);
6326 if (error != NULL)
6327 goto done;
6329 error = got_worktree_open(&worktree, cwd);
6330 if (error) {
6331 if (error->code == GOT_ERR_NOT_WORKTREE)
6332 error = wrap_not_worktree_error(error, "status", cwd);
6333 goto done;
6336 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6337 NULL, pack_fds);
6338 if (error != NULL)
6339 goto done;
6341 error = apply_unveil(got_repo_get_path(repo), 1,
6342 got_worktree_get_root_path(worktree));
6343 if (error)
6344 goto done;
6346 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6347 if (error)
6348 goto done;
6350 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6351 print_status, &st, check_cancelled, NULL);
6352 done:
6353 if (pack_fds) {
6354 const struct got_error *pack_err =
6355 got_repo_pack_fds_close(pack_fds);
6356 if (error == NULL)
6357 error = pack_err;
6360 TAILQ_FOREACH(pe, &paths, entry)
6361 free((char *)pe->path);
6362 got_pathlist_free(&paths);
6363 free(cwd);
6364 return error;
6367 __dead static void
6368 usage_ref(void)
6370 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6371 "[-s reference] [name]\n", getprogname());
6372 exit(1);
6375 static const struct got_error *
6376 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6378 static const struct got_error *err = NULL;
6379 struct got_reflist_head refs;
6380 struct got_reflist_entry *re;
6382 TAILQ_INIT(&refs);
6383 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6384 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6385 repo);
6386 if (err)
6387 return err;
6389 TAILQ_FOREACH(re, &refs, entry) {
6390 char *refstr;
6391 refstr = got_ref_to_str(re->ref);
6392 if (refstr == NULL) {
6393 err = got_error_from_errno("got_ref_to_str");
6394 break;
6396 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6397 free(refstr);
6400 got_ref_list_free(&refs);
6401 return err;
6404 static const struct got_error *
6405 delete_ref_by_name(struct got_repository *repo, const char *refname)
6407 const struct got_error *err;
6408 struct got_reference *ref;
6410 err = got_ref_open(&ref, repo, refname, 0);
6411 if (err)
6412 return err;
6414 err = delete_ref(repo, ref);
6415 got_ref_close(ref);
6416 return err;
6419 static const struct got_error *
6420 add_ref(struct got_repository *repo, const char *refname, const char *target)
6422 const struct got_error *err = NULL;
6423 struct got_object_id *id = NULL;
6424 struct got_reference *ref = NULL;
6425 struct got_reflist_head refs;
6428 * Don't let the user create a reference name with a leading '-'.
6429 * While technically a valid reference name, this case is usually
6430 * an unintended typo.
6432 if (refname[0] == '-')
6433 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6435 TAILQ_INIT(&refs);
6436 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6437 if (err)
6438 goto done;
6439 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6440 &refs, repo);
6441 got_ref_list_free(&refs);
6442 if (err)
6443 goto done;
6445 err = got_ref_alloc(&ref, refname, id);
6446 if (err)
6447 goto done;
6449 err = got_ref_write(ref, repo);
6450 done:
6451 if (ref)
6452 got_ref_close(ref);
6453 free(id);
6454 return err;
6457 static const struct got_error *
6458 add_symref(struct got_repository *repo, const char *refname, const char *target)
6460 const struct got_error *err = NULL;
6461 struct got_reference *ref = NULL;
6462 struct got_reference *target_ref = NULL;
6465 * Don't let the user create a reference name with a leading '-'.
6466 * While technically a valid reference name, this case is usually
6467 * an unintended typo.
6469 if (refname[0] == '-')
6470 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6472 err = got_ref_open(&target_ref, repo, target, 0);
6473 if (err)
6474 return err;
6476 err = got_ref_alloc_symref(&ref, refname, target_ref);
6477 if (err)
6478 goto done;
6480 err = got_ref_write(ref, repo);
6481 done:
6482 if (target_ref)
6483 got_ref_close(target_ref);
6484 if (ref)
6485 got_ref_close(ref);
6486 return err;
6489 static const struct got_error *
6490 cmd_ref(int argc, char *argv[])
6492 const struct got_error *error = NULL;
6493 struct got_repository *repo = NULL;
6494 struct got_worktree *worktree = NULL;
6495 char *cwd = NULL, *repo_path = NULL;
6496 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6497 const char *obj_arg = NULL, *symref_target= NULL;
6498 char *refname = NULL;
6499 int *pack_fds = NULL;
6501 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6502 switch (ch) {
6503 case 'c':
6504 obj_arg = optarg;
6505 break;
6506 case 'd':
6507 do_delete = 1;
6508 break;
6509 case 'l':
6510 do_list = 1;
6511 break;
6512 case 'r':
6513 repo_path = realpath(optarg, NULL);
6514 if (repo_path == NULL)
6515 return got_error_from_errno2("realpath",
6516 optarg);
6517 got_path_strip_trailing_slashes(repo_path);
6518 break;
6519 case 's':
6520 symref_target = optarg;
6521 break;
6522 case 't':
6523 sort_by_time = 1;
6524 break;
6525 default:
6526 usage_ref();
6527 /* NOTREACHED */
6531 if (obj_arg && do_list)
6532 option_conflict('c', 'l');
6533 if (obj_arg && do_delete)
6534 option_conflict('c', 'd');
6535 if (obj_arg && symref_target)
6536 option_conflict('c', 's');
6537 if (symref_target && do_delete)
6538 option_conflict('s', 'd');
6539 if (symref_target && do_list)
6540 option_conflict('s', 'l');
6541 if (do_delete && do_list)
6542 option_conflict('d', 'l');
6543 if (sort_by_time && !do_list)
6544 errx(1, "-t option requires -l option");
6546 argc -= optind;
6547 argv += optind;
6549 if (do_list) {
6550 if (argc != 0 && argc != 1)
6551 usage_ref();
6552 if (argc == 1) {
6553 refname = strdup(argv[0]);
6554 if (refname == NULL) {
6555 error = got_error_from_errno("strdup");
6556 goto done;
6559 } else {
6560 if (argc != 1)
6561 usage_ref();
6562 refname = strdup(argv[0]);
6563 if (refname == NULL) {
6564 error = got_error_from_errno("strdup");
6565 goto done;
6569 if (refname)
6570 got_path_strip_trailing_slashes(refname);
6572 #ifndef PROFILE
6573 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6574 "sendfd unveil", NULL) == -1)
6575 err(1, "pledge");
6576 #endif
6577 cwd = getcwd(NULL, 0);
6578 if (cwd == NULL) {
6579 error = got_error_from_errno("getcwd");
6580 goto done;
6583 error = got_repo_pack_fds_open(&pack_fds);
6584 if (error != NULL)
6585 goto done;
6587 if (repo_path == NULL) {
6588 error = got_worktree_open(&worktree, cwd);
6589 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6590 goto done;
6591 else
6592 error = NULL;
6593 if (worktree) {
6594 repo_path =
6595 strdup(got_worktree_get_repo_path(worktree));
6596 if (repo_path == NULL)
6597 error = got_error_from_errno("strdup");
6598 if (error)
6599 goto done;
6600 } else {
6601 repo_path = strdup(cwd);
6602 if (repo_path == NULL) {
6603 error = got_error_from_errno("strdup");
6604 goto done;
6609 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6610 if (error != NULL)
6611 goto done;
6613 #ifndef PROFILE
6614 if (do_list) {
6615 /* Remove "cpath" promise. */
6616 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6617 NULL) == -1)
6618 err(1, "pledge");
6620 #endif
6622 error = apply_unveil(got_repo_get_path(repo), do_list,
6623 worktree ? got_worktree_get_root_path(worktree) : NULL);
6624 if (error)
6625 goto done;
6627 if (do_list)
6628 error = list_refs(repo, refname, sort_by_time);
6629 else if (do_delete)
6630 error = delete_ref_by_name(repo, refname);
6631 else if (symref_target)
6632 error = add_symref(repo, refname, symref_target);
6633 else {
6634 if (obj_arg == NULL)
6635 usage_ref();
6636 error = add_ref(repo, refname, obj_arg);
6638 done:
6639 free(refname);
6640 if (repo) {
6641 const struct got_error *close_err = got_repo_close(repo);
6642 if (error == NULL)
6643 error = close_err;
6645 if (worktree)
6646 got_worktree_close(worktree);
6647 if (pack_fds) {
6648 const struct got_error *pack_err =
6649 got_repo_pack_fds_close(pack_fds);
6650 if (error == NULL)
6651 error = pack_err;
6653 free(cwd);
6654 free(repo_path);
6655 return error;
6658 __dead static void
6659 usage_branch(void)
6661 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6662 "[-r repository-path] [name]\n", getprogname());
6663 exit(1);
6666 static const struct got_error *
6667 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6668 struct got_reference *ref)
6670 const struct got_error *err = NULL;
6671 const char *refname, *marker = " ";
6672 char *refstr;
6674 refname = got_ref_get_name(ref);
6675 if (worktree && strcmp(refname,
6676 got_worktree_get_head_ref_name(worktree)) == 0) {
6677 struct got_object_id *id = NULL;
6679 err = got_ref_resolve(&id, repo, ref);
6680 if (err)
6681 return err;
6682 if (got_object_id_cmp(id,
6683 got_worktree_get_base_commit_id(worktree)) == 0)
6684 marker = "* ";
6685 else
6686 marker = "~ ";
6687 free(id);
6690 if (strncmp(refname, "refs/heads/", 11) == 0)
6691 refname += 11;
6692 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6693 refname += 18;
6694 if (strncmp(refname, "refs/remotes/", 13) == 0)
6695 refname += 13;
6697 refstr = got_ref_to_str(ref);
6698 if (refstr == NULL)
6699 return got_error_from_errno("got_ref_to_str");
6701 printf("%s%s: %s\n", marker, refname, refstr);
6702 free(refstr);
6703 return NULL;
6706 static const struct got_error *
6707 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6709 const char *refname;
6711 if (worktree == NULL)
6712 return got_error(GOT_ERR_NOT_WORKTREE);
6714 refname = got_worktree_get_head_ref_name(worktree);
6716 if (strncmp(refname, "refs/heads/", 11) == 0)
6717 refname += 11;
6718 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6719 refname += 18;
6721 printf("%s\n", refname);
6723 return NULL;
6726 static const struct got_error *
6727 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6728 int sort_by_time)
6730 static const struct got_error *err = NULL;
6731 struct got_reflist_head refs;
6732 struct got_reflist_entry *re;
6733 struct got_reference *temp_ref = NULL;
6734 int rebase_in_progress, histedit_in_progress;
6736 TAILQ_INIT(&refs);
6738 if (worktree) {
6739 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6740 worktree);
6741 if (err)
6742 return err;
6744 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6745 worktree);
6746 if (err)
6747 return err;
6749 if (rebase_in_progress || histedit_in_progress) {
6750 err = got_ref_open(&temp_ref, repo,
6751 got_worktree_get_head_ref_name(worktree), 0);
6752 if (err)
6753 return err;
6754 list_branch(repo, worktree, temp_ref);
6755 got_ref_close(temp_ref);
6759 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6760 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6761 repo);
6762 if (err)
6763 return err;
6765 TAILQ_FOREACH(re, &refs, entry)
6766 list_branch(repo, worktree, re->ref);
6768 got_ref_list_free(&refs);
6770 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6771 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6772 repo);
6773 if (err)
6774 return err;
6776 TAILQ_FOREACH(re, &refs, entry)
6777 list_branch(repo, worktree, re->ref);
6779 got_ref_list_free(&refs);
6781 return NULL;
6784 static const struct got_error *
6785 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6786 const char *branch_name)
6788 const struct got_error *err = NULL;
6789 struct got_reference *ref = NULL;
6790 char *refname, *remote_refname = NULL;
6792 if (strncmp(branch_name, "refs/", 5) == 0)
6793 branch_name += 5;
6794 if (strncmp(branch_name, "heads/", 6) == 0)
6795 branch_name += 6;
6796 else if (strncmp(branch_name, "remotes/", 8) == 0)
6797 branch_name += 8;
6799 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6800 return got_error_from_errno("asprintf");
6802 if (asprintf(&remote_refname, "refs/remotes/%s",
6803 branch_name) == -1) {
6804 err = got_error_from_errno("asprintf");
6805 goto done;
6808 err = got_ref_open(&ref, repo, refname, 0);
6809 if (err) {
6810 const struct got_error *err2;
6811 if (err->code != GOT_ERR_NOT_REF)
6812 goto done;
6814 * Keep 'err' intact such that if neither branch exists
6815 * we report "refs/heads" rather than "refs/remotes" in
6816 * our error message.
6818 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6819 if (err2)
6820 goto done;
6821 err = NULL;
6824 if (worktree &&
6825 strcmp(got_worktree_get_head_ref_name(worktree),
6826 got_ref_get_name(ref)) == 0) {
6827 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6828 "will not delete this work tree's current branch");
6829 goto done;
6832 err = delete_ref(repo, ref);
6833 done:
6834 if (ref)
6835 got_ref_close(ref);
6836 free(refname);
6837 free(remote_refname);
6838 return err;
6841 static const struct got_error *
6842 add_branch(struct got_repository *repo, const char *branch_name,
6843 struct got_object_id *base_commit_id)
6845 const struct got_error *err = NULL;
6846 struct got_reference *ref = NULL;
6847 char *base_refname = NULL, *refname = NULL;
6850 * Don't let the user create a branch name with a leading '-'.
6851 * While technically a valid reference name, this case is usually
6852 * an unintended typo.
6854 if (branch_name[0] == '-')
6855 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6857 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6858 branch_name += 11;
6860 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6861 err = got_error_from_errno("asprintf");
6862 goto done;
6865 err = got_ref_open(&ref, repo, refname, 0);
6866 if (err == NULL) {
6867 err = got_error(GOT_ERR_BRANCH_EXISTS);
6868 goto done;
6869 } else if (err->code != GOT_ERR_NOT_REF)
6870 goto done;
6872 err = got_ref_alloc(&ref, refname, base_commit_id);
6873 if (err)
6874 goto done;
6876 err = got_ref_write(ref, repo);
6877 done:
6878 if (ref)
6879 got_ref_close(ref);
6880 free(base_refname);
6881 free(refname);
6882 return err;
6885 static const struct got_error *
6886 cmd_branch(int argc, char *argv[])
6888 const struct got_error *error = NULL;
6889 struct got_repository *repo = NULL;
6890 struct got_worktree *worktree = NULL;
6891 char *cwd = NULL, *repo_path = NULL;
6892 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6893 const char *delref = NULL, *commit_id_arg = NULL;
6894 struct got_reference *ref = NULL;
6895 struct got_pathlist_head paths;
6896 struct got_pathlist_entry *pe;
6897 struct got_object_id *commit_id = NULL;
6898 char *commit_id_str = NULL;
6899 int *pack_fds = NULL;
6901 TAILQ_INIT(&paths);
6903 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6904 switch (ch) {
6905 case 'c':
6906 commit_id_arg = optarg;
6907 break;
6908 case 'd':
6909 delref = optarg;
6910 break;
6911 case 'l':
6912 do_list = 1;
6913 break;
6914 case 'n':
6915 do_update = 0;
6916 break;
6917 case 'r':
6918 repo_path = realpath(optarg, NULL);
6919 if (repo_path == NULL)
6920 return got_error_from_errno2("realpath",
6921 optarg);
6922 got_path_strip_trailing_slashes(repo_path);
6923 break;
6924 case 't':
6925 sort_by_time = 1;
6926 break;
6927 default:
6928 usage_branch();
6929 /* NOTREACHED */
6933 if (do_list && delref)
6934 option_conflict('l', 'd');
6935 if (sort_by_time && !do_list)
6936 errx(1, "-t option requires -l option");
6938 argc -= optind;
6939 argv += optind;
6941 if (!do_list && !delref && argc == 0)
6942 do_show = 1;
6944 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6945 errx(1, "-c option can only be used when creating a branch");
6947 if (do_list || delref) {
6948 if (argc > 0)
6949 usage_branch();
6950 } else if (!do_show && argc != 1)
6951 usage_branch();
6953 #ifndef PROFILE
6954 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6955 "sendfd unveil", NULL) == -1)
6956 err(1, "pledge");
6957 #endif
6958 cwd = getcwd(NULL, 0);
6959 if (cwd == NULL) {
6960 error = got_error_from_errno("getcwd");
6961 goto done;
6964 error = got_repo_pack_fds_open(&pack_fds);
6965 if (error != NULL)
6966 goto done;
6968 if (repo_path == NULL) {
6969 error = got_worktree_open(&worktree, cwd);
6970 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6971 goto done;
6972 else
6973 error = NULL;
6974 if (worktree) {
6975 repo_path =
6976 strdup(got_worktree_get_repo_path(worktree));
6977 if (repo_path == NULL)
6978 error = got_error_from_errno("strdup");
6979 if (error)
6980 goto done;
6981 } else {
6982 repo_path = strdup(cwd);
6983 if (repo_path == NULL) {
6984 error = got_error_from_errno("strdup");
6985 goto done;
6990 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6991 if (error != NULL)
6992 goto done;
6994 #ifndef PROFILE
6995 if (do_list || do_show) {
6996 /* Remove "cpath" promise. */
6997 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6998 NULL) == -1)
6999 err(1, "pledge");
7001 #endif
7003 error = apply_unveil(got_repo_get_path(repo), do_list,
7004 worktree ? got_worktree_get_root_path(worktree) : NULL);
7005 if (error)
7006 goto done;
7008 if (do_show)
7009 error = show_current_branch(repo, worktree);
7010 else if (do_list)
7011 error = list_branches(repo, worktree, sort_by_time);
7012 else if (delref)
7013 error = delete_branch(repo, worktree, delref);
7014 else {
7015 struct got_reflist_head refs;
7016 TAILQ_INIT(&refs);
7017 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7018 NULL);
7019 if (error)
7020 goto done;
7021 if (commit_id_arg == NULL)
7022 commit_id_arg = worktree ?
7023 got_worktree_get_head_ref_name(worktree) :
7024 GOT_REF_HEAD;
7025 error = got_repo_match_object_id(&commit_id, NULL,
7026 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7027 got_ref_list_free(&refs);
7028 if (error)
7029 goto done;
7030 error = add_branch(repo, argv[0], commit_id);
7031 if (error)
7032 goto done;
7033 if (worktree && do_update) {
7034 struct got_update_progress_arg upa;
7035 char *branch_refname = NULL;
7037 error = got_object_id_str(&commit_id_str, commit_id);
7038 if (error)
7039 goto done;
7040 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7041 worktree);
7042 if (error)
7043 goto done;
7044 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7045 == -1) {
7046 error = got_error_from_errno("asprintf");
7047 goto done;
7049 error = got_ref_open(&ref, repo, branch_refname, 0);
7050 free(branch_refname);
7051 if (error)
7052 goto done;
7053 error = switch_head_ref(ref, commit_id, worktree,
7054 repo);
7055 if (error)
7056 goto done;
7057 error = got_worktree_set_base_commit_id(worktree, repo,
7058 commit_id);
7059 if (error)
7060 goto done;
7061 memset(&upa, 0, sizeof(upa));
7062 error = got_worktree_checkout_files(worktree, &paths,
7063 repo, update_progress, &upa, check_cancelled,
7064 NULL);
7065 if (error)
7066 goto done;
7067 if (upa.did_something) {
7068 printf("Updated to %s: %s\n",
7069 got_worktree_get_head_ref_name(worktree),
7070 commit_id_str);
7072 print_update_progress_stats(&upa);
7075 done:
7076 if (ref)
7077 got_ref_close(ref);
7078 if (repo) {
7079 const struct got_error *close_err = got_repo_close(repo);
7080 if (error == NULL)
7081 error = close_err;
7083 if (worktree)
7084 got_worktree_close(worktree);
7085 if (pack_fds) {
7086 const struct got_error *pack_err =
7087 got_repo_pack_fds_close(pack_fds);
7088 if (error == NULL)
7089 error = pack_err;
7091 free(cwd);
7092 free(repo_path);
7093 free(commit_id);
7094 free(commit_id_str);
7095 TAILQ_FOREACH(pe, &paths, entry)
7096 free((char *)pe->path);
7097 got_pathlist_free(&paths);
7098 return error;
7102 __dead static void
7103 usage_tag(void)
7105 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7106 "[-r repository-path] [-s signer-id] name\n", getprogname());
7107 exit(1);
7110 #if 0
7111 static const struct got_error *
7112 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7114 const struct got_error *err = NULL;
7115 struct got_reflist_entry *re, *se, *new;
7116 struct got_object_id *re_id, *se_id;
7117 struct got_tag_object *re_tag, *se_tag;
7118 time_t re_time, se_time;
7120 STAILQ_FOREACH(re, tags, entry) {
7121 se = STAILQ_FIRST(sorted);
7122 if (se == NULL) {
7123 err = got_reflist_entry_dup(&new, re);
7124 if (err)
7125 return err;
7126 STAILQ_INSERT_HEAD(sorted, new, entry);
7127 continue;
7128 } else {
7129 err = got_ref_resolve(&re_id, repo, re->ref);
7130 if (err)
7131 break;
7132 err = got_object_open_as_tag(&re_tag, repo, re_id);
7133 free(re_id);
7134 if (err)
7135 break;
7136 re_time = got_object_tag_get_tagger_time(re_tag);
7137 got_object_tag_close(re_tag);
7140 while (se) {
7141 err = got_ref_resolve(&se_id, repo, re->ref);
7142 if (err)
7143 break;
7144 err = got_object_open_as_tag(&se_tag, repo, se_id);
7145 free(se_id);
7146 if (err)
7147 break;
7148 se_time = got_object_tag_get_tagger_time(se_tag);
7149 got_object_tag_close(se_tag);
7151 if (se_time > re_time) {
7152 err = got_reflist_entry_dup(&new, re);
7153 if (err)
7154 return err;
7155 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7156 break;
7158 se = STAILQ_NEXT(se, entry);
7159 continue;
7162 done:
7163 return err;
7165 #endif
7167 static const struct got_error *
7168 get_tag_refname(char **refname, const char *tag_name)
7170 const struct got_error *err;
7172 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7173 *refname = strdup(tag_name);
7174 if (*refname == NULL)
7175 return got_error_from_errno("strdup");
7176 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7177 err = got_error_from_errno("asprintf");
7178 *refname = NULL;
7179 return err;
7182 return NULL;
7185 static const struct got_error *
7186 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7187 const char *allowed_signers, const char *revoked_signers, int verbosity)
7189 static const struct got_error *err = NULL;
7190 struct got_reflist_head refs;
7191 struct got_reflist_entry *re;
7192 char *wanted_refname = NULL;
7193 int bad_sigs = 0;
7195 TAILQ_INIT(&refs);
7197 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7198 if (err)
7199 return err;
7201 if (tag_name) {
7202 struct got_reference *ref;
7203 err = get_tag_refname(&wanted_refname, tag_name);
7204 if (err)
7205 goto done;
7206 /* Wanted tag reference should exist. */
7207 err = got_ref_open(&ref, repo, wanted_refname, 0);
7208 if (err)
7209 goto done;
7210 got_ref_close(ref);
7213 TAILQ_FOREACH(re, &refs, entry) {
7214 const char *refname;
7215 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7216 char datebuf[26];
7217 const char *tagger, *ssh_sig = NULL;
7218 char *sig_msg = NULL;
7219 time_t tagger_time;
7220 struct got_object_id *id;
7221 struct got_tag_object *tag;
7222 struct got_commit_object *commit = NULL;
7224 refname = got_ref_get_name(re->ref);
7225 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7226 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7227 continue;
7228 refname += 10;
7229 refstr = got_ref_to_str(re->ref);
7230 if (refstr == NULL) {
7231 err = got_error_from_errno("got_ref_to_str");
7232 break;
7235 err = got_ref_resolve(&id, repo, re->ref);
7236 if (err)
7237 break;
7238 err = got_object_open_as_tag(&tag, repo, id);
7239 if (err) {
7240 if (err->code != GOT_ERR_OBJ_TYPE) {
7241 free(id);
7242 break;
7244 /* "lightweight" tag */
7245 err = got_object_open_as_commit(&commit, repo, id);
7246 if (err) {
7247 free(id);
7248 break;
7250 tagger = got_object_commit_get_committer(commit);
7251 tagger_time =
7252 got_object_commit_get_committer_time(commit);
7253 err = got_object_id_str(&id_str, id);
7254 free(id);
7255 if (err)
7256 break;
7257 } else {
7258 free(id);
7259 tagger = got_object_tag_get_tagger(tag);
7260 tagger_time = got_object_tag_get_tagger_time(tag);
7261 err = got_object_id_str(&id_str,
7262 got_object_tag_get_object_id(tag));
7263 if (err)
7264 break;
7267 if (tag && verify_tags) {
7268 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7269 got_object_tag_get_message(tag));
7270 if (ssh_sig && allowed_signers == NULL) {
7271 err = got_error_msg(
7272 GOT_ERR_VERIFY_TAG_SIGNATURE,
7273 "SSH signature verification requires "
7274 "setting allowed_signers in "
7275 "got.conf(5)");
7276 break;
7280 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7281 free(refstr);
7282 printf("from: %s\n", tagger);
7283 datestr = get_datestr(&tagger_time, datebuf);
7284 if (datestr)
7285 printf("date: %s UTC\n", datestr);
7286 if (commit)
7287 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7288 else {
7289 switch (got_object_tag_get_object_type(tag)) {
7290 case GOT_OBJ_TYPE_BLOB:
7291 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7292 id_str);
7293 break;
7294 case GOT_OBJ_TYPE_TREE:
7295 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7296 id_str);
7297 break;
7298 case GOT_OBJ_TYPE_COMMIT:
7299 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7300 id_str);
7301 break;
7302 case GOT_OBJ_TYPE_TAG:
7303 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7304 id_str);
7305 break;
7306 default:
7307 break;
7310 free(id_str);
7312 if (ssh_sig) {
7313 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7314 allowed_signers, revoked_signers, verbosity);
7315 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7316 bad_sigs = 1;
7317 else if (err)
7318 break;
7319 printf("signature: %s", sig_msg);
7320 free(sig_msg);
7321 sig_msg = NULL;
7324 if (commit) {
7325 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7326 if (err)
7327 break;
7328 got_object_commit_close(commit);
7329 } else {
7330 tagmsg0 = strdup(got_object_tag_get_message(tag));
7331 got_object_tag_close(tag);
7332 if (tagmsg0 == NULL) {
7333 err = got_error_from_errno("strdup");
7334 break;
7338 tagmsg = tagmsg0;
7339 do {
7340 line = strsep(&tagmsg, "\n");
7341 if (line)
7342 printf(" %s\n", line);
7343 } while (line);
7344 free(tagmsg0);
7346 done:
7347 got_ref_list_free(&refs);
7348 free(wanted_refname);
7350 if (err == NULL && bad_sigs)
7351 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7352 return err;
7355 static const struct got_error *
7356 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7357 const char *tag_name, const char *repo_path)
7359 const struct got_error *err = NULL;
7360 char *template = NULL, *initial_content = NULL;
7361 char *editor = NULL;
7362 int initial_content_len;
7363 int fd = -1;
7365 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7366 err = got_error_from_errno("asprintf");
7367 goto done;
7370 initial_content_len = asprintf(&initial_content,
7371 "\n# tagging commit %s as %s\n",
7372 commit_id_str, tag_name);
7373 if (initial_content_len == -1) {
7374 err = got_error_from_errno("asprintf");
7375 goto done;
7378 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7379 if (err)
7380 goto done;
7382 if (write(fd, initial_content, initial_content_len) == -1) {
7383 err = got_error_from_errno2("write", *tagmsg_path);
7384 goto done;
7387 err = get_editor(&editor);
7388 if (err)
7389 goto done;
7390 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7391 initial_content_len, 1);
7392 done:
7393 free(initial_content);
7394 free(template);
7395 free(editor);
7397 if (fd != -1 && close(fd) == -1 && err == NULL)
7398 err = got_error_from_errno2("close", *tagmsg_path);
7400 if (err) {
7401 free(*tagmsg);
7402 *tagmsg = NULL;
7404 return err;
7407 static const struct got_error *
7408 add_tag(struct got_repository *repo, const char *tagger,
7409 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7410 const char *signer_id, int verbosity)
7412 const struct got_error *err = NULL;
7413 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7414 char *label = NULL, *commit_id_str = NULL;
7415 struct got_reference *ref = NULL;
7416 char *refname = NULL, *tagmsg = NULL;
7417 char *tagmsg_path = NULL, *tag_id_str = NULL;
7418 int preserve_tagmsg = 0;
7419 struct got_reflist_head refs;
7421 TAILQ_INIT(&refs);
7424 * Don't let the user create a tag name with a leading '-'.
7425 * While technically a valid reference name, this case is usually
7426 * an unintended typo.
7428 if (tag_name[0] == '-')
7429 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7431 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7432 if (err)
7433 goto done;
7435 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7436 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7437 if (err)
7438 goto done;
7440 err = got_object_id_str(&commit_id_str, commit_id);
7441 if (err)
7442 goto done;
7444 err = get_tag_refname(&refname, tag_name);
7445 if (err)
7446 goto done;
7447 if (strncmp("refs/tags/", tag_name, 10) == 0)
7448 tag_name += 10;
7450 err = got_ref_open(&ref, repo, refname, 0);
7451 if (err == NULL) {
7452 err = got_error(GOT_ERR_TAG_EXISTS);
7453 goto done;
7454 } else if (err->code != GOT_ERR_NOT_REF)
7455 goto done;
7457 if (tagmsg_arg == NULL) {
7458 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7459 tag_name, got_repo_get_path(repo));
7460 if (err) {
7461 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7462 tagmsg_path != NULL)
7463 preserve_tagmsg = 1;
7464 goto done;
7466 /* Editor is done; we can now apply unveil(2) */
7467 err = got_sigs_apply_unveil();
7468 if (err)
7469 goto done;
7470 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7471 if (err)
7472 goto done;
7475 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7476 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7477 verbosity);
7478 if (err) {
7479 if (tagmsg_path)
7480 preserve_tagmsg = 1;
7481 goto done;
7484 err = got_ref_alloc(&ref, refname, tag_id);
7485 if (err) {
7486 if (tagmsg_path)
7487 preserve_tagmsg = 1;
7488 goto done;
7491 err = got_ref_write(ref, repo);
7492 if (err) {
7493 if (tagmsg_path)
7494 preserve_tagmsg = 1;
7495 goto done;
7498 err = got_object_id_str(&tag_id_str, tag_id);
7499 if (err) {
7500 if (tagmsg_path)
7501 preserve_tagmsg = 1;
7502 goto done;
7504 printf("Created tag %s\n", tag_id_str);
7505 done:
7506 if (preserve_tagmsg) {
7507 fprintf(stderr, "%s: tag message preserved in %s\n",
7508 getprogname(), tagmsg_path);
7509 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7510 err = got_error_from_errno2("unlink", tagmsg_path);
7511 free(tag_id_str);
7512 if (ref)
7513 got_ref_close(ref);
7514 free(commit_id);
7515 free(commit_id_str);
7516 free(refname);
7517 free(tagmsg);
7518 free(tagmsg_path);
7519 got_ref_list_free(&refs);
7520 return err;
7523 static const struct got_error *
7524 cmd_tag(int argc, char *argv[])
7526 const struct got_error *error = NULL;
7527 struct got_repository *repo = NULL;
7528 struct got_worktree *worktree = NULL;
7529 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7530 char *gitconfig_path = NULL, *tagger = NULL;
7531 char *allowed_signers = NULL, *revoked_signers = NULL;
7532 char *signer_id = NULL;
7533 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7534 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7535 int *pack_fds = NULL;
7537 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7538 switch (ch) {
7539 case 'c':
7540 commit_id_arg = optarg;
7541 break;
7542 case 'l':
7543 do_list = 1;
7544 break;
7545 case 'm':
7546 tagmsg = optarg;
7547 break;
7548 case 'r':
7549 repo_path = realpath(optarg, NULL);
7550 if (repo_path == NULL) {
7551 error = got_error_from_errno2("realpath",
7552 optarg);
7553 goto done;
7555 got_path_strip_trailing_slashes(repo_path);
7556 break;
7557 case 's':
7558 signer_id = strdup(optarg);
7559 if (signer_id == NULL) {
7560 error = got_error_from_errno("strdup");
7561 goto done;
7563 break;
7564 case 'V':
7565 verify_tags = 1;
7566 break;
7567 case 'v':
7568 if (verbosity < 0)
7569 verbosity = 0;
7570 else if (verbosity < 3)
7571 verbosity++;
7572 break;
7573 default:
7574 usage_tag();
7575 /* NOTREACHED */
7579 argc -= optind;
7580 argv += optind;
7582 if (do_list || verify_tags) {
7583 if (commit_id_arg != NULL)
7584 errx(1,
7585 "-c option can only be used when creating a tag");
7586 if (tagmsg) {
7587 if (do_list)
7588 option_conflict('l', 'm');
7589 else
7590 option_conflict('V', 'm');
7592 if (signer_id) {
7593 if (do_list)
7594 option_conflict('l', 's');
7595 else
7596 option_conflict('V', 's');
7598 if (argc > 1)
7599 usage_tag();
7600 } else if (argc != 1)
7601 usage_tag();
7603 if (argc == 1)
7604 tag_name = argv[0];
7606 #ifndef PROFILE
7607 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7608 "sendfd unveil", NULL) == -1)
7609 err(1, "pledge");
7610 #endif
7611 cwd = getcwd(NULL, 0);
7612 if (cwd == NULL) {
7613 error = got_error_from_errno("getcwd");
7614 goto done;
7617 error = got_repo_pack_fds_open(&pack_fds);
7618 if (error != NULL)
7619 goto done;
7621 if (repo_path == NULL) {
7622 error = got_worktree_open(&worktree, cwd);
7623 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7624 goto done;
7625 else
7626 error = NULL;
7627 if (worktree) {
7628 repo_path =
7629 strdup(got_worktree_get_repo_path(worktree));
7630 if (repo_path == NULL)
7631 error = got_error_from_errno("strdup");
7632 if (error)
7633 goto done;
7634 } else {
7635 repo_path = strdup(cwd);
7636 if (repo_path == NULL) {
7637 error = got_error_from_errno("strdup");
7638 goto done;
7643 if (do_list || verify_tags) {
7644 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7645 if (error != NULL)
7646 goto done;
7647 error = get_allowed_signers(&allowed_signers, repo, worktree);
7648 if (error)
7649 goto done;
7650 error = get_revoked_signers(&revoked_signers, repo, worktree);
7651 if (error)
7652 goto done;
7653 if (worktree) {
7654 /* Release work tree lock. */
7655 got_worktree_close(worktree);
7656 worktree = NULL;
7660 * Remove "cpath" promise unless needed for signature tmpfile
7661 * creation.
7663 if (verify_tags)
7664 got_sigs_apply_unveil();
7665 else {
7666 #ifndef PROFILE
7667 if (pledge("stdio rpath wpath flock proc exec sendfd "
7668 "unveil", NULL) == -1)
7669 err(1, "pledge");
7670 #endif
7672 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7673 if (error)
7674 goto done;
7675 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7676 revoked_signers, verbosity);
7677 } else {
7678 error = get_gitconfig_path(&gitconfig_path);
7679 if (error)
7680 goto done;
7681 error = got_repo_open(&repo, repo_path, gitconfig_path,
7682 pack_fds);
7683 if (error != NULL)
7684 goto done;
7686 error = get_author(&tagger, repo, worktree);
7687 if (error)
7688 goto done;
7689 if (signer_id == NULL) {
7690 error = get_signer_id(&signer_id, repo, worktree);
7691 if (error)
7692 goto done;
7695 if (tagmsg) {
7696 if (signer_id) {
7697 error = got_sigs_apply_unveil();
7698 if (error)
7699 goto done;
7701 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7702 if (error)
7703 goto done;
7706 if (commit_id_arg == NULL) {
7707 struct got_reference *head_ref;
7708 struct got_object_id *commit_id;
7709 error = got_ref_open(&head_ref, repo,
7710 worktree ? got_worktree_get_head_ref_name(worktree)
7711 : GOT_REF_HEAD, 0);
7712 if (error)
7713 goto done;
7714 error = got_ref_resolve(&commit_id, repo, head_ref);
7715 got_ref_close(head_ref);
7716 if (error)
7717 goto done;
7718 error = got_object_id_str(&commit_id_str, commit_id);
7719 free(commit_id);
7720 if (error)
7721 goto done;
7724 if (worktree) {
7725 /* Release work tree lock. */
7726 got_worktree_close(worktree);
7727 worktree = NULL;
7730 error = add_tag(repo, tagger, tag_name,
7731 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7732 signer_id, verbosity);
7734 done:
7735 if (repo) {
7736 const struct got_error *close_err = got_repo_close(repo);
7737 if (error == NULL)
7738 error = close_err;
7740 if (worktree)
7741 got_worktree_close(worktree);
7742 if (pack_fds) {
7743 const struct got_error *pack_err =
7744 got_repo_pack_fds_close(pack_fds);
7745 if (error == NULL)
7746 error = pack_err;
7748 free(cwd);
7749 free(repo_path);
7750 free(gitconfig_path);
7751 free(commit_id_str);
7752 free(tagger);
7753 free(allowed_signers);
7754 free(revoked_signers);
7755 free(signer_id);
7756 return error;
7759 __dead static void
7760 usage_add(void)
7762 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7763 exit(1);
7766 static const struct got_error *
7767 add_progress(void *arg, unsigned char status, const char *path)
7769 while (path[0] == '/')
7770 path++;
7771 printf("%c %s\n", status, path);
7772 return NULL;
7775 static const struct got_error *
7776 cmd_add(int argc, char *argv[])
7778 const struct got_error *error = NULL;
7779 struct got_repository *repo = NULL;
7780 struct got_worktree *worktree = NULL;
7781 char *cwd = NULL;
7782 struct got_pathlist_head paths;
7783 struct got_pathlist_entry *pe;
7784 int ch, can_recurse = 0, no_ignores = 0;
7785 int *pack_fds = NULL;
7787 TAILQ_INIT(&paths);
7789 while ((ch = getopt(argc, argv, "IR")) != -1) {
7790 switch (ch) {
7791 case 'I':
7792 no_ignores = 1;
7793 break;
7794 case 'R':
7795 can_recurse = 1;
7796 break;
7797 default:
7798 usage_add();
7799 /* NOTREACHED */
7803 argc -= optind;
7804 argv += optind;
7806 #ifndef PROFILE
7807 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7808 NULL) == -1)
7809 err(1, "pledge");
7810 #endif
7811 if (argc < 1)
7812 usage_add();
7814 cwd = getcwd(NULL, 0);
7815 if (cwd == NULL) {
7816 error = got_error_from_errno("getcwd");
7817 goto done;
7820 error = got_repo_pack_fds_open(&pack_fds);
7821 if (error != NULL)
7822 goto done;
7824 error = got_worktree_open(&worktree, cwd);
7825 if (error) {
7826 if (error->code == GOT_ERR_NOT_WORKTREE)
7827 error = wrap_not_worktree_error(error, "add", cwd);
7828 goto done;
7831 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7832 NULL, pack_fds);
7833 if (error != NULL)
7834 goto done;
7836 error = apply_unveil(got_repo_get_path(repo), 1,
7837 got_worktree_get_root_path(worktree));
7838 if (error)
7839 goto done;
7841 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7842 if (error)
7843 goto done;
7845 if (!can_recurse) {
7846 char *ondisk_path;
7847 struct stat sb;
7848 TAILQ_FOREACH(pe, &paths, entry) {
7849 if (asprintf(&ondisk_path, "%s/%s",
7850 got_worktree_get_root_path(worktree),
7851 pe->path) == -1) {
7852 error = got_error_from_errno("asprintf");
7853 goto done;
7855 if (lstat(ondisk_path, &sb) == -1) {
7856 if (errno == ENOENT) {
7857 free(ondisk_path);
7858 continue;
7860 error = got_error_from_errno2("lstat",
7861 ondisk_path);
7862 free(ondisk_path);
7863 goto done;
7865 free(ondisk_path);
7866 if (S_ISDIR(sb.st_mode)) {
7867 error = got_error_msg(GOT_ERR_BAD_PATH,
7868 "adding directories requires -R option");
7869 goto done;
7874 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7875 NULL, repo, no_ignores);
7876 done:
7877 if (repo) {
7878 const struct got_error *close_err = got_repo_close(repo);
7879 if (error == NULL)
7880 error = close_err;
7882 if (worktree)
7883 got_worktree_close(worktree);
7884 if (pack_fds) {
7885 const struct got_error *pack_err =
7886 got_repo_pack_fds_close(pack_fds);
7887 if (error == NULL)
7888 error = pack_err;
7890 TAILQ_FOREACH(pe, &paths, entry)
7891 free((char *)pe->path);
7892 got_pathlist_free(&paths);
7893 free(cwd);
7894 return error;
7897 __dead static void
7898 usage_remove(void)
7900 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7901 getprogname());
7902 exit(1);
7905 static const struct got_error *
7906 print_remove_status(void *arg, unsigned char status,
7907 unsigned char staged_status, const char *path)
7909 while (path[0] == '/')
7910 path++;
7911 if (status == GOT_STATUS_NONEXISTENT)
7912 return NULL;
7913 if (status == staged_status && (status == GOT_STATUS_DELETE))
7914 status = GOT_STATUS_NO_CHANGE;
7915 printf("%c%c %s\n", status, staged_status, path);
7916 return NULL;
7919 static const struct got_error *
7920 cmd_remove(int argc, char *argv[])
7922 const struct got_error *error = NULL;
7923 struct got_worktree *worktree = NULL;
7924 struct got_repository *repo = NULL;
7925 const char *status_codes = NULL;
7926 char *cwd = NULL;
7927 struct got_pathlist_head paths;
7928 struct got_pathlist_entry *pe;
7929 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7930 int ignore_missing_paths = 0;
7931 int *pack_fds = NULL;
7933 TAILQ_INIT(&paths);
7935 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7936 switch (ch) {
7937 case 'f':
7938 delete_local_mods = 1;
7939 ignore_missing_paths = 1;
7940 break;
7941 case 'k':
7942 keep_on_disk = 1;
7943 break;
7944 case 'R':
7945 can_recurse = 1;
7946 break;
7947 case 's':
7948 for (i = 0; i < strlen(optarg); i++) {
7949 switch (optarg[i]) {
7950 case GOT_STATUS_MODIFY:
7951 delete_local_mods = 1;
7952 break;
7953 case GOT_STATUS_MISSING:
7954 ignore_missing_paths = 1;
7955 break;
7956 default:
7957 errx(1, "invalid status code '%c'",
7958 optarg[i]);
7961 status_codes = optarg;
7962 break;
7963 default:
7964 usage_remove();
7965 /* NOTREACHED */
7969 argc -= optind;
7970 argv += optind;
7972 #ifndef PROFILE
7973 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7974 NULL) == -1)
7975 err(1, "pledge");
7976 #endif
7977 if (argc < 1)
7978 usage_remove();
7980 cwd = getcwd(NULL, 0);
7981 if (cwd == NULL) {
7982 error = got_error_from_errno("getcwd");
7983 goto done;
7986 error = got_repo_pack_fds_open(&pack_fds);
7987 if (error != NULL)
7988 goto done;
7990 error = got_worktree_open(&worktree, cwd);
7991 if (error) {
7992 if (error->code == GOT_ERR_NOT_WORKTREE)
7993 error = wrap_not_worktree_error(error, "remove", cwd);
7994 goto done;
7997 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7998 NULL, pack_fds);
7999 if (error)
8000 goto done;
8002 error = apply_unveil(got_repo_get_path(repo), 1,
8003 got_worktree_get_root_path(worktree));
8004 if (error)
8005 goto done;
8007 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8008 if (error)
8009 goto done;
8011 if (!can_recurse) {
8012 char *ondisk_path;
8013 struct stat sb;
8014 TAILQ_FOREACH(pe, &paths, entry) {
8015 if (asprintf(&ondisk_path, "%s/%s",
8016 got_worktree_get_root_path(worktree),
8017 pe->path) == -1) {
8018 error = got_error_from_errno("asprintf");
8019 goto done;
8021 if (lstat(ondisk_path, &sb) == -1) {
8022 if (errno == ENOENT) {
8023 free(ondisk_path);
8024 continue;
8026 error = got_error_from_errno2("lstat",
8027 ondisk_path);
8028 free(ondisk_path);
8029 goto done;
8031 free(ondisk_path);
8032 if (S_ISDIR(sb.st_mode)) {
8033 error = got_error_msg(GOT_ERR_BAD_PATH,
8034 "removing directories requires -R option");
8035 goto done;
8040 error = got_worktree_schedule_delete(worktree, &paths,
8041 delete_local_mods, status_codes, print_remove_status, NULL,
8042 repo, keep_on_disk, ignore_missing_paths);
8043 done:
8044 if (repo) {
8045 const struct got_error *close_err = got_repo_close(repo);
8046 if (error == NULL)
8047 error = close_err;
8049 if (worktree)
8050 got_worktree_close(worktree);
8051 if (pack_fds) {
8052 const struct got_error *pack_err =
8053 got_repo_pack_fds_close(pack_fds);
8054 if (error == NULL)
8055 error = pack_err;
8057 TAILQ_FOREACH(pe, &paths, entry)
8058 free((char *)pe->path);
8059 got_pathlist_free(&paths);
8060 free(cwd);
8061 return error;
8064 __dead static void
8065 usage_patch(void)
8067 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8068 "[patchfile]\n", getprogname());
8069 exit(1);
8072 static const struct got_error *
8073 patch_from_stdin(int *patchfd)
8075 const struct got_error *err = NULL;
8076 ssize_t r;
8077 char buf[BUFSIZ];
8078 sig_t sighup, sigint, sigquit;
8080 *patchfd = got_opentempfd();
8081 if (*patchfd == -1)
8082 return got_error_from_errno("got_opentempfd");
8084 sighup = signal(SIGHUP, SIG_DFL);
8085 sigint = signal(SIGINT, SIG_DFL);
8086 sigquit = signal(SIGQUIT, SIG_DFL);
8088 for (;;) {
8089 r = read(0, buf, sizeof(buf));
8090 if (r == -1) {
8091 err = got_error_from_errno("read");
8092 break;
8094 if (r == 0)
8095 break;
8096 if (write(*patchfd, buf, r) == -1) {
8097 err = got_error_from_errno("write");
8098 break;
8102 signal(SIGHUP, sighup);
8103 signal(SIGINT, sigint);
8104 signal(SIGQUIT, sigquit);
8106 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8107 err = got_error_from_errno("lseek");
8109 if (err != NULL) {
8110 close(*patchfd);
8111 *patchfd = -1;
8114 return err;
8117 static const struct got_error *
8118 patch_progress(void *arg, const char *old, const char *new,
8119 unsigned char status, const struct got_error *error, int old_from,
8120 int old_lines, int new_from, int new_lines, int offset,
8121 int ws_mangled, const struct got_error *hunk_err)
8123 const char *path = new == NULL ? old : new;
8125 while (*path == '/')
8126 path++;
8128 if (status != 0)
8129 printf("%c %s\n", status, path);
8131 if (error != NULL)
8132 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8134 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8135 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8136 old_lines, new_from, new_lines);
8137 if (hunk_err != NULL)
8138 printf("%s\n", hunk_err->msg);
8139 else if (offset != 0)
8140 printf("applied with offset %d\n", offset);
8141 else
8142 printf("hunk contains mangled whitespace\n");
8145 return NULL;
8148 static const struct got_error *
8149 cmd_patch(int argc, char *argv[])
8151 const struct got_error *error = NULL, *close_error = NULL;
8152 struct got_worktree *worktree = NULL;
8153 struct got_repository *repo = NULL;
8154 struct got_reflist_head refs;
8155 struct got_object_id *commit_id = NULL;
8156 const char *commit_id_str = NULL;
8157 struct stat sb;
8158 const char *errstr;
8159 char *cwd = NULL;
8160 int ch, nop = 0, strip = -1, reverse = 0;
8161 int patchfd;
8162 int *pack_fds = NULL;
8164 TAILQ_INIT(&refs);
8166 #ifndef PROFILE
8167 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8168 "unveil", NULL) == -1)
8169 err(1, "pledge");
8170 #endif
8172 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8173 switch (ch) {
8174 case 'c':
8175 commit_id_str = optarg;
8176 break;
8177 case 'n':
8178 nop = 1;
8179 break;
8180 case 'p':
8181 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8182 if (errstr != NULL)
8183 errx(1, "pathname strip count is %s: %s",
8184 errstr, optarg);
8185 break;
8186 case 'R':
8187 reverse = 1;
8188 break;
8189 default:
8190 usage_patch();
8191 /* NOTREACHED */
8195 argc -= optind;
8196 argv += optind;
8198 if (argc == 0) {
8199 error = patch_from_stdin(&patchfd);
8200 if (error)
8201 return error;
8202 } else if (argc == 1) {
8203 patchfd = open(argv[0], O_RDONLY);
8204 if (patchfd == -1) {
8205 error = got_error_from_errno2("open", argv[0]);
8206 return error;
8208 if (fstat(patchfd, &sb) == -1) {
8209 error = got_error_from_errno2("fstat", argv[0]);
8210 goto done;
8212 if (!S_ISREG(sb.st_mode)) {
8213 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8214 goto done;
8216 } else
8217 usage_patch();
8219 if ((cwd = getcwd(NULL, 0)) == NULL) {
8220 error = got_error_from_errno("getcwd");
8221 goto done;
8224 error = got_repo_pack_fds_open(&pack_fds);
8225 if (error != NULL)
8226 goto done;
8228 error = got_worktree_open(&worktree, cwd);
8229 if (error != NULL)
8230 goto done;
8232 const char *repo_path = got_worktree_get_repo_path(worktree);
8233 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8234 if (error != NULL)
8235 goto done;
8237 error = apply_unveil(got_repo_get_path(repo), 0,
8238 got_worktree_get_root_path(worktree));
8239 if (error != NULL)
8240 goto done;
8242 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8243 if (error)
8244 goto done;
8246 if (commit_id_str != NULL) {
8247 error = got_repo_match_object_id(&commit_id, NULL,
8248 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8249 if (error)
8250 goto done;
8253 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8254 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8256 done:
8257 got_ref_list_free(&refs);
8258 free(commit_id);
8259 if (repo) {
8260 close_error = got_repo_close(repo);
8261 if (error == NULL)
8262 error = close_error;
8264 if (worktree != NULL) {
8265 close_error = got_worktree_close(worktree);
8266 if (error == NULL)
8267 error = close_error;
8269 if (pack_fds) {
8270 const struct got_error *pack_err =
8271 got_repo_pack_fds_close(pack_fds);
8272 if (error == NULL)
8273 error = pack_err;
8275 free(cwd);
8276 return error;
8279 __dead static void
8280 usage_revert(void)
8282 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8283 getprogname());
8284 exit(1);
8287 static const struct got_error *
8288 revert_progress(void *arg, unsigned char status, const char *path)
8290 if (status == GOT_STATUS_UNVERSIONED)
8291 return NULL;
8293 while (path[0] == '/')
8294 path++;
8295 printf("%c %s\n", status, path);
8296 return NULL;
8299 struct choose_patch_arg {
8300 FILE *patch_script_file;
8301 const char *action;
8304 static const struct got_error *
8305 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8306 int nchanges, const char *action)
8308 const struct got_error *err;
8309 char *line = NULL;
8310 size_t linesize = 0;
8311 ssize_t linelen;
8313 switch (status) {
8314 case GOT_STATUS_ADD:
8315 printf("A %s\n%s this addition? [y/n] ", path, action);
8316 break;
8317 case GOT_STATUS_DELETE:
8318 printf("D %s\n%s this deletion? [y/n] ", path, action);
8319 break;
8320 case GOT_STATUS_MODIFY:
8321 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8322 return got_error_from_errno("fseek");
8323 printf(GOT_COMMIT_SEP_STR);
8324 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8325 printf("%s", line);
8326 if (linelen == -1 && ferror(patch_file)) {
8327 err = got_error_from_errno("getline");
8328 free(line);
8329 return err;
8331 free(line);
8332 printf(GOT_COMMIT_SEP_STR);
8333 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8334 path, n, nchanges, action);
8335 break;
8336 default:
8337 return got_error_path(path, GOT_ERR_FILE_STATUS);
8340 fflush(stdout);
8341 return NULL;
8344 static const struct got_error *
8345 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8346 FILE *patch_file, int n, int nchanges)
8348 const struct got_error *err = NULL;
8349 char *line = NULL;
8350 size_t linesize = 0;
8351 ssize_t linelen;
8352 int resp = ' ';
8353 struct choose_patch_arg *a = arg;
8355 *choice = GOT_PATCH_CHOICE_NONE;
8357 if (a->patch_script_file) {
8358 char *nl;
8359 err = show_change(status, path, patch_file, n, nchanges,
8360 a->action);
8361 if (err)
8362 return err;
8363 linelen = getline(&line, &linesize, a->patch_script_file);
8364 if (linelen == -1) {
8365 if (ferror(a->patch_script_file))
8366 return got_error_from_errno("getline");
8367 return NULL;
8369 nl = strchr(line, '\n');
8370 if (nl)
8371 *nl = '\0';
8372 if (strcmp(line, "y") == 0) {
8373 *choice = GOT_PATCH_CHOICE_YES;
8374 printf("y\n");
8375 } else if (strcmp(line, "n") == 0) {
8376 *choice = GOT_PATCH_CHOICE_NO;
8377 printf("n\n");
8378 } else if (strcmp(line, "q") == 0 &&
8379 status == GOT_STATUS_MODIFY) {
8380 *choice = GOT_PATCH_CHOICE_QUIT;
8381 printf("q\n");
8382 } else
8383 printf("invalid response '%s'\n", line);
8384 free(line);
8385 return NULL;
8388 while (resp != 'y' && resp != 'n' && resp != 'q') {
8389 err = show_change(status, path, patch_file, n, nchanges,
8390 a->action);
8391 if (err)
8392 return err;
8393 resp = getchar();
8394 if (resp == '\n')
8395 resp = getchar();
8396 if (status == GOT_STATUS_MODIFY) {
8397 if (resp != 'y' && resp != 'n' && resp != 'q') {
8398 printf("invalid response '%c'\n", resp);
8399 resp = ' ';
8401 } else if (resp != 'y' && resp != 'n') {
8402 printf("invalid response '%c'\n", resp);
8403 resp = ' ';
8407 if (resp == 'y')
8408 *choice = GOT_PATCH_CHOICE_YES;
8409 else if (resp == 'n')
8410 *choice = GOT_PATCH_CHOICE_NO;
8411 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8412 *choice = GOT_PATCH_CHOICE_QUIT;
8414 return NULL;
8417 static const struct got_error *
8418 cmd_revert(int argc, char *argv[])
8420 const struct got_error *error = NULL;
8421 struct got_worktree *worktree = NULL;
8422 struct got_repository *repo = NULL;
8423 char *cwd = NULL, *path = NULL;
8424 struct got_pathlist_head paths;
8425 struct got_pathlist_entry *pe;
8426 int ch, can_recurse = 0, pflag = 0;
8427 FILE *patch_script_file = NULL;
8428 const char *patch_script_path = NULL;
8429 struct choose_patch_arg cpa;
8430 int *pack_fds = NULL;
8432 TAILQ_INIT(&paths);
8434 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8435 switch (ch) {
8436 case 'F':
8437 patch_script_path = optarg;
8438 break;
8439 case 'p':
8440 pflag = 1;
8441 break;
8442 case 'R':
8443 can_recurse = 1;
8444 break;
8445 default:
8446 usage_revert();
8447 /* NOTREACHED */
8451 argc -= optind;
8452 argv += optind;
8454 #ifndef PROFILE
8455 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8456 "unveil", NULL) == -1)
8457 err(1, "pledge");
8458 #endif
8459 if (argc < 1)
8460 usage_revert();
8461 if (patch_script_path && !pflag)
8462 errx(1, "-F option can only be used together with -p option");
8464 cwd = getcwd(NULL, 0);
8465 if (cwd == NULL) {
8466 error = got_error_from_errno("getcwd");
8467 goto done;
8470 error = got_repo_pack_fds_open(&pack_fds);
8471 if (error != NULL)
8472 goto done;
8474 error = got_worktree_open(&worktree, cwd);
8475 if (error) {
8476 if (error->code == GOT_ERR_NOT_WORKTREE)
8477 error = wrap_not_worktree_error(error, "revert", cwd);
8478 goto done;
8481 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8482 NULL, pack_fds);
8483 if (error != NULL)
8484 goto done;
8486 if (patch_script_path) {
8487 patch_script_file = fopen(patch_script_path, "re");
8488 if (patch_script_file == NULL) {
8489 error = got_error_from_errno2("fopen",
8490 patch_script_path);
8491 goto done;
8494 error = apply_unveil(got_repo_get_path(repo), 1,
8495 got_worktree_get_root_path(worktree));
8496 if (error)
8497 goto done;
8499 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8500 if (error)
8501 goto done;
8503 if (!can_recurse) {
8504 char *ondisk_path;
8505 struct stat sb;
8506 TAILQ_FOREACH(pe, &paths, entry) {
8507 if (asprintf(&ondisk_path, "%s/%s",
8508 got_worktree_get_root_path(worktree),
8509 pe->path) == -1) {
8510 error = got_error_from_errno("asprintf");
8511 goto done;
8513 if (lstat(ondisk_path, &sb) == -1) {
8514 if (errno == ENOENT) {
8515 free(ondisk_path);
8516 continue;
8518 error = got_error_from_errno2("lstat",
8519 ondisk_path);
8520 free(ondisk_path);
8521 goto done;
8523 free(ondisk_path);
8524 if (S_ISDIR(sb.st_mode)) {
8525 error = got_error_msg(GOT_ERR_BAD_PATH,
8526 "reverting directories requires -R option");
8527 goto done;
8532 cpa.patch_script_file = patch_script_file;
8533 cpa.action = "revert";
8534 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8535 pflag ? choose_patch : NULL, &cpa, repo);
8536 done:
8537 if (patch_script_file && fclose(patch_script_file) == EOF &&
8538 error == NULL)
8539 error = got_error_from_errno2("fclose", patch_script_path);
8540 if (repo) {
8541 const struct got_error *close_err = got_repo_close(repo);
8542 if (error == NULL)
8543 error = close_err;
8545 if (worktree)
8546 got_worktree_close(worktree);
8547 if (pack_fds) {
8548 const struct got_error *pack_err =
8549 got_repo_pack_fds_close(pack_fds);
8550 if (error == NULL)
8551 error = pack_err;
8553 free(path);
8554 free(cwd);
8555 return error;
8558 __dead static void
8559 usage_commit(void)
8561 fprintf(stderr, "usage: %s commit [-NS] [-A author] [-F path] "
8562 "[-m message] [path ...]\n", getprogname());
8563 exit(1);
8566 struct collect_commit_logmsg_arg {
8567 const char *cmdline_log;
8568 const char *prepared_log;
8569 int non_interactive;
8570 const char *editor;
8571 const char *worktree_path;
8572 const char *branch_name;
8573 const char *repo_path;
8574 char *logmsg_path;
8578 static const struct got_error *
8579 read_prepared_logmsg(char **logmsg, const char *path)
8581 const struct got_error *err = NULL;
8582 FILE *f = NULL;
8583 struct stat sb;
8584 size_t r;
8586 *logmsg = NULL;
8587 memset(&sb, 0, sizeof(sb));
8589 f = fopen(path, "re");
8590 if (f == NULL)
8591 return got_error_from_errno2("fopen", path);
8593 if (fstat(fileno(f), &sb) == -1) {
8594 err = got_error_from_errno2("fstat", path);
8595 goto done;
8597 if (sb.st_size == 0) {
8598 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8599 goto done;
8602 *logmsg = malloc(sb.st_size + 1);
8603 if (*logmsg == NULL) {
8604 err = got_error_from_errno("malloc");
8605 goto done;
8608 r = fread(*logmsg, 1, sb.st_size, f);
8609 if (r != sb.st_size) {
8610 if (ferror(f))
8611 err = got_error_from_errno2("fread", path);
8612 else
8613 err = got_error(GOT_ERR_IO);
8614 goto done;
8616 (*logmsg)[sb.st_size] = '\0';
8617 done:
8618 if (fclose(f) == EOF && err == NULL)
8619 err = got_error_from_errno2("fclose", path);
8620 if (err) {
8621 free(*logmsg);
8622 *logmsg = NULL;
8624 return err;
8627 static const struct got_error *
8628 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8629 const char *diff_path, char **logmsg, void *arg)
8631 char *initial_content = NULL;
8632 struct got_pathlist_entry *pe;
8633 const struct got_error *err = NULL;
8634 char *template = NULL;
8635 struct collect_commit_logmsg_arg *a = arg;
8636 int initial_content_len;
8637 int fd = -1;
8638 size_t len;
8640 /* if a message was specified on the command line, just use it */
8641 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8642 len = strlen(a->cmdline_log) + 1;
8643 *logmsg = malloc(len + 1);
8644 if (*logmsg == NULL)
8645 return got_error_from_errno("malloc");
8646 strlcpy(*logmsg, a->cmdline_log, len);
8647 return NULL;
8648 } else if (a->prepared_log != NULL && a->non_interactive)
8649 return read_prepared_logmsg(logmsg, a->prepared_log);
8651 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8652 return got_error_from_errno("asprintf");
8654 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8655 if (err)
8656 goto done;
8658 if (a->prepared_log) {
8659 char *msg;
8660 err = read_prepared_logmsg(&msg, a->prepared_log);
8661 if (err)
8662 goto done;
8663 if (write(fd, msg, strlen(msg)) == -1) {
8664 err = got_error_from_errno2("write", a->logmsg_path);
8665 free(msg);
8666 goto done;
8668 free(msg);
8671 initial_content_len = asprintf(&initial_content,
8672 "\n# changes to be committed on branch %s:\n",
8673 a->branch_name);
8674 if (initial_content_len == -1) {
8675 err = got_error_from_errno("asprintf");
8676 goto done;
8679 if (write(fd, initial_content, initial_content_len) == -1) {
8680 err = got_error_from_errno2("write", a->logmsg_path);
8681 goto done;
8684 TAILQ_FOREACH(pe, commitable_paths, entry) {
8685 struct got_commitable *ct = pe->data;
8686 dprintf(fd, "# %c %s\n",
8687 got_commitable_get_status(ct),
8688 got_commitable_get_path(ct));
8691 if (diff_path) {
8692 dprintf(fd, "# detailed changes can be viewed in %s\n",
8693 diff_path);
8696 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8697 initial_content_len, a->prepared_log ? 0 : 1);
8698 done:
8699 free(initial_content);
8700 free(template);
8702 if (fd != -1 && close(fd) == -1 && err == NULL)
8703 err = got_error_from_errno2("close", a->logmsg_path);
8705 /* Editor is done; we can now apply unveil(2) */
8706 if (err == NULL)
8707 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8708 if (err) {
8709 free(*logmsg);
8710 *logmsg = NULL;
8712 return err;
8715 static const struct got_error *
8716 cmd_commit(int argc, char *argv[])
8718 const struct got_error *error = NULL;
8719 struct got_worktree *worktree = NULL;
8720 struct got_repository *repo = NULL;
8721 char *cwd = NULL, *id_str = NULL;
8722 struct got_object_id *id = NULL;
8723 const char *logmsg = NULL;
8724 char *prepared_logmsg = NULL;
8725 struct collect_commit_logmsg_arg cl_arg;
8726 const char *author = NULL;
8727 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
8728 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8729 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8730 int show_diff = 1;
8731 struct got_pathlist_head paths;
8732 int *pack_fds = NULL;
8734 TAILQ_INIT(&paths);
8735 cl_arg.logmsg_path = NULL;
8737 while ((ch = getopt(argc, argv, "A:F:m:NnS")) != -1) {
8738 switch (ch) {
8739 case 'A':
8740 author = optarg;
8741 error = valid_author(author);
8742 if (error)
8743 return error;
8744 break;
8745 case 'F':
8746 if (logmsg != NULL)
8747 option_conflict('F', 'm');
8748 prepared_logmsg = realpath(optarg, NULL);
8749 if (prepared_logmsg == NULL)
8750 return got_error_from_errno2("realpath",
8751 optarg);
8752 break;
8753 case 'm':
8754 if (prepared_logmsg)
8755 option_conflict('m', 'F');
8756 logmsg = optarg;
8757 break;
8758 case 'N':
8759 non_interactive = 1;
8760 break;
8761 case 'n':
8762 show_diff = 0;
8763 break;
8764 case 'S':
8765 allow_bad_symlinks = 1;
8766 break;
8767 default:
8768 usage_commit();
8769 /* NOTREACHED */
8773 argc -= optind;
8774 argv += optind;
8776 #ifndef PROFILE
8777 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8778 "unveil", NULL) == -1)
8779 err(1, "pledge");
8780 #endif
8781 cwd = getcwd(NULL, 0);
8782 if (cwd == NULL) {
8783 error = got_error_from_errno("getcwd");
8784 goto done;
8787 error = got_repo_pack_fds_open(&pack_fds);
8788 if (error != NULL)
8789 goto done;
8791 error = got_worktree_open(&worktree, cwd);
8792 if (error) {
8793 if (error->code == GOT_ERR_NOT_WORKTREE)
8794 error = wrap_not_worktree_error(error, "commit", cwd);
8795 goto done;
8798 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8799 if (error)
8800 goto done;
8801 if (rebase_in_progress) {
8802 error = got_error(GOT_ERR_REBASING);
8803 goto done;
8806 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8807 worktree);
8808 if (error)
8809 goto done;
8811 error = get_gitconfig_path(&gitconfig_path);
8812 if (error)
8813 goto done;
8814 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8815 gitconfig_path, pack_fds);
8816 if (error != NULL)
8817 goto done;
8819 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8820 if (error)
8821 goto done;
8822 if (merge_in_progress) {
8823 error = got_error(GOT_ERR_MERGE_BUSY);
8824 goto done;
8827 error = get_author(&committer, repo, worktree);
8828 if (error)
8829 goto done;
8831 if (author != NULL && !strcmp(committer, author)) {
8832 error = got_error(GOT_ERR_COMMIT_REDUNDANT_AUTHOR);
8833 goto done;
8836 if (author == NULL)
8837 author = committer;
8840 * unveil(2) traverses exec(2); if an editor is used we have
8841 * to apply unveil after the log message has been written.
8843 if (logmsg == NULL || strlen(logmsg) == 0)
8844 error = get_editor(&editor);
8845 else
8846 error = apply_unveil(got_repo_get_path(repo), 0,
8847 got_worktree_get_root_path(worktree));
8848 if (error)
8849 goto done;
8851 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8852 if (error)
8853 goto done;
8855 cl_arg.editor = editor;
8856 cl_arg.cmdline_log = logmsg;
8857 cl_arg.prepared_log = prepared_logmsg;
8858 cl_arg.non_interactive = non_interactive;
8859 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8860 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8861 if (!histedit_in_progress) {
8862 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8863 error = got_error(GOT_ERR_COMMIT_BRANCH);
8864 goto done;
8866 cl_arg.branch_name += 11;
8868 cl_arg.repo_path = got_repo_get_path(repo);
8869 error = got_worktree_commit(&id, worktree, &paths, author, committer,
8870 allow_bad_symlinks, show_diff, collect_commit_logmsg, &cl_arg,
8871 print_status, NULL, repo);
8872 if (error) {
8873 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8874 cl_arg.logmsg_path != NULL)
8875 preserve_logmsg = 1;
8876 goto done;
8879 error = got_object_id_str(&id_str, id);
8880 if (error)
8881 goto done;
8882 printf("Created commit %s\n", id_str);
8883 done:
8884 if (preserve_logmsg) {
8885 fprintf(stderr, "%s: log message preserved in %s\n",
8886 getprogname(), cl_arg.logmsg_path);
8887 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8888 error == NULL)
8889 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8890 free(cl_arg.logmsg_path);
8891 if (repo) {
8892 const struct got_error *close_err = got_repo_close(repo);
8893 if (error == NULL)
8894 error = close_err;
8896 if (worktree)
8897 got_worktree_close(worktree);
8898 if (pack_fds) {
8899 const struct got_error *pack_err =
8900 got_repo_pack_fds_close(pack_fds);
8901 if (error == NULL)
8902 error = pack_err;
8904 free(cwd);
8905 free(id_str);
8906 free(gitconfig_path);
8907 free(editor);
8908 free(committer);
8909 free(prepared_logmsg);
8910 return error;
8913 __dead static void
8914 usage_send(void)
8916 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
8917 "[-r repository-path] [-t tag] [remote-repository]\n",
8918 getprogname());
8919 exit(1);
8922 static void
8923 print_load_info(int print_colored, int print_found, int print_trees,
8924 int ncolored, int nfound, int ntrees)
8926 if (print_colored) {
8927 printf("%d commit%s colored", ncolored,
8928 ncolored == 1 ? "" : "s");
8930 if (print_found) {
8931 printf("%s%d object%s found",
8932 ncolored > 0 ? "; " : "",
8933 nfound, nfound == 1 ? "" : "s");
8935 if (print_trees) {
8936 printf("; %d tree%s scanned", ntrees,
8937 ntrees == 1 ? "" : "s");
8941 struct got_send_progress_arg {
8942 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8943 int verbosity;
8944 int last_ncolored;
8945 int last_nfound;
8946 int last_ntrees;
8947 int loading_done;
8948 int last_ncommits;
8949 int last_nobj_total;
8950 int last_p_deltify;
8951 int last_p_written;
8952 int last_p_sent;
8953 int printed_something;
8954 int sent_something;
8955 struct got_pathlist_head *delete_branches;
8958 static const struct got_error *
8959 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8960 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8961 int nobj_written, off_t bytes_sent, const char *refname,
8962 const char *errmsg, int success)
8964 struct got_send_progress_arg *a = arg;
8965 char scaled_packsize[FMT_SCALED_STRSIZE];
8966 char scaled_sent[FMT_SCALED_STRSIZE];
8967 int p_deltify = 0, p_written = 0, p_sent = 0;
8968 int print_colored = 0, print_found = 0, print_trees = 0;
8969 int print_searching = 0, print_total = 0;
8970 int print_deltify = 0, print_written = 0, print_sent = 0;
8972 if (a->verbosity < 0)
8973 return NULL;
8975 if (refname) {
8976 const char *status = success ? "accepted" : "rejected";
8978 if (success) {
8979 struct got_pathlist_entry *pe;
8980 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8981 const char *branchname = pe->path;
8982 if (got_path_cmp(branchname, refname,
8983 strlen(branchname), strlen(refname)) == 0) {
8984 status = "deleted";
8985 a->sent_something = 1;
8986 break;
8991 if (a->printed_something)
8992 putchar('\n');
8993 printf("Server has %s %s", status, refname);
8994 if (errmsg)
8995 printf(": %s", errmsg);
8996 a->printed_something = 1;
8997 return NULL;
9000 if (a->last_ncolored != ncolored) {
9001 print_colored = 1;
9002 a->last_ncolored = ncolored;
9005 if (a->last_nfound != nfound) {
9006 print_colored = 1;
9007 print_found = 1;
9008 a->last_nfound = nfound;
9011 if (a->last_ntrees != ntrees) {
9012 print_colored = 1;
9013 print_found = 1;
9014 print_trees = 1;
9015 a->last_ntrees = ntrees;
9018 if ((print_colored || print_found || print_trees) &&
9019 !a->loading_done) {
9020 printf("\r");
9021 print_load_info(print_colored, print_found, print_trees,
9022 ncolored, nfound, ntrees);
9023 a->printed_something = 1;
9024 fflush(stdout);
9025 return NULL;
9026 } else if (!a->loading_done) {
9027 printf("\r");
9028 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9029 printf("\n");
9030 a->loading_done = 1;
9033 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9034 return got_error_from_errno("fmt_scaled");
9035 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9036 return got_error_from_errno("fmt_scaled");
9038 if (a->last_ncommits != ncommits) {
9039 print_searching = 1;
9040 a->last_ncommits = ncommits;
9043 if (a->last_nobj_total != nobj_total) {
9044 print_searching = 1;
9045 print_total = 1;
9046 a->last_nobj_total = nobj_total;
9049 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9050 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9051 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9052 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9053 return got_error(GOT_ERR_NO_SPACE);
9056 if (nobj_deltify > 0 || nobj_written > 0) {
9057 if (nobj_deltify > 0) {
9058 p_deltify = (nobj_deltify * 100) / nobj_total;
9059 if (p_deltify != a->last_p_deltify) {
9060 a->last_p_deltify = p_deltify;
9061 print_searching = 1;
9062 print_total = 1;
9063 print_deltify = 1;
9066 if (nobj_written > 0) {
9067 p_written = (nobj_written * 100) / nobj_total;
9068 if (p_written != a->last_p_written) {
9069 a->last_p_written = p_written;
9070 print_searching = 1;
9071 print_total = 1;
9072 print_deltify = 1;
9073 print_written = 1;
9078 if (bytes_sent > 0) {
9079 p_sent = (bytes_sent * 100) / packfile_size;
9080 if (p_sent != a->last_p_sent) {
9081 a->last_p_sent = p_sent;
9082 print_searching = 1;
9083 print_total = 1;
9084 print_deltify = 1;
9085 print_written = 1;
9086 print_sent = 1;
9088 a->sent_something = 1;
9091 if (print_searching || print_total || print_deltify || print_written ||
9092 print_sent)
9093 printf("\r");
9094 if (print_searching)
9095 printf("packing %d reference%s", ncommits,
9096 ncommits == 1 ? "" : "s");
9097 if (print_total)
9098 printf("; %d object%s", nobj_total,
9099 nobj_total == 1 ? "" : "s");
9100 if (print_deltify)
9101 printf("; deltify: %d%%", p_deltify);
9102 if (print_sent)
9103 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9104 scaled_packsize, p_sent);
9105 else if (print_written)
9106 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9107 scaled_packsize, p_written);
9108 if (print_searching || print_total || print_deltify ||
9109 print_written || print_sent) {
9110 a->printed_something = 1;
9111 fflush(stdout);
9113 return NULL;
9116 static const struct got_error *
9117 cmd_send(int argc, char *argv[])
9119 const struct got_error *error = NULL;
9120 char *cwd = NULL, *repo_path = NULL;
9121 const char *remote_name;
9122 char *proto = NULL, *host = NULL, *port = NULL;
9123 char *repo_name = NULL, *server_path = NULL;
9124 const struct got_remote_repo *remotes, *remote = NULL;
9125 int nremotes, nbranches = 0, ndelete_branches = 0;
9126 struct got_repository *repo = NULL;
9127 struct got_worktree *worktree = NULL;
9128 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9129 struct got_pathlist_head branches;
9130 struct got_pathlist_head tags;
9131 struct got_reflist_head all_branches;
9132 struct got_reflist_head all_tags;
9133 struct got_pathlist_head delete_args;
9134 struct got_pathlist_head delete_branches;
9135 struct got_reflist_entry *re;
9136 struct got_pathlist_entry *pe;
9137 int i, ch, sendfd = -1, sendstatus;
9138 pid_t sendpid = -1;
9139 struct got_send_progress_arg spa;
9140 int verbosity = 0, overwrite_refs = 0;
9141 int send_all_branches = 0, send_all_tags = 0;
9142 struct got_reference *ref = NULL;
9143 int *pack_fds = NULL;
9145 TAILQ_INIT(&branches);
9146 TAILQ_INIT(&tags);
9147 TAILQ_INIT(&all_branches);
9148 TAILQ_INIT(&all_tags);
9149 TAILQ_INIT(&delete_args);
9150 TAILQ_INIT(&delete_branches);
9152 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9153 switch (ch) {
9154 case 'a':
9155 send_all_branches = 1;
9156 break;
9157 case 'b':
9158 error = got_pathlist_append(&branches, optarg, NULL);
9159 if (error)
9160 return error;
9161 nbranches++;
9162 break;
9163 case 'd':
9164 error = got_pathlist_append(&delete_args, optarg, NULL);
9165 if (error)
9166 return error;
9167 break;
9168 case 'f':
9169 overwrite_refs = 1;
9170 break;
9171 case 'q':
9172 verbosity = -1;
9173 break;
9174 case 'r':
9175 repo_path = realpath(optarg, NULL);
9176 if (repo_path == NULL)
9177 return got_error_from_errno2("realpath",
9178 optarg);
9179 got_path_strip_trailing_slashes(repo_path);
9180 break;
9181 case 'T':
9182 send_all_tags = 1;
9183 break;
9184 case 't':
9185 error = got_pathlist_append(&tags, optarg, NULL);
9186 if (error)
9187 return error;
9188 break;
9189 case 'v':
9190 if (verbosity < 0)
9191 verbosity = 0;
9192 else if (verbosity < 3)
9193 verbosity++;
9194 break;
9195 default:
9196 usage_send();
9197 /* NOTREACHED */
9200 argc -= optind;
9201 argv += optind;
9203 if (send_all_branches && !TAILQ_EMPTY(&branches))
9204 option_conflict('a', 'b');
9205 if (send_all_tags && !TAILQ_EMPTY(&tags))
9206 option_conflict('T', 't');
9209 if (argc == 0)
9210 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9211 else if (argc == 1)
9212 remote_name = argv[0];
9213 else
9214 usage_send();
9216 cwd = getcwd(NULL, 0);
9217 if (cwd == NULL) {
9218 error = got_error_from_errno("getcwd");
9219 goto done;
9222 error = got_repo_pack_fds_open(&pack_fds);
9223 if (error != NULL)
9224 goto done;
9226 if (repo_path == NULL) {
9227 error = got_worktree_open(&worktree, cwd);
9228 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9229 goto done;
9230 else
9231 error = NULL;
9232 if (worktree) {
9233 repo_path =
9234 strdup(got_worktree_get_repo_path(worktree));
9235 if (repo_path == NULL)
9236 error = got_error_from_errno("strdup");
9237 if (error)
9238 goto done;
9239 } else {
9240 repo_path = strdup(cwd);
9241 if (repo_path == NULL) {
9242 error = got_error_from_errno("strdup");
9243 goto done;
9248 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9249 if (error)
9250 goto done;
9252 if (worktree) {
9253 worktree_conf = got_worktree_get_gotconfig(worktree);
9254 if (worktree_conf) {
9255 got_gotconfig_get_remotes(&nremotes, &remotes,
9256 worktree_conf);
9257 for (i = 0; i < nremotes; i++) {
9258 if (strcmp(remotes[i].name, remote_name) == 0) {
9259 remote = &remotes[i];
9260 break;
9265 if (remote == NULL) {
9266 repo_conf = got_repo_get_gotconfig(repo);
9267 if (repo_conf) {
9268 got_gotconfig_get_remotes(&nremotes, &remotes,
9269 repo_conf);
9270 for (i = 0; i < nremotes; i++) {
9271 if (strcmp(remotes[i].name, remote_name) == 0) {
9272 remote = &remotes[i];
9273 break;
9278 if (remote == NULL) {
9279 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9280 for (i = 0; i < nremotes; i++) {
9281 if (strcmp(remotes[i].name, remote_name) == 0) {
9282 remote = &remotes[i];
9283 break;
9287 if (remote == NULL) {
9288 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9289 goto done;
9292 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9293 &repo_name, remote->send_url);
9294 if (error)
9295 goto done;
9297 if (strcmp(proto, "git") == 0) {
9298 #ifndef PROFILE
9299 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9300 "sendfd dns inet unveil", NULL) == -1)
9301 err(1, "pledge");
9302 #endif
9303 } else if (strcmp(proto, "git+ssh") == 0 ||
9304 strcmp(proto, "ssh") == 0) {
9305 #ifndef PROFILE
9306 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9307 "sendfd unveil", NULL) == -1)
9308 err(1, "pledge");
9309 #endif
9310 } else if (strcmp(proto, "http") == 0 ||
9311 strcmp(proto, "git+http") == 0) {
9312 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9313 goto done;
9314 } else {
9315 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9316 goto done;
9319 error = got_dial_apply_unveil(proto);
9320 if (error)
9321 goto done;
9323 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9324 if (error)
9325 goto done;
9327 if (send_all_branches) {
9328 error = got_ref_list(&all_branches, repo, "refs/heads",
9329 got_ref_cmp_by_name, NULL);
9330 if (error)
9331 goto done;
9332 TAILQ_FOREACH(re, &all_branches, entry) {
9333 const char *branchname = got_ref_get_name(re->ref);
9334 error = got_pathlist_append(&branches,
9335 branchname, NULL);
9336 if (error)
9337 goto done;
9338 nbranches++;
9340 } else if (nbranches == 0) {
9341 for (i = 0; i < remote->nsend_branches; i++) {
9342 got_pathlist_append(&branches,
9343 remote->send_branches[i], NULL);
9347 if (send_all_tags) {
9348 error = got_ref_list(&all_tags, repo, "refs/tags",
9349 got_ref_cmp_by_name, NULL);
9350 if (error)
9351 goto done;
9352 TAILQ_FOREACH(re, &all_tags, entry) {
9353 const char *tagname = got_ref_get_name(re->ref);
9354 error = got_pathlist_append(&tags,
9355 tagname, NULL);
9356 if (error)
9357 goto done;
9362 * To prevent accidents only branches in refs/heads/ can be deleted
9363 * with 'got send -d'.
9364 * Deleting anything else requires local repository access or Git.
9366 TAILQ_FOREACH(pe, &delete_args, entry) {
9367 const char *branchname = pe->path;
9368 char *s;
9369 struct got_pathlist_entry *new;
9370 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9371 s = strdup(branchname);
9372 if (s == NULL) {
9373 error = got_error_from_errno("strdup");
9374 goto done;
9376 } else {
9377 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9378 error = got_error_from_errno("asprintf");
9379 goto done;
9382 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9383 if (error || new == NULL /* duplicate */)
9384 free(s);
9385 if (error)
9386 goto done;
9387 ndelete_branches++;
9390 if (nbranches == 0 && ndelete_branches == 0) {
9391 struct got_reference *head_ref;
9392 if (worktree)
9393 error = got_ref_open(&head_ref, repo,
9394 got_worktree_get_head_ref_name(worktree), 0);
9395 else
9396 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9397 if (error)
9398 goto done;
9399 if (got_ref_is_symbolic(head_ref)) {
9400 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9401 got_ref_close(head_ref);
9402 if (error)
9403 goto done;
9404 } else
9405 ref = head_ref;
9406 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9407 NULL);
9408 if (error)
9409 goto done;
9410 nbranches++;
9413 if (verbosity >= 0) {
9414 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9415 remote->name, proto, host,
9416 port ? ":" : "", port ? port : "",
9417 *server_path == '/' ? "" : "/", server_path);
9420 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9421 server_path, verbosity);
9422 if (error)
9423 goto done;
9425 memset(&spa, 0, sizeof(spa));
9426 spa.last_scaled_packsize[0] = '\0';
9427 spa.last_p_deltify = -1;
9428 spa.last_p_written = -1;
9429 spa.verbosity = verbosity;
9430 spa.delete_branches = &delete_branches;
9431 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9432 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9433 check_cancelled, NULL);
9434 if (spa.printed_something)
9435 putchar('\n');
9436 if (error)
9437 goto done;
9438 if (!spa.sent_something && verbosity >= 0)
9439 printf("Already up-to-date\n");
9440 done:
9441 if (sendpid > 0) {
9442 if (kill(sendpid, SIGTERM) == -1)
9443 error = got_error_from_errno("kill");
9444 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9445 error = got_error_from_errno("waitpid");
9447 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9448 error = got_error_from_errno("close");
9449 if (repo) {
9450 const struct got_error *close_err = got_repo_close(repo);
9451 if (error == NULL)
9452 error = close_err;
9454 if (worktree)
9455 got_worktree_close(worktree);
9456 if (pack_fds) {
9457 const struct got_error *pack_err =
9458 got_repo_pack_fds_close(pack_fds);
9459 if (error == NULL)
9460 error = pack_err;
9462 if (ref)
9463 got_ref_close(ref);
9464 got_pathlist_free(&branches);
9465 got_pathlist_free(&tags);
9466 got_ref_list_free(&all_branches);
9467 got_ref_list_free(&all_tags);
9468 got_pathlist_free(&delete_args);
9469 TAILQ_FOREACH(pe, &delete_branches, entry)
9470 free((char *)pe->path);
9471 got_pathlist_free(&delete_branches);
9472 free(cwd);
9473 free(repo_path);
9474 free(proto);
9475 free(host);
9476 free(port);
9477 free(server_path);
9478 free(repo_name);
9479 return error;
9482 __dead static void
9483 usage_cherrypick(void)
9485 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
9486 exit(1);
9489 static const struct got_error *
9490 cmd_cherrypick(int argc, char *argv[])
9492 const struct got_error *error = NULL;
9493 struct got_worktree *worktree = NULL;
9494 struct got_repository *repo = NULL;
9495 char *cwd = NULL, *commit_id_str = NULL;
9496 struct got_object_id *commit_id = NULL;
9497 struct got_commit_object *commit = NULL;
9498 struct got_object_qid *pid;
9499 int ch;
9500 struct got_update_progress_arg upa;
9501 int *pack_fds = NULL;
9503 while ((ch = getopt(argc, argv, "")) != -1) {
9504 switch (ch) {
9505 default:
9506 usage_cherrypick();
9507 /* NOTREACHED */
9511 argc -= optind;
9512 argv += optind;
9514 #ifndef PROFILE
9515 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9516 "unveil", NULL) == -1)
9517 err(1, "pledge");
9518 #endif
9519 if (argc != 1)
9520 usage_cherrypick();
9522 cwd = getcwd(NULL, 0);
9523 if (cwd == NULL) {
9524 error = got_error_from_errno("getcwd");
9525 goto done;
9528 error = got_repo_pack_fds_open(&pack_fds);
9529 if (error != NULL)
9530 goto done;
9532 error = got_worktree_open(&worktree, cwd);
9533 if (error) {
9534 if (error->code == GOT_ERR_NOT_WORKTREE)
9535 error = wrap_not_worktree_error(error, "cherrypick",
9536 cwd);
9537 goto done;
9540 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9541 NULL, pack_fds);
9542 if (error != NULL)
9543 goto done;
9545 error = apply_unveil(got_repo_get_path(repo), 0,
9546 got_worktree_get_root_path(worktree));
9547 if (error)
9548 goto done;
9550 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9551 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9552 if (error)
9553 goto done;
9554 error = got_object_id_str(&commit_id_str, commit_id);
9555 if (error)
9556 goto done;
9558 error = got_object_open_as_commit(&commit, repo, commit_id);
9559 if (error)
9560 goto done;
9561 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9562 memset(&upa, 0, sizeof(upa));
9563 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9564 commit_id, repo, update_progress, &upa, check_cancelled,
9565 NULL);
9566 if (error != NULL)
9567 goto done;
9569 if (upa.did_something)
9570 printf("Merged commit %s\n", commit_id_str);
9571 print_merge_progress_stats(&upa);
9572 done:
9573 if (commit)
9574 got_object_commit_close(commit);
9575 free(commit_id_str);
9576 if (worktree)
9577 got_worktree_close(worktree);
9578 if (repo) {
9579 const struct got_error *close_err = got_repo_close(repo);
9580 if (error == NULL)
9581 error = close_err;
9583 if (pack_fds) {
9584 const struct got_error *pack_err =
9585 got_repo_pack_fds_close(pack_fds);
9586 if (error == NULL)
9587 error = pack_err;
9590 return error;
9593 __dead static void
9594 usage_backout(void)
9596 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9597 exit(1);
9600 static const struct got_error *
9601 cmd_backout(int argc, char *argv[])
9603 const struct got_error *error = NULL;
9604 struct got_worktree *worktree = NULL;
9605 struct got_repository *repo = NULL;
9606 char *cwd = NULL, *commit_id_str = NULL;
9607 struct got_object_id *commit_id = NULL;
9608 struct got_commit_object *commit = NULL;
9609 struct got_object_qid *pid;
9610 int ch;
9611 struct got_update_progress_arg upa;
9612 int *pack_fds = NULL;
9614 while ((ch = getopt(argc, argv, "")) != -1) {
9615 switch (ch) {
9616 default:
9617 usage_backout();
9618 /* NOTREACHED */
9622 argc -= optind;
9623 argv += optind;
9625 #ifndef PROFILE
9626 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9627 "unveil", NULL) == -1)
9628 err(1, "pledge");
9629 #endif
9630 if (argc != 1)
9631 usage_backout();
9633 cwd = getcwd(NULL, 0);
9634 if (cwd == NULL) {
9635 error = got_error_from_errno("getcwd");
9636 goto done;
9639 error = got_repo_pack_fds_open(&pack_fds);
9640 if (error != NULL)
9641 goto done;
9643 error = got_worktree_open(&worktree, cwd);
9644 if (error) {
9645 if (error->code == GOT_ERR_NOT_WORKTREE)
9646 error = wrap_not_worktree_error(error, "backout", cwd);
9647 goto done;
9650 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9651 NULL, pack_fds);
9652 if (error != NULL)
9653 goto done;
9655 error = apply_unveil(got_repo_get_path(repo), 0,
9656 got_worktree_get_root_path(worktree));
9657 if (error)
9658 goto done;
9660 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9661 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9662 if (error)
9663 goto done;
9664 error = got_object_id_str(&commit_id_str, commit_id);
9665 if (error)
9666 goto done;
9668 error = got_object_open_as_commit(&commit, repo, commit_id);
9669 if (error)
9670 goto done;
9671 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9672 if (pid == NULL) {
9673 error = got_error(GOT_ERR_ROOT_COMMIT);
9674 goto done;
9677 memset(&upa, 0, sizeof(upa));
9678 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9679 repo, update_progress, &upa, check_cancelled, NULL);
9680 if (error != NULL)
9681 goto done;
9683 if (upa.did_something)
9684 printf("Backed out commit %s\n", commit_id_str);
9685 print_merge_progress_stats(&upa);
9686 done:
9687 if (commit)
9688 got_object_commit_close(commit);
9689 free(commit_id_str);
9690 if (worktree)
9691 got_worktree_close(worktree);
9692 if (repo) {
9693 const struct got_error *close_err = got_repo_close(repo);
9694 if (error == NULL)
9695 error = close_err;
9697 if (pack_fds) {
9698 const struct got_error *pack_err =
9699 got_repo_pack_fds_close(pack_fds);
9700 if (error == NULL)
9701 error = pack_err;
9703 return error;
9706 __dead static void
9707 usage_rebase(void)
9709 fprintf(stderr, "usage: %s rebase [-aclX] [branch]\n", getprogname());
9710 exit(1);
9713 static void
9714 trim_logmsg(char *logmsg, int limit)
9716 char *nl;
9717 size_t len;
9719 len = strlen(logmsg);
9720 if (len > limit)
9721 len = limit;
9722 logmsg[len] = '\0';
9723 nl = strchr(logmsg, '\n');
9724 if (nl)
9725 *nl = '\0';
9728 static const struct got_error *
9729 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9731 const struct got_error *err;
9732 char *logmsg0 = NULL;
9733 const char *s;
9735 err = got_object_commit_get_logmsg(&logmsg0, commit);
9736 if (err)
9737 return err;
9739 s = logmsg0;
9740 while (isspace((unsigned char)s[0]))
9741 s++;
9743 *logmsg = strdup(s);
9744 if (*logmsg == NULL) {
9745 err = got_error_from_errno("strdup");
9746 goto done;
9749 trim_logmsg(*logmsg, limit);
9750 done:
9751 free(logmsg0);
9752 return err;
9755 static const struct got_error *
9756 show_rebase_merge_conflict(struct got_object_id *id,
9757 struct got_repository *repo)
9759 const struct got_error *err;
9760 struct got_commit_object *commit = NULL;
9761 char *id_str = NULL, *logmsg = NULL;
9763 err = got_object_open_as_commit(&commit, repo, id);
9764 if (err)
9765 return err;
9767 err = got_object_id_str(&id_str, id);
9768 if (err)
9769 goto done;
9771 id_str[12] = '\0';
9773 err = get_short_logmsg(&logmsg, 42, commit);
9774 if (err)
9775 goto done;
9777 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9778 done:
9779 free(id_str);
9780 got_object_commit_close(commit);
9781 free(logmsg);
9782 return err;
9785 static const struct got_error *
9786 show_rebase_progress(struct got_commit_object *commit,
9787 struct got_object_id *old_id, struct got_object_id *new_id)
9789 const struct got_error *err;
9790 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9792 err = got_object_id_str(&old_id_str, old_id);
9793 if (err)
9794 goto done;
9796 if (new_id) {
9797 err = got_object_id_str(&new_id_str, new_id);
9798 if (err)
9799 goto done;
9802 old_id_str[12] = '\0';
9803 if (new_id_str)
9804 new_id_str[12] = '\0';
9806 err = get_short_logmsg(&logmsg, 42, commit);
9807 if (err)
9808 goto done;
9810 printf("%s -> %s: %s\n", old_id_str,
9811 new_id_str ? new_id_str : "no-op change", logmsg);
9812 done:
9813 free(old_id_str);
9814 free(new_id_str);
9815 free(logmsg);
9816 return err;
9819 static const struct got_error *
9820 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9821 struct got_reference *branch, struct got_reference *new_base_branch,
9822 struct got_reference *tmp_branch, struct got_repository *repo,
9823 int create_backup)
9825 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9826 return got_worktree_rebase_complete(worktree, fileindex,
9827 new_base_branch, tmp_branch, branch, repo, create_backup);
9830 static const struct got_error *
9831 rebase_commit(struct got_pathlist_head *merged_paths,
9832 struct got_worktree *worktree, struct got_fileindex *fileindex,
9833 struct got_reference *tmp_branch, const char *committer,
9834 struct got_object_id *commit_id, struct got_repository *repo)
9836 const struct got_error *error;
9837 struct got_commit_object *commit;
9838 struct got_object_id *new_commit_id;
9840 error = got_object_open_as_commit(&commit, repo, commit_id);
9841 if (error)
9842 return error;
9844 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9845 worktree, fileindex, tmp_branch, committer, commit, commit_id,
9846 repo);
9847 if (error) {
9848 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9849 goto done;
9850 error = show_rebase_progress(commit, commit_id, NULL);
9851 } else {
9852 error = show_rebase_progress(commit, commit_id, new_commit_id);
9853 free(new_commit_id);
9855 done:
9856 got_object_commit_close(commit);
9857 return error;
9860 struct check_path_prefix_arg {
9861 const char *path_prefix;
9862 size_t len;
9863 int errcode;
9866 static const struct got_error *
9867 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9868 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9869 struct got_object_id *id1, struct got_object_id *id2,
9870 const char *path1, const char *path2,
9871 mode_t mode1, mode_t mode2, struct got_repository *repo)
9873 struct check_path_prefix_arg *a = arg;
9875 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9876 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9877 return got_error(a->errcode);
9879 return NULL;
9882 static const struct got_error *
9883 check_path_prefix(struct got_object_id *parent_id,
9884 struct got_object_id *commit_id, const char *path_prefix,
9885 int errcode, struct got_repository *repo)
9887 const struct got_error *err;
9888 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9889 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9890 struct check_path_prefix_arg cpp_arg;
9892 if (got_path_is_root_dir(path_prefix))
9893 return NULL;
9895 err = got_object_open_as_commit(&commit, repo, commit_id);
9896 if (err)
9897 goto done;
9899 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9900 if (err)
9901 goto done;
9903 err = got_object_open_as_tree(&tree1, repo,
9904 got_object_commit_get_tree_id(parent_commit));
9905 if (err)
9906 goto done;
9908 err = got_object_open_as_tree(&tree2, repo,
9909 got_object_commit_get_tree_id(commit));
9910 if (err)
9911 goto done;
9913 cpp_arg.path_prefix = path_prefix;
9914 while (cpp_arg.path_prefix[0] == '/')
9915 cpp_arg.path_prefix++;
9916 cpp_arg.len = strlen(cpp_arg.path_prefix);
9917 cpp_arg.errcode = errcode;
9918 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
9919 check_path_prefix_in_diff, &cpp_arg, 0);
9920 done:
9921 if (tree1)
9922 got_object_tree_close(tree1);
9923 if (tree2)
9924 got_object_tree_close(tree2);
9925 if (commit)
9926 got_object_commit_close(commit);
9927 if (parent_commit)
9928 got_object_commit_close(parent_commit);
9929 return err;
9932 static const struct got_error *
9933 collect_commits(struct got_object_id_queue *commits,
9934 struct got_object_id *initial_commit_id,
9935 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9936 const char *path_prefix, int path_prefix_errcode,
9937 struct got_repository *repo)
9939 const struct got_error *err = NULL;
9940 struct got_commit_graph *graph = NULL;
9941 struct got_object_id parent_id, commit_id;
9942 struct got_object_qid *qid;
9944 err = got_commit_graph_open(&graph, "/", 1);
9945 if (err)
9946 return err;
9948 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9949 check_cancelled, NULL);
9950 if (err)
9951 goto done;
9953 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
9954 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
9955 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9956 check_cancelled, NULL);
9957 if (err) {
9958 if (err->code == GOT_ERR_ITER_COMPLETED) {
9959 err = got_error_msg(GOT_ERR_ANCESTRY,
9960 "ran out of commits to rebase before "
9961 "youngest common ancestor commit has "
9962 "been reached?!?");
9964 goto done;
9965 } else {
9966 err = check_path_prefix(&parent_id, &commit_id,
9967 path_prefix, path_prefix_errcode, repo);
9968 if (err)
9969 goto done;
9971 err = got_object_qid_alloc(&qid, &commit_id);
9972 if (err)
9973 goto done;
9974 STAILQ_INSERT_HEAD(commits, qid, entry);
9976 memcpy(&commit_id, &parent_id, sizeof(commit_id));
9979 done:
9980 got_commit_graph_close(graph);
9981 return err;
9984 static const struct got_error *
9985 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9987 const struct got_error *err = NULL;
9988 time_t committer_time;
9989 struct tm tm;
9990 char datebuf[11]; /* YYYY-MM-DD + NUL */
9991 char *author0 = NULL, *author, *smallerthan;
9992 char *logmsg0 = NULL, *logmsg, *newline;
9994 committer_time = got_object_commit_get_committer_time(commit);
9995 if (gmtime_r(&committer_time, &tm) == NULL)
9996 return got_error_from_errno("gmtime_r");
9997 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9998 return got_error(GOT_ERR_NO_SPACE);
10000 author0 = strdup(got_object_commit_get_author(commit));
10001 if (author0 == NULL)
10002 return got_error_from_errno("strdup");
10003 author = author0;
10004 smallerthan = strchr(author, '<');
10005 if (smallerthan && smallerthan[1] != '\0')
10006 author = smallerthan + 1;
10007 author[strcspn(author, "@>")] = '\0';
10009 err = got_object_commit_get_logmsg(&logmsg0, commit);
10010 if (err)
10011 goto done;
10012 logmsg = logmsg0;
10013 while (*logmsg == '\n')
10014 logmsg++;
10015 newline = strchr(logmsg, '\n');
10016 if (newline)
10017 *newline = '\0';
10019 if (asprintf(brief_str, "%s %s %s",
10020 datebuf, author, logmsg) == -1)
10021 err = got_error_from_errno("asprintf");
10022 done:
10023 free(author0);
10024 free(logmsg0);
10025 return err;
10028 static const struct got_error *
10029 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10030 struct got_repository *repo)
10032 const struct got_error *err;
10033 char *id_str;
10035 err = got_object_id_str(&id_str, id);
10036 if (err)
10037 return err;
10039 err = got_ref_delete(ref, repo);
10040 if (err)
10041 goto done;
10043 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10044 done:
10045 free(id_str);
10046 return err;
10049 static const struct got_error *
10050 print_backup_ref(const char *branch_name, const char *new_id_str,
10051 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10052 struct got_reflist_object_id_map *refs_idmap,
10053 struct got_repository *repo)
10055 const struct got_error *err = NULL;
10056 struct got_reflist_head *refs;
10057 char *refs_str = NULL;
10058 struct got_object_id *new_commit_id = NULL;
10059 struct got_commit_object *new_commit = NULL;
10060 char *new_commit_brief_str = NULL;
10061 struct got_object_id *yca_id = NULL;
10062 struct got_commit_object *yca_commit = NULL;
10063 char *yca_id_str = NULL, *yca_brief_str = NULL;
10064 char *custom_refs_str;
10066 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10067 return got_error_from_errno("asprintf");
10069 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10070 0, 0, refs_idmap, custom_refs_str);
10071 if (err)
10072 goto done;
10074 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10075 if (err)
10076 goto done;
10078 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10079 if (refs) {
10080 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10081 if (err)
10082 goto done;
10085 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10086 if (err)
10087 goto done;
10089 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10090 if (err)
10091 goto done;
10093 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10094 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10095 if (err)
10096 goto done;
10098 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10099 refs_str ? " (" : "", refs_str ? refs_str : "",
10100 refs_str ? ")" : "", new_commit_brief_str);
10101 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10102 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10103 free(refs_str);
10104 refs_str = NULL;
10106 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10107 if (err)
10108 goto done;
10110 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10111 if (err)
10112 goto done;
10114 err = got_object_id_str(&yca_id_str, yca_id);
10115 if (err)
10116 goto done;
10118 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10119 if (refs) {
10120 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10121 if (err)
10122 goto done;
10124 printf("history forked at %s%s%s%s\n %s\n",
10125 yca_id_str,
10126 refs_str ? " (" : "", refs_str ? refs_str : "",
10127 refs_str ? ")" : "", yca_brief_str);
10129 done:
10130 free(custom_refs_str);
10131 free(new_commit_id);
10132 free(refs_str);
10133 free(yca_id);
10134 free(yca_id_str);
10135 free(yca_brief_str);
10136 if (new_commit)
10137 got_object_commit_close(new_commit);
10138 if (yca_commit)
10139 got_object_commit_close(yca_commit);
10141 return NULL;
10144 static const struct got_error *
10145 process_backup_refs(const char *backup_ref_prefix,
10146 const char *wanted_branch_name,
10147 int delete, struct got_repository *repo)
10149 const struct got_error *err;
10150 struct got_reflist_head refs, backup_refs;
10151 struct got_reflist_entry *re;
10152 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10153 struct got_object_id *old_commit_id = NULL;
10154 char *branch_name = NULL;
10155 struct got_commit_object *old_commit = NULL;
10156 struct got_reflist_object_id_map *refs_idmap = NULL;
10157 int wanted_branch_found = 0;
10159 TAILQ_INIT(&refs);
10160 TAILQ_INIT(&backup_refs);
10162 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10163 if (err)
10164 return err;
10166 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10167 if (err)
10168 goto done;
10170 if (wanted_branch_name) {
10171 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10172 wanted_branch_name += 11;
10175 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10176 got_ref_cmp_by_commit_timestamp_descending, repo);
10177 if (err)
10178 goto done;
10180 TAILQ_FOREACH(re, &backup_refs, entry) {
10181 const char *refname = got_ref_get_name(re->ref);
10182 char *slash;
10184 err = check_cancelled(NULL);
10185 if (err)
10186 break;
10188 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10189 if (err)
10190 break;
10192 err = got_object_open_as_commit(&old_commit, repo,
10193 old_commit_id);
10194 if (err)
10195 break;
10197 if (strncmp(backup_ref_prefix, refname,
10198 backup_ref_prefix_len) == 0)
10199 refname += backup_ref_prefix_len;
10201 while (refname[0] == '/')
10202 refname++;
10204 branch_name = strdup(refname);
10205 if (branch_name == NULL) {
10206 err = got_error_from_errno("strdup");
10207 break;
10209 slash = strrchr(branch_name, '/');
10210 if (slash) {
10211 *slash = '\0';
10212 refname += strlen(branch_name) + 1;
10215 if (wanted_branch_name == NULL ||
10216 strcmp(wanted_branch_name, branch_name) == 0) {
10217 wanted_branch_found = 1;
10218 if (delete) {
10219 err = delete_backup_ref(re->ref,
10220 old_commit_id, repo);
10221 } else {
10222 err = print_backup_ref(branch_name, refname,
10223 old_commit_id, old_commit, refs_idmap,
10224 repo);
10226 if (err)
10227 break;
10230 free(old_commit_id);
10231 old_commit_id = NULL;
10232 free(branch_name);
10233 branch_name = NULL;
10234 got_object_commit_close(old_commit);
10235 old_commit = NULL;
10238 if (wanted_branch_name && !wanted_branch_found) {
10239 err = got_error_fmt(GOT_ERR_NOT_REF,
10240 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10242 done:
10243 if (refs_idmap)
10244 got_reflist_object_id_map_free(refs_idmap);
10245 got_ref_list_free(&refs);
10246 got_ref_list_free(&backup_refs);
10247 free(old_commit_id);
10248 free(branch_name);
10249 if (old_commit)
10250 got_object_commit_close(old_commit);
10251 return err;
10254 static const struct got_error *
10255 abort_progress(void *arg, unsigned char status, const char *path)
10258 * Unversioned files should not clutter progress output when
10259 * an operation is aborted.
10261 if (status == GOT_STATUS_UNVERSIONED)
10262 return NULL;
10264 return update_progress(arg, status, path);
10267 static const struct got_error *
10268 cmd_rebase(int argc, char *argv[])
10270 const struct got_error *error = NULL;
10271 struct got_worktree *worktree = NULL;
10272 struct got_repository *repo = NULL;
10273 struct got_fileindex *fileindex = NULL;
10274 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10275 struct got_reference *branch = NULL;
10276 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10277 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10278 struct got_object_id *resume_commit_id = NULL;
10279 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10280 struct got_object_id *head_commit_id = NULL;
10281 struct got_reference *head_ref = NULL;
10282 struct got_commit_object *commit = NULL;
10283 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10284 int histedit_in_progress = 0, merge_in_progress = 0;
10285 int create_backup = 1, list_backups = 0, delete_backups = 0;
10286 struct got_object_id_queue commits;
10287 struct got_pathlist_head merged_paths;
10288 const struct got_object_id_queue *parent_ids;
10289 struct got_object_qid *qid, *pid;
10290 struct got_update_progress_arg upa;
10291 int *pack_fds = NULL;
10293 STAILQ_INIT(&commits);
10294 TAILQ_INIT(&merged_paths);
10295 memset(&upa, 0, sizeof(upa));
10297 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10298 switch (ch) {
10299 case 'a':
10300 abort_rebase = 1;
10301 break;
10302 case 'c':
10303 continue_rebase = 1;
10304 break;
10305 case 'l':
10306 list_backups = 1;
10307 break;
10308 case 'X':
10309 delete_backups = 1;
10310 break;
10311 default:
10312 usage_rebase();
10313 /* NOTREACHED */
10317 argc -= optind;
10318 argv += optind;
10320 #ifndef PROFILE
10321 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10322 "unveil", NULL) == -1)
10323 err(1, "pledge");
10324 #endif
10325 if (list_backups) {
10326 if (abort_rebase)
10327 option_conflict('l', 'a');
10328 if (continue_rebase)
10329 option_conflict('l', 'c');
10330 if (delete_backups)
10331 option_conflict('l', 'X');
10332 if (argc != 0 && argc != 1)
10333 usage_rebase();
10334 } else if (delete_backups) {
10335 if (abort_rebase)
10336 option_conflict('X', 'a');
10337 if (continue_rebase)
10338 option_conflict('X', 'c');
10339 if (list_backups)
10340 option_conflict('l', 'X');
10341 if (argc != 0 && argc != 1)
10342 usage_rebase();
10343 } else {
10344 if (abort_rebase && continue_rebase)
10345 usage_rebase();
10346 else if (abort_rebase || continue_rebase) {
10347 if (argc != 0)
10348 usage_rebase();
10349 } else if (argc != 1)
10350 usage_rebase();
10353 cwd = getcwd(NULL, 0);
10354 if (cwd == NULL) {
10355 error = got_error_from_errno("getcwd");
10356 goto done;
10359 error = got_repo_pack_fds_open(&pack_fds);
10360 if (error != NULL)
10361 goto done;
10363 error = got_worktree_open(&worktree, cwd);
10364 if (error) {
10365 if (list_backups || delete_backups) {
10366 if (error->code != GOT_ERR_NOT_WORKTREE)
10367 goto done;
10368 } else {
10369 if (error->code == GOT_ERR_NOT_WORKTREE)
10370 error = wrap_not_worktree_error(error,
10371 "rebase", cwd);
10372 goto done;
10376 error = get_gitconfig_path(&gitconfig_path);
10377 if (error)
10378 goto done;
10379 error = got_repo_open(&repo,
10380 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10381 gitconfig_path, pack_fds);
10382 if (error != NULL)
10383 goto done;
10385 error = get_author(&committer, repo, worktree);
10386 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
10387 goto done;
10389 error = apply_unveil(got_repo_get_path(repo), 0,
10390 worktree ? got_worktree_get_root_path(worktree) : NULL);
10391 if (error)
10392 goto done;
10394 if (list_backups || delete_backups) {
10395 error = process_backup_refs(
10396 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
10397 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10398 goto done; /* nothing else to do */
10401 error = got_worktree_histedit_in_progress(&histedit_in_progress,
10402 worktree);
10403 if (error)
10404 goto done;
10405 if (histedit_in_progress) {
10406 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10407 goto done;
10410 error = got_worktree_merge_in_progress(&merge_in_progress,
10411 worktree, repo);
10412 if (error)
10413 goto done;
10414 if (merge_in_progress) {
10415 error = got_error(GOT_ERR_MERGE_BUSY);
10416 goto done;
10419 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10420 if (error)
10421 goto done;
10423 if (abort_rebase) {
10424 if (!rebase_in_progress) {
10425 error = got_error(GOT_ERR_NOT_REBASING);
10426 goto done;
10428 error = got_worktree_rebase_continue(&resume_commit_id,
10429 &new_base_branch, &tmp_branch, &branch, &fileindex,
10430 worktree, repo);
10431 if (error)
10432 goto done;
10433 printf("Switching work tree to %s\n",
10434 got_ref_get_symref_target(new_base_branch));
10435 error = got_worktree_rebase_abort(worktree, fileindex, repo,
10436 new_base_branch, abort_progress, &upa);
10437 if (error)
10438 goto done;
10439 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
10440 print_merge_progress_stats(&upa);
10441 goto done; /* nothing else to do */
10444 if (continue_rebase) {
10445 if (!rebase_in_progress) {
10446 error = got_error(GOT_ERR_NOT_REBASING);
10447 goto done;
10449 error = got_worktree_rebase_continue(&resume_commit_id,
10450 &new_base_branch, &tmp_branch, &branch, &fileindex,
10451 worktree, repo);
10452 if (error)
10453 goto done;
10455 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
10456 committer, resume_commit_id, repo);
10457 if (error)
10458 goto done;
10460 yca_id = got_object_id_dup(resume_commit_id);
10461 if (yca_id == NULL) {
10462 error = got_error_from_errno("got_object_id_dup");
10463 goto done;
10465 } else {
10466 error = got_ref_open(&branch, repo, argv[0], 0);
10467 if (error != NULL)
10468 goto done;
10469 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10470 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10471 "will not rebase a branch which lives outside "
10472 "the \"refs/heads/\" reference namespace");
10473 goto done;
10477 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
10478 if (error)
10479 goto done;
10481 if (!continue_rebase) {
10482 struct got_object_id *base_commit_id;
10484 error = got_ref_open(&head_ref, repo,
10485 got_worktree_get_head_ref_name(worktree), 0);
10486 if (error)
10487 goto done;
10488 error = got_ref_resolve(&head_commit_id, repo, head_ref);
10489 if (error)
10490 goto done;
10491 base_commit_id = got_worktree_get_base_commit_id(worktree);
10492 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
10493 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
10494 goto done;
10497 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10498 base_commit_id, branch_head_commit_id, 1, repo,
10499 check_cancelled, NULL);
10500 if (error)
10501 goto done;
10502 if (yca_id == NULL) {
10503 error = got_error_msg(GOT_ERR_ANCESTRY,
10504 "specified branch shares no common ancestry "
10505 "with work tree's branch");
10506 goto done;
10509 error = check_same_branch(base_commit_id, branch, yca_id, repo);
10510 if (error) {
10511 if (error->code != GOT_ERR_ANCESTRY)
10512 goto done;
10513 error = NULL;
10514 } else {
10515 struct got_pathlist_head paths;
10516 printf("%s is already based on %s\n",
10517 got_ref_get_name(branch),
10518 got_worktree_get_head_ref_name(worktree));
10519 error = switch_head_ref(branch, branch_head_commit_id,
10520 worktree, repo);
10521 if (error)
10522 goto done;
10523 error = got_worktree_set_base_commit_id(worktree, repo,
10524 branch_head_commit_id);
10525 if (error)
10526 goto done;
10527 TAILQ_INIT(&paths);
10528 error = got_pathlist_append(&paths, "", NULL);
10529 if (error)
10530 goto done;
10531 error = got_worktree_checkout_files(worktree,
10532 &paths, repo, update_progress, &upa,
10533 check_cancelled, NULL);
10534 got_pathlist_free(&paths);
10535 if (error)
10536 goto done;
10537 if (upa.did_something) {
10538 char *id_str;
10539 error = got_object_id_str(&id_str,
10540 branch_head_commit_id);
10541 if (error)
10542 goto done;
10543 printf("Updated to %s: %s\n",
10544 got_worktree_get_head_ref_name(worktree),
10545 id_str);
10546 free(id_str);
10547 } else
10548 printf("Already up-to-date\n");
10549 print_update_progress_stats(&upa);
10550 goto done;
10554 commit_id = branch_head_commit_id;
10555 error = got_object_open_as_commit(&commit, repo, commit_id);
10556 if (error)
10557 goto done;
10559 parent_ids = got_object_commit_get_parent_ids(commit);
10560 pid = STAILQ_FIRST(parent_ids);
10561 if (pid == NULL) {
10562 error = got_error(GOT_ERR_EMPTY_REBASE);
10563 goto done;
10565 error = collect_commits(&commits, commit_id, &pid->id,
10566 yca_id, got_worktree_get_path_prefix(worktree),
10567 GOT_ERR_REBASE_PATH, repo);
10568 got_object_commit_close(commit);
10569 commit = NULL;
10570 if (error)
10571 goto done;
10573 if (!continue_rebase) {
10574 error = got_worktree_rebase_prepare(&new_base_branch,
10575 &tmp_branch, &fileindex, worktree, branch, repo);
10576 if (error)
10577 goto done;
10580 if (STAILQ_EMPTY(&commits)) {
10581 if (continue_rebase) {
10582 error = rebase_complete(worktree, fileindex,
10583 branch, new_base_branch, tmp_branch, repo,
10584 create_backup);
10585 goto done;
10586 } else {
10587 /* Fast-forward the reference of the branch. */
10588 struct got_object_id *new_head_commit_id;
10589 char *id_str;
10590 error = got_ref_resolve(&new_head_commit_id, repo,
10591 new_base_branch);
10592 if (error)
10593 goto done;
10594 error = got_object_id_str(&id_str, new_head_commit_id);
10595 if (error)
10596 goto done;
10597 printf("Forwarding %s to commit %s\n",
10598 got_ref_get_name(branch), id_str);
10599 free(id_str);
10600 error = got_ref_change_ref(branch,
10601 new_head_commit_id);
10602 if (error)
10603 goto done;
10604 /* No backup needed since objects did not change. */
10605 create_backup = 0;
10609 pid = NULL;
10610 STAILQ_FOREACH(qid, &commits, entry) {
10612 commit_id = &qid->id;
10613 parent_id = pid ? &pid->id : yca_id;
10614 pid = qid;
10616 memset(&upa, 0, sizeof(upa));
10617 error = got_worktree_rebase_merge_files(&merged_paths,
10618 worktree, fileindex, parent_id, commit_id, repo,
10619 update_progress, &upa, check_cancelled, NULL);
10620 if (error)
10621 goto done;
10623 print_merge_progress_stats(&upa);
10624 if (upa.conflicts > 0 || upa.missing > 0 ||
10625 upa.not_deleted > 0 || upa.unversioned > 0) {
10626 if (upa.conflicts > 0) {
10627 error = show_rebase_merge_conflict(&qid->id,
10628 repo);
10629 if (error)
10630 goto done;
10632 got_worktree_rebase_pathlist_free(&merged_paths);
10633 break;
10636 error = rebase_commit(&merged_paths, worktree, fileindex,
10637 tmp_branch, committer, commit_id, repo);
10638 got_worktree_rebase_pathlist_free(&merged_paths);
10639 if (error)
10640 goto done;
10643 if (upa.conflicts > 0 || upa.missing > 0 ||
10644 upa.not_deleted > 0 || upa.unversioned > 0) {
10645 error = got_worktree_rebase_postpone(worktree, fileindex);
10646 if (error)
10647 goto done;
10648 if (upa.conflicts > 0 && upa.missing == 0 &&
10649 upa.not_deleted == 0 && upa.unversioned == 0) {
10650 error = got_error_msg(GOT_ERR_CONFLICTS,
10651 "conflicts must be resolved before rebasing "
10652 "can continue");
10653 } else if (upa.conflicts > 0) {
10654 error = got_error_msg(GOT_ERR_CONFLICTS,
10655 "conflicts must be resolved before rebasing "
10656 "can continue; changes destined for some "
10657 "files were not yet merged and should be "
10658 "merged manually if required before the "
10659 "rebase operation is continued");
10660 } else {
10661 error = got_error_msg(GOT_ERR_CONFLICTS,
10662 "changes destined for some files were not "
10663 "yet merged and should be merged manually "
10664 "if required before the rebase operation "
10665 "is continued");
10667 } else
10668 error = rebase_complete(worktree, fileindex, branch,
10669 new_base_branch, tmp_branch, repo, create_backup);
10670 done:
10671 free(cwd);
10672 free(committer);
10673 free(gitconfig_path);
10674 got_object_id_queue_free(&commits);
10675 free(branch_head_commit_id);
10676 free(resume_commit_id);
10677 free(head_commit_id);
10678 free(yca_id);
10679 if (commit)
10680 got_object_commit_close(commit);
10681 if (branch)
10682 got_ref_close(branch);
10683 if (new_base_branch)
10684 got_ref_close(new_base_branch);
10685 if (tmp_branch)
10686 got_ref_close(tmp_branch);
10687 if (head_ref)
10688 got_ref_close(head_ref);
10689 if (worktree)
10690 got_worktree_close(worktree);
10691 if (repo) {
10692 const struct got_error *close_err = got_repo_close(repo);
10693 if (error == NULL)
10694 error = close_err;
10696 if (pack_fds) {
10697 const struct got_error *pack_err =
10698 got_repo_pack_fds_close(pack_fds);
10699 if (error == NULL)
10700 error = pack_err;
10702 return error;
10705 __dead static void
10706 usage_histedit(void)
10708 fprintf(stderr, "usage: %s histedit [-aceflmX] [-F histedit-script] "
10709 "[branch]\n", getprogname());
10710 exit(1);
10713 #define GOT_HISTEDIT_PICK 'p'
10714 #define GOT_HISTEDIT_EDIT 'e'
10715 #define GOT_HISTEDIT_FOLD 'f'
10716 #define GOT_HISTEDIT_DROP 'd'
10717 #define GOT_HISTEDIT_MESG 'm'
10719 static const struct got_histedit_cmd {
10720 unsigned char code;
10721 const char *name;
10722 const char *desc;
10723 } got_histedit_cmds[] = {
10724 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10725 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10726 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10727 "be used" },
10728 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10729 { GOT_HISTEDIT_MESG, "mesg",
10730 "single-line log message for commit above (open editor if empty)" },
10733 struct got_histedit_list_entry {
10734 TAILQ_ENTRY(got_histedit_list_entry) entry;
10735 struct got_object_id *commit_id;
10736 const struct got_histedit_cmd *cmd;
10737 char *logmsg;
10739 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10741 static const struct got_error *
10742 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10743 FILE *f, struct got_repository *repo)
10745 const struct got_error *err = NULL;
10746 char *logmsg = NULL, *id_str = NULL;
10747 struct got_commit_object *commit = NULL;
10748 int n;
10750 err = got_object_open_as_commit(&commit, repo, commit_id);
10751 if (err)
10752 goto done;
10754 err = get_short_logmsg(&logmsg, 34, commit);
10755 if (err)
10756 goto done;
10758 err = got_object_id_str(&id_str, commit_id);
10759 if (err)
10760 goto done;
10762 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10763 if (n < 0)
10764 err = got_ferror(f, GOT_ERR_IO);
10765 done:
10766 if (commit)
10767 got_object_commit_close(commit);
10768 free(id_str);
10769 free(logmsg);
10770 return err;
10773 static const struct got_error *
10774 histedit_write_commit_list(struct got_object_id_queue *commits,
10775 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10776 struct got_repository *repo)
10778 const struct got_error *err = NULL;
10779 struct got_object_qid *qid;
10780 const char *histedit_cmd = NULL;
10782 if (STAILQ_EMPTY(commits))
10783 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10785 STAILQ_FOREACH(qid, commits, entry) {
10786 histedit_cmd = got_histedit_cmds[0].name;
10787 if (edit_only)
10788 histedit_cmd = "edit";
10789 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10790 histedit_cmd = "fold";
10791 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10792 if (err)
10793 break;
10794 if (edit_logmsg_only) {
10795 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10796 if (n < 0) {
10797 err = got_ferror(f, GOT_ERR_IO);
10798 break;
10803 return err;
10806 static const struct got_error *
10807 write_cmd_list(FILE *f, const char *branch_name,
10808 struct got_object_id_queue *commits)
10810 const struct got_error *err = NULL;
10811 size_t i;
10812 int n;
10813 char *id_str;
10814 struct got_object_qid *qid;
10816 qid = STAILQ_FIRST(commits);
10817 err = got_object_id_str(&id_str, &qid->id);
10818 if (err)
10819 return err;
10821 n = fprintf(f,
10822 "# Editing the history of branch '%s' starting at\n"
10823 "# commit %s\n"
10824 "# Commits will be processed in order from top to "
10825 "bottom of this file.\n", branch_name, id_str);
10826 if (n < 0) {
10827 err = got_ferror(f, GOT_ERR_IO);
10828 goto done;
10831 n = fprintf(f, "# Available histedit commands:\n");
10832 if (n < 0) {
10833 err = got_ferror(f, GOT_ERR_IO);
10834 goto done;
10837 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10838 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10839 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10840 cmd->desc);
10841 if (n < 0) {
10842 err = got_ferror(f, GOT_ERR_IO);
10843 break;
10846 done:
10847 free(id_str);
10848 return err;
10851 static const struct got_error *
10852 histedit_syntax_error(int lineno)
10854 static char msg[42];
10855 int ret;
10857 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10858 lineno);
10859 if (ret < 0 || (size_t)ret >= sizeof(msg))
10860 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10862 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10865 static const struct got_error *
10866 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10867 char *logmsg, struct got_repository *repo)
10869 const struct got_error *err;
10870 struct got_commit_object *folded_commit = NULL;
10871 char *id_str, *folded_logmsg = NULL;
10873 err = got_object_id_str(&id_str, hle->commit_id);
10874 if (err)
10875 return err;
10877 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10878 if (err)
10879 goto done;
10881 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10882 if (err)
10883 goto done;
10884 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10885 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10886 folded_logmsg) == -1) {
10887 err = got_error_from_errno("asprintf");
10889 done:
10890 if (folded_commit)
10891 got_object_commit_close(folded_commit);
10892 free(id_str);
10893 free(folded_logmsg);
10894 return err;
10897 static struct got_histedit_list_entry *
10898 get_folded_commits(struct got_histedit_list_entry *hle)
10900 struct got_histedit_list_entry *prev, *folded = NULL;
10902 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10903 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10904 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10905 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10906 folded = prev;
10907 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10910 return folded;
10913 static const struct got_error *
10914 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10915 struct got_repository *repo)
10917 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10918 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10919 const struct got_error *err = NULL;
10920 struct got_commit_object *commit = NULL;
10921 int logmsg_len;
10922 int fd;
10923 struct got_histedit_list_entry *folded = NULL;
10925 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10926 if (err)
10927 return err;
10929 folded = get_folded_commits(hle);
10930 if (folded) {
10931 while (folded != hle) {
10932 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10933 folded = TAILQ_NEXT(folded, entry);
10934 continue;
10936 err = append_folded_commit_msg(&new_msg, folded,
10937 logmsg, repo);
10938 if (err)
10939 goto done;
10940 free(logmsg);
10941 logmsg = new_msg;
10942 folded = TAILQ_NEXT(folded, entry);
10946 err = got_object_id_str(&id_str, hle->commit_id);
10947 if (err)
10948 goto done;
10949 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10950 if (err)
10951 goto done;
10952 logmsg_len = asprintf(&new_msg,
10953 "%s\n# original log message of commit %s: %s",
10954 logmsg ? logmsg : "", id_str, orig_logmsg);
10955 if (logmsg_len == -1) {
10956 err = got_error_from_errno("asprintf");
10957 goto done;
10959 free(logmsg);
10960 logmsg = new_msg;
10962 err = got_object_id_str(&id_str, hle->commit_id);
10963 if (err)
10964 goto done;
10966 err = got_opentemp_named_fd(&logmsg_path, &fd,
10967 GOT_TMPDIR_STR "/got-logmsg", "");
10968 if (err)
10969 goto done;
10971 write(fd, logmsg, logmsg_len);
10972 close(fd);
10974 err = get_editor(&editor);
10975 if (err)
10976 goto done;
10978 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10979 logmsg_len, 0);
10980 if (err) {
10981 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10982 goto done;
10983 err = NULL;
10984 hle->logmsg = strdup(new_msg);
10985 if (hle->logmsg == NULL)
10986 err = got_error_from_errno("strdup");
10988 done:
10989 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10990 err = got_error_from_errno2("unlink", logmsg_path);
10991 free(logmsg_path);
10992 free(logmsg);
10993 free(orig_logmsg);
10994 free(editor);
10995 if (commit)
10996 got_object_commit_close(commit);
10997 return err;
11000 static const struct got_error *
11001 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11002 FILE *f, struct got_repository *repo)
11004 const struct got_error *err = NULL;
11005 char *line = NULL, *p, *end;
11006 size_t i, size;
11007 ssize_t len;
11008 int lineno = 0, lastcmd = -1;
11009 const struct got_histedit_cmd *cmd;
11010 struct got_object_id *commit_id = NULL;
11011 struct got_histedit_list_entry *hle = NULL;
11013 for (;;) {
11014 len = getline(&line, &size, f);
11015 if (len == -1) {
11016 const struct got_error *getline_err;
11017 if (feof(f))
11018 break;
11019 getline_err = got_error_from_errno("getline");
11020 err = got_ferror(f, getline_err->code);
11021 break;
11023 lineno++;
11024 p = line;
11025 while (isspace((unsigned char)p[0]))
11026 p++;
11027 if (p[0] == '#' || p[0] == '\0') {
11028 free(line);
11029 line = NULL;
11030 continue;
11032 cmd = NULL;
11033 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11034 cmd = &got_histedit_cmds[i];
11035 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11036 isspace((unsigned char)p[strlen(cmd->name)])) {
11037 p += strlen(cmd->name);
11038 break;
11040 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11041 p++;
11042 break;
11045 if (i == nitems(got_histedit_cmds)) {
11046 err = histedit_syntax_error(lineno);
11047 break;
11049 while (isspace((unsigned char)p[0]))
11050 p++;
11051 if (cmd->code == GOT_HISTEDIT_MESG) {
11052 if (lastcmd != GOT_HISTEDIT_PICK &&
11053 lastcmd != GOT_HISTEDIT_EDIT) {
11054 err = got_error(GOT_ERR_HISTEDIT_CMD);
11055 break;
11057 if (p[0] == '\0') {
11058 err = histedit_edit_logmsg(hle, repo);
11059 if (err)
11060 break;
11061 } else {
11062 hle->logmsg = strdup(p);
11063 if (hle->logmsg == NULL) {
11064 err = got_error_from_errno("strdup");
11065 break;
11068 free(line);
11069 line = NULL;
11070 lastcmd = cmd->code;
11071 continue;
11072 } else {
11073 end = p;
11074 while (end[0] && !isspace((unsigned char)end[0]))
11075 end++;
11076 *end = '\0';
11078 err = got_object_resolve_id_str(&commit_id, repo, p);
11079 if (err) {
11080 /* override error code */
11081 err = histedit_syntax_error(lineno);
11082 break;
11085 hle = malloc(sizeof(*hle));
11086 if (hle == NULL) {
11087 err = got_error_from_errno("malloc");
11088 break;
11090 hle->cmd = cmd;
11091 hle->commit_id = commit_id;
11092 hle->logmsg = NULL;
11093 commit_id = NULL;
11094 free(line);
11095 line = NULL;
11096 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11097 lastcmd = cmd->code;
11100 free(line);
11101 free(commit_id);
11102 return err;
11105 static const struct got_error *
11106 histedit_check_script(struct got_histedit_list *histedit_cmds,
11107 struct got_object_id_queue *commits, struct got_repository *repo)
11109 const struct got_error *err = NULL;
11110 struct got_object_qid *qid;
11111 struct got_histedit_list_entry *hle;
11112 static char msg[92];
11113 char *id_str;
11115 if (TAILQ_EMPTY(histedit_cmds))
11116 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11117 "histedit script contains no commands");
11118 if (STAILQ_EMPTY(commits))
11119 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11121 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11122 struct got_histedit_list_entry *hle2;
11123 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11124 if (hle == hle2)
11125 continue;
11126 if (got_object_id_cmp(hle->commit_id,
11127 hle2->commit_id) != 0)
11128 continue;
11129 err = got_object_id_str(&id_str, hle->commit_id);
11130 if (err)
11131 return err;
11132 snprintf(msg, sizeof(msg), "commit %s is listed "
11133 "more than once in histedit script", id_str);
11134 free(id_str);
11135 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11139 STAILQ_FOREACH(qid, commits, entry) {
11140 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11141 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11142 break;
11144 if (hle == NULL) {
11145 err = got_object_id_str(&id_str, &qid->id);
11146 if (err)
11147 return err;
11148 snprintf(msg, sizeof(msg),
11149 "commit %s missing from histedit script", id_str);
11150 free(id_str);
11151 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11155 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11156 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11157 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11158 "last commit in histedit script cannot be folded");
11160 return NULL;
11163 static const struct got_error *
11164 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11165 const char *path, struct got_object_id_queue *commits,
11166 struct got_repository *repo)
11168 const struct got_error *err = NULL;
11169 char *editor;
11170 FILE *f = NULL;
11172 err = get_editor(&editor);
11173 if (err)
11174 return err;
11176 if (spawn_editor(editor, path) == -1) {
11177 err = got_error_from_errno("failed spawning editor");
11178 goto done;
11181 f = fopen(path, "re");
11182 if (f == NULL) {
11183 err = got_error_from_errno("fopen");
11184 goto done;
11186 err = histedit_parse_list(histedit_cmds, f, repo);
11187 if (err)
11188 goto done;
11190 err = histedit_check_script(histedit_cmds, commits, repo);
11191 done:
11192 if (f && fclose(f) == EOF && err == NULL)
11193 err = got_error_from_errno("fclose");
11194 free(editor);
11195 return err;
11198 static const struct got_error *
11199 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
11200 struct got_object_id_queue *, const char *, const char *,
11201 struct got_repository *);
11203 static const struct got_error *
11204 histedit_edit_script(struct got_histedit_list *histedit_cmds,
11205 struct got_object_id_queue *commits, const char *branch_name,
11206 int edit_logmsg_only, int fold_only, int edit_only,
11207 struct got_repository *repo)
11209 const struct got_error *err;
11210 FILE *f = NULL;
11211 char *path = NULL;
11213 err = got_opentemp_named(&path, &f, "got-histedit", "");
11214 if (err)
11215 return err;
11217 err = write_cmd_list(f, branch_name, commits);
11218 if (err)
11219 goto done;
11221 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
11222 fold_only, edit_only, repo);
11223 if (err)
11224 goto done;
11226 if (edit_logmsg_only || fold_only || edit_only) {
11227 rewind(f);
11228 err = histedit_parse_list(histedit_cmds, f, repo);
11229 } else {
11230 if (fclose(f) == EOF) {
11231 err = got_error_from_errno("fclose");
11232 goto done;
11234 f = NULL;
11235 err = histedit_run_editor(histedit_cmds, path, commits, repo);
11236 if (err) {
11237 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11238 err->code != GOT_ERR_HISTEDIT_CMD)
11239 goto done;
11240 err = histedit_edit_list_retry(histedit_cmds, err,
11241 commits, path, branch_name, repo);
11244 done:
11245 if (f && fclose(f) == EOF && err == NULL)
11246 err = got_error_from_errno("fclose");
11247 if (path && unlink(path) != 0 && err == NULL)
11248 err = got_error_from_errno2("unlink", path);
11249 free(path);
11250 return err;
11253 static const struct got_error *
11254 histedit_save_list(struct got_histedit_list *histedit_cmds,
11255 struct got_worktree *worktree, struct got_repository *repo)
11257 const struct got_error *err = NULL;
11258 char *path = NULL;
11259 FILE *f = NULL;
11260 struct got_histedit_list_entry *hle;
11261 struct got_commit_object *commit = NULL;
11263 err = got_worktree_get_histedit_script_path(&path, worktree);
11264 if (err)
11265 return err;
11267 f = fopen(path, "we");
11268 if (f == NULL) {
11269 err = got_error_from_errno2("fopen", path);
11270 goto done;
11272 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11273 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
11274 repo);
11275 if (err)
11276 break;
11278 if (hle->logmsg) {
11279 int n = fprintf(f, "%c %s\n",
11280 GOT_HISTEDIT_MESG, hle->logmsg);
11281 if (n < 0) {
11282 err = got_ferror(f, GOT_ERR_IO);
11283 break;
11287 done:
11288 if (f && fclose(f) == EOF && err == NULL)
11289 err = got_error_from_errno("fclose");
11290 free(path);
11291 if (commit)
11292 got_object_commit_close(commit);
11293 return err;
11296 static void
11297 histedit_free_list(struct got_histedit_list *histedit_cmds)
11299 struct got_histedit_list_entry *hle;
11301 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11302 TAILQ_REMOVE(histedit_cmds, hle, entry);
11303 free(hle);
11307 static const struct got_error *
11308 histedit_load_list(struct got_histedit_list *histedit_cmds,
11309 const char *path, struct got_repository *repo)
11311 const struct got_error *err = NULL;
11312 FILE *f = NULL;
11314 f = fopen(path, "re");
11315 if (f == NULL) {
11316 err = got_error_from_errno2("fopen", path);
11317 goto done;
11320 err = histedit_parse_list(histedit_cmds, f, repo);
11321 done:
11322 if (f && fclose(f) == EOF && err == NULL)
11323 err = got_error_from_errno("fclose");
11324 return err;
11327 static const struct got_error *
11328 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
11329 const struct got_error *edit_err, struct got_object_id_queue *commits,
11330 const char *path, const char *branch_name, struct got_repository *repo)
11332 const struct got_error *err = NULL, *prev_err = edit_err;
11333 int resp = ' ';
11335 while (resp != 'c' && resp != 'r' && resp != 'a') {
11336 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
11337 "or (a)bort: ", getprogname(), prev_err->msg);
11338 resp = getchar();
11339 if (resp == '\n')
11340 resp = getchar();
11341 if (resp == 'c') {
11342 histedit_free_list(histedit_cmds);
11343 err = histedit_run_editor(histedit_cmds, path, commits,
11344 repo);
11345 if (err) {
11346 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11347 err->code != GOT_ERR_HISTEDIT_CMD)
11348 break;
11349 prev_err = err;
11350 resp = ' ';
11351 continue;
11353 break;
11354 } else if (resp == 'r') {
11355 histedit_free_list(histedit_cmds);
11356 err = histedit_edit_script(histedit_cmds,
11357 commits, branch_name, 0, 0, 0, repo);
11358 if (err) {
11359 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11360 err->code != GOT_ERR_HISTEDIT_CMD)
11361 break;
11362 prev_err = err;
11363 resp = ' ';
11364 continue;
11366 break;
11367 } else if (resp == 'a') {
11368 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
11369 break;
11370 } else
11371 printf("invalid response '%c'\n", resp);
11374 return err;
11377 static const struct got_error *
11378 histedit_complete(struct got_worktree *worktree,
11379 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
11380 struct got_reference *branch, struct got_repository *repo)
11382 printf("Switching work tree to %s\n",
11383 got_ref_get_symref_target(branch));
11384 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
11385 branch, repo);
11388 static const struct got_error *
11389 show_histedit_progress(struct got_commit_object *commit,
11390 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
11392 const struct got_error *err;
11393 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
11395 err = got_object_id_str(&old_id_str, hle->commit_id);
11396 if (err)
11397 goto done;
11399 if (new_id) {
11400 err = got_object_id_str(&new_id_str, new_id);
11401 if (err)
11402 goto done;
11405 old_id_str[12] = '\0';
11406 if (new_id_str)
11407 new_id_str[12] = '\0';
11409 if (hle->logmsg) {
11410 logmsg = strdup(hle->logmsg);
11411 if (logmsg == NULL) {
11412 err = got_error_from_errno("strdup");
11413 goto done;
11415 trim_logmsg(logmsg, 42);
11416 } else {
11417 err = get_short_logmsg(&logmsg, 42, commit);
11418 if (err)
11419 goto done;
11422 switch (hle->cmd->code) {
11423 case GOT_HISTEDIT_PICK:
11424 case GOT_HISTEDIT_EDIT:
11425 printf("%s -> %s: %s\n", old_id_str,
11426 new_id_str ? new_id_str : "no-op change", logmsg);
11427 break;
11428 case GOT_HISTEDIT_DROP:
11429 case GOT_HISTEDIT_FOLD:
11430 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
11431 logmsg);
11432 break;
11433 default:
11434 break;
11436 done:
11437 free(old_id_str);
11438 free(new_id_str);
11439 return err;
11442 static const struct got_error *
11443 histedit_commit(struct got_pathlist_head *merged_paths,
11444 struct got_worktree *worktree, struct got_fileindex *fileindex,
11445 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
11446 const char *committer, struct got_repository *repo)
11448 const struct got_error *err;
11449 struct got_commit_object *commit;
11450 struct got_object_id *new_commit_id;
11452 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
11453 && hle->logmsg == NULL) {
11454 err = histedit_edit_logmsg(hle, repo);
11455 if (err)
11456 return err;
11459 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11460 if (err)
11461 return err;
11463 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
11464 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
11465 hle->logmsg, repo);
11466 if (err) {
11467 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
11468 goto done;
11469 err = show_histedit_progress(commit, hle, NULL);
11470 } else {
11471 err = show_histedit_progress(commit, hle, new_commit_id);
11472 free(new_commit_id);
11474 done:
11475 got_object_commit_close(commit);
11476 return err;
11479 static const struct got_error *
11480 histedit_skip_commit(struct got_histedit_list_entry *hle,
11481 struct got_worktree *worktree, struct got_repository *repo)
11483 const struct got_error *error;
11484 struct got_commit_object *commit;
11486 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
11487 repo);
11488 if (error)
11489 return error;
11491 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
11492 if (error)
11493 return error;
11495 error = show_histedit_progress(commit, hle, NULL);
11496 got_object_commit_close(commit);
11497 return error;
11500 static const struct got_error *
11501 check_local_changes(void *arg, unsigned char status,
11502 unsigned char staged_status, const char *path,
11503 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11504 struct got_object_id *commit_id, int dirfd, const char *de_name)
11506 int *have_local_changes = arg;
11508 switch (status) {
11509 case GOT_STATUS_ADD:
11510 case GOT_STATUS_DELETE:
11511 case GOT_STATUS_MODIFY:
11512 case GOT_STATUS_CONFLICT:
11513 *have_local_changes = 1;
11514 return got_error(GOT_ERR_CANCELLED);
11515 default:
11516 break;
11519 switch (staged_status) {
11520 case GOT_STATUS_ADD:
11521 case GOT_STATUS_DELETE:
11522 case GOT_STATUS_MODIFY:
11523 *have_local_changes = 1;
11524 return got_error(GOT_ERR_CANCELLED);
11525 default:
11526 break;
11529 return NULL;
11532 static const struct got_error *
11533 cmd_histedit(int argc, char *argv[])
11535 const struct got_error *error = NULL;
11536 struct got_worktree *worktree = NULL;
11537 struct got_fileindex *fileindex = NULL;
11538 struct got_repository *repo = NULL;
11539 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11540 struct got_reference *branch = NULL;
11541 struct got_reference *tmp_branch = NULL;
11542 struct got_object_id *resume_commit_id = NULL;
11543 struct got_object_id *base_commit_id = NULL;
11544 struct got_object_id *head_commit_id = NULL;
11545 struct got_commit_object *commit = NULL;
11546 int ch, rebase_in_progress = 0, merge_in_progress = 0;
11547 struct got_update_progress_arg upa;
11548 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
11549 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
11550 int list_backups = 0, delete_backups = 0;
11551 const char *edit_script_path = NULL;
11552 struct got_object_id_queue commits;
11553 struct got_pathlist_head merged_paths;
11554 const struct got_object_id_queue *parent_ids;
11555 struct got_object_qid *pid;
11556 struct got_histedit_list histedit_cmds;
11557 struct got_histedit_list_entry *hle;
11558 int *pack_fds = NULL;
11560 STAILQ_INIT(&commits);
11561 TAILQ_INIT(&histedit_cmds);
11562 TAILQ_INIT(&merged_paths);
11563 memset(&upa, 0, sizeof(upa));
11565 while ((ch = getopt(argc, argv, "aceF:flmX")) != -1) {
11566 switch (ch) {
11567 case 'a':
11568 abort_edit = 1;
11569 break;
11570 case 'c':
11571 continue_edit = 1;
11572 break;
11573 case 'e':
11574 edit_only = 1;
11575 break;
11576 case 'F':
11577 edit_script_path = optarg;
11578 break;
11579 case 'f':
11580 fold_only = 1;
11581 break;
11582 case 'l':
11583 list_backups = 1;
11584 break;
11585 case 'm':
11586 edit_logmsg_only = 1;
11587 break;
11588 case 'X':
11589 delete_backups = 1;
11590 break;
11591 default:
11592 usage_histedit();
11593 /* NOTREACHED */
11597 argc -= optind;
11598 argv += optind;
11600 #ifndef PROFILE
11601 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11602 "unveil", NULL) == -1)
11603 err(1, "pledge");
11604 #endif
11605 if (abort_edit && continue_edit)
11606 option_conflict('a', 'c');
11607 if (edit_script_path && edit_logmsg_only)
11608 option_conflict('F', 'm');
11609 if (abort_edit && edit_logmsg_only)
11610 option_conflict('a', 'm');
11611 if (continue_edit && edit_logmsg_only)
11612 option_conflict('c', 'm');
11613 if (abort_edit && fold_only)
11614 option_conflict('a', 'f');
11615 if (continue_edit && fold_only)
11616 option_conflict('c', 'f');
11617 if (fold_only && edit_logmsg_only)
11618 option_conflict('f', 'm');
11619 if (edit_script_path && fold_only)
11620 option_conflict('F', 'f');
11621 if (abort_edit && edit_only)
11622 option_conflict('a', 'e');
11623 if (continue_edit && edit_only)
11624 option_conflict('c', 'e');
11625 if (edit_only && edit_logmsg_only)
11626 option_conflict('e', 'm');
11627 if (edit_script_path && edit_only)
11628 option_conflict('F', 'e');
11629 if (list_backups) {
11630 if (abort_edit)
11631 option_conflict('l', 'a');
11632 if (continue_edit)
11633 option_conflict('l', 'c');
11634 if (edit_script_path)
11635 option_conflict('l', 'F');
11636 if (edit_logmsg_only)
11637 option_conflict('l', 'm');
11638 if (fold_only)
11639 option_conflict('l', 'f');
11640 if (edit_only)
11641 option_conflict('l', 'e');
11642 if (delete_backups)
11643 option_conflict('l', 'X');
11644 if (argc != 0 && argc != 1)
11645 usage_histedit();
11646 } else if (delete_backups) {
11647 if (abort_edit)
11648 option_conflict('X', 'a');
11649 if (continue_edit)
11650 option_conflict('X', 'c');
11651 if (edit_script_path)
11652 option_conflict('X', 'F');
11653 if (edit_logmsg_only)
11654 option_conflict('X', 'm');
11655 if (fold_only)
11656 option_conflict('X', 'f');
11657 if (edit_only)
11658 option_conflict('X', 'e');
11659 if (list_backups)
11660 option_conflict('X', 'l');
11661 if (argc != 0 && argc != 1)
11662 usage_histedit();
11663 } else if (argc != 0)
11664 usage_histedit();
11667 * This command cannot apply unveil(2) in all cases because the
11668 * user may choose to run an editor to edit the histedit script
11669 * and to edit individual commit log messages.
11670 * unveil(2) traverses exec(2); if an editor is used we have to
11671 * apply unveil after edit script and log messages have been written.
11672 * XXX TODO: Make use of unveil(2) where possible.
11675 cwd = getcwd(NULL, 0);
11676 if (cwd == NULL) {
11677 error = got_error_from_errno("getcwd");
11678 goto done;
11681 error = got_repo_pack_fds_open(&pack_fds);
11682 if (error != NULL)
11683 goto done;
11685 error = got_worktree_open(&worktree, cwd);
11686 if (error) {
11687 if (list_backups || delete_backups) {
11688 if (error->code != GOT_ERR_NOT_WORKTREE)
11689 goto done;
11690 } else {
11691 if (error->code == GOT_ERR_NOT_WORKTREE)
11692 error = wrap_not_worktree_error(error,
11693 "histedit", cwd);
11694 goto done;
11698 if (list_backups || delete_backups) {
11699 error = got_repo_open(&repo,
11700 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11701 NULL, pack_fds);
11702 if (error != NULL)
11703 goto done;
11704 error = apply_unveil(got_repo_get_path(repo), 0,
11705 worktree ? got_worktree_get_root_path(worktree) : NULL);
11706 if (error)
11707 goto done;
11708 error = process_backup_refs(
11709 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11710 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11711 goto done; /* nothing else to do */
11714 error = get_gitconfig_path(&gitconfig_path);
11715 if (error)
11716 goto done;
11717 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11718 gitconfig_path, pack_fds);
11719 if (error != NULL)
11720 goto done;
11722 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11723 if (error)
11724 goto done;
11725 if (rebase_in_progress) {
11726 error = got_error(GOT_ERR_REBASING);
11727 goto done;
11730 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11731 repo);
11732 if (error)
11733 goto done;
11734 if (merge_in_progress) {
11735 error = got_error(GOT_ERR_MERGE_BUSY);
11736 goto done;
11739 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11740 if (error)
11741 goto done;
11743 if (edit_in_progress && edit_logmsg_only) {
11744 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11745 "histedit operation is in progress in this "
11746 "work tree and must be continued or aborted "
11747 "before the -m option can be used");
11748 goto done;
11750 if (edit_in_progress && fold_only) {
11751 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11752 "histedit operation is in progress in this "
11753 "work tree and must be continued or aborted "
11754 "before the -f option can be used");
11755 goto done;
11757 if (edit_in_progress && edit_only) {
11758 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11759 "histedit operation is in progress in this "
11760 "work tree and must be continued or aborted "
11761 "before the -e option can be used");
11762 goto done;
11765 if (edit_in_progress && abort_edit) {
11766 error = got_worktree_histedit_continue(&resume_commit_id,
11767 &tmp_branch, &branch, &base_commit_id, &fileindex,
11768 worktree, repo);
11769 if (error)
11770 goto done;
11771 printf("Switching work tree to %s\n",
11772 got_ref_get_symref_target(branch));
11773 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11774 branch, base_commit_id, abort_progress, &upa);
11775 if (error)
11776 goto done;
11777 printf("Histedit of %s aborted\n",
11778 got_ref_get_symref_target(branch));
11779 print_merge_progress_stats(&upa);
11780 goto done; /* nothing else to do */
11781 } else if (abort_edit) {
11782 error = got_error(GOT_ERR_NOT_HISTEDIT);
11783 goto done;
11786 error = get_author(&committer, repo, worktree);
11787 if (error)
11788 goto done;
11790 if (continue_edit) {
11791 char *path;
11793 if (!edit_in_progress) {
11794 error = got_error(GOT_ERR_NOT_HISTEDIT);
11795 goto done;
11798 error = got_worktree_get_histedit_script_path(&path, worktree);
11799 if (error)
11800 goto done;
11802 error = histedit_load_list(&histedit_cmds, path, repo);
11803 free(path);
11804 if (error)
11805 goto done;
11807 error = got_worktree_histedit_continue(&resume_commit_id,
11808 &tmp_branch, &branch, &base_commit_id, &fileindex,
11809 worktree, repo);
11810 if (error)
11811 goto done;
11813 error = got_ref_resolve(&head_commit_id, repo, branch);
11814 if (error)
11815 goto done;
11817 error = got_object_open_as_commit(&commit, repo,
11818 head_commit_id);
11819 if (error)
11820 goto done;
11821 parent_ids = got_object_commit_get_parent_ids(commit);
11822 pid = STAILQ_FIRST(parent_ids);
11823 if (pid == NULL) {
11824 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11825 goto done;
11827 error = collect_commits(&commits, head_commit_id, &pid->id,
11828 base_commit_id, got_worktree_get_path_prefix(worktree),
11829 GOT_ERR_HISTEDIT_PATH, repo);
11830 got_object_commit_close(commit);
11831 commit = NULL;
11832 if (error)
11833 goto done;
11834 } else {
11835 if (edit_in_progress) {
11836 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11837 goto done;
11840 error = got_ref_open(&branch, repo,
11841 got_worktree_get_head_ref_name(worktree), 0);
11842 if (error != NULL)
11843 goto done;
11845 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11846 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11847 "will not edit commit history of a branch outside "
11848 "the \"refs/heads/\" reference namespace");
11849 goto done;
11852 error = got_ref_resolve(&head_commit_id, repo, branch);
11853 got_ref_close(branch);
11854 branch = NULL;
11855 if (error)
11856 goto done;
11858 error = got_object_open_as_commit(&commit, repo,
11859 head_commit_id);
11860 if (error)
11861 goto done;
11862 parent_ids = got_object_commit_get_parent_ids(commit);
11863 pid = STAILQ_FIRST(parent_ids);
11864 if (pid == NULL) {
11865 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11866 goto done;
11868 error = collect_commits(&commits, head_commit_id, &pid->id,
11869 got_worktree_get_base_commit_id(worktree),
11870 got_worktree_get_path_prefix(worktree),
11871 GOT_ERR_HISTEDIT_PATH, repo);
11872 got_object_commit_close(commit);
11873 commit = NULL;
11874 if (error)
11875 goto done;
11877 if (STAILQ_EMPTY(&commits)) {
11878 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11879 goto done;
11882 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11883 &base_commit_id, &fileindex, worktree, repo);
11884 if (error)
11885 goto done;
11887 if (edit_script_path) {
11888 error = histedit_load_list(&histedit_cmds,
11889 edit_script_path, repo);
11890 if (error) {
11891 got_worktree_histedit_abort(worktree, fileindex,
11892 repo, branch, base_commit_id,
11893 abort_progress, &upa);
11894 print_merge_progress_stats(&upa);
11895 goto done;
11897 } else {
11898 const char *branch_name;
11899 branch_name = got_ref_get_symref_target(branch);
11900 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11901 branch_name += 11;
11902 error = histedit_edit_script(&histedit_cmds, &commits,
11903 branch_name, edit_logmsg_only, fold_only,
11904 edit_only, repo);
11905 if (error) {
11906 got_worktree_histedit_abort(worktree, fileindex,
11907 repo, branch, base_commit_id,
11908 abort_progress, &upa);
11909 print_merge_progress_stats(&upa);
11910 goto done;
11915 error = histedit_save_list(&histedit_cmds, worktree,
11916 repo);
11917 if (error) {
11918 got_worktree_histedit_abort(worktree, fileindex,
11919 repo, branch, base_commit_id,
11920 abort_progress, &upa);
11921 print_merge_progress_stats(&upa);
11922 goto done;
11927 error = histedit_check_script(&histedit_cmds, &commits, repo);
11928 if (error)
11929 goto done;
11931 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11932 if (resume_commit_id) {
11933 if (got_object_id_cmp(hle->commit_id,
11934 resume_commit_id) != 0)
11935 continue;
11937 resume_commit_id = NULL;
11938 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11939 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11940 error = histedit_skip_commit(hle, worktree,
11941 repo);
11942 if (error)
11943 goto done;
11944 } else {
11945 struct got_pathlist_head paths;
11946 int have_changes = 0;
11948 TAILQ_INIT(&paths);
11949 error = got_pathlist_append(&paths, "", NULL);
11950 if (error)
11951 goto done;
11952 error = got_worktree_status(worktree, &paths,
11953 repo, 0, check_local_changes, &have_changes,
11954 check_cancelled, NULL);
11955 got_pathlist_free(&paths);
11956 if (error) {
11957 if (error->code != GOT_ERR_CANCELLED)
11958 goto done;
11959 if (sigint_received || sigpipe_received)
11960 goto done;
11962 if (have_changes) {
11963 error = histedit_commit(NULL, worktree,
11964 fileindex, tmp_branch, hle,
11965 committer, repo);
11966 if (error)
11967 goto done;
11968 } else {
11969 error = got_object_open_as_commit(
11970 &commit, repo, hle->commit_id);
11971 if (error)
11972 goto done;
11973 error = show_histedit_progress(commit,
11974 hle, NULL);
11975 got_object_commit_close(commit);
11976 commit = NULL;
11977 if (error)
11978 goto done;
11981 continue;
11984 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11985 error = histedit_skip_commit(hle, worktree, repo);
11986 if (error)
11987 goto done;
11988 continue;
11991 error = got_object_open_as_commit(&commit, repo,
11992 hle->commit_id);
11993 if (error)
11994 goto done;
11995 parent_ids = got_object_commit_get_parent_ids(commit);
11996 pid = STAILQ_FIRST(parent_ids);
11998 error = got_worktree_histedit_merge_files(&merged_paths,
11999 worktree, fileindex, &pid->id, hle->commit_id, repo,
12000 update_progress, &upa, check_cancelled, NULL);
12001 if (error)
12002 goto done;
12003 got_object_commit_close(commit);
12004 commit = NULL;
12006 print_merge_progress_stats(&upa);
12007 if (upa.conflicts > 0 || upa.missing > 0 ||
12008 upa.not_deleted > 0 || upa.unversioned > 0) {
12009 if (upa.conflicts > 0) {
12010 error = show_rebase_merge_conflict(
12011 hle->commit_id, repo);
12012 if (error)
12013 goto done;
12015 got_worktree_rebase_pathlist_free(&merged_paths);
12016 break;
12019 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
12020 char *id_str;
12021 error = got_object_id_str(&id_str, hle->commit_id);
12022 if (error)
12023 goto done;
12024 printf("Stopping histedit for amending commit %s\n",
12025 id_str);
12026 free(id_str);
12027 got_worktree_rebase_pathlist_free(&merged_paths);
12028 error = got_worktree_histedit_postpone(worktree,
12029 fileindex);
12030 goto done;
12033 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
12034 error = histedit_skip_commit(hle, worktree, repo);
12035 if (error)
12036 goto done;
12037 continue;
12040 error = histedit_commit(&merged_paths, worktree, fileindex,
12041 tmp_branch, hle, committer, repo);
12042 got_worktree_rebase_pathlist_free(&merged_paths);
12043 if (error)
12044 goto done;
12047 if (upa.conflicts > 0 || upa.missing > 0 ||
12048 upa.not_deleted > 0 || upa.unversioned > 0) {
12049 error = got_worktree_histedit_postpone(worktree, fileindex);
12050 if (error)
12051 goto done;
12052 if (upa.conflicts > 0 && upa.missing == 0 &&
12053 upa.not_deleted == 0 && upa.unversioned == 0) {
12054 error = got_error_msg(GOT_ERR_CONFLICTS,
12055 "conflicts must be resolved before histedit "
12056 "can continue");
12057 } else if (upa.conflicts > 0) {
12058 error = got_error_msg(GOT_ERR_CONFLICTS,
12059 "conflicts must be resolved before histedit "
12060 "can continue; changes destined for some "
12061 "files were not yet merged and should be "
12062 "merged manually if required before the "
12063 "histedit operation is continued");
12064 } else {
12065 error = got_error_msg(GOT_ERR_CONFLICTS,
12066 "changes destined for some files were not "
12067 "yet merged and should be merged manually "
12068 "if required before the histedit operation "
12069 "is continued");
12071 } else
12072 error = histedit_complete(worktree, fileindex, tmp_branch,
12073 branch, repo);
12074 done:
12075 free(cwd);
12076 free(committer);
12077 free(gitconfig_path);
12078 got_object_id_queue_free(&commits);
12079 histedit_free_list(&histedit_cmds);
12080 free(head_commit_id);
12081 free(base_commit_id);
12082 free(resume_commit_id);
12083 if (commit)
12084 got_object_commit_close(commit);
12085 if (branch)
12086 got_ref_close(branch);
12087 if (tmp_branch)
12088 got_ref_close(tmp_branch);
12089 if (worktree)
12090 got_worktree_close(worktree);
12091 if (repo) {
12092 const struct got_error *close_err = got_repo_close(repo);
12093 if (error == NULL)
12094 error = close_err;
12096 if (pack_fds) {
12097 const struct got_error *pack_err =
12098 got_repo_pack_fds_close(pack_fds);
12099 if (error == NULL)
12100 error = pack_err;
12102 return error;
12105 __dead static void
12106 usage_integrate(void)
12108 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12109 exit(1);
12112 static const struct got_error *
12113 cmd_integrate(int argc, char *argv[])
12115 const struct got_error *error = NULL;
12116 struct got_repository *repo = NULL;
12117 struct got_worktree *worktree = NULL;
12118 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12119 const char *branch_arg = NULL;
12120 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12121 struct got_fileindex *fileindex = NULL;
12122 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12123 int ch;
12124 struct got_update_progress_arg upa;
12125 int *pack_fds = NULL;
12127 while ((ch = getopt(argc, argv, "")) != -1) {
12128 switch (ch) {
12129 default:
12130 usage_integrate();
12131 /* NOTREACHED */
12135 argc -= optind;
12136 argv += optind;
12138 if (argc != 1)
12139 usage_integrate();
12140 branch_arg = argv[0];
12141 #ifndef PROFILE
12142 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12143 "unveil", NULL) == -1)
12144 err(1, "pledge");
12145 #endif
12146 cwd = getcwd(NULL, 0);
12147 if (cwd == NULL) {
12148 error = got_error_from_errno("getcwd");
12149 goto done;
12152 error = got_repo_pack_fds_open(&pack_fds);
12153 if (error != NULL)
12154 goto done;
12156 error = got_worktree_open(&worktree, cwd);
12157 if (error) {
12158 if (error->code == GOT_ERR_NOT_WORKTREE)
12159 error = wrap_not_worktree_error(error, "integrate",
12160 cwd);
12161 goto done;
12164 error = check_rebase_or_histedit_in_progress(worktree);
12165 if (error)
12166 goto done;
12168 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12169 NULL, pack_fds);
12170 if (error != NULL)
12171 goto done;
12173 error = apply_unveil(got_repo_get_path(repo), 0,
12174 got_worktree_get_root_path(worktree));
12175 if (error)
12176 goto done;
12178 error = check_merge_in_progress(worktree, repo);
12179 if (error)
12180 goto done;
12182 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
12183 error = got_error_from_errno("asprintf");
12184 goto done;
12187 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
12188 &base_branch_ref, worktree, refname, repo);
12189 if (error)
12190 goto done;
12192 refname = strdup(got_ref_get_name(branch_ref));
12193 if (refname == NULL) {
12194 error = got_error_from_errno("strdup");
12195 got_worktree_integrate_abort(worktree, fileindex, repo,
12196 branch_ref, base_branch_ref);
12197 goto done;
12199 base_refname = strdup(got_ref_get_name(base_branch_ref));
12200 if (base_refname == NULL) {
12201 error = got_error_from_errno("strdup");
12202 got_worktree_integrate_abort(worktree, fileindex, repo,
12203 branch_ref, base_branch_ref);
12204 goto done;
12206 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
12207 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
12208 got_worktree_integrate_abort(worktree, fileindex, repo,
12209 branch_ref, base_branch_ref);
12210 goto done;
12213 error = got_ref_resolve(&commit_id, repo, branch_ref);
12214 if (error)
12215 goto done;
12217 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
12218 if (error)
12219 goto done;
12221 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
12222 error = got_error_msg(GOT_ERR_SAME_BRANCH,
12223 "specified branch has already been integrated");
12224 got_worktree_integrate_abort(worktree, fileindex, repo,
12225 branch_ref, base_branch_ref);
12226 goto done;
12229 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
12230 if (error) {
12231 if (error->code == GOT_ERR_ANCESTRY)
12232 error = got_error(GOT_ERR_REBASE_REQUIRED);
12233 got_worktree_integrate_abort(worktree, fileindex, repo,
12234 branch_ref, base_branch_ref);
12235 goto done;
12238 memset(&upa, 0, sizeof(upa));
12239 error = got_worktree_integrate_continue(worktree, fileindex, repo,
12240 branch_ref, base_branch_ref, update_progress, &upa,
12241 check_cancelled, NULL);
12242 if (error)
12243 goto done;
12245 printf("Integrated %s into %s\n", refname, base_refname);
12246 print_update_progress_stats(&upa);
12247 done:
12248 if (repo) {
12249 const struct got_error *close_err = got_repo_close(repo);
12250 if (error == NULL)
12251 error = close_err;
12253 if (worktree)
12254 got_worktree_close(worktree);
12255 if (pack_fds) {
12256 const struct got_error *pack_err =
12257 got_repo_pack_fds_close(pack_fds);
12258 if (error == NULL)
12259 error = pack_err;
12261 free(cwd);
12262 free(base_commit_id);
12263 free(commit_id);
12264 free(refname);
12265 free(base_refname);
12266 return error;
12269 __dead static void
12270 usage_merge(void)
12272 fprintf(stderr, "usage: %s merge [-acn] [branch]\n", getprogname());
12273 exit(1);
12276 static const struct got_error *
12277 cmd_merge(int argc, char *argv[])
12279 const struct got_error *error = NULL;
12280 struct got_worktree *worktree = NULL;
12281 struct got_repository *repo = NULL;
12282 struct got_fileindex *fileindex = NULL;
12283 char *cwd = NULL, *id_str = NULL, *author = NULL;
12284 struct got_reference *branch = NULL, *wt_branch = NULL;
12285 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
12286 struct got_object_id *wt_branch_tip = NULL;
12287 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
12288 int interrupt_merge = 0;
12289 struct got_update_progress_arg upa;
12290 struct got_object_id *merge_commit_id = NULL;
12291 char *branch_name = NULL;
12292 int *pack_fds = NULL;
12294 memset(&upa, 0, sizeof(upa));
12296 while ((ch = getopt(argc, argv, "acn")) != -1) {
12297 switch (ch) {
12298 case 'a':
12299 abort_merge = 1;
12300 break;
12301 case 'c':
12302 continue_merge = 1;
12303 break;
12304 case 'n':
12305 interrupt_merge = 1;
12306 break;
12307 default:
12308 usage_rebase();
12309 /* NOTREACHED */
12313 argc -= optind;
12314 argv += optind;
12316 #ifndef PROFILE
12317 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12318 "unveil", NULL) == -1)
12319 err(1, "pledge");
12320 #endif
12322 if (abort_merge && continue_merge)
12323 option_conflict('a', 'c');
12324 if (abort_merge || continue_merge) {
12325 if (argc != 0)
12326 usage_merge();
12327 } else if (argc != 1)
12328 usage_merge();
12330 cwd = getcwd(NULL, 0);
12331 if (cwd == NULL) {
12332 error = got_error_from_errno("getcwd");
12333 goto done;
12336 error = got_repo_pack_fds_open(&pack_fds);
12337 if (error != NULL)
12338 goto done;
12340 error = got_worktree_open(&worktree, cwd);
12341 if (error) {
12342 if (error->code == GOT_ERR_NOT_WORKTREE)
12343 error = wrap_not_worktree_error(error,
12344 "merge", cwd);
12345 goto done;
12348 error = got_repo_open(&repo,
12349 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
12350 pack_fds);
12351 if (error != NULL)
12352 goto done;
12354 error = apply_unveil(got_repo_get_path(repo), 0,
12355 worktree ? got_worktree_get_root_path(worktree) : NULL);
12356 if (error)
12357 goto done;
12359 error = check_rebase_or_histedit_in_progress(worktree);
12360 if (error)
12361 goto done;
12363 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12364 repo);
12365 if (error)
12366 goto done;
12368 if (abort_merge) {
12369 if (!merge_in_progress) {
12370 error = got_error(GOT_ERR_NOT_MERGING);
12371 goto done;
12373 error = got_worktree_merge_continue(&branch_name,
12374 &branch_tip, &fileindex, worktree, repo);
12375 if (error)
12376 goto done;
12377 error = got_worktree_merge_abort(worktree, fileindex, repo,
12378 abort_progress, &upa);
12379 if (error)
12380 goto done;
12381 printf("Merge of %s aborted\n", branch_name);
12382 goto done; /* nothing else to do */
12385 error = get_author(&author, repo, worktree);
12386 if (error)
12387 goto done;
12389 if (continue_merge) {
12390 if (!merge_in_progress) {
12391 error = got_error(GOT_ERR_NOT_MERGING);
12392 goto done;
12394 error = got_worktree_merge_continue(&branch_name,
12395 &branch_tip, &fileindex, worktree, repo);
12396 if (error)
12397 goto done;
12398 } else {
12399 error = got_ref_open(&branch, repo, argv[0], 0);
12400 if (error != NULL)
12401 goto done;
12402 branch_name = strdup(got_ref_get_name(branch));
12403 if (branch_name == NULL) {
12404 error = got_error_from_errno("strdup");
12405 goto done;
12407 error = got_ref_resolve(&branch_tip, repo, branch);
12408 if (error)
12409 goto done;
12412 error = got_ref_open(&wt_branch, repo,
12413 got_worktree_get_head_ref_name(worktree), 0);
12414 if (error)
12415 goto done;
12416 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
12417 if (error)
12418 goto done;
12419 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
12420 wt_branch_tip, branch_tip, 0, repo,
12421 check_cancelled, NULL);
12422 if (error && error->code != GOT_ERR_ANCESTRY)
12423 goto done;
12425 if (!continue_merge) {
12426 error = check_path_prefix(wt_branch_tip, branch_tip,
12427 got_worktree_get_path_prefix(worktree),
12428 GOT_ERR_MERGE_PATH, repo);
12429 if (error)
12430 goto done;
12431 if (yca_id) {
12432 error = check_same_branch(wt_branch_tip, branch,
12433 yca_id, repo);
12434 if (error) {
12435 if (error->code != GOT_ERR_ANCESTRY)
12436 goto done;
12437 error = NULL;
12438 } else {
12439 static char msg[512];
12440 snprintf(msg, sizeof(msg),
12441 "cannot create a merge commit because "
12442 "%s is based on %s; %s can be integrated "
12443 "with 'got integrate' instead", branch_name,
12444 got_worktree_get_head_ref_name(worktree),
12445 branch_name);
12446 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
12447 goto done;
12450 error = got_worktree_merge_prepare(&fileindex, worktree,
12451 branch, repo);
12452 if (error)
12453 goto done;
12455 error = got_worktree_merge_branch(worktree, fileindex,
12456 yca_id, branch_tip, repo, update_progress, &upa,
12457 check_cancelled, NULL);
12458 if (error)
12459 goto done;
12460 print_merge_progress_stats(&upa);
12461 if (!upa.did_something) {
12462 error = got_worktree_merge_abort(worktree, fileindex,
12463 repo, abort_progress, &upa);
12464 if (error)
12465 goto done;
12466 printf("Already up-to-date\n");
12467 goto done;
12471 if (interrupt_merge) {
12472 error = got_worktree_merge_postpone(worktree, fileindex);
12473 if (error)
12474 goto done;
12475 printf("Merge of %s interrupted on request\n", branch_name);
12476 } else if (upa.conflicts > 0 || upa.missing > 0 ||
12477 upa.not_deleted > 0 || upa.unversioned > 0) {
12478 error = got_worktree_merge_postpone(worktree, fileindex);
12479 if (error)
12480 goto done;
12481 if (upa.conflicts > 0 && upa.missing == 0 &&
12482 upa.not_deleted == 0 && upa.unversioned == 0) {
12483 error = got_error_msg(GOT_ERR_CONFLICTS,
12484 "conflicts must be resolved before merging "
12485 "can continue");
12486 } else if (upa.conflicts > 0) {
12487 error = got_error_msg(GOT_ERR_CONFLICTS,
12488 "conflicts must be resolved before merging "
12489 "can continue; changes destined for some "
12490 "files were not yet merged and "
12491 "should be merged manually if required before the "
12492 "merge operation is continued");
12493 } else {
12494 error = got_error_msg(GOT_ERR_CONFLICTS,
12495 "changes destined for some "
12496 "files were not yet merged and should be "
12497 "merged manually if required before the "
12498 "merge operation is continued");
12500 goto done;
12501 } else {
12502 error = got_worktree_merge_commit(&merge_commit_id, worktree,
12503 fileindex, author, NULL, 1, branch_tip, branch_name,
12504 repo, continue_merge ? print_status : NULL, NULL);
12505 if (error)
12506 goto done;
12507 error = got_worktree_merge_complete(worktree, fileindex, repo);
12508 if (error)
12509 goto done;
12510 error = got_object_id_str(&id_str, merge_commit_id);
12511 if (error)
12512 goto done;
12513 printf("Merged %s into %s: %s\n", branch_name,
12514 got_worktree_get_head_ref_name(worktree),
12515 id_str);
12518 done:
12519 free(id_str);
12520 free(merge_commit_id);
12521 free(author);
12522 free(branch_tip);
12523 free(branch_name);
12524 free(yca_id);
12525 if (branch)
12526 got_ref_close(branch);
12527 if (wt_branch)
12528 got_ref_close(wt_branch);
12529 if (worktree)
12530 got_worktree_close(worktree);
12531 if (repo) {
12532 const struct got_error *close_err = got_repo_close(repo);
12533 if (error == NULL)
12534 error = close_err;
12536 if (pack_fds) {
12537 const struct got_error *pack_err =
12538 got_repo_pack_fds_close(pack_fds);
12539 if (error == NULL)
12540 error = pack_err;
12542 return error;
12545 __dead static void
12546 usage_stage(void)
12548 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
12549 "[path ...]\n", getprogname());
12550 exit(1);
12553 static const struct got_error *
12554 print_stage(void *arg, unsigned char status, unsigned char staged_status,
12555 const char *path, struct got_object_id *blob_id,
12556 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
12557 int dirfd, const char *de_name)
12559 const struct got_error *err = NULL;
12560 char *id_str = NULL;
12562 if (staged_status != GOT_STATUS_ADD &&
12563 staged_status != GOT_STATUS_MODIFY &&
12564 staged_status != GOT_STATUS_DELETE)
12565 return NULL;
12567 if (staged_status == GOT_STATUS_ADD ||
12568 staged_status == GOT_STATUS_MODIFY)
12569 err = got_object_id_str(&id_str, staged_blob_id);
12570 else
12571 err = got_object_id_str(&id_str, blob_id);
12572 if (err)
12573 return err;
12575 printf("%s %c %s\n", id_str, staged_status, path);
12576 free(id_str);
12577 return NULL;
12580 static const struct got_error *
12581 cmd_stage(int argc, char *argv[])
12583 const struct got_error *error = NULL;
12584 struct got_repository *repo = NULL;
12585 struct got_worktree *worktree = NULL;
12586 char *cwd = NULL;
12587 struct got_pathlist_head paths;
12588 struct got_pathlist_entry *pe;
12589 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12590 FILE *patch_script_file = NULL;
12591 const char *patch_script_path = NULL;
12592 struct choose_patch_arg cpa;
12593 int *pack_fds = NULL;
12595 TAILQ_INIT(&paths);
12597 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
12598 switch (ch) {
12599 case 'F':
12600 patch_script_path = optarg;
12601 break;
12602 case 'l':
12603 list_stage = 1;
12604 break;
12605 case 'p':
12606 pflag = 1;
12607 break;
12608 case 'S':
12609 allow_bad_symlinks = 1;
12610 break;
12611 default:
12612 usage_stage();
12613 /* NOTREACHED */
12617 argc -= optind;
12618 argv += optind;
12620 #ifndef PROFILE
12621 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12622 "unveil", NULL) == -1)
12623 err(1, "pledge");
12624 #endif
12625 if (list_stage && (pflag || patch_script_path))
12626 errx(1, "-l option cannot be used with other options");
12627 if (patch_script_path && !pflag)
12628 errx(1, "-F option can only be used together with -p option");
12630 cwd = getcwd(NULL, 0);
12631 if (cwd == NULL) {
12632 error = got_error_from_errno("getcwd");
12633 goto done;
12636 error = got_repo_pack_fds_open(&pack_fds);
12637 if (error != NULL)
12638 goto done;
12640 error = got_worktree_open(&worktree, cwd);
12641 if (error) {
12642 if (error->code == GOT_ERR_NOT_WORKTREE)
12643 error = wrap_not_worktree_error(error, "stage", cwd);
12644 goto done;
12647 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12648 NULL, pack_fds);
12649 if (error != NULL)
12650 goto done;
12652 if (patch_script_path) {
12653 patch_script_file = fopen(patch_script_path, "re");
12654 if (patch_script_file == NULL) {
12655 error = got_error_from_errno2("fopen",
12656 patch_script_path);
12657 goto done;
12660 error = apply_unveil(got_repo_get_path(repo), 0,
12661 got_worktree_get_root_path(worktree));
12662 if (error)
12663 goto done;
12665 error = check_merge_in_progress(worktree, repo);
12666 if (error)
12667 goto done;
12669 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12670 if (error)
12671 goto done;
12673 if (list_stage)
12674 error = got_worktree_status(worktree, &paths, repo, 0,
12675 print_stage, NULL, check_cancelled, NULL);
12676 else {
12677 cpa.patch_script_file = patch_script_file;
12678 cpa.action = "stage";
12679 error = got_worktree_stage(worktree, &paths,
12680 pflag ? NULL : print_status, NULL,
12681 pflag ? choose_patch : NULL, &cpa,
12682 allow_bad_symlinks, repo);
12684 done:
12685 if (patch_script_file && fclose(patch_script_file) == EOF &&
12686 error == NULL)
12687 error = got_error_from_errno2("fclose", patch_script_path);
12688 if (repo) {
12689 const struct got_error *close_err = got_repo_close(repo);
12690 if (error == NULL)
12691 error = close_err;
12693 if (worktree)
12694 got_worktree_close(worktree);
12695 if (pack_fds) {
12696 const struct got_error *pack_err =
12697 got_repo_pack_fds_close(pack_fds);
12698 if (error == NULL)
12699 error = pack_err;
12701 TAILQ_FOREACH(pe, &paths, entry)
12702 free((char *)pe->path);
12703 got_pathlist_free(&paths);
12704 free(cwd);
12705 return error;
12708 __dead static void
12709 usage_unstage(void)
12711 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12712 "[path ...]\n", getprogname());
12713 exit(1);
12717 static const struct got_error *
12718 cmd_unstage(int argc, char *argv[])
12720 const struct got_error *error = NULL;
12721 struct got_repository *repo = NULL;
12722 struct got_worktree *worktree = NULL;
12723 char *cwd = NULL;
12724 struct got_pathlist_head paths;
12725 struct got_pathlist_entry *pe;
12726 int ch, pflag = 0;
12727 struct got_update_progress_arg upa;
12728 FILE *patch_script_file = NULL;
12729 const char *patch_script_path = NULL;
12730 struct choose_patch_arg cpa;
12731 int *pack_fds = NULL;
12733 TAILQ_INIT(&paths);
12735 while ((ch = getopt(argc, argv, "F:p")) != -1) {
12736 switch (ch) {
12737 case 'F':
12738 patch_script_path = optarg;
12739 break;
12740 case 'p':
12741 pflag = 1;
12742 break;
12743 default:
12744 usage_unstage();
12745 /* NOTREACHED */
12749 argc -= optind;
12750 argv += optind;
12752 #ifndef PROFILE
12753 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12754 "unveil", NULL) == -1)
12755 err(1, "pledge");
12756 #endif
12757 if (patch_script_path && !pflag)
12758 errx(1, "-F option can only be used together with -p option");
12760 cwd = getcwd(NULL, 0);
12761 if (cwd == NULL) {
12762 error = got_error_from_errno("getcwd");
12763 goto done;
12766 error = got_repo_pack_fds_open(&pack_fds);
12767 if (error != NULL)
12768 goto done;
12770 error = got_worktree_open(&worktree, cwd);
12771 if (error) {
12772 if (error->code == GOT_ERR_NOT_WORKTREE)
12773 error = wrap_not_worktree_error(error, "unstage", cwd);
12774 goto done;
12777 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12778 NULL, pack_fds);
12779 if (error != NULL)
12780 goto done;
12782 if (patch_script_path) {
12783 patch_script_file = fopen(patch_script_path, "re");
12784 if (patch_script_file == NULL) {
12785 error = got_error_from_errno2("fopen",
12786 patch_script_path);
12787 goto done;
12791 error = apply_unveil(got_repo_get_path(repo), 0,
12792 got_worktree_get_root_path(worktree));
12793 if (error)
12794 goto done;
12796 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12797 if (error)
12798 goto done;
12800 cpa.patch_script_file = patch_script_file;
12801 cpa.action = "unstage";
12802 memset(&upa, 0, sizeof(upa));
12803 error = got_worktree_unstage(worktree, &paths, update_progress,
12804 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12805 if (!error)
12806 print_merge_progress_stats(&upa);
12807 done:
12808 if (patch_script_file && fclose(patch_script_file) == EOF &&
12809 error == NULL)
12810 error = got_error_from_errno2("fclose", patch_script_path);
12811 if (repo) {
12812 const struct got_error *close_err = got_repo_close(repo);
12813 if (error == NULL)
12814 error = close_err;
12816 if (worktree)
12817 got_worktree_close(worktree);
12818 if (pack_fds) {
12819 const struct got_error *pack_err =
12820 got_repo_pack_fds_close(pack_fds);
12821 if (error == NULL)
12822 error = pack_err;
12824 TAILQ_FOREACH(pe, &paths, entry)
12825 free((char *)pe->path);
12826 got_pathlist_free(&paths);
12827 free(cwd);
12828 return error;
12831 __dead static void
12832 usage_cat(void)
12834 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
12835 "arg ...\n", getprogname());
12836 exit(1);
12839 static const struct got_error *
12840 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12842 const struct got_error *err;
12843 struct got_blob_object *blob;
12844 int fd = -1;
12846 fd = got_opentempfd();
12847 if (fd == -1)
12848 return got_error_from_errno("got_opentempfd");
12850 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
12851 if (err)
12852 goto done;
12854 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12855 done:
12856 if (fd != -1 && close(fd) == -1 && err == NULL)
12857 err = got_error_from_errno("close");
12858 if (blob)
12859 got_object_blob_close(blob);
12860 return err;
12863 static const struct got_error *
12864 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12866 const struct got_error *err;
12867 struct got_tree_object *tree;
12868 int nentries, i;
12870 err = got_object_open_as_tree(&tree, repo, id);
12871 if (err)
12872 return err;
12874 nentries = got_object_tree_get_nentries(tree);
12875 for (i = 0; i < nentries; i++) {
12876 struct got_tree_entry *te;
12877 char *id_str;
12878 if (sigint_received || sigpipe_received)
12879 break;
12880 te = got_object_tree_get_entry(tree, i);
12881 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12882 if (err)
12883 break;
12884 fprintf(outfile, "%s %.7o %s\n", id_str,
12885 got_tree_entry_get_mode(te),
12886 got_tree_entry_get_name(te));
12887 free(id_str);
12890 got_object_tree_close(tree);
12891 return err;
12894 static const struct got_error *
12895 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12897 const struct got_error *err;
12898 struct got_commit_object *commit;
12899 const struct got_object_id_queue *parent_ids;
12900 struct got_object_qid *pid;
12901 char *id_str = NULL;
12902 const char *logmsg = NULL;
12903 char gmtoff[6];
12905 err = got_object_open_as_commit(&commit, repo, id);
12906 if (err)
12907 return err;
12909 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12910 if (err)
12911 goto done;
12913 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12914 parent_ids = got_object_commit_get_parent_ids(commit);
12915 fprintf(outfile, "numparents %d\n",
12916 got_object_commit_get_nparents(commit));
12917 STAILQ_FOREACH(pid, parent_ids, entry) {
12918 char *pid_str;
12919 err = got_object_id_str(&pid_str, &pid->id);
12920 if (err)
12921 goto done;
12922 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12923 free(pid_str);
12925 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12926 got_object_commit_get_author_gmtoff(commit));
12927 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12928 got_object_commit_get_author(commit),
12929 (long long)got_object_commit_get_author_time(commit),
12930 gmtoff);
12932 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12933 got_object_commit_get_committer_gmtoff(commit));
12934 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12935 got_object_commit_get_committer(commit),
12936 (long long)got_object_commit_get_committer_time(commit),
12937 gmtoff);
12939 logmsg = got_object_commit_get_logmsg_raw(commit);
12940 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12941 fprintf(outfile, "%s", logmsg);
12942 done:
12943 free(id_str);
12944 got_object_commit_close(commit);
12945 return err;
12948 static const struct got_error *
12949 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12951 const struct got_error *err;
12952 struct got_tag_object *tag;
12953 char *id_str = NULL;
12954 const char *tagmsg = NULL;
12955 char gmtoff[6];
12957 err = got_object_open_as_tag(&tag, repo, id);
12958 if (err)
12959 return err;
12961 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12962 if (err)
12963 goto done;
12965 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12967 switch (got_object_tag_get_object_type(tag)) {
12968 case GOT_OBJ_TYPE_BLOB:
12969 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12970 GOT_OBJ_LABEL_BLOB);
12971 break;
12972 case GOT_OBJ_TYPE_TREE:
12973 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12974 GOT_OBJ_LABEL_TREE);
12975 break;
12976 case GOT_OBJ_TYPE_COMMIT:
12977 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12978 GOT_OBJ_LABEL_COMMIT);
12979 break;
12980 case GOT_OBJ_TYPE_TAG:
12981 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12982 GOT_OBJ_LABEL_TAG);
12983 break;
12984 default:
12985 break;
12988 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12989 got_object_tag_get_name(tag));
12991 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12992 got_object_tag_get_tagger_gmtoff(tag));
12993 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12994 got_object_tag_get_tagger(tag),
12995 (long long)got_object_tag_get_tagger_time(tag),
12996 gmtoff);
12998 tagmsg = got_object_tag_get_message(tag);
12999 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
13000 fprintf(outfile, "%s", tagmsg);
13001 done:
13002 free(id_str);
13003 got_object_tag_close(tag);
13004 return err;
13007 static const struct got_error *
13008 cmd_cat(int argc, char *argv[])
13010 const struct got_error *error;
13011 struct got_repository *repo = NULL;
13012 struct got_worktree *worktree = NULL;
13013 char *cwd = NULL, *repo_path = NULL, *label = NULL;
13014 const char *commit_id_str = NULL;
13015 struct got_object_id *id = NULL, *commit_id = NULL;
13016 struct got_commit_object *commit = NULL;
13017 int ch, obj_type, i, force_path = 0;
13018 struct got_reflist_head refs;
13019 int *pack_fds = NULL;
13021 TAILQ_INIT(&refs);
13023 #ifndef PROFILE
13024 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13025 NULL) == -1)
13026 err(1, "pledge");
13027 #endif
13029 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
13030 switch (ch) {
13031 case 'c':
13032 commit_id_str = optarg;
13033 break;
13034 case 'P':
13035 force_path = 1;
13036 break;
13037 case 'r':
13038 repo_path = realpath(optarg, NULL);
13039 if (repo_path == NULL)
13040 return got_error_from_errno2("realpath",
13041 optarg);
13042 got_path_strip_trailing_slashes(repo_path);
13043 break;
13044 default:
13045 usage_cat();
13046 /* NOTREACHED */
13050 argc -= optind;
13051 argv += optind;
13053 cwd = getcwd(NULL, 0);
13054 if (cwd == NULL) {
13055 error = got_error_from_errno("getcwd");
13056 goto done;
13059 error = got_repo_pack_fds_open(&pack_fds);
13060 if (error != NULL)
13061 goto done;
13063 if (repo_path == NULL) {
13064 error = got_worktree_open(&worktree, cwd);
13065 if (error && error->code != GOT_ERR_NOT_WORKTREE)
13066 goto done;
13067 if (worktree) {
13068 repo_path = strdup(
13069 got_worktree_get_repo_path(worktree));
13070 if (repo_path == NULL) {
13071 error = got_error_from_errno("strdup");
13072 goto done;
13075 /* Release work tree lock. */
13076 got_worktree_close(worktree);
13077 worktree = NULL;
13081 if (repo_path == NULL) {
13082 repo_path = strdup(cwd);
13083 if (repo_path == NULL)
13084 return got_error_from_errno("strdup");
13087 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
13088 free(repo_path);
13089 if (error != NULL)
13090 goto done;
13092 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
13093 if (error)
13094 goto done;
13096 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
13097 if (error)
13098 goto done;
13100 if (commit_id_str == NULL)
13101 commit_id_str = GOT_REF_HEAD;
13102 error = got_repo_match_object_id(&commit_id, NULL,
13103 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
13104 if (error)
13105 goto done;
13107 error = got_object_open_as_commit(&commit, repo, commit_id);
13108 if (error)
13109 goto done;
13111 for (i = 0; i < argc; i++) {
13112 if (force_path) {
13113 error = got_object_id_by_path(&id, repo, commit,
13114 argv[i]);
13115 if (error)
13116 break;
13117 } else {
13118 error = got_repo_match_object_id(&id, &label, argv[i],
13119 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
13120 repo);
13121 if (error) {
13122 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
13123 error->code != GOT_ERR_NOT_REF)
13124 break;
13125 error = got_object_id_by_path(&id, repo,
13126 commit, argv[i]);
13127 if (error)
13128 break;
13132 error = got_object_get_type(&obj_type, repo, id);
13133 if (error)
13134 break;
13136 switch (obj_type) {
13137 case GOT_OBJ_TYPE_BLOB:
13138 error = cat_blob(id, repo, stdout);
13139 break;
13140 case GOT_OBJ_TYPE_TREE:
13141 error = cat_tree(id, repo, stdout);
13142 break;
13143 case GOT_OBJ_TYPE_COMMIT:
13144 error = cat_commit(id, repo, stdout);
13145 break;
13146 case GOT_OBJ_TYPE_TAG:
13147 error = cat_tag(id, repo, stdout);
13148 break;
13149 default:
13150 error = got_error(GOT_ERR_OBJ_TYPE);
13151 break;
13153 if (error)
13154 break;
13155 free(label);
13156 label = NULL;
13157 free(id);
13158 id = NULL;
13160 done:
13161 free(label);
13162 free(id);
13163 free(commit_id);
13164 if (commit)
13165 got_object_commit_close(commit);
13166 if (worktree)
13167 got_worktree_close(worktree);
13168 if (repo) {
13169 const struct got_error *close_err = got_repo_close(repo);
13170 if (error == NULL)
13171 error = close_err;
13173 if (pack_fds) {
13174 const struct got_error *pack_err =
13175 got_repo_pack_fds_close(pack_fds);
13176 if (error == NULL)
13177 error = pack_err;
13180 got_ref_list_free(&refs);
13181 return error;
13184 __dead static void
13185 usage_info(void)
13187 fprintf(stderr, "usage: %s info [path ...]\n",
13188 getprogname());
13189 exit(1);
13192 static const struct got_error *
13193 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
13194 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
13195 struct got_object_id *commit_id)
13197 const struct got_error *err = NULL;
13198 char *id_str = NULL;
13199 char datebuf[128];
13200 struct tm mytm, *tm;
13201 struct got_pathlist_head *paths = arg;
13202 struct got_pathlist_entry *pe;
13205 * Clear error indication from any of the path arguments which
13206 * would cause this file index entry to be displayed.
13208 TAILQ_FOREACH(pe, paths, entry) {
13209 if (got_path_cmp(path, pe->path, strlen(path),
13210 pe->path_len) == 0 ||
13211 got_path_is_child(path, pe->path, pe->path_len))
13212 pe->data = NULL; /* no error */
13215 printf(GOT_COMMIT_SEP_STR);
13216 if (S_ISLNK(mode))
13217 printf("symlink: %s\n", path);
13218 else if (S_ISREG(mode)) {
13219 printf("file: %s\n", path);
13220 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
13221 } else if (S_ISDIR(mode))
13222 printf("directory: %s\n", path);
13223 else
13224 printf("something: %s\n", path);
13226 tm = localtime_r(&mtime, &mytm);
13227 if (tm == NULL)
13228 return NULL;
13229 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
13230 return got_error(GOT_ERR_NO_SPACE);
13231 printf("timestamp: %s\n", datebuf);
13233 if (blob_id) {
13234 err = got_object_id_str(&id_str, blob_id);
13235 if (err)
13236 return err;
13237 printf("based on blob: %s\n", id_str);
13238 free(id_str);
13241 if (staged_blob_id) {
13242 err = got_object_id_str(&id_str, staged_blob_id);
13243 if (err)
13244 return err;
13245 printf("based on staged blob: %s\n", id_str);
13246 free(id_str);
13249 if (commit_id) {
13250 err = got_object_id_str(&id_str, commit_id);
13251 if (err)
13252 return err;
13253 printf("based on commit: %s\n", id_str);
13254 free(id_str);
13257 return NULL;
13260 static const struct got_error *
13261 cmd_info(int argc, char *argv[])
13263 const struct got_error *error = NULL;
13264 struct got_worktree *worktree = NULL;
13265 char *cwd = NULL, *id_str = NULL;
13266 struct got_pathlist_head paths;
13267 struct got_pathlist_entry *pe;
13268 char *uuidstr = NULL;
13269 int ch, show_files = 0;
13271 TAILQ_INIT(&paths);
13273 while ((ch = getopt(argc, argv, "")) != -1) {
13274 switch (ch) {
13275 default:
13276 usage_info();
13277 /* NOTREACHED */
13281 argc -= optind;
13282 argv += optind;
13284 #ifndef PROFILE
13285 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13286 NULL) == -1)
13287 err(1, "pledge");
13288 #endif
13289 cwd = getcwd(NULL, 0);
13290 if (cwd == NULL) {
13291 error = got_error_from_errno("getcwd");
13292 goto done;
13295 error = got_worktree_open(&worktree, cwd);
13296 if (error) {
13297 if (error->code == GOT_ERR_NOT_WORKTREE)
13298 error = wrap_not_worktree_error(error, "info", cwd);
13299 goto done;
13302 #ifndef PROFILE
13303 /* Remove "wpath cpath proc exec sendfd" promises. */
13304 if (pledge("stdio rpath flock unveil", NULL) == -1)
13305 err(1, "pledge");
13306 #endif
13307 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
13308 if (error)
13309 goto done;
13311 if (argc >= 1) {
13312 error = get_worktree_paths_from_argv(&paths, argc, argv,
13313 worktree);
13314 if (error)
13315 goto done;
13316 show_files = 1;
13319 error = got_object_id_str(&id_str,
13320 got_worktree_get_base_commit_id(worktree));
13321 if (error)
13322 goto done;
13324 error = got_worktree_get_uuid(&uuidstr, worktree);
13325 if (error)
13326 goto done;
13328 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
13329 printf("work tree base commit: %s\n", id_str);
13330 printf("work tree path prefix: %s\n",
13331 got_worktree_get_path_prefix(worktree));
13332 printf("work tree branch reference: %s\n",
13333 got_worktree_get_head_ref_name(worktree));
13334 printf("work tree UUID: %s\n", uuidstr);
13335 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
13337 if (show_files) {
13338 struct got_pathlist_entry *pe;
13339 TAILQ_FOREACH(pe, &paths, entry) {
13340 if (pe->path_len == 0)
13341 continue;
13343 * Assume this path will fail. This will be corrected
13344 * in print_path_info() in case the path does suceeed.
13346 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
13348 error = got_worktree_path_info(worktree, &paths,
13349 print_path_info, &paths, check_cancelled, NULL);
13350 if (error)
13351 goto done;
13352 TAILQ_FOREACH(pe, &paths, entry) {
13353 if (pe->data != NULL) {
13354 const struct got_error *perr;
13356 perr = pe->data;
13357 error = got_error_fmt(perr->code, "%s",
13358 pe->path);
13359 break;
13363 done:
13364 if (worktree)
13365 got_worktree_close(worktree);
13366 TAILQ_FOREACH(pe, &paths, entry)
13367 free((char *)pe->path);
13368 got_pathlist_free(&paths);
13369 free(cwd);
13370 free(id_str);
13371 free(uuidstr);
13372 return error;