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/types.h>
21 #include <sys/stat.h>
22 #include <sys/wait.h>
24 #include <err.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <limits.h>
28 #include <locale.h>
29 #include <ctype.h>
30 #include <sha1.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
41 #include <util.h>
43 #include "got_version.h"
44 #include "got_error.h"
45 #include "got_object.h"
46 #include "got_reference.h"
47 #include "got_repository.h"
48 #include "got_path.h"
49 #include "got_cancel.h"
50 #include "got_worktree.h"
51 #include "got_diff.h"
52 #include "got_commit_graph.h"
53 #include "got_fetch.h"
54 #include "got_send.h"
55 #include "got_blame.h"
56 #include "got_privsep.h"
57 #include "got_opentemp.h"
58 #include "got_gotconfig.h"
59 #include "got_dial.h"
60 #include "got_patch.h"
62 #ifndef nitems
63 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
64 #endif
66 static volatile sig_atomic_t sigint_received;
67 static volatile sig_atomic_t sigpipe_received;
69 static void
70 catch_sigint(int signo)
71 {
72 sigint_received = 1;
73 }
75 static void
76 catch_sigpipe(int signo)
77 {
78 sigpipe_received = 1;
79 }
82 struct got_cmd {
83 const char *cmd_name;
84 const struct got_error *(*cmd_main)(int, char *[]);
85 void (*cmd_usage)(void);
86 const char *cmd_alias;
87 };
89 __dead static void usage(int, int);
90 __dead static void usage_init(void);
91 __dead static void usage_import(void);
92 __dead static void usage_clone(void);
93 __dead static void usage_fetch(void);
94 __dead static void usage_checkout(void);
95 __dead static void usage_update(void);
96 __dead static void usage_log(void);
97 __dead static void usage_diff(void);
98 __dead static void usage_blame(void);
99 __dead static void usage_tree(void);
100 __dead static void usage_status(void);
101 __dead static void usage_ref(void);
102 __dead static void usage_branch(void);
103 __dead static void usage_tag(void);
104 __dead static void usage_add(void);
105 __dead static void usage_remove(void);
106 __dead static void usage_patch(void);
107 __dead static void usage_revert(void);
108 __dead static void usage_commit(void);
109 __dead static void usage_send(void);
110 __dead static void usage_cherrypick(void);
111 __dead static void usage_backout(void);
112 __dead static void usage_rebase(void);
113 __dead static void usage_histedit(void);
114 __dead static void usage_integrate(void);
115 __dead static void usage_merge(void);
116 __dead static void usage_stage(void);
117 __dead static void usage_unstage(void);
118 __dead static void usage_cat(void);
119 __dead static void usage_info(void);
121 static const struct got_error* cmd_init(int, char *[]);
122 static const struct got_error* cmd_import(int, char *[]);
123 static const struct got_error* cmd_clone(int, char *[]);
124 static const struct got_error* cmd_fetch(int, char *[]);
125 static const struct got_error* cmd_checkout(int, char *[]);
126 static const struct got_error* cmd_update(int, char *[]);
127 static const struct got_error* cmd_log(int, char *[]);
128 static const struct got_error* cmd_diff(int, char *[]);
129 static const struct got_error* cmd_blame(int, char *[]);
130 static const struct got_error* cmd_tree(int, char *[]);
131 static const struct got_error* cmd_status(int, char *[]);
132 static const struct got_error* cmd_ref(int, char *[]);
133 static const struct got_error* cmd_branch(int, char *[]);
134 static const struct got_error* cmd_tag(int, char *[]);
135 static const struct got_error* cmd_add(int, char *[]);
136 static const struct got_error* cmd_remove(int, char *[]);
137 static const struct got_error* cmd_patch(int, char *[]);
138 static const struct got_error* cmd_revert(int, char *[]);
139 static const struct got_error* cmd_commit(int, char *[]);
140 static const struct got_error* cmd_send(int, char *[]);
141 static const struct got_error* cmd_cherrypick(int, char *[]);
142 static const struct got_error* cmd_backout(int, char *[]);
143 static const struct got_error* cmd_rebase(int, char *[]);
144 static const struct got_error* cmd_histedit(int, char *[]);
145 static const struct got_error* cmd_integrate(int, char *[]);
146 static const struct got_error* cmd_merge(int, char *[]);
147 static const struct got_error* cmd_stage(int, char *[]);
148 static const struct got_error* cmd_unstage(int, char *[]);
149 static const struct got_error* cmd_cat(int, char *[]);
150 static const struct got_error* cmd_info(int, char *[]);
152 static const struct got_cmd got_commands[] = {
153 { "init", cmd_init, usage_init, "" },
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 [-h] [-V | --version] 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_init(void)
350 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
351 exit(1);
354 static const struct got_error *
355 cmd_init(int argc, char *argv[])
357 const struct got_error *error = NULL;
358 char *repo_path = NULL;
359 int ch;
361 while ((ch = getopt(argc, argv, "")) != -1) {
362 switch (ch) {
363 default:
364 usage_init();
365 /* NOTREACHED */
369 argc -= optind;
370 argv += optind;
372 #ifndef PROFILE
373 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
374 err(1, "pledge");
375 #endif
376 if (argc != 1)
377 usage_init();
379 repo_path = strdup(argv[0]);
380 if (repo_path == NULL)
381 return got_error_from_errno("strdup");
383 got_path_strip_trailing_slashes(repo_path);
385 error = got_path_mkdir(repo_path);
386 if (error &&
387 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
388 goto done;
390 error = apply_unveil(repo_path, 0, NULL);
391 if (error)
392 goto done;
394 error = got_repo_init(repo_path);
395 done:
396 free(repo_path);
397 return error;
400 __dead static void
401 usage_import(void)
403 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
404 "[-r repository-path] [-I pattern] path\n", getprogname());
405 exit(1);
408 int
409 spawn_editor(const char *editor, const char *file)
411 pid_t pid;
412 sig_t sighup, sigint, sigquit;
413 int st = -1;
415 sighup = signal(SIGHUP, SIG_IGN);
416 sigint = signal(SIGINT, SIG_IGN);
417 sigquit = signal(SIGQUIT, SIG_IGN);
419 switch (pid = fork()) {
420 case -1:
421 goto doneediting;
422 case 0:
423 execl(editor, editor, file, (char *)NULL);
424 _exit(127);
427 while (waitpid(pid, &st, 0) == -1)
428 if (errno != EINTR)
429 break;
431 doneediting:
432 (void)signal(SIGHUP, sighup);
433 (void)signal(SIGINT, sigint);
434 (void)signal(SIGQUIT, sigquit);
436 if (!WIFEXITED(st)) {
437 errno = EINTR;
438 return -1;
441 return WEXITSTATUS(st);
444 static const struct got_error *
445 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
446 const char *initial_content, size_t initial_content_len,
447 int require_modification)
449 const struct got_error *err = NULL;
450 char *line = NULL;
451 size_t linesize = 0;
452 ssize_t linelen;
453 struct stat st, st2;
454 FILE *fp = NULL;
455 size_t len, logmsg_len;
456 char *initial_content_stripped = NULL, *buf = NULL, *s;
458 *logmsg = NULL;
460 if (stat(logmsg_path, &st) == -1)
461 return got_error_from_errno2("stat", logmsg_path);
463 if (spawn_editor(editor, logmsg_path) == -1)
464 return got_error_from_errno("failed spawning editor");
466 if (stat(logmsg_path, &st2) == -1)
467 return got_error_from_errno("stat");
469 if (require_modification &&
470 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
471 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
472 "no changes made to commit message, aborting");
474 /*
475 * Set up a stripped version of the initial content without comments
476 * and blank lines. We need this in order to check if the message
477 * has in fact been edited.
478 */
479 initial_content_stripped = malloc(initial_content_len + 1);
480 if (initial_content_stripped == NULL)
481 return got_error_from_errno("malloc");
482 initial_content_stripped[0] = '\0';
484 buf = strdup(initial_content);
485 if (buf == NULL) {
486 err = got_error_from_errno("strdup");
487 goto done;
489 s = buf;
490 len = 0;
491 while ((line = strsep(&s, "\n")) != NULL) {
492 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
493 continue; /* remove comments and leading empty lines */
494 len = strlcat(initial_content_stripped, line,
495 initial_content_len + 1);
496 if (len >= initial_content_len + 1) {
497 err = got_error(GOT_ERR_NO_SPACE);
498 goto done;
501 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
502 initial_content_stripped[len - 1] = '\0';
503 len--;
506 logmsg_len = st2.st_size;
507 *logmsg = malloc(logmsg_len + 1);
508 if (*logmsg == NULL)
509 return got_error_from_errno("malloc");
510 (*logmsg)[0] = '\0';
512 fp = fopen(logmsg_path, "re");
513 if (fp == NULL) {
514 err = got_error_from_errno("fopen");
515 goto done;
518 len = 0;
519 while ((linelen = getline(&line, &linesize, fp)) != -1) {
520 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
521 continue; /* remove comments and leading empty lines */
522 len = strlcat(*logmsg, line, logmsg_len + 1);
523 if (len >= logmsg_len + 1) {
524 err = got_error(GOT_ERR_NO_SPACE);
525 goto done;
528 free(line);
529 if (ferror(fp)) {
530 err = got_ferror(fp, GOT_ERR_IO);
531 goto done;
533 while (len > 0 && (*logmsg)[len - 1] == '\n') {
534 (*logmsg)[len - 1] = '\0';
535 len--;
538 if (len == 0) {
539 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
540 "commit message cannot be empty, aborting");
541 goto done;
543 if (require_modification &&
544 strcmp(*logmsg, initial_content_stripped) == 0)
545 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
546 "no changes made to commit message, aborting");
547 done:
548 free(initial_content_stripped);
549 free(buf);
550 if (fp && fclose(fp) == EOF && err == NULL)
551 err = got_error_from_errno("fclose");
552 if (err) {
553 free(*logmsg);
554 *logmsg = NULL;
556 return err;
559 static const struct got_error *
560 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
561 const char *path_dir, const char *branch_name)
563 char *initial_content = NULL;
564 const struct got_error *err = NULL;
565 int initial_content_len;
566 int fd = -1;
568 initial_content_len = asprintf(&initial_content,
569 "\n# %s to be imported to branch %s\n", path_dir,
570 branch_name);
571 if (initial_content_len == -1)
572 return got_error_from_errno("asprintf");
574 err = got_opentemp_named_fd(logmsg_path, &fd,
575 GOT_TMPDIR_STR "/got-importmsg");
576 if (err)
577 goto done;
579 if (write(fd, initial_content, initial_content_len) == -1) {
580 err = got_error_from_errno2("write", *logmsg_path);
581 goto done;
584 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
585 initial_content_len, 1);
586 done:
587 if (fd != -1 && close(fd) == -1 && err == NULL)
588 err = got_error_from_errno2("close", *logmsg_path);
589 free(initial_content);
590 if (err) {
591 free(*logmsg_path);
592 *logmsg_path = NULL;
594 return err;
597 static const struct got_error *
598 import_progress(void *arg, const char *path)
600 printf("A %s\n", path);
601 return NULL;
604 static int
605 valid_author(const char *author)
607 /*
608 * Really dumb email address check; we're only doing this to
609 * avoid git's object parser breaking on commits we create.
610 */
611 while (*author && *author != '<')
612 author++;
613 if (*author != '<')
614 return 0;
615 while (*author && *author != '@')
616 author++;
617 if (*author != '@')
618 return 0;
619 while (*author && *author != '>')
620 author++;
621 return *author == '>';
624 static const struct got_error *
625 get_author(char **author, struct got_repository *repo,
626 struct got_worktree *worktree)
628 const struct got_error *err = NULL;
629 const char *got_author = NULL, *name, *email;
630 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
632 *author = NULL;
634 if (worktree)
635 worktree_conf = got_worktree_get_gotconfig(worktree);
636 repo_conf = got_repo_get_gotconfig(repo);
638 /*
639 * Priority of potential author information sources, from most
640 * significant to least significant:
641 * 1) work tree's .got/got.conf file
642 * 2) repository's got.conf file
643 * 3) repository's git config file
644 * 4) environment variables
645 * 5) global git config files (in user's home directory or /etc)
646 */
648 if (worktree_conf)
649 got_author = got_gotconfig_get_author(worktree_conf);
650 if (got_author == NULL)
651 got_author = got_gotconfig_get_author(repo_conf);
652 if (got_author == NULL) {
653 name = got_repo_get_gitconfig_author_name(repo);
654 email = got_repo_get_gitconfig_author_email(repo);
655 if (name && email) {
656 if (asprintf(author, "%s <%s>", name, email) == -1)
657 return got_error_from_errno("asprintf");
658 return NULL;
661 got_author = getenv("GOT_AUTHOR");
662 if (got_author == NULL) {
663 name = got_repo_get_global_gitconfig_author_name(repo);
664 email = got_repo_get_global_gitconfig_author_email(
665 repo);
666 if (name && email) {
667 if (asprintf(author, "%s <%s>", name, email)
668 == -1)
669 return got_error_from_errno("asprintf");
670 return NULL;
672 /* TODO: Look up user in password database? */
673 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
677 *author = strdup(got_author);
678 if (*author == NULL)
679 return got_error_from_errno("strdup");
681 if (!valid_author(*author)) {
682 err = got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", *author);
683 free(*author);
684 *author = NULL;
686 return err;
689 static const struct got_error *
690 get_gitconfig_path(char **gitconfig_path)
692 const char *homedir = getenv("HOME");
694 *gitconfig_path = NULL;
695 if (homedir) {
696 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
697 return got_error_from_errno("asprintf");
700 return NULL;
703 static const struct got_error *
704 cmd_import(int argc, char *argv[])
706 const struct got_error *error = NULL;
707 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
708 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
709 const char *branch_name = "main";
710 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
711 struct got_repository *repo = NULL;
712 struct got_reference *branch_ref = NULL, *head_ref = NULL;
713 struct got_object_id *new_commit_id = NULL;
714 int ch;
715 struct got_pathlist_head ignores;
716 struct got_pathlist_entry *pe;
717 int preserve_logmsg = 0;
719 TAILQ_INIT(&ignores);
721 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
722 switch (ch) {
723 case 'b':
724 branch_name = optarg;
725 break;
726 case 'm':
727 logmsg = strdup(optarg);
728 if (logmsg == NULL) {
729 error = got_error_from_errno("strdup");
730 goto done;
732 break;
733 case 'r':
734 repo_path = realpath(optarg, NULL);
735 if (repo_path == NULL) {
736 error = got_error_from_errno2("realpath",
737 optarg);
738 goto done;
740 break;
741 case 'I':
742 if (optarg[0] == '\0')
743 break;
744 error = got_pathlist_insert(&pe, &ignores, optarg,
745 NULL);
746 if (error)
747 goto done;
748 break;
749 default:
750 usage_import();
751 /* NOTREACHED */
755 argc -= optind;
756 argv += optind;
758 #ifndef PROFILE
759 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
760 "unveil",
761 NULL) == -1)
762 err(1, "pledge");
763 #endif
764 if (argc != 1)
765 usage_import();
767 if (repo_path == NULL) {
768 repo_path = getcwd(NULL, 0);
769 if (repo_path == NULL)
770 return got_error_from_errno("getcwd");
772 got_path_strip_trailing_slashes(repo_path);
773 error = get_gitconfig_path(&gitconfig_path);
774 if (error)
775 goto done;
776 error = got_repo_open(&repo, repo_path, gitconfig_path);
777 if (error)
778 goto done;
780 error = get_author(&author, repo, NULL);
781 if (error)
782 return error;
784 /*
785 * Don't let the user create a branch name with a leading '-'.
786 * While technically a valid reference name, this case is usually
787 * an unintended typo.
788 */
789 if (branch_name[0] == '-')
790 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
792 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
793 error = got_error_from_errno("asprintf");
794 goto done;
797 error = got_ref_open(&branch_ref, repo, refname, 0);
798 if (error) {
799 if (error->code != GOT_ERR_NOT_REF)
800 goto done;
801 } else {
802 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
803 "import target branch already exists");
804 goto done;
807 path_dir = realpath(argv[0], NULL);
808 if (path_dir == NULL) {
809 error = got_error_from_errno2("realpath", argv[0]);
810 goto done;
812 got_path_strip_trailing_slashes(path_dir);
814 /*
815 * unveil(2) traverses exec(2); if an editor is used we have
816 * to apply unveil after the log message has been written.
817 */
818 if (logmsg == NULL || strlen(logmsg) == 0) {
819 error = get_editor(&editor);
820 if (error)
821 goto done;
822 free(logmsg);
823 error = collect_import_msg(&logmsg, &logmsg_path, editor,
824 path_dir, refname);
825 if (error) {
826 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
827 logmsg_path != NULL)
828 preserve_logmsg = 1;
829 goto done;
833 if (unveil(path_dir, "r") != 0) {
834 error = got_error_from_errno2("unveil", path_dir);
835 if (logmsg_path)
836 preserve_logmsg = 1;
837 goto done;
840 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
841 if (error) {
842 if (logmsg_path)
843 preserve_logmsg = 1;
844 goto done;
847 error = got_repo_import(&new_commit_id, path_dir, logmsg,
848 author, &ignores, repo, import_progress, NULL);
849 if (error) {
850 if (logmsg_path)
851 preserve_logmsg = 1;
852 goto done;
855 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
856 if (error) {
857 if (logmsg_path)
858 preserve_logmsg = 1;
859 goto done;
862 error = got_ref_write(branch_ref, repo);
863 if (error) {
864 if (logmsg_path)
865 preserve_logmsg = 1;
866 goto done;
869 error = got_object_id_str(&id_str, new_commit_id);
870 if (error) {
871 if (logmsg_path)
872 preserve_logmsg = 1;
873 goto done;
876 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
877 if (error) {
878 if (error->code != GOT_ERR_NOT_REF) {
879 if (logmsg_path)
880 preserve_logmsg = 1;
881 goto done;
884 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
885 branch_ref);
886 if (error) {
887 if (logmsg_path)
888 preserve_logmsg = 1;
889 goto done;
892 error = got_ref_write(head_ref, repo);
893 if (error) {
894 if (logmsg_path)
895 preserve_logmsg = 1;
896 goto done;
900 printf("Created branch %s with commit %s\n",
901 got_ref_get_name(branch_ref), id_str);
902 done:
903 if (preserve_logmsg) {
904 fprintf(stderr, "%s: log message preserved in %s\n",
905 getprogname(), logmsg_path);
906 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
907 error = got_error_from_errno2("unlink", logmsg_path);
908 free(logmsg);
909 free(logmsg_path);
910 free(repo_path);
911 free(editor);
912 free(refname);
913 free(new_commit_id);
914 free(id_str);
915 free(author);
916 free(gitconfig_path);
917 if (branch_ref)
918 got_ref_close(branch_ref);
919 if (head_ref)
920 got_ref_close(head_ref);
921 return error;
924 __dead static void
925 usage_clone(void)
927 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
928 "[-R reference] repository-url [directory]\n", getprogname());
929 exit(1);
932 struct got_fetch_progress_arg {
933 char last_scaled_size[FMT_SCALED_STRSIZE];
934 int last_p_indexed;
935 int last_p_resolved;
936 int verbosity;
938 struct got_repository *repo;
940 int create_configs;
941 int configs_created;
942 struct {
943 struct got_pathlist_head *symrefs;
944 struct got_pathlist_head *wanted_branches;
945 struct got_pathlist_head *wanted_refs;
946 const char *proto;
947 const char *host;
948 const char *port;
949 const char *remote_repo_path;
950 const char *git_url;
951 int fetch_all_branches;
952 int mirror_references;
953 } config_info;
954 };
956 /* XXX forward declaration */
957 static const struct got_error *
958 create_config_files(const char *proto, const char *host, const char *port,
959 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
960 int mirror_references, struct got_pathlist_head *symrefs,
961 struct got_pathlist_head *wanted_branches,
962 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
964 static const struct got_error *
965 fetch_progress(void *arg, const char *message, off_t packfile_size,
966 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
968 const struct got_error *err = NULL;
969 struct got_fetch_progress_arg *a = arg;
970 char scaled_size[FMT_SCALED_STRSIZE];
971 int p_indexed, p_resolved;
972 int print_size = 0, print_indexed = 0, print_resolved = 0;
974 /*
975 * In order to allow a failed clone to be resumed with 'got fetch'
976 * we try to create configuration files as soon as possible.
977 * Once the server has sent information about its default branch
978 * we have all required information.
979 */
980 if (a->create_configs && !a->configs_created &&
981 !TAILQ_EMPTY(a->config_info.symrefs)) {
982 err = create_config_files(a->config_info.proto,
983 a->config_info.host, a->config_info.port,
984 a->config_info.remote_repo_path,
985 a->config_info.git_url,
986 a->config_info.fetch_all_branches,
987 a->config_info.mirror_references,
988 a->config_info.symrefs,
989 a->config_info.wanted_branches,
990 a->config_info.wanted_refs, a->repo);
991 if (err)
992 return err;
993 a->configs_created = 1;
996 if (a->verbosity < 0)
997 return NULL;
999 if (message && message[0] != '\0') {
1000 printf("\rserver: %s", message);
1001 fflush(stdout);
1002 return NULL;
1005 if (packfile_size > 0 || nobj_indexed > 0) {
1006 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1007 (a->last_scaled_size[0] == '\0' ||
1008 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1009 print_size = 1;
1010 if (strlcpy(a->last_scaled_size, scaled_size,
1011 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1012 return got_error(GOT_ERR_NO_SPACE);
1014 if (nobj_indexed > 0) {
1015 p_indexed = (nobj_indexed * 100) / nobj_total;
1016 if (p_indexed != a->last_p_indexed) {
1017 a->last_p_indexed = p_indexed;
1018 print_indexed = 1;
1019 print_size = 1;
1022 if (nobj_resolved > 0) {
1023 p_resolved = (nobj_resolved * 100) /
1024 (nobj_total - nobj_loose);
1025 if (p_resolved != a->last_p_resolved) {
1026 a->last_p_resolved = p_resolved;
1027 print_resolved = 1;
1028 print_indexed = 1;
1029 print_size = 1;
1034 if (print_size || print_indexed || print_resolved)
1035 printf("\r");
1036 if (print_size)
1037 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1038 if (print_indexed)
1039 printf("; indexing %d%%", p_indexed);
1040 if (print_resolved)
1041 printf("; resolving deltas %d%%", p_resolved);
1042 if (print_size || print_indexed || print_resolved)
1043 fflush(stdout);
1045 return NULL;
1048 static const struct got_error *
1049 create_symref(const char *refname, struct got_reference *target_ref,
1050 int verbosity, struct got_repository *repo)
1052 const struct got_error *err;
1053 struct got_reference *head_symref;
1055 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1056 if (err)
1057 return err;
1059 err = got_ref_write(head_symref, repo);
1060 if (err == NULL && verbosity > 0) {
1061 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1062 got_ref_get_name(target_ref));
1064 got_ref_close(head_symref);
1065 return err;
1068 static const struct got_error *
1069 list_remote_refs(struct got_pathlist_head *symrefs,
1070 struct got_pathlist_head *refs)
1072 const struct got_error *err;
1073 struct got_pathlist_entry *pe;
1075 TAILQ_FOREACH(pe, symrefs, entry) {
1076 const char *refname = pe->path;
1077 const char *targetref = pe->data;
1079 printf("%s: %s\n", refname, targetref);
1082 TAILQ_FOREACH(pe, refs, entry) {
1083 const char *refname = pe->path;
1084 struct got_object_id *id = pe->data;
1085 char *id_str;
1087 err = got_object_id_str(&id_str, id);
1088 if (err)
1089 return err;
1090 printf("%s: %s\n", refname, id_str);
1091 free(id_str);
1094 return NULL;
1097 static const struct got_error *
1098 create_ref(const char *refname, struct got_object_id *id,
1099 int verbosity, struct got_repository *repo)
1101 const struct got_error *err = NULL;
1102 struct got_reference *ref;
1103 char *id_str;
1105 err = got_object_id_str(&id_str, id);
1106 if (err)
1107 return err;
1109 err = got_ref_alloc(&ref, refname, id);
1110 if (err)
1111 goto done;
1113 err = got_ref_write(ref, repo);
1114 got_ref_close(ref);
1116 if (err == NULL && verbosity >= 0)
1117 printf("Created reference %s: %s\n", refname, id_str);
1118 done:
1119 free(id_str);
1120 return err;
1123 static int
1124 match_wanted_ref(const char *refname, const char *wanted_ref)
1126 if (strncmp(refname, "refs/", 5) != 0)
1127 return 0;
1128 refname += 5;
1131 * Prevent fetching of references that won't make any
1132 * sense outside of the remote repository's context.
1134 if (strncmp(refname, "got/", 4) == 0)
1135 return 0;
1136 if (strncmp(refname, "remotes/", 8) == 0)
1137 return 0;
1139 if (strncmp(wanted_ref, "refs/", 5) == 0)
1140 wanted_ref += 5;
1142 /* Allow prefix match. */
1143 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1144 return 1;
1146 /* Allow exact match. */
1147 return (strcmp(refname, wanted_ref) == 0);
1150 static int
1151 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1153 struct got_pathlist_entry *pe;
1155 TAILQ_FOREACH(pe, wanted_refs, entry) {
1156 if (match_wanted_ref(refname, pe->path))
1157 return 1;
1160 return 0;
1163 static const struct got_error *
1164 create_wanted_ref(const char *refname, struct got_object_id *id,
1165 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1167 const struct got_error *err;
1168 char *remote_refname;
1170 if (strncmp("refs/", refname, 5) == 0)
1171 refname += 5;
1173 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1174 remote_repo_name, refname) == -1)
1175 return got_error_from_errno("asprintf");
1177 err = create_ref(remote_refname, id, verbosity, repo);
1178 free(remote_refname);
1179 return err;
1182 static const struct got_error *
1183 create_gotconfig(const char *proto, const char *host, const char *port,
1184 const char *remote_repo_path, const char *default_branch,
1185 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1186 struct got_pathlist_head *wanted_refs, int mirror_references,
1187 struct got_repository *repo)
1189 const struct got_error *err = NULL;
1190 char *gotconfig_path = NULL;
1191 char *gotconfig = NULL;
1192 FILE *gotconfig_file = NULL;
1193 const char *branchname = NULL;
1194 char *branches = NULL, *refs = NULL;
1195 ssize_t n;
1197 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1198 struct got_pathlist_entry *pe;
1199 TAILQ_FOREACH(pe, wanted_branches, entry) {
1200 char *s;
1201 branchname = pe->path;
1202 if (strncmp(branchname, "refs/heads/", 11) == 0)
1203 branchname += 11;
1204 if (asprintf(&s, "%s\"%s\" ",
1205 branches ? branches : "", branchname) == -1) {
1206 err = got_error_from_errno("asprintf");
1207 goto done;
1209 free(branches);
1210 branches = s;
1212 } else if (!fetch_all_branches && default_branch) {
1213 branchname = default_branch;
1214 if (strncmp(branchname, "refs/heads/", 11) == 0)
1215 branchname += 11;
1216 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1217 err = got_error_from_errno("asprintf");
1218 goto done;
1221 if (!TAILQ_EMPTY(wanted_refs)) {
1222 struct got_pathlist_entry *pe;
1223 TAILQ_FOREACH(pe, wanted_refs, entry) {
1224 char *s;
1225 const char *refname = pe->path;
1226 if (strncmp(refname, "refs/", 5) == 0)
1227 branchname += 5;
1228 if (asprintf(&s, "%s\"%s\" ",
1229 refs ? refs : "", refname) == -1) {
1230 err = got_error_from_errno("asprintf");
1231 goto done;
1233 free(refs);
1234 refs = s;
1238 /* Create got.conf(5). */
1239 gotconfig_path = got_repo_get_path_gotconfig(repo);
1240 if (gotconfig_path == NULL) {
1241 err = got_error_from_errno("got_repo_get_path_gotconfig");
1242 goto done;
1244 gotconfig_file = fopen(gotconfig_path, "ae");
1245 if (gotconfig_file == NULL) {
1246 err = got_error_from_errno2("fopen", gotconfig_path);
1247 goto done;
1249 if (asprintf(&gotconfig,
1250 "remote \"%s\" {\n"
1251 "\tserver %s\n"
1252 "\tprotocol %s\n"
1253 "%s%s%s"
1254 "\trepository \"%s\"\n"
1255 "%s%s%s"
1256 "%s%s%s"
1257 "%s"
1258 "%s"
1259 "}\n",
1260 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1261 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1262 remote_repo_path, branches ? "\tbranch { " : "",
1263 branches ? branches : "", branches ? "}\n" : "",
1264 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1265 mirror_references ? "\tmirror-references yes\n" : "",
1266 fetch_all_branches ? "\tfetch-all-branches yes\n" : "") == -1) {
1267 err = got_error_from_errno("asprintf");
1268 goto done;
1270 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1271 if (n != strlen(gotconfig)) {
1272 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1273 goto done;
1276 done:
1277 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1278 err = got_error_from_errno2("fclose", gotconfig_path);
1279 free(gotconfig_path);
1280 free(branches);
1281 return err;
1284 static const struct got_error *
1285 create_gitconfig(const char *git_url, const char *default_branch,
1286 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1287 struct got_pathlist_head *wanted_refs, int mirror_references,
1288 struct got_repository *repo)
1290 const struct got_error *err = NULL;
1291 char *gitconfig_path = NULL;
1292 char *gitconfig = NULL;
1293 FILE *gitconfig_file = NULL;
1294 char *branches = NULL, *refs = NULL;
1295 const char *branchname;
1296 ssize_t n;
1298 /* Create a config file Git can understand. */
1299 gitconfig_path = got_repo_get_path_gitconfig(repo);
1300 if (gitconfig_path == NULL) {
1301 err = got_error_from_errno("got_repo_get_path_gitconfig");
1302 goto done;
1304 gitconfig_file = fopen(gitconfig_path, "ae");
1305 if (gitconfig_file == NULL) {
1306 err = got_error_from_errno2("fopen", gitconfig_path);
1307 goto done;
1309 if (fetch_all_branches) {
1310 if (mirror_references) {
1311 if (asprintf(&branches,
1312 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1313 err = got_error_from_errno("asprintf");
1314 goto done;
1316 } else if (asprintf(&branches,
1317 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1318 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1319 err = got_error_from_errno("asprintf");
1320 goto done;
1322 } else if (!TAILQ_EMPTY(wanted_branches)) {
1323 struct got_pathlist_entry *pe;
1324 TAILQ_FOREACH(pe, wanted_branches, entry) {
1325 char *s;
1326 branchname = pe->path;
1327 if (strncmp(branchname, "refs/heads/", 11) == 0)
1328 branchname += 11;
1329 if (mirror_references) {
1330 if (asprintf(&s,
1331 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1332 branches ? branches : "",
1333 branchname, branchname) == -1) {
1334 err = got_error_from_errno("asprintf");
1335 goto done;
1337 } else if (asprintf(&s,
1338 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1339 branches ? branches : "",
1340 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1341 branchname) == -1) {
1342 err = got_error_from_errno("asprintf");
1343 goto done;
1345 free(branches);
1346 branches = s;
1348 } else {
1350 * If the server specified a default branch, use just that one.
1351 * Otherwise fall back to fetching all branches on next fetch.
1353 if (default_branch) {
1354 branchname = default_branch;
1355 if (strncmp(branchname, "refs/heads/", 11) == 0)
1356 branchname += 11;
1357 } else
1358 branchname = "*"; /* fall back to all branches */
1359 if (mirror_references) {
1360 if (asprintf(&branches,
1361 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1362 branchname, branchname) == -1) {
1363 err = got_error_from_errno("asprintf");
1364 goto done;
1366 } else if (asprintf(&branches,
1367 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1368 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1369 branchname) == -1) {
1370 err = got_error_from_errno("asprintf");
1371 goto done;
1374 if (!TAILQ_EMPTY(wanted_refs)) {
1375 struct got_pathlist_entry *pe;
1376 TAILQ_FOREACH(pe, wanted_refs, entry) {
1377 char *s;
1378 const char *refname = pe->path;
1379 if (strncmp(refname, "refs/", 5) == 0)
1380 refname += 5;
1381 if (mirror_references) {
1382 if (asprintf(&s,
1383 "%s\tfetch = refs/%s:refs/%s\n",
1384 refs ? refs : "", refname, refname) == -1) {
1385 err = got_error_from_errno("asprintf");
1386 goto done;
1388 } else if (asprintf(&s,
1389 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1390 refs ? refs : "",
1391 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1392 refname) == -1) {
1393 err = got_error_from_errno("asprintf");
1394 goto done;
1396 free(refs);
1397 refs = s;
1401 if (asprintf(&gitconfig,
1402 "[remote \"%s\"]\n"
1403 "\turl = %s\n"
1404 "%s"
1405 "%s"
1406 "\tfetch = refs/tags/*:refs/tags/*\n",
1407 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1408 refs ? refs : "") == -1) {
1409 err = got_error_from_errno("asprintf");
1410 goto done;
1412 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1413 if (n != strlen(gitconfig)) {
1414 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1415 goto done;
1417 done:
1418 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1419 err = got_error_from_errno2("fclose", gitconfig_path);
1420 free(gitconfig_path);
1421 free(branches);
1422 return err;
1425 static const struct got_error *
1426 create_config_files(const char *proto, const char *host, const char *port,
1427 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1428 int mirror_references, struct got_pathlist_head *symrefs,
1429 struct got_pathlist_head *wanted_branches,
1430 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1432 const struct got_error *err = NULL;
1433 const char *default_branch = NULL;
1434 struct got_pathlist_entry *pe;
1437 * If we asked for a set of wanted branches then use the first
1438 * one of those.
1440 if (!TAILQ_EMPTY(wanted_branches)) {
1441 pe = TAILQ_FIRST(wanted_branches);
1442 default_branch = pe->path;
1443 } else {
1444 /* First HEAD ref listed by server is the default branch. */
1445 TAILQ_FOREACH(pe, symrefs, entry) {
1446 const char *refname = pe->path;
1447 const char *target = pe->data;
1449 if (strcmp(refname, GOT_REF_HEAD) != 0)
1450 continue;
1452 default_branch = target;
1453 break;
1457 /* Create got.conf(5). */
1458 err = create_gotconfig(proto, host, port, remote_repo_path,
1459 default_branch, fetch_all_branches, wanted_branches,
1460 wanted_refs, mirror_references, repo);
1461 if (err)
1462 return err;
1464 /* Create a config file Git can understand. */
1465 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1466 wanted_branches, wanted_refs, mirror_references, repo);
1469 static const struct got_error *
1470 cmd_clone(int argc, char *argv[])
1472 const struct got_error *error = NULL;
1473 const char *uri, *dirname;
1474 char *proto, *host, *port, *repo_name, *server_path;
1475 char *default_destdir = NULL, *id_str = NULL;
1476 const char *repo_path;
1477 struct got_repository *repo = NULL;
1478 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1479 struct got_pathlist_entry *pe;
1480 struct got_object_id *pack_hash = NULL;
1481 int ch, fetchfd = -1, fetchstatus;
1482 pid_t fetchpid = -1;
1483 struct got_fetch_progress_arg fpa;
1484 char *git_url = NULL;
1485 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1486 int list_refs_only = 0;
1488 TAILQ_INIT(&refs);
1489 TAILQ_INIT(&symrefs);
1490 TAILQ_INIT(&wanted_branches);
1491 TAILQ_INIT(&wanted_refs);
1493 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1494 switch (ch) {
1495 case 'a':
1496 fetch_all_branches = 1;
1497 break;
1498 case 'b':
1499 error = got_pathlist_append(&wanted_branches,
1500 optarg, NULL);
1501 if (error)
1502 return error;
1503 break;
1504 case 'l':
1505 list_refs_only = 1;
1506 break;
1507 case 'm':
1508 mirror_references = 1;
1509 break;
1510 case 'v':
1511 if (verbosity < 0)
1512 verbosity = 0;
1513 else if (verbosity < 3)
1514 verbosity++;
1515 break;
1516 case 'q':
1517 verbosity = -1;
1518 break;
1519 case 'R':
1520 error = got_pathlist_append(&wanted_refs,
1521 optarg, NULL);
1522 if (error)
1523 return error;
1524 break;
1525 default:
1526 usage_clone();
1527 break;
1530 argc -= optind;
1531 argv += optind;
1533 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1534 option_conflict('a', 'b');
1535 if (list_refs_only) {
1536 if (!TAILQ_EMPTY(&wanted_branches))
1537 option_conflict('l', 'b');
1538 if (fetch_all_branches)
1539 option_conflict('l', 'a');
1540 if (mirror_references)
1541 option_conflict('l', 'm');
1542 if (!TAILQ_EMPTY(&wanted_refs))
1543 option_conflict('l', 'R');
1546 uri = argv[0];
1548 if (argc == 1)
1549 dirname = NULL;
1550 else if (argc == 2)
1551 dirname = argv[1];
1552 else
1553 usage_clone();
1555 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1556 &repo_name, uri);
1557 if (error)
1558 goto done;
1560 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1561 host, port ? ":" : "", port ? port : "",
1562 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1563 error = got_error_from_errno("asprintf");
1564 goto done;
1567 if (strcmp(proto, "git") == 0) {
1568 #ifndef PROFILE
1569 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1570 "sendfd dns inet unveil", NULL) == -1)
1571 err(1, "pledge");
1572 #endif
1573 } else if (strcmp(proto, "git+ssh") == 0 ||
1574 strcmp(proto, "ssh") == 0) {
1575 #ifndef PROFILE
1576 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1577 "sendfd unveil", NULL) == -1)
1578 err(1, "pledge");
1579 #endif
1580 } else if (strcmp(proto, "http") == 0 ||
1581 strcmp(proto, "git+http") == 0) {
1582 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1583 goto done;
1584 } else {
1585 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1586 goto done;
1588 if (dirname == NULL) {
1589 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1590 error = got_error_from_errno("asprintf");
1591 goto done;
1593 repo_path = default_destdir;
1594 } else
1595 repo_path = dirname;
1597 if (!list_refs_only) {
1598 error = got_path_mkdir(repo_path);
1599 if (error &&
1600 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1601 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1602 goto done;
1603 if (!got_path_dir_is_empty(repo_path)) {
1604 error = got_error_path(repo_path,
1605 GOT_ERR_DIR_NOT_EMPTY);
1606 goto done;
1610 error = got_dial_apply_unveil(proto);
1611 if (error)
1612 goto done;
1614 error = apply_unveil(repo_path, 0, NULL);
1615 if (error)
1616 goto done;
1618 if (verbosity >= 0)
1619 printf("Connecting to %s%s%s\n", host,
1620 port ? ":" : "", port ? port : "");
1622 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1623 server_path, verbosity);
1624 if (error)
1625 goto done;
1627 if (!list_refs_only) {
1628 error = got_repo_init(repo_path);
1629 if (error)
1630 goto done;
1631 error = got_repo_open(&repo, repo_path, NULL);
1632 if (error)
1633 goto done;
1636 fpa.last_scaled_size[0] = '\0';
1637 fpa.last_p_indexed = -1;
1638 fpa.last_p_resolved = -1;
1639 fpa.verbosity = verbosity;
1640 fpa.create_configs = 1;
1641 fpa.configs_created = 0;
1642 fpa.repo = repo;
1643 fpa.config_info.symrefs = &symrefs;
1644 fpa.config_info.wanted_branches = &wanted_branches;
1645 fpa.config_info.wanted_refs = &wanted_refs;
1646 fpa.config_info.proto = proto;
1647 fpa.config_info.host = host;
1648 fpa.config_info.port = port;
1649 fpa.config_info.remote_repo_path = server_path;
1650 fpa.config_info.git_url = git_url;
1651 fpa.config_info.fetch_all_branches = fetch_all_branches;
1652 fpa.config_info.mirror_references = mirror_references;
1653 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1654 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1655 fetch_all_branches, &wanted_branches, &wanted_refs,
1656 list_refs_only, verbosity, fetchfd, repo,
1657 fetch_progress, &fpa);
1658 if (error)
1659 goto done;
1661 if (list_refs_only) {
1662 error = list_remote_refs(&symrefs, &refs);
1663 goto done;
1666 if (pack_hash == NULL) {
1667 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1668 "server sent an empty pack file");
1669 goto done;
1671 error = got_object_id_str(&id_str, pack_hash);
1672 if (error)
1673 goto done;
1674 if (verbosity >= 0)
1675 printf("\nFetched %s.pack\n", id_str);
1676 free(id_str);
1678 /* Set up references provided with the pack file. */
1679 TAILQ_FOREACH(pe, &refs, entry) {
1680 const char *refname = pe->path;
1681 struct got_object_id *id = pe->data;
1682 char *remote_refname;
1684 if (is_wanted_ref(&wanted_refs, refname) &&
1685 !mirror_references) {
1686 error = create_wanted_ref(refname, id,
1687 GOT_FETCH_DEFAULT_REMOTE_NAME,
1688 verbosity - 1, repo);
1689 if (error)
1690 goto done;
1691 continue;
1694 error = create_ref(refname, id, verbosity - 1, repo);
1695 if (error)
1696 goto done;
1698 if (mirror_references)
1699 continue;
1701 if (strncmp("refs/heads/", refname, 11) != 0)
1702 continue;
1704 if (asprintf(&remote_refname,
1705 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1706 refname + 11) == -1) {
1707 error = got_error_from_errno("asprintf");
1708 goto done;
1710 error = create_ref(remote_refname, id, verbosity - 1, repo);
1711 free(remote_refname);
1712 if (error)
1713 goto done;
1716 /* Set the HEAD reference if the server provided one. */
1717 TAILQ_FOREACH(pe, &symrefs, entry) {
1718 struct got_reference *target_ref;
1719 const char *refname = pe->path;
1720 const char *target = pe->data;
1721 char *remote_refname = NULL, *remote_target = NULL;
1723 if (strcmp(refname, GOT_REF_HEAD) != 0)
1724 continue;
1726 error = got_ref_open(&target_ref, repo, target, 0);
1727 if (error) {
1728 if (error->code == GOT_ERR_NOT_REF) {
1729 error = NULL;
1730 continue;
1732 goto done;
1735 error = create_symref(refname, target_ref, verbosity, repo);
1736 got_ref_close(target_ref);
1737 if (error)
1738 goto done;
1740 if (mirror_references)
1741 continue;
1743 if (strncmp("refs/heads/", target, 11) != 0)
1744 continue;
1746 if (asprintf(&remote_refname,
1747 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1748 refname) == -1) {
1749 error = got_error_from_errno("asprintf");
1750 goto done;
1752 if (asprintf(&remote_target,
1753 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1754 target + 11) == -1) {
1755 error = got_error_from_errno("asprintf");
1756 free(remote_refname);
1757 goto done;
1759 error = got_ref_open(&target_ref, repo, remote_target, 0);
1760 if (error) {
1761 free(remote_refname);
1762 free(remote_target);
1763 if (error->code == GOT_ERR_NOT_REF) {
1764 error = NULL;
1765 continue;
1767 goto done;
1769 error = create_symref(remote_refname, target_ref,
1770 verbosity - 1, repo);
1771 free(remote_refname);
1772 free(remote_target);
1773 got_ref_close(target_ref);
1774 if (error)
1775 goto done;
1777 if (pe == NULL) {
1779 * We failed to set the HEAD reference. If we asked for
1780 * a set of wanted branches use the first of one of those
1781 * which could be fetched instead.
1783 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1784 const char *target = pe->path;
1785 struct got_reference *target_ref;
1787 error = got_ref_open(&target_ref, repo, target, 0);
1788 if (error) {
1789 if (error->code == GOT_ERR_NOT_REF) {
1790 error = NULL;
1791 continue;
1793 goto done;
1796 error = create_symref(GOT_REF_HEAD, target_ref,
1797 verbosity, repo);
1798 got_ref_close(target_ref);
1799 if (error)
1800 goto done;
1801 break;
1805 if (verbosity >= 0)
1806 printf("Created %s repository '%s'\n",
1807 mirror_references ? "mirrored" : "cloned", repo_path);
1808 done:
1809 if (fetchpid > 0) {
1810 if (kill(fetchpid, SIGTERM) == -1)
1811 error = got_error_from_errno("kill");
1812 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1813 error = got_error_from_errno("waitpid");
1815 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1816 error = got_error_from_errno("close");
1817 if (repo) {
1818 const struct got_error *close_err = got_repo_close(repo);
1819 if (error == NULL)
1820 error = close_err;
1822 TAILQ_FOREACH(pe, &refs, entry) {
1823 free((void *)pe->path);
1824 free(pe->data);
1826 got_pathlist_free(&refs);
1827 TAILQ_FOREACH(pe, &symrefs, entry) {
1828 free((void *)pe->path);
1829 free(pe->data);
1831 got_pathlist_free(&symrefs);
1832 got_pathlist_free(&wanted_branches);
1833 got_pathlist_free(&wanted_refs);
1834 free(pack_hash);
1835 free(proto);
1836 free(host);
1837 free(port);
1838 free(server_path);
1839 free(repo_name);
1840 free(default_destdir);
1841 free(git_url);
1842 return error;
1845 static const struct got_error *
1846 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1847 int replace_tags, int verbosity, struct got_repository *repo)
1849 const struct got_error *err = NULL;
1850 char *new_id_str = NULL;
1851 struct got_object_id *old_id = NULL;
1853 err = got_object_id_str(&new_id_str, new_id);
1854 if (err)
1855 goto done;
1857 if (!replace_tags &&
1858 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1859 err = got_ref_resolve(&old_id, repo, ref);
1860 if (err)
1861 goto done;
1862 if (got_object_id_cmp(old_id, new_id) == 0)
1863 goto done;
1864 if (verbosity >= 0) {
1865 printf("Rejecting update of existing tag %s: %s\n",
1866 got_ref_get_name(ref), new_id_str);
1868 goto done;
1871 if (got_ref_is_symbolic(ref)) {
1872 if (verbosity >= 0) {
1873 printf("Replacing reference %s: %s\n",
1874 got_ref_get_name(ref),
1875 got_ref_get_symref_target(ref));
1877 err = got_ref_change_symref_to_ref(ref, new_id);
1878 if (err)
1879 goto done;
1880 err = got_ref_write(ref, repo);
1881 if (err)
1882 goto done;
1883 } else {
1884 err = got_ref_resolve(&old_id, repo, ref);
1885 if (err)
1886 goto done;
1887 if (got_object_id_cmp(old_id, new_id) == 0)
1888 goto done;
1890 err = got_ref_change_ref(ref, new_id);
1891 if (err)
1892 goto done;
1893 err = got_ref_write(ref, repo);
1894 if (err)
1895 goto done;
1898 if (verbosity >= 0)
1899 printf("Updated %s: %s\n", got_ref_get_name(ref),
1900 new_id_str);
1901 done:
1902 free(old_id);
1903 free(new_id_str);
1904 return err;
1907 static const struct got_error *
1908 update_symref(const char *refname, struct got_reference *target_ref,
1909 int verbosity, struct got_repository *repo)
1911 const struct got_error *err = NULL, *unlock_err;
1912 struct got_reference *symref;
1913 int symref_is_locked = 0;
1915 err = got_ref_open(&symref, repo, refname, 1);
1916 if (err) {
1917 if (err->code != GOT_ERR_NOT_REF)
1918 return err;
1919 err = got_ref_alloc_symref(&symref, refname, target_ref);
1920 if (err)
1921 goto done;
1923 err = got_ref_write(symref, repo);
1924 if (err)
1925 goto done;
1927 if (verbosity >= 0)
1928 printf("Created reference %s: %s\n",
1929 got_ref_get_name(symref),
1930 got_ref_get_symref_target(symref));
1931 } else {
1932 symref_is_locked = 1;
1934 if (strcmp(got_ref_get_symref_target(symref),
1935 got_ref_get_name(target_ref)) == 0)
1936 goto done;
1938 err = got_ref_change_symref(symref,
1939 got_ref_get_name(target_ref));
1940 if (err)
1941 goto done;
1943 err = got_ref_write(symref, repo);
1944 if (err)
1945 goto done;
1947 if (verbosity >= 0)
1948 printf("Updated %s: %s\n", got_ref_get_name(symref),
1949 got_ref_get_symref_target(symref));
1952 done:
1953 if (symref_is_locked) {
1954 unlock_err = got_ref_unlock(symref);
1955 if (unlock_err && err == NULL)
1956 err = unlock_err;
1958 got_ref_close(symref);
1959 return err;
1962 __dead static void
1963 usage_fetch(void)
1965 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1966 "[-r repository-path] [-t] [-q] [-v] [-R reference] [-X] "
1967 "[remote-repository-name]\n",
1968 getprogname());
1969 exit(1);
1972 static const struct got_error *
1973 delete_missing_ref(struct got_reference *ref,
1974 int verbosity, struct got_repository *repo)
1976 const struct got_error *err = NULL;
1977 struct got_object_id *id = NULL;
1978 char *id_str = NULL;
1980 if (got_ref_is_symbolic(ref)) {
1981 err = got_ref_delete(ref, repo);
1982 if (err)
1983 return err;
1984 if (verbosity >= 0) {
1985 printf("Deleted %s: %s\n",
1986 got_ref_get_name(ref),
1987 got_ref_get_symref_target(ref));
1989 } else {
1990 err = got_ref_resolve(&id, repo, ref);
1991 if (err)
1992 return err;
1993 err = got_object_id_str(&id_str, id);
1994 if (err)
1995 goto done;
1997 err = got_ref_delete(ref, repo);
1998 if (err)
1999 goto done;
2000 if (verbosity >= 0) {
2001 printf("Deleted %s: %s\n",
2002 got_ref_get_name(ref), id_str);
2005 done:
2006 free(id);
2007 free(id_str);
2008 return NULL;
2011 static const struct got_error *
2012 delete_missing_refs(struct got_pathlist_head *their_refs,
2013 struct got_pathlist_head *their_symrefs,
2014 const struct got_remote_repo *remote,
2015 int verbosity, struct got_repository *repo)
2017 const struct got_error *err = NULL, *unlock_err;
2018 struct got_reflist_head my_refs;
2019 struct got_reflist_entry *re;
2020 struct got_pathlist_entry *pe;
2021 char *remote_namespace = NULL;
2022 char *local_refname = NULL;
2024 TAILQ_INIT(&my_refs);
2026 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2027 == -1)
2028 return got_error_from_errno("asprintf");
2030 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2031 if (err)
2032 goto done;
2034 TAILQ_FOREACH(re, &my_refs, entry) {
2035 const char *refname = got_ref_get_name(re->ref);
2036 const char *their_refname;
2038 if (remote->mirror_references) {
2039 their_refname = refname;
2040 } else {
2041 if (strncmp(refname, remote_namespace,
2042 strlen(remote_namespace)) == 0) {
2043 if (strcmp(refname + strlen(remote_namespace),
2044 GOT_REF_HEAD) == 0)
2045 continue;
2046 if (asprintf(&local_refname, "refs/heads/%s",
2047 refname + strlen(remote_namespace)) == -1) {
2048 err = got_error_from_errno("asprintf");
2049 goto done;
2051 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2052 continue;
2054 their_refname = local_refname;
2057 TAILQ_FOREACH(pe, their_refs, entry) {
2058 if (strcmp(their_refname, pe->path) == 0)
2059 break;
2061 if (pe != NULL)
2062 continue;
2064 TAILQ_FOREACH(pe, their_symrefs, entry) {
2065 if (strcmp(their_refname, pe->path) == 0)
2066 break;
2068 if (pe != NULL)
2069 continue;
2071 err = delete_missing_ref(re->ref, verbosity, repo);
2072 if (err)
2073 break;
2075 if (local_refname) {
2076 struct got_reference *ref;
2077 err = got_ref_open(&ref, repo, local_refname, 1);
2078 if (err) {
2079 if (err->code != GOT_ERR_NOT_REF)
2080 break;
2081 free(local_refname);
2082 local_refname = NULL;
2083 continue;
2085 err = delete_missing_ref(ref, verbosity, repo);
2086 if (err)
2087 break;
2088 unlock_err = got_ref_unlock(ref);
2089 got_ref_close(ref);
2090 if (unlock_err && err == NULL) {
2091 err = unlock_err;
2092 break;
2095 free(local_refname);
2096 local_refname = NULL;
2099 done:
2100 free(remote_namespace);
2101 free(local_refname);
2102 return err;
2105 static const struct got_error *
2106 update_wanted_ref(const char *refname, struct got_object_id *id,
2107 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2109 const struct got_error *err, *unlock_err;
2110 char *remote_refname;
2111 struct got_reference *ref;
2113 if (strncmp("refs/", refname, 5) == 0)
2114 refname += 5;
2116 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2117 remote_repo_name, refname) == -1)
2118 return got_error_from_errno("asprintf");
2120 err = got_ref_open(&ref, repo, remote_refname, 1);
2121 if (err) {
2122 if (err->code != GOT_ERR_NOT_REF)
2123 goto done;
2124 err = create_ref(remote_refname, id, verbosity, repo);
2125 } else {
2126 err = update_ref(ref, id, 0, verbosity, repo);
2127 unlock_err = got_ref_unlock(ref);
2128 if (unlock_err && err == NULL)
2129 err = unlock_err;
2130 got_ref_close(ref);
2132 done:
2133 free(remote_refname);
2134 return err;
2137 static const struct got_error *
2138 delete_ref(struct got_repository *repo, struct got_reference *ref)
2140 const struct got_error *err = NULL;
2141 struct got_object_id *id = NULL;
2142 char *id_str = NULL;
2143 const char *target;
2145 if (got_ref_is_symbolic(ref)) {
2146 target = got_ref_get_symref_target(ref);
2147 } else {
2148 err = got_ref_resolve(&id, repo, ref);
2149 if (err)
2150 goto done;
2151 err = got_object_id_str(&id_str, id);
2152 if (err)
2153 goto done;
2154 target = id_str;
2157 err = got_ref_delete(ref, repo);
2158 if (err)
2159 goto done;
2161 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2162 done:
2163 free(id);
2164 free(id_str);
2165 return err;
2168 static const struct got_error *
2169 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2171 const struct got_error *err = NULL;
2172 struct got_reflist_head refs;
2173 struct got_reflist_entry *re;
2174 char *prefix;
2176 TAILQ_INIT(&refs);
2178 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2179 err = got_error_from_errno("asprintf");
2180 goto done;
2182 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2183 if (err)
2184 goto done;
2186 TAILQ_FOREACH(re, &refs, entry)
2187 delete_ref(repo, re->ref);
2188 done:
2189 got_ref_list_free(&refs);
2190 return err;
2193 static const struct got_error *
2194 cmd_fetch(int argc, char *argv[])
2196 const struct got_error *error = NULL, *unlock_err;
2197 char *cwd = NULL, *repo_path = NULL;
2198 const char *remote_name;
2199 char *proto = NULL, *host = NULL, *port = NULL;
2200 char *repo_name = NULL, *server_path = NULL;
2201 const struct got_remote_repo *remotes, *remote = NULL;
2202 int nremotes;
2203 char *id_str = NULL;
2204 struct got_repository *repo = NULL;
2205 struct got_worktree *worktree = NULL;
2206 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2207 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2208 struct got_pathlist_entry *pe;
2209 struct got_object_id *pack_hash = NULL;
2210 int i, ch, fetchfd = -1, fetchstatus;
2211 pid_t fetchpid = -1;
2212 struct got_fetch_progress_arg fpa;
2213 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2214 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2216 TAILQ_INIT(&refs);
2217 TAILQ_INIT(&symrefs);
2218 TAILQ_INIT(&wanted_branches);
2219 TAILQ_INIT(&wanted_refs);
2221 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2222 switch (ch) {
2223 case 'a':
2224 fetch_all_branches = 1;
2225 break;
2226 case 'b':
2227 error = got_pathlist_append(&wanted_branches,
2228 optarg, NULL);
2229 if (error)
2230 return error;
2231 break;
2232 case 'd':
2233 delete_refs = 1;
2234 break;
2235 case 'l':
2236 list_refs_only = 1;
2237 break;
2238 case 'r':
2239 repo_path = realpath(optarg, NULL);
2240 if (repo_path == NULL)
2241 return got_error_from_errno2("realpath",
2242 optarg);
2243 got_path_strip_trailing_slashes(repo_path);
2244 break;
2245 case 't':
2246 replace_tags = 1;
2247 break;
2248 case 'v':
2249 if (verbosity < 0)
2250 verbosity = 0;
2251 else if (verbosity < 3)
2252 verbosity++;
2253 break;
2254 case 'q':
2255 verbosity = -1;
2256 break;
2257 case 'R':
2258 error = got_pathlist_append(&wanted_refs,
2259 optarg, NULL);
2260 if (error)
2261 return error;
2262 break;
2263 case 'X':
2264 delete_remote = 1;
2265 break;
2266 default:
2267 usage_fetch();
2268 break;
2271 argc -= optind;
2272 argv += optind;
2274 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2275 option_conflict('a', 'b');
2276 if (list_refs_only) {
2277 if (!TAILQ_EMPTY(&wanted_branches))
2278 option_conflict('l', 'b');
2279 if (fetch_all_branches)
2280 option_conflict('l', 'a');
2281 if (delete_refs)
2282 option_conflict('l', 'd');
2283 if (delete_remote)
2284 option_conflict('l', 'X');
2286 if (delete_remote) {
2287 if (fetch_all_branches)
2288 option_conflict('X', 'a');
2289 if (!TAILQ_EMPTY(&wanted_branches))
2290 option_conflict('X', 'b');
2291 if (delete_refs)
2292 option_conflict('X', 'd');
2293 if (replace_tags)
2294 option_conflict('X', 't');
2295 if (!TAILQ_EMPTY(&wanted_refs))
2296 option_conflict('X', 'R');
2299 if (argc == 0) {
2300 if (delete_remote)
2301 errx(1, "-X option requires a remote name");
2302 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2303 } else if (argc == 1)
2304 remote_name = argv[0];
2305 else
2306 usage_fetch();
2308 cwd = getcwd(NULL, 0);
2309 if (cwd == NULL) {
2310 error = got_error_from_errno("getcwd");
2311 goto done;
2314 if (repo_path == NULL) {
2315 error = got_worktree_open(&worktree, cwd);
2316 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2317 goto done;
2318 else
2319 error = NULL;
2320 if (worktree) {
2321 repo_path =
2322 strdup(got_worktree_get_repo_path(worktree));
2323 if (repo_path == NULL)
2324 error = got_error_from_errno("strdup");
2325 if (error)
2326 goto done;
2327 } else {
2328 repo_path = strdup(cwd);
2329 if (repo_path == NULL) {
2330 error = got_error_from_errno("strdup");
2331 goto done;
2336 error = got_repo_open(&repo, repo_path, NULL);
2337 if (error)
2338 goto done;
2340 if (delete_remote) {
2341 error = delete_refs_for_remote(repo, remote_name);
2342 goto done; /* nothing else to do */
2345 if (worktree) {
2346 worktree_conf = got_worktree_get_gotconfig(worktree);
2347 if (worktree_conf) {
2348 got_gotconfig_get_remotes(&nremotes, &remotes,
2349 worktree_conf);
2350 for (i = 0; i < nremotes; i++) {
2351 if (strcmp(remotes[i].name, remote_name) == 0) {
2352 remote = &remotes[i];
2353 break;
2358 if (remote == NULL) {
2359 repo_conf = got_repo_get_gotconfig(repo);
2360 if (repo_conf) {
2361 got_gotconfig_get_remotes(&nremotes, &remotes,
2362 repo_conf);
2363 for (i = 0; i < nremotes; i++) {
2364 if (strcmp(remotes[i].name, remote_name) == 0) {
2365 remote = &remotes[i];
2366 break;
2371 if (remote == NULL) {
2372 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2373 for (i = 0; i < nremotes; i++) {
2374 if (strcmp(remotes[i].name, remote_name) == 0) {
2375 remote = &remotes[i];
2376 break;
2380 if (remote == NULL) {
2381 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2382 goto done;
2385 if (TAILQ_EMPTY(&wanted_branches)) {
2386 if (!fetch_all_branches)
2387 fetch_all_branches = remote->fetch_all_branches;
2388 for (i = 0; i < remote->nfetch_branches; i++) {
2389 got_pathlist_append(&wanted_branches,
2390 remote->fetch_branches[i], NULL);
2393 if (TAILQ_EMPTY(&wanted_refs)) {
2394 for (i = 0; i < remote->nfetch_refs; i++) {
2395 got_pathlist_append(&wanted_refs,
2396 remote->fetch_refs[i], NULL);
2400 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2401 &repo_name, remote->fetch_url);
2402 if (error)
2403 goto done;
2405 if (strcmp(proto, "git") == 0) {
2406 #ifndef PROFILE
2407 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2408 "sendfd dns inet unveil", NULL) == -1)
2409 err(1, "pledge");
2410 #endif
2411 } else if (strcmp(proto, "git+ssh") == 0 ||
2412 strcmp(proto, "ssh") == 0) {
2413 #ifndef PROFILE
2414 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2415 "sendfd unveil", NULL) == -1)
2416 err(1, "pledge");
2417 #endif
2418 } else if (strcmp(proto, "http") == 0 ||
2419 strcmp(proto, "git+http") == 0) {
2420 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2421 goto done;
2422 } else {
2423 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2424 goto done;
2427 error = got_dial_apply_unveil(proto);
2428 if (error)
2429 goto done;
2431 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2432 if (error)
2433 goto done;
2435 if (verbosity >= 0)
2436 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2437 port ? ":" : "", port ? port : "");
2439 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2440 server_path, verbosity);
2441 if (error)
2442 goto done;
2444 fpa.last_scaled_size[0] = '\0';
2445 fpa.last_p_indexed = -1;
2446 fpa.last_p_resolved = -1;
2447 fpa.verbosity = verbosity;
2448 fpa.repo = repo;
2449 fpa.create_configs = 0;
2450 fpa.configs_created = 0;
2451 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2452 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2453 remote->mirror_references, fetch_all_branches, &wanted_branches,
2454 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2455 fetch_progress, &fpa);
2456 if (error)
2457 goto done;
2459 if (list_refs_only) {
2460 error = list_remote_refs(&symrefs, &refs);
2461 goto done;
2464 if (pack_hash == NULL) {
2465 if (verbosity >= 0)
2466 printf("Already up-to-date\n");
2467 } else if (verbosity >= 0) {
2468 error = got_object_id_str(&id_str, pack_hash);
2469 if (error)
2470 goto done;
2471 printf("\nFetched %s.pack\n", id_str);
2472 free(id_str);
2473 id_str = NULL;
2476 /* Update references provided with the pack file. */
2477 TAILQ_FOREACH(pe, &refs, entry) {
2478 const char *refname = pe->path;
2479 struct got_object_id *id = pe->data;
2480 struct got_reference *ref;
2481 char *remote_refname;
2483 if (is_wanted_ref(&wanted_refs, refname) &&
2484 !remote->mirror_references) {
2485 error = update_wanted_ref(refname, id,
2486 remote->name, verbosity, repo);
2487 if (error)
2488 goto done;
2489 continue;
2492 if (remote->mirror_references ||
2493 strncmp("refs/tags/", refname, 10) == 0) {
2494 error = got_ref_open(&ref, repo, refname, 1);
2495 if (error) {
2496 if (error->code != GOT_ERR_NOT_REF)
2497 goto done;
2498 error = create_ref(refname, id, verbosity,
2499 repo);
2500 if (error)
2501 goto done;
2502 } else {
2503 error = update_ref(ref, id, replace_tags,
2504 verbosity, repo);
2505 unlock_err = got_ref_unlock(ref);
2506 if (unlock_err && error == NULL)
2507 error = unlock_err;
2508 got_ref_close(ref);
2509 if (error)
2510 goto done;
2512 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2513 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2514 remote_name, refname + 11) == -1) {
2515 error = got_error_from_errno("asprintf");
2516 goto done;
2519 error = got_ref_open(&ref, repo, remote_refname, 1);
2520 if (error) {
2521 if (error->code != GOT_ERR_NOT_REF)
2522 goto done;
2523 error = create_ref(remote_refname, id,
2524 verbosity, repo);
2525 if (error)
2526 goto done;
2527 } else {
2528 error = update_ref(ref, id, replace_tags,
2529 verbosity, repo);
2530 unlock_err = got_ref_unlock(ref);
2531 if (unlock_err && error == NULL)
2532 error = unlock_err;
2533 got_ref_close(ref);
2534 if (error)
2535 goto done;
2538 /* Also create a local branch if none exists yet. */
2539 error = got_ref_open(&ref, repo, refname, 1);
2540 if (error) {
2541 if (error->code != GOT_ERR_NOT_REF)
2542 goto done;
2543 error = create_ref(refname, id, verbosity,
2544 repo);
2545 if (error)
2546 goto done;
2547 } else {
2548 unlock_err = got_ref_unlock(ref);
2549 if (unlock_err && error == NULL)
2550 error = unlock_err;
2551 got_ref_close(ref);
2555 if (delete_refs) {
2556 error = delete_missing_refs(&refs, &symrefs, remote,
2557 verbosity, repo);
2558 if (error)
2559 goto done;
2562 if (!remote->mirror_references) {
2563 /* Update remote HEAD reference if the server provided one. */
2564 TAILQ_FOREACH(pe, &symrefs, entry) {
2565 struct got_reference *target_ref;
2566 const char *refname = pe->path;
2567 const char *target = pe->data;
2568 char *remote_refname = NULL, *remote_target = NULL;
2570 if (strcmp(refname, GOT_REF_HEAD) != 0)
2571 continue;
2573 if (strncmp("refs/heads/", target, 11) != 0)
2574 continue;
2576 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2577 remote->name, refname) == -1) {
2578 error = got_error_from_errno("asprintf");
2579 goto done;
2581 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2582 remote->name, target + 11) == -1) {
2583 error = got_error_from_errno("asprintf");
2584 free(remote_refname);
2585 goto done;
2588 error = got_ref_open(&target_ref, repo, remote_target,
2589 0);
2590 if (error) {
2591 free(remote_refname);
2592 free(remote_target);
2593 if (error->code == GOT_ERR_NOT_REF) {
2594 error = NULL;
2595 continue;
2597 goto done;
2599 error = update_symref(remote_refname, target_ref,
2600 verbosity, repo);
2601 free(remote_refname);
2602 free(remote_target);
2603 got_ref_close(target_ref);
2604 if (error)
2605 goto done;
2608 done:
2609 if (fetchpid > 0) {
2610 if (kill(fetchpid, SIGTERM) == -1)
2611 error = got_error_from_errno("kill");
2612 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2613 error = got_error_from_errno("waitpid");
2615 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2616 error = got_error_from_errno("close");
2617 if (repo) {
2618 const struct got_error *close_err = got_repo_close(repo);
2619 if (error == NULL)
2620 error = close_err;
2622 if (worktree)
2623 got_worktree_close(worktree);
2624 TAILQ_FOREACH(pe, &refs, entry) {
2625 free((void *)pe->path);
2626 free(pe->data);
2628 got_pathlist_free(&refs);
2629 TAILQ_FOREACH(pe, &symrefs, entry) {
2630 free((void *)pe->path);
2631 free(pe->data);
2633 got_pathlist_free(&symrefs);
2634 got_pathlist_free(&wanted_branches);
2635 got_pathlist_free(&wanted_refs);
2636 free(id_str);
2637 free(cwd);
2638 free(repo_path);
2639 free(pack_hash);
2640 free(proto);
2641 free(host);
2642 free(port);
2643 free(server_path);
2644 free(repo_name);
2645 return error;
2649 __dead static void
2650 usage_checkout(void)
2652 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2653 "[-p prefix] [-q] repository-path [worktree-path]\n",
2654 getprogname());
2655 exit(1);
2658 static void
2659 show_worktree_base_ref_warning(void)
2661 fprintf(stderr, "%s: warning: could not create a reference "
2662 "to the work tree's base commit; the commit could be "
2663 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2664 "repository writable and running 'got update' will prevent this\n",
2665 getprogname());
2668 struct got_checkout_progress_arg {
2669 const char *worktree_path;
2670 int had_base_commit_ref_error;
2671 int verbosity;
2674 static const struct got_error *
2675 checkout_progress(void *arg, unsigned char status, const char *path)
2677 struct got_checkout_progress_arg *a = arg;
2679 /* Base commit bump happens silently. */
2680 if (status == GOT_STATUS_BUMP_BASE)
2681 return NULL;
2683 if (status == GOT_STATUS_BASE_REF_ERR) {
2684 a->had_base_commit_ref_error = 1;
2685 return NULL;
2688 while (path[0] == '/')
2689 path++;
2691 if (a->verbosity >= 0)
2692 printf("%c %s/%s\n", status, a->worktree_path, path);
2694 return NULL;
2697 static const struct got_error *
2698 check_cancelled(void *arg)
2700 if (sigint_received || sigpipe_received)
2701 return got_error(GOT_ERR_CANCELLED);
2702 return NULL;
2705 static const struct got_error *
2706 check_linear_ancestry(struct got_object_id *commit_id,
2707 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2708 struct got_repository *repo)
2710 const struct got_error *err = NULL;
2711 struct got_object_id *yca_id;
2713 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2714 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2715 if (err)
2716 return err;
2718 if (yca_id == NULL)
2719 return got_error(GOT_ERR_ANCESTRY);
2722 * Require a straight line of history between the target commit
2723 * and the work tree's base commit.
2725 * Non-linear situations such as this require a rebase:
2727 * (commit) D F (base_commit)
2728 * \ /
2729 * C E
2730 * \ /
2731 * B (yca)
2732 * |
2733 * A
2735 * 'got update' only handles linear cases:
2736 * Update forwards in time: A (base/yca) - B - C - D (commit)
2737 * Update backwards in time: D (base) - C - B - A (commit/yca)
2739 if (allow_forwards_in_time_only) {
2740 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2741 return got_error(GOT_ERR_ANCESTRY);
2742 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2743 got_object_id_cmp(base_commit_id, yca_id) != 0)
2744 return got_error(GOT_ERR_ANCESTRY);
2746 free(yca_id);
2747 return NULL;
2750 static const struct got_error *
2751 check_same_branch(struct got_object_id *commit_id,
2752 struct got_reference *head_ref, struct got_object_id *yca_id,
2753 struct got_repository *repo)
2755 const struct got_error *err = NULL;
2756 struct got_commit_graph *graph = NULL;
2757 struct got_object_id *head_commit_id = NULL;
2758 int is_same_branch = 0;
2760 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2761 if (err)
2762 goto done;
2764 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2765 is_same_branch = 1;
2766 goto done;
2768 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2769 is_same_branch = 1;
2770 goto done;
2773 err = got_commit_graph_open(&graph, "/", 1);
2774 if (err)
2775 goto done;
2777 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2778 check_cancelled, NULL);
2779 if (err)
2780 goto done;
2782 for (;;) {
2783 struct got_object_id *id;
2784 err = got_commit_graph_iter_next(&id, graph, repo,
2785 check_cancelled, NULL);
2786 if (err) {
2787 if (err->code == GOT_ERR_ITER_COMPLETED)
2788 err = NULL;
2789 break;
2792 if (id) {
2793 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2794 break;
2795 if (got_object_id_cmp(id, commit_id) == 0) {
2796 is_same_branch = 1;
2797 break;
2801 done:
2802 if (graph)
2803 got_commit_graph_close(graph);
2804 free(head_commit_id);
2805 if (!err && !is_same_branch)
2806 err = got_error(GOT_ERR_ANCESTRY);
2807 return err;
2810 static const struct got_error *
2811 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2813 static char msg[512];
2814 const char *branch_name;
2816 if (got_ref_is_symbolic(ref))
2817 branch_name = got_ref_get_symref_target(ref);
2818 else
2819 branch_name = got_ref_get_name(ref);
2821 if (strncmp("refs/heads/", branch_name, 11) == 0)
2822 branch_name += 11;
2824 snprintf(msg, sizeof(msg),
2825 "target commit is not contained in branch '%s'; "
2826 "the branch to use must be specified with -b; "
2827 "if necessary a new branch can be created for "
2828 "this commit with 'got branch -c %s BRANCH_NAME'",
2829 branch_name, commit_id_str);
2831 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2834 static const struct got_error *
2835 cmd_checkout(int argc, char *argv[])
2837 const struct got_error *error = NULL;
2838 struct got_repository *repo = NULL;
2839 struct got_reference *head_ref = NULL, *ref = NULL;
2840 struct got_worktree *worktree = NULL;
2841 char *repo_path = NULL;
2842 char *worktree_path = NULL;
2843 const char *path_prefix = "";
2844 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2845 char *commit_id_str = NULL;
2846 struct got_object_id *commit_id = NULL;
2847 char *cwd = NULL;
2848 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2849 struct got_pathlist_head paths;
2850 struct got_checkout_progress_arg cpa;
2852 TAILQ_INIT(&paths);
2854 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2855 switch (ch) {
2856 case 'b':
2857 branch_name = optarg;
2858 break;
2859 case 'c':
2860 commit_id_str = strdup(optarg);
2861 if (commit_id_str == NULL)
2862 return got_error_from_errno("strdup");
2863 break;
2864 case 'E':
2865 allow_nonempty = 1;
2866 break;
2867 case 'p':
2868 path_prefix = optarg;
2869 break;
2870 case 'q':
2871 verbosity = -1;
2872 break;
2873 default:
2874 usage_checkout();
2875 /* NOTREACHED */
2879 argc -= optind;
2880 argv += optind;
2882 #ifndef PROFILE
2883 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2884 "unveil", NULL) == -1)
2885 err(1, "pledge");
2886 #endif
2887 if (argc == 1) {
2888 char *base, *dotgit;
2889 const char *path;
2890 repo_path = realpath(argv[0], NULL);
2891 if (repo_path == NULL)
2892 return got_error_from_errno2("realpath", argv[0]);
2893 cwd = getcwd(NULL, 0);
2894 if (cwd == NULL) {
2895 error = got_error_from_errno("getcwd");
2896 goto done;
2898 if (path_prefix[0])
2899 path = path_prefix;
2900 else
2901 path = repo_path;
2902 error = got_path_basename(&base, path);
2903 if (error)
2904 goto done;
2905 dotgit = strstr(base, ".git");
2906 if (dotgit)
2907 *dotgit = '\0';
2908 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2909 error = got_error_from_errno("asprintf");
2910 free(base);
2911 goto done;
2913 free(base);
2914 } else if (argc == 2) {
2915 repo_path = realpath(argv[0], NULL);
2916 if (repo_path == NULL) {
2917 error = got_error_from_errno2("realpath", argv[0]);
2918 goto done;
2920 worktree_path = realpath(argv[1], NULL);
2921 if (worktree_path == NULL) {
2922 if (errno != ENOENT) {
2923 error = got_error_from_errno2("realpath",
2924 argv[1]);
2925 goto done;
2927 worktree_path = strdup(argv[1]);
2928 if (worktree_path == NULL) {
2929 error = got_error_from_errno("strdup");
2930 goto done;
2933 } else
2934 usage_checkout();
2936 got_path_strip_trailing_slashes(repo_path);
2937 got_path_strip_trailing_slashes(worktree_path);
2939 error = got_repo_open(&repo, repo_path, NULL);
2940 if (error != NULL)
2941 goto done;
2943 /* Pre-create work tree path for unveil(2) */
2944 error = got_path_mkdir(worktree_path);
2945 if (error) {
2946 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2947 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2948 goto done;
2949 if (!allow_nonempty &&
2950 !got_path_dir_is_empty(worktree_path)) {
2951 error = got_error_path(worktree_path,
2952 GOT_ERR_DIR_NOT_EMPTY);
2953 goto done;
2957 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2958 if (error)
2959 goto done;
2961 error = got_ref_open(&head_ref, repo, branch_name, 0);
2962 if (error != NULL)
2963 goto done;
2965 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2966 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2967 goto done;
2969 error = got_worktree_open(&worktree, worktree_path);
2970 if (error != NULL)
2971 goto done;
2973 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2974 path_prefix);
2975 if (error != NULL)
2976 goto done;
2977 if (!same_path_prefix) {
2978 error = got_error(GOT_ERR_PATH_PREFIX);
2979 goto done;
2982 if (commit_id_str) {
2983 struct got_reflist_head refs;
2984 TAILQ_INIT(&refs);
2985 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2986 NULL);
2987 if (error)
2988 goto done;
2989 error = got_repo_match_object_id(&commit_id, NULL,
2990 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2991 got_ref_list_free(&refs);
2992 if (error)
2993 goto done;
2994 error = check_linear_ancestry(commit_id,
2995 got_worktree_get_base_commit_id(worktree), 0, repo);
2996 if (error != NULL) {
2997 if (error->code == GOT_ERR_ANCESTRY) {
2998 error = checkout_ancestry_error(
2999 head_ref, commit_id_str);
3001 goto done;
3003 error = check_same_branch(commit_id, head_ref, NULL, repo);
3004 if (error) {
3005 if (error->code == GOT_ERR_ANCESTRY) {
3006 error = checkout_ancestry_error(
3007 head_ref, commit_id_str);
3009 goto done;
3011 error = got_worktree_set_base_commit_id(worktree, repo,
3012 commit_id);
3013 if (error)
3014 goto done;
3015 /* Expand potentially abbreviated commit ID string. */
3016 free(commit_id_str);
3017 error = got_object_id_str(&commit_id_str, commit_id);
3018 if (error)
3019 goto done;
3020 } else {
3021 commit_id = got_object_id_dup(
3022 got_worktree_get_base_commit_id(worktree));
3023 if (commit_id == NULL) {
3024 error = got_error_from_errno("got_object_id_dup");
3025 goto done;
3027 error = got_object_id_str(&commit_id_str, commit_id);
3028 if (error)
3029 goto done;
3032 error = got_pathlist_append(&paths, "", NULL);
3033 if (error)
3034 goto done;
3035 cpa.worktree_path = worktree_path;
3036 cpa.had_base_commit_ref_error = 0;
3037 cpa.verbosity = verbosity;
3038 error = got_worktree_checkout_files(worktree, &paths, repo,
3039 checkout_progress, &cpa, check_cancelled, NULL);
3040 if (error != NULL)
3041 goto done;
3043 if (got_ref_is_symbolic(head_ref)) {
3044 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3045 if (error)
3046 goto done;
3047 refname = got_ref_get_name(ref);
3048 } else
3049 refname = got_ref_get_name(head_ref);
3050 printf("Checked out %s: %s\n", refname, commit_id_str);
3051 printf("Now shut up and hack\n");
3052 if (cpa.had_base_commit_ref_error)
3053 show_worktree_base_ref_warning();
3054 done:
3055 if (head_ref)
3056 got_ref_close(head_ref);
3057 if (ref)
3058 got_ref_close(ref);
3059 got_pathlist_free(&paths);
3060 free(commit_id_str);
3061 free(commit_id);
3062 free(repo_path);
3063 free(worktree_path);
3064 free(cwd);
3065 return error;
3068 struct got_update_progress_arg {
3069 int did_something;
3070 int conflicts;
3071 int obstructed;
3072 int not_updated;
3073 int missing;
3074 int not_deleted;
3075 int unversioned;
3076 int verbosity;
3079 void
3080 print_update_progress_stats(struct got_update_progress_arg *upa)
3082 if (!upa->did_something)
3083 return;
3085 if (upa->conflicts > 0)
3086 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3087 if (upa->obstructed > 0)
3088 printf("File paths obstructed by a non-regular file: %d\n",
3089 upa->obstructed);
3090 if (upa->not_updated > 0)
3091 printf("Files not updated because of existing merge "
3092 "conflicts: %d\n", upa->not_updated);
3096 * The meaning of some status codes differs between merge-style operations and
3097 * update operations. For example, the ! status code means "file was missing"
3098 * if changes were merged into the work tree, and "missing file was restored"
3099 * if the work tree was updated. This function should be used by any operation
3100 * which merges changes into the work tree without updating the work tree.
3102 void
3103 print_merge_progress_stats(struct got_update_progress_arg *upa)
3105 if (!upa->did_something)
3106 return;
3108 if (upa->conflicts > 0)
3109 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3110 if (upa->obstructed > 0)
3111 printf("File paths obstructed by a non-regular file: %d\n",
3112 upa->obstructed);
3113 if (upa->missing > 0)
3114 printf("Files which had incoming changes but could not be "
3115 "found in the work tree: %d\n", upa->missing);
3116 if (upa->not_deleted > 0)
3117 printf("Files not deleted due to differences in deleted "
3118 "content: %d\n", upa->not_deleted);
3119 if (upa->unversioned > 0)
3120 printf("Files not merged because an unversioned file was "
3121 "found in the work tree: %d\n", upa->unversioned);
3124 __dead static void
3125 usage_update(void)
3127 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [-q] "
3128 "[path ...]\n",
3129 getprogname());
3130 exit(1);
3133 static const struct got_error *
3134 update_progress(void *arg, unsigned char status, const char *path)
3136 struct got_update_progress_arg *upa = arg;
3138 if (status == GOT_STATUS_EXISTS ||
3139 status == GOT_STATUS_BASE_REF_ERR)
3140 return NULL;
3142 upa->did_something = 1;
3144 /* Base commit bump happens silently. */
3145 if (status == GOT_STATUS_BUMP_BASE)
3146 return NULL;
3148 if (status == GOT_STATUS_CONFLICT)
3149 upa->conflicts++;
3150 if (status == GOT_STATUS_OBSTRUCTED)
3151 upa->obstructed++;
3152 if (status == GOT_STATUS_CANNOT_UPDATE)
3153 upa->not_updated++;
3154 if (status == GOT_STATUS_MISSING)
3155 upa->missing++;
3156 if (status == GOT_STATUS_CANNOT_DELETE)
3157 upa->not_deleted++;
3158 if (status == GOT_STATUS_UNVERSIONED)
3159 upa->unversioned++;
3161 while (path[0] == '/')
3162 path++;
3163 if (upa->verbosity >= 0)
3164 printf("%c %s\n", status, path);
3166 return NULL;
3169 static const struct got_error *
3170 switch_head_ref(struct got_reference *head_ref,
3171 struct got_object_id *commit_id, struct got_worktree *worktree,
3172 struct got_repository *repo)
3174 const struct got_error *err = NULL;
3175 char *base_id_str;
3176 int ref_has_moved = 0;
3178 /* Trivial case: switching between two different references. */
3179 if (strcmp(got_ref_get_name(head_ref),
3180 got_worktree_get_head_ref_name(worktree)) != 0) {
3181 printf("Switching work tree from %s to %s\n",
3182 got_worktree_get_head_ref_name(worktree),
3183 got_ref_get_name(head_ref));
3184 return got_worktree_set_head_ref(worktree, head_ref);
3187 err = check_linear_ancestry(commit_id,
3188 got_worktree_get_base_commit_id(worktree), 0, repo);
3189 if (err) {
3190 if (err->code != GOT_ERR_ANCESTRY)
3191 return err;
3192 ref_has_moved = 1;
3194 if (!ref_has_moved)
3195 return NULL;
3197 /* Switching to a rebased branch with the same reference name. */
3198 err = got_object_id_str(&base_id_str,
3199 got_worktree_get_base_commit_id(worktree));
3200 if (err)
3201 return err;
3202 printf("Reference %s now points at a different branch\n",
3203 got_worktree_get_head_ref_name(worktree));
3204 printf("Switching work tree from %s to %s\n", base_id_str,
3205 got_worktree_get_head_ref_name(worktree));
3206 return NULL;
3209 static const struct got_error *
3210 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3212 const struct got_error *err;
3213 int in_progress;
3215 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3216 if (err)
3217 return err;
3218 if (in_progress)
3219 return got_error(GOT_ERR_REBASING);
3221 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3222 if (err)
3223 return err;
3224 if (in_progress)
3225 return got_error(GOT_ERR_HISTEDIT_BUSY);
3227 return NULL;
3230 static const struct got_error *
3231 check_merge_in_progress(struct got_worktree *worktree,
3232 struct got_repository *repo)
3234 const struct got_error *err;
3235 int in_progress;
3237 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3238 if (err)
3239 return err;
3240 if (in_progress)
3241 return got_error(GOT_ERR_MERGE_BUSY);
3243 return NULL;
3246 static const struct got_error *
3247 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3248 char *argv[], struct got_worktree *worktree)
3250 const struct got_error *err = NULL;
3251 char *path;
3252 struct got_pathlist_entry *new;
3253 int i;
3255 if (argc == 0) {
3256 path = strdup("");
3257 if (path == NULL)
3258 return got_error_from_errno("strdup");
3259 return got_pathlist_append(paths, path, NULL);
3262 for (i = 0; i < argc; i++) {
3263 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3264 if (err)
3265 break;
3266 err = got_pathlist_insert(&new, paths, path, NULL);
3267 if (err || new == NULL /* duplicate */) {
3268 free(path);
3269 if (err)
3270 break;
3274 return err;
3277 static const struct got_error *
3278 wrap_not_worktree_error(const struct got_error *orig_err,
3279 const char *cmdname, const char *path)
3281 const struct got_error *err;
3282 struct got_repository *repo;
3283 static char msg[512];
3285 err = got_repo_open(&repo, path, NULL);
3286 if (err)
3287 return orig_err;
3289 snprintf(msg, sizeof(msg),
3290 "'got %s' needs a work tree in addition to a git repository\n"
3291 "Work trees can be checked out from this Git repository with "
3292 "'got checkout'.\n"
3293 "The got(1) manual page contains more information.", cmdname);
3294 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3295 got_repo_close(repo);
3296 return err;
3299 static const struct got_error *
3300 cmd_update(int argc, char *argv[])
3302 const struct got_error *error = NULL;
3303 struct got_repository *repo = NULL;
3304 struct got_worktree *worktree = NULL;
3305 char *worktree_path = NULL;
3306 struct got_object_id *commit_id = NULL;
3307 char *commit_id_str = NULL;
3308 const char *branch_name = NULL;
3309 struct got_reference *head_ref = NULL;
3310 struct got_pathlist_head paths;
3311 struct got_pathlist_entry *pe;
3312 int ch, verbosity = 0;
3313 struct got_update_progress_arg upa;
3315 TAILQ_INIT(&paths);
3317 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3318 switch (ch) {
3319 case 'b':
3320 branch_name = optarg;
3321 break;
3322 case 'c':
3323 commit_id_str = strdup(optarg);
3324 if (commit_id_str == NULL)
3325 return got_error_from_errno("strdup");
3326 break;
3327 case 'q':
3328 verbosity = -1;
3329 break;
3330 default:
3331 usage_update();
3332 /* NOTREACHED */
3336 argc -= optind;
3337 argv += optind;
3339 #ifndef PROFILE
3340 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3341 "unveil", NULL) == -1)
3342 err(1, "pledge");
3343 #endif
3344 worktree_path = getcwd(NULL, 0);
3345 if (worktree_path == NULL) {
3346 error = got_error_from_errno("getcwd");
3347 goto done;
3349 error = got_worktree_open(&worktree, worktree_path);
3350 if (error) {
3351 if (error->code == GOT_ERR_NOT_WORKTREE)
3352 error = wrap_not_worktree_error(error, "update",
3353 worktree_path);
3354 goto done;
3357 error = check_rebase_or_histedit_in_progress(worktree);
3358 if (error)
3359 goto done;
3361 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3362 NULL);
3363 if (error != NULL)
3364 goto done;
3366 error = apply_unveil(got_repo_get_path(repo), 0,
3367 got_worktree_get_root_path(worktree));
3368 if (error)
3369 goto done;
3371 error = check_merge_in_progress(worktree, repo);
3372 if (error)
3373 goto done;
3375 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3376 if (error)
3377 goto done;
3379 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3380 got_worktree_get_head_ref_name(worktree), 0);
3381 if (error != NULL)
3382 goto done;
3383 if (commit_id_str == NULL) {
3384 error = got_ref_resolve(&commit_id, repo, head_ref);
3385 if (error != NULL)
3386 goto done;
3387 error = got_object_id_str(&commit_id_str, commit_id);
3388 if (error != NULL)
3389 goto done;
3390 } else {
3391 struct got_reflist_head refs;
3392 TAILQ_INIT(&refs);
3393 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3394 NULL);
3395 if (error)
3396 goto done;
3397 error = got_repo_match_object_id(&commit_id, NULL,
3398 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3399 got_ref_list_free(&refs);
3400 free(commit_id_str);
3401 commit_id_str = NULL;
3402 if (error)
3403 goto done;
3404 error = got_object_id_str(&commit_id_str, commit_id);
3405 if (error)
3406 goto done;
3409 if (branch_name) {
3410 struct got_object_id *head_commit_id;
3411 TAILQ_FOREACH(pe, &paths, entry) {
3412 if (pe->path_len == 0)
3413 continue;
3414 error = got_error_msg(GOT_ERR_BAD_PATH,
3415 "switching between branches requires that "
3416 "the entire work tree gets updated");
3417 goto done;
3419 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3420 if (error)
3421 goto done;
3422 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3423 repo);
3424 free(head_commit_id);
3425 if (error != NULL)
3426 goto done;
3427 error = check_same_branch(commit_id, head_ref, NULL, repo);
3428 if (error)
3429 goto done;
3430 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3431 if (error)
3432 goto done;
3433 } else {
3434 error = check_linear_ancestry(commit_id,
3435 got_worktree_get_base_commit_id(worktree), 0, repo);
3436 if (error != NULL) {
3437 if (error->code == GOT_ERR_ANCESTRY)
3438 error = got_error(GOT_ERR_BRANCH_MOVED);
3439 goto done;
3441 error = check_same_branch(commit_id, head_ref, NULL, repo);
3442 if (error)
3443 goto done;
3446 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3447 commit_id) != 0) {
3448 error = got_worktree_set_base_commit_id(worktree, repo,
3449 commit_id);
3450 if (error)
3451 goto done;
3454 memset(&upa, 0, sizeof(upa));
3455 upa.verbosity = verbosity;
3456 error = got_worktree_checkout_files(worktree, &paths, repo,
3457 update_progress, &upa, check_cancelled, NULL);
3458 if (error != NULL)
3459 goto done;
3461 if (upa.did_something) {
3462 printf("Updated to %s: %s\n",
3463 got_worktree_get_head_ref_name(worktree), commit_id_str);
3464 } else
3465 printf("Already up-to-date\n");
3466 print_update_progress_stats(&upa);
3467 done:
3468 free(worktree_path);
3469 TAILQ_FOREACH(pe, &paths, entry)
3470 free((char *)pe->path);
3471 got_pathlist_free(&paths);
3472 free(commit_id);
3473 free(commit_id_str);
3474 return error;
3477 static const struct got_error *
3478 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3479 const char *path, int diff_context, int ignore_whitespace,
3480 int force_text_diff, struct got_repository *repo)
3482 const struct got_error *err = NULL;
3483 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3484 FILE *f1 = NULL, *f2 = NULL;
3486 if (blob_id1) {
3487 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3488 if (err)
3489 goto done;
3490 f1 = got_opentemp();
3491 if (f1 == NULL) {
3492 err = got_error_from_errno("got_opentemp");
3493 goto done;
3497 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3498 if (err)
3499 goto done;
3501 f2 = got_opentemp();
3502 if (f2 == NULL) {
3503 err = got_error_from_errno("got_opentemp");
3504 goto done;
3507 while (path[0] == '/')
3508 path++;
3509 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3510 diff_context, ignore_whitespace, force_text_diff, stdout);
3511 done:
3512 if (blob1)
3513 got_object_blob_close(blob1);
3514 got_object_blob_close(blob2);
3515 if (f1 && fclose(f1) == EOF && err == NULL)
3516 err = got_error_from_errno("fclose");
3517 if (f2 && fclose(f2) == EOF && err == NULL)
3518 err = got_error_from_errno("fclose");
3519 return err;
3522 static const struct got_error *
3523 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3524 const char *path, int diff_context, int ignore_whitespace,
3525 int force_text_diff, struct got_repository *repo)
3527 const struct got_error *err = NULL;
3528 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3529 struct got_diff_blob_output_unidiff_arg arg;
3530 FILE *f1 = NULL, *f2 = NULL;
3532 if (tree_id1) {
3533 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3534 if (err)
3535 goto done;
3536 f1 = got_opentemp();
3537 if (f1 == NULL) {
3538 err = got_error_from_errno("got_opentemp");
3539 goto done;
3543 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3544 if (err)
3545 goto done;
3547 f2 = got_opentemp();
3548 if (f2 == NULL) {
3549 err = got_error_from_errno("got_opentemp");
3550 goto done;
3553 arg.diff_context = diff_context;
3554 arg.ignore_whitespace = ignore_whitespace;
3555 arg.force_text_diff = force_text_diff;
3556 arg.outfile = stdout;
3557 arg.line_offsets = NULL;
3558 arg.nlines = 0;
3559 while (path[0] == '/')
3560 path++;
3561 err = got_diff_tree(tree1, tree2, f1, f2, path, path, repo,
3562 got_diff_blob_output_unidiff, &arg, 1);
3563 done:
3564 if (tree1)
3565 got_object_tree_close(tree1);
3566 if (tree2)
3567 got_object_tree_close(tree2);
3568 if (f1 && fclose(f1) == EOF && err == NULL)
3569 err = got_error_from_errno("fclose");
3570 if (f2 && fclose(f2) == EOF && err == NULL)
3571 err = got_error_from_errno("fclose");
3572 return err;
3575 static const struct got_error *
3576 get_changed_paths(struct got_pathlist_head *paths,
3577 struct got_commit_object *commit, struct got_repository *repo)
3579 const struct got_error *err = NULL;
3580 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3581 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3582 struct got_object_qid *qid;
3584 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3585 if (qid != NULL) {
3586 struct got_commit_object *pcommit;
3587 err = got_object_open_as_commit(&pcommit, repo,
3588 &qid->id);
3589 if (err)
3590 return err;
3592 tree_id1 = got_object_id_dup(
3593 got_object_commit_get_tree_id(pcommit));
3594 if (tree_id1 == NULL) {
3595 got_object_commit_close(pcommit);
3596 return got_error_from_errno("got_object_id_dup");
3598 got_object_commit_close(pcommit);
3602 if (tree_id1) {
3603 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3604 if (err)
3605 goto done;
3608 tree_id2 = got_object_commit_get_tree_id(commit);
3609 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3610 if (err)
3611 goto done;
3613 err = got_diff_tree(tree1, tree2, NULL, NULL, "", "", repo,
3614 got_diff_tree_collect_changed_paths, paths, 0);
3615 done:
3616 if (tree1)
3617 got_object_tree_close(tree1);
3618 if (tree2)
3619 got_object_tree_close(tree2);
3620 free(tree_id1);
3621 return err;
3624 static const struct got_error *
3625 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3626 const char *path, int diff_context, struct got_repository *repo)
3628 const struct got_error *err = NULL;
3629 struct got_commit_object *pcommit = NULL;
3630 char *id_str1 = NULL, *id_str2 = NULL;
3631 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3632 struct got_object_qid *qid;
3634 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3635 if (qid != NULL) {
3636 err = got_object_open_as_commit(&pcommit, repo,
3637 &qid->id);
3638 if (err)
3639 return err;
3642 if (path && path[0] != '\0') {
3643 int obj_type;
3644 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3645 if (err)
3646 goto done;
3647 err = got_object_id_str(&id_str2, obj_id2);
3648 if (err) {
3649 free(obj_id2);
3650 goto done;
3652 if (pcommit) {
3653 err = got_object_id_by_path(&obj_id1, repo,
3654 pcommit, path);
3655 if (err) {
3656 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3657 free(obj_id2);
3658 goto done;
3660 } else {
3661 err = got_object_id_str(&id_str1, obj_id1);
3662 if (err) {
3663 free(obj_id2);
3664 goto done;
3668 err = got_object_get_type(&obj_type, repo, obj_id2);
3669 if (err) {
3670 free(obj_id2);
3671 goto done;
3673 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3674 switch (obj_type) {
3675 case GOT_OBJ_TYPE_BLOB:
3676 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3677 0, 0, repo);
3678 break;
3679 case GOT_OBJ_TYPE_TREE:
3680 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3681 0, 0, repo);
3682 break;
3683 default:
3684 err = got_error(GOT_ERR_OBJ_TYPE);
3685 break;
3687 free(obj_id1);
3688 free(obj_id2);
3689 } else {
3690 obj_id2 = got_object_commit_get_tree_id(commit);
3691 err = got_object_id_str(&id_str2, obj_id2);
3692 if (err)
3693 goto done;
3694 if (pcommit) {
3695 obj_id1 = got_object_commit_get_tree_id(pcommit);
3696 err = got_object_id_str(&id_str1, obj_id1);
3697 if (err)
3698 goto done;
3700 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null",
3701 id_str2);
3702 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3703 repo);
3705 done:
3706 free(id_str1);
3707 free(id_str2);
3708 if (pcommit)
3709 got_object_commit_close(pcommit);
3710 return err;
3713 static char *
3714 get_datestr(time_t *time, char *datebuf)
3716 struct tm mytm, *tm;
3717 char *p, *s;
3719 tm = gmtime_r(time, &mytm);
3720 if (tm == NULL)
3721 return NULL;
3722 s = asctime_r(tm, datebuf);
3723 if (s == NULL)
3724 return NULL;
3725 p = strchr(s, '\n');
3726 if (p)
3727 *p = '\0';
3728 return s;
3731 static const struct got_error *
3732 match_logmsg(int *have_match, struct got_object_id *id,
3733 struct got_commit_object *commit, regex_t *regex)
3735 const struct got_error *err = NULL;
3736 regmatch_t regmatch;
3737 char *id_str = NULL, *logmsg = NULL;
3739 *have_match = 0;
3741 err = got_object_id_str(&id_str, id);
3742 if (err)
3743 return err;
3745 err = got_object_commit_get_logmsg(&logmsg, commit);
3746 if (err)
3747 goto done;
3749 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3750 *have_match = 1;
3751 done:
3752 free(id_str);
3753 free(logmsg);
3754 return err;
3757 static void
3758 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3759 regex_t *regex)
3761 regmatch_t regmatch;
3762 struct got_pathlist_entry *pe;
3764 *have_match = 0;
3766 TAILQ_FOREACH(pe, changed_paths, entry) {
3767 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3768 *have_match = 1;
3769 break;
3774 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3776 static const struct got_error*
3777 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3778 struct got_object_id *id, struct got_repository *repo)
3780 static const struct got_error *err = NULL;
3781 struct got_reflist_entry *re;
3782 char *s;
3783 const char *name;
3785 *refs_str = NULL;
3787 TAILQ_FOREACH(re, refs, entry) {
3788 struct got_tag_object *tag = NULL;
3789 struct got_object_id *ref_id;
3790 int cmp;
3792 name = got_ref_get_name(re->ref);
3793 if (strcmp(name, GOT_REF_HEAD) == 0)
3794 continue;
3795 if (strncmp(name, "refs/", 5) == 0)
3796 name += 5;
3797 if (strncmp(name, "got/", 4) == 0)
3798 continue;
3799 if (strncmp(name, "heads/", 6) == 0)
3800 name += 6;
3801 if (strncmp(name, "remotes/", 8) == 0) {
3802 name += 8;
3803 s = strstr(name, "/" GOT_REF_HEAD);
3804 if (s != NULL && s[strlen(s)] == '\0')
3805 continue;
3807 err = got_ref_resolve(&ref_id, repo, re->ref);
3808 if (err)
3809 break;
3810 if (strncmp(name, "tags/", 5) == 0) {
3811 err = got_object_open_as_tag(&tag, repo, ref_id);
3812 if (err) {
3813 if (err->code != GOT_ERR_OBJ_TYPE) {
3814 free(ref_id);
3815 break;
3817 /* Ref points at something other than a tag. */
3818 err = NULL;
3819 tag = NULL;
3822 cmp = got_object_id_cmp(tag ?
3823 got_object_tag_get_object_id(tag) : ref_id, id);
3824 free(ref_id);
3825 if (tag)
3826 got_object_tag_close(tag);
3827 if (cmp != 0)
3828 continue;
3829 s = *refs_str;
3830 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3831 s ? ", " : "", name) == -1) {
3832 err = got_error_from_errno("asprintf");
3833 free(s);
3834 *refs_str = NULL;
3835 break;
3837 free(s);
3840 return err;
3843 static const struct got_error *
3844 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id)
3846 const struct got_error *err = NULL;
3847 char *id_str, *s, *nl, *logmsg0;
3849 err = got_object_id_str(&id_str, id);
3850 if (err)
3851 return err;
3853 err = got_object_commit_get_logmsg(&logmsg0, commit);
3854 if (err)
3855 goto done;
3857 s = logmsg0;
3858 while (isspace((unsigned char)s[0]))
3859 s++;
3861 nl = strchr(s, '\n');
3862 if (nl) {
3863 *nl = '\0';
3866 printf("%.7s %s\n", id_str, s);
3868 if (fflush(stdout) != 0 && err == NULL)
3869 err = got_error_from_errno("fflush");
3870 done:
3871 free(id_str);
3872 free(logmsg0);
3873 return err;
3876 static const struct got_error *
3877 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3878 struct got_repository *repo, const char *path,
3879 struct got_pathlist_head *changed_paths, int show_patch,
3880 int diff_context, struct got_reflist_object_id_map *refs_idmap,
3881 const char *custom_refs_str)
3883 const struct got_error *err = NULL;
3884 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3885 char datebuf[26];
3886 time_t committer_time;
3887 const char *author, *committer;
3888 char *refs_str = NULL;
3890 err = got_object_id_str(&id_str, id);
3891 if (err)
3892 return err;
3894 if (custom_refs_str == NULL) {
3895 struct got_reflist_head *refs;
3896 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3897 if (refs) {
3898 err = build_refs_str(&refs_str, refs, id, repo);
3899 if (err)
3900 goto done;
3904 printf(GOT_COMMIT_SEP_STR);
3905 if (custom_refs_str)
3906 printf("commit %s (%s)\n", id_str, custom_refs_str);
3907 else
3908 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3909 refs_str ? refs_str : "", refs_str ? ")" : "");
3910 free(id_str);
3911 id_str = NULL;
3912 free(refs_str);
3913 refs_str = NULL;
3914 printf("from: %s\n", got_object_commit_get_author(commit));
3915 committer_time = got_object_commit_get_committer_time(commit);
3916 datestr = get_datestr(&committer_time, datebuf);
3917 if (datestr)
3918 printf("date: %s UTC\n", datestr);
3919 author = got_object_commit_get_author(commit);
3920 committer = got_object_commit_get_committer(commit);
3921 if (strcmp(author, committer) != 0)
3922 printf("via: %s\n", committer);
3923 if (got_object_commit_get_nparents(commit) > 1) {
3924 const struct got_object_id_queue *parent_ids;
3925 struct got_object_qid *qid;
3926 int n = 1;
3927 parent_ids = got_object_commit_get_parent_ids(commit);
3928 STAILQ_FOREACH(qid, parent_ids, entry) {
3929 err = got_object_id_str(&id_str, &qid->id);
3930 if (err)
3931 goto done;
3932 printf("parent %d: %s\n", n++, id_str);
3933 free(id_str);
3934 id_str = NULL;
3938 err = got_object_commit_get_logmsg(&logmsg0, commit);
3939 if (err)
3940 goto done;
3942 logmsg = logmsg0;
3943 do {
3944 line = strsep(&logmsg, "\n");
3945 if (line)
3946 printf(" %s\n", line);
3947 } while (line);
3948 free(logmsg0);
3950 if (changed_paths) {
3951 struct got_pathlist_entry *pe;
3952 TAILQ_FOREACH(pe, changed_paths, entry) {
3953 struct got_diff_changed_path *cp = pe->data;
3954 printf(" %c %s\n", cp->status, pe->path);
3956 printf("\n");
3958 if (show_patch) {
3959 err = print_patch(commit, id, path, diff_context, repo);
3960 if (err == 0)
3961 printf("\n");
3964 if (fflush(stdout) != 0 && err == NULL)
3965 err = got_error_from_errno("fflush");
3966 done:
3967 free(id_str);
3968 free(refs_str);
3969 return err;
3972 static const struct got_error *
3973 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3974 struct got_repository *repo, const char *path, int show_changed_paths,
3975 int show_patch, const char *search_pattern, int diff_context, int limit,
3976 int log_branches, int reverse_display_order,
3977 struct got_reflist_object_id_map *refs_idmap, int one_line)
3979 const struct got_error *err;
3980 struct got_commit_graph *graph;
3981 regex_t regex;
3982 int have_match;
3983 struct got_object_id_queue reversed_commits;
3984 struct got_object_qid *qid;
3985 struct got_commit_object *commit;
3986 struct got_pathlist_head changed_paths;
3987 struct got_pathlist_entry *pe;
3989 STAILQ_INIT(&reversed_commits);
3990 TAILQ_INIT(&changed_paths);
3992 if (search_pattern && regcomp(&regex, search_pattern,
3993 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3994 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3996 err = got_commit_graph_open(&graph, path, !log_branches);
3997 if (err)
3998 return err;
3999 err = got_commit_graph_iter_start(graph, root_id, repo,
4000 check_cancelled, NULL);
4001 if (err)
4002 goto done;
4003 for (;;) {
4004 struct got_object_id *id;
4006 if (sigint_received || sigpipe_received)
4007 break;
4009 err = got_commit_graph_iter_next(&id, graph, repo,
4010 check_cancelled, NULL);
4011 if (err) {
4012 if (err->code == GOT_ERR_ITER_COMPLETED)
4013 err = NULL;
4014 break;
4016 if (id == NULL)
4017 break;
4019 err = got_object_open_as_commit(&commit, repo, id);
4020 if (err)
4021 break;
4023 if (show_changed_paths && !reverse_display_order) {
4024 err = get_changed_paths(&changed_paths, commit, repo);
4025 if (err)
4026 break;
4029 if (search_pattern) {
4030 err = match_logmsg(&have_match, id, commit, &regex);
4031 if (err) {
4032 got_object_commit_close(commit);
4033 break;
4035 if (have_match == 0 && show_changed_paths)
4036 match_changed_paths(&have_match,
4037 &changed_paths, &regex);
4038 if (have_match == 0) {
4039 got_object_commit_close(commit);
4040 TAILQ_FOREACH(pe, &changed_paths, entry) {
4041 free((char *)pe->path);
4042 free(pe->data);
4044 got_pathlist_free(&changed_paths);
4045 continue;
4049 if (reverse_display_order) {
4050 err = got_object_qid_alloc(&qid, id);
4051 if (err)
4052 break;
4053 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4054 got_object_commit_close(commit);
4055 } else {
4056 if (one_line)
4057 err = print_commit_oneline(commit, id);
4058 else
4059 err = print_commit(commit, id, repo, path,
4060 show_changed_paths ? &changed_paths : NULL,
4061 show_patch, diff_context, refs_idmap, NULL);
4062 got_object_commit_close(commit);
4063 if (err)
4064 break;
4066 if ((limit && --limit == 0) ||
4067 (end_id && got_object_id_cmp(id, end_id) == 0))
4068 break;
4070 TAILQ_FOREACH(pe, &changed_paths, entry) {
4071 free((char *)pe->path);
4072 free(pe->data);
4074 got_pathlist_free(&changed_paths);
4076 if (reverse_display_order) {
4077 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4078 err = got_object_open_as_commit(&commit, repo,
4079 &qid->id);
4080 if (err)
4081 break;
4082 if (show_changed_paths) {
4083 err = get_changed_paths(&changed_paths,
4084 commit, repo);
4085 if (err)
4086 break;
4088 if (one_line)
4089 err = print_commit_oneline(commit, &qid->id);
4090 else
4091 err = print_commit(commit, &qid->id, repo, path,
4092 show_changed_paths ? &changed_paths : NULL,
4093 show_patch, diff_context, refs_idmap, NULL);
4094 got_object_commit_close(commit);
4095 if (err)
4096 break;
4097 TAILQ_FOREACH(pe, &changed_paths, entry) {
4098 free((char *)pe->path);
4099 free(pe->data);
4101 got_pathlist_free(&changed_paths);
4104 done:
4105 while (!STAILQ_EMPTY(&reversed_commits)) {
4106 qid = STAILQ_FIRST(&reversed_commits);
4107 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4108 got_object_qid_free(qid);
4110 TAILQ_FOREACH(pe, &changed_paths, entry) {
4111 free((char *)pe->path);
4112 free(pe->data);
4114 got_pathlist_free(&changed_paths);
4115 if (search_pattern)
4116 regfree(&regex);
4117 got_commit_graph_close(graph);
4118 return err;
4121 __dead static void
4122 usage_log(void)
4124 fprintf(stderr, "usage: %s log [-b] [-p] [-P] [-s] [-c commit] "
4125 "[-C number] [ -l N ] [-x commit] [-S search-pattern] "
4126 "[-r repository-path] [-R] [path]\n", getprogname());
4127 exit(1);
4130 static int
4131 get_default_log_limit(void)
4133 const char *got_default_log_limit;
4134 long long n;
4135 const char *errstr;
4137 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4138 if (got_default_log_limit == NULL)
4139 return 0;
4140 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4141 if (errstr != NULL)
4142 return 0;
4143 return n;
4146 static const struct got_error *
4147 cmd_log(int argc, char *argv[])
4149 const struct got_error *error;
4150 struct got_repository *repo = NULL;
4151 struct got_worktree *worktree = NULL;
4152 struct got_object_id *start_id = NULL, *end_id = NULL;
4153 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4154 const char *start_commit = NULL, *end_commit = NULL;
4155 const char *search_pattern = NULL;
4156 int diff_context = -1, ch;
4157 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4158 int reverse_display_order = 0, one_line = 0;
4159 const char *errstr;
4160 struct got_reflist_head refs;
4161 struct got_reflist_object_id_map *refs_idmap = NULL;
4163 TAILQ_INIT(&refs);
4165 #ifndef PROFILE
4166 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4167 NULL)
4168 == -1)
4169 err(1, "pledge");
4170 #endif
4172 limit = get_default_log_limit();
4174 while ((ch = getopt(argc, argv, "bpPc:C:l:r:RsS:x:")) != -1) {
4175 switch (ch) {
4176 case 'p':
4177 show_patch = 1;
4178 break;
4179 case 'P':
4180 show_changed_paths = 1;
4181 break;
4182 case 'c':
4183 start_commit = optarg;
4184 break;
4185 case 'C':
4186 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4187 &errstr);
4188 if (errstr != NULL)
4189 errx(1, "number of context lines is %s: %s",
4190 errstr, optarg);
4191 break;
4192 case 'l':
4193 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4194 if (errstr != NULL)
4195 errx(1, "number of commits is %s: %s",
4196 errstr, optarg);
4197 break;
4198 case 'b':
4199 log_branches = 1;
4200 break;
4201 case 'r':
4202 repo_path = realpath(optarg, NULL);
4203 if (repo_path == NULL)
4204 return got_error_from_errno2("realpath",
4205 optarg);
4206 got_path_strip_trailing_slashes(repo_path);
4207 break;
4208 case 'R':
4209 reverse_display_order = 1;
4210 break;
4211 case 's':
4212 one_line = 1;
4213 break;
4214 case 'S':
4215 search_pattern = optarg;
4216 break;
4217 case 'x':
4218 end_commit = optarg;
4219 break;
4220 default:
4221 usage_log();
4222 /* NOTREACHED */
4226 argc -= optind;
4227 argv += optind;
4229 if (diff_context == -1)
4230 diff_context = 3;
4231 else if (!show_patch)
4232 errx(1, "-C requires -p");
4234 if (one_line && (show_patch || show_changed_paths))
4235 errx(1, "cannot use -s with -p or -P");
4237 cwd = getcwd(NULL, 0);
4238 if (cwd == NULL) {
4239 error = got_error_from_errno("getcwd");
4240 goto done;
4243 if (repo_path == NULL) {
4244 error = got_worktree_open(&worktree, cwd);
4245 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4246 goto done;
4247 error = NULL;
4250 if (argc == 1) {
4251 if (worktree) {
4252 error = got_worktree_resolve_path(&path, worktree,
4253 argv[0]);
4254 if (error)
4255 goto done;
4256 } else {
4257 path = strdup(argv[0]);
4258 if (path == NULL) {
4259 error = got_error_from_errno("strdup");
4260 goto done;
4263 } else if (argc != 0)
4264 usage_log();
4266 if (repo_path == NULL) {
4267 repo_path = worktree ?
4268 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4270 if (repo_path == NULL) {
4271 error = got_error_from_errno("strdup");
4272 goto done;
4275 error = got_repo_open(&repo, repo_path, NULL);
4276 if (error != NULL)
4277 goto done;
4279 error = apply_unveil(got_repo_get_path(repo), 1,
4280 worktree ? got_worktree_get_root_path(worktree) : NULL);
4281 if (error)
4282 goto done;
4284 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4285 if (error)
4286 goto done;
4288 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4289 if (error)
4290 goto done;
4292 if (start_commit == NULL) {
4293 struct got_reference *head_ref;
4294 struct got_commit_object *commit = NULL;
4295 error = got_ref_open(&head_ref, repo,
4296 worktree ? got_worktree_get_head_ref_name(worktree)
4297 : GOT_REF_HEAD, 0);
4298 if (error != NULL)
4299 goto done;
4300 error = got_ref_resolve(&start_id, repo, head_ref);
4301 got_ref_close(head_ref);
4302 if (error != NULL)
4303 goto done;
4304 error = got_object_open_as_commit(&commit, repo,
4305 start_id);
4306 if (error != NULL)
4307 goto done;
4308 got_object_commit_close(commit);
4309 } else {
4310 error = got_repo_match_object_id(&start_id, NULL,
4311 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4312 if (error != NULL)
4313 goto done;
4315 if (end_commit != NULL) {
4316 error = got_repo_match_object_id(&end_id, NULL,
4317 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4318 if (error != NULL)
4319 goto done;
4322 if (worktree) {
4324 * If a path was specified on the command line it was resolved
4325 * to a path in the work tree above. Prepend the work tree's
4326 * path prefix to obtain the corresponding in-repository path.
4328 if (path) {
4329 const char *prefix;
4330 prefix = got_worktree_get_path_prefix(worktree);
4331 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4332 (path[0] != '\0') ? "/" : "", path) == -1) {
4333 error = got_error_from_errno("asprintf");
4334 goto done;
4337 } else
4338 error = got_repo_map_path(&in_repo_path, repo,
4339 path ? path : "");
4340 if (error != NULL)
4341 goto done;
4342 if (in_repo_path) {
4343 free(path);
4344 path = in_repo_path;
4347 if (worktree) {
4348 /* Release work tree lock. */
4349 got_worktree_close(worktree);
4350 worktree = NULL;
4353 error = print_commits(start_id, end_id, repo, path ? path : "",
4354 show_changed_paths, show_patch, search_pattern, diff_context,
4355 limit, log_branches, reverse_display_order, refs_idmap, one_line);
4356 done:
4357 free(path);
4358 free(repo_path);
4359 free(cwd);
4360 if (worktree)
4361 got_worktree_close(worktree);
4362 if (repo) {
4363 const struct got_error *close_err = got_repo_close(repo);
4364 if (error == NULL)
4365 error = close_err;
4367 if (refs_idmap)
4368 got_reflist_object_id_map_free(refs_idmap);
4369 got_ref_list_free(&refs);
4370 return error;
4373 __dead static void
4374 usage_diff(void)
4376 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4377 "[-r repository-path] [-s] [-w] [-P] "
4378 "[object1 object2 | path ...]\n", getprogname());
4379 exit(1);
4382 struct print_diff_arg {
4383 struct got_repository *repo;
4384 struct got_worktree *worktree;
4385 int diff_context;
4386 const char *id_str;
4387 int header_shown;
4388 int diff_staged;
4389 int ignore_whitespace;
4390 int force_text_diff;
4394 * Create a file which contains the target path of a symlink so we can feed
4395 * it as content to the diff engine.
4397 static const struct got_error *
4398 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4399 const char *abspath)
4401 const struct got_error *err = NULL;
4402 char target_path[PATH_MAX];
4403 ssize_t target_len, outlen;
4405 *fd = -1;
4407 if (dirfd != -1) {
4408 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4409 if (target_len == -1)
4410 return got_error_from_errno2("readlinkat", abspath);
4411 } else {
4412 target_len = readlink(abspath, target_path, PATH_MAX);
4413 if (target_len == -1)
4414 return got_error_from_errno2("readlink", abspath);
4417 *fd = got_opentempfd();
4418 if (*fd == -1)
4419 return got_error_from_errno("got_opentempfd");
4421 outlen = write(*fd, target_path, target_len);
4422 if (outlen == -1) {
4423 err = got_error_from_errno("got_opentempfd");
4424 goto done;
4427 if (lseek(*fd, 0, SEEK_SET) == -1) {
4428 err = got_error_from_errno2("lseek", abspath);
4429 goto done;
4431 done:
4432 if (err) {
4433 close(*fd);
4434 *fd = -1;
4436 return err;
4439 static const struct got_error *
4440 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4441 const char *path, struct got_object_id *blob_id,
4442 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4443 int dirfd, const char *de_name)
4445 struct print_diff_arg *a = arg;
4446 const struct got_error *err = NULL;
4447 struct got_blob_object *blob1 = NULL;
4448 int fd = -1;
4449 FILE *f1 = NULL, *f2 = NULL;
4450 char *abspath = NULL, *label1 = NULL;
4451 struct stat sb;
4452 off_t size1 = 0;
4454 if (a->diff_staged) {
4455 if (staged_status != GOT_STATUS_MODIFY &&
4456 staged_status != GOT_STATUS_ADD &&
4457 staged_status != GOT_STATUS_DELETE)
4458 return NULL;
4459 } else {
4460 if (staged_status == GOT_STATUS_DELETE)
4461 return NULL;
4462 if (status == GOT_STATUS_NONEXISTENT)
4463 return got_error_set_errno(ENOENT, path);
4464 if (status != GOT_STATUS_MODIFY &&
4465 status != GOT_STATUS_ADD &&
4466 status != GOT_STATUS_DELETE &&
4467 status != GOT_STATUS_CONFLICT)
4468 return NULL;
4471 if (!a->header_shown) {
4472 printf("diff %s %s%s\n", a->id_str,
4473 got_worktree_get_root_path(a->worktree),
4474 a->diff_staged ? " (staged changes)" : "");
4475 a->header_shown = 1;
4478 if (a->diff_staged) {
4479 const char *label1 = NULL, *label2 = NULL;
4480 switch (staged_status) {
4481 case GOT_STATUS_MODIFY:
4482 label1 = path;
4483 label2 = path;
4484 break;
4485 case GOT_STATUS_ADD:
4486 label2 = path;
4487 break;
4488 case GOT_STATUS_DELETE:
4489 label1 = path;
4490 break;
4491 default:
4492 return got_error(GOT_ERR_FILE_STATUS);
4494 f1 = got_opentemp();
4495 if (f1 == NULL) {
4496 err = got_error_from_errno("got_opentemp");
4497 goto done;
4499 f2 = got_opentemp();
4500 if (f2 == NULL) {
4501 err = got_error_from_errno("got_opentemp");
4502 goto done;
4504 err = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
4505 blob_id, staged_blob_id, label1, label2, a->diff_context,
4506 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4507 goto done;
4510 if (staged_status == GOT_STATUS_ADD ||
4511 staged_status == GOT_STATUS_MODIFY) {
4512 char *id_str;
4513 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4514 8192);
4515 if (err)
4516 goto done;
4517 err = got_object_id_str(&id_str, staged_blob_id);
4518 if (err)
4519 goto done;
4520 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4521 err = got_error_from_errno("asprintf");
4522 free(id_str);
4523 goto done;
4525 free(id_str);
4526 } else if (status != GOT_STATUS_ADD) {
4527 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4528 if (err)
4529 goto done;
4532 if (status != GOT_STATUS_DELETE) {
4533 if (asprintf(&abspath, "%s/%s",
4534 got_worktree_get_root_path(a->worktree), path) == -1) {
4535 err = got_error_from_errno("asprintf");
4536 goto done;
4539 if (dirfd != -1) {
4540 fd = openat(dirfd, de_name,
4541 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4542 if (fd == -1) {
4543 if (!got_err_open_nofollow_on_symlink()) {
4544 err = got_error_from_errno2("openat",
4545 abspath);
4546 goto done;
4548 err = get_symlink_target_file(&fd, dirfd,
4549 de_name, abspath);
4550 if (err)
4551 goto done;
4553 } else {
4554 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4555 if (fd == -1) {
4556 if (!got_err_open_nofollow_on_symlink()) {
4557 err = got_error_from_errno2("open",
4558 abspath);
4559 goto done;
4561 err = get_symlink_target_file(&fd, dirfd,
4562 de_name, abspath);
4563 if (err)
4564 goto done;
4567 if (fstat(fd, &sb) == -1) {
4568 err = got_error_from_errno2("fstat", abspath);
4569 goto done;
4571 f2 = fdopen(fd, "r");
4572 if (f2 == NULL) {
4573 err = got_error_from_errno2("fdopen", abspath);
4574 goto done;
4576 fd = -1;
4577 } else
4578 sb.st_size = 0;
4580 if (blob1) {
4581 f1 = got_opentemp();
4582 if (f1 == NULL) {
4583 err = got_error_from_errno("got_opentemp");
4584 goto done;
4586 err = got_object_blob_dump_to_file(&size1, NULL, NULL, f1,
4587 blob1);
4588 if (err)
4589 goto done;
4592 err = got_diff_blob_file(blob1, f1, size1, label1, f2, sb.st_size,
4593 path, a->diff_context, a->ignore_whitespace, a->force_text_diff,
4594 stdout);
4595 done:
4596 if (blob1)
4597 got_object_blob_close(blob1);
4598 if (f1 && fclose(f1) == EOF && err == NULL)
4599 err = got_error_from_errno("fclose");
4600 if (f2 && fclose(f2) == EOF && err == NULL)
4601 err = got_error_from_errno("fclose");
4602 if (fd != -1 && close(fd) == -1 && err == NULL)
4603 err = got_error_from_errno("close");
4604 free(abspath);
4605 return err;
4608 static const struct got_error *
4609 cmd_diff(int argc, char *argv[])
4611 const struct got_error *error;
4612 struct got_repository *repo = NULL;
4613 struct got_worktree *worktree = NULL;
4614 char *cwd = NULL, *repo_path = NULL;
4615 const char *commit_args[2] = { NULL, NULL };
4616 int ncommit_args = 0;
4617 struct got_object_id *ids[2] = { NULL, NULL };
4618 char *labels[2] = { NULL, NULL };
4619 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4620 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4621 int force_text_diff = 0, force_path = 0, rflag = 0;
4622 const char *errstr;
4623 struct got_reflist_head refs;
4624 struct got_pathlist_head paths;
4625 struct got_pathlist_entry *pe;
4626 FILE *f1 = NULL, *f2 = NULL;
4628 TAILQ_INIT(&refs);
4629 TAILQ_INIT(&paths);
4631 #ifndef PROFILE
4632 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4633 NULL) == -1)
4634 err(1, "pledge");
4635 #endif
4637 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4638 switch (ch) {
4639 case 'a':
4640 force_text_diff = 1;
4641 break;
4642 case 'c':
4643 if (ncommit_args >= 2)
4644 errx(1, "too many -c options used");
4645 commit_args[ncommit_args++] = optarg;
4646 break;
4647 case 'C':
4648 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4649 &errstr);
4650 if (errstr != NULL)
4651 errx(1, "number of context lines is %s: %s",
4652 errstr, optarg);
4653 break;
4654 case 'r':
4655 repo_path = realpath(optarg, NULL);
4656 if (repo_path == NULL)
4657 return got_error_from_errno2("realpath",
4658 optarg);
4659 got_path_strip_trailing_slashes(repo_path);
4660 rflag = 1;
4661 break;
4662 case 's':
4663 diff_staged = 1;
4664 break;
4665 case 'w':
4666 ignore_whitespace = 1;
4667 break;
4668 case 'P':
4669 force_path = 1;
4670 break;
4671 default:
4672 usage_diff();
4673 /* NOTREACHED */
4677 argc -= optind;
4678 argv += optind;
4680 cwd = getcwd(NULL, 0);
4681 if (cwd == NULL) {
4682 error = got_error_from_errno("getcwd");
4683 goto done;
4686 if (repo_path == NULL) {
4687 error = got_worktree_open(&worktree, cwd);
4688 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4689 goto done;
4690 else
4691 error = NULL;
4692 if (worktree) {
4693 repo_path =
4694 strdup(got_worktree_get_repo_path(worktree));
4695 if (repo_path == NULL) {
4696 error = got_error_from_errno("strdup");
4697 goto done;
4699 } else {
4700 repo_path = strdup(cwd);
4701 if (repo_path == NULL) {
4702 error = got_error_from_errno("strdup");
4703 goto done;
4708 error = got_repo_open(&repo, repo_path, NULL);
4709 free(repo_path);
4710 if (error != NULL)
4711 goto done;
4713 if (rflag || worktree == NULL || ncommit_args > 0) {
4714 if (force_path) {
4715 error = got_error_msg(GOT_ERR_NOT_IMPL,
4716 "-P option can only be used when diffing "
4717 "a work tree");
4718 goto done;
4720 if (diff_staged) {
4721 error = got_error_msg(GOT_ERR_NOT_IMPL,
4722 "-s option can only be used when diffing "
4723 "a work tree");
4724 goto done;
4728 error = apply_unveil(got_repo_get_path(repo), 1,
4729 worktree ? got_worktree_get_root_path(worktree) : NULL);
4730 if (error)
4731 goto done;
4733 if ((!force_path && argc == 2) || ncommit_args > 0) {
4734 int obj_type = (ncommit_args > 0 ?
4735 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4736 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4737 NULL);
4738 if (error)
4739 goto done;
4740 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4741 const char *arg;
4742 if (ncommit_args > 0)
4743 arg = commit_args[i];
4744 else
4745 arg = argv[i];
4746 error = got_repo_match_object_id(&ids[i], &labels[i],
4747 arg, obj_type, &refs, repo);
4748 if (error) {
4749 if (error->code != GOT_ERR_NOT_REF &&
4750 error->code != GOT_ERR_NO_OBJ)
4751 goto done;
4752 if (ncommit_args > 0)
4753 goto done;
4754 error = NULL;
4755 break;
4760 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4761 struct print_diff_arg arg;
4762 char *id_str;
4764 if (worktree == NULL) {
4765 if (argc == 2 && ids[0] == NULL) {
4766 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
4767 goto done;
4768 } else if (argc == 2 && ids[1] == NULL) {
4769 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
4770 goto done;
4771 } else if (argc > 0) {
4772 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
4773 "%s", "specified paths cannot be resolved");
4774 goto done;
4775 } else {
4776 error = got_error(GOT_ERR_NOT_WORKTREE);
4777 goto done;
4781 error = get_worktree_paths_from_argv(&paths, argc, argv,
4782 worktree);
4783 if (error)
4784 goto done;
4786 error = got_object_id_str(&id_str,
4787 got_worktree_get_base_commit_id(worktree));
4788 if (error)
4789 goto done;
4790 arg.repo = repo;
4791 arg.worktree = worktree;
4792 arg.diff_context = diff_context;
4793 arg.id_str = id_str;
4794 arg.header_shown = 0;
4795 arg.diff_staged = diff_staged;
4796 arg.ignore_whitespace = ignore_whitespace;
4797 arg.force_text_diff = force_text_diff;
4799 error = got_worktree_status(worktree, &paths, repo, 0,
4800 print_diff, &arg, check_cancelled, NULL);
4801 free(id_str);
4802 goto done;
4805 if (ncommit_args == 1) {
4806 struct got_commit_object *commit;
4807 error = got_object_open_as_commit(&commit, repo, ids[0]);
4808 if (error)
4809 goto done;
4811 labels[1] = labels[0];
4812 ids[1] = ids[0];
4813 if (got_object_commit_get_nparents(commit) > 0) {
4814 const struct got_object_id_queue *pids;
4815 struct got_object_qid *pid;
4816 pids = got_object_commit_get_parent_ids(commit);
4817 pid = STAILQ_FIRST(pids);
4818 ids[0] = got_object_id_dup(&pid->id);
4819 if (ids[0] == NULL) {
4820 error = got_error_from_errno(
4821 "got_object_id_dup");
4822 got_object_commit_close(commit);
4823 goto done;
4825 error = got_object_id_str(&labels[0], ids[0]);
4826 if (error) {
4827 got_object_commit_close(commit);
4828 goto done;
4830 } else {
4831 ids[0] = NULL;
4832 labels[0] = strdup("/dev/null");
4833 if (labels[0] == NULL) {
4834 error = got_error_from_errno("strdup");
4835 got_object_commit_close(commit);
4836 goto done;
4840 got_object_commit_close(commit);
4843 if (ncommit_args == 0 && argc > 2) {
4844 error = got_error_msg(GOT_ERR_BAD_PATH,
4845 "path arguments cannot be used when diffing two objects");
4846 goto done;
4849 if (ids[0]) {
4850 error = got_object_get_type(&type1, repo, ids[0]);
4851 if (error)
4852 goto done;
4855 error = got_object_get_type(&type2, repo, ids[1]);
4856 if (error)
4857 goto done;
4858 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
4859 error = got_error(GOT_ERR_OBJ_TYPE);
4860 goto done;
4862 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
4863 error = got_error_msg(GOT_ERR_OBJ_TYPE,
4864 "path arguments cannot be used when diffing blobs");
4865 goto done;
4868 for (i = 0; ncommit_args > 0 && i < argc; i++) {
4869 char *in_repo_path;
4870 struct got_pathlist_entry *new;
4871 if (worktree) {
4872 const char *prefix;
4873 char *p;
4874 error = got_worktree_resolve_path(&p, worktree,
4875 argv[i]);
4876 if (error)
4877 goto done;
4878 prefix = got_worktree_get_path_prefix(worktree);
4879 while (prefix[0] == '/')
4880 prefix++;
4881 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4882 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
4883 p) == -1) {
4884 error = got_error_from_errno("asprintf");
4885 free(p);
4886 goto done;
4888 free(p);
4889 } else {
4890 char *mapped_path, *s;
4891 error = got_repo_map_path(&mapped_path, repo, argv[i]);
4892 if (error)
4893 goto done;
4894 s = mapped_path;
4895 while (s[0] == '/')
4896 s++;
4897 in_repo_path = strdup(s);
4898 if (in_repo_path == NULL) {
4899 error = got_error_from_errno("asprintf");
4900 free(mapped_path);
4901 goto done;
4903 free(mapped_path);
4906 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
4907 if (error || new == NULL /* duplicate */)
4908 free(in_repo_path);
4909 if (error)
4910 goto done;
4913 if (worktree) {
4914 /* Release work tree lock. */
4915 got_worktree_close(worktree);
4916 worktree = NULL;
4919 f1 = got_opentemp();
4920 if (f1 == NULL) {
4921 error = got_error_from_errno("got_opentemp");
4922 goto done;
4925 f2 = got_opentemp();
4926 if (f2 == NULL) {
4927 error = got_error_from_errno("got_opentemp");
4928 goto done;
4931 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
4932 case GOT_OBJ_TYPE_BLOB:
4933 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
4934 ids[0], ids[1], NULL, NULL, diff_context,
4935 ignore_whitespace, force_text_diff, repo, stdout);
4936 break;
4937 case GOT_OBJ_TYPE_TREE:
4938 error = got_diff_objects_as_trees(NULL, NULL, f1, f2,
4939 ids[0], ids[1], &paths, "", "", diff_context,
4940 ignore_whitespace, force_text_diff, repo, stdout);
4941 break;
4942 case GOT_OBJ_TYPE_COMMIT:
4943 printf("diff %s %s\n", labels[0], labels[1]);
4944 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
4945 ids[0], ids[1], &paths, diff_context, ignore_whitespace,
4946 force_text_diff, repo, stdout);
4947 break;
4948 default:
4949 error = got_error(GOT_ERR_OBJ_TYPE);
4951 done:
4952 free(labels[0]);
4953 free(labels[1]);
4954 free(ids[0]);
4955 free(ids[1]);
4956 if (worktree)
4957 got_worktree_close(worktree);
4958 if (repo) {
4959 const struct got_error *close_err = got_repo_close(repo);
4960 if (error == NULL)
4961 error = close_err;
4963 TAILQ_FOREACH(pe, &paths, entry)
4964 free((char *)pe->path);
4965 got_pathlist_free(&paths);
4966 got_ref_list_free(&refs);
4967 if (f1 && fclose(f1) == EOF && error == NULL)
4968 error = got_error_from_errno("fclose");
4969 if (f2 && fclose(f2) == EOF && error == NULL)
4970 error = got_error_from_errno("fclose");
4971 return error;
4974 __dead static void
4975 usage_blame(void)
4977 fprintf(stderr,
4978 "usage: %s blame [-c commit] [-r repository-path] path\n",
4979 getprogname());
4980 exit(1);
4983 struct blame_line {
4984 int annotated;
4985 char *id_str;
4986 char *committer;
4987 char datebuf[11]; /* YYYY-MM-DD + NUL */
4990 struct blame_cb_args {
4991 struct blame_line *lines;
4992 int nlines;
4993 int nlines_prec;
4994 int lineno_cur;
4995 off_t *line_offsets;
4996 FILE *f;
4997 struct got_repository *repo;
5000 static const struct got_error *
5001 blame_cb(void *arg, int nlines, int lineno,
5002 struct got_commit_object *commit, struct got_object_id *id)
5004 const struct got_error *err = NULL;
5005 struct blame_cb_args *a = arg;
5006 struct blame_line *bline;
5007 char *line = NULL;
5008 size_t linesize = 0;
5009 off_t offset;
5010 struct tm tm;
5011 time_t committer_time;
5013 if (nlines != a->nlines ||
5014 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5015 return got_error(GOT_ERR_RANGE);
5017 if (sigint_received)
5018 return got_error(GOT_ERR_ITER_COMPLETED);
5020 if (lineno == -1)
5021 return NULL; /* no change in this commit */
5023 /* Annotate this line. */
5024 bline = &a->lines[lineno - 1];
5025 if (bline->annotated)
5026 return NULL;
5027 err = got_object_id_str(&bline->id_str, id);
5028 if (err)
5029 return err;
5031 bline->committer = strdup(got_object_commit_get_committer(commit));
5032 if (bline->committer == NULL) {
5033 err = got_error_from_errno("strdup");
5034 goto done;
5037 committer_time = got_object_commit_get_committer_time(commit);
5038 if (gmtime_r(&committer_time, &tm) == NULL)
5039 return got_error_from_errno("gmtime_r");
5040 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5041 &tm) == 0) {
5042 err = got_error(GOT_ERR_NO_SPACE);
5043 goto done;
5045 bline->annotated = 1;
5047 /* Print lines annotated so far. */
5048 bline = &a->lines[a->lineno_cur - 1];
5049 if (!bline->annotated)
5050 goto done;
5052 offset = a->line_offsets[a->lineno_cur - 1];
5053 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5054 err = got_error_from_errno("fseeko");
5055 goto done;
5058 while (bline->annotated) {
5059 char *smallerthan, *at, *nl, *committer;
5060 size_t len;
5062 if (getline(&line, &linesize, a->f) == -1) {
5063 if (ferror(a->f))
5064 err = got_error_from_errno("getline");
5065 break;
5068 committer = bline->committer;
5069 smallerthan = strchr(committer, '<');
5070 if (smallerthan && smallerthan[1] != '\0')
5071 committer = smallerthan + 1;
5072 at = strchr(committer, '@');
5073 if (at)
5074 *at = '\0';
5075 len = strlen(committer);
5076 if (len >= 9)
5077 committer[8] = '\0';
5079 nl = strchr(line, '\n');
5080 if (nl)
5081 *nl = '\0';
5082 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5083 bline->id_str, bline->datebuf, committer, line);
5085 a->lineno_cur++;
5086 bline = &a->lines[a->lineno_cur - 1];
5088 done:
5089 free(line);
5090 return err;
5093 static const struct got_error *
5094 cmd_blame(int argc, char *argv[])
5096 const struct got_error *error;
5097 struct got_repository *repo = NULL;
5098 struct got_worktree *worktree = NULL;
5099 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5100 char *link_target = NULL;
5101 struct got_object_id *obj_id = NULL;
5102 struct got_object_id *commit_id = NULL;
5103 struct got_commit_object *commit = NULL;
5104 struct got_blob_object *blob = NULL;
5105 char *commit_id_str = NULL;
5106 struct blame_cb_args bca;
5107 int ch, obj_type, i;
5108 off_t filesize;
5110 memset(&bca, 0, sizeof(bca));
5112 #ifndef PROFILE
5113 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5114 NULL) == -1)
5115 err(1, "pledge");
5116 #endif
5118 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5119 switch (ch) {
5120 case 'c':
5121 commit_id_str = optarg;
5122 break;
5123 case 'r':
5124 repo_path = realpath(optarg, NULL);
5125 if (repo_path == NULL)
5126 return got_error_from_errno2("realpath",
5127 optarg);
5128 got_path_strip_trailing_slashes(repo_path);
5129 break;
5130 default:
5131 usage_blame();
5132 /* NOTREACHED */
5136 argc -= optind;
5137 argv += optind;
5139 if (argc == 1)
5140 path = argv[0];
5141 else
5142 usage_blame();
5144 cwd = getcwd(NULL, 0);
5145 if (cwd == NULL) {
5146 error = got_error_from_errno("getcwd");
5147 goto done;
5149 if (repo_path == NULL) {
5150 error = got_worktree_open(&worktree, cwd);
5151 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5152 goto done;
5153 else
5154 error = NULL;
5155 if (worktree) {
5156 repo_path =
5157 strdup(got_worktree_get_repo_path(worktree));
5158 if (repo_path == NULL) {
5159 error = got_error_from_errno("strdup");
5160 if (error)
5161 goto done;
5163 } else {
5164 repo_path = strdup(cwd);
5165 if (repo_path == NULL) {
5166 error = got_error_from_errno("strdup");
5167 goto done;
5172 error = got_repo_open(&repo, repo_path, NULL);
5173 if (error != NULL)
5174 goto done;
5176 if (worktree) {
5177 const char *prefix = got_worktree_get_path_prefix(worktree);
5178 char *p;
5180 error = got_worktree_resolve_path(&p, worktree, path);
5181 if (error)
5182 goto done;
5183 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5184 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5185 p) == -1) {
5186 error = got_error_from_errno("asprintf");
5187 free(p);
5188 goto done;
5190 free(p);
5191 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5192 } else {
5193 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5194 if (error)
5195 goto done;
5196 error = got_repo_map_path(&in_repo_path, repo, path);
5198 if (error)
5199 goto done;
5201 if (commit_id_str == NULL) {
5202 struct got_reference *head_ref;
5203 error = got_ref_open(&head_ref, repo, worktree ?
5204 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5205 if (error != NULL)
5206 goto done;
5207 error = got_ref_resolve(&commit_id, repo, head_ref);
5208 got_ref_close(head_ref);
5209 if (error != NULL)
5210 goto done;
5211 } else {
5212 struct got_reflist_head refs;
5213 TAILQ_INIT(&refs);
5214 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5215 NULL);
5216 if (error)
5217 goto done;
5218 error = got_repo_match_object_id(&commit_id, NULL,
5219 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5220 got_ref_list_free(&refs);
5221 if (error)
5222 goto done;
5225 if (worktree) {
5226 /* Release work tree lock. */
5227 got_worktree_close(worktree);
5228 worktree = NULL;
5231 error = got_object_open_as_commit(&commit, repo, commit_id);
5232 if (error)
5233 goto done;
5235 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5236 commit, repo);
5237 if (error)
5238 goto done;
5240 error = got_object_id_by_path(&obj_id, repo, commit,
5241 link_target ? link_target : in_repo_path);
5242 if (error)
5243 goto done;
5245 error = got_object_get_type(&obj_type, repo, obj_id);
5246 if (error)
5247 goto done;
5249 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5250 error = got_error_path(link_target ? link_target : in_repo_path,
5251 GOT_ERR_OBJ_TYPE);
5252 goto done;
5255 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
5256 if (error)
5257 goto done;
5258 bca.f = got_opentemp();
5259 if (bca.f == NULL) {
5260 error = got_error_from_errno("got_opentemp");
5261 goto done;
5263 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5264 &bca.line_offsets, bca.f, blob);
5265 if (error || bca.nlines == 0)
5266 goto done;
5268 /* Don't include \n at EOF in the blame line count. */
5269 if (bca.line_offsets[bca.nlines - 1] == filesize)
5270 bca.nlines--;
5272 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5273 if (bca.lines == NULL) {
5274 error = got_error_from_errno("calloc");
5275 goto done;
5277 bca.lineno_cur = 1;
5278 bca.nlines_prec = 0;
5279 i = bca.nlines;
5280 while (i > 0) {
5281 i /= 10;
5282 bca.nlines_prec++;
5284 bca.repo = repo;
5286 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5287 repo, blame_cb, &bca, check_cancelled, NULL);
5288 done:
5289 free(in_repo_path);
5290 free(link_target);
5291 free(repo_path);
5292 free(cwd);
5293 free(commit_id);
5294 free(obj_id);
5295 if (commit)
5296 got_object_commit_close(commit);
5297 if (blob)
5298 got_object_blob_close(blob);
5299 if (worktree)
5300 got_worktree_close(worktree);
5301 if (repo) {
5302 const struct got_error *close_err = got_repo_close(repo);
5303 if (error == NULL)
5304 error = close_err;
5306 if (bca.lines) {
5307 for (i = 0; i < bca.nlines; i++) {
5308 struct blame_line *bline = &bca.lines[i];
5309 free(bline->id_str);
5310 free(bline->committer);
5312 free(bca.lines);
5314 free(bca.line_offsets);
5315 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5316 error = got_error_from_errno("fclose");
5317 return error;
5320 __dead static void
5321 usage_tree(void)
5323 fprintf(stderr,
5324 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5325 getprogname());
5326 exit(1);
5329 static const struct got_error *
5330 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5331 const char *root_path, struct got_repository *repo)
5333 const struct got_error *err = NULL;
5334 int is_root_path = (strcmp(path, root_path) == 0);
5335 const char *modestr = "";
5336 mode_t mode = got_tree_entry_get_mode(te);
5337 char *link_target = NULL;
5339 path += strlen(root_path);
5340 while (path[0] == '/')
5341 path++;
5343 if (got_object_tree_entry_is_submodule(te))
5344 modestr = "$";
5345 else if (S_ISLNK(mode)) {
5346 int i;
5348 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5349 if (err)
5350 return err;
5351 for (i = 0; i < strlen(link_target); i++) {
5352 if (!isprint((unsigned char)link_target[i]))
5353 link_target[i] = '?';
5356 modestr = "@";
5358 else if (S_ISDIR(mode))
5359 modestr = "/";
5360 else if (mode & S_IXUSR)
5361 modestr = "*";
5363 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5364 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5365 link_target ? " -> ": "", link_target ? link_target : "");
5367 free(link_target);
5368 return NULL;
5371 static const struct got_error *
5372 print_tree(const char *path, struct got_commit_object *commit,
5373 int show_ids, int recurse, const char *root_path,
5374 struct got_repository *repo)
5376 const struct got_error *err = NULL;
5377 struct got_object_id *tree_id = NULL;
5378 struct got_tree_object *tree = NULL;
5379 int nentries, i;
5381 err = got_object_id_by_path(&tree_id, repo, commit, path);
5382 if (err)
5383 goto done;
5385 err = got_object_open_as_tree(&tree, repo, tree_id);
5386 if (err)
5387 goto done;
5388 nentries = got_object_tree_get_nentries(tree);
5389 for (i = 0; i < nentries; i++) {
5390 struct got_tree_entry *te;
5391 char *id = NULL;
5393 if (sigint_received || sigpipe_received)
5394 break;
5396 te = got_object_tree_get_entry(tree, i);
5397 if (show_ids) {
5398 char *id_str;
5399 err = got_object_id_str(&id_str,
5400 got_tree_entry_get_id(te));
5401 if (err)
5402 goto done;
5403 if (asprintf(&id, "%s ", id_str) == -1) {
5404 err = got_error_from_errno("asprintf");
5405 free(id_str);
5406 goto done;
5408 free(id_str);
5410 err = print_entry(te, id, path, root_path, repo);
5411 free(id);
5412 if (err)
5413 goto done;
5415 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5416 char *child_path;
5417 if (asprintf(&child_path, "%s%s%s", path,
5418 path[0] == '/' && path[1] == '\0' ? "" : "/",
5419 got_tree_entry_get_name(te)) == -1) {
5420 err = got_error_from_errno("asprintf");
5421 goto done;
5423 err = print_tree(child_path, commit, show_ids, 1,
5424 root_path, repo);
5425 free(child_path);
5426 if (err)
5427 goto done;
5430 done:
5431 if (tree)
5432 got_object_tree_close(tree);
5433 free(tree_id);
5434 return err;
5437 static const struct got_error *
5438 cmd_tree(int argc, char *argv[])
5440 const struct got_error *error;
5441 struct got_repository *repo = NULL;
5442 struct got_worktree *worktree = NULL;
5443 const char *path, *refname = NULL;
5444 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5445 struct got_object_id *commit_id = NULL;
5446 struct got_commit_object *commit = NULL;
5447 char *commit_id_str = NULL;
5448 int show_ids = 0, recurse = 0;
5449 int ch;
5451 #ifndef PROFILE
5452 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5453 NULL) == -1)
5454 err(1, "pledge");
5455 #endif
5457 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5458 switch (ch) {
5459 case 'c':
5460 commit_id_str = optarg;
5461 break;
5462 case 'r':
5463 repo_path = realpath(optarg, NULL);
5464 if (repo_path == NULL)
5465 return got_error_from_errno2("realpath",
5466 optarg);
5467 got_path_strip_trailing_slashes(repo_path);
5468 break;
5469 case 'i':
5470 show_ids = 1;
5471 break;
5472 case 'R':
5473 recurse = 1;
5474 break;
5475 default:
5476 usage_tree();
5477 /* NOTREACHED */
5481 argc -= optind;
5482 argv += optind;
5484 if (argc == 1)
5485 path = argv[0];
5486 else if (argc > 1)
5487 usage_tree();
5488 else
5489 path = NULL;
5491 cwd = getcwd(NULL, 0);
5492 if (cwd == NULL) {
5493 error = got_error_from_errno("getcwd");
5494 goto done;
5496 if (repo_path == NULL) {
5497 error = got_worktree_open(&worktree, cwd);
5498 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5499 goto done;
5500 else
5501 error = NULL;
5502 if (worktree) {
5503 repo_path =
5504 strdup(got_worktree_get_repo_path(worktree));
5505 if (repo_path == NULL)
5506 error = got_error_from_errno("strdup");
5507 if (error)
5508 goto done;
5509 } else {
5510 repo_path = strdup(cwd);
5511 if (repo_path == NULL) {
5512 error = got_error_from_errno("strdup");
5513 goto done;
5518 error = got_repo_open(&repo, repo_path, NULL);
5519 if (error != NULL)
5520 goto done;
5522 if (worktree) {
5523 const char *prefix = got_worktree_get_path_prefix(worktree);
5524 char *p;
5526 if (path == NULL)
5527 path = "";
5528 error = got_worktree_resolve_path(&p, worktree, path);
5529 if (error)
5530 goto done;
5531 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5532 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5533 p) == -1) {
5534 error = got_error_from_errno("asprintf");
5535 free(p);
5536 goto done;
5538 free(p);
5539 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5540 if (error)
5541 goto done;
5542 } else {
5543 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5544 if (error)
5545 goto done;
5546 if (path == NULL)
5547 path = "/";
5548 error = got_repo_map_path(&in_repo_path, repo, path);
5549 if (error != NULL)
5550 goto done;
5553 if (commit_id_str == NULL) {
5554 struct got_reference *head_ref;
5555 if (worktree)
5556 refname = got_worktree_get_head_ref_name(worktree);
5557 else
5558 refname = GOT_REF_HEAD;
5559 error = got_ref_open(&head_ref, repo, refname, 0);
5560 if (error != NULL)
5561 goto done;
5562 error = got_ref_resolve(&commit_id, repo, head_ref);
5563 got_ref_close(head_ref);
5564 if (error != NULL)
5565 goto done;
5566 } else {
5567 struct got_reflist_head refs;
5568 TAILQ_INIT(&refs);
5569 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5570 NULL);
5571 if (error)
5572 goto done;
5573 error = got_repo_match_object_id(&commit_id, NULL,
5574 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5575 got_ref_list_free(&refs);
5576 if (error)
5577 goto done;
5580 if (worktree) {
5581 /* Release work tree lock. */
5582 got_worktree_close(worktree);
5583 worktree = NULL;
5586 error = got_object_open_as_commit(&commit, repo, commit_id);
5587 if (error)
5588 goto done;
5590 error = print_tree(in_repo_path, commit, show_ids, recurse,
5591 in_repo_path, repo);
5592 done:
5593 free(in_repo_path);
5594 free(repo_path);
5595 free(cwd);
5596 free(commit_id);
5597 if (commit)
5598 got_object_commit_close(commit);
5599 if (worktree)
5600 got_worktree_close(worktree);
5601 if (repo) {
5602 const struct got_error *close_err = got_repo_close(repo);
5603 if (error == NULL)
5604 error = close_err;
5606 return error;
5609 __dead static void
5610 usage_status(void)
5612 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5613 "[-S status-codes] [path ...]\n", getprogname());
5614 exit(1);
5617 struct got_status_arg {
5618 char *status_codes;
5619 int suppress;
5622 static const struct got_error *
5623 print_status(void *arg, unsigned char status, unsigned char staged_status,
5624 const char *path, struct got_object_id *blob_id,
5625 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5626 int dirfd, const char *de_name)
5628 struct got_status_arg *st = arg;
5630 if (status == staged_status && (status == GOT_STATUS_DELETE))
5631 status = GOT_STATUS_NO_CHANGE;
5632 if (st != NULL && st->status_codes) {
5633 size_t ncodes = strlen(st->status_codes);
5634 int i, j = 0;
5636 for (i = 0; i < ncodes ; i++) {
5637 if (st->suppress) {
5638 if (status == st->status_codes[i] ||
5639 staged_status == st->status_codes[i]) {
5640 j++;
5641 continue;
5643 } else {
5644 if (status == st->status_codes[i] ||
5645 staged_status == st->status_codes[i])
5646 break;
5650 if (st->suppress && j == 0)
5651 goto print;
5653 if (i == ncodes)
5654 return NULL;
5656 print:
5657 printf("%c%c %s\n", status, staged_status, path);
5658 return NULL;
5661 static const struct got_error *
5662 cmd_status(int argc, char *argv[])
5664 const struct got_error *error = NULL;
5665 struct got_repository *repo = NULL;
5666 struct got_worktree *worktree = NULL;
5667 struct got_status_arg st;
5668 char *cwd = NULL;
5669 struct got_pathlist_head paths;
5670 struct got_pathlist_entry *pe;
5671 int ch, i, no_ignores = 0;
5673 TAILQ_INIT(&paths);
5675 memset(&st, 0, sizeof(st));
5676 st.status_codes = NULL;
5677 st.suppress = 0;
5679 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
5680 switch (ch) {
5681 case 'I':
5682 no_ignores = 1;
5683 break;
5684 case 'S':
5685 if (st.status_codes != NULL && st.suppress == 0)
5686 option_conflict('S', 's');
5687 st.suppress = 1;
5688 /* fallthrough */
5689 case 's':
5690 for (i = 0; i < strlen(optarg); i++) {
5691 switch (optarg[i]) {
5692 case GOT_STATUS_MODIFY:
5693 case GOT_STATUS_ADD:
5694 case GOT_STATUS_DELETE:
5695 case GOT_STATUS_CONFLICT:
5696 case GOT_STATUS_MISSING:
5697 case GOT_STATUS_OBSTRUCTED:
5698 case GOT_STATUS_UNVERSIONED:
5699 case GOT_STATUS_MODE_CHANGE:
5700 case GOT_STATUS_NONEXISTENT:
5701 break;
5702 default:
5703 errx(1, "invalid status code '%c'",
5704 optarg[i]);
5707 if (ch == 's' && st.suppress)
5708 option_conflict('s', 'S');
5709 st.status_codes = optarg;
5710 break;
5711 default:
5712 usage_status();
5713 /* NOTREACHED */
5717 argc -= optind;
5718 argv += optind;
5720 #ifndef PROFILE
5721 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5722 NULL) == -1)
5723 err(1, "pledge");
5724 #endif
5725 cwd = getcwd(NULL, 0);
5726 if (cwd == NULL) {
5727 error = got_error_from_errno("getcwd");
5728 goto done;
5731 error = got_worktree_open(&worktree, cwd);
5732 if (error) {
5733 if (error->code == GOT_ERR_NOT_WORKTREE)
5734 error = wrap_not_worktree_error(error, "status", cwd);
5735 goto done;
5738 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5739 NULL);
5740 if (error != NULL)
5741 goto done;
5743 error = apply_unveil(got_repo_get_path(repo), 1,
5744 got_worktree_get_root_path(worktree));
5745 if (error)
5746 goto done;
5748 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5749 if (error)
5750 goto done;
5752 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5753 print_status, &st, check_cancelled, NULL);
5754 done:
5755 TAILQ_FOREACH(pe, &paths, entry)
5756 free((char *)pe->path);
5757 got_pathlist_free(&paths);
5758 free(cwd);
5759 return error;
5762 __dead static void
5763 usage_ref(void)
5765 fprintf(stderr,
5766 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
5767 "[-s reference] [-d] [name]\n",
5768 getprogname());
5769 exit(1);
5772 static const struct got_error *
5773 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
5775 static const struct got_error *err = NULL;
5776 struct got_reflist_head refs;
5777 struct got_reflist_entry *re;
5779 TAILQ_INIT(&refs);
5780 err = got_ref_list(&refs, repo, refname, sort_by_time ?
5781 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
5782 repo);
5783 if (err)
5784 return err;
5786 TAILQ_FOREACH(re, &refs, entry) {
5787 char *refstr;
5788 refstr = got_ref_to_str(re->ref);
5789 if (refstr == NULL) {
5790 err = got_error_from_errno("got_ref_to_str");
5791 break;
5793 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5794 free(refstr);
5797 got_ref_list_free(&refs);
5798 return err;
5801 static const struct got_error *
5802 delete_ref_by_name(struct got_repository *repo, const char *refname)
5804 const struct got_error *err;
5805 struct got_reference *ref;
5807 err = got_ref_open(&ref, repo, refname, 0);
5808 if (err)
5809 return err;
5811 err = delete_ref(repo, ref);
5812 got_ref_close(ref);
5813 return err;
5816 static const struct got_error *
5817 add_ref(struct got_repository *repo, const char *refname, const char *target)
5819 const struct got_error *err = NULL;
5820 struct got_object_id *id = NULL;
5821 struct got_reference *ref = NULL;
5822 struct got_reflist_head refs;
5825 * Don't let the user create a reference name with a leading '-'.
5826 * While technically a valid reference name, this case is usually
5827 * an unintended typo.
5829 if (refname[0] == '-')
5830 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5832 TAILQ_INIT(&refs);
5833 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
5834 if (err)
5835 goto done;
5836 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
5837 &refs, repo);
5838 got_ref_list_free(&refs);
5839 if (err)
5840 goto done;
5842 err = got_ref_alloc(&ref, refname, id);
5843 if (err)
5844 goto done;
5846 err = got_ref_write(ref, repo);
5847 done:
5848 if (ref)
5849 got_ref_close(ref);
5850 free(id);
5851 return err;
5854 static const struct got_error *
5855 add_symref(struct got_repository *repo, const char *refname, const char *target)
5857 const struct got_error *err = NULL;
5858 struct got_reference *ref = NULL;
5859 struct got_reference *target_ref = NULL;
5862 * Don't let the user create a reference name with a leading '-'.
5863 * While technically a valid reference name, this case is usually
5864 * an unintended typo.
5866 if (refname[0] == '-')
5867 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5869 err = got_ref_open(&target_ref, repo, target, 0);
5870 if (err)
5871 return err;
5873 err = got_ref_alloc_symref(&ref, refname, target_ref);
5874 if (err)
5875 goto done;
5877 err = got_ref_write(ref, repo);
5878 done:
5879 if (target_ref)
5880 got_ref_close(target_ref);
5881 if (ref)
5882 got_ref_close(ref);
5883 return err;
5886 static const struct got_error *
5887 cmd_ref(int argc, char *argv[])
5889 const struct got_error *error = NULL;
5890 struct got_repository *repo = NULL;
5891 struct got_worktree *worktree = NULL;
5892 char *cwd = NULL, *repo_path = NULL;
5893 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
5894 const char *obj_arg = NULL, *symref_target= NULL;
5895 char *refname = NULL;
5897 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
5898 switch (ch) {
5899 case 'c':
5900 obj_arg = optarg;
5901 break;
5902 case 'd':
5903 do_delete = 1;
5904 break;
5905 case 'r':
5906 repo_path = realpath(optarg, NULL);
5907 if (repo_path == NULL)
5908 return got_error_from_errno2("realpath",
5909 optarg);
5910 got_path_strip_trailing_slashes(repo_path);
5911 break;
5912 case 'l':
5913 do_list = 1;
5914 break;
5915 case 's':
5916 symref_target = optarg;
5917 break;
5918 case 't':
5919 sort_by_time = 1;
5920 break;
5921 default:
5922 usage_ref();
5923 /* NOTREACHED */
5927 if (obj_arg && do_list)
5928 option_conflict('c', 'l');
5929 if (obj_arg && do_delete)
5930 option_conflict('c', 'd');
5931 if (obj_arg && symref_target)
5932 option_conflict('c', 's');
5933 if (symref_target && do_delete)
5934 option_conflict('s', 'd');
5935 if (symref_target && do_list)
5936 option_conflict('s', 'l');
5937 if (do_delete && do_list)
5938 option_conflict('d', 'l');
5939 if (sort_by_time && !do_list)
5940 errx(1, "-t option requires -l option");
5942 argc -= optind;
5943 argv += optind;
5945 if (do_list) {
5946 if (argc != 0 && argc != 1)
5947 usage_ref();
5948 if (argc == 1) {
5949 refname = strdup(argv[0]);
5950 if (refname == NULL) {
5951 error = got_error_from_errno("strdup");
5952 goto done;
5955 } else {
5956 if (argc != 1)
5957 usage_ref();
5958 refname = strdup(argv[0]);
5959 if (refname == NULL) {
5960 error = got_error_from_errno("strdup");
5961 goto done;
5965 if (refname)
5966 got_path_strip_trailing_slashes(refname);
5968 #ifndef PROFILE
5969 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5970 "sendfd unveil", NULL) == -1)
5971 err(1, "pledge");
5972 #endif
5973 cwd = getcwd(NULL, 0);
5974 if (cwd == NULL) {
5975 error = got_error_from_errno("getcwd");
5976 goto done;
5979 if (repo_path == NULL) {
5980 error = got_worktree_open(&worktree, cwd);
5981 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5982 goto done;
5983 else
5984 error = NULL;
5985 if (worktree) {
5986 repo_path =
5987 strdup(got_worktree_get_repo_path(worktree));
5988 if (repo_path == NULL)
5989 error = got_error_from_errno("strdup");
5990 if (error)
5991 goto done;
5992 } else {
5993 repo_path = strdup(cwd);
5994 if (repo_path == NULL) {
5995 error = got_error_from_errno("strdup");
5996 goto done;
6001 error = got_repo_open(&repo, repo_path, NULL);
6002 if (error != NULL)
6003 goto done;
6005 #ifndef PROFILE
6006 if (do_list) {
6007 /* Remove "cpath" promise. */
6008 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6009 NULL) == -1)
6010 err(1, "pledge");
6012 #endif
6014 error = apply_unveil(got_repo_get_path(repo), do_list,
6015 worktree ? got_worktree_get_root_path(worktree) : NULL);
6016 if (error)
6017 goto done;
6019 if (do_list)
6020 error = list_refs(repo, refname, sort_by_time);
6021 else if (do_delete)
6022 error = delete_ref_by_name(repo, refname);
6023 else if (symref_target)
6024 error = add_symref(repo, refname, symref_target);
6025 else {
6026 if (obj_arg == NULL)
6027 usage_ref();
6028 error = add_ref(repo, refname, obj_arg);
6030 done:
6031 free(refname);
6032 if (repo) {
6033 const struct got_error *close_err = got_repo_close(repo);
6034 if (error == NULL)
6035 error = close_err;
6037 if (worktree)
6038 got_worktree_close(worktree);
6039 free(cwd);
6040 free(repo_path);
6041 return error;
6044 __dead static void
6045 usage_branch(void)
6047 fprintf(stderr,
6048 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
6049 "[-n] [name]\n", getprogname());
6050 exit(1);
6053 static const struct got_error *
6054 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6055 struct got_reference *ref)
6057 const struct got_error *err = NULL;
6058 const char *refname, *marker = " ";
6059 char *refstr;
6061 refname = got_ref_get_name(ref);
6062 if (worktree && strcmp(refname,
6063 got_worktree_get_head_ref_name(worktree)) == 0) {
6064 struct got_object_id *id = NULL;
6066 err = got_ref_resolve(&id, repo, ref);
6067 if (err)
6068 return err;
6069 if (got_object_id_cmp(id,
6070 got_worktree_get_base_commit_id(worktree)) == 0)
6071 marker = "* ";
6072 else
6073 marker = "~ ";
6074 free(id);
6077 if (strncmp(refname, "refs/heads/", 11) == 0)
6078 refname += 11;
6079 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6080 refname += 18;
6081 if (strncmp(refname, "refs/remotes/", 13) == 0)
6082 refname += 13;
6084 refstr = got_ref_to_str(ref);
6085 if (refstr == NULL)
6086 return got_error_from_errno("got_ref_to_str");
6088 printf("%s%s: %s\n", marker, refname, refstr);
6089 free(refstr);
6090 return NULL;
6093 static const struct got_error *
6094 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6096 const char *refname;
6098 if (worktree == NULL)
6099 return got_error(GOT_ERR_NOT_WORKTREE);
6101 refname = got_worktree_get_head_ref_name(worktree);
6103 if (strncmp(refname, "refs/heads/", 11) == 0)
6104 refname += 11;
6105 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6106 refname += 18;
6108 printf("%s\n", refname);
6110 return NULL;
6113 static const struct got_error *
6114 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6115 int sort_by_time)
6117 static const struct got_error *err = NULL;
6118 struct got_reflist_head refs;
6119 struct got_reflist_entry *re;
6120 struct got_reference *temp_ref = NULL;
6121 int rebase_in_progress, histedit_in_progress;
6123 TAILQ_INIT(&refs);
6125 if (worktree) {
6126 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6127 worktree);
6128 if (err)
6129 return err;
6131 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6132 worktree);
6133 if (err)
6134 return err;
6136 if (rebase_in_progress || histedit_in_progress) {
6137 err = got_ref_open(&temp_ref, repo,
6138 got_worktree_get_head_ref_name(worktree), 0);
6139 if (err)
6140 return err;
6141 list_branch(repo, worktree, temp_ref);
6142 got_ref_close(temp_ref);
6146 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6147 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6148 repo);
6149 if (err)
6150 return err;
6152 TAILQ_FOREACH(re, &refs, entry)
6153 list_branch(repo, worktree, re->ref);
6155 got_ref_list_free(&refs);
6157 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6158 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6159 repo);
6160 if (err)
6161 return err;
6163 TAILQ_FOREACH(re, &refs, entry)
6164 list_branch(repo, worktree, re->ref);
6166 got_ref_list_free(&refs);
6168 return NULL;
6171 static const struct got_error *
6172 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6173 const char *branch_name)
6175 const struct got_error *err = NULL;
6176 struct got_reference *ref = NULL;
6177 char *refname, *remote_refname = NULL;
6179 if (strncmp(branch_name, "refs/", 5) == 0)
6180 branch_name += 5;
6181 if (strncmp(branch_name, "heads/", 6) == 0)
6182 branch_name += 6;
6183 else if (strncmp(branch_name, "remotes/", 8) == 0)
6184 branch_name += 8;
6186 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6187 return got_error_from_errno("asprintf");
6189 if (asprintf(&remote_refname, "refs/remotes/%s",
6190 branch_name) == -1) {
6191 err = got_error_from_errno("asprintf");
6192 goto done;
6195 err = got_ref_open(&ref, repo, refname, 0);
6196 if (err) {
6197 const struct got_error *err2;
6198 if (err->code != GOT_ERR_NOT_REF)
6199 goto done;
6201 * Keep 'err' intact such that if neither branch exists
6202 * we report "refs/heads" rather than "refs/remotes" in
6203 * our error message.
6205 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6206 if (err2)
6207 goto done;
6208 err = NULL;
6211 if (worktree &&
6212 strcmp(got_worktree_get_head_ref_name(worktree),
6213 got_ref_get_name(ref)) == 0) {
6214 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6215 "will not delete this work tree's current branch");
6216 goto done;
6219 err = delete_ref(repo, ref);
6220 done:
6221 if (ref)
6222 got_ref_close(ref);
6223 free(refname);
6224 free(remote_refname);
6225 return err;
6228 static const struct got_error *
6229 add_branch(struct got_repository *repo, const char *branch_name,
6230 struct got_object_id *base_commit_id)
6232 const struct got_error *err = NULL;
6233 struct got_reference *ref = NULL;
6234 char *base_refname = NULL, *refname = NULL;
6237 * Don't let the user create a branch name with a leading '-'.
6238 * While technically a valid reference name, this case is usually
6239 * an unintended typo.
6241 if (branch_name[0] == '-')
6242 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6244 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6245 branch_name += 11;
6247 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6248 err = got_error_from_errno("asprintf");
6249 goto done;
6252 err = got_ref_open(&ref, repo, refname, 0);
6253 if (err == NULL) {
6254 err = got_error(GOT_ERR_BRANCH_EXISTS);
6255 goto done;
6256 } else if (err->code != GOT_ERR_NOT_REF)
6257 goto done;
6259 err = got_ref_alloc(&ref, refname, base_commit_id);
6260 if (err)
6261 goto done;
6263 err = got_ref_write(ref, repo);
6264 done:
6265 if (ref)
6266 got_ref_close(ref);
6267 free(base_refname);
6268 free(refname);
6269 return err;
6272 static const struct got_error *
6273 cmd_branch(int argc, char *argv[])
6275 const struct got_error *error = NULL;
6276 struct got_repository *repo = NULL;
6277 struct got_worktree *worktree = NULL;
6278 char *cwd = NULL, *repo_path = NULL;
6279 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6280 const char *delref = NULL, *commit_id_arg = NULL;
6281 struct got_reference *ref = NULL;
6282 struct got_pathlist_head paths;
6283 struct got_pathlist_entry *pe;
6284 struct got_object_id *commit_id = NULL;
6285 char *commit_id_str = NULL;
6287 TAILQ_INIT(&paths);
6289 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6290 switch (ch) {
6291 case 'c':
6292 commit_id_arg = optarg;
6293 break;
6294 case 'd':
6295 delref = optarg;
6296 break;
6297 case 'r':
6298 repo_path = realpath(optarg, NULL);
6299 if (repo_path == NULL)
6300 return got_error_from_errno2("realpath",
6301 optarg);
6302 got_path_strip_trailing_slashes(repo_path);
6303 break;
6304 case 'l':
6305 do_list = 1;
6306 break;
6307 case 'n':
6308 do_update = 0;
6309 break;
6310 case 't':
6311 sort_by_time = 1;
6312 break;
6313 default:
6314 usage_branch();
6315 /* NOTREACHED */
6319 if (do_list && delref)
6320 option_conflict('l', 'd');
6321 if (sort_by_time && !do_list)
6322 errx(1, "-t option requires -l option");
6324 argc -= optind;
6325 argv += optind;
6327 if (!do_list && !delref && argc == 0)
6328 do_show = 1;
6330 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6331 errx(1, "-c option can only be used when creating a branch");
6333 if (do_list || delref) {
6334 if (argc > 0)
6335 usage_branch();
6336 } else if (!do_show && argc != 1)
6337 usage_branch();
6339 #ifndef PROFILE
6340 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6341 "sendfd unveil", NULL) == -1)
6342 err(1, "pledge");
6343 #endif
6344 cwd = getcwd(NULL, 0);
6345 if (cwd == NULL) {
6346 error = got_error_from_errno("getcwd");
6347 goto done;
6350 if (repo_path == NULL) {
6351 error = got_worktree_open(&worktree, cwd);
6352 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6353 goto done;
6354 else
6355 error = NULL;
6356 if (worktree) {
6357 repo_path =
6358 strdup(got_worktree_get_repo_path(worktree));
6359 if (repo_path == NULL)
6360 error = got_error_from_errno("strdup");
6361 if (error)
6362 goto done;
6363 } else {
6364 repo_path = strdup(cwd);
6365 if (repo_path == NULL) {
6366 error = got_error_from_errno("strdup");
6367 goto done;
6372 error = got_repo_open(&repo, repo_path, NULL);
6373 if (error != NULL)
6374 goto done;
6376 #ifndef PROFILE
6377 if (do_list || do_show) {
6378 /* Remove "cpath" promise. */
6379 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6380 NULL) == -1)
6381 err(1, "pledge");
6383 #endif
6385 error = apply_unveil(got_repo_get_path(repo), do_list,
6386 worktree ? got_worktree_get_root_path(worktree) : NULL);
6387 if (error)
6388 goto done;
6390 if (do_show)
6391 error = show_current_branch(repo, worktree);
6392 else if (do_list)
6393 error = list_branches(repo, worktree, sort_by_time);
6394 else if (delref)
6395 error = delete_branch(repo, worktree, delref);
6396 else {
6397 struct got_reflist_head refs;
6398 TAILQ_INIT(&refs);
6399 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6400 NULL);
6401 if (error)
6402 goto done;
6403 if (commit_id_arg == NULL)
6404 commit_id_arg = worktree ?
6405 got_worktree_get_head_ref_name(worktree) :
6406 GOT_REF_HEAD;
6407 error = got_repo_match_object_id(&commit_id, NULL,
6408 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6409 got_ref_list_free(&refs);
6410 if (error)
6411 goto done;
6412 error = add_branch(repo, argv[0], commit_id);
6413 if (error)
6414 goto done;
6415 if (worktree && do_update) {
6416 struct got_update_progress_arg upa;
6417 char *branch_refname = NULL;
6419 error = got_object_id_str(&commit_id_str, commit_id);
6420 if (error)
6421 goto done;
6422 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6423 worktree);
6424 if (error)
6425 goto done;
6426 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6427 == -1) {
6428 error = got_error_from_errno("asprintf");
6429 goto done;
6431 error = got_ref_open(&ref, repo, branch_refname, 0);
6432 free(branch_refname);
6433 if (error)
6434 goto done;
6435 error = switch_head_ref(ref, commit_id, worktree,
6436 repo);
6437 if (error)
6438 goto done;
6439 error = got_worktree_set_base_commit_id(worktree, repo,
6440 commit_id);
6441 if (error)
6442 goto done;
6443 memset(&upa, 0, sizeof(upa));
6444 error = got_worktree_checkout_files(worktree, &paths,
6445 repo, update_progress, &upa, check_cancelled,
6446 NULL);
6447 if (error)
6448 goto done;
6449 if (upa.did_something) {
6450 printf("Updated to %s: %s\n",
6451 got_worktree_get_head_ref_name(worktree),
6452 commit_id_str);
6454 print_update_progress_stats(&upa);
6457 done:
6458 if (ref)
6459 got_ref_close(ref);
6460 if (repo) {
6461 const struct got_error *close_err = got_repo_close(repo);
6462 if (error == NULL)
6463 error = close_err;
6465 if (worktree)
6466 got_worktree_close(worktree);
6467 free(cwd);
6468 free(repo_path);
6469 free(commit_id);
6470 free(commit_id_str);
6471 TAILQ_FOREACH(pe, &paths, entry)
6472 free((char *)pe->path);
6473 got_pathlist_free(&paths);
6474 return error;
6478 __dead static void
6479 usage_tag(void)
6481 fprintf(stderr,
6482 "usage: %s tag [-c commit] [-r repository] [-l] "
6483 "[-m message] name\n", getprogname());
6484 exit(1);
6487 #if 0
6488 static const struct got_error *
6489 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6491 const struct got_error *err = NULL;
6492 struct got_reflist_entry *re, *se, *new;
6493 struct got_object_id *re_id, *se_id;
6494 struct got_tag_object *re_tag, *se_tag;
6495 time_t re_time, se_time;
6497 STAILQ_FOREACH(re, tags, entry) {
6498 se = STAILQ_FIRST(sorted);
6499 if (se == NULL) {
6500 err = got_reflist_entry_dup(&new, re);
6501 if (err)
6502 return err;
6503 STAILQ_INSERT_HEAD(sorted, new, entry);
6504 continue;
6505 } else {
6506 err = got_ref_resolve(&re_id, repo, re->ref);
6507 if (err)
6508 break;
6509 err = got_object_open_as_tag(&re_tag, repo, re_id);
6510 free(re_id);
6511 if (err)
6512 break;
6513 re_time = got_object_tag_get_tagger_time(re_tag);
6514 got_object_tag_close(re_tag);
6517 while (se) {
6518 err = got_ref_resolve(&se_id, repo, re->ref);
6519 if (err)
6520 break;
6521 err = got_object_open_as_tag(&se_tag, repo, se_id);
6522 free(se_id);
6523 if (err)
6524 break;
6525 se_time = got_object_tag_get_tagger_time(se_tag);
6526 got_object_tag_close(se_tag);
6528 if (se_time > re_time) {
6529 err = got_reflist_entry_dup(&new, re);
6530 if (err)
6531 return err;
6532 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6533 break;
6535 se = STAILQ_NEXT(se, entry);
6536 continue;
6539 done:
6540 return err;
6542 #endif
6544 static const struct got_error *
6545 list_tags(struct got_repository *repo)
6547 static const struct got_error *err = NULL;
6548 struct got_reflist_head refs;
6549 struct got_reflist_entry *re;
6551 TAILQ_INIT(&refs);
6553 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6554 if (err)
6555 return err;
6557 TAILQ_FOREACH(re, &refs, entry) {
6558 const char *refname;
6559 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6560 char datebuf[26];
6561 const char *tagger;
6562 time_t tagger_time;
6563 struct got_object_id *id;
6564 struct got_tag_object *tag;
6565 struct got_commit_object *commit = NULL;
6567 refname = got_ref_get_name(re->ref);
6568 if (strncmp(refname, "refs/tags/", 10) != 0)
6569 continue;
6570 refname += 10;
6571 refstr = got_ref_to_str(re->ref);
6572 if (refstr == NULL) {
6573 err = got_error_from_errno("got_ref_to_str");
6574 break;
6576 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6577 free(refstr);
6579 err = got_ref_resolve(&id, repo, re->ref);
6580 if (err)
6581 break;
6582 err = got_object_open_as_tag(&tag, repo, id);
6583 if (err) {
6584 if (err->code != GOT_ERR_OBJ_TYPE) {
6585 free(id);
6586 break;
6588 /* "lightweight" tag */
6589 err = got_object_open_as_commit(&commit, repo, id);
6590 if (err) {
6591 free(id);
6592 break;
6594 tagger = got_object_commit_get_committer(commit);
6595 tagger_time =
6596 got_object_commit_get_committer_time(commit);
6597 err = got_object_id_str(&id_str, id);
6598 free(id);
6599 if (err)
6600 break;
6601 } else {
6602 free(id);
6603 tagger = got_object_tag_get_tagger(tag);
6604 tagger_time = got_object_tag_get_tagger_time(tag);
6605 err = got_object_id_str(&id_str,
6606 got_object_tag_get_object_id(tag));
6607 if (err)
6608 break;
6610 printf("from: %s\n", tagger);
6611 datestr = get_datestr(&tagger_time, datebuf);
6612 if (datestr)
6613 printf("date: %s UTC\n", datestr);
6614 if (commit)
6615 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6616 else {
6617 switch (got_object_tag_get_object_type(tag)) {
6618 case GOT_OBJ_TYPE_BLOB:
6619 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6620 id_str);
6621 break;
6622 case GOT_OBJ_TYPE_TREE:
6623 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6624 id_str);
6625 break;
6626 case GOT_OBJ_TYPE_COMMIT:
6627 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6628 id_str);
6629 break;
6630 case GOT_OBJ_TYPE_TAG:
6631 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6632 id_str);
6633 break;
6634 default:
6635 break;
6638 free(id_str);
6639 if (commit) {
6640 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6641 if (err)
6642 break;
6643 got_object_commit_close(commit);
6644 } else {
6645 tagmsg0 = strdup(got_object_tag_get_message(tag));
6646 got_object_tag_close(tag);
6647 if (tagmsg0 == NULL) {
6648 err = got_error_from_errno("strdup");
6649 break;
6653 tagmsg = tagmsg0;
6654 do {
6655 line = strsep(&tagmsg, "\n");
6656 if (line)
6657 printf(" %s\n", line);
6658 } while (line);
6659 free(tagmsg0);
6662 got_ref_list_free(&refs);
6663 return NULL;
6666 static const struct got_error *
6667 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6668 const char *tag_name, const char *repo_path)
6670 const struct got_error *err = NULL;
6671 char *template = NULL, *initial_content = NULL;
6672 char *editor = NULL;
6673 int initial_content_len;
6674 int fd = -1;
6676 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6677 err = got_error_from_errno("asprintf");
6678 goto done;
6681 initial_content_len = asprintf(&initial_content,
6682 "\n# tagging commit %s as %s\n",
6683 commit_id_str, tag_name);
6684 if (initial_content_len == -1) {
6685 err = got_error_from_errno("asprintf");
6686 goto done;
6689 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6690 if (err)
6691 goto done;
6693 if (write(fd, initial_content, initial_content_len) == -1) {
6694 err = got_error_from_errno2("write", *tagmsg_path);
6695 goto done;
6698 err = get_editor(&editor);
6699 if (err)
6700 goto done;
6701 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6702 initial_content_len, 1);
6703 done:
6704 free(initial_content);
6705 free(template);
6706 free(editor);
6708 if (fd != -1 && close(fd) == -1 && err == NULL)
6709 err = got_error_from_errno2("close", *tagmsg_path);
6711 /* Editor is done; we can now apply unveil(2) */
6712 if (err == NULL)
6713 err = apply_unveil(repo_path, 0, NULL);
6714 if (err) {
6715 free(*tagmsg);
6716 *tagmsg = NULL;
6718 return err;
6721 static const struct got_error *
6722 add_tag(struct got_repository *repo, const char *tagger,
6723 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6725 const struct got_error *err = NULL;
6726 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6727 char *label = NULL, *commit_id_str = NULL;
6728 struct got_reference *ref = NULL;
6729 char *refname = NULL, *tagmsg = NULL;
6730 char *tagmsg_path = NULL, *tag_id_str = NULL;
6731 int preserve_tagmsg = 0;
6732 struct got_reflist_head refs;
6734 TAILQ_INIT(&refs);
6737 * Don't let the user create a tag name with a leading '-'.
6738 * While technically a valid reference name, this case is usually
6739 * an unintended typo.
6741 if (tag_name[0] == '-')
6742 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6744 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6745 if (err)
6746 goto done;
6748 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6749 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6750 if (err)
6751 goto done;
6753 err = got_object_id_str(&commit_id_str, commit_id);
6754 if (err)
6755 goto done;
6757 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6758 refname = strdup(tag_name);
6759 if (refname == NULL) {
6760 err = got_error_from_errno("strdup");
6761 goto done;
6763 tag_name += 10;
6764 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6765 err = got_error_from_errno("asprintf");
6766 goto done;
6769 err = got_ref_open(&ref, repo, refname, 0);
6770 if (err == NULL) {
6771 err = got_error(GOT_ERR_TAG_EXISTS);
6772 goto done;
6773 } else if (err->code != GOT_ERR_NOT_REF)
6774 goto done;
6776 if (tagmsg_arg == NULL) {
6777 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6778 tag_name, got_repo_get_path(repo));
6779 if (err) {
6780 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6781 tagmsg_path != NULL)
6782 preserve_tagmsg = 1;
6783 goto done;
6787 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6788 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6789 if (err) {
6790 if (tagmsg_path)
6791 preserve_tagmsg = 1;
6792 goto done;
6795 err = got_ref_alloc(&ref, refname, tag_id);
6796 if (err) {
6797 if (tagmsg_path)
6798 preserve_tagmsg = 1;
6799 goto done;
6802 err = got_ref_write(ref, repo);
6803 if (err) {
6804 if (tagmsg_path)
6805 preserve_tagmsg = 1;
6806 goto done;
6809 err = got_object_id_str(&tag_id_str, tag_id);
6810 if (err) {
6811 if (tagmsg_path)
6812 preserve_tagmsg = 1;
6813 goto done;
6815 printf("Created tag %s\n", tag_id_str);
6816 done:
6817 if (preserve_tagmsg) {
6818 fprintf(stderr, "%s: tag message preserved in %s\n",
6819 getprogname(), tagmsg_path);
6820 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6821 err = got_error_from_errno2("unlink", tagmsg_path);
6822 free(tag_id_str);
6823 if (ref)
6824 got_ref_close(ref);
6825 free(commit_id);
6826 free(commit_id_str);
6827 free(refname);
6828 free(tagmsg);
6829 free(tagmsg_path);
6830 got_ref_list_free(&refs);
6831 return err;
6834 static const struct got_error *
6835 cmd_tag(int argc, char *argv[])
6837 const struct got_error *error = NULL;
6838 struct got_repository *repo = NULL;
6839 struct got_worktree *worktree = NULL;
6840 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6841 char *gitconfig_path = NULL, *tagger = NULL;
6842 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6843 int ch, do_list = 0;
6845 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6846 switch (ch) {
6847 case 'c':
6848 commit_id_arg = optarg;
6849 break;
6850 case 'm':
6851 tagmsg = optarg;
6852 break;
6853 case 'r':
6854 repo_path = realpath(optarg, NULL);
6855 if (repo_path == NULL)
6856 return got_error_from_errno2("realpath",
6857 optarg);
6858 got_path_strip_trailing_slashes(repo_path);
6859 break;
6860 case 'l':
6861 do_list = 1;
6862 break;
6863 default:
6864 usage_tag();
6865 /* NOTREACHED */
6869 argc -= optind;
6870 argv += optind;
6872 if (do_list) {
6873 if (commit_id_arg != NULL)
6874 errx(1,
6875 "-c option can only be used when creating a tag");
6876 if (tagmsg)
6877 option_conflict('l', 'm');
6878 if (argc > 0)
6879 usage_tag();
6880 } else if (argc != 1)
6881 usage_tag();
6883 tag_name = argv[0];
6885 #ifndef PROFILE
6886 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6887 "sendfd unveil", NULL) == -1)
6888 err(1, "pledge");
6889 #endif
6890 cwd = getcwd(NULL, 0);
6891 if (cwd == NULL) {
6892 error = got_error_from_errno("getcwd");
6893 goto done;
6896 if (repo_path == NULL) {
6897 error = got_worktree_open(&worktree, cwd);
6898 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6899 goto done;
6900 else
6901 error = NULL;
6902 if (worktree) {
6903 repo_path =
6904 strdup(got_worktree_get_repo_path(worktree));
6905 if (repo_path == NULL)
6906 error = got_error_from_errno("strdup");
6907 if (error)
6908 goto done;
6909 } else {
6910 repo_path = strdup(cwd);
6911 if (repo_path == NULL) {
6912 error = got_error_from_errno("strdup");
6913 goto done;
6918 if (do_list) {
6919 if (worktree) {
6920 /* Release work tree lock. */
6921 got_worktree_close(worktree);
6922 worktree = NULL;
6924 error = got_repo_open(&repo, repo_path, NULL);
6925 if (error != NULL)
6926 goto done;
6927 #ifndef PROFILE
6928 /* Remove "cpath" promise. */
6929 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6930 NULL) == -1)
6931 err(1, "pledge");
6932 #endif
6933 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6934 if (error)
6935 goto done;
6936 error = list_tags(repo);
6937 } else {
6938 error = get_gitconfig_path(&gitconfig_path);
6939 if (error)
6940 goto done;
6941 error = got_repo_open(&repo, repo_path, gitconfig_path);
6942 if (error != NULL)
6943 goto done;
6945 error = get_author(&tagger, repo, worktree);
6946 if (error)
6947 goto done;
6948 if (worktree) {
6949 /* Release work tree lock. */
6950 got_worktree_close(worktree);
6951 worktree = NULL;
6954 if (tagmsg) {
6955 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6956 if (error)
6957 goto done;
6960 if (commit_id_arg == NULL) {
6961 struct got_reference *head_ref;
6962 struct got_object_id *commit_id;
6963 error = got_ref_open(&head_ref, repo,
6964 worktree ? got_worktree_get_head_ref_name(worktree)
6965 : GOT_REF_HEAD, 0);
6966 if (error)
6967 goto done;
6968 error = got_ref_resolve(&commit_id, repo, head_ref);
6969 got_ref_close(head_ref);
6970 if (error)
6971 goto done;
6972 error = got_object_id_str(&commit_id_str, commit_id);
6973 free(commit_id);
6974 if (error)
6975 goto done;
6978 error = add_tag(repo, tagger, tag_name,
6979 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6981 done:
6982 if (repo) {
6983 const struct got_error *close_err = got_repo_close(repo);
6984 if (error == NULL)
6985 error = close_err;
6987 if (worktree)
6988 got_worktree_close(worktree);
6989 free(cwd);
6990 free(repo_path);
6991 free(gitconfig_path);
6992 free(commit_id_str);
6993 free(tagger);
6994 return error;
6997 __dead static void
6998 usage_add(void)
7000 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
7001 getprogname());
7002 exit(1);
7005 static const struct got_error *
7006 add_progress(void *arg, unsigned char status, const char *path)
7008 while (path[0] == '/')
7009 path++;
7010 printf("%c %s\n", status, path);
7011 return NULL;
7014 static const struct got_error *
7015 cmd_add(int argc, char *argv[])
7017 const struct got_error *error = NULL;
7018 struct got_repository *repo = NULL;
7019 struct got_worktree *worktree = NULL;
7020 char *cwd = NULL;
7021 struct got_pathlist_head paths;
7022 struct got_pathlist_entry *pe;
7023 int ch, can_recurse = 0, no_ignores = 0;
7025 TAILQ_INIT(&paths);
7027 while ((ch = getopt(argc, argv, "IR")) != -1) {
7028 switch (ch) {
7029 case 'I':
7030 no_ignores = 1;
7031 break;
7032 case 'R':
7033 can_recurse = 1;
7034 break;
7035 default:
7036 usage_add();
7037 /* NOTREACHED */
7041 argc -= optind;
7042 argv += optind;
7044 #ifndef PROFILE
7045 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7046 NULL) == -1)
7047 err(1, "pledge");
7048 #endif
7049 if (argc < 1)
7050 usage_add();
7052 cwd = getcwd(NULL, 0);
7053 if (cwd == NULL) {
7054 error = got_error_from_errno("getcwd");
7055 goto done;
7058 error = got_worktree_open(&worktree, cwd);
7059 if (error) {
7060 if (error->code == GOT_ERR_NOT_WORKTREE)
7061 error = wrap_not_worktree_error(error, "add", cwd);
7062 goto done;
7065 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7066 NULL);
7067 if (error != NULL)
7068 goto done;
7070 error = apply_unveil(got_repo_get_path(repo), 1,
7071 got_worktree_get_root_path(worktree));
7072 if (error)
7073 goto done;
7075 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7076 if (error)
7077 goto done;
7079 if (!can_recurse) {
7080 char *ondisk_path;
7081 struct stat sb;
7082 TAILQ_FOREACH(pe, &paths, entry) {
7083 if (asprintf(&ondisk_path, "%s/%s",
7084 got_worktree_get_root_path(worktree),
7085 pe->path) == -1) {
7086 error = got_error_from_errno("asprintf");
7087 goto done;
7089 if (lstat(ondisk_path, &sb) == -1) {
7090 if (errno == ENOENT) {
7091 free(ondisk_path);
7092 continue;
7094 error = got_error_from_errno2("lstat",
7095 ondisk_path);
7096 free(ondisk_path);
7097 goto done;
7099 free(ondisk_path);
7100 if (S_ISDIR(sb.st_mode)) {
7101 error = got_error_msg(GOT_ERR_BAD_PATH,
7102 "adding directories requires -R option");
7103 goto done;
7108 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7109 NULL, repo, no_ignores);
7110 done:
7111 if (repo) {
7112 const struct got_error *close_err = got_repo_close(repo);
7113 if (error == NULL)
7114 error = close_err;
7116 if (worktree)
7117 got_worktree_close(worktree);
7118 TAILQ_FOREACH(pe, &paths, entry)
7119 free((char *)pe->path);
7120 got_pathlist_free(&paths);
7121 free(cwd);
7122 return error;
7125 __dead static void
7126 usage_remove(void)
7128 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7129 "path ...\n", getprogname());
7130 exit(1);
7133 static const struct got_error *
7134 print_remove_status(void *arg, unsigned char status,
7135 unsigned char staged_status, const char *path)
7137 while (path[0] == '/')
7138 path++;
7139 if (status == GOT_STATUS_NONEXISTENT)
7140 return NULL;
7141 if (status == staged_status && (status == GOT_STATUS_DELETE))
7142 status = GOT_STATUS_NO_CHANGE;
7143 printf("%c%c %s\n", status, staged_status, path);
7144 return NULL;
7147 static const struct got_error *
7148 cmd_remove(int argc, char *argv[])
7150 const struct got_error *error = NULL;
7151 struct got_worktree *worktree = NULL;
7152 struct got_repository *repo = NULL;
7153 const char *status_codes = NULL;
7154 char *cwd = NULL;
7155 struct got_pathlist_head paths;
7156 struct got_pathlist_entry *pe;
7157 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7158 int ignore_missing_paths = 0;
7160 TAILQ_INIT(&paths);
7162 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7163 switch (ch) {
7164 case 'f':
7165 delete_local_mods = 1;
7166 ignore_missing_paths = 1;
7167 break;
7168 case 'k':
7169 keep_on_disk = 1;
7170 break;
7171 case 'R':
7172 can_recurse = 1;
7173 break;
7174 case 's':
7175 for (i = 0; i < strlen(optarg); i++) {
7176 switch (optarg[i]) {
7177 case GOT_STATUS_MODIFY:
7178 delete_local_mods = 1;
7179 break;
7180 case GOT_STATUS_MISSING:
7181 ignore_missing_paths = 1;
7182 break;
7183 default:
7184 errx(1, "invalid status code '%c'",
7185 optarg[i]);
7188 status_codes = optarg;
7189 break;
7190 default:
7191 usage_remove();
7192 /* NOTREACHED */
7196 argc -= optind;
7197 argv += optind;
7199 #ifndef PROFILE
7200 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7201 NULL) == -1)
7202 err(1, "pledge");
7203 #endif
7204 if (argc < 1)
7205 usage_remove();
7207 cwd = getcwd(NULL, 0);
7208 if (cwd == NULL) {
7209 error = got_error_from_errno("getcwd");
7210 goto done;
7212 error = got_worktree_open(&worktree, cwd);
7213 if (error) {
7214 if (error->code == GOT_ERR_NOT_WORKTREE)
7215 error = wrap_not_worktree_error(error, "remove", cwd);
7216 goto done;
7219 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7220 NULL);
7221 if (error)
7222 goto done;
7224 error = apply_unveil(got_repo_get_path(repo), 1,
7225 got_worktree_get_root_path(worktree));
7226 if (error)
7227 goto done;
7229 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7230 if (error)
7231 goto done;
7233 if (!can_recurse) {
7234 char *ondisk_path;
7235 struct stat sb;
7236 TAILQ_FOREACH(pe, &paths, entry) {
7237 if (asprintf(&ondisk_path, "%s/%s",
7238 got_worktree_get_root_path(worktree),
7239 pe->path) == -1) {
7240 error = got_error_from_errno("asprintf");
7241 goto done;
7243 if (lstat(ondisk_path, &sb) == -1) {
7244 if (errno == ENOENT) {
7245 free(ondisk_path);
7246 continue;
7248 error = got_error_from_errno2("lstat",
7249 ondisk_path);
7250 free(ondisk_path);
7251 goto done;
7253 free(ondisk_path);
7254 if (S_ISDIR(sb.st_mode)) {
7255 error = got_error_msg(GOT_ERR_BAD_PATH,
7256 "removing directories requires -R option");
7257 goto done;
7262 error = got_worktree_schedule_delete(worktree, &paths,
7263 delete_local_mods, status_codes, print_remove_status, NULL,
7264 repo, keep_on_disk, ignore_missing_paths);
7265 done:
7266 if (repo) {
7267 const struct got_error *close_err = got_repo_close(repo);
7268 if (error == NULL)
7269 error = close_err;
7271 if (worktree)
7272 got_worktree_close(worktree);
7273 TAILQ_FOREACH(pe, &paths, entry)
7274 free((char *)pe->path);
7275 got_pathlist_free(&paths);
7276 free(cwd);
7277 return error;
7280 __dead static void
7281 usage_patch(void)
7283 fprintf(stderr, "usage: %s patch [-n] [-p strip-count] "
7284 "[-R] [patchfile]\n", getprogname());
7285 exit(1);
7288 static const struct got_error *
7289 patch_from_stdin(int *patchfd)
7291 const struct got_error *err = NULL;
7292 ssize_t r;
7293 char *path, buf[BUFSIZ];
7294 sig_t sighup, sigint, sigquit;
7296 err = got_opentemp_named_fd(&path, patchfd,
7297 GOT_TMPDIR_STR "/got-patch");
7298 if (err)
7299 return err;
7300 unlink(path);
7301 free(path);
7303 sighup = signal(SIGHUP, SIG_DFL);
7304 sigint = signal(SIGINT, SIG_DFL);
7305 sigquit = signal(SIGQUIT, SIG_DFL);
7307 for (;;) {
7308 r = read(0, buf, sizeof(buf));
7309 if (r == -1) {
7310 err = got_error_from_errno("read");
7311 break;
7313 if (r == 0)
7314 break;
7315 if (write(*patchfd, buf, r) == -1) {
7316 err = got_error_from_errno("write");
7317 break;
7321 signal(SIGHUP, sighup);
7322 signal(SIGINT, sigint);
7323 signal(SIGQUIT, sigquit);
7325 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7326 err = got_error_from_errno("lseek");
7328 if (err != NULL) {
7329 close(*patchfd);
7330 *patchfd = -1;
7333 return err;
7336 static const struct got_error *
7337 patch_progress(void *arg, const char *old, const char *new,
7338 unsigned char status, const struct got_error *error, long old_from,
7339 long old_lines, long new_from, long new_lines, long offset,
7340 const struct got_error *hunk_err)
7342 const char *path = new == NULL ? old : new;
7344 while (*path == '/')
7345 path++;
7347 if (status != 0)
7348 printf("%c %s\n", status, path);
7350 if (error != NULL)
7351 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7353 if (offset != 0 || hunk_err != NULL) {
7354 printf("@@ -%ld,%ld +%ld,%ld @@ ", old_from,
7355 old_lines, new_from, new_lines);
7356 if (hunk_err != NULL)
7357 printf("%s\n", hunk_err->msg);
7358 else
7359 printf("applied with offset %ld\n", offset);
7362 return NULL;
7365 static const struct got_error *
7366 cmd_patch(int argc, char *argv[])
7368 const struct got_error *error = NULL, *close_error = NULL;
7369 struct got_worktree *worktree = NULL;
7370 struct got_repository *repo = NULL;
7371 const char *errstr;
7372 char *cwd = NULL;
7373 int ch, nop = 0, strip = -1, reverse = 0;
7374 int patchfd;
7376 while ((ch = getopt(argc, argv, "np:R")) != -1) {
7377 switch (ch) {
7378 case 'n':
7379 nop = 1;
7380 break;
7381 case 'p':
7382 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7383 if (errstr != NULL)
7384 errx(1, "pathname strip count is %s: %s",
7385 errstr, optarg);
7386 break;
7387 case 'R':
7388 reverse = 1;
7389 break;
7390 default:
7391 usage_patch();
7392 /* NOTREACHED */
7396 argc -= optind;
7397 argv += optind;
7399 if (argc == 0) {
7400 error = patch_from_stdin(&patchfd);
7401 if (error)
7402 return error;
7403 } else if (argc == 1) {
7404 patchfd = open(argv[0], O_RDONLY);
7405 if (patchfd == -1) {
7406 error = got_error_from_errno2("open", argv[0]);
7407 return error;
7409 } else
7410 usage_patch();
7412 if ((cwd = getcwd(NULL, 0)) == NULL) {
7413 error = got_error_from_errno("getcwd");
7414 goto done;
7417 error = got_worktree_open(&worktree, cwd);
7418 if (error != NULL)
7419 goto done;
7421 const char *repo_path = got_worktree_get_repo_path(worktree);
7422 error = got_repo_open(&repo, repo_path, NULL);
7423 if (error != NULL)
7424 goto done;
7426 error = apply_unveil(got_repo_get_path(repo), 0,
7427 got_worktree_get_root_path(worktree));
7428 if (error != NULL)
7429 goto done;
7431 #ifndef PROFILE
7432 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock",
7433 NULL) == -1)
7434 err(1, "pledge");
7435 #endif
7437 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
7438 &patch_progress, NULL, check_cancelled, NULL);
7440 done:
7441 if (repo) {
7442 close_error = got_repo_close(repo);
7443 if (error == NULL)
7444 error = close_error;
7446 if (worktree != NULL) {
7447 close_error = got_worktree_close(worktree);
7448 if (error == NULL)
7449 error = close_error;
7451 free(cwd);
7452 return error;
7455 __dead static void
7456 usage_revert(void)
7458 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
7459 "path ...\n", getprogname());
7460 exit(1);
7463 static const struct got_error *
7464 revert_progress(void *arg, unsigned char status, const char *path)
7466 if (status == GOT_STATUS_UNVERSIONED)
7467 return NULL;
7469 while (path[0] == '/')
7470 path++;
7471 printf("%c %s\n", status, path);
7472 return NULL;
7475 struct choose_patch_arg {
7476 FILE *patch_script_file;
7477 const char *action;
7480 static const struct got_error *
7481 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7482 int nchanges, const char *action)
7484 const struct got_error *err;
7485 char *line = NULL;
7486 size_t linesize = 0;
7487 ssize_t linelen;
7489 switch (status) {
7490 case GOT_STATUS_ADD:
7491 printf("A %s\n%s this addition? [y/n] ", path, action);
7492 break;
7493 case GOT_STATUS_DELETE:
7494 printf("D %s\n%s this deletion? [y/n] ", path, action);
7495 break;
7496 case GOT_STATUS_MODIFY:
7497 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7498 return got_error_from_errno("fseek");
7499 printf(GOT_COMMIT_SEP_STR);
7500 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7501 printf("%s", line);
7502 if (linelen == -1 && ferror(patch_file)) {
7503 err = got_error_from_errno("getline");
7504 free(line);
7505 return err;
7507 free(line);
7508 printf(GOT_COMMIT_SEP_STR);
7509 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7510 path, n, nchanges, action);
7511 break;
7512 default:
7513 return got_error_path(path, GOT_ERR_FILE_STATUS);
7516 return NULL;
7519 static const struct got_error *
7520 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7521 FILE *patch_file, int n, int nchanges)
7523 const struct got_error *err = NULL;
7524 char *line = NULL;
7525 size_t linesize = 0;
7526 ssize_t linelen;
7527 int resp = ' ';
7528 struct choose_patch_arg *a = arg;
7530 *choice = GOT_PATCH_CHOICE_NONE;
7532 if (a->patch_script_file) {
7533 char *nl;
7534 err = show_change(status, path, patch_file, n, nchanges,
7535 a->action);
7536 if (err)
7537 return err;
7538 linelen = getline(&line, &linesize, a->patch_script_file);
7539 if (linelen == -1) {
7540 if (ferror(a->patch_script_file))
7541 return got_error_from_errno("getline");
7542 return NULL;
7544 nl = strchr(line, '\n');
7545 if (nl)
7546 *nl = '\0';
7547 if (strcmp(line, "y") == 0) {
7548 *choice = GOT_PATCH_CHOICE_YES;
7549 printf("y\n");
7550 } else if (strcmp(line, "n") == 0) {
7551 *choice = GOT_PATCH_CHOICE_NO;
7552 printf("n\n");
7553 } else if (strcmp(line, "q") == 0 &&
7554 status == GOT_STATUS_MODIFY) {
7555 *choice = GOT_PATCH_CHOICE_QUIT;
7556 printf("q\n");
7557 } else
7558 printf("invalid response '%s'\n", line);
7559 free(line);
7560 return NULL;
7563 while (resp != 'y' && resp != 'n' && resp != 'q') {
7564 err = show_change(status, path, patch_file, n, nchanges,
7565 a->action);
7566 if (err)
7567 return err;
7568 resp = getchar();
7569 if (resp == '\n')
7570 resp = getchar();
7571 if (status == GOT_STATUS_MODIFY) {
7572 if (resp != 'y' && resp != 'n' && resp != 'q') {
7573 printf("invalid response '%c'\n", resp);
7574 resp = ' ';
7576 } else if (resp != 'y' && resp != 'n') {
7577 printf("invalid response '%c'\n", resp);
7578 resp = ' ';
7582 if (resp == 'y')
7583 *choice = GOT_PATCH_CHOICE_YES;
7584 else if (resp == 'n')
7585 *choice = GOT_PATCH_CHOICE_NO;
7586 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7587 *choice = GOT_PATCH_CHOICE_QUIT;
7589 return NULL;
7592 static const struct got_error *
7593 cmd_revert(int argc, char *argv[])
7595 const struct got_error *error = NULL;
7596 struct got_worktree *worktree = NULL;
7597 struct got_repository *repo = NULL;
7598 char *cwd = NULL, *path = NULL;
7599 struct got_pathlist_head paths;
7600 struct got_pathlist_entry *pe;
7601 int ch, can_recurse = 0, pflag = 0;
7602 FILE *patch_script_file = NULL;
7603 const char *patch_script_path = NULL;
7604 struct choose_patch_arg cpa;
7606 TAILQ_INIT(&paths);
7608 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
7609 switch (ch) {
7610 case 'p':
7611 pflag = 1;
7612 break;
7613 case 'F':
7614 patch_script_path = optarg;
7615 break;
7616 case 'R':
7617 can_recurse = 1;
7618 break;
7619 default:
7620 usage_revert();
7621 /* NOTREACHED */
7625 argc -= optind;
7626 argv += optind;
7628 #ifndef PROFILE
7629 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7630 "unveil", NULL) == -1)
7631 err(1, "pledge");
7632 #endif
7633 if (argc < 1)
7634 usage_revert();
7635 if (patch_script_path && !pflag)
7636 errx(1, "-F option can only be used together with -p option");
7638 cwd = getcwd(NULL, 0);
7639 if (cwd == NULL) {
7640 error = got_error_from_errno("getcwd");
7641 goto done;
7643 error = got_worktree_open(&worktree, cwd);
7644 if (error) {
7645 if (error->code == GOT_ERR_NOT_WORKTREE)
7646 error = wrap_not_worktree_error(error, "revert", cwd);
7647 goto done;
7650 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7651 NULL);
7652 if (error != NULL)
7653 goto done;
7655 if (patch_script_path) {
7656 patch_script_file = fopen(patch_script_path, "re");
7657 if (patch_script_file == NULL) {
7658 error = got_error_from_errno2("fopen",
7659 patch_script_path);
7660 goto done;
7663 error = apply_unveil(got_repo_get_path(repo), 1,
7664 got_worktree_get_root_path(worktree));
7665 if (error)
7666 goto done;
7668 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7669 if (error)
7670 goto done;
7672 if (!can_recurse) {
7673 char *ondisk_path;
7674 struct stat sb;
7675 TAILQ_FOREACH(pe, &paths, entry) {
7676 if (asprintf(&ondisk_path, "%s/%s",
7677 got_worktree_get_root_path(worktree),
7678 pe->path) == -1) {
7679 error = got_error_from_errno("asprintf");
7680 goto done;
7682 if (lstat(ondisk_path, &sb) == -1) {
7683 if (errno == ENOENT) {
7684 free(ondisk_path);
7685 continue;
7687 error = got_error_from_errno2("lstat",
7688 ondisk_path);
7689 free(ondisk_path);
7690 goto done;
7692 free(ondisk_path);
7693 if (S_ISDIR(sb.st_mode)) {
7694 error = got_error_msg(GOT_ERR_BAD_PATH,
7695 "reverting directories requires -R option");
7696 goto done;
7701 cpa.patch_script_file = patch_script_file;
7702 cpa.action = "revert";
7703 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7704 pflag ? choose_patch : NULL, &cpa, repo);
7705 done:
7706 if (patch_script_file && fclose(patch_script_file) == EOF &&
7707 error == NULL)
7708 error = got_error_from_errno2("fclose", patch_script_path);
7709 if (repo) {
7710 const struct got_error *close_err = got_repo_close(repo);
7711 if (error == NULL)
7712 error = close_err;
7714 if (worktree)
7715 got_worktree_close(worktree);
7716 free(path);
7717 free(cwd);
7718 return error;
7721 __dead static void
7722 usage_commit(void)
7724 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
7725 "[path ...]\n", getprogname());
7726 exit(1);
7729 struct collect_commit_logmsg_arg {
7730 const char *cmdline_log;
7731 const char *prepared_log;
7732 int non_interactive;
7733 const char *editor;
7734 const char *worktree_path;
7735 const char *branch_name;
7736 const char *repo_path;
7737 char *logmsg_path;
7741 static const struct got_error *
7742 read_prepared_logmsg(char **logmsg, const char *path)
7744 const struct got_error *err = NULL;
7745 FILE *f = NULL;
7746 struct stat sb;
7747 size_t r;
7749 *logmsg = NULL;
7750 memset(&sb, 0, sizeof(sb));
7752 f = fopen(path, "re");
7753 if (f == NULL)
7754 return got_error_from_errno2("fopen", path);
7756 if (fstat(fileno(f), &sb) == -1) {
7757 err = got_error_from_errno2("fstat", path);
7758 goto done;
7760 if (sb.st_size == 0) {
7761 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7762 goto done;
7765 *logmsg = malloc(sb.st_size + 1);
7766 if (*logmsg == NULL) {
7767 err = got_error_from_errno("malloc");
7768 goto done;
7771 r = fread(*logmsg, 1, sb.st_size, f);
7772 if (r != sb.st_size) {
7773 if (ferror(f))
7774 err = got_error_from_errno2("fread", path);
7775 else
7776 err = got_error(GOT_ERR_IO);
7777 goto done;
7779 (*logmsg)[sb.st_size] = '\0';
7780 done:
7781 if (fclose(f) == EOF && err == NULL)
7782 err = got_error_from_errno2("fclose", path);
7783 if (err) {
7784 free(*logmsg);
7785 *logmsg = NULL;
7787 return err;
7791 static const struct got_error *
7792 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7793 void *arg)
7795 char *initial_content = NULL;
7796 struct got_pathlist_entry *pe;
7797 const struct got_error *err = NULL;
7798 char *template = NULL;
7799 struct collect_commit_logmsg_arg *a = arg;
7800 int initial_content_len;
7801 int fd = -1;
7802 size_t len;
7804 /* if a message was specified on the command line, just use it */
7805 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7806 len = strlen(a->cmdline_log) + 1;
7807 *logmsg = malloc(len + 1);
7808 if (*logmsg == NULL)
7809 return got_error_from_errno("malloc");
7810 strlcpy(*logmsg, a->cmdline_log, len);
7811 return NULL;
7812 } else if (a->prepared_log != NULL && a->non_interactive)
7813 return read_prepared_logmsg(logmsg, a->prepared_log);
7815 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7816 return got_error_from_errno("asprintf");
7818 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7819 if (err)
7820 goto done;
7822 if (a->prepared_log) {
7823 char *msg;
7824 err = read_prepared_logmsg(&msg, a->prepared_log);
7825 if (err)
7826 goto done;
7827 if (write(fd, msg, strlen(msg)) == -1) {
7828 err = got_error_from_errno2("write", a->logmsg_path);
7829 free(msg);
7830 goto done;
7832 free(msg);
7835 initial_content_len = asprintf(&initial_content,
7836 "\n# changes to be committed on branch %s:\n",
7837 a->branch_name);
7838 if (initial_content_len == -1) {
7839 err = got_error_from_errno("asprintf");
7840 goto done;
7843 if (write(fd, initial_content, initial_content_len) == -1) {
7844 err = got_error_from_errno2("write", a->logmsg_path);
7845 goto done;
7848 TAILQ_FOREACH(pe, commitable_paths, entry) {
7849 struct got_commitable *ct = pe->data;
7850 dprintf(fd, "# %c %s\n",
7851 got_commitable_get_status(ct),
7852 got_commitable_get_path(ct));
7855 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7856 initial_content_len, a->prepared_log ? 0 : 1);
7857 done:
7858 free(initial_content);
7859 free(template);
7861 if (fd != -1 && close(fd) == -1 && err == NULL)
7862 err = got_error_from_errno2("close", a->logmsg_path);
7864 /* Editor is done; we can now apply unveil(2) */
7865 if (err == NULL)
7866 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7867 if (err) {
7868 free(*logmsg);
7869 *logmsg = NULL;
7871 return err;
7874 static const struct got_error *
7875 cmd_commit(int argc, char *argv[])
7877 const struct got_error *error = NULL;
7878 struct got_worktree *worktree = NULL;
7879 struct got_repository *repo = NULL;
7880 char *cwd = NULL, *id_str = NULL;
7881 struct got_object_id *id = NULL;
7882 const char *logmsg = NULL;
7883 char *prepared_logmsg = NULL;
7884 struct collect_commit_logmsg_arg cl_arg;
7885 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7886 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7887 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
7888 struct got_pathlist_head paths;
7890 TAILQ_INIT(&paths);
7891 cl_arg.logmsg_path = NULL;
7893 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7894 switch (ch) {
7895 case 'F':
7896 if (logmsg != NULL)
7897 option_conflict('F', 'm');
7898 prepared_logmsg = realpath(optarg, NULL);
7899 if (prepared_logmsg == NULL)
7900 return got_error_from_errno2("realpath",
7901 optarg);
7902 break;
7903 case 'm':
7904 if (prepared_logmsg)
7905 option_conflict('m', 'F');
7906 logmsg = optarg;
7907 break;
7908 case 'N':
7909 non_interactive = 1;
7910 break;
7911 case 'S':
7912 allow_bad_symlinks = 1;
7913 break;
7914 default:
7915 usage_commit();
7916 /* NOTREACHED */
7920 argc -= optind;
7921 argv += optind;
7923 #ifndef PROFILE
7924 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7925 "unveil", NULL) == -1)
7926 err(1, "pledge");
7927 #endif
7928 cwd = getcwd(NULL, 0);
7929 if (cwd == NULL) {
7930 error = got_error_from_errno("getcwd");
7931 goto done;
7933 error = got_worktree_open(&worktree, cwd);
7934 if (error) {
7935 if (error->code == GOT_ERR_NOT_WORKTREE)
7936 error = wrap_not_worktree_error(error, "commit", cwd);
7937 goto done;
7940 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7941 if (error)
7942 goto done;
7943 if (rebase_in_progress) {
7944 error = got_error(GOT_ERR_REBASING);
7945 goto done;
7948 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7949 worktree);
7950 if (error)
7951 goto done;
7953 error = get_gitconfig_path(&gitconfig_path);
7954 if (error)
7955 goto done;
7956 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7957 gitconfig_path);
7958 if (error != NULL)
7959 goto done;
7961 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
7962 if (error)
7963 goto done;
7964 if (merge_in_progress) {
7965 error = got_error(GOT_ERR_MERGE_BUSY);
7966 goto done;
7969 error = get_author(&author, repo, worktree);
7970 if (error)
7971 return error;
7974 * unveil(2) traverses exec(2); if an editor is used we have
7975 * to apply unveil after the log message has been written.
7977 if (logmsg == NULL || strlen(logmsg) == 0)
7978 error = get_editor(&editor);
7979 else
7980 error = apply_unveil(got_repo_get_path(repo), 0,
7981 got_worktree_get_root_path(worktree));
7982 if (error)
7983 goto done;
7985 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7986 if (error)
7987 goto done;
7989 cl_arg.editor = editor;
7990 cl_arg.cmdline_log = logmsg;
7991 cl_arg.prepared_log = prepared_logmsg;
7992 cl_arg.non_interactive = non_interactive;
7993 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
7994 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
7995 if (!histedit_in_progress) {
7996 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
7997 error = got_error(GOT_ERR_COMMIT_BRANCH);
7998 goto done;
8000 cl_arg.branch_name += 11;
8002 cl_arg.repo_path = got_repo_get_path(repo);
8003 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
8004 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
8005 print_status, NULL, repo);
8006 if (error) {
8007 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8008 cl_arg.logmsg_path != NULL)
8009 preserve_logmsg = 1;
8010 goto done;
8013 error = got_object_id_str(&id_str, id);
8014 if (error)
8015 goto done;
8016 printf("Created commit %s\n", id_str);
8017 done:
8018 if (preserve_logmsg) {
8019 fprintf(stderr, "%s: log message preserved in %s\n",
8020 getprogname(), cl_arg.logmsg_path);
8021 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8022 error == NULL)
8023 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8024 free(cl_arg.logmsg_path);
8025 if (repo) {
8026 const struct got_error *close_err = got_repo_close(repo);
8027 if (error == NULL)
8028 error = close_err;
8030 if (worktree)
8031 got_worktree_close(worktree);
8032 free(cwd);
8033 free(id_str);
8034 free(gitconfig_path);
8035 free(editor);
8036 free(author);
8037 free(prepared_logmsg);
8038 return error;
8041 __dead static void
8042 usage_send(void)
8044 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
8045 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
8046 "[remote-repository]\n", getprogname());
8047 exit(1);
8050 static void
8051 print_load_info(int print_colored, int print_found, int print_trees,
8052 int ncolored, int nfound, int ntrees)
8054 if (print_colored) {
8055 printf("%d commit%s colored", ncolored,
8056 ncolored == 1 ? "" : "s");
8058 if (print_found) {
8059 printf("%s%d object%s found",
8060 ncolored > 0 ? "; " : "",
8061 nfound, nfound == 1 ? "" : "s");
8063 if (print_trees) {
8064 printf("; %d tree%s scanned", ntrees,
8065 ntrees == 1 ? "" : "s");
8069 struct got_send_progress_arg {
8070 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8071 int verbosity;
8072 int last_ncolored;
8073 int last_nfound;
8074 int last_ntrees;
8075 int loading_done;
8076 int last_ncommits;
8077 int last_nobj_total;
8078 int last_p_deltify;
8079 int last_p_written;
8080 int last_p_sent;
8081 int printed_something;
8082 int sent_something;
8083 struct got_pathlist_head *delete_branches;
8086 static const struct got_error *
8087 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8088 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8089 int nobj_written, off_t bytes_sent, const char *refname, int success)
8091 struct got_send_progress_arg *a = arg;
8092 char scaled_packsize[FMT_SCALED_STRSIZE];
8093 char scaled_sent[FMT_SCALED_STRSIZE];
8094 int p_deltify = 0, p_written = 0, p_sent = 0;
8095 int print_colored = 0, print_found = 0, print_trees = 0;
8096 int print_searching = 0, print_total = 0;
8097 int print_deltify = 0, print_written = 0, print_sent = 0;
8099 if (a->verbosity < 0)
8100 return NULL;
8102 if (refname) {
8103 const char *status = success ? "accepted" : "rejected";
8105 if (success) {
8106 struct got_pathlist_entry *pe;
8107 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8108 const char *branchname = pe->path;
8109 if (got_path_cmp(branchname, refname,
8110 strlen(branchname), strlen(refname)) == 0) {
8111 status = "deleted";
8112 a->sent_something = 1;
8113 break;
8118 if (a->printed_something)
8119 putchar('\n');
8120 printf("Server has %s %s", status, refname);
8121 a->printed_something = 1;
8122 return NULL;
8125 if (a->last_ncolored != ncolored) {
8126 print_colored = 1;
8127 a->last_ncolored = ncolored;
8130 if (a->last_nfound != nfound) {
8131 print_colored = 1;
8132 print_found = 1;
8133 a->last_nfound = nfound;
8136 if (a->last_ntrees != ntrees) {
8137 print_colored = 1;
8138 print_found = 1;
8139 print_trees = 1;
8140 a->last_ntrees = ntrees;
8143 if ((print_colored || print_found || print_trees) &&
8144 !a->loading_done) {
8145 printf("\r");
8146 print_load_info(print_colored, print_found, print_trees,
8147 ncolored, nfound, ntrees);
8148 a->printed_something = 1;
8149 fflush(stdout);
8150 return NULL;
8151 } else if (!a->loading_done) {
8152 printf("\r");
8153 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8154 printf("\n");
8155 a->loading_done = 1;
8158 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8159 return got_error_from_errno("fmt_scaled");
8160 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8161 return got_error_from_errno("fmt_scaled");
8163 if (a->last_ncommits != ncommits) {
8164 print_searching = 1;
8165 a->last_ncommits = ncommits;
8168 if (a->last_nobj_total != nobj_total) {
8169 print_searching = 1;
8170 print_total = 1;
8171 a->last_nobj_total = nobj_total;
8174 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8175 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8176 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8177 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8178 return got_error(GOT_ERR_NO_SPACE);
8181 if (nobj_deltify > 0 || nobj_written > 0) {
8182 if (nobj_deltify > 0) {
8183 p_deltify = (nobj_deltify * 100) / nobj_total;
8184 if (p_deltify != a->last_p_deltify) {
8185 a->last_p_deltify = p_deltify;
8186 print_searching = 1;
8187 print_total = 1;
8188 print_deltify = 1;
8191 if (nobj_written > 0) {
8192 p_written = (nobj_written * 100) / nobj_total;
8193 if (p_written != a->last_p_written) {
8194 a->last_p_written = p_written;
8195 print_searching = 1;
8196 print_total = 1;
8197 print_deltify = 1;
8198 print_written = 1;
8203 if (bytes_sent > 0) {
8204 p_sent = (bytes_sent * 100) / packfile_size;
8205 if (p_sent != a->last_p_sent) {
8206 a->last_p_sent = p_sent;
8207 print_searching = 1;
8208 print_total = 1;
8209 print_deltify = 1;
8210 print_written = 1;
8211 print_sent = 1;
8213 a->sent_something = 1;
8216 if (print_searching || print_total || print_deltify || print_written ||
8217 print_sent)
8218 printf("\r");
8219 if (print_searching)
8220 printf("packing %d reference%s", ncommits,
8221 ncommits == 1 ? "" : "s");
8222 if (print_total)
8223 printf("; %d object%s", nobj_total,
8224 nobj_total == 1 ? "" : "s");
8225 if (print_deltify)
8226 printf("; deltify: %d%%", p_deltify);
8227 if (print_sent)
8228 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8229 scaled_packsize, p_sent);
8230 else if (print_written)
8231 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8232 scaled_packsize, p_written);
8233 if (print_searching || print_total || print_deltify ||
8234 print_written || print_sent) {
8235 a->printed_something = 1;
8236 fflush(stdout);
8238 return NULL;
8241 static const struct got_error *
8242 cmd_send(int argc, char *argv[])
8244 const struct got_error *error = NULL;
8245 char *cwd = NULL, *repo_path = NULL;
8246 const char *remote_name;
8247 char *proto = NULL, *host = NULL, *port = NULL;
8248 char *repo_name = NULL, *server_path = NULL;
8249 const struct got_remote_repo *remotes, *remote = NULL;
8250 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8251 struct got_repository *repo = NULL;
8252 struct got_worktree *worktree = NULL;
8253 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8254 struct got_pathlist_head branches;
8255 struct got_pathlist_head tags;
8256 struct got_reflist_head all_branches;
8257 struct got_reflist_head all_tags;
8258 struct got_pathlist_head delete_args;
8259 struct got_pathlist_head delete_branches;
8260 struct got_reflist_entry *re;
8261 struct got_pathlist_entry *pe;
8262 int i, ch, sendfd = -1, sendstatus;
8263 pid_t sendpid = -1;
8264 struct got_send_progress_arg spa;
8265 int verbosity = 0, overwrite_refs = 0;
8266 int send_all_branches = 0, send_all_tags = 0;
8267 struct got_reference *ref = NULL;
8269 TAILQ_INIT(&branches);
8270 TAILQ_INIT(&tags);
8271 TAILQ_INIT(&all_branches);
8272 TAILQ_INIT(&all_tags);
8273 TAILQ_INIT(&delete_args);
8274 TAILQ_INIT(&delete_branches);
8276 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8277 switch (ch) {
8278 case 'a':
8279 send_all_branches = 1;
8280 break;
8281 case 'b':
8282 error = got_pathlist_append(&branches, optarg, NULL);
8283 if (error)
8284 return error;
8285 nbranches++;
8286 break;
8287 case 'd':
8288 error = got_pathlist_append(&delete_args, optarg, NULL);
8289 if (error)
8290 return error;
8291 break;
8292 case 'f':
8293 overwrite_refs = 1;
8294 break;
8295 case 'r':
8296 repo_path = realpath(optarg, NULL);
8297 if (repo_path == NULL)
8298 return got_error_from_errno2("realpath",
8299 optarg);
8300 got_path_strip_trailing_slashes(repo_path);
8301 break;
8302 case 't':
8303 error = got_pathlist_append(&tags, optarg, NULL);
8304 if (error)
8305 return error;
8306 ntags++;
8307 break;
8308 case 'T':
8309 send_all_tags = 1;
8310 break;
8311 case 'v':
8312 if (verbosity < 0)
8313 verbosity = 0;
8314 else if (verbosity < 3)
8315 verbosity++;
8316 break;
8317 case 'q':
8318 verbosity = -1;
8319 break;
8320 default:
8321 usage_send();
8322 /* NOTREACHED */
8325 argc -= optind;
8326 argv += optind;
8328 if (send_all_branches && !TAILQ_EMPTY(&branches))
8329 option_conflict('a', 'b');
8330 if (send_all_tags && !TAILQ_EMPTY(&tags))
8331 option_conflict('T', 't');
8334 if (argc == 0)
8335 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8336 else if (argc == 1)
8337 remote_name = argv[0];
8338 else
8339 usage_send();
8341 cwd = getcwd(NULL, 0);
8342 if (cwd == NULL) {
8343 error = got_error_from_errno("getcwd");
8344 goto done;
8347 if (repo_path == NULL) {
8348 error = got_worktree_open(&worktree, cwd);
8349 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8350 goto done;
8351 else
8352 error = NULL;
8353 if (worktree) {
8354 repo_path =
8355 strdup(got_worktree_get_repo_path(worktree));
8356 if (repo_path == NULL)
8357 error = got_error_from_errno("strdup");
8358 if (error)
8359 goto done;
8360 } else {
8361 repo_path = strdup(cwd);
8362 if (repo_path == NULL) {
8363 error = got_error_from_errno("strdup");
8364 goto done;
8369 error = got_repo_open(&repo, repo_path, NULL);
8370 if (error)
8371 goto done;
8373 if (worktree) {
8374 worktree_conf = got_worktree_get_gotconfig(worktree);
8375 if (worktree_conf) {
8376 got_gotconfig_get_remotes(&nremotes, &remotes,
8377 worktree_conf);
8378 for (i = 0; i < nremotes; i++) {
8379 if (strcmp(remotes[i].name, remote_name) == 0) {
8380 remote = &remotes[i];
8381 break;
8386 if (remote == NULL) {
8387 repo_conf = got_repo_get_gotconfig(repo);
8388 if (repo_conf) {
8389 got_gotconfig_get_remotes(&nremotes, &remotes,
8390 repo_conf);
8391 for (i = 0; i < nremotes; i++) {
8392 if (strcmp(remotes[i].name, remote_name) == 0) {
8393 remote = &remotes[i];
8394 break;
8399 if (remote == NULL) {
8400 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
8401 for (i = 0; i < nremotes; i++) {
8402 if (strcmp(remotes[i].name, remote_name) == 0) {
8403 remote = &remotes[i];
8404 break;
8408 if (remote == NULL) {
8409 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
8410 goto done;
8413 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
8414 &repo_name, remote->send_url);
8415 if (error)
8416 goto done;
8418 if (strcmp(proto, "git") == 0) {
8419 #ifndef PROFILE
8420 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8421 "sendfd dns inet unveil", NULL) == -1)
8422 err(1, "pledge");
8423 #endif
8424 } else if (strcmp(proto, "git+ssh") == 0 ||
8425 strcmp(proto, "ssh") == 0) {
8426 #ifndef PROFILE
8427 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8428 "sendfd unveil", NULL) == -1)
8429 err(1, "pledge");
8430 #endif
8431 } else if (strcmp(proto, "http") == 0 ||
8432 strcmp(proto, "git+http") == 0) {
8433 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
8434 goto done;
8435 } else {
8436 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
8437 goto done;
8440 error = got_dial_apply_unveil(proto);
8441 if (error)
8442 goto done;
8444 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8445 if (error)
8446 goto done;
8448 if (send_all_branches) {
8449 error = got_ref_list(&all_branches, repo, "refs/heads",
8450 got_ref_cmp_by_name, NULL);
8451 if (error)
8452 goto done;
8453 TAILQ_FOREACH(re, &all_branches, entry) {
8454 const char *branchname = got_ref_get_name(re->ref);
8455 error = got_pathlist_append(&branches,
8456 branchname, NULL);
8457 if (error)
8458 goto done;
8459 nbranches++;
8461 } else if (nbranches == 0) {
8462 for (i = 0; i < remote->nsend_branches; i++) {
8463 got_pathlist_append(&branches,
8464 remote->send_branches[i], NULL);
8468 if (send_all_tags) {
8469 error = got_ref_list(&all_tags, repo, "refs/tags",
8470 got_ref_cmp_by_name, NULL);
8471 if (error)
8472 goto done;
8473 TAILQ_FOREACH(re, &all_tags, entry) {
8474 const char *tagname = got_ref_get_name(re->ref);
8475 error = got_pathlist_append(&tags,
8476 tagname, NULL);
8477 if (error)
8478 goto done;
8479 ntags++;
8484 * To prevent accidents only branches in refs/heads/ can be deleted
8485 * with 'got send -d'.
8486 * Deleting anything else requires local repository access or Git.
8488 TAILQ_FOREACH(pe, &delete_args, entry) {
8489 const char *branchname = pe->path;
8490 char *s;
8491 struct got_pathlist_entry *new;
8492 if (strncmp(branchname, "refs/heads/", 11) == 0) {
8493 s = strdup(branchname);
8494 if (s == NULL) {
8495 error = got_error_from_errno("strdup");
8496 goto done;
8498 } else {
8499 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
8500 error = got_error_from_errno("asprintf");
8501 goto done;
8504 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
8505 if (error || new == NULL /* duplicate */)
8506 free(s);
8507 if (error)
8508 goto done;
8509 ndelete_branches++;
8512 if (nbranches == 0 && ndelete_branches == 0) {
8513 struct got_reference *head_ref;
8514 if (worktree)
8515 error = got_ref_open(&head_ref, repo,
8516 got_worktree_get_head_ref_name(worktree), 0);
8517 else
8518 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
8519 if (error)
8520 goto done;
8521 if (got_ref_is_symbolic(head_ref)) {
8522 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
8523 got_ref_close(head_ref);
8524 if (error)
8525 goto done;
8526 } else
8527 ref = head_ref;
8528 error = got_pathlist_append(&branches, got_ref_get_name(ref),
8529 NULL);
8530 if (error)
8531 goto done;
8532 nbranches++;
8535 if (verbosity >= 0)
8536 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
8537 port ? ":" : "", port ? port : "");
8539 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
8540 server_path, verbosity);
8541 if (error)
8542 goto done;
8544 memset(&spa, 0, sizeof(spa));
8545 spa.last_scaled_packsize[0] = '\0';
8546 spa.last_p_deltify = -1;
8547 spa.last_p_written = -1;
8548 spa.verbosity = verbosity;
8549 spa.delete_branches = &delete_branches;
8550 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
8551 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
8552 check_cancelled, NULL);
8553 if (spa.printed_something)
8554 putchar('\n');
8555 if (error)
8556 goto done;
8557 if (!spa.sent_something && verbosity >= 0)
8558 printf("Already up-to-date\n");
8559 done:
8560 if (sendpid > 0) {
8561 if (kill(sendpid, SIGTERM) == -1)
8562 error = got_error_from_errno("kill");
8563 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
8564 error = got_error_from_errno("waitpid");
8566 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
8567 error = got_error_from_errno("close");
8568 if (repo) {
8569 const struct got_error *close_err = got_repo_close(repo);
8570 if (error == NULL)
8571 error = close_err;
8573 if (worktree)
8574 got_worktree_close(worktree);
8575 if (ref)
8576 got_ref_close(ref);
8577 got_pathlist_free(&branches);
8578 got_pathlist_free(&tags);
8579 got_ref_list_free(&all_branches);
8580 got_ref_list_free(&all_tags);
8581 got_pathlist_free(&delete_args);
8582 TAILQ_FOREACH(pe, &delete_branches, entry)
8583 free((char *)pe->path);
8584 got_pathlist_free(&delete_branches);
8585 free(cwd);
8586 free(repo_path);
8587 free(proto);
8588 free(host);
8589 free(port);
8590 free(server_path);
8591 free(repo_name);
8592 return error;
8595 __dead static void
8596 usage_cherrypick(void)
8598 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
8599 exit(1);
8602 static const struct got_error *
8603 cmd_cherrypick(int argc, char *argv[])
8605 const struct got_error *error = NULL;
8606 struct got_worktree *worktree = NULL;
8607 struct got_repository *repo = NULL;
8608 char *cwd = NULL, *commit_id_str = NULL;
8609 struct got_object_id *commit_id = NULL;
8610 struct got_commit_object *commit = NULL;
8611 struct got_object_qid *pid;
8612 int ch;
8613 struct got_update_progress_arg upa;
8615 while ((ch = getopt(argc, argv, "")) != -1) {
8616 switch (ch) {
8617 default:
8618 usage_cherrypick();
8619 /* NOTREACHED */
8623 argc -= optind;
8624 argv += optind;
8626 #ifndef PROFILE
8627 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8628 "unveil", NULL) == -1)
8629 err(1, "pledge");
8630 #endif
8631 if (argc != 1)
8632 usage_cherrypick();
8634 cwd = getcwd(NULL, 0);
8635 if (cwd == NULL) {
8636 error = got_error_from_errno("getcwd");
8637 goto done;
8639 error = got_worktree_open(&worktree, cwd);
8640 if (error) {
8641 if (error->code == GOT_ERR_NOT_WORKTREE)
8642 error = wrap_not_worktree_error(error, "cherrypick",
8643 cwd);
8644 goto done;
8647 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8648 NULL);
8649 if (error != NULL)
8650 goto done;
8652 error = apply_unveil(got_repo_get_path(repo), 0,
8653 got_worktree_get_root_path(worktree));
8654 if (error)
8655 goto done;
8657 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8658 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8659 if (error)
8660 goto done;
8661 error = got_object_id_str(&commit_id_str, commit_id);
8662 if (error)
8663 goto done;
8665 error = got_object_open_as_commit(&commit, repo, commit_id);
8666 if (error)
8667 goto done;
8668 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8669 memset(&upa, 0, sizeof(upa));
8670 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
8671 commit_id, repo, update_progress, &upa, check_cancelled,
8672 NULL);
8673 if (error != NULL)
8674 goto done;
8676 if (upa.did_something)
8677 printf("Merged commit %s\n", commit_id_str);
8678 print_merge_progress_stats(&upa);
8679 done:
8680 if (commit)
8681 got_object_commit_close(commit);
8682 free(commit_id_str);
8683 if (worktree)
8684 got_worktree_close(worktree);
8685 if (repo) {
8686 const struct got_error *close_err = got_repo_close(repo);
8687 if (error == NULL)
8688 error = close_err;
8690 return error;
8693 __dead static void
8694 usage_backout(void)
8696 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
8697 exit(1);
8700 static const struct got_error *
8701 cmd_backout(int argc, char *argv[])
8703 const struct got_error *error = NULL;
8704 struct got_worktree *worktree = NULL;
8705 struct got_repository *repo = NULL;
8706 char *cwd = NULL, *commit_id_str = NULL;
8707 struct got_object_id *commit_id = NULL;
8708 struct got_commit_object *commit = NULL;
8709 struct got_object_qid *pid;
8710 int ch;
8711 struct got_update_progress_arg upa;
8713 while ((ch = getopt(argc, argv, "")) != -1) {
8714 switch (ch) {
8715 default:
8716 usage_backout();
8717 /* NOTREACHED */
8721 argc -= optind;
8722 argv += optind;
8724 #ifndef PROFILE
8725 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8726 "unveil", NULL) == -1)
8727 err(1, "pledge");
8728 #endif
8729 if (argc != 1)
8730 usage_backout();
8732 cwd = getcwd(NULL, 0);
8733 if (cwd == NULL) {
8734 error = got_error_from_errno("getcwd");
8735 goto done;
8737 error = got_worktree_open(&worktree, cwd);
8738 if (error) {
8739 if (error->code == GOT_ERR_NOT_WORKTREE)
8740 error = wrap_not_worktree_error(error, "backout", cwd);
8741 goto done;
8744 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8745 NULL);
8746 if (error != NULL)
8747 goto done;
8749 error = apply_unveil(got_repo_get_path(repo), 0,
8750 got_worktree_get_root_path(worktree));
8751 if (error)
8752 goto done;
8754 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8755 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8756 if (error)
8757 goto done;
8758 error = got_object_id_str(&commit_id_str, commit_id);
8759 if (error)
8760 goto done;
8762 error = got_object_open_as_commit(&commit, repo, commit_id);
8763 if (error)
8764 goto done;
8765 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8766 if (pid == NULL) {
8767 error = got_error(GOT_ERR_ROOT_COMMIT);
8768 goto done;
8771 memset(&upa, 0, sizeof(upa));
8772 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
8773 repo, update_progress, &upa, check_cancelled, NULL);
8774 if (error != NULL)
8775 goto done;
8777 if (upa.did_something)
8778 printf("Backed out commit %s\n", commit_id_str);
8779 print_merge_progress_stats(&upa);
8780 done:
8781 if (commit)
8782 got_object_commit_close(commit);
8783 free(commit_id_str);
8784 if (worktree)
8785 got_worktree_close(worktree);
8786 if (repo) {
8787 const struct got_error *close_err = got_repo_close(repo);
8788 if (error == NULL)
8789 error = close_err;
8791 return error;
8794 __dead static void
8795 usage_rebase(void)
8797 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
8798 getprogname());
8799 exit(1);
8802 void
8803 trim_logmsg(char *logmsg, int limit)
8805 char *nl;
8806 size_t len;
8808 len = strlen(logmsg);
8809 if (len > limit)
8810 len = limit;
8811 logmsg[len] = '\0';
8812 nl = strchr(logmsg, '\n');
8813 if (nl)
8814 *nl = '\0';
8817 static const struct got_error *
8818 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
8820 const struct got_error *err;
8821 char *logmsg0 = NULL;
8822 const char *s;
8824 err = got_object_commit_get_logmsg(&logmsg0, commit);
8825 if (err)
8826 return err;
8828 s = logmsg0;
8829 while (isspace((unsigned char)s[0]))
8830 s++;
8832 *logmsg = strdup(s);
8833 if (*logmsg == NULL) {
8834 err = got_error_from_errno("strdup");
8835 goto done;
8838 trim_logmsg(*logmsg, limit);
8839 done:
8840 free(logmsg0);
8841 return err;
8844 static const struct got_error *
8845 show_rebase_merge_conflict(struct got_object_id *id,
8846 struct got_repository *repo)
8848 const struct got_error *err;
8849 struct got_commit_object *commit = NULL;
8850 char *id_str = NULL, *logmsg = NULL;
8852 err = got_object_open_as_commit(&commit, repo, id);
8853 if (err)
8854 return err;
8856 err = got_object_id_str(&id_str, id);
8857 if (err)
8858 goto done;
8860 id_str[12] = '\0';
8862 err = get_short_logmsg(&logmsg, 42, commit);
8863 if (err)
8864 goto done;
8866 printf("%s -> merge conflict: %s\n", id_str, logmsg);
8867 done:
8868 free(id_str);
8869 got_object_commit_close(commit);
8870 free(logmsg);
8871 return err;
8874 static const struct got_error *
8875 show_rebase_progress(struct got_commit_object *commit,
8876 struct got_object_id *old_id, struct got_object_id *new_id)
8878 const struct got_error *err;
8879 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8881 err = got_object_id_str(&old_id_str, old_id);
8882 if (err)
8883 goto done;
8885 if (new_id) {
8886 err = got_object_id_str(&new_id_str, new_id);
8887 if (err)
8888 goto done;
8891 old_id_str[12] = '\0';
8892 if (new_id_str)
8893 new_id_str[12] = '\0';
8895 err = get_short_logmsg(&logmsg, 42, commit);
8896 if (err)
8897 goto done;
8899 printf("%s -> %s: %s\n", old_id_str,
8900 new_id_str ? new_id_str : "no-op change", logmsg);
8901 done:
8902 free(old_id_str);
8903 free(new_id_str);
8904 free(logmsg);
8905 return err;
8908 static const struct got_error *
8909 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
8910 struct got_reference *branch, struct got_reference *new_base_branch,
8911 struct got_reference *tmp_branch, struct got_repository *repo,
8912 int create_backup)
8914 printf("Switching work tree to %s\n", got_ref_get_name(branch));
8915 return got_worktree_rebase_complete(worktree, fileindex,
8916 new_base_branch, tmp_branch, branch, repo, create_backup);
8919 static const struct got_error *
8920 rebase_commit(struct got_pathlist_head *merged_paths,
8921 struct got_worktree *worktree, struct got_fileindex *fileindex,
8922 struct got_reference *tmp_branch,
8923 struct got_object_id *commit_id, struct got_repository *repo)
8925 const struct got_error *error;
8926 struct got_commit_object *commit;
8927 struct got_object_id *new_commit_id;
8929 error = got_object_open_as_commit(&commit, repo, commit_id);
8930 if (error)
8931 return error;
8933 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
8934 worktree, fileindex, tmp_branch, commit, commit_id, repo);
8935 if (error) {
8936 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
8937 goto done;
8938 error = show_rebase_progress(commit, commit_id, NULL);
8939 } else {
8940 error = show_rebase_progress(commit, commit_id, new_commit_id);
8941 free(new_commit_id);
8943 done:
8944 got_object_commit_close(commit);
8945 return error;
8948 struct check_path_prefix_arg {
8949 const char *path_prefix;
8950 size_t len;
8951 int errcode;
8954 static const struct got_error *
8955 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
8956 struct got_blob_object *blob2, FILE *f1, FILE *f2,
8957 struct got_object_id *id1, struct got_object_id *id2,
8958 const char *path1, const char *path2,
8959 mode_t mode1, mode_t mode2, struct got_repository *repo)
8961 struct check_path_prefix_arg *a = arg;
8963 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
8964 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
8965 return got_error(a->errcode);
8967 return NULL;
8970 static const struct got_error *
8971 check_path_prefix(struct got_object_id *parent_id,
8972 struct got_object_id *commit_id, const char *path_prefix,
8973 int errcode, struct got_repository *repo)
8975 const struct got_error *err;
8976 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
8977 struct got_commit_object *commit = NULL, *parent_commit = NULL;
8978 struct check_path_prefix_arg cpp_arg;
8980 if (got_path_is_root_dir(path_prefix))
8981 return NULL;
8983 err = got_object_open_as_commit(&commit, repo, commit_id);
8984 if (err)
8985 goto done;
8987 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
8988 if (err)
8989 goto done;
8991 err = got_object_open_as_tree(&tree1, repo,
8992 got_object_commit_get_tree_id(parent_commit));
8993 if (err)
8994 goto done;
8996 err = got_object_open_as_tree(&tree2, repo,
8997 got_object_commit_get_tree_id(commit));
8998 if (err)
8999 goto done;
9001 cpp_arg.path_prefix = path_prefix;
9002 while (cpp_arg.path_prefix[0] == '/')
9003 cpp_arg.path_prefix++;
9004 cpp_arg.len = strlen(cpp_arg.path_prefix);
9005 cpp_arg.errcode = errcode;
9006 err = got_diff_tree(tree1, tree2, NULL, NULL, "", "", repo,
9007 check_path_prefix_in_diff, &cpp_arg, 0);
9008 done:
9009 if (tree1)
9010 got_object_tree_close(tree1);
9011 if (tree2)
9012 got_object_tree_close(tree2);
9013 if (commit)
9014 got_object_commit_close(commit);
9015 if (parent_commit)
9016 got_object_commit_close(parent_commit);
9017 return err;
9020 static const struct got_error *
9021 collect_commits(struct got_object_id_queue *commits,
9022 struct got_object_id *initial_commit_id,
9023 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9024 const char *path_prefix, int path_prefix_errcode,
9025 struct got_repository *repo)
9027 const struct got_error *err = NULL;
9028 struct got_commit_graph *graph = NULL;
9029 struct got_object_id *parent_id = NULL;
9030 struct got_object_qid *qid;
9031 struct got_object_id *commit_id = initial_commit_id;
9033 err = got_commit_graph_open(&graph, "/", 1);
9034 if (err)
9035 return err;
9037 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9038 check_cancelled, NULL);
9039 if (err)
9040 goto done;
9041 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
9042 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9043 check_cancelled, NULL);
9044 if (err) {
9045 if (err->code == GOT_ERR_ITER_COMPLETED) {
9046 err = got_error_msg(GOT_ERR_ANCESTRY,
9047 "ran out of commits to rebase before "
9048 "youngest common ancestor commit has "
9049 "been reached?!?");
9051 goto done;
9052 } else {
9053 err = check_path_prefix(parent_id, commit_id,
9054 path_prefix, path_prefix_errcode, repo);
9055 if (err)
9056 goto done;
9058 err = got_object_qid_alloc(&qid, commit_id);
9059 if (err)
9060 goto done;
9061 STAILQ_INSERT_HEAD(commits, qid, entry);
9062 commit_id = parent_id;
9065 done:
9066 got_commit_graph_close(graph);
9067 return err;
9070 static const struct got_error *
9071 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9073 const struct got_error *err = NULL;
9074 time_t committer_time;
9075 struct tm tm;
9076 char datebuf[11]; /* YYYY-MM-DD + NUL */
9077 char *author0 = NULL, *author, *smallerthan;
9078 char *logmsg0 = NULL, *logmsg, *newline;
9080 committer_time = got_object_commit_get_committer_time(commit);
9081 if (gmtime_r(&committer_time, &tm) == NULL)
9082 return got_error_from_errno("gmtime_r");
9083 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9084 return got_error(GOT_ERR_NO_SPACE);
9086 author0 = strdup(got_object_commit_get_author(commit));
9087 if (author0 == NULL)
9088 return got_error_from_errno("strdup");
9089 author = author0;
9090 smallerthan = strchr(author, '<');
9091 if (smallerthan && smallerthan[1] != '\0')
9092 author = smallerthan + 1;
9093 author[strcspn(author, "@>")] = '\0';
9095 err = got_object_commit_get_logmsg(&logmsg0, commit);
9096 if (err)
9097 goto done;
9098 logmsg = logmsg0;
9099 while (*logmsg == '\n')
9100 logmsg++;
9101 newline = strchr(logmsg, '\n');
9102 if (newline)
9103 *newline = '\0';
9105 if (asprintf(brief_str, "%s %s %s",
9106 datebuf, author, logmsg) == -1)
9107 err = got_error_from_errno("asprintf");
9108 done:
9109 free(author0);
9110 free(logmsg0);
9111 return err;
9114 static const struct got_error *
9115 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9116 struct got_repository *repo)
9118 const struct got_error *err;
9119 char *id_str;
9121 err = got_object_id_str(&id_str, id);
9122 if (err)
9123 return err;
9125 err = got_ref_delete(ref, repo);
9126 if (err)
9127 goto done;
9129 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9130 done:
9131 free(id_str);
9132 return err;
9135 static const struct got_error *
9136 print_backup_ref(const char *branch_name, const char *new_id_str,
9137 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9138 struct got_reflist_object_id_map *refs_idmap,
9139 struct got_repository *repo)
9141 const struct got_error *err = NULL;
9142 struct got_reflist_head *refs;
9143 char *refs_str = NULL;
9144 struct got_object_id *new_commit_id = NULL;
9145 struct got_commit_object *new_commit = NULL;
9146 char *new_commit_brief_str = NULL;
9147 struct got_object_id *yca_id = NULL;
9148 struct got_commit_object *yca_commit = NULL;
9149 char *yca_id_str = NULL, *yca_brief_str = NULL;
9150 char *custom_refs_str;
9152 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9153 return got_error_from_errno("asprintf");
9155 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9156 0, 0, refs_idmap, custom_refs_str);
9157 if (err)
9158 goto done;
9160 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9161 if (err)
9162 goto done;
9164 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9165 if (refs) {
9166 err = build_refs_str(&refs_str, refs, new_commit_id, repo);
9167 if (err)
9168 goto done;
9171 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9172 if (err)
9173 goto done;
9175 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9176 if (err)
9177 goto done;
9179 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9180 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9181 if (err)
9182 goto done;
9184 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9185 refs_str ? " (" : "", refs_str ? refs_str : "",
9186 refs_str ? ")" : "", new_commit_brief_str);
9187 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9188 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9189 free(refs_str);
9190 refs_str = NULL;
9192 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9193 if (err)
9194 goto done;
9196 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9197 if (err)
9198 goto done;
9200 err = got_object_id_str(&yca_id_str, yca_id);
9201 if (err)
9202 goto done;
9204 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9205 if (refs) {
9206 err = build_refs_str(&refs_str, refs, yca_id, repo);
9207 if (err)
9208 goto done;
9210 printf("history forked at %s%s%s%s\n %s\n",
9211 yca_id_str,
9212 refs_str ? " (" : "", refs_str ? refs_str : "",
9213 refs_str ? ")" : "", yca_brief_str);
9215 done:
9216 free(custom_refs_str);
9217 free(new_commit_id);
9218 free(refs_str);
9219 free(yca_id);
9220 free(yca_id_str);
9221 free(yca_brief_str);
9222 if (new_commit)
9223 got_object_commit_close(new_commit);
9224 if (yca_commit)
9225 got_object_commit_close(yca_commit);
9227 return NULL;
9230 static const struct got_error *
9231 process_backup_refs(const char *backup_ref_prefix,
9232 const char *wanted_branch_name,
9233 int delete, struct got_repository *repo)
9235 const struct got_error *err;
9236 struct got_reflist_head refs, backup_refs;
9237 struct got_reflist_entry *re;
9238 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9239 struct got_object_id *old_commit_id = NULL;
9240 char *branch_name = NULL;
9241 struct got_commit_object *old_commit = NULL;
9242 struct got_reflist_object_id_map *refs_idmap = NULL;
9243 int wanted_branch_found = 0;
9245 TAILQ_INIT(&refs);
9246 TAILQ_INIT(&backup_refs);
9248 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9249 if (err)
9250 return err;
9252 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9253 if (err)
9254 goto done;
9256 if (wanted_branch_name) {
9257 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9258 wanted_branch_name += 11;
9261 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9262 got_ref_cmp_by_commit_timestamp_descending, repo);
9263 if (err)
9264 goto done;
9266 TAILQ_FOREACH(re, &backup_refs, entry) {
9267 const char *refname = got_ref_get_name(re->ref);
9268 char *slash;
9270 err = check_cancelled(NULL);
9271 if (err)
9272 break;
9274 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9275 if (err)
9276 break;
9278 err = got_object_open_as_commit(&old_commit, repo,
9279 old_commit_id);
9280 if (err)
9281 break;
9283 if (strncmp(backup_ref_prefix, refname,
9284 backup_ref_prefix_len) == 0)
9285 refname += backup_ref_prefix_len;
9287 while (refname[0] == '/')
9288 refname++;
9290 branch_name = strdup(refname);
9291 if (branch_name == NULL) {
9292 err = got_error_from_errno("strdup");
9293 break;
9295 slash = strrchr(branch_name, '/');
9296 if (slash) {
9297 *slash = '\0';
9298 refname += strlen(branch_name) + 1;
9301 if (wanted_branch_name == NULL ||
9302 strcmp(wanted_branch_name, branch_name) == 0) {
9303 wanted_branch_found = 1;
9304 if (delete) {
9305 err = delete_backup_ref(re->ref,
9306 old_commit_id, repo);
9307 } else {
9308 err = print_backup_ref(branch_name, refname,
9309 old_commit_id, old_commit, refs_idmap,
9310 repo);
9312 if (err)
9313 break;
9316 free(old_commit_id);
9317 old_commit_id = NULL;
9318 free(branch_name);
9319 branch_name = NULL;
9320 got_object_commit_close(old_commit);
9321 old_commit = NULL;
9324 if (wanted_branch_name && !wanted_branch_found) {
9325 err = got_error_fmt(GOT_ERR_NOT_REF,
9326 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9328 done:
9329 if (refs_idmap)
9330 got_reflist_object_id_map_free(refs_idmap);
9331 got_ref_list_free(&refs);
9332 got_ref_list_free(&backup_refs);
9333 free(old_commit_id);
9334 free(branch_name);
9335 if (old_commit)
9336 got_object_commit_close(old_commit);
9337 return err;
9340 static const struct got_error *
9341 abort_progress(void *arg, unsigned char status, const char *path)
9344 * Unversioned files should not clutter progress output when
9345 * an operation is aborted.
9347 if (status == GOT_STATUS_UNVERSIONED)
9348 return NULL;
9350 return update_progress(arg, status, path);
9353 static const struct got_error *
9354 cmd_rebase(int argc, char *argv[])
9356 const struct got_error *error = NULL;
9357 struct got_worktree *worktree = NULL;
9358 struct got_repository *repo = NULL;
9359 struct got_fileindex *fileindex = NULL;
9360 char *cwd = NULL;
9361 struct got_reference *branch = NULL;
9362 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
9363 struct got_object_id *commit_id = NULL, *parent_id = NULL;
9364 struct got_object_id *resume_commit_id = NULL;
9365 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
9366 struct got_commit_object *commit = NULL;
9367 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
9368 int histedit_in_progress = 0, merge_in_progress = 0;
9369 int create_backup = 1, list_backups = 0, delete_backups = 0;
9370 struct got_object_id_queue commits;
9371 struct got_pathlist_head merged_paths;
9372 const struct got_object_id_queue *parent_ids;
9373 struct got_object_qid *qid, *pid;
9374 struct got_update_progress_arg upa;
9376 STAILQ_INIT(&commits);
9377 TAILQ_INIT(&merged_paths);
9378 memset(&upa, 0, sizeof(upa));
9380 while ((ch = getopt(argc, argv, "aclX")) != -1) {
9381 switch (ch) {
9382 case 'a':
9383 abort_rebase = 1;
9384 break;
9385 case 'c':
9386 continue_rebase = 1;
9387 break;
9388 case 'l':
9389 list_backups = 1;
9390 break;
9391 case 'X':
9392 delete_backups = 1;
9393 break;
9394 default:
9395 usage_rebase();
9396 /* NOTREACHED */
9400 argc -= optind;
9401 argv += optind;
9403 #ifndef PROFILE
9404 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9405 "unveil", NULL) == -1)
9406 err(1, "pledge");
9407 #endif
9408 if (list_backups) {
9409 if (abort_rebase)
9410 option_conflict('l', 'a');
9411 if (continue_rebase)
9412 option_conflict('l', 'c');
9413 if (delete_backups)
9414 option_conflict('l', 'X');
9415 if (argc != 0 && argc != 1)
9416 usage_rebase();
9417 } else if (delete_backups) {
9418 if (abort_rebase)
9419 option_conflict('X', 'a');
9420 if (continue_rebase)
9421 option_conflict('X', 'c');
9422 if (list_backups)
9423 option_conflict('l', 'X');
9424 if (argc != 0 && argc != 1)
9425 usage_rebase();
9426 } else {
9427 if (abort_rebase && continue_rebase)
9428 usage_rebase();
9429 else if (abort_rebase || continue_rebase) {
9430 if (argc != 0)
9431 usage_rebase();
9432 } else if (argc != 1)
9433 usage_rebase();
9436 cwd = getcwd(NULL, 0);
9437 if (cwd == NULL) {
9438 error = got_error_from_errno("getcwd");
9439 goto done;
9441 error = got_worktree_open(&worktree, cwd);
9442 if (error) {
9443 if (list_backups || delete_backups) {
9444 if (error->code != GOT_ERR_NOT_WORKTREE)
9445 goto done;
9446 } else {
9447 if (error->code == GOT_ERR_NOT_WORKTREE)
9448 error = wrap_not_worktree_error(error,
9449 "rebase", cwd);
9450 goto done;
9454 error = got_repo_open(&repo,
9455 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
9456 if (error != NULL)
9457 goto done;
9459 error = apply_unveil(got_repo_get_path(repo), 0,
9460 worktree ? got_worktree_get_root_path(worktree) : NULL);
9461 if (error)
9462 goto done;
9464 if (list_backups || delete_backups) {
9465 error = process_backup_refs(
9466 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
9467 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9468 goto done; /* nothing else to do */
9471 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9472 worktree);
9473 if (error)
9474 goto done;
9475 if (histedit_in_progress) {
9476 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9477 goto done;
9480 error = got_worktree_merge_in_progress(&merge_in_progress,
9481 worktree, repo);
9482 if (error)
9483 goto done;
9484 if (merge_in_progress) {
9485 error = got_error(GOT_ERR_MERGE_BUSY);
9486 goto done;
9489 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9490 if (error)
9491 goto done;
9493 if (abort_rebase) {
9494 if (!rebase_in_progress) {
9495 error = got_error(GOT_ERR_NOT_REBASING);
9496 goto done;
9498 error = got_worktree_rebase_continue(&resume_commit_id,
9499 &new_base_branch, &tmp_branch, &branch, &fileindex,
9500 worktree, repo);
9501 if (error)
9502 goto done;
9503 printf("Switching work tree to %s\n",
9504 got_ref_get_symref_target(new_base_branch));
9505 error = got_worktree_rebase_abort(worktree, fileindex, repo,
9506 new_base_branch, abort_progress, &upa);
9507 if (error)
9508 goto done;
9509 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
9510 print_merge_progress_stats(&upa);
9511 goto done; /* nothing else to do */
9514 if (continue_rebase) {
9515 if (!rebase_in_progress) {
9516 error = got_error(GOT_ERR_NOT_REBASING);
9517 goto done;
9519 error = got_worktree_rebase_continue(&resume_commit_id,
9520 &new_base_branch, &tmp_branch, &branch, &fileindex,
9521 worktree, repo);
9522 if (error)
9523 goto done;
9525 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
9526 resume_commit_id, repo);
9527 if (error)
9528 goto done;
9530 yca_id = got_object_id_dup(resume_commit_id);
9531 if (yca_id == NULL) {
9532 error = got_error_from_errno("got_object_id_dup");
9533 goto done;
9535 } else {
9536 error = got_ref_open(&branch, repo, argv[0], 0);
9537 if (error != NULL)
9538 goto done;
9541 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
9542 if (error)
9543 goto done;
9545 if (!continue_rebase) {
9546 struct got_object_id *base_commit_id;
9548 base_commit_id = got_worktree_get_base_commit_id(worktree);
9549 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9550 base_commit_id, branch_head_commit_id, 1, repo,
9551 check_cancelled, NULL);
9552 if (error)
9553 goto done;
9554 if (yca_id == NULL) {
9555 error = got_error_msg(GOT_ERR_ANCESTRY,
9556 "specified branch shares no common ancestry "
9557 "with work tree's branch");
9558 goto done;
9561 error = check_same_branch(base_commit_id, branch, yca_id, repo);
9562 if (error) {
9563 if (error->code != GOT_ERR_ANCESTRY)
9564 goto done;
9565 error = NULL;
9566 } else {
9567 struct got_pathlist_head paths;
9568 printf("%s is already based on %s\n",
9569 got_ref_get_name(branch),
9570 got_worktree_get_head_ref_name(worktree));
9571 error = switch_head_ref(branch, branch_head_commit_id,
9572 worktree, repo);
9573 if (error)
9574 goto done;
9575 error = got_worktree_set_base_commit_id(worktree, repo,
9576 branch_head_commit_id);
9577 if (error)
9578 goto done;
9579 TAILQ_INIT(&paths);
9580 error = got_pathlist_append(&paths, "", NULL);
9581 if (error)
9582 goto done;
9583 error = got_worktree_checkout_files(worktree,
9584 &paths, repo, update_progress, &upa,
9585 check_cancelled, NULL);
9586 got_pathlist_free(&paths);
9587 if (error)
9588 goto done;
9589 if (upa.did_something) {
9590 char *id_str;
9591 error = got_object_id_str(&id_str,
9592 branch_head_commit_id);
9593 if (error)
9594 goto done;
9595 printf("Updated to %s: %s\n",
9596 got_worktree_get_head_ref_name(worktree),
9597 id_str);
9598 free(id_str);
9599 } else
9600 printf("Already up-to-date\n");
9601 print_update_progress_stats(&upa);
9602 goto done;
9606 commit_id = branch_head_commit_id;
9607 error = got_object_open_as_commit(&commit, repo, commit_id);
9608 if (error)
9609 goto done;
9611 parent_ids = got_object_commit_get_parent_ids(commit);
9612 pid = STAILQ_FIRST(parent_ids);
9613 if (pid == NULL) {
9614 error = got_error(GOT_ERR_EMPTY_REBASE);
9615 goto done;
9617 error = collect_commits(&commits, commit_id, &pid->id,
9618 yca_id, got_worktree_get_path_prefix(worktree),
9619 GOT_ERR_REBASE_PATH, repo);
9620 got_object_commit_close(commit);
9621 commit = NULL;
9622 if (error)
9623 goto done;
9625 if (!continue_rebase) {
9626 error = got_worktree_rebase_prepare(&new_base_branch,
9627 &tmp_branch, &fileindex, worktree, branch, repo);
9628 if (error)
9629 goto done;
9632 if (STAILQ_EMPTY(&commits)) {
9633 if (continue_rebase) {
9634 error = rebase_complete(worktree, fileindex,
9635 branch, new_base_branch, tmp_branch, repo,
9636 create_backup);
9637 goto done;
9638 } else {
9639 /* Fast-forward the reference of the branch. */
9640 struct got_object_id *new_head_commit_id;
9641 char *id_str;
9642 error = got_ref_resolve(&new_head_commit_id, repo,
9643 new_base_branch);
9644 if (error)
9645 goto done;
9646 error = got_object_id_str(&id_str, new_head_commit_id);
9647 printf("Forwarding %s to commit %s\n",
9648 got_ref_get_name(branch), id_str);
9649 free(id_str);
9650 error = got_ref_change_ref(branch,
9651 new_head_commit_id);
9652 if (error)
9653 goto done;
9654 /* No backup needed since objects did not change. */
9655 create_backup = 0;
9659 pid = NULL;
9660 STAILQ_FOREACH(qid, &commits, entry) {
9662 commit_id = &qid->id;
9663 parent_id = pid ? &pid->id : yca_id;
9664 pid = qid;
9666 memset(&upa, 0, sizeof(upa));
9667 error = got_worktree_rebase_merge_files(&merged_paths,
9668 worktree, fileindex, parent_id, commit_id, repo,
9669 update_progress, &upa, check_cancelled, NULL);
9670 if (error)
9671 goto done;
9673 print_merge_progress_stats(&upa);
9674 if (upa.conflicts > 0 || upa.missing > 0 ||
9675 upa.not_deleted > 0 || upa.unversioned > 0) {
9676 if (upa.conflicts > 0) {
9677 error = show_rebase_merge_conflict(&qid->id,
9678 repo);
9679 if (error)
9680 goto done;
9682 got_worktree_rebase_pathlist_free(&merged_paths);
9683 break;
9686 error = rebase_commit(&merged_paths, worktree, fileindex,
9687 tmp_branch, commit_id, repo);
9688 got_worktree_rebase_pathlist_free(&merged_paths);
9689 if (error)
9690 goto done;
9693 if (upa.conflicts > 0 || upa.missing > 0 ||
9694 upa.not_deleted > 0 || upa.unversioned > 0) {
9695 error = got_worktree_rebase_postpone(worktree, fileindex);
9696 if (error)
9697 goto done;
9698 if (upa.conflicts > 0 && upa.missing == 0 &&
9699 upa.not_deleted == 0 && upa.unversioned == 0) {
9700 error = got_error_msg(GOT_ERR_CONFLICTS,
9701 "conflicts must be resolved before rebasing "
9702 "can continue");
9703 } else if (upa.conflicts > 0) {
9704 error = got_error_msg(GOT_ERR_CONFLICTS,
9705 "conflicts must be resolved before rebasing "
9706 "can continue; changes destined for some "
9707 "files were not yet merged and should be "
9708 "merged manually if required before the "
9709 "rebase operation is continued");
9710 } else {
9711 error = got_error_msg(GOT_ERR_CONFLICTS,
9712 "changes destined for some files were not "
9713 "yet merged and should be merged manually "
9714 "if required before the rebase operation "
9715 "is continued");
9717 } else
9718 error = rebase_complete(worktree, fileindex, branch,
9719 new_base_branch, tmp_branch, repo, create_backup);
9720 done:
9721 got_object_id_queue_free(&commits);
9722 free(branch_head_commit_id);
9723 free(resume_commit_id);
9724 free(yca_id);
9725 if (commit)
9726 got_object_commit_close(commit);
9727 if (branch)
9728 got_ref_close(branch);
9729 if (new_base_branch)
9730 got_ref_close(new_base_branch);
9731 if (tmp_branch)
9732 got_ref_close(tmp_branch);
9733 if (worktree)
9734 got_worktree_close(worktree);
9735 if (repo) {
9736 const struct got_error *close_err = got_repo_close(repo);
9737 if (error == NULL)
9738 error = close_err;
9740 return error;
9743 __dead static void
9744 usage_histedit(void)
9746 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
9747 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
9748 getprogname());
9749 exit(1);
9752 #define GOT_HISTEDIT_PICK 'p'
9753 #define GOT_HISTEDIT_EDIT 'e'
9754 #define GOT_HISTEDIT_FOLD 'f'
9755 #define GOT_HISTEDIT_DROP 'd'
9756 #define GOT_HISTEDIT_MESG 'm'
9758 static const struct got_histedit_cmd {
9759 unsigned char code;
9760 const char *name;
9761 const char *desc;
9762 } got_histedit_cmds[] = {
9763 { GOT_HISTEDIT_PICK, "pick", "use commit" },
9764 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
9765 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
9766 "be used" },
9767 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
9768 { GOT_HISTEDIT_MESG, "mesg",
9769 "single-line log message for commit above (open editor if empty)" },
9772 struct got_histedit_list_entry {
9773 TAILQ_ENTRY(got_histedit_list_entry) entry;
9774 struct got_object_id *commit_id;
9775 const struct got_histedit_cmd *cmd;
9776 char *logmsg;
9778 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
9780 static const struct got_error *
9781 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
9782 FILE *f, struct got_repository *repo)
9784 const struct got_error *err = NULL;
9785 char *logmsg = NULL, *id_str = NULL;
9786 struct got_commit_object *commit = NULL;
9787 int n;
9789 err = got_object_open_as_commit(&commit, repo, commit_id);
9790 if (err)
9791 goto done;
9793 err = get_short_logmsg(&logmsg, 34, commit);
9794 if (err)
9795 goto done;
9797 err = got_object_id_str(&id_str, commit_id);
9798 if (err)
9799 goto done;
9801 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
9802 if (n < 0)
9803 err = got_ferror(f, GOT_ERR_IO);
9804 done:
9805 if (commit)
9806 got_object_commit_close(commit);
9807 free(id_str);
9808 free(logmsg);
9809 return err;
9812 static const struct got_error *
9813 histedit_write_commit_list(struct got_object_id_queue *commits,
9814 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
9815 struct got_repository *repo)
9817 const struct got_error *err = NULL;
9818 struct got_object_qid *qid;
9819 const char *histedit_cmd = NULL;
9821 if (STAILQ_EMPTY(commits))
9822 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9824 STAILQ_FOREACH(qid, commits, entry) {
9825 histedit_cmd = got_histedit_cmds[0].name;
9826 if (edit_only)
9827 histedit_cmd = "edit";
9828 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
9829 histedit_cmd = "fold";
9830 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
9831 if (err)
9832 break;
9833 if (edit_logmsg_only) {
9834 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
9835 if (n < 0) {
9836 err = got_ferror(f, GOT_ERR_IO);
9837 break;
9842 return err;
9845 static const struct got_error *
9846 write_cmd_list(FILE *f, const char *branch_name,
9847 struct got_object_id_queue *commits)
9849 const struct got_error *err = NULL;
9850 size_t i;
9851 int n;
9852 char *id_str;
9853 struct got_object_qid *qid;
9855 qid = STAILQ_FIRST(commits);
9856 err = got_object_id_str(&id_str, &qid->id);
9857 if (err)
9858 return err;
9860 n = fprintf(f,
9861 "# Editing the history of branch '%s' starting at\n"
9862 "# commit %s\n"
9863 "# Commits will be processed in order from top to "
9864 "bottom of this file.\n", branch_name, id_str);
9865 if (n < 0) {
9866 err = got_ferror(f, GOT_ERR_IO);
9867 goto done;
9870 n = fprintf(f, "# Available histedit commands:\n");
9871 if (n < 0) {
9872 err = got_ferror(f, GOT_ERR_IO);
9873 goto done;
9876 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9877 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
9878 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
9879 cmd->desc);
9880 if (n < 0) {
9881 err = got_ferror(f, GOT_ERR_IO);
9882 break;
9885 done:
9886 free(id_str);
9887 return err;
9890 static const struct got_error *
9891 histedit_syntax_error(int lineno)
9893 static char msg[42];
9894 int ret;
9896 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
9897 lineno);
9898 if (ret == -1 || ret >= sizeof(msg))
9899 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
9901 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
9904 static const struct got_error *
9905 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
9906 char *logmsg, struct got_repository *repo)
9908 const struct got_error *err;
9909 struct got_commit_object *folded_commit = NULL;
9910 char *id_str, *folded_logmsg = NULL;
9912 err = got_object_id_str(&id_str, hle->commit_id);
9913 if (err)
9914 return err;
9916 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
9917 if (err)
9918 goto done;
9920 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
9921 if (err)
9922 goto done;
9923 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
9924 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
9925 folded_logmsg) == -1) {
9926 err = got_error_from_errno("asprintf");
9928 done:
9929 if (folded_commit)
9930 got_object_commit_close(folded_commit);
9931 free(id_str);
9932 free(folded_logmsg);
9933 return err;
9936 static struct got_histedit_list_entry *
9937 get_folded_commits(struct got_histedit_list_entry *hle)
9939 struct got_histedit_list_entry *prev, *folded = NULL;
9941 prev = TAILQ_PREV(hle, got_histedit_list, entry);
9942 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
9943 prev->cmd->code == GOT_HISTEDIT_DROP)) {
9944 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
9945 folded = prev;
9946 prev = TAILQ_PREV(prev, got_histedit_list, entry);
9949 return folded;
9952 static const struct got_error *
9953 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
9954 struct got_repository *repo)
9956 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
9957 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
9958 const struct got_error *err = NULL;
9959 struct got_commit_object *commit = NULL;
9960 int logmsg_len;
9961 int fd;
9962 struct got_histedit_list_entry *folded = NULL;
9964 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9965 if (err)
9966 return err;
9968 folded = get_folded_commits(hle);
9969 if (folded) {
9970 while (folded != hle) {
9971 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
9972 folded = TAILQ_NEXT(folded, entry);
9973 continue;
9975 err = append_folded_commit_msg(&new_msg, folded,
9976 logmsg, repo);
9977 if (err)
9978 goto done;
9979 free(logmsg);
9980 logmsg = new_msg;
9981 folded = TAILQ_NEXT(folded, entry);
9985 err = got_object_id_str(&id_str, hle->commit_id);
9986 if (err)
9987 goto done;
9988 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
9989 if (err)
9990 goto done;
9991 logmsg_len = asprintf(&new_msg,
9992 "%s\n# original log message of commit %s: %s",
9993 logmsg ? logmsg : "", id_str, orig_logmsg);
9994 if (logmsg_len == -1) {
9995 err = got_error_from_errno("asprintf");
9996 goto done;
9998 free(logmsg);
9999 logmsg = new_msg;
10001 err = got_object_id_str(&id_str, hle->commit_id);
10002 if (err)
10003 goto done;
10005 err = got_opentemp_named_fd(&logmsg_path, &fd,
10006 GOT_TMPDIR_STR "/got-logmsg");
10007 if (err)
10008 goto done;
10010 write(fd, logmsg, logmsg_len);
10011 close(fd);
10013 err = get_editor(&editor);
10014 if (err)
10015 goto done;
10017 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10018 logmsg_len, 0);
10019 if (err) {
10020 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10021 goto done;
10022 err = NULL;
10023 hle->logmsg = strdup(new_msg);
10024 if (hle->logmsg == NULL)
10025 err = got_error_from_errno("strdup");
10027 done:
10028 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10029 err = got_error_from_errno2("unlink", logmsg_path);
10030 free(logmsg_path);
10031 free(logmsg);
10032 free(orig_logmsg);
10033 free(editor);
10034 if (commit)
10035 got_object_commit_close(commit);
10036 return err;
10039 static const struct got_error *
10040 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10041 FILE *f, struct got_repository *repo)
10043 const struct got_error *err = NULL;
10044 char *line = NULL, *p, *end;
10045 size_t i, size;
10046 ssize_t len;
10047 int lineno = 0;
10048 const struct got_histedit_cmd *cmd;
10049 struct got_object_id *commit_id = NULL;
10050 struct got_histedit_list_entry *hle = NULL;
10052 for (;;) {
10053 len = getline(&line, &size, f);
10054 if (len == -1) {
10055 const struct got_error *getline_err;
10056 if (feof(f))
10057 break;
10058 getline_err = got_error_from_errno("getline");
10059 err = got_ferror(f, getline_err->code);
10060 break;
10062 lineno++;
10063 p = line;
10064 while (isspace((unsigned char)p[0]))
10065 p++;
10066 if (p[0] == '#' || p[0] == '\0') {
10067 free(line);
10068 line = NULL;
10069 continue;
10071 cmd = NULL;
10072 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10073 cmd = &got_histedit_cmds[i];
10074 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10075 isspace((unsigned char)p[strlen(cmd->name)])) {
10076 p += strlen(cmd->name);
10077 break;
10079 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10080 p++;
10081 break;
10084 if (i == nitems(got_histedit_cmds)) {
10085 err = histedit_syntax_error(lineno);
10086 break;
10088 while (isspace((unsigned char)p[0]))
10089 p++;
10090 if (cmd->code == GOT_HISTEDIT_MESG) {
10091 if (hle == NULL || hle->logmsg != NULL) {
10092 err = got_error(GOT_ERR_HISTEDIT_CMD);
10093 break;
10095 if (p[0] == '\0') {
10096 err = histedit_edit_logmsg(hle, repo);
10097 if (err)
10098 break;
10099 } else {
10100 hle->logmsg = strdup(p);
10101 if (hle->logmsg == NULL) {
10102 err = got_error_from_errno("strdup");
10103 break;
10106 free(line);
10107 line = NULL;
10108 continue;
10109 } else {
10110 end = p;
10111 while (end[0] && !isspace((unsigned char)end[0]))
10112 end++;
10113 *end = '\0';
10115 err = got_object_resolve_id_str(&commit_id, repo, p);
10116 if (err) {
10117 /* override error code */
10118 err = histedit_syntax_error(lineno);
10119 break;
10122 hle = malloc(sizeof(*hle));
10123 if (hle == NULL) {
10124 err = got_error_from_errno("malloc");
10125 break;
10127 hle->cmd = cmd;
10128 hle->commit_id = commit_id;
10129 hle->logmsg = NULL;
10130 commit_id = NULL;
10131 free(line);
10132 line = NULL;
10133 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10136 free(line);
10137 free(commit_id);
10138 return err;
10141 static const struct got_error *
10142 histedit_check_script(struct got_histedit_list *histedit_cmds,
10143 struct got_object_id_queue *commits, struct got_repository *repo)
10145 const struct got_error *err = NULL;
10146 struct got_object_qid *qid;
10147 struct got_histedit_list_entry *hle;
10148 static char msg[92];
10149 char *id_str;
10151 if (TAILQ_EMPTY(histedit_cmds))
10152 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10153 "histedit script contains no commands");
10154 if (STAILQ_EMPTY(commits))
10155 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10157 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10158 struct got_histedit_list_entry *hle2;
10159 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10160 if (hle == hle2)
10161 continue;
10162 if (got_object_id_cmp(hle->commit_id,
10163 hle2->commit_id) != 0)
10164 continue;
10165 err = got_object_id_str(&id_str, hle->commit_id);
10166 if (err)
10167 return err;
10168 snprintf(msg, sizeof(msg), "commit %s is listed "
10169 "more than once in histedit script", id_str);
10170 free(id_str);
10171 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10175 STAILQ_FOREACH(qid, commits, entry) {
10176 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10177 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10178 break;
10180 if (hle == NULL) {
10181 err = got_object_id_str(&id_str, &qid->id);
10182 if (err)
10183 return err;
10184 snprintf(msg, sizeof(msg),
10185 "commit %s missing from histedit script", id_str);
10186 free(id_str);
10187 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10191 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10192 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10193 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10194 "last commit in histedit script cannot be folded");
10196 return NULL;
10199 static const struct got_error *
10200 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10201 const char *path, struct got_object_id_queue *commits,
10202 struct got_repository *repo)
10204 const struct got_error *err = NULL;
10205 char *editor;
10206 FILE *f = NULL;
10208 err = get_editor(&editor);
10209 if (err)
10210 return err;
10212 if (spawn_editor(editor, path) == -1) {
10213 err = got_error_from_errno("failed spawning editor");
10214 goto done;
10217 f = fopen(path, "re");
10218 if (f == NULL) {
10219 err = got_error_from_errno("fopen");
10220 goto done;
10222 err = histedit_parse_list(histedit_cmds, f, repo);
10223 if (err)
10224 goto done;
10226 err = histedit_check_script(histedit_cmds, commits, repo);
10227 done:
10228 if (f && fclose(f) == EOF && err == NULL)
10229 err = got_error_from_errno("fclose");
10230 free(editor);
10231 return err;
10234 static const struct got_error *
10235 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10236 struct got_object_id_queue *, const char *, const char *,
10237 struct got_repository *);
10239 static const struct got_error *
10240 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10241 struct got_object_id_queue *commits, const char *branch_name,
10242 int edit_logmsg_only, int fold_only, int edit_only,
10243 struct got_repository *repo)
10245 const struct got_error *err;
10246 FILE *f = NULL;
10247 char *path = NULL;
10249 err = got_opentemp_named(&path, &f, "got-histedit");
10250 if (err)
10251 return err;
10253 err = write_cmd_list(f, branch_name, commits);
10254 if (err)
10255 goto done;
10257 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10258 fold_only, edit_only, repo);
10259 if (err)
10260 goto done;
10262 if (edit_logmsg_only || fold_only || edit_only) {
10263 rewind(f);
10264 err = histedit_parse_list(histedit_cmds, f, repo);
10265 } else {
10266 if (fclose(f) == EOF) {
10267 err = got_error_from_errno("fclose");
10268 goto done;
10270 f = NULL;
10271 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10272 if (err) {
10273 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10274 err->code != GOT_ERR_HISTEDIT_CMD)
10275 goto done;
10276 err = histedit_edit_list_retry(histedit_cmds, err,
10277 commits, path, branch_name, repo);
10280 done:
10281 if (f && fclose(f) == EOF && err == NULL)
10282 err = got_error_from_errno("fclose");
10283 if (path && unlink(path) != 0 && err == NULL)
10284 err = got_error_from_errno2("unlink", path);
10285 free(path);
10286 return err;
10289 static const struct got_error *
10290 histedit_save_list(struct got_histedit_list *histedit_cmds,
10291 struct got_worktree *worktree, struct got_repository *repo)
10293 const struct got_error *err = NULL;
10294 char *path = NULL;
10295 FILE *f = NULL;
10296 struct got_histedit_list_entry *hle;
10297 struct got_commit_object *commit = NULL;
10299 err = got_worktree_get_histedit_script_path(&path, worktree);
10300 if (err)
10301 return err;
10303 f = fopen(path, "we");
10304 if (f == NULL) {
10305 err = got_error_from_errno2("fopen", path);
10306 goto done;
10308 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10309 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10310 repo);
10311 if (err)
10312 break;
10314 if (hle->logmsg) {
10315 int n = fprintf(f, "%c %s\n",
10316 GOT_HISTEDIT_MESG, hle->logmsg);
10317 if (n < 0) {
10318 err = got_ferror(f, GOT_ERR_IO);
10319 break;
10323 done:
10324 if (f && fclose(f) == EOF && err == NULL)
10325 err = got_error_from_errno("fclose");
10326 free(path);
10327 if (commit)
10328 got_object_commit_close(commit);
10329 return err;
10332 void
10333 histedit_free_list(struct got_histedit_list *histedit_cmds)
10335 struct got_histedit_list_entry *hle;
10337 while ((hle = TAILQ_FIRST(histedit_cmds))) {
10338 TAILQ_REMOVE(histedit_cmds, hle, entry);
10339 free(hle);
10343 static const struct got_error *
10344 histedit_load_list(struct got_histedit_list *histedit_cmds,
10345 const char *path, struct got_repository *repo)
10347 const struct got_error *err = NULL;
10348 FILE *f = NULL;
10350 f = fopen(path, "re");
10351 if (f == NULL) {
10352 err = got_error_from_errno2("fopen", path);
10353 goto done;
10356 err = histedit_parse_list(histedit_cmds, f, repo);
10357 done:
10358 if (f && fclose(f) == EOF && err == NULL)
10359 err = got_error_from_errno("fclose");
10360 return err;
10363 static const struct got_error *
10364 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
10365 const struct got_error *edit_err, struct got_object_id_queue *commits,
10366 const char *path, const char *branch_name, struct got_repository *repo)
10368 const struct got_error *err = NULL, *prev_err = edit_err;
10369 int resp = ' ';
10371 while (resp != 'c' && resp != 'r' && resp != 'a') {
10372 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
10373 "or (a)bort: ", getprogname(), prev_err->msg);
10374 resp = getchar();
10375 if (resp == '\n')
10376 resp = getchar();
10377 if (resp == 'c') {
10378 histedit_free_list(histedit_cmds);
10379 err = histedit_run_editor(histedit_cmds, path, commits,
10380 repo);
10381 if (err) {
10382 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10383 err->code != GOT_ERR_HISTEDIT_CMD)
10384 break;
10385 prev_err = err;
10386 resp = ' ';
10387 continue;
10389 break;
10390 } else if (resp == 'r') {
10391 histedit_free_list(histedit_cmds);
10392 err = histedit_edit_script(histedit_cmds,
10393 commits, branch_name, 0, 0, 0, repo);
10394 if (err) {
10395 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10396 err->code != GOT_ERR_HISTEDIT_CMD)
10397 break;
10398 prev_err = err;
10399 resp = ' ';
10400 continue;
10402 break;
10403 } else if (resp == 'a') {
10404 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
10405 break;
10406 } else
10407 printf("invalid response '%c'\n", resp);
10410 return err;
10413 static const struct got_error *
10414 histedit_complete(struct got_worktree *worktree,
10415 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
10416 struct got_reference *branch, struct got_repository *repo)
10418 printf("Switching work tree to %s\n",
10419 got_ref_get_symref_target(branch));
10420 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
10421 branch, repo);
10424 static const struct got_error *
10425 show_histedit_progress(struct got_commit_object *commit,
10426 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
10428 const struct got_error *err;
10429 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10431 err = got_object_id_str(&old_id_str, hle->commit_id);
10432 if (err)
10433 goto done;
10435 if (new_id) {
10436 err = got_object_id_str(&new_id_str, new_id);
10437 if (err)
10438 goto done;
10441 old_id_str[12] = '\0';
10442 if (new_id_str)
10443 new_id_str[12] = '\0';
10445 if (hle->logmsg) {
10446 logmsg = strdup(hle->logmsg);
10447 if (logmsg == NULL) {
10448 err = got_error_from_errno("strdup");
10449 goto done;
10451 trim_logmsg(logmsg, 42);
10452 } else {
10453 err = get_short_logmsg(&logmsg, 42, commit);
10454 if (err)
10455 goto done;
10458 switch (hle->cmd->code) {
10459 case GOT_HISTEDIT_PICK:
10460 case GOT_HISTEDIT_EDIT:
10461 printf("%s -> %s: %s\n", old_id_str,
10462 new_id_str ? new_id_str : "no-op change", logmsg);
10463 break;
10464 case GOT_HISTEDIT_DROP:
10465 case GOT_HISTEDIT_FOLD:
10466 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
10467 logmsg);
10468 break;
10469 default:
10470 break;
10472 done:
10473 free(old_id_str);
10474 free(new_id_str);
10475 return err;
10478 static const struct got_error *
10479 histedit_commit(struct got_pathlist_head *merged_paths,
10480 struct got_worktree *worktree, struct got_fileindex *fileindex,
10481 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
10482 struct got_repository *repo)
10484 const struct got_error *err;
10485 struct got_commit_object *commit;
10486 struct got_object_id *new_commit_id;
10488 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
10489 && hle->logmsg == NULL) {
10490 err = histedit_edit_logmsg(hle, repo);
10491 if (err)
10492 return err;
10495 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10496 if (err)
10497 return err;
10499 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
10500 worktree, fileindex, tmp_branch, commit, hle->commit_id,
10501 hle->logmsg, repo);
10502 if (err) {
10503 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
10504 goto done;
10505 err = show_histedit_progress(commit, hle, NULL);
10506 } else {
10507 err = show_histedit_progress(commit, hle, new_commit_id);
10508 free(new_commit_id);
10510 done:
10511 got_object_commit_close(commit);
10512 return err;
10515 static const struct got_error *
10516 histedit_skip_commit(struct got_histedit_list_entry *hle,
10517 struct got_worktree *worktree, struct got_repository *repo)
10519 const struct got_error *error;
10520 struct got_commit_object *commit;
10522 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
10523 repo);
10524 if (error)
10525 return error;
10527 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
10528 if (error)
10529 return error;
10531 error = show_histedit_progress(commit, hle, NULL);
10532 got_object_commit_close(commit);
10533 return error;
10536 static const struct got_error *
10537 check_local_changes(void *arg, unsigned char status,
10538 unsigned char staged_status, const char *path,
10539 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
10540 struct got_object_id *commit_id, int dirfd, const char *de_name)
10542 int *have_local_changes = arg;
10544 switch (status) {
10545 case GOT_STATUS_ADD:
10546 case GOT_STATUS_DELETE:
10547 case GOT_STATUS_MODIFY:
10548 case GOT_STATUS_CONFLICT:
10549 *have_local_changes = 1;
10550 return got_error(GOT_ERR_CANCELLED);
10551 default:
10552 break;
10555 switch (staged_status) {
10556 case GOT_STATUS_ADD:
10557 case GOT_STATUS_DELETE:
10558 case GOT_STATUS_MODIFY:
10559 *have_local_changes = 1;
10560 return got_error(GOT_ERR_CANCELLED);
10561 default:
10562 break;
10565 return NULL;
10568 static const struct got_error *
10569 cmd_histedit(int argc, char *argv[])
10571 const struct got_error *error = NULL;
10572 struct got_worktree *worktree = NULL;
10573 struct got_fileindex *fileindex = NULL;
10574 struct got_repository *repo = NULL;
10575 char *cwd = NULL;
10576 struct got_reference *branch = NULL;
10577 struct got_reference *tmp_branch = NULL;
10578 struct got_object_id *resume_commit_id = NULL;
10579 struct got_object_id *base_commit_id = NULL;
10580 struct got_object_id *head_commit_id = NULL;
10581 struct got_commit_object *commit = NULL;
10582 int ch, rebase_in_progress = 0, merge_in_progress = 0;
10583 struct got_update_progress_arg upa;
10584 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
10585 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
10586 int list_backups = 0, delete_backups = 0;
10587 const char *edit_script_path = NULL;
10588 struct got_object_id_queue commits;
10589 struct got_pathlist_head merged_paths;
10590 const struct got_object_id_queue *parent_ids;
10591 struct got_object_qid *pid;
10592 struct got_histedit_list histedit_cmds;
10593 struct got_histedit_list_entry *hle;
10595 STAILQ_INIT(&commits);
10596 TAILQ_INIT(&histedit_cmds);
10597 TAILQ_INIT(&merged_paths);
10598 memset(&upa, 0, sizeof(upa));
10600 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
10601 switch (ch) {
10602 case 'a':
10603 abort_edit = 1;
10604 break;
10605 case 'c':
10606 continue_edit = 1;
10607 break;
10608 case 'e':
10609 edit_only = 1;
10610 break;
10611 case 'f':
10612 fold_only = 1;
10613 break;
10614 case 'F':
10615 edit_script_path = optarg;
10616 break;
10617 case 'm':
10618 edit_logmsg_only = 1;
10619 break;
10620 case 'l':
10621 list_backups = 1;
10622 break;
10623 case 'X':
10624 delete_backups = 1;
10625 break;
10626 default:
10627 usage_histedit();
10628 /* NOTREACHED */
10632 argc -= optind;
10633 argv += optind;
10635 #ifndef PROFILE
10636 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10637 "unveil", NULL) == -1)
10638 err(1, "pledge");
10639 #endif
10640 if (abort_edit && continue_edit)
10641 option_conflict('a', 'c');
10642 if (edit_script_path && edit_logmsg_only)
10643 option_conflict('F', 'm');
10644 if (abort_edit && edit_logmsg_only)
10645 option_conflict('a', 'm');
10646 if (continue_edit && edit_logmsg_only)
10647 option_conflict('c', 'm');
10648 if (abort_edit && fold_only)
10649 option_conflict('a', 'f');
10650 if (continue_edit && fold_only)
10651 option_conflict('c', 'f');
10652 if (fold_only && edit_logmsg_only)
10653 option_conflict('f', 'm');
10654 if (edit_script_path && fold_only)
10655 option_conflict('F', 'f');
10656 if (abort_edit && edit_only)
10657 option_conflict('a', 'e');
10658 if (continue_edit && edit_only)
10659 option_conflict('c', 'e');
10660 if (edit_only && edit_logmsg_only)
10661 option_conflict('e', 'm');
10662 if (edit_script_path && edit_only)
10663 option_conflict('F', 'e');
10664 if (list_backups) {
10665 if (abort_edit)
10666 option_conflict('l', 'a');
10667 if (continue_edit)
10668 option_conflict('l', 'c');
10669 if (edit_script_path)
10670 option_conflict('l', 'F');
10671 if (edit_logmsg_only)
10672 option_conflict('l', 'm');
10673 if (fold_only)
10674 option_conflict('l', 'f');
10675 if (edit_only)
10676 option_conflict('l', 'e');
10677 if (delete_backups)
10678 option_conflict('l', 'X');
10679 if (argc != 0 && argc != 1)
10680 usage_histedit();
10681 } else if (delete_backups) {
10682 if (abort_edit)
10683 option_conflict('X', 'a');
10684 if (continue_edit)
10685 option_conflict('X', 'c');
10686 if (edit_script_path)
10687 option_conflict('X', 'F');
10688 if (edit_logmsg_only)
10689 option_conflict('X', 'm');
10690 if (fold_only)
10691 option_conflict('X', 'f');
10692 if (edit_only)
10693 option_conflict('X', 'e');
10694 if (list_backups)
10695 option_conflict('X', 'l');
10696 if (argc != 0 && argc != 1)
10697 usage_histedit();
10698 } else if (argc != 0)
10699 usage_histedit();
10702 * This command cannot apply unveil(2) in all cases because the
10703 * user may choose to run an editor to edit the histedit script
10704 * and to edit individual commit log messages.
10705 * unveil(2) traverses exec(2); if an editor is used we have to
10706 * apply unveil after edit script and log messages have been written.
10707 * XXX TODO: Make use of unveil(2) where possible.
10710 cwd = getcwd(NULL, 0);
10711 if (cwd == NULL) {
10712 error = got_error_from_errno("getcwd");
10713 goto done;
10715 error = got_worktree_open(&worktree, cwd);
10716 if (error) {
10717 if (list_backups || delete_backups) {
10718 if (error->code != GOT_ERR_NOT_WORKTREE)
10719 goto done;
10720 } else {
10721 if (error->code == GOT_ERR_NOT_WORKTREE)
10722 error = wrap_not_worktree_error(error,
10723 "histedit", cwd);
10724 goto done;
10728 if (list_backups || delete_backups) {
10729 error = got_repo_open(&repo,
10730 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10731 NULL);
10732 if (error != NULL)
10733 goto done;
10734 error = apply_unveil(got_repo_get_path(repo), 0,
10735 worktree ? got_worktree_get_root_path(worktree) : NULL);
10736 if (error)
10737 goto done;
10738 error = process_backup_refs(
10739 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
10740 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10741 goto done; /* nothing else to do */
10744 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10745 NULL);
10746 if (error != NULL)
10747 goto done;
10749 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10750 if (error)
10751 goto done;
10752 if (rebase_in_progress) {
10753 error = got_error(GOT_ERR_REBASING);
10754 goto done;
10757 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10758 repo);
10759 if (error)
10760 goto done;
10761 if (merge_in_progress) {
10762 error = got_error(GOT_ERR_MERGE_BUSY);
10763 goto done;
10766 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
10767 if (error)
10768 goto done;
10770 if (edit_in_progress && edit_logmsg_only) {
10771 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10772 "histedit operation is in progress in this "
10773 "work tree and must be continued or aborted "
10774 "before the -m option can be used");
10775 goto done;
10777 if (edit_in_progress && fold_only) {
10778 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10779 "histedit operation is in progress in this "
10780 "work tree and must be continued or aborted "
10781 "before the -f option can be used");
10782 goto done;
10784 if (edit_in_progress && edit_only) {
10785 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10786 "histedit operation is in progress in this "
10787 "work tree and must be continued or aborted "
10788 "before the -e option can be used");
10789 goto done;
10792 if (edit_in_progress && abort_edit) {
10793 error = got_worktree_histedit_continue(&resume_commit_id,
10794 &tmp_branch, &branch, &base_commit_id, &fileindex,
10795 worktree, repo);
10796 if (error)
10797 goto done;
10798 printf("Switching work tree to %s\n",
10799 got_ref_get_symref_target(branch));
10800 error = got_worktree_histedit_abort(worktree, fileindex, repo,
10801 branch, base_commit_id, abort_progress, &upa);
10802 if (error)
10803 goto done;
10804 printf("Histedit of %s aborted\n",
10805 got_ref_get_symref_target(branch));
10806 print_merge_progress_stats(&upa);
10807 goto done; /* nothing else to do */
10808 } else if (abort_edit) {
10809 error = got_error(GOT_ERR_NOT_HISTEDIT);
10810 goto done;
10813 if (continue_edit) {
10814 char *path;
10816 if (!edit_in_progress) {
10817 error = got_error(GOT_ERR_NOT_HISTEDIT);
10818 goto done;
10821 error = got_worktree_get_histedit_script_path(&path, worktree);
10822 if (error)
10823 goto done;
10825 error = histedit_load_list(&histedit_cmds, path, repo);
10826 free(path);
10827 if (error)
10828 goto done;
10830 error = got_worktree_histedit_continue(&resume_commit_id,
10831 &tmp_branch, &branch, &base_commit_id, &fileindex,
10832 worktree, repo);
10833 if (error)
10834 goto done;
10836 error = got_ref_resolve(&head_commit_id, repo, branch);
10837 if (error)
10838 goto done;
10840 error = got_object_open_as_commit(&commit, repo,
10841 head_commit_id);
10842 if (error)
10843 goto done;
10844 parent_ids = got_object_commit_get_parent_ids(commit);
10845 pid = STAILQ_FIRST(parent_ids);
10846 if (pid == NULL) {
10847 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10848 goto done;
10850 error = collect_commits(&commits, head_commit_id, &pid->id,
10851 base_commit_id, got_worktree_get_path_prefix(worktree),
10852 GOT_ERR_HISTEDIT_PATH, repo);
10853 got_object_commit_close(commit);
10854 commit = NULL;
10855 if (error)
10856 goto done;
10857 } else {
10858 if (edit_in_progress) {
10859 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10860 goto done;
10863 error = got_ref_open(&branch, repo,
10864 got_worktree_get_head_ref_name(worktree), 0);
10865 if (error != NULL)
10866 goto done;
10868 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10869 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10870 "will not edit commit history of a branch outside "
10871 "the \"refs/heads/\" reference namespace");
10872 goto done;
10875 error = got_ref_resolve(&head_commit_id, repo, branch);
10876 got_ref_close(branch);
10877 branch = NULL;
10878 if (error)
10879 goto done;
10881 error = got_object_open_as_commit(&commit, repo,
10882 head_commit_id);
10883 if (error)
10884 goto done;
10885 parent_ids = got_object_commit_get_parent_ids(commit);
10886 pid = STAILQ_FIRST(parent_ids);
10887 if (pid == NULL) {
10888 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10889 goto done;
10891 error = collect_commits(&commits, head_commit_id, &pid->id,
10892 got_worktree_get_base_commit_id(worktree),
10893 got_worktree_get_path_prefix(worktree),
10894 GOT_ERR_HISTEDIT_PATH, repo);
10895 got_object_commit_close(commit);
10896 commit = NULL;
10897 if (error)
10898 goto done;
10900 if (STAILQ_EMPTY(&commits)) {
10901 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10902 goto done;
10905 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
10906 &base_commit_id, &fileindex, worktree, repo);
10907 if (error)
10908 goto done;
10910 if (edit_script_path) {
10911 error = histedit_load_list(&histedit_cmds,
10912 edit_script_path, repo);
10913 if (error) {
10914 got_worktree_histedit_abort(worktree, fileindex,
10915 repo, branch, base_commit_id,
10916 abort_progress, &upa);
10917 print_merge_progress_stats(&upa);
10918 goto done;
10920 } else {
10921 const char *branch_name;
10922 branch_name = got_ref_get_symref_target(branch);
10923 if (strncmp(branch_name, "refs/heads/", 11) == 0)
10924 branch_name += 11;
10925 error = histedit_edit_script(&histedit_cmds, &commits,
10926 branch_name, edit_logmsg_only, fold_only,
10927 edit_only, repo);
10928 if (error) {
10929 got_worktree_histedit_abort(worktree, fileindex,
10930 repo, branch, base_commit_id,
10931 abort_progress, &upa);
10932 print_merge_progress_stats(&upa);
10933 goto done;
10938 error = histedit_save_list(&histedit_cmds, worktree,
10939 repo);
10940 if (error) {
10941 got_worktree_histedit_abort(worktree, fileindex,
10942 repo, branch, base_commit_id,
10943 abort_progress, &upa);
10944 print_merge_progress_stats(&upa);
10945 goto done;
10950 error = histedit_check_script(&histedit_cmds, &commits, repo);
10951 if (error)
10952 goto done;
10954 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
10955 if (resume_commit_id) {
10956 if (got_object_id_cmp(hle->commit_id,
10957 resume_commit_id) != 0)
10958 continue;
10960 resume_commit_id = NULL;
10961 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
10962 hle->cmd->code == GOT_HISTEDIT_FOLD) {
10963 error = histedit_skip_commit(hle, worktree,
10964 repo);
10965 if (error)
10966 goto done;
10967 } else {
10968 struct got_pathlist_head paths;
10969 int have_changes = 0;
10971 TAILQ_INIT(&paths);
10972 error = got_pathlist_append(&paths, "", NULL);
10973 if (error)
10974 goto done;
10975 error = got_worktree_status(worktree, &paths,
10976 repo, 0, check_local_changes, &have_changes,
10977 check_cancelled, NULL);
10978 got_pathlist_free(&paths);
10979 if (error) {
10980 if (error->code != GOT_ERR_CANCELLED)
10981 goto done;
10982 if (sigint_received || sigpipe_received)
10983 goto done;
10985 if (have_changes) {
10986 error = histedit_commit(NULL, worktree,
10987 fileindex, tmp_branch, hle, repo);
10988 if (error)
10989 goto done;
10990 } else {
10991 error = got_object_open_as_commit(
10992 &commit, repo, hle->commit_id);
10993 if (error)
10994 goto done;
10995 error = show_histedit_progress(commit,
10996 hle, NULL);
10997 got_object_commit_close(commit);
10998 commit = NULL;
10999 if (error)
11000 goto done;
11003 continue;
11006 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11007 error = histedit_skip_commit(hle, worktree, repo);
11008 if (error)
11009 goto done;
11010 continue;
11013 error = got_object_open_as_commit(&commit, repo,
11014 hle->commit_id);
11015 if (error)
11016 goto done;
11017 parent_ids = got_object_commit_get_parent_ids(commit);
11018 pid = STAILQ_FIRST(parent_ids);
11020 error = got_worktree_histedit_merge_files(&merged_paths,
11021 worktree, fileindex, &pid->id, hle->commit_id, repo,
11022 update_progress, &upa, check_cancelled, NULL);
11023 if (error)
11024 goto done;
11025 got_object_commit_close(commit);
11026 commit = NULL;
11028 print_merge_progress_stats(&upa);
11029 if (upa.conflicts > 0 || upa.missing > 0 ||
11030 upa.not_deleted > 0 || upa.unversioned > 0) {
11031 if (upa.conflicts > 0) {
11032 error = show_rebase_merge_conflict(
11033 hle->commit_id, repo);
11034 if (error)
11035 goto done;
11037 got_worktree_rebase_pathlist_free(&merged_paths);
11038 break;
11041 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11042 char *id_str;
11043 error = got_object_id_str(&id_str, hle->commit_id);
11044 if (error)
11045 goto done;
11046 printf("Stopping histedit for amending commit %s\n",
11047 id_str);
11048 free(id_str);
11049 got_worktree_rebase_pathlist_free(&merged_paths);
11050 error = got_worktree_histedit_postpone(worktree,
11051 fileindex);
11052 goto done;
11055 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11056 error = histedit_skip_commit(hle, worktree, repo);
11057 if (error)
11058 goto done;
11059 continue;
11062 error = histedit_commit(&merged_paths, worktree, fileindex,
11063 tmp_branch, hle, repo);
11064 got_worktree_rebase_pathlist_free(&merged_paths);
11065 if (error)
11066 goto done;
11069 if (upa.conflicts > 0 || upa.missing > 0 ||
11070 upa.not_deleted > 0 || upa.unversioned > 0) {
11071 error = got_worktree_histedit_postpone(worktree, fileindex);
11072 if (error)
11073 goto done;
11074 if (upa.conflicts > 0 && upa.missing == 0 &&
11075 upa.not_deleted == 0 && upa.unversioned == 0) {
11076 error = got_error_msg(GOT_ERR_CONFLICTS,
11077 "conflicts must be resolved before histedit "
11078 "can continue");
11079 } else if (upa.conflicts > 0) {
11080 error = got_error_msg(GOT_ERR_CONFLICTS,
11081 "conflicts must be resolved before histedit "
11082 "can continue; changes destined for some "
11083 "files were not yet merged and should be "
11084 "merged manually if required before the "
11085 "histedit operation is continued");
11086 } else {
11087 error = got_error_msg(GOT_ERR_CONFLICTS,
11088 "changes destined for some files were not "
11089 "yet merged and should be merged manually "
11090 "if required before the histedit operation "
11091 "is continued");
11093 } else
11094 error = histedit_complete(worktree, fileindex, tmp_branch,
11095 branch, repo);
11096 done:
11097 got_object_id_queue_free(&commits);
11098 histedit_free_list(&histedit_cmds);
11099 free(head_commit_id);
11100 free(base_commit_id);
11101 free(resume_commit_id);
11102 if (commit)
11103 got_object_commit_close(commit);
11104 if (branch)
11105 got_ref_close(branch);
11106 if (tmp_branch)
11107 got_ref_close(tmp_branch);
11108 if (worktree)
11109 got_worktree_close(worktree);
11110 if (repo) {
11111 const struct got_error *close_err = got_repo_close(repo);
11112 if (error == NULL)
11113 error = close_err;
11115 return error;
11118 __dead static void
11119 usage_integrate(void)
11121 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11122 exit(1);
11125 static const struct got_error *
11126 cmd_integrate(int argc, char *argv[])
11128 const struct got_error *error = NULL;
11129 struct got_repository *repo = NULL;
11130 struct got_worktree *worktree = NULL;
11131 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11132 const char *branch_arg = NULL;
11133 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11134 struct got_fileindex *fileindex = NULL;
11135 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11136 int ch;
11137 struct got_update_progress_arg upa;
11139 while ((ch = getopt(argc, argv, "")) != -1) {
11140 switch (ch) {
11141 default:
11142 usage_integrate();
11143 /* NOTREACHED */
11147 argc -= optind;
11148 argv += optind;
11150 if (argc != 1)
11151 usage_integrate();
11152 branch_arg = argv[0];
11153 #ifndef PROFILE
11154 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11155 "unveil", NULL) == -1)
11156 err(1, "pledge");
11157 #endif
11158 cwd = getcwd(NULL, 0);
11159 if (cwd == NULL) {
11160 error = got_error_from_errno("getcwd");
11161 goto done;
11164 error = got_worktree_open(&worktree, cwd);
11165 if (error) {
11166 if (error->code == GOT_ERR_NOT_WORKTREE)
11167 error = wrap_not_worktree_error(error, "integrate",
11168 cwd);
11169 goto done;
11172 error = check_rebase_or_histedit_in_progress(worktree);
11173 if (error)
11174 goto done;
11176 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11177 NULL);
11178 if (error != NULL)
11179 goto done;
11181 error = apply_unveil(got_repo_get_path(repo), 0,
11182 got_worktree_get_root_path(worktree));
11183 if (error)
11184 goto done;
11186 error = check_merge_in_progress(worktree, repo);
11187 if (error)
11188 goto done;
11190 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11191 error = got_error_from_errno("asprintf");
11192 goto done;
11195 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11196 &base_branch_ref, worktree, refname, repo);
11197 if (error)
11198 goto done;
11200 refname = strdup(got_ref_get_name(branch_ref));
11201 if (refname == NULL) {
11202 error = got_error_from_errno("strdup");
11203 got_worktree_integrate_abort(worktree, fileindex, repo,
11204 branch_ref, base_branch_ref);
11205 goto done;
11207 base_refname = strdup(got_ref_get_name(base_branch_ref));
11208 if (base_refname == NULL) {
11209 error = got_error_from_errno("strdup");
11210 got_worktree_integrate_abort(worktree, fileindex, repo,
11211 branch_ref, base_branch_ref);
11212 goto done;
11215 error = got_ref_resolve(&commit_id, repo, branch_ref);
11216 if (error)
11217 goto done;
11219 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11220 if (error)
11221 goto done;
11223 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11224 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11225 "specified branch has already been integrated");
11226 got_worktree_integrate_abort(worktree, fileindex, repo,
11227 branch_ref, base_branch_ref);
11228 goto done;
11231 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11232 if (error) {
11233 if (error->code == GOT_ERR_ANCESTRY)
11234 error = got_error(GOT_ERR_REBASE_REQUIRED);
11235 got_worktree_integrate_abort(worktree, fileindex, repo,
11236 branch_ref, base_branch_ref);
11237 goto done;
11240 memset(&upa, 0, sizeof(upa));
11241 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11242 branch_ref, base_branch_ref, update_progress, &upa,
11243 check_cancelled, NULL);
11244 if (error)
11245 goto done;
11247 printf("Integrated %s into %s\n", refname, base_refname);
11248 print_update_progress_stats(&upa);
11249 done:
11250 if (repo) {
11251 const struct got_error *close_err = got_repo_close(repo);
11252 if (error == NULL)
11253 error = close_err;
11255 if (worktree)
11256 got_worktree_close(worktree);
11257 free(cwd);
11258 free(base_commit_id);
11259 free(commit_id);
11260 free(refname);
11261 free(base_refname);
11262 return error;
11265 __dead static void
11266 usage_merge(void)
11268 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11269 getprogname());
11270 exit(1);
11273 static const struct got_error *
11274 cmd_merge(int argc, char *argv[])
11276 const struct got_error *error = NULL;
11277 struct got_worktree *worktree = NULL;
11278 struct got_repository *repo = NULL;
11279 struct got_fileindex *fileindex = NULL;
11280 char *cwd = NULL, *id_str = NULL, *author = NULL;
11281 struct got_reference *branch = NULL, *wt_branch = NULL;
11282 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11283 struct got_object_id *wt_branch_tip = NULL;
11284 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11285 int interrupt_merge = 0;
11286 struct got_update_progress_arg upa;
11287 struct got_object_id *merge_commit_id = NULL;
11288 char *branch_name = NULL;
11290 memset(&upa, 0, sizeof(upa));
11292 while ((ch = getopt(argc, argv, "acn")) != -1) {
11293 switch (ch) {
11294 case 'a':
11295 abort_merge = 1;
11296 break;
11297 case 'c':
11298 continue_merge = 1;
11299 break;
11300 case 'n':
11301 interrupt_merge = 1;
11302 break;
11303 default:
11304 usage_rebase();
11305 /* NOTREACHED */
11309 argc -= optind;
11310 argv += optind;
11312 #ifndef PROFILE
11313 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11314 "unveil", NULL) == -1)
11315 err(1, "pledge");
11316 #endif
11318 if (abort_merge && continue_merge)
11319 option_conflict('a', 'c');
11320 if (abort_merge || continue_merge) {
11321 if (argc != 0)
11322 usage_merge();
11323 } else if (argc != 1)
11324 usage_merge();
11326 cwd = getcwd(NULL, 0);
11327 if (cwd == NULL) {
11328 error = got_error_from_errno("getcwd");
11329 goto done;
11332 error = got_worktree_open(&worktree, cwd);
11333 if (error) {
11334 if (error->code == GOT_ERR_NOT_WORKTREE)
11335 error = wrap_not_worktree_error(error,
11336 "merge", cwd);
11337 goto done;
11340 error = got_repo_open(&repo,
11341 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
11342 if (error != NULL)
11343 goto done;
11345 error = apply_unveil(got_repo_get_path(repo), 0,
11346 worktree ? got_worktree_get_root_path(worktree) : NULL);
11347 if (error)
11348 goto done;
11350 error = check_rebase_or_histedit_in_progress(worktree);
11351 if (error)
11352 goto done;
11354 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11355 repo);
11356 if (error)
11357 goto done;
11359 if (abort_merge) {
11360 if (!merge_in_progress) {
11361 error = got_error(GOT_ERR_NOT_MERGING);
11362 goto done;
11364 error = got_worktree_merge_continue(&branch_name,
11365 &branch_tip, &fileindex, worktree, repo);
11366 if (error)
11367 goto done;
11368 error = got_worktree_merge_abort(worktree, fileindex, repo,
11369 abort_progress, &upa);
11370 if (error)
11371 goto done;
11372 printf("Merge of %s aborted\n", branch_name);
11373 goto done; /* nothing else to do */
11376 error = get_author(&author, repo, worktree);
11377 if (error)
11378 goto done;
11380 if (continue_merge) {
11381 if (!merge_in_progress) {
11382 error = got_error(GOT_ERR_NOT_MERGING);
11383 goto done;
11385 error = got_worktree_merge_continue(&branch_name,
11386 &branch_tip, &fileindex, worktree, repo);
11387 if (error)
11388 goto done;
11389 } else {
11390 error = got_ref_open(&branch, repo, argv[0], 0);
11391 if (error != NULL)
11392 goto done;
11393 branch_name = strdup(got_ref_get_name(branch));
11394 if (branch_name == NULL) {
11395 error = got_error_from_errno("strdup");
11396 goto done;
11398 error = got_ref_resolve(&branch_tip, repo, branch);
11399 if (error)
11400 goto done;
11403 error = got_ref_open(&wt_branch, repo,
11404 got_worktree_get_head_ref_name(worktree), 0);
11405 if (error)
11406 goto done;
11407 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
11408 if (error)
11409 goto done;
11410 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11411 wt_branch_tip, branch_tip, 0, repo,
11412 check_cancelled, NULL);
11413 if (error && error->code != GOT_ERR_ANCESTRY)
11414 goto done;
11416 if (!continue_merge) {
11417 error = check_path_prefix(wt_branch_tip, branch_tip,
11418 got_worktree_get_path_prefix(worktree),
11419 GOT_ERR_MERGE_PATH, repo);
11420 if (error)
11421 goto done;
11422 if (yca_id) {
11423 error = check_same_branch(wt_branch_tip, branch,
11424 yca_id, repo);
11425 if (error) {
11426 if (error->code != GOT_ERR_ANCESTRY)
11427 goto done;
11428 error = NULL;
11429 } else {
11430 static char msg[512];
11431 snprintf(msg, sizeof(msg),
11432 "cannot create a merge commit because "
11433 "%s is based on %s; %s can be integrated "
11434 "with 'got integrate' instead", branch_name,
11435 got_worktree_get_head_ref_name(worktree),
11436 branch_name);
11437 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
11438 goto done;
11441 error = got_worktree_merge_prepare(&fileindex, worktree,
11442 branch, repo);
11443 if (error)
11444 goto done;
11446 error = got_worktree_merge_branch(worktree, fileindex,
11447 yca_id, branch_tip, repo, update_progress, &upa,
11448 check_cancelled, NULL);
11449 if (error)
11450 goto done;
11451 print_merge_progress_stats(&upa);
11452 if (!upa.did_something) {
11453 error = got_worktree_merge_abort(worktree, fileindex,
11454 repo, abort_progress, &upa);
11455 if (error)
11456 goto done;
11457 printf("Already up-to-date\n");
11458 goto done;
11462 if (interrupt_merge) {
11463 error = got_worktree_merge_postpone(worktree, fileindex);
11464 if (error)
11465 goto done;
11466 printf("Merge of %s interrupted on request\n", branch_name);
11467 } else if (upa.conflicts > 0 || upa.missing > 0 ||
11468 upa.not_deleted > 0 || upa.unversioned > 0) {
11469 error = got_worktree_merge_postpone(worktree, fileindex);
11470 if (error)
11471 goto done;
11472 if (upa.conflicts > 0 && upa.missing == 0 &&
11473 upa.not_deleted == 0 && upa.unversioned == 0) {
11474 error = got_error_msg(GOT_ERR_CONFLICTS,
11475 "conflicts must be resolved before merging "
11476 "can continue");
11477 } else if (upa.conflicts > 0) {
11478 error = got_error_msg(GOT_ERR_CONFLICTS,
11479 "conflicts must be resolved before merging "
11480 "can continue; changes destined for some "
11481 "files were not yet merged and "
11482 "should be merged manually if required before the "
11483 "merge operation is continued");
11484 } else {
11485 error = got_error_msg(GOT_ERR_CONFLICTS,
11486 "changes destined for some "
11487 "files were not yet merged and should be "
11488 "merged manually if required before the "
11489 "merge operation is continued");
11491 goto done;
11492 } else {
11493 error = got_worktree_merge_commit(&merge_commit_id, worktree,
11494 fileindex, author, NULL, 1, branch_tip, branch_name,
11495 repo, continue_merge ? print_status : NULL, NULL);
11496 if (error)
11497 goto done;
11498 error = got_worktree_merge_complete(worktree, fileindex, repo);
11499 if (error)
11500 goto done;
11501 error = got_object_id_str(&id_str, merge_commit_id);
11502 if (error)
11503 goto done;
11504 printf("Merged %s into %s: %s\n", branch_name,
11505 got_worktree_get_head_ref_name(worktree),
11506 id_str);
11509 done:
11510 free(id_str);
11511 free(merge_commit_id);
11512 free(author);
11513 free(branch_tip);
11514 free(branch_name);
11515 free(yca_id);
11516 if (branch)
11517 got_ref_close(branch);
11518 if (wt_branch)
11519 got_ref_close(wt_branch);
11520 if (worktree)
11521 got_worktree_close(worktree);
11522 if (repo) {
11523 const struct got_error *close_err = got_repo_close(repo);
11524 if (error == NULL)
11525 error = close_err;
11527 return error;
11530 __dead static void
11531 usage_stage(void)
11533 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
11534 "[-S] [file-path ...]\n",
11535 getprogname());
11536 exit(1);
11539 static const struct got_error *
11540 print_stage(void *arg, unsigned char status, unsigned char staged_status,
11541 const char *path, struct got_object_id *blob_id,
11542 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
11543 int dirfd, const char *de_name)
11545 const struct got_error *err = NULL;
11546 char *id_str = NULL;
11548 if (staged_status != GOT_STATUS_ADD &&
11549 staged_status != GOT_STATUS_MODIFY &&
11550 staged_status != GOT_STATUS_DELETE)
11551 return NULL;
11553 if (staged_status == GOT_STATUS_ADD ||
11554 staged_status == GOT_STATUS_MODIFY)
11555 err = got_object_id_str(&id_str, staged_blob_id);
11556 else
11557 err = got_object_id_str(&id_str, blob_id);
11558 if (err)
11559 return err;
11561 printf("%s %c %s\n", id_str, staged_status, path);
11562 free(id_str);
11563 return NULL;
11566 static const struct got_error *
11567 cmd_stage(int argc, char *argv[])
11569 const struct got_error *error = NULL;
11570 struct got_repository *repo = NULL;
11571 struct got_worktree *worktree = NULL;
11572 char *cwd = NULL;
11573 struct got_pathlist_head paths;
11574 struct got_pathlist_entry *pe;
11575 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
11576 FILE *patch_script_file = NULL;
11577 const char *patch_script_path = NULL;
11578 struct choose_patch_arg cpa;
11580 TAILQ_INIT(&paths);
11582 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
11583 switch (ch) {
11584 case 'l':
11585 list_stage = 1;
11586 break;
11587 case 'p':
11588 pflag = 1;
11589 break;
11590 case 'F':
11591 patch_script_path = optarg;
11592 break;
11593 case 'S':
11594 allow_bad_symlinks = 1;
11595 break;
11596 default:
11597 usage_stage();
11598 /* NOTREACHED */
11602 argc -= optind;
11603 argv += optind;
11605 #ifndef PROFILE
11606 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11607 "unveil", NULL) == -1)
11608 err(1, "pledge");
11609 #endif
11610 if (list_stage && (pflag || patch_script_path))
11611 errx(1, "-l option cannot be used with other options");
11612 if (patch_script_path && !pflag)
11613 errx(1, "-F option can only be used together with -p option");
11615 cwd = getcwd(NULL, 0);
11616 if (cwd == NULL) {
11617 error = got_error_from_errno("getcwd");
11618 goto done;
11621 error = got_worktree_open(&worktree, cwd);
11622 if (error) {
11623 if (error->code == GOT_ERR_NOT_WORKTREE)
11624 error = wrap_not_worktree_error(error, "stage", cwd);
11625 goto done;
11628 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11629 NULL);
11630 if (error != NULL)
11631 goto done;
11633 if (patch_script_path) {
11634 patch_script_file = fopen(patch_script_path, "re");
11635 if (patch_script_file == NULL) {
11636 error = got_error_from_errno2("fopen",
11637 patch_script_path);
11638 goto done;
11641 error = apply_unveil(got_repo_get_path(repo), 0,
11642 got_worktree_get_root_path(worktree));
11643 if (error)
11644 goto done;
11646 error = check_merge_in_progress(worktree, repo);
11647 if (error)
11648 goto done;
11650 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11651 if (error)
11652 goto done;
11654 if (list_stage)
11655 error = got_worktree_status(worktree, &paths, repo, 0,
11656 print_stage, NULL, check_cancelled, NULL);
11657 else {
11658 cpa.patch_script_file = patch_script_file;
11659 cpa.action = "stage";
11660 error = got_worktree_stage(worktree, &paths,
11661 pflag ? NULL : print_status, NULL,
11662 pflag ? choose_patch : NULL, &cpa,
11663 allow_bad_symlinks, repo);
11665 done:
11666 if (patch_script_file && fclose(patch_script_file) == EOF &&
11667 error == NULL)
11668 error = got_error_from_errno2("fclose", patch_script_path);
11669 if (repo) {
11670 const struct got_error *close_err = got_repo_close(repo);
11671 if (error == NULL)
11672 error = close_err;
11674 if (worktree)
11675 got_worktree_close(worktree);
11676 TAILQ_FOREACH(pe, &paths, entry)
11677 free((char *)pe->path);
11678 got_pathlist_free(&paths);
11679 free(cwd);
11680 return error;
11683 __dead static void
11684 usage_unstage(void)
11686 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
11687 "[file-path ...]\n",
11688 getprogname());
11689 exit(1);
11693 static const struct got_error *
11694 cmd_unstage(int argc, char *argv[])
11696 const struct got_error *error = NULL;
11697 struct got_repository *repo = NULL;
11698 struct got_worktree *worktree = NULL;
11699 char *cwd = NULL;
11700 struct got_pathlist_head paths;
11701 struct got_pathlist_entry *pe;
11702 int ch, pflag = 0;
11703 struct got_update_progress_arg upa;
11704 FILE *patch_script_file = NULL;
11705 const char *patch_script_path = NULL;
11706 struct choose_patch_arg cpa;
11708 TAILQ_INIT(&paths);
11710 while ((ch = getopt(argc, argv, "pF:")) != -1) {
11711 switch (ch) {
11712 case 'p':
11713 pflag = 1;
11714 break;
11715 case 'F':
11716 patch_script_path = optarg;
11717 break;
11718 default:
11719 usage_unstage();
11720 /* NOTREACHED */
11724 argc -= optind;
11725 argv += optind;
11727 #ifndef PROFILE
11728 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11729 "unveil", NULL) == -1)
11730 err(1, "pledge");
11731 #endif
11732 if (patch_script_path && !pflag)
11733 errx(1, "-F option can only be used together with -p option");
11735 cwd = getcwd(NULL, 0);
11736 if (cwd == NULL) {
11737 error = got_error_from_errno("getcwd");
11738 goto done;
11741 error = got_worktree_open(&worktree, cwd);
11742 if (error) {
11743 if (error->code == GOT_ERR_NOT_WORKTREE)
11744 error = wrap_not_worktree_error(error, "unstage", cwd);
11745 goto done;
11748 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11749 NULL);
11750 if (error != NULL)
11751 goto done;
11753 if (patch_script_path) {
11754 patch_script_file = fopen(patch_script_path, "re");
11755 if (patch_script_file == NULL) {
11756 error = got_error_from_errno2("fopen",
11757 patch_script_path);
11758 goto done;
11762 error = apply_unveil(got_repo_get_path(repo), 0,
11763 got_worktree_get_root_path(worktree));
11764 if (error)
11765 goto done;
11767 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11768 if (error)
11769 goto done;
11771 cpa.patch_script_file = patch_script_file;
11772 cpa.action = "unstage";
11773 memset(&upa, 0, sizeof(upa));
11774 error = got_worktree_unstage(worktree, &paths, update_progress,
11775 &upa, pflag ? choose_patch : NULL, &cpa, repo);
11776 if (!error)
11777 print_merge_progress_stats(&upa);
11778 done:
11779 if (patch_script_file && fclose(patch_script_file) == EOF &&
11780 error == NULL)
11781 error = got_error_from_errno2("fclose", patch_script_path);
11782 if (repo) {
11783 const struct got_error *close_err = got_repo_close(repo);
11784 if (error == NULL)
11785 error = close_err;
11787 if (worktree)
11788 got_worktree_close(worktree);
11789 TAILQ_FOREACH(pe, &paths, entry)
11790 free((char *)pe->path);
11791 got_pathlist_free(&paths);
11792 free(cwd);
11793 return error;
11796 __dead static void
11797 usage_cat(void)
11799 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
11800 "arg1 [arg2 ...]\n", getprogname());
11801 exit(1);
11804 static const struct got_error *
11805 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11807 const struct got_error *err;
11808 struct got_blob_object *blob;
11810 err = got_object_open_as_blob(&blob, repo, id, 8192);
11811 if (err)
11812 return err;
11814 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
11815 got_object_blob_close(blob);
11816 return err;
11819 static const struct got_error *
11820 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11822 const struct got_error *err;
11823 struct got_tree_object *tree;
11824 int nentries, i;
11826 err = got_object_open_as_tree(&tree, repo, id);
11827 if (err)
11828 return err;
11830 nentries = got_object_tree_get_nentries(tree);
11831 for (i = 0; i < nentries; i++) {
11832 struct got_tree_entry *te;
11833 char *id_str;
11834 if (sigint_received || sigpipe_received)
11835 break;
11836 te = got_object_tree_get_entry(tree, i);
11837 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
11838 if (err)
11839 break;
11840 fprintf(outfile, "%s %.7o %s\n", id_str,
11841 got_tree_entry_get_mode(te),
11842 got_tree_entry_get_name(te));
11843 free(id_str);
11846 got_object_tree_close(tree);
11847 return err;
11850 static void
11851 format_gmtoff(char *buf, size_t sz, time_t gmtoff)
11853 long long h, m;
11854 char sign = '+';
11856 if (gmtoff < 0) {
11857 sign = '-';
11858 gmtoff = -gmtoff;
11861 h = (long long)gmtoff / 3600;
11862 m = ((long long)gmtoff - h*3600) / 60;
11863 snprintf(buf, sz, "%c%02lld%02lld", sign, h, m);
11866 static const struct got_error *
11867 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11869 const struct got_error *err;
11870 struct got_commit_object *commit;
11871 const struct got_object_id_queue *parent_ids;
11872 struct got_object_qid *pid;
11873 char *id_str = NULL;
11874 const char *logmsg = NULL;
11875 char gmtoff[6];
11877 err = got_object_open_as_commit(&commit, repo, id);
11878 if (err)
11879 return err;
11881 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
11882 if (err)
11883 goto done;
11885 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
11886 parent_ids = got_object_commit_get_parent_ids(commit);
11887 fprintf(outfile, "numparents %d\n",
11888 got_object_commit_get_nparents(commit));
11889 STAILQ_FOREACH(pid, parent_ids, entry) {
11890 char *pid_str;
11891 err = got_object_id_str(&pid_str, &pid->id);
11892 if (err)
11893 goto done;
11894 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
11895 free(pid_str);
11897 format_gmtoff(gmtoff, sizeof(gmtoff),
11898 got_object_commit_get_author_gmtoff(commit));
11899 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
11900 got_object_commit_get_author(commit),
11901 (long long)got_object_commit_get_author_time(commit),
11902 gmtoff);
11904 format_gmtoff(gmtoff, sizeof(gmtoff),
11905 got_object_commit_get_committer_gmtoff(commit));
11906 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
11907 got_object_commit_get_author(commit),
11908 (long long)got_object_commit_get_committer_time(commit),
11909 gmtoff);
11911 logmsg = got_object_commit_get_logmsg_raw(commit);
11912 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
11913 fprintf(outfile, "%s", logmsg);
11914 done:
11915 free(id_str);
11916 got_object_commit_close(commit);
11917 return err;
11920 static const struct got_error *
11921 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11923 const struct got_error *err;
11924 struct got_tag_object *tag;
11925 char *id_str = NULL;
11926 const char *tagmsg = NULL;
11927 char gmtoff[6];
11929 err = got_object_open_as_tag(&tag, repo, id);
11930 if (err)
11931 return err;
11933 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
11934 if (err)
11935 goto done;
11937 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
11939 switch (got_object_tag_get_object_type(tag)) {
11940 case GOT_OBJ_TYPE_BLOB:
11941 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11942 GOT_OBJ_LABEL_BLOB);
11943 break;
11944 case GOT_OBJ_TYPE_TREE:
11945 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11946 GOT_OBJ_LABEL_TREE);
11947 break;
11948 case GOT_OBJ_TYPE_COMMIT:
11949 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11950 GOT_OBJ_LABEL_COMMIT);
11951 break;
11952 case GOT_OBJ_TYPE_TAG:
11953 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11954 GOT_OBJ_LABEL_TAG);
11955 break;
11956 default:
11957 break;
11960 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
11961 got_object_tag_get_name(tag));
11963 format_gmtoff(gmtoff, sizeof(gmtoff),
11964 got_object_tag_get_tagger_gmtoff(tag));
11965 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
11966 got_object_tag_get_tagger(tag),
11967 (long long)got_object_tag_get_tagger_time(tag),
11968 gmtoff);
11970 tagmsg = got_object_tag_get_message(tag);
11971 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
11972 fprintf(outfile, "%s", tagmsg);
11973 done:
11974 free(id_str);
11975 got_object_tag_close(tag);
11976 return err;
11979 static const struct got_error *
11980 cmd_cat(int argc, char *argv[])
11982 const struct got_error *error;
11983 struct got_repository *repo = NULL;
11984 struct got_worktree *worktree = NULL;
11985 char *cwd = NULL, *repo_path = NULL, *label = NULL;
11986 const char *commit_id_str = NULL;
11987 struct got_object_id *id = NULL, *commit_id = NULL;
11988 struct got_commit_object *commit = NULL;
11989 int ch, obj_type, i, force_path = 0;
11990 struct got_reflist_head refs;
11992 TAILQ_INIT(&refs);
11994 #ifndef PROFILE
11995 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
11996 NULL) == -1)
11997 err(1, "pledge");
11998 #endif
12000 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
12001 switch (ch) {
12002 case 'c':
12003 commit_id_str = optarg;
12004 break;
12005 case 'r':
12006 repo_path = realpath(optarg, NULL);
12007 if (repo_path == NULL)
12008 return got_error_from_errno2("realpath",
12009 optarg);
12010 got_path_strip_trailing_slashes(repo_path);
12011 break;
12012 case 'P':
12013 force_path = 1;
12014 break;
12015 default:
12016 usage_cat();
12017 /* NOTREACHED */
12021 argc -= optind;
12022 argv += optind;
12024 cwd = getcwd(NULL, 0);
12025 if (cwd == NULL) {
12026 error = got_error_from_errno("getcwd");
12027 goto done;
12030 if (repo_path == NULL) {
12031 error = got_worktree_open(&worktree, cwd);
12032 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12033 goto done;
12034 if (worktree) {
12035 repo_path = strdup(
12036 got_worktree_get_repo_path(worktree));
12037 if (repo_path == NULL) {
12038 error = got_error_from_errno("strdup");
12039 goto done;
12042 /* Release work tree lock. */
12043 got_worktree_close(worktree);
12044 worktree = NULL;
12048 if (repo_path == NULL) {
12049 repo_path = strdup(cwd);
12050 if (repo_path == NULL)
12051 return got_error_from_errno("strdup");
12054 error = got_repo_open(&repo, repo_path, NULL);
12055 free(repo_path);
12056 if (error != NULL)
12057 goto done;
12059 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12060 if (error)
12061 goto done;
12063 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12064 if (error)
12065 goto done;
12067 if (commit_id_str == NULL)
12068 commit_id_str = GOT_REF_HEAD;
12069 error = got_repo_match_object_id(&commit_id, NULL,
12070 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12071 if (error)
12072 goto done;
12074 error = got_object_open_as_commit(&commit, repo, commit_id);
12075 if (error)
12076 goto done;
12078 for (i = 0; i < argc; i++) {
12079 if (force_path) {
12080 error = got_object_id_by_path(&id, repo, commit,
12081 argv[i]);
12082 if (error)
12083 break;
12084 } else {
12085 error = got_repo_match_object_id(&id, &label, argv[i],
12086 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12087 repo);
12088 if (error) {
12089 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12090 error->code != GOT_ERR_NOT_REF)
12091 break;
12092 error = got_object_id_by_path(&id, repo,
12093 commit, argv[i]);
12094 if (error)
12095 break;
12099 error = got_object_get_type(&obj_type, repo, id);
12100 if (error)
12101 break;
12103 switch (obj_type) {
12104 case GOT_OBJ_TYPE_BLOB:
12105 error = cat_blob(id, repo, stdout);
12106 break;
12107 case GOT_OBJ_TYPE_TREE:
12108 error = cat_tree(id, repo, stdout);
12109 break;
12110 case GOT_OBJ_TYPE_COMMIT:
12111 error = cat_commit(id, repo, stdout);
12112 break;
12113 case GOT_OBJ_TYPE_TAG:
12114 error = cat_tag(id, repo, stdout);
12115 break;
12116 default:
12117 error = got_error(GOT_ERR_OBJ_TYPE);
12118 break;
12120 if (error)
12121 break;
12122 free(label);
12123 label = NULL;
12124 free(id);
12125 id = NULL;
12127 done:
12128 free(label);
12129 free(id);
12130 free(commit_id);
12131 if (commit)
12132 got_object_commit_close(commit);
12133 if (worktree)
12134 got_worktree_close(worktree);
12135 if (repo) {
12136 const struct got_error *close_err = got_repo_close(repo);
12137 if (error == NULL)
12138 error = close_err;
12140 got_ref_list_free(&refs);
12141 return error;
12144 __dead static void
12145 usage_info(void)
12147 fprintf(stderr, "usage: %s info [path ...]\n",
12148 getprogname());
12149 exit(1);
12152 static const struct got_error *
12153 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12154 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12155 struct got_object_id *commit_id)
12157 const struct got_error *err = NULL;
12158 char *id_str = NULL;
12159 char datebuf[128];
12160 struct tm mytm, *tm;
12161 struct got_pathlist_head *paths = arg;
12162 struct got_pathlist_entry *pe;
12165 * Clear error indication from any of the path arguments which
12166 * would cause this file index entry to be displayed.
12168 TAILQ_FOREACH(pe, paths, entry) {
12169 if (got_path_cmp(path, pe->path, strlen(path),
12170 pe->path_len) == 0 ||
12171 got_path_is_child(path, pe->path, pe->path_len))
12172 pe->data = NULL; /* no error */
12175 printf(GOT_COMMIT_SEP_STR);
12176 if (S_ISLNK(mode))
12177 printf("symlink: %s\n", path);
12178 else if (S_ISREG(mode)) {
12179 printf("file: %s\n", path);
12180 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12181 } else if (S_ISDIR(mode))
12182 printf("directory: %s\n", path);
12183 else
12184 printf("something: %s\n", path);
12186 tm = localtime_r(&mtime, &mytm);
12187 if (tm == NULL)
12188 return NULL;
12189 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12190 return got_error(GOT_ERR_NO_SPACE);
12191 printf("timestamp: %s\n", datebuf);
12193 if (blob_id) {
12194 err = got_object_id_str(&id_str, blob_id);
12195 if (err)
12196 return err;
12197 printf("based on blob: %s\n", id_str);
12198 free(id_str);
12201 if (staged_blob_id) {
12202 err = got_object_id_str(&id_str, staged_blob_id);
12203 if (err)
12204 return err;
12205 printf("based on staged blob: %s\n", id_str);
12206 free(id_str);
12209 if (commit_id) {
12210 err = got_object_id_str(&id_str, commit_id);
12211 if (err)
12212 return err;
12213 printf("based on commit: %s\n", id_str);
12214 free(id_str);
12217 return NULL;
12220 static const struct got_error *
12221 cmd_info(int argc, char *argv[])
12223 const struct got_error *error = NULL;
12224 struct got_worktree *worktree = NULL;
12225 char *cwd = NULL, *id_str = NULL;
12226 struct got_pathlist_head paths;
12227 struct got_pathlist_entry *pe;
12228 char *uuidstr = NULL;
12229 int ch, show_files = 0;
12231 TAILQ_INIT(&paths);
12233 while ((ch = getopt(argc, argv, "")) != -1) {
12234 switch (ch) {
12235 default:
12236 usage_info();
12237 /* NOTREACHED */
12241 argc -= optind;
12242 argv += optind;
12244 #ifndef PROFILE
12245 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12246 NULL) == -1)
12247 err(1, "pledge");
12248 #endif
12249 cwd = getcwd(NULL, 0);
12250 if (cwd == NULL) {
12251 error = got_error_from_errno("getcwd");
12252 goto done;
12255 error = got_worktree_open(&worktree, cwd);
12256 if (error) {
12257 if (error->code == GOT_ERR_NOT_WORKTREE)
12258 error = wrap_not_worktree_error(error, "info", cwd);
12259 goto done;
12262 #ifndef PROFILE
12263 /* Remove "cpath" promise. */
12264 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
12265 NULL) == -1)
12266 err(1, "pledge");
12267 #endif
12268 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
12269 if (error)
12270 goto done;
12272 if (argc >= 1) {
12273 error = get_worktree_paths_from_argv(&paths, argc, argv,
12274 worktree);
12275 if (error)
12276 goto done;
12277 show_files = 1;
12280 error = got_object_id_str(&id_str,
12281 got_worktree_get_base_commit_id(worktree));
12282 if (error)
12283 goto done;
12285 error = got_worktree_get_uuid(&uuidstr, worktree);
12286 if (error)
12287 goto done;
12289 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
12290 printf("work tree base commit: %s\n", id_str);
12291 printf("work tree path prefix: %s\n",
12292 got_worktree_get_path_prefix(worktree));
12293 printf("work tree branch reference: %s\n",
12294 got_worktree_get_head_ref_name(worktree));
12295 printf("work tree UUID: %s\n", uuidstr);
12296 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
12298 if (show_files) {
12299 struct got_pathlist_entry *pe;
12300 TAILQ_FOREACH(pe, &paths, entry) {
12301 if (pe->path_len == 0)
12302 continue;
12304 * Assume this path will fail. This will be corrected
12305 * in print_path_info() in case the path does suceeed.
12307 pe->data = (void *)got_error_path(pe->path,
12308 GOT_ERR_BAD_PATH);
12310 error = got_worktree_path_info(worktree, &paths,
12311 print_path_info, &paths, check_cancelled, NULL);
12312 if (error)
12313 goto done;
12314 TAILQ_FOREACH(pe, &paths, entry) {
12315 if (pe->data != NULL) {
12316 error = pe->data; /* bad path */
12317 break;
12321 done:
12322 TAILQ_FOREACH(pe, &paths, entry)
12323 free((char *)pe->path);
12324 got_pathlist_free(&paths);
12325 free(cwd);
12326 free(id_str);
12327 free(uuidstr);
12328 return error;