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/param.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <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_blame.h"
55 #include "got_privsep.h"
56 #include "got_opentemp.h"
57 #include "got_gotconfig.h"
59 #ifndef nitems
60 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
61 #endif
63 static volatile sig_atomic_t sigint_received;
64 static volatile sig_atomic_t sigpipe_received;
66 static void
67 catch_sigint(int signo)
68 {
69 sigint_received = 1;
70 }
72 static void
73 catch_sigpipe(int signo)
74 {
75 sigpipe_received = 1;
76 }
79 struct got_cmd {
80 const char *cmd_name;
81 const struct got_error *(*cmd_main)(int, char *[]);
82 void (*cmd_usage)(void);
83 const char *cmd_alias;
84 };
86 __dead static void usage(int, int);
87 __dead static void usage_init(void);
88 __dead static void usage_import(void);
89 __dead static void usage_clone(void);
90 __dead static void usage_fetch(void);
91 __dead static void usage_checkout(void);
92 __dead static void usage_update(void);
93 __dead static void usage_log(void);
94 __dead static void usage_diff(void);
95 __dead static void usage_blame(void);
96 __dead static void usage_tree(void);
97 __dead static void usage_status(void);
98 __dead static void usage_ref(void);
99 __dead static void usage_branch(void);
100 __dead static void usage_tag(void);
101 __dead static void usage_add(void);
102 __dead static void usage_remove(void);
103 __dead static void usage_revert(void);
104 __dead static void usage_commit(void);
105 __dead static void usage_cherrypick(void);
106 __dead static void usage_backout(void);
107 __dead static void usage_rebase(void);
108 __dead static void usage_histedit(void);
109 __dead static void usage_integrate(void);
110 __dead static void usage_stage(void);
111 __dead static void usage_unstage(void);
112 __dead static void usage_cat(void);
113 __dead static void usage_info(void);
115 static const struct got_error* cmd_init(int, char *[]);
116 static const struct got_error* cmd_import(int, char *[]);
117 static const struct got_error* cmd_clone(int, char *[]);
118 static const struct got_error* cmd_fetch(int, char *[]);
119 static const struct got_error* cmd_checkout(int, char *[]);
120 static const struct got_error* cmd_update(int, char *[]);
121 static const struct got_error* cmd_log(int, char *[]);
122 static const struct got_error* cmd_diff(int, char *[]);
123 static const struct got_error* cmd_blame(int, char *[]);
124 static const struct got_error* cmd_tree(int, char *[]);
125 static const struct got_error* cmd_status(int, char *[]);
126 static const struct got_error* cmd_ref(int, char *[]);
127 static const struct got_error* cmd_branch(int, char *[]);
128 static const struct got_error* cmd_tag(int, char *[]);
129 static const struct got_error* cmd_add(int, char *[]);
130 static const struct got_error* cmd_remove(int, char *[]);
131 static const struct got_error* cmd_revert(int, char *[]);
132 static const struct got_error* cmd_commit(int, char *[]);
133 static const struct got_error* cmd_cherrypick(int, char *[]);
134 static const struct got_error* cmd_backout(int, char *[]);
135 static const struct got_error* cmd_rebase(int, char *[]);
136 static const struct got_error* cmd_histedit(int, char *[]);
137 static const struct got_error* cmd_integrate(int, char *[]);
138 static const struct got_error* cmd_stage(int, char *[]);
139 static const struct got_error* cmd_unstage(int, char *[]);
140 static const struct got_error* cmd_cat(int, char *[]);
141 static const struct got_error* cmd_info(int, char *[]);
143 static struct got_cmd got_commands[] = {
144 { "init", cmd_init, usage_init, "" },
145 { "import", cmd_import, usage_import, "im" },
146 { "clone", cmd_clone, usage_clone, "cl" },
147 { "fetch", cmd_fetch, usage_fetch, "fe" },
148 { "checkout", cmd_checkout, usage_checkout, "co" },
149 { "update", cmd_update, usage_update, "up" },
150 { "log", cmd_log, usage_log, "" },
151 { "diff", cmd_diff, usage_diff, "di" },
152 { "blame", cmd_blame, usage_blame, "bl" },
153 { "tree", cmd_tree, usage_tree, "tr" },
154 { "status", cmd_status, usage_status, "st" },
155 { "ref", cmd_ref, usage_ref, "" },
156 { "branch", cmd_branch, usage_branch, "br" },
157 { "tag", cmd_tag, usage_tag, "" },
158 { "add", cmd_add, usage_add, "" },
159 { "remove", cmd_remove, usage_remove, "rm" },
160 { "revert", cmd_revert, usage_revert, "rv" },
161 { "commit", cmd_commit, usage_commit, "ci" },
162 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
163 { "backout", cmd_backout, usage_backout, "bo" },
164 { "rebase", cmd_rebase, usage_rebase, "rb" },
165 { "histedit", cmd_histedit, usage_histedit, "he" },
166 { "integrate", cmd_integrate, usage_integrate,"ig" },
167 { "stage", cmd_stage, usage_stage, "sg" },
168 { "unstage", cmd_unstage, usage_unstage, "ug" },
169 { "cat", cmd_cat, usage_cat, "" },
170 { "info", cmd_info, usage_info, "" },
171 };
173 static void
174 list_commands(FILE *fp)
176 size_t i;
178 fprintf(fp, "commands:");
179 for (i = 0; i < nitems(got_commands); i++) {
180 struct got_cmd *cmd = &got_commands[i];
181 fprintf(fp, " %s", cmd->cmd_name);
183 fputc('\n', fp);
186 __dead static void
187 option_conflict(char a, char b)
189 errx(1, "-%c and -%c options are mutually exclusive", a, b);
192 int
193 main(int argc, char *argv[])
195 struct got_cmd *cmd;
196 size_t i;
197 int ch;
198 int hflag = 0, Vflag = 0;
199 static struct option longopts[] = {
200 { "version", no_argument, NULL, 'V' },
201 { NULL, 0, NULL, 0 }
202 };
204 setlocale(LC_CTYPE, "");
206 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
207 switch (ch) {
208 case 'h':
209 hflag = 1;
210 break;
211 case 'V':
212 Vflag = 1;
213 break;
214 default:
215 usage(hflag, 1);
216 /* NOTREACHED */
220 argc -= optind;
221 argv += optind;
222 optind = 1;
223 optreset = 1;
225 if (Vflag) {
226 got_version_print_str();
227 return 0;
230 if (argc <= 0)
231 usage(hflag, hflag ? 0 : 1);
233 signal(SIGINT, catch_sigint);
234 signal(SIGPIPE, catch_sigpipe);
236 for (i = 0; i < nitems(got_commands); i++) {
237 const struct got_error *error;
239 cmd = &got_commands[i];
241 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
242 strcmp(cmd->cmd_alias, argv[0]) != 0)
243 continue;
245 if (hflag)
246 got_commands[i].cmd_usage();
248 error = got_commands[i].cmd_main(argc, argv);
249 if (error && error->code != GOT_ERR_CANCELLED &&
250 error->code != GOT_ERR_PRIVSEP_EXIT &&
251 !(sigpipe_received &&
252 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
253 !(sigint_received &&
254 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
255 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
256 return 1;
259 return 0;
262 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
263 list_commands(stderr);
264 return 1;
267 __dead static void
268 usage(int hflag, int status)
270 FILE *fp = (status == 0) ? stdout : stderr;
272 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
273 getprogname());
274 if (hflag)
275 list_commands(fp);
276 exit(status);
279 static const struct got_error *
280 get_editor(char **abspath)
282 const struct got_error *err = NULL;
283 const char *editor;
285 *abspath = NULL;
287 editor = getenv("VISUAL");
288 if (editor == NULL)
289 editor = getenv("EDITOR");
291 if (editor) {
292 err = got_path_find_prog(abspath, editor);
293 if (err)
294 return err;
297 if (*abspath == NULL) {
298 *abspath = strdup("/bin/ed");
299 if (*abspath == NULL)
300 return got_error_from_errno("strdup");
303 return NULL;
306 static const struct got_error *
307 apply_unveil(const char *repo_path, int repo_read_only,
308 const char *worktree_path)
310 const struct got_error *err;
312 #ifdef PROFILE
313 if (unveil("gmon.out", "rwc") != 0)
314 return got_error_from_errno2("unveil", "gmon.out");
315 #endif
316 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
317 return got_error_from_errno2("unveil", repo_path);
319 if (worktree_path && unveil(worktree_path, "rwc") != 0)
320 return got_error_from_errno2("unveil", worktree_path);
322 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
323 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
325 err = got_privsep_unveil_exec_helpers();
326 if (err != NULL)
327 return err;
329 if (unveil(NULL, NULL) != 0)
330 return got_error_from_errno("unveil");
332 return NULL;
335 __dead static void
336 usage_init(void)
338 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
339 exit(1);
342 static const struct got_error *
343 cmd_init(int argc, char *argv[])
345 const struct got_error *error = NULL;
346 char *repo_path = NULL;
347 int ch;
349 while ((ch = getopt(argc, argv, "")) != -1) {
350 switch (ch) {
351 default:
352 usage_init();
353 /* NOTREACHED */
357 argc -= optind;
358 argv += optind;
360 #ifndef PROFILE
361 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
362 err(1, "pledge");
363 #endif
364 if (argc != 1)
365 usage_init();
367 repo_path = strdup(argv[0]);
368 if (repo_path == NULL)
369 return got_error_from_errno("strdup");
371 got_path_strip_trailing_slashes(repo_path);
373 error = got_path_mkdir(repo_path);
374 if (error &&
375 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
376 goto done;
378 error = apply_unveil(repo_path, 0, NULL);
379 if (error)
380 goto done;
382 error = got_repo_init(repo_path);
383 done:
384 free(repo_path);
385 return error;
388 __dead static void
389 usage_import(void)
391 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
392 "[-r repository-path] [-I pattern] path\n", getprogname());
393 exit(1);
396 int
397 spawn_editor(const char *editor, const char *file)
399 pid_t pid;
400 sig_t sighup, sigint, sigquit;
401 int st = -1;
403 sighup = signal(SIGHUP, SIG_IGN);
404 sigint = signal(SIGINT, SIG_IGN);
405 sigquit = signal(SIGQUIT, SIG_IGN);
407 switch (pid = fork()) {
408 case -1:
409 goto doneediting;
410 case 0:
411 execl(editor, editor, file, (char *)NULL);
412 _exit(127);
415 while (waitpid(pid, &st, 0) == -1)
416 if (errno != EINTR)
417 break;
419 doneediting:
420 (void)signal(SIGHUP, sighup);
421 (void)signal(SIGINT, sigint);
422 (void)signal(SIGQUIT, sigquit);
424 if (!WIFEXITED(st)) {
425 errno = EINTR;
426 return -1;
429 return WEXITSTATUS(st);
432 static const struct got_error *
433 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
434 const char *initial_content, size_t initial_content_len, int check_comments)
436 const struct got_error *err = NULL;
437 char *line = NULL;
438 size_t linesize = 0;
439 ssize_t linelen;
440 struct stat st, st2;
441 FILE *fp = NULL;
442 size_t len, logmsg_len;
443 char *initial_content_stripped = NULL, *buf = NULL, *s;
445 *logmsg = NULL;
447 if (stat(logmsg_path, &st) == -1)
448 return got_error_from_errno2("stat", logmsg_path);
450 if (spawn_editor(editor, logmsg_path) == -1)
451 return got_error_from_errno("failed spawning editor");
453 if (stat(logmsg_path, &st2) == -1)
454 return got_error_from_errno("stat");
456 if (st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
457 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
458 "no changes made to commit message, aborting");
460 /*
461 * Set up a stripped version of the initial content without comments
462 * and blank lines. We need this in order to check if the message
463 * has in fact been edited.
464 */
465 initial_content_stripped = malloc(initial_content_len + 1);
466 if (initial_content_stripped == NULL)
467 return got_error_from_errno("malloc");
468 initial_content_stripped[0] = '\0';
470 buf = strdup(initial_content);
471 if (buf == NULL) {
472 err = got_error_from_errno("strdup");
473 goto done;
475 s = buf;
476 len = 0;
477 while ((line = strsep(&s, "\n")) != NULL) {
478 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
479 continue; /* remove comments and leading empty lines */
480 len = strlcat(initial_content_stripped, line,
481 initial_content_len + 1);
482 if (len >= initial_content_len + 1) {
483 err = got_error(GOT_ERR_NO_SPACE);
484 goto done;
487 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
488 initial_content_stripped[len - 1] = '\0';
489 len--;
492 logmsg_len = st2.st_size;
493 *logmsg = malloc(logmsg_len + 1);
494 if (*logmsg == NULL)
495 return got_error_from_errno("malloc");
496 (*logmsg)[0] = '\0';
498 fp = fopen(logmsg_path, "r");
499 if (fp == NULL) {
500 err = got_error_from_errno("fopen");
501 goto done;
504 len = 0;
505 while ((linelen = getline(&line, &linesize, fp)) != -1) {
506 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
507 continue; /* remove comments and leading empty lines */
508 len = strlcat(*logmsg, line, logmsg_len + 1);
509 if (len >= logmsg_len + 1) {
510 err = got_error(GOT_ERR_NO_SPACE);
511 goto done;
514 free(line);
515 if (ferror(fp)) {
516 err = got_ferror(fp, GOT_ERR_IO);
517 goto done;
519 while (len > 0 && (*logmsg)[len - 1] == '\n') {
520 (*logmsg)[len - 1] = '\0';
521 len--;
524 if (len == 0) {
525 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
526 "commit message cannot be empty, aborting");
527 goto done;
529 if (check_comments && strcmp(*logmsg, initial_content_stripped) == 0)
530 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
531 "no changes made to commit message, aborting");
532 done:
533 free(initial_content_stripped);
534 free(buf);
535 if (fp && fclose(fp) == EOF && err == NULL)
536 err = got_error_from_errno("fclose");
537 if (err) {
538 free(*logmsg);
539 *logmsg = NULL;
541 return err;
544 static const struct got_error *
545 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
546 const char *path_dir, const char *branch_name)
548 char *initial_content = NULL;
549 const struct got_error *err = NULL;
550 int initial_content_len;
551 int fd = -1;
553 initial_content_len = asprintf(&initial_content,
554 "\n# %s to be imported to branch %s\n", path_dir,
555 branch_name);
556 if (initial_content_len == -1)
557 return got_error_from_errno("asprintf");
559 err = got_opentemp_named_fd(logmsg_path, &fd,
560 GOT_TMPDIR_STR "/got-importmsg");
561 if (err)
562 goto done;
564 if (write(fd, initial_content, initial_content_len) == -1) {
565 err = got_error_from_errno2("write", *logmsg_path);
566 goto done;
569 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
570 initial_content_len, 1);
571 done:
572 if (fd != -1 && close(fd) == -1 && err == NULL)
573 err = got_error_from_errno2("close", *logmsg_path);
574 free(initial_content);
575 if (err) {
576 free(*logmsg_path);
577 *logmsg_path = NULL;
579 return err;
582 static const struct got_error *
583 import_progress(void *arg, const char *path)
585 printf("A %s\n", path);
586 return NULL;
589 static const struct got_error *
590 get_author(char **author, struct got_repository *repo,
591 struct got_worktree *worktree)
593 const struct got_error *err = NULL;
594 const char *got_author = NULL, *name, *email;
595 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
597 *author = NULL;
599 if (worktree)
600 worktree_conf = got_worktree_get_gotconfig(worktree);
601 repo_conf = got_repo_get_gotconfig(repo);
603 /*
604 * Priority of potential author information sources, from most
605 * significant to least significant:
606 * 1) work tree's .got/got.conf file
607 * 2) repository's got.conf file
608 * 3) repository's git config file
609 * 4) environment variables
610 * 5) global git config files (in user's home directory or /etc)
611 */
613 if (worktree_conf)
614 got_author = got_gotconfig_get_author(worktree_conf);
615 if (got_author == NULL)
616 got_author = got_gotconfig_get_author(repo_conf);
617 if (got_author == NULL) {
618 name = got_repo_get_gitconfig_author_name(repo);
619 email = got_repo_get_gitconfig_author_email(repo);
620 if (name && email) {
621 if (asprintf(author, "%s <%s>", name, email) == -1)
622 return got_error_from_errno("asprintf");
623 return NULL;
626 got_author = getenv("GOT_AUTHOR");
627 if (got_author == NULL) {
628 name = got_repo_get_global_gitconfig_author_name(repo);
629 email = got_repo_get_global_gitconfig_author_email(
630 repo);
631 if (name && email) {
632 if (asprintf(author, "%s <%s>", name, email)
633 == -1)
634 return got_error_from_errno("asprintf");
635 return NULL;
637 /* TODO: Look up user in password database? */
638 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
642 *author = strdup(got_author);
643 if (*author == NULL)
644 return got_error_from_errno("strdup");
646 /*
647 * Really dumb email address check; we're only doing this to
648 * avoid git's object parser breaking on commits we create.
649 */
650 while (*got_author && *got_author != '<')
651 got_author++;
652 if (*got_author != '<') {
653 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
654 goto done;
656 while (*got_author && *got_author != '@')
657 got_author++;
658 if (*got_author != '@') {
659 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
660 goto done;
662 while (*got_author && *got_author != '>')
663 got_author++;
664 if (*got_author != '>')
665 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
666 done:
667 if (err) {
668 free(*author);
669 *author = NULL;
671 return err;
674 static const struct got_error *
675 get_gitconfig_path(char **gitconfig_path)
677 const char *homedir = getenv("HOME");
679 *gitconfig_path = NULL;
680 if (homedir) {
681 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
682 return got_error_from_errno("asprintf");
685 return NULL;
688 static const struct got_error *
689 cmd_import(int argc, char *argv[])
691 const struct got_error *error = NULL;
692 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
693 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
694 const char *branch_name = "main";
695 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
696 struct got_repository *repo = NULL;
697 struct got_reference *branch_ref = NULL, *head_ref = NULL;
698 struct got_object_id *new_commit_id = NULL;
699 int ch;
700 struct got_pathlist_head ignores;
701 struct got_pathlist_entry *pe;
702 int preserve_logmsg = 0;
704 TAILQ_INIT(&ignores);
706 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
707 switch (ch) {
708 case 'b':
709 branch_name = optarg;
710 break;
711 case 'm':
712 logmsg = strdup(optarg);
713 if (logmsg == NULL) {
714 error = got_error_from_errno("strdup");
715 goto done;
717 break;
718 case 'r':
719 repo_path = realpath(optarg, NULL);
720 if (repo_path == NULL) {
721 error = got_error_from_errno2("realpath",
722 optarg);
723 goto done;
725 break;
726 case 'I':
727 if (optarg[0] == '\0')
728 break;
729 error = got_pathlist_insert(&pe, &ignores, optarg,
730 NULL);
731 if (error)
732 goto done;
733 break;
734 default:
735 usage_import();
736 /* NOTREACHED */
740 argc -= optind;
741 argv += optind;
743 #ifndef PROFILE
744 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
745 "unveil",
746 NULL) == -1)
747 err(1, "pledge");
748 #endif
749 if (argc != 1)
750 usage_import();
752 if (repo_path == NULL) {
753 repo_path = getcwd(NULL, 0);
754 if (repo_path == NULL)
755 return got_error_from_errno("getcwd");
757 got_path_strip_trailing_slashes(repo_path);
758 error = get_gitconfig_path(&gitconfig_path);
759 if (error)
760 goto done;
761 error = got_repo_open(&repo, repo_path, gitconfig_path);
762 if (error)
763 goto done;
765 error = get_author(&author, repo, NULL);
766 if (error)
767 return error;
769 /*
770 * Don't let the user create a branch name with a leading '-'.
771 * While technically a valid reference name, this case is usually
772 * an unintended typo.
773 */
774 if (branch_name[0] == '-')
775 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
777 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
778 error = got_error_from_errno("asprintf");
779 goto done;
782 error = got_ref_open(&branch_ref, repo, refname, 0);
783 if (error) {
784 if (error->code != GOT_ERR_NOT_REF)
785 goto done;
786 } else {
787 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
788 "import target branch already exists");
789 goto done;
792 path_dir = realpath(argv[0], NULL);
793 if (path_dir == NULL) {
794 error = got_error_from_errno2("realpath", argv[0]);
795 goto done;
797 got_path_strip_trailing_slashes(path_dir);
799 /*
800 * unveil(2) traverses exec(2); if an editor is used we have
801 * to apply unveil after the log message has been written.
802 */
803 if (logmsg == NULL || strlen(logmsg) == 0) {
804 error = get_editor(&editor);
805 if (error)
806 goto done;
807 free(logmsg);
808 error = collect_import_msg(&logmsg, &logmsg_path, editor,
809 path_dir, refname);
810 if (error) {
811 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
812 logmsg_path != NULL)
813 preserve_logmsg = 1;
814 goto done;
818 if (unveil(path_dir, "r") != 0) {
819 error = got_error_from_errno2("unveil", path_dir);
820 if (logmsg_path)
821 preserve_logmsg = 1;
822 goto done;
825 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
826 if (error) {
827 if (logmsg_path)
828 preserve_logmsg = 1;
829 goto done;
832 error = got_repo_import(&new_commit_id, path_dir, logmsg,
833 author, &ignores, repo, import_progress, NULL);
834 if (error) {
835 if (logmsg_path)
836 preserve_logmsg = 1;
837 goto done;
840 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
841 if (error) {
842 if (logmsg_path)
843 preserve_logmsg = 1;
844 goto done;
847 error = got_ref_write(branch_ref, repo);
848 if (error) {
849 if (logmsg_path)
850 preserve_logmsg = 1;
851 goto done;
854 error = got_object_id_str(&id_str, new_commit_id);
855 if (error) {
856 if (logmsg_path)
857 preserve_logmsg = 1;
858 goto done;
861 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
862 if (error) {
863 if (error->code != GOT_ERR_NOT_REF) {
864 if (logmsg_path)
865 preserve_logmsg = 1;
866 goto done;
869 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
870 branch_ref);
871 if (error) {
872 if (logmsg_path)
873 preserve_logmsg = 1;
874 goto done;
877 error = got_ref_write(head_ref, repo);
878 if (error) {
879 if (logmsg_path)
880 preserve_logmsg = 1;
881 goto done;
885 printf("Created branch %s with commit %s\n",
886 got_ref_get_name(branch_ref), id_str);
887 done:
888 if (preserve_logmsg) {
889 fprintf(stderr, "%s: log message preserved in %s\n",
890 getprogname(), logmsg_path);
891 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
892 error = got_error_from_errno2("unlink", logmsg_path);
893 free(logmsg);
894 free(logmsg_path);
895 free(repo_path);
896 free(editor);
897 free(refname);
898 free(new_commit_id);
899 free(id_str);
900 free(author);
901 free(gitconfig_path);
902 if (branch_ref)
903 got_ref_close(branch_ref);
904 if (head_ref)
905 got_ref_close(head_ref);
906 return error;
909 __dead static void
910 usage_clone(void)
912 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
913 "[-R reference] repository-url [directory]\n", getprogname());
914 exit(1);
917 struct got_fetch_progress_arg {
918 char last_scaled_size[FMT_SCALED_STRSIZE];
919 int last_p_indexed;
920 int last_p_resolved;
921 int verbosity;
923 struct got_repository *repo;
925 int create_configs;
926 int configs_created;
927 struct {
928 struct got_pathlist_head *symrefs;
929 struct got_pathlist_head *wanted_branches;
930 const char *proto;
931 const char *host;
932 const char *port;
933 const char *remote_repo_path;
934 const char *git_url;
935 int fetch_all_branches;
936 int mirror_references;
937 } config_info;
938 };
940 /* XXX forward declaration */
941 static const struct got_error *
942 create_config_files(const char *proto, const char *host, const char *port,
943 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
944 int mirror_references, struct got_pathlist_head *symrefs,
945 struct got_pathlist_head *wanted_branches, struct got_repository *repo);
947 static const struct got_error *
948 fetch_progress(void *arg, const char *message, off_t packfile_size,
949 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
951 const struct got_error *err = NULL;
952 struct got_fetch_progress_arg *a = arg;
953 char scaled_size[FMT_SCALED_STRSIZE];
954 int p_indexed, p_resolved;
955 int print_size = 0, print_indexed = 0, print_resolved = 0;
957 /*
958 * In order to allow a failed clone to be resumed with 'got fetch'
959 * we try to create configuration files as soon as possible.
960 * Once the server has sent information about its default branch
961 * we have all required information.
962 */
963 if (a->create_configs && !a->configs_created &&
964 !TAILQ_EMPTY(a->config_info.symrefs)) {
965 err = create_config_files(a->config_info.proto,
966 a->config_info.host, a->config_info.port,
967 a->config_info.remote_repo_path,
968 a->config_info.git_url,
969 a->config_info.fetch_all_branches,
970 a->config_info.mirror_references,
971 a->config_info.symrefs,
972 a->config_info.wanted_branches, a->repo);
973 if (err)
974 return err;
975 a->configs_created = 1;
978 if (a->verbosity < 0)
979 return NULL;
981 if (message && message[0] != '\0') {
982 printf("\rserver: %s", message);
983 fflush(stdout);
984 return NULL;
987 if (packfile_size > 0 || nobj_indexed > 0) {
988 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
989 (a->last_scaled_size[0] == '\0' ||
990 strcmp(scaled_size, a->last_scaled_size)) != 0) {
991 print_size = 1;
992 if (strlcpy(a->last_scaled_size, scaled_size,
993 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
994 return got_error(GOT_ERR_NO_SPACE);
996 if (nobj_indexed > 0) {
997 p_indexed = (nobj_indexed * 100) / nobj_total;
998 if (p_indexed != a->last_p_indexed) {
999 a->last_p_indexed = p_indexed;
1000 print_indexed = 1;
1001 print_size = 1;
1004 if (nobj_resolved > 0) {
1005 p_resolved = (nobj_resolved * 100) /
1006 (nobj_total - nobj_loose);
1007 if (p_resolved != a->last_p_resolved) {
1008 a->last_p_resolved = p_resolved;
1009 print_resolved = 1;
1010 print_indexed = 1;
1011 print_size = 1;
1016 if (print_size || print_indexed || print_resolved)
1017 printf("\r");
1018 if (print_size)
1019 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
1020 if (print_indexed)
1021 printf("; indexing %d%%", p_indexed);
1022 if (print_resolved)
1023 printf("; resolving deltas %d%%", p_resolved);
1024 if (print_size || print_indexed || print_resolved)
1025 fflush(stdout);
1027 return NULL;
1030 static const struct got_error *
1031 create_symref(const char *refname, struct got_reference *target_ref,
1032 int verbosity, struct got_repository *repo)
1034 const struct got_error *err;
1035 struct got_reference *head_symref;
1037 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1038 if (err)
1039 return err;
1041 err = got_ref_write(head_symref, repo);
1042 if (err == NULL && verbosity > 0) {
1043 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1044 got_ref_get_name(target_ref));
1046 got_ref_close(head_symref);
1047 return err;
1050 static const struct got_error *
1051 list_remote_refs(struct got_pathlist_head *symrefs,
1052 struct got_pathlist_head *refs)
1054 const struct got_error *err;
1055 struct got_pathlist_entry *pe;
1057 TAILQ_FOREACH(pe, symrefs, entry) {
1058 const char *refname = pe->path;
1059 const char *targetref = pe->data;
1061 printf("%s: %s\n", refname, targetref);
1064 TAILQ_FOREACH(pe, refs, entry) {
1065 const char *refname = pe->path;
1066 struct got_object_id *id = pe->data;
1067 char *id_str;
1069 err = got_object_id_str(&id_str, id);
1070 if (err)
1071 return err;
1072 printf("%s: %s\n", refname, id_str);
1073 free(id_str);
1076 return NULL;
1079 static const struct got_error *
1080 create_ref(const char *refname, struct got_object_id *id,
1081 int verbosity, struct got_repository *repo)
1083 const struct got_error *err = NULL;
1084 struct got_reference *ref;
1085 char *id_str;
1087 err = got_object_id_str(&id_str, id);
1088 if (err)
1089 return err;
1091 err = got_ref_alloc(&ref, refname, id);
1092 if (err)
1093 goto done;
1095 err = got_ref_write(ref, repo);
1096 got_ref_close(ref);
1098 if (err == NULL && verbosity >= 0)
1099 printf("Created reference %s: %s\n", refname, id_str);
1100 done:
1101 free(id_str);
1102 return err;
1105 static int
1106 match_wanted_ref(const char *refname, const char *wanted_ref)
1108 if (strncmp(refname, "refs/", 5) != 0)
1109 return 0;
1110 refname += 5;
1113 * Prevent fetching of references that won't make any
1114 * sense outside of the remote repository's context.
1116 if (strncmp(refname, "got/", 4) == 0)
1117 return 0;
1118 if (strncmp(refname, "remotes/", 8) == 0)
1119 return 0;
1121 if (strncmp(wanted_ref, "refs/", 5) == 0)
1122 wanted_ref += 5;
1124 /* Allow prefix match. */
1125 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1126 return 1;
1128 /* Allow exact match. */
1129 return (strcmp(refname, wanted_ref) == 0);
1132 static int
1133 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1135 struct got_pathlist_entry *pe;
1137 TAILQ_FOREACH(pe, wanted_refs, entry) {
1138 if (match_wanted_ref(refname, pe->path))
1139 return 1;
1142 return 0;
1145 static const struct got_error *
1146 create_wanted_ref(const char *refname, struct got_object_id *id,
1147 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1149 const struct got_error *err;
1150 char *remote_refname;
1152 if (strncmp("refs/", refname, 5) == 0)
1153 refname += 5;
1155 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1156 remote_repo_name, refname) == -1)
1157 return got_error_from_errno("asprintf");
1159 err = create_ref(remote_refname, id, verbosity, repo);
1160 free(remote_refname);
1161 return err;
1164 static const struct got_error *
1165 create_gotconfig(const char *proto, const char *host, const char *port,
1166 const char *remote_repo_path, int fetch_all_branches, int mirror_references,
1167 struct got_repository *repo)
1169 const struct got_error *err = NULL;
1170 char *gotconfig_path = NULL;
1171 char *gotconfig = NULL;
1172 FILE *gotconfig_file = NULL;
1173 ssize_t n;
1175 /* Create got.conf(5). */
1176 gotconfig_path = got_repo_get_path_gotconfig(repo);
1177 if (gotconfig_path == NULL) {
1178 err = got_error_from_errno("got_repo_get_path_gotconfig");
1179 goto done;
1181 gotconfig_file = fopen(gotconfig_path, "a");
1182 if (gotconfig_file == NULL) {
1183 err = got_error_from_errno2("fopen", gotconfig_path);
1184 goto done;
1186 if (asprintf(&gotconfig,
1187 "remote \"%s\" {\n"
1188 "\tserver %s\n"
1189 "\tprotocol %s\n"
1190 "%s%s%s"
1191 "\trepository \"%s\"\n"
1192 "%s"
1193 "}\n",
1194 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1195 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1196 remote_repo_path,
1197 mirror_references ? "\tmirror-references yes\n" : "") == -1) {
1198 err = got_error_from_errno("asprintf");
1199 goto done;
1201 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1202 if (n != strlen(gotconfig)) {
1203 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1204 goto done;
1207 done:
1208 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1209 err = got_error_from_errno2("fclose", gotconfig_path);
1210 free(gotconfig_path);
1211 return err;
1214 static const struct got_error *
1215 create_gitconfig(const char *git_url, const char *default_branch,
1216 int fetch_all_branches, int mirror_references, struct got_repository *repo)
1218 const struct got_error *err = NULL;
1219 char *gitconfig_path = NULL;
1220 char *gitconfig = NULL;
1221 FILE *gitconfig_file = NULL;
1222 ssize_t n;
1224 /* Create a config file Git can understand. */
1225 gitconfig_path = got_repo_get_path_gitconfig(repo);
1226 if (gitconfig_path == NULL) {
1227 err = got_error_from_errno("got_repo_get_path_gitconfig");
1228 goto done;
1230 gitconfig_file = fopen(gitconfig_path, "a");
1231 if (gitconfig_file == NULL) {
1232 err = got_error_from_errno2("fopen", gitconfig_path);
1233 goto done;
1235 if (mirror_references) {
1236 if (asprintf(&gitconfig,
1237 "[remote \"%s\"]\n"
1238 "\turl = %s\n"
1239 "\tfetch = +refs/*:refs/*\n"
1240 "\tmirror = true\n",
1241 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1242 err = got_error_from_errno("asprintf");
1243 goto done;
1245 } else if (fetch_all_branches) {
1246 if (asprintf(&gitconfig,
1247 "[remote \"%s\"]\n"
1248 "\turl = %s\n"
1249 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1250 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1251 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1252 err = got_error_from_errno("asprintf");
1253 goto done;
1255 } else {
1256 const char *branchname;
1259 * If the server specified a default branch, use just that one.
1260 * Otherwise fall back to fetching all branches on next fetch.
1262 if (default_branch) {
1263 branchname = default_branch;
1264 if (strncmp(branchname, "refs/heads/", 11) == 0)
1265 branchname += 11;
1266 } else
1267 branchname = "*"; /* fall back to all branches */
1268 if (asprintf(&gitconfig,
1269 "[remote \"%s\"]\n"
1270 "\turl = %s\n"
1271 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1272 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1273 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1274 branchname) == -1) {
1275 err = got_error_from_errno("asprintf");
1276 goto done;
1279 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1280 if (n != strlen(gitconfig)) {
1281 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1282 goto done;
1284 done:
1285 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1286 err = got_error_from_errno2("fclose", gitconfig_path);
1287 free(gitconfig_path);
1288 return err;
1291 static const struct got_error *
1292 create_config_files(const char *proto, const char *host, const char *port,
1293 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1294 int mirror_references, struct got_pathlist_head *symrefs,
1295 struct got_pathlist_head *wanted_branches, struct got_repository *repo)
1297 const struct got_error *err = NULL;
1298 const char *default_branch = NULL;
1299 struct got_pathlist_entry *pe;
1302 * If we asked for a set of wanted branches then use the first
1303 * one of those.
1305 if (!TAILQ_EMPTY(wanted_branches)) {
1306 pe = TAILQ_FIRST(wanted_branches);
1307 default_branch = pe->path;
1308 } else {
1309 /* First HEAD ref listed by server is the default branch. */
1310 TAILQ_FOREACH(pe, symrefs, entry) {
1311 const char *refname = pe->path;
1312 const char *target = pe->data;
1314 if (strcmp(refname, GOT_REF_HEAD) != 0)
1315 continue;
1317 default_branch = target;
1318 break;
1322 /* Create got.conf(5). */
1323 err = create_gotconfig(proto, host, port, remote_repo_path,
1324 fetch_all_branches, mirror_references, repo);
1325 if (err)
1326 return err;
1328 /* Create a config file Git can understand. */
1329 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1330 mirror_references, repo);
1333 static const struct got_error *
1334 cmd_clone(int argc, char *argv[])
1336 const struct got_error *error = NULL;
1337 const char *uri, *dirname;
1338 char *proto, *host, *port, *repo_name, *server_path;
1339 char *default_destdir = NULL, *id_str = NULL;
1340 const char *repo_path;
1341 struct got_repository *repo = NULL;
1342 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1343 struct got_pathlist_entry *pe;
1344 struct got_object_id *pack_hash = NULL;
1345 int ch, fetchfd = -1, fetchstatus;
1346 pid_t fetchpid = -1;
1347 struct got_fetch_progress_arg fpa;
1348 char *git_url = NULL;
1349 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1350 int list_refs_only = 0;
1352 TAILQ_INIT(&refs);
1353 TAILQ_INIT(&symrefs);
1354 TAILQ_INIT(&wanted_branches);
1355 TAILQ_INIT(&wanted_refs);
1357 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1358 switch (ch) {
1359 case 'a':
1360 fetch_all_branches = 1;
1361 break;
1362 case 'b':
1363 error = got_pathlist_append(&wanted_branches,
1364 optarg, NULL);
1365 if (error)
1366 return error;
1367 break;
1368 case 'l':
1369 list_refs_only = 1;
1370 break;
1371 case 'm':
1372 mirror_references = 1;
1373 break;
1374 case 'v':
1375 if (verbosity < 0)
1376 verbosity = 0;
1377 else if (verbosity < 3)
1378 verbosity++;
1379 break;
1380 case 'q':
1381 verbosity = -1;
1382 break;
1383 case 'R':
1384 error = got_pathlist_append(&wanted_refs,
1385 optarg, NULL);
1386 if (error)
1387 return error;
1388 break;
1389 default:
1390 usage_clone();
1391 break;
1394 argc -= optind;
1395 argv += optind;
1397 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1398 option_conflict('a', 'b');
1399 if (list_refs_only) {
1400 if (!TAILQ_EMPTY(&wanted_branches))
1401 option_conflict('l', 'b');
1402 if (fetch_all_branches)
1403 option_conflict('l', 'a');
1404 if (mirror_references)
1405 option_conflict('l', 'm');
1406 if (verbosity == -1)
1407 option_conflict('l', 'q');
1408 if (!TAILQ_EMPTY(&wanted_refs))
1409 option_conflict('l', 'R');
1412 uri = argv[0];
1414 if (argc == 1)
1415 dirname = NULL;
1416 else if (argc == 2)
1417 dirname = argv[1];
1418 else
1419 usage_clone();
1421 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1422 &repo_name, uri);
1423 if (error)
1424 goto done;
1426 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1427 host, port ? ":" : "", port ? port : "",
1428 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1429 error = got_error_from_errno("asprintf");
1430 goto done;
1433 if (strcmp(proto, "git") == 0) {
1434 #ifndef PROFILE
1435 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1436 "sendfd dns inet unveil", NULL) == -1)
1437 err(1, "pledge");
1438 #endif
1439 } else if (strcmp(proto, "git+ssh") == 0 ||
1440 strcmp(proto, "ssh") == 0) {
1441 #ifndef PROFILE
1442 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1443 "sendfd unveil", NULL) == -1)
1444 err(1, "pledge");
1445 #endif
1446 } else if (strcmp(proto, "http") == 0 ||
1447 strcmp(proto, "git+http") == 0) {
1448 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1449 goto done;
1450 } else {
1451 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1452 goto done;
1454 if (dirname == NULL) {
1455 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1456 error = got_error_from_errno("asprintf");
1457 goto done;
1459 repo_path = default_destdir;
1460 } else
1461 repo_path = dirname;
1463 if (!list_refs_only) {
1464 error = got_path_mkdir(repo_path);
1465 if (error &&
1466 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1467 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1468 goto done;
1469 if (!got_path_dir_is_empty(repo_path)) {
1470 error = got_error_path(repo_path,
1471 GOT_ERR_DIR_NOT_EMPTY);
1472 goto done;
1476 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1477 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1478 error = got_error_from_errno2("unveil",
1479 GOT_FETCH_PATH_SSH);
1480 goto done;
1483 error = apply_unveil(repo_path, 0, NULL);
1484 if (error)
1485 goto done;
1487 if (verbosity >= 0)
1488 printf("Connecting to %s%s%s\n", host,
1489 port ? ":" : "", port ? port : "");
1491 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1492 server_path, verbosity);
1493 if (error)
1494 goto done;
1496 if (!list_refs_only) {
1497 error = got_repo_init(repo_path);
1498 if (error)
1499 goto done;
1500 error = got_repo_open(&repo, repo_path, NULL);
1501 if (error)
1502 goto done;
1505 fpa.last_scaled_size[0] = '\0';
1506 fpa.last_p_indexed = -1;
1507 fpa.last_p_resolved = -1;
1508 fpa.verbosity = verbosity;
1509 fpa.create_configs = 1;
1510 fpa.configs_created = 0;
1511 fpa.repo = repo;
1512 fpa.config_info.symrefs = &symrefs;
1513 fpa.config_info.wanted_branches = &wanted_branches;
1514 fpa.config_info.proto = proto;
1515 fpa.config_info.host = host;
1516 fpa.config_info.port = port;
1517 fpa.config_info.remote_repo_path = server_path;
1518 fpa.config_info.git_url = git_url;
1519 fpa.config_info.fetch_all_branches = fetch_all_branches;
1520 fpa.config_info.mirror_references = mirror_references;
1521 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1522 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1523 fetch_all_branches, &wanted_branches, &wanted_refs,
1524 list_refs_only, verbosity, fetchfd, repo,
1525 fetch_progress, &fpa);
1526 if (error)
1527 goto done;
1529 if (list_refs_only) {
1530 error = list_remote_refs(&symrefs, &refs);
1531 goto done;
1534 error = got_object_id_str(&id_str, pack_hash);
1535 if (error)
1536 goto done;
1537 if (verbosity >= 0)
1538 printf("\nFetched %s.pack\n", id_str);
1539 free(id_str);
1541 /* Set up references provided with the pack file. */
1542 TAILQ_FOREACH(pe, &refs, entry) {
1543 const char *refname = pe->path;
1544 struct got_object_id *id = pe->data;
1545 char *remote_refname;
1547 if (is_wanted_ref(&wanted_refs, refname) &&
1548 !mirror_references) {
1549 error = create_wanted_ref(refname, id,
1550 GOT_FETCH_DEFAULT_REMOTE_NAME,
1551 verbosity - 1, repo);
1552 if (error)
1553 goto done;
1554 continue;
1557 error = create_ref(refname, id, verbosity - 1, repo);
1558 if (error)
1559 goto done;
1561 if (mirror_references)
1562 continue;
1564 if (strncmp("refs/heads/", refname, 11) != 0)
1565 continue;
1567 if (asprintf(&remote_refname,
1568 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1569 refname + 11) == -1) {
1570 error = got_error_from_errno("asprintf");
1571 goto done;
1573 error = create_ref(remote_refname, id, verbosity - 1, repo);
1574 free(remote_refname);
1575 if (error)
1576 goto done;
1579 /* Set the HEAD reference if the server provided one. */
1580 TAILQ_FOREACH(pe, &symrefs, entry) {
1581 struct got_reference *target_ref;
1582 const char *refname = pe->path;
1583 const char *target = pe->data;
1584 char *remote_refname = NULL, *remote_target = NULL;
1586 if (strcmp(refname, GOT_REF_HEAD) != 0)
1587 continue;
1589 error = got_ref_open(&target_ref, repo, target, 0);
1590 if (error) {
1591 if (error->code == GOT_ERR_NOT_REF) {
1592 error = NULL;
1593 continue;
1595 goto done;
1598 error = create_symref(refname, target_ref, verbosity, repo);
1599 got_ref_close(target_ref);
1600 if (error)
1601 goto done;
1603 if (mirror_references)
1604 continue;
1606 if (strncmp("refs/heads/", target, 11) != 0)
1607 continue;
1609 if (asprintf(&remote_refname,
1610 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1611 refname) == -1) {
1612 error = got_error_from_errno("asprintf");
1613 goto done;
1615 if (asprintf(&remote_target,
1616 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1617 target + 11) == -1) {
1618 error = got_error_from_errno("asprintf");
1619 free(remote_refname);
1620 goto done;
1622 error = got_ref_open(&target_ref, repo, remote_target, 0);
1623 if (error) {
1624 free(remote_refname);
1625 free(remote_target);
1626 if (error->code == GOT_ERR_NOT_REF) {
1627 error = NULL;
1628 continue;
1630 goto done;
1632 error = create_symref(remote_refname, target_ref,
1633 verbosity - 1, repo);
1634 free(remote_refname);
1635 free(remote_target);
1636 got_ref_close(target_ref);
1637 if (error)
1638 goto done;
1640 if (pe == NULL) {
1642 * We failed to set the HEAD reference. If we asked for
1643 * a set of wanted branches use the first of one of those
1644 * which could be fetched instead.
1646 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1647 const char *target = pe->path;
1648 struct got_reference *target_ref;
1650 error = got_ref_open(&target_ref, repo, target, 0);
1651 if (error) {
1652 if (error->code == GOT_ERR_NOT_REF) {
1653 error = NULL;
1654 continue;
1656 goto done;
1659 error = create_symref(GOT_REF_HEAD, target_ref,
1660 verbosity, repo);
1661 got_ref_close(target_ref);
1662 if (error)
1663 goto done;
1664 break;
1668 if (verbosity >= 0)
1669 printf("Created %s repository '%s'\n",
1670 mirror_references ? "mirrored" : "cloned", repo_path);
1671 done:
1672 if (fetchpid > 0) {
1673 if (kill(fetchpid, SIGTERM) == -1)
1674 error = got_error_from_errno("kill");
1675 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1676 error = got_error_from_errno("waitpid");
1678 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1679 error = got_error_from_errno("close");
1680 if (repo)
1681 got_repo_close(repo);
1682 TAILQ_FOREACH(pe, &refs, entry) {
1683 free((void *)pe->path);
1684 free(pe->data);
1686 got_pathlist_free(&refs);
1687 TAILQ_FOREACH(pe, &symrefs, entry) {
1688 free((void *)pe->path);
1689 free(pe->data);
1691 got_pathlist_free(&symrefs);
1692 got_pathlist_free(&wanted_branches);
1693 got_pathlist_free(&wanted_refs);
1694 free(pack_hash);
1695 free(proto);
1696 free(host);
1697 free(port);
1698 free(server_path);
1699 free(repo_name);
1700 free(default_destdir);
1701 free(git_url);
1702 return error;
1705 static const struct got_error *
1706 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1707 int replace_tags, int verbosity, struct got_repository *repo)
1709 const struct got_error *err = NULL;
1710 char *new_id_str = NULL;
1711 struct got_object_id *old_id = NULL;
1713 err = got_object_id_str(&new_id_str, new_id);
1714 if (err)
1715 goto done;
1717 if (!replace_tags &&
1718 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1719 err = got_ref_resolve(&old_id, repo, ref);
1720 if (err)
1721 goto done;
1722 if (got_object_id_cmp(old_id, new_id) == 0)
1723 goto done;
1724 if (verbosity >= 0) {
1725 printf("Rejecting update of existing tag %s: %s\n",
1726 got_ref_get_name(ref), new_id_str);
1728 goto done;
1731 if (got_ref_is_symbolic(ref)) {
1732 if (verbosity >= 0) {
1733 printf("Replacing reference %s: %s\n",
1734 got_ref_get_name(ref),
1735 got_ref_get_symref_target(ref));
1737 err = got_ref_change_symref_to_ref(ref, new_id);
1738 if (err)
1739 goto done;
1740 err = got_ref_write(ref, repo);
1741 if (err)
1742 goto done;
1743 } else {
1744 err = got_ref_resolve(&old_id, repo, ref);
1745 if (err)
1746 goto done;
1747 if (got_object_id_cmp(old_id, new_id) == 0)
1748 goto done;
1750 err = got_ref_change_ref(ref, new_id);
1751 if (err)
1752 goto done;
1753 err = got_ref_write(ref, repo);
1754 if (err)
1755 goto done;
1758 if (verbosity >= 0)
1759 printf("Updated %s: %s\n", got_ref_get_name(ref),
1760 new_id_str);
1761 done:
1762 free(old_id);
1763 free(new_id_str);
1764 return err;
1767 static const struct got_error *
1768 update_symref(const char *refname, struct got_reference *target_ref,
1769 int verbosity, struct got_repository *repo)
1771 const struct got_error *err = NULL, *unlock_err;
1772 struct got_reference *symref;
1773 int symref_is_locked = 0;
1775 err = got_ref_open(&symref, repo, refname, 1);
1776 if (err) {
1777 if (err->code != GOT_ERR_NOT_REF)
1778 return err;
1779 err = got_ref_alloc_symref(&symref, refname, target_ref);
1780 if (err)
1781 goto done;
1783 err = got_ref_write(symref, repo);
1784 if (err)
1785 goto done;
1787 if (verbosity >= 0)
1788 printf("Created reference %s: %s\n",
1789 got_ref_get_name(symref),
1790 got_ref_get_symref_target(symref));
1791 } else {
1792 symref_is_locked = 1;
1794 if (strcmp(got_ref_get_symref_target(symref),
1795 got_ref_get_name(target_ref)) == 0)
1796 goto done;
1798 err = got_ref_change_symref(symref,
1799 got_ref_get_name(target_ref));
1800 if (err)
1801 goto done;
1803 err = got_ref_write(symref, repo);
1804 if (err)
1805 goto done;
1807 if (verbosity >= 0)
1808 printf("Updated %s: %s\n", got_ref_get_name(symref),
1809 got_ref_get_symref_target(symref));
1812 done:
1813 if (symref_is_locked) {
1814 unlock_err = got_ref_unlock(symref);
1815 if (unlock_err && err == NULL)
1816 err = unlock_err;
1818 got_ref_close(symref);
1819 return err;
1822 __dead static void
1823 usage_fetch(void)
1825 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1826 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1827 "[remote-repository-name]\n",
1828 getprogname());
1829 exit(1);
1832 static const struct got_error *
1833 delete_missing_ref(struct got_reference *ref,
1834 int verbosity, struct got_repository *repo)
1836 const struct got_error *err = NULL;
1837 struct got_object_id *id = NULL;
1838 char *id_str = NULL;
1840 if (got_ref_is_symbolic(ref)) {
1841 err = got_ref_delete(ref, repo);
1842 if (err)
1843 return err;
1844 if (verbosity >= 0) {
1845 printf("Deleted reference %s: %s\n",
1846 got_ref_get_name(ref),
1847 got_ref_get_symref_target(ref));
1849 } else {
1850 err = got_ref_resolve(&id, repo, ref);
1851 if (err)
1852 return err;
1853 err = got_object_id_str(&id_str, id);
1854 if (err)
1855 goto done;
1857 err = got_ref_delete(ref, repo);
1858 if (err)
1859 goto done;
1860 if (verbosity >= 0) {
1861 printf("Deleted reference %s: %s\n",
1862 got_ref_get_name(ref), id_str);
1865 done:
1866 free(id);
1867 free(id_str);
1868 return NULL;
1871 static const struct got_error *
1872 delete_missing_refs(struct got_pathlist_head *their_refs,
1873 struct got_pathlist_head *their_symrefs,
1874 const struct got_remote_repo *remote,
1875 int verbosity, struct got_repository *repo)
1877 const struct got_error *err = NULL, *unlock_err;
1878 struct got_reflist_head my_refs;
1879 struct got_reflist_entry *re;
1880 struct got_pathlist_entry *pe;
1881 char *remote_namespace = NULL;
1882 char *local_refname = NULL;
1884 SIMPLEQ_INIT(&my_refs);
1886 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
1887 == -1)
1888 return got_error_from_errno("asprintf");
1890 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1891 if (err)
1892 goto done;
1894 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1895 const char *refname = got_ref_get_name(re->ref);
1897 if (!remote->mirror_references) {
1898 if (strncmp(refname, remote_namespace,
1899 strlen(remote_namespace)) == 0) {
1900 if (strcmp(refname + strlen(remote_namespace),
1901 GOT_REF_HEAD) == 0)
1902 continue;
1903 if (asprintf(&local_refname, "refs/heads/%s",
1904 refname + strlen(remote_namespace)) == -1) {
1905 err = got_error_from_errno("asprintf");
1906 goto done;
1908 } else if (strncmp(refname, "refs/tags/", 10) != 0)
1909 continue;
1912 TAILQ_FOREACH(pe, their_refs, entry) {
1913 if (strcmp(local_refname, pe->path) == 0)
1914 break;
1916 if (pe != NULL)
1917 continue;
1919 TAILQ_FOREACH(pe, their_symrefs, entry) {
1920 if (strcmp(local_refname, pe->path) == 0)
1921 break;
1923 if (pe != NULL)
1924 continue;
1926 err = delete_missing_ref(re->ref, verbosity, repo);
1927 if (err)
1928 break;
1930 if (local_refname) {
1931 struct got_reference *ref;
1932 err = got_ref_open(&ref, repo, local_refname, 1);
1933 if (err) {
1934 if (err->code != GOT_ERR_NOT_REF)
1935 break;
1936 free(local_refname);
1937 local_refname = NULL;
1938 continue;
1940 err = delete_missing_ref(ref, verbosity, repo);
1941 if (err)
1942 break;
1943 unlock_err = got_ref_unlock(ref);
1944 got_ref_close(ref);
1945 if (unlock_err && err == NULL) {
1946 err = unlock_err;
1947 break;
1950 free(local_refname);
1951 local_refname = NULL;
1954 done:
1955 free(remote_namespace);
1956 free(local_refname);
1957 return err;
1960 static const struct got_error *
1961 update_wanted_ref(const char *refname, struct got_object_id *id,
1962 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1964 const struct got_error *err, *unlock_err;
1965 char *remote_refname;
1966 struct got_reference *ref;
1968 if (strncmp("refs/", refname, 5) == 0)
1969 refname += 5;
1971 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1972 remote_repo_name, refname) == -1)
1973 return got_error_from_errno("asprintf");
1975 err = got_ref_open(&ref, repo, remote_refname, 1);
1976 if (err) {
1977 if (err->code != GOT_ERR_NOT_REF)
1978 goto done;
1979 err = create_ref(remote_refname, id, verbosity, repo);
1980 } else {
1981 err = update_ref(ref, id, 0, verbosity, repo);
1982 unlock_err = got_ref_unlock(ref);
1983 if (unlock_err && err == NULL)
1984 err = unlock_err;
1985 got_ref_close(ref);
1987 done:
1988 free(remote_refname);
1989 return err;
1992 static const struct got_error *
1993 cmd_fetch(int argc, char *argv[])
1995 const struct got_error *error = NULL, *unlock_err;
1996 char *cwd = NULL, *repo_path = NULL;
1997 const char *remote_name;
1998 char *proto = NULL, *host = NULL, *port = NULL;
1999 char *repo_name = NULL, *server_path = NULL;
2000 const struct got_remote_repo *remotes, *remote = NULL;
2001 int nremotes;
2002 char *id_str = NULL;
2003 struct got_repository *repo = NULL;
2004 struct got_worktree *worktree = NULL;
2005 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2006 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2007 struct got_pathlist_entry *pe;
2008 struct got_object_id *pack_hash = NULL;
2009 int i, ch, fetchfd = -1, fetchstatus;
2010 pid_t fetchpid = -1;
2011 struct got_fetch_progress_arg fpa;
2012 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2013 int delete_refs = 0, replace_tags = 0;
2015 TAILQ_INIT(&refs);
2016 TAILQ_INIT(&symrefs);
2017 TAILQ_INIT(&wanted_branches);
2018 TAILQ_INIT(&wanted_refs);
2020 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
2021 switch (ch) {
2022 case 'a':
2023 fetch_all_branches = 1;
2024 break;
2025 case 'b':
2026 error = got_pathlist_append(&wanted_branches,
2027 optarg, NULL);
2028 if (error)
2029 return error;
2030 break;
2031 case 'd':
2032 delete_refs = 1;
2033 break;
2034 case 'l':
2035 list_refs_only = 1;
2036 break;
2037 case 'r':
2038 repo_path = realpath(optarg, NULL);
2039 if (repo_path == NULL)
2040 return got_error_from_errno2("realpath",
2041 optarg);
2042 got_path_strip_trailing_slashes(repo_path);
2043 break;
2044 case 't':
2045 replace_tags = 1;
2046 break;
2047 case 'v':
2048 if (verbosity < 0)
2049 verbosity = 0;
2050 else if (verbosity < 3)
2051 verbosity++;
2052 break;
2053 case 'q':
2054 verbosity = -1;
2055 break;
2056 case 'R':
2057 error = got_pathlist_append(&wanted_refs,
2058 optarg, NULL);
2059 if (error)
2060 return error;
2061 break;
2062 default:
2063 usage_fetch();
2064 break;
2067 argc -= optind;
2068 argv += optind;
2070 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2071 option_conflict('a', 'b');
2072 if (list_refs_only) {
2073 if (!TAILQ_EMPTY(&wanted_branches))
2074 option_conflict('l', 'b');
2075 if (fetch_all_branches)
2076 option_conflict('l', 'a');
2077 if (delete_refs)
2078 option_conflict('l', 'd');
2079 if (verbosity == -1)
2080 option_conflict('l', 'q');
2083 if (argc == 0)
2084 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2085 else if (argc == 1)
2086 remote_name = argv[0];
2087 else
2088 usage_fetch();
2090 cwd = getcwd(NULL, 0);
2091 if (cwd == NULL) {
2092 error = got_error_from_errno("getcwd");
2093 goto done;
2096 if (repo_path == NULL) {
2097 error = got_worktree_open(&worktree, cwd);
2098 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2099 goto done;
2100 else
2101 error = NULL;
2102 if (worktree) {
2103 repo_path =
2104 strdup(got_worktree_get_repo_path(worktree));
2105 if (repo_path == NULL)
2106 error = got_error_from_errno("strdup");
2107 if (error)
2108 goto done;
2109 } else {
2110 repo_path = strdup(cwd);
2111 if (repo_path == NULL) {
2112 error = got_error_from_errno("strdup");
2113 goto done;
2118 error = got_repo_open(&repo, repo_path, NULL);
2119 if (error)
2120 goto done;
2122 if (worktree) {
2123 worktree_conf = got_worktree_get_gotconfig(worktree);
2124 if (worktree_conf) {
2125 got_gotconfig_get_remotes(&nremotes, &remotes,
2126 worktree_conf);
2127 for (i = 0; i < nremotes; i++) {
2128 if (strcmp(remotes[i].name, remote_name) == 0) {
2129 remote = &remotes[i];
2130 break;
2135 if (remote == NULL) {
2136 repo_conf = got_repo_get_gotconfig(repo);
2137 if (repo_conf) {
2138 got_gotconfig_get_remotes(&nremotes, &remotes,
2139 repo_conf);
2140 for (i = 0; i < nremotes; i++) {
2141 if (strcmp(remotes[i].name, remote_name) == 0) {
2142 remote = &remotes[i];
2143 break;
2148 if (remote == NULL) {
2149 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2150 for (i = 0; i < nremotes; i++) {
2151 if (strcmp(remotes[i].name, remote_name) == 0) {
2152 remote = &remotes[i];
2153 break;
2157 if (remote == NULL) {
2158 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2159 goto done;
2162 if (TAILQ_EMPTY(&wanted_branches) && remote->nbranches > 0) {
2163 for (i = 0; i < remote->nbranches; i++) {
2164 got_pathlist_append(&wanted_branches,
2165 remote->branches[i], NULL);
2170 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
2171 &repo_name, remote->url);
2172 if (error)
2173 goto done;
2175 if (strcmp(proto, "git") == 0) {
2176 #ifndef PROFILE
2177 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2178 "sendfd dns inet unveil", NULL) == -1)
2179 err(1, "pledge");
2180 #endif
2181 } else if (strcmp(proto, "git+ssh") == 0 ||
2182 strcmp(proto, "ssh") == 0) {
2183 #ifndef PROFILE
2184 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2185 "sendfd unveil", NULL) == -1)
2186 err(1, "pledge");
2187 #endif
2188 } else if (strcmp(proto, "http") == 0 ||
2189 strcmp(proto, "git+http") == 0) {
2190 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2191 goto done;
2192 } else {
2193 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2194 goto done;
2197 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
2198 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
2199 error = got_error_from_errno2("unveil",
2200 GOT_FETCH_PATH_SSH);
2201 goto done;
2204 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2205 if (error)
2206 goto done;
2208 if (verbosity >= 0)
2209 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2210 port ? ":" : "", port ? port : "");
2212 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2213 server_path, verbosity);
2214 if (error)
2215 goto done;
2217 fpa.last_scaled_size[0] = '\0';
2218 fpa.last_p_indexed = -1;
2219 fpa.last_p_resolved = -1;
2220 fpa.verbosity = verbosity;
2221 fpa.repo = repo;
2222 fpa.create_configs = 0;
2223 fpa.configs_created = 0;
2224 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2225 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2226 remote->mirror_references, fetch_all_branches, &wanted_branches,
2227 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2228 fetch_progress, &fpa);
2229 if (error)
2230 goto done;
2232 if (list_refs_only) {
2233 error = list_remote_refs(&symrefs, &refs);
2234 goto done;
2237 if (pack_hash == NULL) {
2238 if (verbosity >= 0)
2239 printf("Already up-to-date\n");
2240 } else if (verbosity >= 0) {
2241 error = got_object_id_str(&id_str, pack_hash);
2242 if (error)
2243 goto done;
2244 printf("\nFetched %s.pack\n", id_str);
2245 free(id_str);
2246 id_str = NULL;
2249 /* Update references provided with the pack file. */
2250 TAILQ_FOREACH(pe, &refs, entry) {
2251 const char *refname = pe->path;
2252 struct got_object_id *id = pe->data;
2253 struct got_reference *ref;
2254 char *remote_refname;
2256 if (is_wanted_ref(&wanted_refs, refname) &&
2257 !remote->mirror_references) {
2258 error = update_wanted_ref(refname, id,
2259 remote->name, verbosity, repo);
2260 if (error)
2261 goto done;
2262 continue;
2265 if (remote->mirror_references ||
2266 strncmp("refs/tags/", refname, 10) == 0) {
2267 error = got_ref_open(&ref, repo, refname, 1);
2268 if (error) {
2269 if (error->code != GOT_ERR_NOT_REF)
2270 goto done;
2271 error = create_ref(refname, id, verbosity,
2272 repo);
2273 if (error)
2274 goto done;
2275 } else {
2276 error = update_ref(ref, id, replace_tags,
2277 verbosity, repo);
2278 unlock_err = got_ref_unlock(ref);
2279 if (unlock_err && error == NULL)
2280 error = unlock_err;
2281 got_ref_close(ref);
2282 if (error)
2283 goto done;
2285 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2286 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2287 remote_name, refname + 11) == -1) {
2288 error = got_error_from_errno("asprintf");
2289 goto done;
2292 error = got_ref_open(&ref, repo, remote_refname, 1);
2293 if (error) {
2294 if (error->code != GOT_ERR_NOT_REF)
2295 goto done;
2296 error = create_ref(remote_refname, id,
2297 verbosity, repo);
2298 if (error)
2299 goto done;
2300 } else {
2301 error = update_ref(ref, id, replace_tags,
2302 verbosity, repo);
2303 unlock_err = got_ref_unlock(ref);
2304 if (unlock_err && error == NULL)
2305 error = unlock_err;
2306 got_ref_close(ref);
2307 if (error)
2308 goto done;
2311 /* Also create a local branch if none exists yet. */
2312 error = got_ref_open(&ref, repo, refname, 1);
2313 if (error) {
2314 if (error->code != GOT_ERR_NOT_REF)
2315 goto done;
2316 error = create_ref(refname, id, verbosity,
2317 repo);
2318 if (error)
2319 goto done;
2320 } else {
2321 unlock_err = got_ref_unlock(ref);
2322 if (unlock_err && error == NULL)
2323 error = unlock_err;
2324 got_ref_close(ref);
2328 if (delete_refs) {
2329 error = delete_missing_refs(&refs, &symrefs, remote,
2330 verbosity, repo);
2331 if (error)
2332 goto done;
2335 if (!remote->mirror_references) {
2336 /* Update remote HEAD reference if the server provided one. */
2337 TAILQ_FOREACH(pe, &symrefs, entry) {
2338 struct got_reference *target_ref;
2339 const char *refname = pe->path;
2340 const char *target = pe->data;
2341 char *remote_refname = NULL, *remote_target = NULL;
2343 if (strcmp(refname, GOT_REF_HEAD) != 0)
2344 continue;
2346 if (strncmp("refs/heads/", target, 11) != 0)
2347 continue;
2349 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2350 remote->name, refname) == -1) {
2351 error = got_error_from_errno("asprintf");
2352 goto done;
2354 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2355 remote->name, target + 11) == -1) {
2356 error = got_error_from_errno("asprintf");
2357 free(remote_refname);
2358 goto done;
2361 error = got_ref_open(&target_ref, repo, remote_target,
2362 0);
2363 if (error) {
2364 free(remote_refname);
2365 free(remote_target);
2366 if (error->code == GOT_ERR_NOT_REF) {
2367 error = NULL;
2368 continue;
2370 goto done;
2372 error = update_symref(remote_refname, target_ref,
2373 verbosity, repo);
2374 free(remote_refname);
2375 free(remote_target);
2376 got_ref_close(target_ref);
2377 if (error)
2378 goto done;
2381 done:
2382 if (fetchpid > 0) {
2383 if (kill(fetchpid, SIGTERM) == -1)
2384 error = got_error_from_errno("kill");
2385 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2386 error = got_error_from_errno("waitpid");
2388 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2389 error = got_error_from_errno("close");
2390 if (repo)
2391 got_repo_close(repo);
2392 if (worktree)
2393 got_worktree_close(worktree);
2394 TAILQ_FOREACH(pe, &refs, entry) {
2395 free((void *)pe->path);
2396 free(pe->data);
2398 got_pathlist_free(&refs);
2399 TAILQ_FOREACH(pe, &symrefs, entry) {
2400 free((void *)pe->path);
2401 free(pe->data);
2403 got_pathlist_free(&symrefs);
2404 got_pathlist_free(&wanted_branches);
2405 got_pathlist_free(&wanted_refs);
2406 free(id_str);
2407 free(cwd);
2408 free(repo_path);
2409 free(pack_hash);
2410 free(proto);
2411 free(host);
2412 free(port);
2413 free(server_path);
2414 free(repo_name);
2415 return error;
2419 __dead static void
2420 usage_checkout(void)
2422 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2423 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2424 exit(1);
2427 static void
2428 show_worktree_base_ref_warning(void)
2430 fprintf(stderr, "%s: warning: could not create a reference "
2431 "to the work tree's base commit; the commit could be "
2432 "garbage-collected by Git; making the repository "
2433 "writable and running 'got update' will prevent this\n",
2434 getprogname());
2437 struct got_checkout_progress_arg {
2438 const char *worktree_path;
2439 int had_base_commit_ref_error;
2442 static const struct got_error *
2443 checkout_progress(void *arg, unsigned char status, const char *path)
2445 struct got_checkout_progress_arg *a = arg;
2447 /* Base commit bump happens silently. */
2448 if (status == GOT_STATUS_BUMP_BASE)
2449 return NULL;
2451 if (status == GOT_STATUS_BASE_REF_ERR) {
2452 a->had_base_commit_ref_error = 1;
2453 return NULL;
2456 while (path[0] == '/')
2457 path++;
2459 printf("%c %s/%s\n", status, a->worktree_path, path);
2460 return NULL;
2463 static const struct got_error *
2464 check_cancelled(void *arg)
2466 if (sigint_received || sigpipe_received)
2467 return got_error(GOT_ERR_CANCELLED);
2468 return NULL;
2471 static const struct got_error *
2472 check_linear_ancestry(struct got_object_id *commit_id,
2473 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2474 struct got_repository *repo)
2476 const struct got_error *err = NULL;
2477 struct got_object_id *yca_id;
2479 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2480 commit_id, base_commit_id, repo, check_cancelled, NULL);
2481 if (err)
2482 return err;
2484 if (yca_id == NULL)
2485 return got_error(GOT_ERR_ANCESTRY);
2488 * Require a straight line of history between the target commit
2489 * and the work tree's base commit.
2491 * Non-linear situations such as this require a rebase:
2493 * (commit) D F (base_commit)
2494 * \ /
2495 * C E
2496 * \ /
2497 * B (yca)
2498 * |
2499 * A
2501 * 'got update' only handles linear cases:
2502 * Update forwards in time: A (base/yca) - B - C - D (commit)
2503 * Update backwards in time: D (base) - C - B - A (commit/yca)
2505 if (allow_forwards_in_time_only) {
2506 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2507 return got_error(GOT_ERR_ANCESTRY);
2508 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2509 got_object_id_cmp(base_commit_id, yca_id) != 0)
2510 return got_error(GOT_ERR_ANCESTRY);
2512 free(yca_id);
2513 return NULL;
2516 static const struct got_error *
2517 check_same_branch(struct got_object_id *commit_id,
2518 struct got_reference *head_ref, struct got_object_id *yca_id,
2519 struct got_repository *repo)
2521 const struct got_error *err = NULL;
2522 struct got_commit_graph *graph = NULL;
2523 struct got_object_id *head_commit_id = NULL;
2524 int is_same_branch = 0;
2526 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2527 if (err)
2528 goto done;
2530 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2531 is_same_branch = 1;
2532 goto done;
2534 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2535 is_same_branch = 1;
2536 goto done;
2539 err = got_commit_graph_open(&graph, "/", 1);
2540 if (err)
2541 goto done;
2543 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2544 check_cancelled, NULL);
2545 if (err)
2546 goto done;
2548 for (;;) {
2549 struct got_object_id *id;
2550 err = got_commit_graph_iter_next(&id, graph, repo,
2551 check_cancelled, NULL);
2552 if (err) {
2553 if (err->code == GOT_ERR_ITER_COMPLETED)
2554 err = NULL;
2555 break;
2558 if (id) {
2559 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2560 break;
2561 if (got_object_id_cmp(id, commit_id) == 0) {
2562 is_same_branch = 1;
2563 break;
2567 done:
2568 if (graph)
2569 got_commit_graph_close(graph);
2570 free(head_commit_id);
2571 if (!err && !is_same_branch)
2572 err = got_error(GOT_ERR_ANCESTRY);
2573 return err;
2576 static const struct got_error *
2577 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2579 static char msg[512];
2580 const char *branch_name;
2582 if (got_ref_is_symbolic(ref))
2583 branch_name = got_ref_get_symref_target(ref);
2584 else
2585 branch_name = got_ref_get_name(ref);
2587 if (strncmp("refs/heads/", branch_name, 11) == 0)
2588 branch_name += 11;
2590 snprintf(msg, sizeof(msg),
2591 "target commit is not contained in branch '%s'; "
2592 "the branch to use must be specified with -b; "
2593 "if necessary a new branch can be created for "
2594 "this commit with 'got branch -c %s BRANCH_NAME'",
2595 branch_name, commit_id_str);
2597 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2600 static const struct got_error *
2601 cmd_checkout(int argc, char *argv[])
2603 const struct got_error *error = NULL;
2604 struct got_repository *repo = NULL;
2605 struct got_reference *head_ref = NULL;
2606 struct got_worktree *worktree = NULL;
2607 char *repo_path = NULL;
2608 char *worktree_path = NULL;
2609 const char *path_prefix = "";
2610 const char *branch_name = GOT_REF_HEAD;
2611 char *commit_id_str = NULL;
2612 char *cwd = NULL;
2613 int ch, same_path_prefix, allow_nonempty = 0;
2614 struct got_pathlist_head paths;
2615 struct got_checkout_progress_arg cpa;
2617 TAILQ_INIT(&paths);
2619 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2620 switch (ch) {
2621 case 'b':
2622 branch_name = optarg;
2623 break;
2624 case 'c':
2625 commit_id_str = strdup(optarg);
2626 if (commit_id_str == NULL)
2627 return got_error_from_errno("strdup");
2628 break;
2629 case 'E':
2630 allow_nonempty = 1;
2631 break;
2632 case 'p':
2633 path_prefix = optarg;
2634 break;
2635 default:
2636 usage_checkout();
2637 /* NOTREACHED */
2641 argc -= optind;
2642 argv += optind;
2644 #ifndef PROFILE
2645 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2646 "unveil", NULL) == -1)
2647 err(1, "pledge");
2648 #endif
2649 if (argc == 1) {
2650 char *base, *dotgit;
2651 const char *path;
2652 repo_path = realpath(argv[0], NULL);
2653 if (repo_path == NULL)
2654 return got_error_from_errno2("realpath", argv[0]);
2655 cwd = getcwd(NULL, 0);
2656 if (cwd == NULL) {
2657 error = got_error_from_errno("getcwd");
2658 goto done;
2660 if (path_prefix[0])
2661 path = path_prefix;
2662 else
2663 path = repo_path;
2664 error = got_path_basename(&base, path);
2665 if (error)
2666 goto done;
2667 dotgit = strstr(base, ".git");
2668 if (dotgit)
2669 *dotgit = '\0';
2670 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2671 error = got_error_from_errno("asprintf");
2672 free(base);
2673 goto done;
2675 free(base);
2676 } else if (argc == 2) {
2677 repo_path = realpath(argv[0], NULL);
2678 if (repo_path == NULL) {
2679 error = got_error_from_errno2("realpath", argv[0]);
2680 goto done;
2682 worktree_path = realpath(argv[1], NULL);
2683 if (worktree_path == NULL) {
2684 if (errno != ENOENT) {
2685 error = got_error_from_errno2("realpath",
2686 argv[1]);
2687 goto done;
2689 worktree_path = strdup(argv[1]);
2690 if (worktree_path == NULL) {
2691 error = got_error_from_errno("strdup");
2692 goto done;
2695 } else
2696 usage_checkout();
2698 got_path_strip_trailing_slashes(repo_path);
2699 got_path_strip_trailing_slashes(worktree_path);
2701 error = got_repo_open(&repo, repo_path, NULL);
2702 if (error != NULL)
2703 goto done;
2705 /* Pre-create work tree path for unveil(2) */
2706 error = got_path_mkdir(worktree_path);
2707 if (error) {
2708 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2709 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2710 goto done;
2711 if (!allow_nonempty &&
2712 !got_path_dir_is_empty(worktree_path)) {
2713 error = got_error_path(worktree_path,
2714 GOT_ERR_DIR_NOT_EMPTY);
2715 goto done;
2719 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2720 if (error)
2721 goto done;
2723 error = got_ref_open(&head_ref, repo, branch_name, 0);
2724 if (error != NULL)
2725 goto done;
2727 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2728 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2729 goto done;
2731 error = got_worktree_open(&worktree, worktree_path);
2732 if (error != NULL)
2733 goto done;
2735 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2736 path_prefix);
2737 if (error != NULL)
2738 goto done;
2739 if (!same_path_prefix) {
2740 error = got_error(GOT_ERR_PATH_PREFIX);
2741 goto done;
2744 if (commit_id_str) {
2745 struct got_object_id *commit_id;
2746 struct got_reflist_head refs;
2747 SIMPLEQ_INIT(&refs);
2748 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2749 NULL);
2750 if (error)
2751 goto done;
2752 error = got_repo_match_object_id(&commit_id, NULL,
2753 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2754 got_ref_list_free(&refs);
2755 if (error)
2756 goto done;
2757 error = check_linear_ancestry(commit_id,
2758 got_worktree_get_base_commit_id(worktree), 0, repo);
2759 if (error != NULL) {
2760 free(commit_id);
2761 if (error->code == GOT_ERR_ANCESTRY) {
2762 error = checkout_ancestry_error(
2763 head_ref, commit_id_str);
2765 goto done;
2767 error = check_same_branch(commit_id, head_ref, NULL, repo);
2768 if (error) {
2769 if (error->code == GOT_ERR_ANCESTRY) {
2770 error = checkout_ancestry_error(
2771 head_ref, commit_id_str);
2773 goto done;
2775 error = got_worktree_set_base_commit_id(worktree, repo,
2776 commit_id);
2777 free(commit_id);
2778 if (error)
2779 goto done;
2782 error = got_pathlist_append(&paths, "", NULL);
2783 if (error)
2784 goto done;
2785 cpa.worktree_path = worktree_path;
2786 cpa.had_base_commit_ref_error = 0;
2787 error = got_worktree_checkout_files(worktree, &paths, repo,
2788 checkout_progress, &cpa, check_cancelled, NULL);
2789 if (error != NULL)
2790 goto done;
2792 printf("Now shut up and hack\n");
2793 if (cpa.had_base_commit_ref_error)
2794 show_worktree_base_ref_warning();
2795 done:
2796 got_pathlist_free(&paths);
2797 free(commit_id_str);
2798 free(repo_path);
2799 free(worktree_path);
2800 free(cwd);
2801 return error;
2804 struct got_update_progress_arg {
2805 int did_something;
2806 int conflicts;
2807 int obstructed;
2808 int not_updated;
2811 void
2812 print_update_progress_stats(struct got_update_progress_arg *upa)
2814 if (!upa->did_something)
2815 return;
2817 if (upa->conflicts > 0)
2818 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2819 if (upa->obstructed > 0)
2820 printf("File paths obstructed by a non-regular file: %d\n",
2821 upa->obstructed);
2822 if (upa->not_updated > 0)
2823 printf("Files not updated because of existing merge "
2824 "conflicts: %d\n", upa->not_updated);
2827 __dead static void
2828 usage_update(void)
2830 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2831 getprogname());
2832 exit(1);
2835 static const struct got_error *
2836 update_progress(void *arg, unsigned char status, const char *path)
2838 struct got_update_progress_arg *upa = arg;
2840 if (status == GOT_STATUS_EXISTS ||
2841 status == GOT_STATUS_BASE_REF_ERR)
2842 return NULL;
2844 upa->did_something = 1;
2846 /* Base commit bump happens silently. */
2847 if (status == GOT_STATUS_BUMP_BASE)
2848 return NULL;
2850 if (status == GOT_STATUS_CONFLICT)
2851 upa->conflicts++;
2852 if (status == GOT_STATUS_OBSTRUCTED)
2853 upa->obstructed++;
2854 if (status == GOT_STATUS_CANNOT_UPDATE)
2855 upa->not_updated++;
2857 while (path[0] == '/')
2858 path++;
2859 printf("%c %s\n", status, path);
2860 return NULL;
2863 static const struct got_error *
2864 switch_head_ref(struct got_reference *head_ref,
2865 struct got_object_id *commit_id, struct got_worktree *worktree,
2866 struct got_repository *repo)
2868 const struct got_error *err = NULL;
2869 char *base_id_str;
2870 int ref_has_moved = 0;
2872 /* Trivial case: switching between two different references. */
2873 if (strcmp(got_ref_get_name(head_ref),
2874 got_worktree_get_head_ref_name(worktree)) != 0) {
2875 printf("Switching work tree from %s to %s\n",
2876 got_worktree_get_head_ref_name(worktree),
2877 got_ref_get_name(head_ref));
2878 return got_worktree_set_head_ref(worktree, head_ref);
2881 err = check_linear_ancestry(commit_id,
2882 got_worktree_get_base_commit_id(worktree), 0, repo);
2883 if (err) {
2884 if (err->code != GOT_ERR_ANCESTRY)
2885 return err;
2886 ref_has_moved = 1;
2888 if (!ref_has_moved)
2889 return NULL;
2891 /* Switching to a rebased branch with the same reference name. */
2892 err = got_object_id_str(&base_id_str,
2893 got_worktree_get_base_commit_id(worktree));
2894 if (err)
2895 return err;
2896 printf("Reference %s now points at a different branch\n",
2897 got_worktree_get_head_ref_name(worktree));
2898 printf("Switching work tree from %s to %s\n", base_id_str,
2899 got_worktree_get_head_ref_name(worktree));
2900 return NULL;
2903 static const struct got_error *
2904 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2906 const struct got_error *err;
2907 int in_progress;
2909 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2910 if (err)
2911 return err;
2912 if (in_progress)
2913 return got_error(GOT_ERR_REBASING);
2915 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2916 if (err)
2917 return err;
2918 if (in_progress)
2919 return got_error(GOT_ERR_HISTEDIT_BUSY);
2921 return NULL;
2924 static const struct got_error *
2925 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2926 char *argv[], struct got_worktree *worktree)
2928 const struct got_error *err = NULL;
2929 char *path;
2930 int i;
2932 if (argc == 0) {
2933 path = strdup("");
2934 if (path == NULL)
2935 return got_error_from_errno("strdup");
2936 return got_pathlist_append(paths, path, NULL);
2939 for (i = 0; i < argc; i++) {
2940 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2941 if (err)
2942 break;
2943 err = got_pathlist_append(paths, path, NULL);
2944 if (err) {
2945 free(path);
2946 break;
2950 return err;
2953 static const struct got_error *
2954 wrap_not_worktree_error(const struct got_error *orig_err,
2955 const char *cmdname, const char *path)
2957 const struct got_error *err;
2958 struct got_repository *repo;
2959 static char msg[512];
2961 err = got_repo_open(&repo, path, NULL);
2962 if (err)
2963 return orig_err;
2965 snprintf(msg, sizeof(msg),
2966 "'got %s' needs a work tree in addition to a git repository\n"
2967 "Work trees can be checked out from this Git repository with "
2968 "'got checkout'.\n"
2969 "The got(1) manual page contains more information.", cmdname);
2970 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2971 got_repo_close(repo);
2972 return err;
2975 static const struct got_error *
2976 cmd_update(int argc, char *argv[])
2978 const struct got_error *error = NULL;
2979 struct got_repository *repo = NULL;
2980 struct got_worktree *worktree = NULL;
2981 char *worktree_path = NULL;
2982 struct got_object_id *commit_id = NULL;
2983 char *commit_id_str = NULL;
2984 const char *branch_name = NULL;
2985 struct got_reference *head_ref = NULL;
2986 struct got_pathlist_head paths;
2987 struct got_pathlist_entry *pe;
2988 int ch;
2989 struct got_update_progress_arg upa;
2991 TAILQ_INIT(&paths);
2993 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2994 switch (ch) {
2995 case 'b':
2996 branch_name = optarg;
2997 break;
2998 case 'c':
2999 commit_id_str = strdup(optarg);
3000 if (commit_id_str == NULL)
3001 return got_error_from_errno("strdup");
3002 break;
3003 default:
3004 usage_update();
3005 /* NOTREACHED */
3009 argc -= optind;
3010 argv += optind;
3012 #ifndef PROFILE
3013 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3014 "unveil", NULL) == -1)
3015 err(1, "pledge");
3016 #endif
3017 worktree_path = getcwd(NULL, 0);
3018 if (worktree_path == NULL) {
3019 error = got_error_from_errno("getcwd");
3020 goto done;
3022 error = got_worktree_open(&worktree, worktree_path);
3023 if (error) {
3024 if (error->code == GOT_ERR_NOT_WORKTREE)
3025 error = wrap_not_worktree_error(error, "update",
3026 worktree_path);
3027 goto done;
3030 error = check_rebase_or_histedit_in_progress(worktree);
3031 if (error)
3032 goto done;
3034 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3035 NULL);
3036 if (error != NULL)
3037 goto done;
3039 error = apply_unveil(got_repo_get_path(repo), 0,
3040 got_worktree_get_root_path(worktree));
3041 if (error)
3042 goto done;
3044 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3045 if (error)
3046 goto done;
3048 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3049 got_worktree_get_head_ref_name(worktree), 0);
3050 if (error != NULL)
3051 goto done;
3052 if (commit_id_str == NULL) {
3053 error = got_ref_resolve(&commit_id, repo, head_ref);
3054 if (error != NULL)
3055 goto done;
3056 error = got_object_id_str(&commit_id_str, commit_id);
3057 if (error != NULL)
3058 goto done;
3059 } else {
3060 struct got_reflist_head refs;
3061 SIMPLEQ_INIT(&refs);
3062 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3063 NULL);
3064 if (error)
3065 goto done;
3066 error = got_repo_match_object_id(&commit_id, NULL,
3067 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3068 got_ref_list_free(&refs);
3069 free(commit_id_str);
3070 commit_id_str = NULL;
3071 if (error)
3072 goto done;
3073 error = got_object_id_str(&commit_id_str, commit_id);
3074 if (error)
3075 goto done;
3078 if (branch_name) {
3079 struct got_object_id *head_commit_id;
3080 TAILQ_FOREACH(pe, &paths, entry) {
3081 if (pe->path_len == 0)
3082 continue;
3083 error = got_error_msg(GOT_ERR_BAD_PATH,
3084 "switching between branches requires that "
3085 "the entire work tree gets updated");
3086 goto done;
3088 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3089 if (error)
3090 goto done;
3091 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3092 repo);
3093 free(head_commit_id);
3094 if (error != NULL)
3095 goto done;
3096 error = check_same_branch(commit_id, head_ref, NULL, repo);
3097 if (error)
3098 goto done;
3099 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3100 if (error)
3101 goto done;
3102 } else {
3103 error = check_linear_ancestry(commit_id,
3104 got_worktree_get_base_commit_id(worktree), 0, repo);
3105 if (error != NULL) {
3106 if (error->code == GOT_ERR_ANCESTRY)
3107 error = got_error(GOT_ERR_BRANCH_MOVED);
3108 goto done;
3110 error = check_same_branch(commit_id, head_ref, NULL, repo);
3111 if (error)
3112 goto done;
3115 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3116 commit_id) != 0) {
3117 error = got_worktree_set_base_commit_id(worktree, repo,
3118 commit_id);
3119 if (error)
3120 goto done;
3123 memset(&upa, 0, sizeof(upa));
3124 error = got_worktree_checkout_files(worktree, &paths, repo,
3125 update_progress, &upa, check_cancelled, NULL);
3126 if (error != NULL)
3127 goto done;
3129 if (upa.did_something)
3130 printf("Updated to commit %s\n", commit_id_str);
3131 else
3132 printf("Already up-to-date\n");
3133 print_update_progress_stats(&upa);
3134 done:
3135 free(worktree_path);
3136 TAILQ_FOREACH(pe, &paths, entry)
3137 free((char *)pe->path);
3138 got_pathlist_free(&paths);
3139 free(commit_id);
3140 free(commit_id_str);
3141 return error;
3144 static const struct got_error *
3145 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3146 const char *path, int diff_context, int ignore_whitespace,
3147 int force_text_diff, struct got_repository *repo)
3149 const struct got_error *err = NULL;
3150 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3152 if (blob_id1) {
3153 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3154 if (err)
3155 goto done;
3158 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3159 if (err)
3160 goto done;
3162 while (path[0] == '/')
3163 path++;
3164 err = got_diff_blob(NULL, NULL, blob1, blob2, path, path,
3165 diff_context, ignore_whitespace, force_text_diff, stdout);
3166 done:
3167 if (blob1)
3168 got_object_blob_close(blob1);
3169 got_object_blob_close(blob2);
3170 return err;
3173 static const struct got_error *
3174 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3175 const char *path, int diff_context, int ignore_whitespace,
3176 int force_text_diff, struct got_repository *repo)
3178 const struct got_error *err = NULL;
3179 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3180 struct got_diff_blob_output_unidiff_arg arg;
3182 if (tree_id1) {
3183 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3184 if (err)
3185 goto done;
3188 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3189 if (err)
3190 goto done;
3192 arg.diff_context = diff_context;
3193 arg.ignore_whitespace = ignore_whitespace;
3194 arg.force_text_diff = force_text_diff;
3195 arg.outfile = stdout;
3196 arg.line_offsets = NULL;
3197 arg.nlines = 0;
3198 while (path[0] == '/')
3199 path++;
3200 err = got_diff_tree(tree1, tree2, path, path, repo,
3201 got_diff_blob_output_unidiff, &arg, 1);
3202 done:
3203 if (tree1)
3204 got_object_tree_close(tree1);
3205 if (tree2)
3206 got_object_tree_close(tree2);
3207 return err;
3210 static const struct got_error *
3211 get_changed_paths(struct got_pathlist_head *paths,
3212 struct got_commit_object *commit, struct got_repository *repo)
3214 const struct got_error *err = NULL;
3215 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3216 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3217 struct got_object_qid *qid;
3219 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3220 if (qid != NULL) {
3221 struct got_commit_object *pcommit;
3222 err = got_object_open_as_commit(&pcommit, repo,
3223 qid->id);
3224 if (err)
3225 return err;
3227 tree_id1 = got_object_commit_get_tree_id(pcommit);
3228 got_object_commit_close(pcommit);
3232 if (tree_id1) {
3233 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3234 if (err)
3235 goto done;
3238 tree_id2 = got_object_commit_get_tree_id(commit);
3239 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3240 if (err)
3241 goto done;
3243 err = got_diff_tree(tree1, tree2, "", "", repo,
3244 got_diff_tree_collect_changed_paths, paths, 0);
3245 done:
3246 if (tree1)
3247 got_object_tree_close(tree1);
3248 if (tree2)
3249 got_object_tree_close(tree2);
3250 return err;
3253 static const struct got_error *
3254 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3255 const char *path, int diff_context, struct got_repository *repo)
3257 const struct got_error *err = NULL;
3258 struct got_commit_object *pcommit = NULL;
3259 char *id_str1 = NULL, *id_str2 = NULL;
3260 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3261 struct got_object_qid *qid;
3263 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3264 if (qid != NULL) {
3265 err = got_object_open_as_commit(&pcommit, repo,
3266 qid->id);
3267 if (err)
3268 return err;
3271 if (path && path[0] != '\0') {
3272 int obj_type;
3273 err = got_object_id_by_path(&obj_id2, repo, id, path);
3274 if (err)
3275 goto done;
3276 err = got_object_id_str(&id_str2, obj_id2);
3277 if (err) {
3278 free(obj_id2);
3279 goto done;
3281 if (pcommit) {
3282 err = got_object_id_by_path(&obj_id1, repo,
3283 qid->id, path);
3284 if (err) {
3285 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3286 free(obj_id2);
3287 goto done;
3289 } else {
3290 err = got_object_id_str(&id_str1, obj_id1);
3291 if (err) {
3292 free(obj_id2);
3293 goto done;
3297 err = got_object_get_type(&obj_type, repo, obj_id2);
3298 if (err) {
3299 free(obj_id2);
3300 goto done;
3302 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3303 switch (obj_type) {
3304 case GOT_OBJ_TYPE_BLOB:
3305 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3306 0, 0, repo);
3307 break;
3308 case GOT_OBJ_TYPE_TREE:
3309 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3310 0, 0, repo);
3311 break;
3312 default:
3313 err = got_error(GOT_ERR_OBJ_TYPE);
3314 break;
3316 free(obj_id1);
3317 free(obj_id2);
3318 } else {
3319 obj_id2 = got_object_commit_get_tree_id(commit);
3320 err = got_object_id_str(&id_str2, obj_id2);
3321 if (err)
3322 goto done;
3323 if (pcommit) {
3324 obj_id1 = got_object_commit_get_tree_id(pcommit);
3325 err = got_object_id_str(&id_str1, obj_id1);
3326 if (err)
3327 goto done;
3329 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null",
3330 id_str2);
3331 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3332 repo);
3334 done:
3335 free(id_str1);
3336 free(id_str2);
3337 if (pcommit)
3338 got_object_commit_close(pcommit);
3339 return err;
3342 static char *
3343 get_datestr(time_t *time, char *datebuf)
3345 struct tm mytm, *tm;
3346 char *p, *s;
3348 tm = gmtime_r(time, &mytm);
3349 if (tm == NULL)
3350 return NULL;
3351 s = asctime_r(tm, datebuf);
3352 if (s == NULL)
3353 return NULL;
3354 p = strchr(s, '\n');
3355 if (p)
3356 *p = '\0';
3357 return s;
3360 static const struct got_error *
3361 match_logmsg(int *have_match, struct got_object_id *id,
3362 struct got_commit_object *commit, regex_t *regex)
3364 const struct got_error *err = NULL;
3365 regmatch_t regmatch;
3366 char *id_str = NULL, *logmsg = NULL;
3368 *have_match = 0;
3370 err = got_object_id_str(&id_str, id);
3371 if (err)
3372 return err;
3374 err = got_object_commit_get_logmsg(&logmsg, commit);
3375 if (err)
3376 goto done;
3378 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3379 *have_match = 1;
3380 done:
3381 free(id_str);
3382 free(logmsg);
3383 return err;
3386 static void
3387 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3388 regex_t *regex)
3390 regmatch_t regmatch;
3391 struct got_pathlist_entry *pe;
3393 *have_match = 0;
3395 TAILQ_FOREACH(pe, changed_paths, entry) {
3396 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3397 *have_match = 1;
3398 break;
3403 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3405 static const struct got_error *
3406 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3407 struct got_repository *repo, const char *path,
3408 struct got_pathlist_head *changed_paths, int show_patch,
3409 int diff_context, struct got_reflist_head *refs)
3411 const struct got_error *err = NULL;
3412 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3413 char datebuf[26];
3414 time_t committer_time;
3415 const char *author, *committer;
3416 char *refs_str = NULL;
3417 struct got_reflist_entry *re;
3419 SIMPLEQ_FOREACH(re, refs, entry) {
3420 char *s;
3421 const char *name;
3422 struct got_tag_object *tag = NULL;
3423 struct got_object_id *ref_id;
3424 int cmp;
3426 name = got_ref_get_name(re->ref);
3427 if (strcmp(name, GOT_REF_HEAD) == 0)
3428 continue;
3429 if (strncmp(name, "refs/", 5) == 0)
3430 name += 5;
3431 if (strncmp(name, "got/", 4) == 0)
3432 continue;
3433 if (strncmp(name, "heads/", 6) == 0)
3434 name += 6;
3435 if (strncmp(name, "remotes/", 8) == 0) {
3436 name += 8;
3437 s = strstr(name, "/" GOT_REF_HEAD);
3438 if (s != NULL && s[strlen(s)] == '\0')
3439 continue;
3441 err = got_ref_resolve(&ref_id, repo, re->ref);
3442 if (err)
3443 return err;
3444 if (strncmp(name, "tags/", 5) == 0) {
3445 err = got_object_open_as_tag(&tag, repo, ref_id);
3446 if (err) {
3447 if (err->code != GOT_ERR_OBJ_TYPE) {
3448 free(ref_id);
3449 return err;
3451 /* Ref points at something other than a tag. */
3452 err = NULL;
3453 tag = NULL;
3456 cmp = got_object_id_cmp(tag ?
3457 got_object_tag_get_object_id(tag) : ref_id, id);
3458 free(ref_id);
3459 if (tag)
3460 got_object_tag_close(tag);
3461 if (cmp != 0)
3462 continue;
3463 s = refs_str;
3464 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3465 name) == -1) {
3466 err = got_error_from_errno("asprintf");
3467 free(s);
3468 return err;
3470 free(s);
3472 err = got_object_id_str(&id_str, id);
3473 if (err)
3474 return err;
3476 printf(GOT_COMMIT_SEP_STR);
3477 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3478 refs_str ? refs_str : "", refs_str ? ")" : "");
3479 free(id_str);
3480 id_str = NULL;
3481 free(refs_str);
3482 refs_str = NULL;
3483 printf("from: %s\n", got_object_commit_get_author(commit));
3484 committer_time = got_object_commit_get_committer_time(commit);
3485 datestr = get_datestr(&committer_time, datebuf);
3486 if (datestr)
3487 printf("date: %s UTC\n", datestr);
3488 author = got_object_commit_get_author(commit);
3489 committer = got_object_commit_get_committer(commit);
3490 if (strcmp(author, committer) != 0)
3491 printf("via: %s\n", committer);
3492 if (got_object_commit_get_nparents(commit) > 1) {
3493 const struct got_object_id_queue *parent_ids;
3494 struct got_object_qid *qid;
3495 int n = 1;
3496 parent_ids = got_object_commit_get_parent_ids(commit);
3497 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3498 err = got_object_id_str(&id_str, qid->id);
3499 if (err)
3500 return err;
3501 printf("parent %d: %s\n", n++, id_str);
3502 free(id_str);
3506 err = got_object_commit_get_logmsg(&logmsg0, commit);
3507 if (err)
3508 return err;
3510 logmsg = logmsg0;
3511 do {
3512 line = strsep(&logmsg, "\n");
3513 if (line)
3514 printf(" %s\n", line);
3515 } while (line);
3516 free(logmsg0);
3518 if (changed_paths) {
3519 struct got_pathlist_entry *pe;
3520 TAILQ_FOREACH(pe, changed_paths, entry) {
3521 struct got_diff_changed_path *cp = pe->data;
3522 printf(" %c %s\n", cp->status, pe->path);
3524 printf("\n");
3526 if (show_patch) {
3527 err = print_patch(commit, id, path, diff_context, repo);
3528 if (err == 0)
3529 printf("\n");
3532 if (fflush(stdout) != 0 && err == NULL)
3533 err = got_error_from_errno("fflush");
3534 return err;
3537 static const struct got_error *
3538 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3539 struct got_repository *repo, const char *path, int show_changed_paths,
3540 int show_patch, const char *search_pattern, int diff_context, int limit,
3541 int log_branches, int reverse_display_order, struct got_reflist_head *refs)
3543 const struct got_error *err;
3544 struct got_commit_graph *graph;
3545 regex_t regex;
3546 int have_match;
3547 struct got_object_id_queue reversed_commits;
3548 struct got_object_qid *qid;
3549 struct got_commit_object *commit;
3550 struct got_pathlist_head changed_paths;
3551 struct got_pathlist_entry *pe;
3553 SIMPLEQ_INIT(&reversed_commits);
3554 TAILQ_INIT(&changed_paths);
3556 if (search_pattern && regcomp(&regex, search_pattern,
3557 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3558 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3560 err = got_commit_graph_open(&graph, path, !log_branches);
3561 if (err)
3562 return err;
3563 err = got_commit_graph_iter_start(graph, root_id, repo,
3564 check_cancelled, NULL);
3565 if (err)
3566 goto done;
3567 for (;;) {
3568 struct got_object_id *id;
3570 if (sigint_received || sigpipe_received)
3571 break;
3573 err = got_commit_graph_iter_next(&id, graph, repo,
3574 check_cancelled, NULL);
3575 if (err) {
3576 if (err->code == GOT_ERR_ITER_COMPLETED)
3577 err = NULL;
3578 break;
3580 if (id == NULL)
3581 break;
3583 err = got_object_open_as_commit(&commit, repo, id);
3584 if (err)
3585 break;
3587 if (show_changed_paths && !reverse_display_order) {
3588 err = get_changed_paths(&changed_paths, commit, repo);
3589 if (err)
3590 break;
3593 if (search_pattern) {
3594 err = match_logmsg(&have_match, id, commit, &regex);
3595 if (err) {
3596 got_object_commit_close(commit);
3597 break;
3599 if (have_match == 0 && show_changed_paths)
3600 match_changed_paths(&have_match,
3601 &changed_paths, &regex);
3602 if (have_match == 0) {
3603 got_object_commit_close(commit);
3604 TAILQ_FOREACH(pe, &changed_paths, entry) {
3605 free((char *)pe->path);
3606 free(pe->data);
3608 got_pathlist_free(&changed_paths);
3609 continue;
3613 if (reverse_display_order) {
3614 err = got_object_qid_alloc(&qid, id);
3615 if (err)
3616 break;
3617 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3618 got_object_commit_close(commit);
3619 } else {
3620 err = print_commit(commit, id, repo, path,
3621 show_changed_paths ? &changed_paths : NULL,
3622 show_patch, diff_context, refs);
3623 got_object_commit_close(commit);
3624 if (err)
3625 break;
3627 if ((limit && --limit == 0) ||
3628 (end_id && got_object_id_cmp(id, end_id) == 0))
3629 break;
3631 TAILQ_FOREACH(pe, &changed_paths, entry) {
3632 free((char *)pe->path);
3633 free(pe->data);
3635 got_pathlist_free(&changed_paths);
3637 if (reverse_display_order) {
3638 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3639 err = got_object_open_as_commit(&commit, repo, qid->id);
3640 if (err)
3641 break;
3642 if (show_changed_paths) {
3643 err = get_changed_paths(&changed_paths,
3644 commit, repo);
3645 if (err)
3646 break;
3648 err = print_commit(commit, qid->id, repo, path,
3649 show_changed_paths ? &changed_paths : NULL,
3650 show_patch, diff_context, refs);
3651 got_object_commit_close(commit);
3652 if (err)
3653 break;
3654 TAILQ_FOREACH(pe, &changed_paths, entry) {
3655 free((char *)pe->path);
3656 free(pe->data);
3658 got_pathlist_free(&changed_paths);
3661 done:
3662 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3663 qid = SIMPLEQ_FIRST(&reversed_commits);
3664 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3665 got_object_qid_free(qid);
3667 TAILQ_FOREACH(pe, &changed_paths, entry) {
3668 free((char *)pe->path);
3669 free(pe->data);
3671 got_pathlist_free(&changed_paths);
3672 if (search_pattern)
3673 regfree(&regex);
3674 got_commit_graph_close(graph);
3675 return err;
3678 __dead static void
3679 usage_log(void)
3681 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3682 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3683 "[-R] [path]\n", getprogname());
3684 exit(1);
3687 static int
3688 get_default_log_limit(void)
3690 const char *got_default_log_limit;
3691 long long n;
3692 const char *errstr;
3694 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3695 if (got_default_log_limit == NULL)
3696 return 0;
3697 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3698 if (errstr != NULL)
3699 return 0;
3700 return n;
3703 static const struct got_error *
3704 cmd_log(int argc, char *argv[])
3706 const struct got_error *error;
3707 struct got_repository *repo = NULL;
3708 struct got_worktree *worktree = NULL;
3709 struct got_object_id *start_id = NULL, *end_id = NULL;
3710 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3711 const char *start_commit = NULL, *end_commit = NULL;
3712 const char *search_pattern = NULL;
3713 int diff_context = -1, ch;
3714 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3715 int reverse_display_order = 0;
3716 const char *errstr;
3717 struct got_reflist_head refs;
3719 SIMPLEQ_INIT(&refs);
3721 #ifndef PROFILE
3722 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3723 NULL)
3724 == -1)
3725 err(1, "pledge");
3726 #endif
3728 limit = get_default_log_limit();
3730 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3731 switch (ch) {
3732 case 'p':
3733 show_patch = 1;
3734 break;
3735 case 'P':
3736 show_changed_paths = 1;
3737 break;
3738 case 'c':
3739 start_commit = optarg;
3740 break;
3741 case 'C':
3742 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3743 &errstr);
3744 if (errstr != NULL)
3745 err(1, "-C option %s", errstr);
3746 break;
3747 case 'l':
3748 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3749 if (errstr != NULL)
3750 err(1, "-l option %s", errstr);
3751 break;
3752 case 'b':
3753 log_branches = 1;
3754 break;
3755 case 'r':
3756 repo_path = realpath(optarg, NULL);
3757 if (repo_path == NULL)
3758 return got_error_from_errno2("realpath",
3759 optarg);
3760 got_path_strip_trailing_slashes(repo_path);
3761 break;
3762 case 'R':
3763 reverse_display_order = 1;
3764 break;
3765 case 's':
3766 search_pattern = optarg;
3767 break;
3768 case 'x':
3769 end_commit = optarg;
3770 break;
3771 default:
3772 usage_log();
3773 /* NOTREACHED */
3777 argc -= optind;
3778 argv += optind;
3780 if (diff_context == -1)
3781 diff_context = 3;
3782 else if (!show_patch)
3783 errx(1, "-C requires -p");
3785 cwd = getcwd(NULL, 0);
3786 if (cwd == NULL) {
3787 error = got_error_from_errno("getcwd");
3788 goto done;
3791 if (repo_path == NULL) {
3792 error = got_worktree_open(&worktree, cwd);
3793 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3794 goto done;
3795 error = NULL;
3798 if (argc == 1) {
3799 if (worktree) {
3800 error = got_worktree_resolve_path(&path, worktree,
3801 argv[0]);
3802 if (error)
3803 goto done;
3804 } else {
3805 path = strdup(argv[0]);
3806 if (path == NULL) {
3807 error = got_error_from_errno("strdup");
3808 goto done;
3811 } else if (argc != 0)
3812 usage_log();
3814 if (repo_path == NULL) {
3815 repo_path = worktree ?
3816 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3818 if (repo_path == NULL) {
3819 error = got_error_from_errno("strdup");
3820 goto done;
3823 error = got_repo_open(&repo, repo_path, NULL);
3824 if (error != NULL)
3825 goto done;
3827 error = apply_unveil(got_repo_get_path(repo), 1,
3828 worktree ? got_worktree_get_root_path(worktree) : NULL);
3829 if (error)
3830 goto done;
3832 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3833 if (error)
3834 goto done;
3836 if (start_commit == NULL) {
3837 struct got_reference *head_ref;
3838 struct got_commit_object *commit = NULL;
3839 error = got_ref_open(&head_ref, repo,
3840 worktree ? got_worktree_get_head_ref_name(worktree)
3841 : GOT_REF_HEAD, 0);
3842 if (error != NULL)
3843 goto done;
3844 error = got_ref_resolve(&start_id, repo, head_ref);
3845 got_ref_close(head_ref);
3846 if (error != NULL)
3847 goto done;
3848 error = got_object_open_as_commit(&commit, repo,
3849 start_id);
3850 if (error != NULL)
3851 goto done;
3852 got_object_commit_close(commit);
3853 } else {
3854 error = got_repo_match_object_id(&start_id, NULL,
3855 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3856 if (error != NULL)
3857 goto done;
3859 if (end_commit != NULL) {
3860 error = got_repo_match_object_id(&end_id, NULL,
3861 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3862 if (error != NULL)
3863 goto done;
3866 if (worktree) {
3868 * If a path was specified on the command line it was resolved
3869 * to a path in the work tree above. Prepend the work tree's
3870 * path prefix to obtain the corresponding in-repository path.
3872 if (path) {
3873 const char *prefix;
3874 prefix = got_worktree_get_path_prefix(worktree);
3875 if (asprintf(&in_repo_path, "%s%s%s", prefix,
3876 (path[0] != '\0') ? "/" : "", path) == -1) {
3877 error = got_error_from_errno("asprintf");
3878 goto done;
3881 } else
3882 error = got_repo_map_path(&in_repo_path, repo,
3883 path ? path : "");
3884 if (error != NULL)
3885 goto done;
3886 if (in_repo_path) {
3887 free(path);
3888 path = in_repo_path;
3891 error = print_commits(start_id, end_id, repo, path ? path : "",
3892 show_changed_paths, show_patch, search_pattern, diff_context,
3893 limit, log_branches, reverse_display_order, &refs);
3894 done:
3895 free(path);
3896 free(repo_path);
3897 free(cwd);
3898 if (worktree)
3899 got_worktree_close(worktree);
3900 if (repo) {
3901 const struct got_error *repo_error;
3902 repo_error = got_repo_close(repo);
3903 if (error == NULL)
3904 error = repo_error;
3906 got_ref_list_free(&refs);
3907 return error;
3910 __dead static void
3911 usage_diff(void)
3913 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
3914 "[-s] [-w] [object1 object2 | path]\n", getprogname());
3915 exit(1);
3918 struct print_diff_arg {
3919 struct got_repository *repo;
3920 struct got_worktree *worktree;
3921 int diff_context;
3922 const char *id_str;
3923 int header_shown;
3924 int diff_staged;
3925 int ignore_whitespace;
3926 int force_text_diff;
3930 * Create a file which contains the target path of a symlink so we can feed
3931 * it as content to the diff engine.
3933 static const struct got_error *
3934 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
3935 const char *abspath)
3937 const struct got_error *err = NULL;
3938 char target_path[PATH_MAX];
3939 ssize_t target_len, outlen;
3941 *fd = -1;
3943 if (dirfd != -1) {
3944 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
3945 if (target_len == -1)
3946 return got_error_from_errno2("readlinkat", abspath);
3947 } else {
3948 target_len = readlink(abspath, target_path, PATH_MAX);
3949 if (target_len == -1)
3950 return got_error_from_errno2("readlink", abspath);
3953 *fd = got_opentempfd();
3954 if (*fd == -1)
3955 return got_error_from_errno("got_opentempfd");
3957 outlen = write(*fd, target_path, target_len);
3958 if (outlen == -1) {
3959 err = got_error_from_errno("got_opentempfd");
3960 goto done;
3963 if (lseek(*fd, 0, SEEK_SET) == -1) {
3964 err = got_error_from_errno2("lseek", abspath);
3965 goto done;
3967 done:
3968 if (err) {
3969 close(*fd);
3970 *fd = -1;
3972 return err;
3975 static const struct got_error *
3976 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3977 const char *path, struct got_object_id *blob_id,
3978 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3979 int dirfd, const char *de_name)
3981 struct print_diff_arg *a = arg;
3982 const struct got_error *err = NULL;
3983 struct got_blob_object *blob1 = NULL;
3984 int fd = -1;
3985 FILE *f2 = NULL;
3986 char *abspath = NULL, *label1 = NULL;
3987 struct stat sb;
3989 if (a->diff_staged) {
3990 if (staged_status != GOT_STATUS_MODIFY &&
3991 staged_status != GOT_STATUS_ADD &&
3992 staged_status != GOT_STATUS_DELETE)
3993 return NULL;
3994 } else {
3995 if (staged_status == GOT_STATUS_DELETE)
3996 return NULL;
3997 if (status == GOT_STATUS_NONEXISTENT)
3998 return got_error_set_errno(ENOENT, path);
3999 if (status != GOT_STATUS_MODIFY &&
4000 status != GOT_STATUS_ADD &&
4001 status != GOT_STATUS_DELETE &&
4002 status != GOT_STATUS_CONFLICT)
4003 return NULL;
4006 if (!a->header_shown) {
4007 printf("diff %s %s%s\n", a->id_str,
4008 got_worktree_get_root_path(a->worktree),
4009 a->diff_staged ? " (staged changes)" : "");
4010 a->header_shown = 1;
4013 if (a->diff_staged) {
4014 const char *label1 = NULL, *label2 = NULL;
4015 switch (staged_status) {
4016 case GOT_STATUS_MODIFY:
4017 label1 = path;
4018 label2 = path;
4019 break;
4020 case GOT_STATUS_ADD:
4021 label2 = path;
4022 break;
4023 case GOT_STATUS_DELETE:
4024 label1 = path;
4025 break;
4026 default:
4027 return got_error(GOT_ERR_FILE_STATUS);
4029 return got_diff_objects_as_blobs(NULL, NULL, blob_id,
4030 staged_blob_id, label1, label2, a->diff_context,
4031 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4034 if (staged_status == GOT_STATUS_ADD ||
4035 staged_status == GOT_STATUS_MODIFY) {
4036 char *id_str;
4037 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4038 8192);
4039 if (err)
4040 goto done;
4041 err = got_object_id_str(&id_str, staged_blob_id);
4042 if (err)
4043 goto done;
4044 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4045 err = got_error_from_errno("asprintf");
4046 free(id_str);
4047 goto done;
4049 free(id_str);
4050 } else if (status != GOT_STATUS_ADD) {
4051 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4052 if (err)
4053 goto done;
4056 if (status != GOT_STATUS_DELETE) {
4057 if (asprintf(&abspath, "%s/%s",
4058 got_worktree_get_root_path(a->worktree), path) == -1) {
4059 err = got_error_from_errno("asprintf");
4060 goto done;
4063 if (dirfd != -1) {
4064 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
4065 if (fd == -1) {
4066 if (errno != ELOOP) {
4067 err = got_error_from_errno2("openat",
4068 abspath);
4069 goto done;
4071 err = get_symlink_target_file(&fd, dirfd,
4072 de_name, abspath);
4073 if (err)
4074 goto done;
4076 } else {
4077 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
4078 if (fd == -1) {
4079 if (errno != ELOOP) {
4080 err = got_error_from_errno2("open",
4081 abspath);
4082 goto done;
4084 err = get_symlink_target_file(&fd, dirfd,
4085 de_name, abspath);
4086 if (err)
4087 goto done;
4090 if (fstat(fd, &sb) == -1) {
4091 err = got_error_from_errno2("fstat", abspath);
4092 goto done;
4094 f2 = fdopen(fd, "r");
4095 if (f2 == NULL) {
4096 err = got_error_from_errno2("fdopen", abspath);
4097 goto done;
4099 fd = -1;
4100 } else
4101 sb.st_size = 0;
4103 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4104 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4105 done:
4106 if (blob1)
4107 got_object_blob_close(blob1);
4108 if (f2 && fclose(f2) == EOF && err == NULL)
4109 err = got_error_from_errno("fclose");
4110 if (fd != -1 && close(fd) == -1 && err == NULL)
4111 err = got_error_from_errno("close");
4112 free(abspath);
4113 return err;
4116 static const struct got_error *
4117 cmd_diff(int argc, char *argv[])
4119 const struct got_error *error;
4120 struct got_repository *repo = NULL;
4121 struct got_worktree *worktree = NULL;
4122 char *cwd = NULL, *repo_path = NULL;
4123 struct got_object_id *id1 = NULL, *id2 = NULL;
4124 const char *id_str1 = NULL, *id_str2 = NULL;
4125 char *label1 = NULL, *label2 = NULL;
4126 int type1, type2;
4127 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
4128 int force_text_diff = 0;
4129 const char *errstr;
4130 char *path = NULL;
4131 struct got_reflist_head refs;
4133 SIMPLEQ_INIT(&refs);
4135 #ifndef PROFILE
4136 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4137 NULL) == -1)
4138 err(1, "pledge");
4139 #endif
4141 while ((ch = getopt(argc, argv, "aC:r:sw")) != -1) {
4142 switch (ch) {
4143 case 'a':
4144 force_text_diff = 1;
4145 break;
4146 case 'C':
4147 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4148 &errstr);
4149 if (errstr != NULL)
4150 err(1, "-C option %s", errstr);
4151 break;
4152 case 'r':
4153 repo_path = realpath(optarg, NULL);
4154 if (repo_path == NULL)
4155 return got_error_from_errno2("realpath",
4156 optarg);
4157 got_path_strip_trailing_slashes(repo_path);
4158 break;
4159 case 's':
4160 diff_staged = 1;
4161 break;
4162 case 'w':
4163 ignore_whitespace = 1;
4164 break;
4165 default:
4166 usage_diff();
4167 /* NOTREACHED */
4171 argc -= optind;
4172 argv += optind;
4174 cwd = getcwd(NULL, 0);
4175 if (cwd == NULL) {
4176 error = got_error_from_errno("getcwd");
4177 goto done;
4179 if (argc <= 1) {
4180 if (repo_path)
4181 errx(1,
4182 "-r option can't be used when diffing a work tree");
4183 error = got_worktree_open(&worktree, cwd);
4184 if (error) {
4185 if (error->code == GOT_ERR_NOT_WORKTREE)
4186 error = wrap_not_worktree_error(error, "diff",
4187 cwd);
4188 goto done;
4190 repo_path = strdup(got_worktree_get_repo_path(worktree));
4191 if (repo_path == NULL) {
4192 error = got_error_from_errno("strdup");
4193 goto done;
4195 if (argc == 1) {
4196 error = got_worktree_resolve_path(&path, worktree,
4197 argv[0]);
4198 if (error)
4199 goto done;
4200 } else {
4201 path = strdup("");
4202 if (path == NULL) {
4203 error = got_error_from_errno("strdup");
4204 goto done;
4207 } else if (argc == 2) {
4208 if (diff_staged)
4209 errx(1, "-s option can't be used when diffing "
4210 "objects in repository");
4211 id_str1 = argv[0];
4212 id_str2 = argv[1];
4213 if (repo_path == NULL) {
4214 error = got_worktree_open(&worktree, cwd);
4215 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4216 goto done;
4217 if (worktree) {
4218 repo_path = strdup(
4219 got_worktree_get_repo_path(worktree));
4220 if (repo_path == NULL) {
4221 error = got_error_from_errno("strdup");
4222 goto done;
4224 } else {
4225 repo_path = strdup(cwd);
4226 if (repo_path == NULL) {
4227 error = got_error_from_errno("strdup");
4228 goto done;
4232 } else
4233 usage_diff();
4235 error = got_repo_open(&repo, repo_path, NULL);
4236 free(repo_path);
4237 if (error != NULL)
4238 goto done;
4240 error = apply_unveil(got_repo_get_path(repo), 1,
4241 worktree ? got_worktree_get_root_path(worktree) : NULL);
4242 if (error)
4243 goto done;
4245 if (argc <= 1) {
4246 struct print_diff_arg arg;
4247 struct got_pathlist_head paths;
4248 char *id_str;
4250 TAILQ_INIT(&paths);
4252 error = got_object_id_str(&id_str,
4253 got_worktree_get_base_commit_id(worktree));
4254 if (error)
4255 goto done;
4256 arg.repo = repo;
4257 arg.worktree = worktree;
4258 arg.diff_context = diff_context;
4259 arg.id_str = id_str;
4260 arg.header_shown = 0;
4261 arg.diff_staged = diff_staged;
4262 arg.ignore_whitespace = ignore_whitespace;
4263 arg.force_text_diff = force_text_diff;
4265 error = got_pathlist_append(&paths, path, NULL);
4266 if (error)
4267 goto done;
4269 error = got_worktree_status(worktree, &paths, repo, print_diff,
4270 &arg, check_cancelled, NULL);
4271 free(id_str);
4272 got_pathlist_free(&paths);
4273 goto done;
4276 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4277 if (error)
4278 return error;
4280 error = got_repo_match_object_id(&id1, &label1, id_str1,
4281 GOT_OBJ_TYPE_ANY, &refs, repo);
4282 if (error)
4283 goto done;
4285 error = got_repo_match_object_id(&id2, &label2, id_str2,
4286 GOT_OBJ_TYPE_ANY, &refs, repo);
4287 if (error)
4288 goto done;
4290 error = got_object_get_type(&type1, repo, id1);
4291 if (error)
4292 goto done;
4294 error = got_object_get_type(&type2, repo, id2);
4295 if (error)
4296 goto done;
4298 if (type1 != type2) {
4299 error = got_error(GOT_ERR_OBJ_TYPE);
4300 goto done;
4303 switch (type1) {
4304 case GOT_OBJ_TYPE_BLOB:
4305 error = got_diff_objects_as_blobs(NULL, NULL, id1, id2,
4306 NULL, NULL, diff_context, ignore_whitespace,
4307 force_text_diff, repo, stdout);
4308 break;
4309 case GOT_OBJ_TYPE_TREE:
4310 error = got_diff_objects_as_trees(NULL, NULL, id1, id2,
4311 "", "", diff_context, ignore_whitespace, force_text_diff,
4312 repo, stdout);
4313 break;
4314 case GOT_OBJ_TYPE_COMMIT:
4315 printf("diff %s %s\n", label1, label2);
4316 error = got_diff_objects_as_commits(NULL, NULL, id1, id2,
4317 diff_context, ignore_whitespace, force_text_diff, repo,
4318 stdout);
4319 break;
4320 default:
4321 error = got_error(GOT_ERR_OBJ_TYPE);
4323 done:
4324 free(label1);
4325 free(label2);
4326 free(id1);
4327 free(id2);
4328 free(path);
4329 if (worktree)
4330 got_worktree_close(worktree);
4331 if (repo) {
4332 const struct got_error *repo_error;
4333 repo_error = got_repo_close(repo);
4334 if (error == NULL)
4335 error = repo_error;
4337 got_ref_list_free(&refs);
4338 return error;
4341 __dead static void
4342 usage_blame(void)
4344 fprintf(stderr,
4345 "usage: %s blame [-c commit] [-r repository-path] path\n",
4346 getprogname());
4347 exit(1);
4350 struct blame_line {
4351 int annotated;
4352 char *id_str;
4353 char *committer;
4354 char datebuf[11]; /* YYYY-MM-DD + NUL */
4357 struct blame_cb_args {
4358 struct blame_line *lines;
4359 int nlines;
4360 int nlines_prec;
4361 int lineno_cur;
4362 off_t *line_offsets;
4363 FILE *f;
4364 struct got_repository *repo;
4367 static const struct got_error *
4368 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4370 const struct got_error *err = NULL;
4371 struct blame_cb_args *a = arg;
4372 struct blame_line *bline;
4373 char *line = NULL;
4374 size_t linesize = 0;
4375 struct got_commit_object *commit = NULL;
4376 off_t offset;
4377 struct tm tm;
4378 time_t committer_time;
4380 if (nlines != a->nlines ||
4381 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4382 return got_error(GOT_ERR_RANGE);
4384 if (sigint_received)
4385 return got_error(GOT_ERR_ITER_COMPLETED);
4387 if (lineno == -1)
4388 return NULL; /* no change in this commit */
4390 /* Annotate this line. */
4391 bline = &a->lines[lineno - 1];
4392 if (bline->annotated)
4393 return NULL;
4394 err = got_object_id_str(&bline->id_str, id);
4395 if (err)
4396 return err;
4398 err = got_object_open_as_commit(&commit, a->repo, id);
4399 if (err)
4400 goto done;
4402 bline->committer = strdup(got_object_commit_get_committer(commit));
4403 if (bline->committer == NULL) {
4404 err = got_error_from_errno("strdup");
4405 goto done;
4408 committer_time = got_object_commit_get_committer_time(commit);
4409 if (localtime_r(&committer_time, &tm) == NULL)
4410 return got_error_from_errno("localtime_r");
4411 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4412 &tm) >= sizeof(bline->datebuf)) {
4413 err = got_error(GOT_ERR_NO_SPACE);
4414 goto done;
4416 bline->annotated = 1;
4418 /* Print lines annotated so far. */
4419 bline = &a->lines[a->lineno_cur - 1];
4420 if (!bline->annotated)
4421 goto done;
4423 offset = a->line_offsets[a->lineno_cur - 1];
4424 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4425 err = got_error_from_errno("fseeko");
4426 goto done;
4429 while (bline->annotated) {
4430 char *smallerthan, *at, *nl, *committer;
4431 size_t len;
4433 if (getline(&line, &linesize, a->f) == -1) {
4434 if (ferror(a->f))
4435 err = got_error_from_errno("getline");
4436 break;
4439 committer = bline->committer;
4440 smallerthan = strchr(committer, '<');
4441 if (smallerthan && smallerthan[1] != '\0')
4442 committer = smallerthan + 1;
4443 at = strchr(committer, '@');
4444 if (at)
4445 *at = '\0';
4446 len = strlen(committer);
4447 if (len >= 9)
4448 committer[8] = '\0';
4450 nl = strchr(line, '\n');
4451 if (nl)
4452 *nl = '\0';
4453 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4454 bline->id_str, bline->datebuf, committer, line);
4456 a->lineno_cur++;
4457 bline = &a->lines[a->lineno_cur - 1];
4459 done:
4460 if (commit)
4461 got_object_commit_close(commit);
4462 free(line);
4463 return err;
4466 static const struct got_error *
4467 cmd_blame(int argc, char *argv[])
4469 const struct got_error *error;
4470 struct got_repository *repo = NULL;
4471 struct got_worktree *worktree = NULL;
4472 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4473 char *link_target = NULL;
4474 struct got_object_id *obj_id = NULL;
4475 struct got_object_id *commit_id = NULL;
4476 struct got_blob_object *blob = NULL;
4477 char *commit_id_str = NULL;
4478 struct blame_cb_args bca;
4479 int ch, obj_type, i;
4480 off_t filesize;
4482 memset(&bca, 0, sizeof(bca));
4484 #ifndef PROFILE
4485 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4486 NULL) == -1)
4487 err(1, "pledge");
4488 #endif
4490 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4491 switch (ch) {
4492 case 'c':
4493 commit_id_str = optarg;
4494 break;
4495 case 'r':
4496 repo_path = realpath(optarg, NULL);
4497 if (repo_path == NULL)
4498 return got_error_from_errno2("realpath",
4499 optarg);
4500 got_path_strip_trailing_slashes(repo_path);
4501 break;
4502 default:
4503 usage_blame();
4504 /* NOTREACHED */
4508 argc -= optind;
4509 argv += optind;
4511 if (argc == 1)
4512 path = argv[0];
4513 else
4514 usage_blame();
4516 cwd = getcwd(NULL, 0);
4517 if (cwd == NULL) {
4518 error = got_error_from_errno("getcwd");
4519 goto done;
4521 if (repo_path == NULL) {
4522 error = got_worktree_open(&worktree, cwd);
4523 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4524 goto done;
4525 else
4526 error = NULL;
4527 if (worktree) {
4528 repo_path =
4529 strdup(got_worktree_get_repo_path(worktree));
4530 if (repo_path == NULL) {
4531 error = got_error_from_errno("strdup");
4532 if (error)
4533 goto done;
4535 } else {
4536 repo_path = strdup(cwd);
4537 if (repo_path == NULL) {
4538 error = got_error_from_errno("strdup");
4539 goto done;
4544 error = got_repo_open(&repo, repo_path, NULL);
4545 if (error != NULL)
4546 goto done;
4548 if (worktree) {
4549 const char *prefix = got_worktree_get_path_prefix(worktree);
4550 char *p;
4552 error = got_worktree_resolve_path(&p, worktree, path);
4553 if (error)
4554 goto done;
4555 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4556 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4557 p) == -1) {
4558 error = got_error_from_errno("asprintf");
4559 free(p);
4560 goto done;
4562 free(p);
4563 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4564 } else {
4565 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4566 if (error)
4567 goto done;
4568 error = got_repo_map_path(&in_repo_path, repo, path);
4570 if (error)
4571 goto done;
4573 if (commit_id_str == NULL) {
4574 struct got_reference *head_ref;
4575 error = got_ref_open(&head_ref, repo, worktree ?
4576 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4577 if (error != NULL)
4578 goto done;
4579 error = got_ref_resolve(&commit_id, repo, head_ref);
4580 got_ref_close(head_ref);
4581 if (error != NULL)
4582 goto done;
4583 } else {
4584 struct got_reflist_head refs;
4585 SIMPLEQ_INIT(&refs);
4586 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4587 NULL);
4588 if (error)
4589 goto done;
4590 error = got_repo_match_object_id(&commit_id, NULL,
4591 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4592 got_ref_list_free(&refs);
4593 if (error)
4594 goto done;
4597 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4598 commit_id, repo);
4599 if (error)
4600 goto done;
4602 error = got_object_id_by_path(&obj_id, repo, commit_id,
4603 link_target ? link_target : in_repo_path);
4604 if (error)
4605 goto done;
4607 error = got_object_get_type(&obj_type, repo, obj_id);
4608 if (error)
4609 goto done;
4611 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4612 error = got_error_path(link_target ? link_target : in_repo_path,
4613 GOT_ERR_OBJ_TYPE);
4614 goto done;
4617 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4618 if (error)
4619 goto done;
4620 bca.f = got_opentemp();
4621 if (bca.f == NULL) {
4622 error = got_error_from_errno("got_opentemp");
4623 goto done;
4625 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4626 &bca.line_offsets, bca.f, blob);
4627 if (error || bca.nlines == 0)
4628 goto done;
4630 /* Don't include \n at EOF in the blame line count. */
4631 if (bca.line_offsets[bca.nlines - 1] == filesize)
4632 bca.nlines--;
4634 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4635 if (bca.lines == NULL) {
4636 error = got_error_from_errno("calloc");
4637 goto done;
4639 bca.lineno_cur = 1;
4640 bca.nlines_prec = 0;
4641 i = bca.nlines;
4642 while (i > 0) {
4643 i /= 10;
4644 bca.nlines_prec++;
4646 bca.repo = repo;
4648 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4649 repo, blame_cb, &bca, check_cancelled, NULL);
4650 done:
4651 free(in_repo_path);
4652 free(link_target);
4653 free(repo_path);
4654 free(cwd);
4655 free(commit_id);
4656 free(obj_id);
4657 if (blob)
4658 got_object_blob_close(blob);
4659 if (worktree)
4660 got_worktree_close(worktree);
4661 if (repo) {
4662 const struct got_error *repo_error;
4663 repo_error = got_repo_close(repo);
4664 if (error == NULL)
4665 error = repo_error;
4667 if (bca.lines) {
4668 for (i = 0; i < bca.nlines; i++) {
4669 struct blame_line *bline = &bca.lines[i];
4670 free(bline->id_str);
4671 free(bline->committer);
4673 free(bca.lines);
4675 free(bca.line_offsets);
4676 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4677 error = got_error_from_errno("fclose");
4678 return error;
4681 __dead static void
4682 usage_tree(void)
4684 fprintf(stderr,
4685 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4686 getprogname());
4687 exit(1);
4690 static const struct got_error *
4691 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4692 const char *root_path, struct got_repository *repo)
4694 const struct got_error *err = NULL;
4695 int is_root_path = (strcmp(path, root_path) == 0);
4696 const char *modestr = "";
4697 mode_t mode = got_tree_entry_get_mode(te);
4698 char *link_target = NULL;
4700 path += strlen(root_path);
4701 while (path[0] == '/')
4702 path++;
4704 if (got_object_tree_entry_is_submodule(te))
4705 modestr = "$";
4706 else if (S_ISLNK(mode)) {
4707 int i;
4709 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4710 if (err)
4711 return err;
4712 for (i = 0; i < strlen(link_target); i++) {
4713 if (!isprint((unsigned char)link_target[i]))
4714 link_target[i] = '?';
4717 modestr = "@";
4719 else if (S_ISDIR(mode))
4720 modestr = "/";
4721 else if (mode & S_IXUSR)
4722 modestr = "*";
4724 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4725 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4726 link_target ? " -> ": "", link_target ? link_target : "");
4728 free(link_target);
4729 return NULL;
4732 static const struct got_error *
4733 print_tree(const char *path, struct got_object_id *commit_id,
4734 int show_ids, int recurse, const char *root_path,
4735 struct got_repository *repo)
4737 const struct got_error *err = NULL;
4738 struct got_object_id *tree_id = NULL;
4739 struct got_tree_object *tree = NULL;
4740 int nentries, i;
4742 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4743 if (err)
4744 goto done;
4746 err = got_object_open_as_tree(&tree, repo, tree_id);
4747 if (err)
4748 goto done;
4749 nentries = got_object_tree_get_nentries(tree);
4750 for (i = 0; i < nentries; i++) {
4751 struct got_tree_entry *te;
4752 char *id = NULL;
4754 if (sigint_received || sigpipe_received)
4755 break;
4757 te = got_object_tree_get_entry(tree, i);
4758 if (show_ids) {
4759 char *id_str;
4760 err = got_object_id_str(&id_str,
4761 got_tree_entry_get_id(te));
4762 if (err)
4763 goto done;
4764 if (asprintf(&id, "%s ", id_str) == -1) {
4765 err = got_error_from_errno("asprintf");
4766 free(id_str);
4767 goto done;
4769 free(id_str);
4771 err = print_entry(te, id, path, root_path, repo);
4772 free(id);
4773 if (err)
4774 goto done;
4776 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4777 char *child_path;
4778 if (asprintf(&child_path, "%s%s%s", path,
4779 path[0] == '/' && path[1] == '\0' ? "" : "/",
4780 got_tree_entry_get_name(te)) == -1) {
4781 err = got_error_from_errno("asprintf");
4782 goto done;
4784 err = print_tree(child_path, commit_id, show_ids, 1,
4785 root_path, repo);
4786 free(child_path);
4787 if (err)
4788 goto done;
4791 done:
4792 if (tree)
4793 got_object_tree_close(tree);
4794 free(tree_id);
4795 return err;
4798 static const struct got_error *
4799 cmd_tree(int argc, char *argv[])
4801 const struct got_error *error;
4802 struct got_repository *repo = NULL;
4803 struct got_worktree *worktree = NULL;
4804 const char *path, *refname = NULL;
4805 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4806 struct got_object_id *commit_id = NULL;
4807 char *commit_id_str = NULL;
4808 int show_ids = 0, recurse = 0;
4809 int ch;
4811 #ifndef PROFILE
4812 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4813 NULL) == -1)
4814 err(1, "pledge");
4815 #endif
4817 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4818 switch (ch) {
4819 case 'c':
4820 commit_id_str = optarg;
4821 break;
4822 case 'r':
4823 repo_path = realpath(optarg, NULL);
4824 if (repo_path == NULL)
4825 return got_error_from_errno2("realpath",
4826 optarg);
4827 got_path_strip_trailing_slashes(repo_path);
4828 break;
4829 case 'i':
4830 show_ids = 1;
4831 break;
4832 case 'R':
4833 recurse = 1;
4834 break;
4835 default:
4836 usage_tree();
4837 /* NOTREACHED */
4841 argc -= optind;
4842 argv += optind;
4844 if (argc == 1)
4845 path = argv[0];
4846 else if (argc > 1)
4847 usage_tree();
4848 else
4849 path = NULL;
4851 cwd = getcwd(NULL, 0);
4852 if (cwd == NULL) {
4853 error = got_error_from_errno("getcwd");
4854 goto done;
4856 if (repo_path == NULL) {
4857 error = got_worktree_open(&worktree, cwd);
4858 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4859 goto done;
4860 else
4861 error = NULL;
4862 if (worktree) {
4863 repo_path =
4864 strdup(got_worktree_get_repo_path(worktree));
4865 if (repo_path == NULL)
4866 error = got_error_from_errno("strdup");
4867 if (error)
4868 goto done;
4869 } else {
4870 repo_path = strdup(cwd);
4871 if (repo_path == NULL) {
4872 error = got_error_from_errno("strdup");
4873 goto done;
4878 error = got_repo_open(&repo, repo_path, NULL);
4879 if (error != NULL)
4880 goto done;
4882 if (worktree) {
4883 const char *prefix = got_worktree_get_path_prefix(worktree);
4884 char *p;
4886 if (path == NULL)
4887 path = "";
4888 error = got_worktree_resolve_path(&p, worktree, path);
4889 if (error)
4890 goto done;
4891 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4892 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4893 p) == -1) {
4894 error = got_error_from_errno("asprintf");
4895 free(p);
4896 goto done;
4898 free(p);
4899 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4900 if (error)
4901 goto done;
4902 } else {
4903 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4904 if (error)
4905 goto done;
4906 if (path == NULL)
4907 path = "/";
4908 error = got_repo_map_path(&in_repo_path, repo, path);
4909 if (error != NULL)
4910 goto done;
4913 if (commit_id_str == NULL) {
4914 struct got_reference *head_ref;
4915 if (worktree)
4916 refname = got_worktree_get_head_ref_name(worktree);
4917 else
4918 refname = GOT_REF_HEAD;
4919 error = got_ref_open(&head_ref, repo, refname, 0);
4920 if (error != NULL)
4921 goto done;
4922 error = got_ref_resolve(&commit_id, repo, head_ref);
4923 got_ref_close(head_ref);
4924 if (error != NULL)
4925 goto done;
4926 } else {
4927 struct got_reflist_head refs;
4928 SIMPLEQ_INIT(&refs);
4929 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4930 NULL);
4931 if (error)
4932 goto done;
4933 error = got_repo_match_object_id(&commit_id, NULL,
4934 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4935 got_ref_list_free(&refs);
4936 if (error)
4937 goto done;
4940 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4941 in_repo_path, repo);
4942 done:
4943 free(in_repo_path);
4944 free(repo_path);
4945 free(cwd);
4946 free(commit_id);
4947 if (worktree)
4948 got_worktree_close(worktree);
4949 if (repo) {
4950 const struct got_error *repo_error;
4951 repo_error = got_repo_close(repo);
4952 if (error == NULL)
4953 error = repo_error;
4955 return error;
4958 __dead static void
4959 usage_status(void)
4961 fprintf(stderr, "usage: %s status [-s status-codes ] [path ...]\n",
4962 getprogname());
4963 exit(1);
4966 static const struct got_error *
4967 print_status(void *arg, unsigned char status, unsigned char staged_status,
4968 const char *path, struct got_object_id *blob_id,
4969 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4970 int dirfd, const char *de_name)
4972 if (status == staged_status && (status == GOT_STATUS_DELETE))
4973 status = GOT_STATUS_NO_CHANGE;
4974 if (arg) {
4975 char *status_codes = arg;
4976 size_t ncodes = strlen(status_codes);
4977 int i;
4978 for (i = 0; i < ncodes ; i++) {
4979 if (status == status_codes[i] ||
4980 staged_status == status_codes[i])
4981 break;
4983 if (i == ncodes)
4984 return NULL;
4986 printf("%c%c %s\n", status, staged_status, path);
4987 return NULL;
4990 static const struct got_error *
4991 cmd_status(int argc, char *argv[])
4993 const struct got_error *error = NULL;
4994 struct got_repository *repo = NULL;
4995 struct got_worktree *worktree = NULL;
4996 char *cwd = NULL, *status_codes = NULL;;
4997 struct got_pathlist_head paths;
4998 struct got_pathlist_entry *pe;
4999 int ch, i;
5001 TAILQ_INIT(&paths);
5003 while ((ch = getopt(argc, argv, "s:")) != -1) {
5004 switch (ch) {
5005 case 's':
5006 for (i = 0; i < strlen(optarg); i++) {
5007 switch (optarg[i]) {
5008 case GOT_STATUS_MODIFY:
5009 case GOT_STATUS_ADD:
5010 case GOT_STATUS_DELETE:
5011 case GOT_STATUS_CONFLICT:
5012 case GOT_STATUS_MISSING:
5013 case GOT_STATUS_OBSTRUCTED:
5014 case GOT_STATUS_UNVERSIONED:
5015 case GOT_STATUS_MODE_CHANGE:
5016 case GOT_STATUS_NONEXISTENT:
5017 break;
5018 default:
5019 errx(1, "invalid status code '%c'",
5020 optarg[i]);
5023 status_codes = optarg;
5024 break;
5025 default:
5026 usage_status();
5027 /* NOTREACHED */
5031 argc -= optind;
5032 argv += optind;
5034 #ifndef PROFILE
5035 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5036 NULL) == -1)
5037 err(1, "pledge");
5038 #endif
5039 cwd = getcwd(NULL, 0);
5040 if (cwd == NULL) {
5041 error = got_error_from_errno("getcwd");
5042 goto done;
5045 error = got_worktree_open(&worktree, cwd);
5046 if (error) {
5047 if (error->code == GOT_ERR_NOT_WORKTREE)
5048 error = wrap_not_worktree_error(error, "status", cwd);
5049 goto done;
5052 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5053 NULL);
5054 if (error != NULL)
5055 goto done;
5057 error = apply_unveil(got_repo_get_path(repo), 1,
5058 got_worktree_get_root_path(worktree));
5059 if (error)
5060 goto done;
5062 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5063 if (error)
5064 goto done;
5066 error = got_worktree_status(worktree, &paths, repo, print_status,
5067 status_codes, check_cancelled, NULL);
5068 done:
5069 TAILQ_FOREACH(pe, &paths, entry)
5070 free((char *)pe->path);
5071 got_pathlist_free(&paths);
5072 free(cwd);
5073 return error;
5076 __dead static void
5077 usage_ref(void)
5079 fprintf(stderr,
5080 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
5081 "[-d] [name]\n",
5082 getprogname());
5083 exit(1);
5086 static const struct got_error *
5087 list_refs(struct got_repository *repo, const char *refname)
5089 static const struct got_error *err = NULL;
5090 struct got_reflist_head refs;
5091 struct got_reflist_entry *re;
5093 SIMPLEQ_INIT(&refs);
5094 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
5095 if (err)
5096 return err;
5098 SIMPLEQ_FOREACH(re, &refs, entry) {
5099 char *refstr;
5100 refstr = got_ref_to_str(re->ref);
5101 if (refstr == NULL)
5102 return got_error_from_errno("got_ref_to_str");
5103 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5104 free(refstr);
5107 got_ref_list_free(&refs);
5108 return NULL;
5111 static const struct got_error *
5112 delete_ref(struct got_repository *repo, const char *refname)
5114 const struct got_error *err = NULL;
5115 struct got_reference *ref;
5117 err = got_ref_open(&ref, repo, refname, 0);
5118 if (err)
5119 return err;
5121 err = got_ref_delete(ref, repo);
5122 got_ref_close(ref);
5123 return err;
5126 static const struct got_error *
5127 add_ref(struct got_repository *repo, const char *refname, const char *target)
5129 const struct got_error *err = NULL;
5130 struct got_object_id *id;
5131 struct got_reference *ref = NULL;
5134 * Don't let the user create a reference name with a leading '-'.
5135 * While technically a valid reference name, this case is usually
5136 * an unintended typo.
5138 if (refname[0] == '-')
5139 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5141 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5142 repo);
5143 if (err) {
5144 struct got_reference *target_ref;
5146 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5147 return err;
5148 err = got_ref_open(&target_ref, repo, target, 0);
5149 if (err)
5150 return err;
5151 err = got_ref_resolve(&id, repo, target_ref);
5152 got_ref_close(target_ref);
5153 if (err)
5154 return err;
5157 err = got_ref_alloc(&ref, refname, id);
5158 if (err)
5159 goto done;
5161 err = got_ref_write(ref, repo);
5162 done:
5163 if (ref)
5164 got_ref_close(ref);
5165 free(id);
5166 return err;
5169 static const struct got_error *
5170 add_symref(struct got_repository *repo, const char *refname, const char *target)
5172 const struct got_error *err = NULL;
5173 struct got_reference *ref = NULL;
5174 struct got_reference *target_ref = NULL;
5177 * Don't let the user create a reference name with a leading '-'.
5178 * While technically a valid reference name, this case is usually
5179 * an unintended typo.
5181 if (refname[0] == '-')
5182 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5184 err = got_ref_open(&target_ref, repo, target, 0);
5185 if (err)
5186 return err;
5188 err = got_ref_alloc_symref(&ref, refname, target_ref);
5189 if (err)
5190 goto done;
5192 err = got_ref_write(ref, repo);
5193 done:
5194 if (target_ref)
5195 got_ref_close(target_ref);
5196 if (ref)
5197 got_ref_close(ref);
5198 return err;
5201 static const struct got_error *
5202 cmd_ref(int argc, char *argv[])
5204 const struct got_error *error = NULL;
5205 struct got_repository *repo = NULL;
5206 struct got_worktree *worktree = NULL;
5207 char *cwd = NULL, *repo_path = NULL;
5208 int ch, do_list = 0, do_delete = 0;
5209 const char *obj_arg = NULL, *symref_target= NULL;
5210 char *refname = NULL;
5212 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5213 switch (ch) {
5214 case 'c':
5215 obj_arg = optarg;
5216 break;
5217 case 'd':
5218 do_delete = 1;
5219 break;
5220 case 'r':
5221 repo_path = realpath(optarg, NULL);
5222 if (repo_path == NULL)
5223 return got_error_from_errno2("realpath",
5224 optarg);
5225 got_path_strip_trailing_slashes(repo_path);
5226 break;
5227 case 'l':
5228 do_list = 1;
5229 break;
5230 case 's':
5231 symref_target = optarg;
5232 break;
5233 default:
5234 usage_ref();
5235 /* NOTREACHED */
5239 if (obj_arg && do_list)
5240 option_conflict('c', 'l');
5241 if (obj_arg && do_delete)
5242 option_conflict('c', 'd');
5243 if (obj_arg && symref_target)
5244 option_conflict('c', 's');
5245 if (symref_target && do_delete)
5246 option_conflict('s', 'd');
5247 if (symref_target && do_list)
5248 option_conflict('s', 'l');
5249 if (do_delete && do_list)
5250 option_conflict('d', 'l');
5252 argc -= optind;
5253 argv += optind;
5255 if (do_list) {
5256 if (argc != 0 && argc != 1)
5257 usage_ref();
5258 if (argc == 1) {
5259 refname = strdup(argv[0]);
5260 if (refname == NULL) {
5261 error = got_error_from_errno("strdup");
5262 goto done;
5265 } else {
5266 if (argc != 1)
5267 usage_ref();
5268 refname = strdup(argv[0]);
5269 if (refname == NULL) {
5270 error = got_error_from_errno("strdup");
5271 goto done;
5275 if (refname)
5276 got_path_strip_trailing_slashes(refname);
5278 #ifndef PROFILE
5279 if (do_list) {
5280 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5281 NULL) == -1)
5282 err(1, "pledge");
5283 } else {
5284 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5285 "sendfd unveil", NULL) == -1)
5286 err(1, "pledge");
5288 #endif
5289 cwd = getcwd(NULL, 0);
5290 if (cwd == NULL) {
5291 error = got_error_from_errno("getcwd");
5292 goto done;
5295 if (repo_path == NULL) {
5296 error = got_worktree_open(&worktree, cwd);
5297 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5298 goto done;
5299 else
5300 error = NULL;
5301 if (worktree) {
5302 repo_path =
5303 strdup(got_worktree_get_repo_path(worktree));
5304 if (repo_path == NULL)
5305 error = got_error_from_errno("strdup");
5306 if (error)
5307 goto done;
5308 } else {
5309 repo_path = strdup(cwd);
5310 if (repo_path == NULL) {
5311 error = got_error_from_errno("strdup");
5312 goto done;
5317 error = got_repo_open(&repo, repo_path, NULL);
5318 if (error != NULL)
5319 goto done;
5321 error = apply_unveil(got_repo_get_path(repo), do_list,
5322 worktree ? got_worktree_get_root_path(worktree) : NULL);
5323 if (error)
5324 goto done;
5326 if (do_list)
5327 error = list_refs(repo, refname);
5328 else if (do_delete)
5329 error = delete_ref(repo, refname);
5330 else if (symref_target)
5331 error = add_symref(repo, refname, symref_target);
5332 else {
5333 if (obj_arg == NULL)
5334 usage_ref();
5335 error = add_ref(repo, refname, obj_arg);
5337 done:
5338 free(refname);
5339 if (repo)
5340 got_repo_close(repo);
5341 if (worktree)
5342 got_worktree_close(worktree);
5343 free(cwd);
5344 free(repo_path);
5345 return error;
5348 __dead static void
5349 usage_branch(void)
5351 fprintf(stderr,
5352 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5353 "[name]\n", getprogname());
5354 exit(1);
5357 static const struct got_error *
5358 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5359 struct got_reference *ref)
5361 const struct got_error *err = NULL;
5362 const char *refname, *marker = " ";
5363 char *refstr;
5365 refname = got_ref_get_name(ref);
5366 if (worktree && strcmp(refname,
5367 got_worktree_get_head_ref_name(worktree)) == 0) {
5368 struct got_object_id *id = NULL;
5370 err = got_ref_resolve(&id, repo, ref);
5371 if (err)
5372 return err;
5373 if (got_object_id_cmp(id,
5374 got_worktree_get_base_commit_id(worktree)) == 0)
5375 marker = "* ";
5376 else
5377 marker = "~ ";
5378 free(id);
5381 if (strncmp(refname, "refs/heads/", 11) == 0)
5382 refname += 11;
5383 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5384 refname += 18;
5386 refstr = got_ref_to_str(ref);
5387 if (refstr == NULL)
5388 return got_error_from_errno("got_ref_to_str");
5390 printf("%s%s: %s\n", marker, refname, refstr);
5391 free(refstr);
5392 return NULL;
5395 static const struct got_error *
5396 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5398 const char *refname;
5400 if (worktree == NULL)
5401 return got_error(GOT_ERR_NOT_WORKTREE);
5403 refname = got_worktree_get_head_ref_name(worktree);
5405 if (strncmp(refname, "refs/heads/", 11) == 0)
5406 refname += 11;
5407 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5408 refname += 18;
5410 printf("%s\n", refname);
5412 return NULL;
5415 static const struct got_error *
5416 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5418 static const struct got_error *err = NULL;
5419 struct got_reflist_head refs;
5420 struct got_reflist_entry *re;
5421 struct got_reference *temp_ref = NULL;
5422 int rebase_in_progress, histedit_in_progress;
5424 SIMPLEQ_INIT(&refs);
5426 if (worktree) {
5427 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5428 worktree);
5429 if (err)
5430 return err;
5432 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5433 worktree);
5434 if (err)
5435 return err;
5437 if (rebase_in_progress || histedit_in_progress) {
5438 err = got_ref_open(&temp_ref, repo,
5439 got_worktree_get_head_ref_name(worktree), 0);
5440 if (err)
5441 return err;
5442 list_branch(repo, worktree, temp_ref);
5443 got_ref_close(temp_ref);
5447 err = got_ref_list(&refs, repo, "refs/heads",
5448 got_ref_cmp_by_name, NULL);
5449 if (err)
5450 return err;
5452 SIMPLEQ_FOREACH(re, &refs, entry)
5453 list_branch(repo, worktree, re->ref);
5455 got_ref_list_free(&refs);
5456 return NULL;
5459 static const struct got_error *
5460 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5461 const char *branch_name)
5463 const struct got_error *err = NULL;
5464 struct got_reference *ref = NULL;
5465 char *refname;
5467 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5468 return got_error_from_errno("asprintf");
5470 err = got_ref_open(&ref, repo, refname, 0);
5471 if (err)
5472 goto done;
5474 if (worktree &&
5475 strcmp(got_worktree_get_head_ref_name(worktree),
5476 got_ref_get_name(ref)) == 0) {
5477 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5478 "will not delete this work tree's current branch");
5479 goto done;
5482 err = got_ref_delete(ref, repo);
5483 done:
5484 if (ref)
5485 got_ref_close(ref);
5486 free(refname);
5487 return err;
5490 static const struct got_error *
5491 add_branch(struct got_repository *repo, const char *branch_name,
5492 struct got_object_id *base_commit_id)
5494 const struct got_error *err = NULL;
5495 struct got_reference *ref = NULL;
5496 char *base_refname = NULL, *refname = NULL;
5499 * Don't let the user create a branch name with a leading '-'.
5500 * While technically a valid reference name, this case is usually
5501 * an unintended typo.
5503 if (branch_name[0] == '-')
5504 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5506 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5507 err = got_error_from_errno("asprintf");
5508 goto done;
5511 err = got_ref_open(&ref, repo, refname, 0);
5512 if (err == NULL) {
5513 err = got_error(GOT_ERR_BRANCH_EXISTS);
5514 goto done;
5515 } else if (err->code != GOT_ERR_NOT_REF)
5516 goto done;
5518 err = got_ref_alloc(&ref, refname, base_commit_id);
5519 if (err)
5520 goto done;
5522 err = got_ref_write(ref, repo);
5523 done:
5524 if (ref)
5525 got_ref_close(ref);
5526 free(base_refname);
5527 free(refname);
5528 return err;
5531 static const struct got_error *
5532 cmd_branch(int argc, char *argv[])
5534 const struct got_error *error = NULL;
5535 struct got_repository *repo = NULL;
5536 struct got_worktree *worktree = NULL;
5537 char *cwd = NULL, *repo_path = NULL;
5538 int ch, do_list = 0, do_show = 0, do_update = 1;
5539 const char *delref = NULL, *commit_id_arg = NULL;
5540 struct got_reference *ref = NULL;
5541 struct got_pathlist_head paths;
5542 struct got_pathlist_entry *pe;
5543 struct got_object_id *commit_id = NULL;
5544 char *commit_id_str = NULL;
5546 TAILQ_INIT(&paths);
5548 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5549 switch (ch) {
5550 case 'c':
5551 commit_id_arg = optarg;
5552 break;
5553 case 'd':
5554 delref = optarg;
5555 break;
5556 case 'r':
5557 repo_path = realpath(optarg, NULL);
5558 if (repo_path == NULL)
5559 return got_error_from_errno2("realpath",
5560 optarg);
5561 got_path_strip_trailing_slashes(repo_path);
5562 break;
5563 case 'l':
5564 do_list = 1;
5565 break;
5566 case 'n':
5567 do_update = 0;
5568 break;
5569 default:
5570 usage_branch();
5571 /* NOTREACHED */
5575 if (do_list && delref)
5576 option_conflict('l', 'd');
5578 argc -= optind;
5579 argv += optind;
5581 if (!do_list && !delref && argc == 0)
5582 do_show = 1;
5584 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5585 errx(1, "-c option can only be used when creating a branch");
5587 if (do_list || delref) {
5588 if (argc > 0)
5589 usage_branch();
5590 } else if (!do_show && argc != 1)
5591 usage_branch();
5593 #ifndef PROFILE
5594 if (do_list || do_show) {
5595 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5596 NULL) == -1)
5597 err(1, "pledge");
5598 } else {
5599 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5600 "sendfd unveil", NULL) == -1)
5601 err(1, "pledge");
5603 #endif
5604 cwd = getcwd(NULL, 0);
5605 if (cwd == NULL) {
5606 error = got_error_from_errno("getcwd");
5607 goto done;
5610 if (repo_path == NULL) {
5611 error = got_worktree_open(&worktree, cwd);
5612 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5613 goto done;
5614 else
5615 error = NULL;
5616 if (worktree) {
5617 repo_path =
5618 strdup(got_worktree_get_repo_path(worktree));
5619 if (repo_path == NULL)
5620 error = got_error_from_errno("strdup");
5621 if (error)
5622 goto done;
5623 } else {
5624 repo_path = strdup(cwd);
5625 if (repo_path == NULL) {
5626 error = got_error_from_errno("strdup");
5627 goto done;
5632 error = got_repo_open(&repo, repo_path, NULL);
5633 if (error != NULL)
5634 goto done;
5636 error = apply_unveil(got_repo_get_path(repo), do_list,
5637 worktree ? got_worktree_get_root_path(worktree) : NULL);
5638 if (error)
5639 goto done;
5641 if (do_show)
5642 error = show_current_branch(repo, worktree);
5643 else if (do_list)
5644 error = list_branches(repo, worktree);
5645 else if (delref)
5646 error = delete_branch(repo, worktree, delref);
5647 else {
5648 struct got_reflist_head refs;
5649 SIMPLEQ_INIT(&refs);
5650 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5651 NULL);
5652 if (error)
5653 goto done;
5654 if (commit_id_arg == NULL)
5655 commit_id_arg = worktree ?
5656 got_worktree_get_head_ref_name(worktree) :
5657 GOT_REF_HEAD;
5658 error = got_repo_match_object_id(&commit_id, NULL,
5659 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5660 got_ref_list_free(&refs);
5661 if (error)
5662 goto done;
5663 error = add_branch(repo, argv[0], commit_id);
5664 if (error)
5665 goto done;
5666 if (worktree && do_update) {
5667 struct got_update_progress_arg upa;
5668 char *branch_refname = NULL;
5670 error = got_object_id_str(&commit_id_str, commit_id);
5671 if (error)
5672 goto done;
5673 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5674 worktree);
5675 if (error)
5676 goto done;
5677 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5678 == -1) {
5679 error = got_error_from_errno("asprintf");
5680 goto done;
5682 error = got_ref_open(&ref, repo, branch_refname, 0);
5683 free(branch_refname);
5684 if (error)
5685 goto done;
5686 error = switch_head_ref(ref, commit_id, worktree,
5687 repo);
5688 if (error)
5689 goto done;
5690 error = got_worktree_set_base_commit_id(worktree, repo,
5691 commit_id);
5692 if (error)
5693 goto done;
5694 memset(&upa, 0, sizeof(upa));
5695 error = got_worktree_checkout_files(worktree, &paths,
5696 repo, update_progress, &upa, check_cancelled,
5697 NULL);
5698 if (error)
5699 goto done;
5700 if (upa.did_something)
5701 printf("Updated to commit %s\n", commit_id_str);
5702 print_update_progress_stats(&upa);
5705 done:
5706 if (ref)
5707 got_ref_close(ref);
5708 if (repo)
5709 got_repo_close(repo);
5710 if (worktree)
5711 got_worktree_close(worktree);
5712 free(cwd);
5713 free(repo_path);
5714 free(commit_id);
5715 free(commit_id_str);
5716 TAILQ_FOREACH(pe, &paths, entry)
5717 free((char *)pe->path);
5718 got_pathlist_free(&paths);
5719 return error;
5723 __dead static void
5724 usage_tag(void)
5726 fprintf(stderr,
5727 "usage: %s tag [-c commit] [-r repository] [-l] "
5728 "[-m message] name\n", getprogname());
5729 exit(1);
5732 #if 0
5733 static const struct got_error *
5734 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5736 const struct got_error *err = NULL;
5737 struct got_reflist_entry *re, *se, *new;
5738 struct got_object_id *re_id, *se_id;
5739 struct got_tag_object *re_tag, *se_tag;
5740 time_t re_time, se_time;
5742 SIMPLEQ_FOREACH(re, tags, entry) {
5743 se = SIMPLEQ_FIRST(sorted);
5744 if (se == NULL) {
5745 err = got_reflist_entry_dup(&new, re);
5746 if (err)
5747 return err;
5748 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5749 continue;
5750 } else {
5751 err = got_ref_resolve(&re_id, repo, re->ref);
5752 if (err)
5753 break;
5754 err = got_object_open_as_tag(&re_tag, repo, re_id);
5755 free(re_id);
5756 if (err)
5757 break;
5758 re_time = got_object_tag_get_tagger_time(re_tag);
5759 got_object_tag_close(re_tag);
5762 while (se) {
5763 err = got_ref_resolve(&se_id, repo, re->ref);
5764 if (err)
5765 break;
5766 err = got_object_open_as_tag(&se_tag, repo, se_id);
5767 free(se_id);
5768 if (err)
5769 break;
5770 se_time = got_object_tag_get_tagger_time(se_tag);
5771 got_object_tag_close(se_tag);
5773 if (se_time > re_time) {
5774 err = got_reflist_entry_dup(&new, re);
5775 if (err)
5776 return err;
5777 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5778 break;
5780 se = SIMPLEQ_NEXT(se, entry);
5781 continue;
5784 done:
5785 return err;
5787 #endif
5789 static const struct got_error *
5790 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5792 static const struct got_error *err = NULL;
5793 struct got_reflist_head refs;
5794 struct got_reflist_entry *re;
5796 SIMPLEQ_INIT(&refs);
5798 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5799 if (err)
5800 return err;
5802 SIMPLEQ_FOREACH(re, &refs, entry) {
5803 const char *refname;
5804 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5805 char datebuf[26];
5806 const char *tagger;
5807 time_t tagger_time;
5808 struct got_object_id *id;
5809 struct got_tag_object *tag;
5810 struct got_commit_object *commit = NULL;
5812 refname = got_ref_get_name(re->ref);
5813 if (strncmp(refname, "refs/tags/", 10) != 0)
5814 continue;
5815 refname += 10;
5816 refstr = got_ref_to_str(re->ref);
5817 if (refstr == NULL) {
5818 err = got_error_from_errno("got_ref_to_str");
5819 break;
5821 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5822 free(refstr);
5824 err = got_ref_resolve(&id, repo, re->ref);
5825 if (err)
5826 break;
5827 err = got_object_open_as_tag(&tag, repo, id);
5828 if (err) {
5829 if (err->code != GOT_ERR_OBJ_TYPE) {
5830 free(id);
5831 break;
5833 /* "lightweight" tag */
5834 err = got_object_open_as_commit(&commit, repo, id);
5835 if (err) {
5836 free(id);
5837 break;
5839 tagger = got_object_commit_get_committer(commit);
5840 tagger_time =
5841 got_object_commit_get_committer_time(commit);
5842 err = got_object_id_str(&id_str, id);
5843 free(id);
5844 if (err)
5845 break;
5846 } else {
5847 free(id);
5848 tagger = got_object_tag_get_tagger(tag);
5849 tagger_time = got_object_tag_get_tagger_time(tag);
5850 err = got_object_id_str(&id_str,
5851 got_object_tag_get_object_id(tag));
5852 if (err)
5853 break;
5855 printf("from: %s\n", tagger);
5856 datestr = get_datestr(&tagger_time, datebuf);
5857 if (datestr)
5858 printf("date: %s UTC\n", datestr);
5859 if (commit)
5860 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5861 else {
5862 switch (got_object_tag_get_object_type(tag)) {
5863 case GOT_OBJ_TYPE_BLOB:
5864 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5865 id_str);
5866 break;
5867 case GOT_OBJ_TYPE_TREE:
5868 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5869 id_str);
5870 break;
5871 case GOT_OBJ_TYPE_COMMIT:
5872 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5873 id_str);
5874 break;
5875 case GOT_OBJ_TYPE_TAG:
5876 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5877 id_str);
5878 break;
5879 default:
5880 break;
5883 free(id_str);
5884 if (commit) {
5885 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5886 if (err)
5887 break;
5888 got_object_commit_close(commit);
5889 } else {
5890 tagmsg0 = strdup(got_object_tag_get_message(tag));
5891 got_object_tag_close(tag);
5892 if (tagmsg0 == NULL) {
5893 err = got_error_from_errno("strdup");
5894 break;
5898 tagmsg = tagmsg0;
5899 do {
5900 line = strsep(&tagmsg, "\n");
5901 if (line)
5902 printf(" %s\n", line);
5903 } while (line);
5904 free(tagmsg0);
5907 got_ref_list_free(&refs);
5908 return NULL;
5911 static const struct got_error *
5912 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5913 const char *tag_name, const char *repo_path)
5915 const struct got_error *err = NULL;
5916 char *template = NULL, *initial_content = NULL;
5917 char *editor = NULL;
5918 int initial_content_len;
5919 int fd = -1;
5921 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5922 err = got_error_from_errno("asprintf");
5923 goto done;
5926 initial_content_len = asprintf(&initial_content,
5927 "\n# tagging commit %s as %s\n",
5928 commit_id_str, tag_name);
5929 if (initial_content_len == -1) {
5930 err = got_error_from_errno("asprintf");
5931 goto done;
5934 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5935 if (err)
5936 goto done;
5938 if (write(fd, initial_content, initial_content_len) == -1) {
5939 err = got_error_from_errno2("write", *tagmsg_path);
5940 goto done;
5943 err = get_editor(&editor);
5944 if (err)
5945 goto done;
5946 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
5947 initial_content_len, 1);
5948 done:
5949 free(initial_content);
5950 free(template);
5951 free(editor);
5953 if (fd != -1 && close(fd) == -1 && err == NULL)
5954 err = got_error_from_errno2("close", *tagmsg_path);
5956 /* Editor is done; we can now apply unveil(2) */
5957 if (err == NULL)
5958 err = apply_unveil(repo_path, 0, NULL);
5959 if (err) {
5960 free(*tagmsg);
5961 *tagmsg = NULL;
5963 return err;
5966 static const struct got_error *
5967 add_tag(struct got_repository *repo, struct got_worktree *worktree,
5968 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
5970 const struct got_error *err = NULL;
5971 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5972 char *label = NULL, *commit_id_str = NULL;
5973 struct got_reference *ref = NULL;
5974 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5975 char *tagmsg_path = NULL, *tag_id_str = NULL;
5976 int preserve_tagmsg = 0;
5977 struct got_reflist_head refs;
5979 SIMPLEQ_INIT(&refs);
5982 * Don't let the user create a tag name with a leading '-'.
5983 * While technically a valid reference name, this case is usually
5984 * an unintended typo.
5986 if (tag_name[0] == '-')
5987 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5989 err = get_author(&tagger, repo, worktree);
5990 if (err)
5991 return err;
5993 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
5994 if (err)
5995 goto done;
5997 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5998 GOT_OBJ_TYPE_COMMIT, &refs, repo);
5999 if (err)
6000 goto done;
6002 err = got_object_id_str(&commit_id_str, commit_id);
6003 if (err)
6004 goto done;
6006 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6007 refname = strdup(tag_name);
6008 if (refname == NULL) {
6009 err = got_error_from_errno("strdup");
6010 goto done;
6012 tag_name += 10;
6013 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6014 err = got_error_from_errno("asprintf");
6015 goto done;
6018 err = got_ref_open(&ref, repo, refname, 0);
6019 if (err == NULL) {
6020 err = got_error(GOT_ERR_TAG_EXISTS);
6021 goto done;
6022 } else if (err->code != GOT_ERR_NOT_REF)
6023 goto done;
6025 if (tagmsg_arg == NULL) {
6026 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6027 tag_name, got_repo_get_path(repo));
6028 if (err) {
6029 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6030 tagmsg_path != NULL)
6031 preserve_tagmsg = 1;
6032 goto done;
6036 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6037 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6038 if (err) {
6039 if (tagmsg_path)
6040 preserve_tagmsg = 1;
6041 goto done;
6044 err = got_ref_alloc(&ref, refname, tag_id);
6045 if (err) {
6046 if (tagmsg_path)
6047 preserve_tagmsg = 1;
6048 goto done;
6051 err = got_ref_write(ref, repo);
6052 if (err) {
6053 if (tagmsg_path)
6054 preserve_tagmsg = 1;
6055 goto done;
6058 err = got_object_id_str(&tag_id_str, tag_id);
6059 if (err) {
6060 if (tagmsg_path)
6061 preserve_tagmsg = 1;
6062 goto done;
6064 printf("Created tag %s\n", tag_id_str);
6065 done:
6066 if (preserve_tagmsg) {
6067 fprintf(stderr, "%s: tag message preserved in %s\n",
6068 getprogname(), tagmsg_path);
6069 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6070 err = got_error_from_errno2("unlink", tagmsg_path);
6071 free(tag_id_str);
6072 if (ref)
6073 got_ref_close(ref);
6074 free(commit_id);
6075 free(commit_id_str);
6076 free(refname);
6077 free(tagmsg);
6078 free(tagmsg_path);
6079 free(tagger);
6080 got_ref_list_free(&refs);
6081 return err;
6084 static const struct got_error *
6085 cmd_tag(int argc, char *argv[])
6087 const struct got_error *error = NULL;
6088 struct got_repository *repo = NULL;
6089 struct got_worktree *worktree = NULL;
6090 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6091 char *gitconfig_path = NULL;
6092 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6093 int ch, do_list = 0;
6095 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6096 switch (ch) {
6097 case 'c':
6098 commit_id_arg = optarg;
6099 break;
6100 case 'm':
6101 tagmsg = optarg;
6102 break;
6103 case 'r':
6104 repo_path = realpath(optarg, NULL);
6105 if (repo_path == NULL)
6106 return got_error_from_errno2("realpath",
6107 optarg);
6108 got_path_strip_trailing_slashes(repo_path);
6109 break;
6110 case 'l':
6111 do_list = 1;
6112 break;
6113 default:
6114 usage_tag();
6115 /* NOTREACHED */
6119 argc -= optind;
6120 argv += optind;
6122 if (do_list) {
6123 if (commit_id_arg != NULL)
6124 errx(1,
6125 "-c option can only be used when creating a tag");
6126 if (tagmsg)
6127 option_conflict('l', 'm');
6128 if (argc > 0)
6129 usage_tag();
6130 } else if (argc != 1)
6131 usage_tag();
6133 tag_name = argv[0];
6135 #ifndef PROFILE
6136 if (do_list) {
6137 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6138 NULL) == -1)
6139 err(1, "pledge");
6140 } else {
6141 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6142 "sendfd unveil", NULL) == -1)
6143 err(1, "pledge");
6145 #endif
6146 cwd = getcwd(NULL, 0);
6147 if (cwd == NULL) {
6148 error = got_error_from_errno("getcwd");
6149 goto done;
6152 if (repo_path == NULL) {
6153 error = got_worktree_open(&worktree, cwd);
6154 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6155 goto done;
6156 else
6157 error = NULL;
6158 if (worktree) {
6159 repo_path =
6160 strdup(got_worktree_get_repo_path(worktree));
6161 if (repo_path == NULL)
6162 error = got_error_from_errno("strdup");
6163 if (error)
6164 goto done;
6165 } else {
6166 repo_path = strdup(cwd);
6167 if (repo_path == NULL) {
6168 error = got_error_from_errno("strdup");
6169 goto done;
6174 if (do_list) {
6175 error = got_repo_open(&repo, repo_path, NULL);
6176 if (error != NULL)
6177 goto done;
6178 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6179 if (error)
6180 goto done;
6181 error = list_tags(repo, worktree);
6182 } else {
6183 error = get_gitconfig_path(&gitconfig_path);
6184 if (error)
6185 goto done;
6186 error = got_repo_open(&repo, repo_path, gitconfig_path);
6187 if (error != NULL)
6188 goto done;
6190 if (tagmsg) {
6191 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6192 if (error)
6193 goto done;
6196 if (commit_id_arg == NULL) {
6197 struct got_reference *head_ref;
6198 struct got_object_id *commit_id;
6199 error = got_ref_open(&head_ref, repo,
6200 worktree ? got_worktree_get_head_ref_name(worktree)
6201 : GOT_REF_HEAD, 0);
6202 if (error)
6203 goto done;
6204 error = got_ref_resolve(&commit_id, repo, head_ref);
6205 got_ref_close(head_ref);
6206 if (error)
6207 goto done;
6208 error = got_object_id_str(&commit_id_str, commit_id);
6209 free(commit_id);
6210 if (error)
6211 goto done;
6214 error = add_tag(repo, worktree, tag_name,
6215 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6217 done:
6218 if (repo)
6219 got_repo_close(repo);
6220 if (worktree)
6221 got_worktree_close(worktree);
6222 free(cwd);
6223 free(repo_path);
6224 free(gitconfig_path);
6225 free(commit_id_str);
6226 return error;
6229 __dead static void
6230 usage_add(void)
6232 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6233 getprogname());
6234 exit(1);
6237 static const struct got_error *
6238 add_progress(void *arg, unsigned char status, const char *path)
6240 while (path[0] == '/')
6241 path++;
6242 printf("%c %s\n", status, path);
6243 return NULL;
6246 static const struct got_error *
6247 cmd_add(int argc, char *argv[])
6249 const struct got_error *error = NULL;
6250 struct got_repository *repo = NULL;
6251 struct got_worktree *worktree = NULL;
6252 char *cwd = NULL;
6253 struct got_pathlist_head paths;
6254 struct got_pathlist_entry *pe;
6255 int ch, can_recurse = 0, no_ignores = 0;
6257 TAILQ_INIT(&paths);
6259 while ((ch = getopt(argc, argv, "IR")) != -1) {
6260 switch (ch) {
6261 case 'I':
6262 no_ignores = 1;
6263 break;
6264 case 'R':
6265 can_recurse = 1;
6266 break;
6267 default:
6268 usage_add();
6269 /* NOTREACHED */
6273 argc -= optind;
6274 argv += optind;
6276 #ifndef PROFILE
6277 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6278 NULL) == -1)
6279 err(1, "pledge");
6280 #endif
6281 if (argc < 1)
6282 usage_add();
6284 cwd = getcwd(NULL, 0);
6285 if (cwd == NULL) {
6286 error = got_error_from_errno("getcwd");
6287 goto done;
6290 error = got_worktree_open(&worktree, cwd);
6291 if (error) {
6292 if (error->code == GOT_ERR_NOT_WORKTREE)
6293 error = wrap_not_worktree_error(error, "add", cwd);
6294 goto done;
6297 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6298 NULL);
6299 if (error != NULL)
6300 goto done;
6302 error = apply_unveil(got_repo_get_path(repo), 1,
6303 got_worktree_get_root_path(worktree));
6304 if (error)
6305 goto done;
6307 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6308 if (error)
6309 goto done;
6311 if (!can_recurse && no_ignores) {
6312 error = got_error_msg(GOT_ERR_BAD_PATH,
6313 "disregarding ignores requires -R option");
6314 goto done;
6318 if (!can_recurse) {
6319 char *ondisk_path;
6320 struct stat sb;
6321 TAILQ_FOREACH(pe, &paths, entry) {
6322 if (asprintf(&ondisk_path, "%s/%s",
6323 got_worktree_get_root_path(worktree),
6324 pe->path) == -1) {
6325 error = got_error_from_errno("asprintf");
6326 goto done;
6328 if (lstat(ondisk_path, &sb) == -1) {
6329 if (errno == ENOENT) {
6330 free(ondisk_path);
6331 continue;
6333 error = got_error_from_errno2("lstat",
6334 ondisk_path);
6335 free(ondisk_path);
6336 goto done;
6338 free(ondisk_path);
6339 if (S_ISDIR(sb.st_mode)) {
6340 error = got_error_msg(GOT_ERR_BAD_PATH,
6341 "adding directories requires -R option");
6342 goto done;
6347 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6348 NULL, repo, no_ignores);
6349 done:
6350 if (repo)
6351 got_repo_close(repo);
6352 if (worktree)
6353 got_worktree_close(worktree);
6354 TAILQ_FOREACH(pe, &paths, entry)
6355 free((char *)pe->path);
6356 got_pathlist_free(&paths);
6357 free(cwd);
6358 return error;
6361 __dead static void
6362 usage_remove(void)
6364 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6365 "path ...\n", getprogname());
6366 exit(1);
6369 static const struct got_error *
6370 print_remove_status(void *arg, unsigned char status,
6371 unsigned char staged_status, const char *path)
6373 while (path[0] == '/')
6374 path++;
6375 if (status == GOT_STATUS_NONEXISTENT)
6376 return NULL;
6377 if (status == staged_status && (status == GOT_STATUS_DELETE))
6378 status = GOT_STATUS_NO_CHANGE;
6379 printf("%c%c %s\n", status, staged_status, path);
6380 return NULL;
6383 static const struct got_error *
6384 cmd_remove(int argc, char *argv[])
6386 const struct got_error *error = NULL;
6387 struct got_worktree *worktree = NULL;
6388 struct got_repository *repo = NULL;
6389 const char *status_codes = NULL;
6390 char *cwd = NULL;
6391 struct got_pathlist_head paths;
6392 struct got_pathlist_entry *pe;
6393 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6395 TAILQ_INIT(&paths);
6397 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6398 switch (ch) {
6399 case 'f':
6400 delete_local_mods = 1;
6401 break;
6402 case 'k':
6403 keep_on_disk = 1;
6404 break;
6405 case 'R':
6406 can_recurse = 1;
6407 break;
6408 case 's':
6409 for (i = 0; i < strlen(optarg); i++) {
6410 switch (optarg[i]) {
6411 case GOT_STATUS_MODIFY:
6412 delete_local_mods = 1;
6413 break;
6414 case GOT_STATUS_MISSING:
6415 break;
6416 default:
6417 errx(1, "invalid status code '%c'",
6418 optarg[i]);
6421 status_codes = optarg;
6422 break;
6423 default:
6424 usage_remove();
6425 /* NOTREACHED */
6429 argc -= optind;
6430 argv += optind;
6432 #ifndef PROFILE
6433 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6434 NULL) == -1)
6435 err(1, "pledge");
6436 #endif
6437 if (argc < 1)
6438 usage_remove();
6440 cwd = getcwd(NULL, 0);
6441 if (cwd == NULL) {
6442 error = got_error_from_errno("getcwd");
6443 goto done;
6445 error = got_worktree_open(&worktree, cwd);
6446 if (error) {
6447 if (error->code == GOT_ERR_NOT_WORKTREE)
6448 error = wrap_not_worktree_error(error, "remove", cwd);
6449 goto done;
6452 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6453 NULL);
6454 if (error)
6455 goto done;
6457 error = apply_unveil(got_repo_get_path(repo), 1,
6458 got_worktree_get_root_path(worktree));
6459 if (error)
6460 goto done;
6462 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6463 if (error)
6464 goto done;
6466 if (!can_recurse) {
6467 char *ondisk_path;
6468 struct stat sb;
6469 TAILQ_FOREACH(pe, &paths, entry) {
6470 if (asprintf(&ondisk_path, "%s/%s",
6471 got_worktree_get_root_path(worktree),
6472 pe->path) == -1) {
6473 error = got_error_from_errno("asprintf");
6474 goto done;
6476 if (lstat(ondisk_path, &sb) == -1) {
6477 if (errno == ENOENT) {
6478 free(ondisk_path);
6479 continue;
6481 error = got_error_from_errno2("lstat",
6482 ondisk_path);
6483 free(ondisk_path);
6484 goto done;
6486 free(ondisk_path);
6487 if (S_ISDIR(sb.st_mode)) {
6488 error = got_error_msg(GOT_ERR_BAD_PATH,
6489 "removing directories requires -R option");
6490 goto done;
6495 error = got_worktree_schedule_delete(worktree, &paths,
6496 delete_local_mods, status_codes, print_remove_status, NULL,
6497 repo, keep_on_disk);
6498 done:
6499 if (repo)
6500 got_repo_close(repo);
6501 if (worktree)
6502 got_worktree_close(worktree);
6503 TAILQ_FOREACH(pe, &paths, entry)
6504 free((char *)pe->path);
6505 got_pathlist_free(&paths);
6506 free(cwd);
6507 return error;
6510 __dead static void
6511 usage_revert(void)
6513 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6514 "path ...\n", getprogname());
6515 exit(1);
6518 static const struct got_error *
6519 revert_progress(void *arg, unsigned char status, const char *path)
6521 if (status == GOT_STATUS_UNVERSIONED)
6522 return NULL;
6524 while (path[0] == '/')
6525 path++;
6526 printf("%c %s\n", status, path);
6527 return NULL;
6530 struct choose_patch_arg {
6531 FILE *patch_script_file;
6532 const char *action;
6535 static const struct got_error *
6536 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6537 int nchanges, const char *action)
6539 char *line = NULL;
6540 size_t linesize = 0;
6541 ssize_t linelen;
6543 switch (status) {
6544 case GOT_STATUS_ADD:
6545 printf("A %s\n%s this addition? [y/n] ", path, action);
6546 break;
6547 case GOT_STATUS_DELETE:
6548 printf("D %s\n%s this deletion? [y/n] ", path, action);
6549 break;
6550 case GOT_STATUS_MODIFY:
6551 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6552 return got_error_from_errno("fseek");
6553 printf(GOT_COMMIT_SEP_STR);
6554 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6555 printf("%s", line);
6556 if (ferror(patch_file))
6557 return got_error_from_errno("getline");
6558 printf(GOT_COMMIT_SEP_STR);
6559 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6560 path, n, nchanges, action);
6561 break;
6562 default:
6563 return got_error_path(path, GOT_ERR_FILE_STATUS);
6566 return NULL;
6569 static const struct got_error *
6570 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6571 FILE *patch_file, int n, int nchanges)
6573 const struct got_error *err = NULL;
6574 char *line = NULL;
6575 size_t linesize = 0;
6576 ssize_t linelen;
6577 int resp = ' ';
6578 struct choose_patch_arg *a = arg;
6580 *choice = GOT_PATCH_CHOICE_NONE;
6582 if (a->patch_script_file) {
6583 char *nl;
6584 err = show_change(status, path, patch_file, n, nchanges,
6585 a->action);
6586 if (err)
6587 return err;
6588 linelen = getline(&line, &linesize, a->patch_script_file);
6589 if (linelen == -1) {
6590 if (ferror(a->patch_script_file))
6591 return got_error_from_errno("getline");
6592 return NULL;
6594 nl = strchr(line, '\n');
6595 if (nl)
6596 *nl = '\0';
6597 if (strcmp(line, "y") == 0) {
6598 *choice = GOT_PATCH_CHOICE_YES;
6599 printf("y\n");
6600 } else if (strcmp(line, "n") == 0) {
6601 *choice = GOT_PATCH_CHOICE_NO;
6602 printf("n\n");
6603 } else if (strcmp(line, "q") == 0 &&
6604 status == GOT_STATUS_MODIFY) {
6605 *choice = GOT_PATCH_CHOICE_QUIT;
6606 printf("q\n");
6607 } else
6608 printf("invalid response '%s'\n", line);
6609 free(line);
6610 return NULL;
6613 while (resp != 'y' && resp != 'n' && resp != 'q') {
6614 err = show_change(status, path, patch_file, n, nchanges,
6615 a->action);
6616 if (err)
6617 return err;
6618 resp = getchar();
6619 if (resp == '\n')
6620 resp = getchar();
6621 if (status == GOT_STATUS_MODIFY) {
6622 if (resp != 'y' && resp != 'n' && resp != 'q') {
6623 printf("invalid response '%c'\n", resp);
6624 resp = ' ';
6626 } else if (resp != 'y' && resp != 'n') {
6627 printf("invalid response '%c'\n", resp);
6628 resp = ' ';
6632 if (resp == 'y')
6633 *choice = GOT_PATCH_CHOICE_YES;
6634 else if (resp == 'n')
6635 *choice = GOT_PATCH_CHOICE_NO;
6636 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6637 *choice = GOT_PATCH_CHOICE_QUIT;
6639 return NULL;
6643 static const struct got_error *
6644 cmd_revert(int argc, char *argv[])
6646 const struct got_error *error = NULL;
6647 struct got_worktree *worktree = NULL;
6648 struct got_repository *repo = NULL;
6649 char *cwd = NULL, *path = NULL;
6650 struct got_pathlist_head paths;
6651 struct got_pathlist_entry *pe;
6652 int ch, can_recurse = 0, pflag = 0;
6653 FILE *patch_script_file = NULL;
6654 const char *patch_script_path = NULL;
6655 struct choose_patch_arg cpa;
6657 TAILQ_INIT(&paths);
6659 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6660 switch (ch) {
6661 case 'p':
6662 pflag = 1;
6663 break;
6664 case 'F':
6665 patch_script_path = optarg;
6666 break;
6667 case 'R':
6668 can_recurse = 1;
6669 break;
6670 default:
6671 usage_revert();
6672 /* NOTREACHED */
6676 argc -= optind;
6677 argv += optind;
6679 #ifndef PROFILE
6680 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6681 "unveil", NULL) == -1)
6682 err(1, "pledge");
6683 #endif
6684 if (argc < 1)
6685 usage_revert();
6686 if (patch_script_path && !pflag)
6687 errx(1, "-F option can only be used together with -p option");
6689 cwd = getcwd(NULL, 0);
6690 if (cwd == NULL) {
6691 error = got_error_from_errno("getcwd");
6692 goto done;
6694 error = got_worktree_open(&worktree, cwd);
6695 if (error) {
6696 if (error->code == GOT_ERR_NOT_WORKTREE)
6697 error = wrap_not_worktree_error(error, "revert", cwd);
6698 goto done;
6701 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6702 NULL);
6703 if (error != NULL)
6704 goto done;
6706 if (patch_script_path) {
6707 patch_script_file = fopen(patch_script_path, "r");
6708 if (patch_script_file == NULL) {
6709 error = got_error_from_errno2("fopen",
6710 patch_script_path);
6711 goto done;
6714 error = apply_unveil(got_repo_get_path(repo), 1,
6715 got_worktree_get_root_path(worktree));
6716 if (error)
6717 goto done;
6719 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6720 if (error)
6721 goto done;
6723 if (!can_recurse) {
6724 char *ondisk_path;
6725 struct stat sb;
6726 TAILQ_FOREACH(pe, &paths, entry) {
6727 if (asprintf(&ondisk_path, "%s/%s",
6728 got_worktree_get_root_path(worktree),
6729 pe->path) == -1) {
6730 error = got_error_from_errno("asprintf");
6731 goto done;
6733 if (lstat(ondisk_path, &sb) == -1) {
6734 if (errno == ENOENT) {
6735 free(ondisk_path);
6736 continue;
6738 error = got_error_from_errno2("lstat",
6739 ondisk_path);
6740 free(ondisk_path);
6741 goto done;
6743 free(ondisk_path);
6744 if (S_ISDIR(sb.st_mode)) {
6745 error = got_error_msg(GOT_ERR_BAD_PATH,
6746 "reverting directories requires -R option");
6747 goto done;
6752 cpa.patch_script_file = patch_script_file;
6753 cpa.action = "revert";
6754 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6755 pflag ? choose_patch : NULL, &cpa, repo);
6756 done:
6757 if (patch_script_file && fclose(patch_script_file) == EOF &&
6758 error == NULL)
6759 error = got_error_from_errno2("fclose", patch_script_path);
6760 if (repo)
6761 got_repo_close(repo);
6762 if (worktree)
6763 got_worktree_close(worktree);
6764 free(path);
6765 free(cwd);
6766 return error;
6769 __dead static void
6770 usage_commit(void)
6772 fprintf(stderr, "usage: %s commit [-m msg] [-S] [path ...]\n",
6773 getprogname());
6774 exit(1);
6777 struct collect_commit_logmsg_arg {
6778 const char *cmdline_log;
6779 const char *editor;
6780 const char *worktree_path;
6781 const char *branch_name;
6782 const char *repo_path;
6783 char *logmsg_path;
6787 static const struct got_error *
6788 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6789 void *arg)
6791 char *initial_content = NULL;
6792 struct got_pathlist_entry *pe;
6793 const struct got_error *err = NULL;
6794 char *template = NULL;
6795 struct collect_commit_logmsg_arg *a = arg;
6796 int initial_content_len;
6797 int fd = -1;
6798 size_t len;
6800 /* if a message was specified on the command line, just use it */
6801 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6802 len = strlen(a->cmdline_log) + 1;
6803 *logmsg = malloc(len + 1);
6804 if (*logmsg == NULL)
6805 return got_error_from_errno("malloc");
6806 strlcpy(*logmsg, a->cmdline_log, len);
6807 return NULL;
6810 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6811 return got_error_from_errno("asprintf");
6813 initial_content_len = asprintf(&initial_content,
6814 "\n# changes to be committed on branch %s:\n",
6815 a->branch_name);
6816 if (initial_content_len == -1)
6817 return got_error_from_errno("asprintf");
6819 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6820 if (err)
6821 goto done;
6823 if (write(fd, initial_content, initial_content_len) == -1) {
6824 err = got_error_from_errno2("write", a->logmsg_path);
6825 goto done;
6828 TAILQ_FOREACH(pe, commitable_paths, entry) {
6829 struct got_commitable *ct = pe->data;
6830 dprintf(fd, "# %c %s\n",
6831 got_commitable_get_status(ct),
6832 got_commitable_get_path(ct));
6835 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
6836 initial_content_len, 1);
6837 done:
6838 free(initial_content);
6839 free(template);
6841 if (fd != -1 && close(fd) == -1 && err == NULL)
6842 err = got_error_from_errno2("close", a->logmsg_path);
6844 /* Editor is done; we can now apply unveil(2) */
6845 if (err == NULL)
6846 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6847 if (err) {
6848 free(*logmsg);
6849 *logmsg = NULL;
6851 return err;
6854 static const struct got_error *
6855 cmd_commit(int argc, char *argv[])
6857 const struct got_error *error = NULL;
6858 struct got_worktree *worktree = NULL;
6859 struct got_repository *repo = NULL;
6860 char *cwd = NULL, *id_str = NULL;
6861 struct got_object_id *id = NULL;
6862 const char *logmsg = NULL;
6863 struct collect_commit_logmsg_arg cl_arg;
6864 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6865 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6866 int allow_bad_symlinks = 0;
6867 struct got_pathlist_head paths;
6869 TAILQ_INIT(&paths);
6870 cl_arg.logmsg_path = NULL;
6872 while ((ch = getopt(argc, argv, "m:S")) != -1) {
6873 switch (ch) {
6874 case 'm':
6875 logmsg = optarg;
6876 break;
6877 case 'S':
6878 allow_bad_symlinks = 1;
6879 break;
6880 default:
6881 usage_commit();
6882 /* NOTREACHED */
6886 argc -= optind;
6887 argv += optind;
6889 #ifndef PROFILE
6890 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6891 "unveil", NULL) == -1)
6892 err(1, "pledge");
6893 #endif
6894 cwd = getcwd(NULL, 0);
6895 if (cwd == NULL) {
6896 error = got_error_from_errno("getcwd");
6897 goto done;
6899 error = got_worktree_open(&worktree, cwd);
6900 if (error) {
6901 if (error->code == GOT_ERR_NOT_WORKTREE)
6902 error = wrap_not_worktree_error(error, "commit", cwd);
6903 goto done;
6906 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6907 if (error)
6908 goto done;
6909 if (rebase_in_progress) {
6910 error = got_error(GOT_ERR_REBASING);
6911 goto done;
6914 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6915 worktree);
6916 if (error)
6917 goto done;
6919 error = get_gitconfig_path(&gitconfig_path);
6920 if (error)
6921 goto done;
6922 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6923 gitconfig_path);
6924 if (error != NULL)
6925 goto done;
6927 error = get_author(&author, repo, worktree);
6928 if (error)
6929 return error;
6932 * unveil(2) traverses exec(2); if an editor is used we have
6933 * to apply unveil after the log message has been written.
6935 if (logmsg == NULL || strlen(logmsg) == 0)
6936 error = get_editor(&editor);
6937 else
6938 error = apply_unveil(got_repo_get_path(repo), 0,
6939 got_worktree_get_root_path(worktree));
6940 if (error)
6941 goto done;
6943 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6944 if (error)
6945 goto done;
6947 cl_arg.editor = editor;
6948 cl_arg.cmdline_log = logmsg;
6949 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6950 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6951 if (!histedit_in_progress) {
6952 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6953 error = got_error(GOT_ERR_COMMIT_BRANCH);
6954 goto done;
6956 cl_arg.branch_name += 11;
6958 cl_arg.repo_path = got_repo_get_path(repo);
6959 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6960 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
6961 print_status, NULL, repo);
6962 if (error) {
6963 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6964 cl_arg.logmsg_path != NULL)
6965 preserve_logmsg = 1;
6966 goto done;
6969 error = got_object_id_str(&id_str, id);
6970 if (error)
6971 goto done;
6972 printf("Created commit %s\n", id_str);
6973 done:
6974 if (preserve_logmsg) {
6975 fprintf(stderr, "%s: log message preserved in %s\n",
6976 getprogname(), cl_arg.logmsg_path);
6977 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6978 error == NULL)
6979 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6980 free(cl_arg.logmsg_path);
6981 if (repo)
6982 got_repo_close(repo);
6983 if (worktree)
6984 got_worktree_close(worktree);
6985 free(cwd);
6986 free(id_str);
6987 free(gitconfig_path);
6988 free(editor);
6989 free(author);
6990 return error;
6993 __dead static void
6994 usage_cherrypick(void)
6996 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6997 exit(1);
7000 static const struct got_error *
7001 cmd_cherrypick(int argc, char *argv[])
7003 const struct got_error *error = NULL;
7004 struct got_worktree *worktree = NULL;
7005 struct got_repository *repo = NULL;
7006 char *cwd = NULL, *commit_id_str = NULL;
7007 struct got_object_id *commit_id = NULL;
7008 struct got_commit_object *commit = NULL;
7009 struct got_object_qid *pid;
7010 struct got_reference *head_ref = NULL;
7011 int ch;
7012 struct got_update_progress_arg upa;
7014 while ((ch = getopt(argc, argv, "")) != -1) {
7015 switch (ch) {
7016 default:
7017 usage_cherrypick();
7018 /* NOTREACHED */
7022 argc -= optind;
7023 argv += optind;
7025 #ifndef PROFILE
7026 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7027 "unveil", NULL) == -1)
7028 err(1, "pledge");
7029 #endif
7030 if (argc != 1)
7031 usage_cherrypick();
7033 cwd = getcwd(NULL, 0);
7034 if (cwd == NULL) {
7035 error = got_error_from_errno("getcwd");
7036 goto done;
7038 error = got_worktree_open(&worktree, cwd);
7039 if (error) {
7040 if (error->code == GOT_ERR_NOT_WORKTREE)
7041 error = wrap_not_worktree_error(error, "cherrypick",
7042 cwd);
7043 goto done;
7046 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7047 NULL);
7048 if (error != NULL)
7049 goto done;
7051 error = apply_unveil(got_repo_get_path(repo), 0,
7052 got_worktree_get_root_path(worktree));
7053 if (error)
7054 goto done;
7056 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7057 GOT_OBJ_TYPE_COMMIT, repo);
7058 if (error != NULL) {
7059 struct got_reference *ref;
7060 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7061 goto done;
7062 error = got_ref_open(&ref, repo, argv[0], 0);
7063 if (error != NULL)
7064 goto done;
7065 error = got_ref_resolve(&commit_id, repo, ref);
7066 got_ref_close(ref);
7067 if (error != NULL)
7068 goto done;
7070 error = got_object_id_str(&commit_id_str, commit_id);
7071 if (error)
7072 goto done;
7074 error = got_ref_open(&head_ref, repo,
7075 got_worktree_get_head_ref_name(worktree), 0);
7076 if (error != NULL)
7077 goto done;
7079 error = check_same_branch(commit_id, head_ref, NULL, repo);
7080 if (error) {
7081 if (error->code != GOT_ERR_ANCESTRY)
7082 goto done;
7083 error = NULL;
7084 } else {
7085 error = got_error(GOT_ERR_SAME_BRANCH);
7086 goto done;
7089 error = got_object_open_as_commit(&commit, repo, commit_id);
7090 if (error)
7091 goto done;
7092 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7093 memset(&upa, 0, sizeof(upa));
7094 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
7095 commit_id, repo, update_progress, &upa, check_cancelled,
7096 NULL);
7097 if (error != NULL)
7098 goto done;
7100 if (upa.did_something)
7101 printf("Merged commit %s\n", commit_id_str);
7102 print_update_progress_stats(&upa);
7103 done:
7104 if (commit)
7105 got_object_commit_close(commit);
7106 free(commit_id_str);
7107 if (head_ref)
7108 got_ref_close(head_ref);
7109 if (worktree)
7110 got_worktree_close(worktree);
7111 if (repo)
7112 got_repo_close(repo);
7113 return error;
7116 __dead static void
7117 usage_backout(void)
7119 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
7120 exit(1);
7123 static const struct got_error *
7124 cmd_backout(int argc, char *argv[])
7126 const struct got_error *error = NULL;
7127 struct got_worktree *worktree = NULL;
7128 struct got_repository *repo = NULL;
7129 char *cwd = NULL, *commit_id_str = NULL;
7130 struct got_object_id *commit_id = NULL;
7131 struct got_commit_object *commit = NULL;
7132 struct got_object_qid *pid;
7133 struct got_reference *head_ref = NULL;
7134 int ch;
7135 struct got_update_progress_arg upa;
7137 while ((ch = getopt(argc, argv, "")) != -1) {
7138 switch (ch) {
7139 default:
7140 usage_backout();
7141 /* NOTREACHED */
7145 argc -= optind;
7146 argv += optind;
7148 #ifndef PROFILE
7149 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7150 "unveil", NULL) == -1)
7151 err(1, "pledge");
7152 #endif
7153 if (argc != 1)
7154 usage_backout();
7156 cwd = getcwd(NULL, 0);
7157 if (cwd == NULL) {
7158 error = got_error_from_errno("getcwd");
7159 goto done;
7161 error = got_worktree_open(&worktree, cwd);
7162 if (error) {
7163 if (error->code == GOT_ERR_NOT_WORKTREE)
7164 error = wrap_not_worktree_error(error, "backout", cwd);
7165 goto done;
7168 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7169 NULL);
7170 if (error != NULL)
7171 goto done;
7173 error = apply_unveil(got_repo_get_path(repo), 0,
7174 got_worktree_get_root_path(worktree));
7175 if (error)
7176 goto done;
7178 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7179 GOT_OBJ_TYPE_COMMIT, repo);
7180 if (error != NULL) {
7181 struct got_reference *ref;
7182 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7183 goto done;
7184 error = got_ref_open(&ref, repo, argv[0], 0);
7185 if (error != NULL)
7186 goto done;
7187 error = got_ref_resolve(&commit_id, repo, ref);
7188 got_ref_close(ref);
7189 if (error != NULL)
7190 goto done;
7192 error = got_object_id_str(&commit_id_str, commit_id);
7193 if (error)
7194 goto done;
7196 error = got_ref_open(&head_ref, repo,
7197 got_worktree_get_head_ref_name(worktree), 0);
7198 if (error != NULL)
7199 goto done;
7201 error = check_same_branch(commit_id, head_ref, NULL, repo);
7202 if (error)
7203 goto done;
7205 error = got_object_open_as_commit(&commit, repo, commit_id);
7206 if (error)
7207 goto done;
7208 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7209 if (pid == NULL) {
7210 error = got_error(GOT_ERR_ROOT_COMMIT);
7211 goto done;
7214 memset(&upa, 0, sizeof(upa));
7215 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
7216 update_progress, &upa, check_cancelled, NULL);
7217 if (error != NULL)
7218 goto done;
7220 if (upa.did_something)
7221 printf("Backed out commit %s\n", commit_id_str);
7222 print_update_progress_stats(&upa);
7223 done:
7224 if (commit)
7225 got_object_commit_close(commit);
7226 free(commit_id_str);
7227 if (head_ref)
7228 got_ref_close(head_ref);
7229 if (worktree)
7230 got_worktree_close(worktree);
7231 if (repo)
7232 got_repo_close(repo);
7233 return error;
7236 __dead static void
7237 usage_rebase(void)
7239 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
7240 getprogname());
7241 exit(1);
7244 void
7245 trim_logmsg(char *logmsg, int limit)
7247 char *nl;
7248 size_t len;
7250 len = strlen(logmsg);
7251 if (len > limit)
7252 len = limit;
7253 logmsg[len] = '\0';
7254 nl = strchr(logmsg, '\n');
7255 if (nl)
7256 *nl = '\0';
7259 static const struct got_error *
7260 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
7262 const struct got_error *err;
7263 char *logmsg0 = NULL;
7264 const char *s;
7266 err = got_object_commit_get_logmsg(&logmsg0, commit);
7267 if (err)
7268 return err;
7270 s = logmsg0;
7271 while (isspace((unsigned char)s[0]))
7272 s++;
7274 *logmsg = strdup(s);
7275 if (*logmsg == NULL) {
7276 err = got_error_from_errno("strdup");
7277 goto done;
7280 trim_logmsg(*logmsg, limit);
7281 done:
7282 free(logmsg0);
7283 return err;
7286 static const struct got_error *
7287 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
7289 const struct got_error *err;
7290 struct got_commit_object *commit = NULL;
7291 char *id_str = NULL, *logmsg = NULL;
7293 err = got_object_open_as_commit(&commit, repo, id);
7294 if (err)
7295 return err;
7297 err = got_object_id_str(&id_str, id);
7298 if (err)
7299 goto done;
7301 id_str[12] = '\0';
7303 err = get_short_logmsg(&logmsg, 42, commit);
7304 if (err)
7305 goto done;
7307 printf("%s -> merge conflict: %s\n", id_str, logmsg);
7308 done:
7309 free(id_str);
7310 got_object_commit_close(commit);
7311 free(logmsg);
7312 return err;
7315 static const struct got_error *
7316 show_rebase_progress(struct got_commit_object *commit,
7317 struct got_object_id *old_id, struct got_object_id *new_id)
7319 const struct got_error *err;
7320 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7322 err = got_object_id_str(&old_id_str, old_id);
7323 if (err)
7324 goto done;
7326 if (new_id) {
7327 err = got_object_id_str(&new_id_str, new_id);
7328 if (err)
7329 goto done;
7332 old_id_str[12] = '\0';
7333 if (new_id_str)
7334 new_id_str[12] = '\0';
7336 err = get_short_logmsg(&logmsg, 42, commit);
7337 if (err)
7338 goto done;
7340 printf("%s -> %s: %s\n", old_id_str,
7341 new_id_str ? new_id_str : "no-op change", logmsg);
7342 done:
7343 free(old_id_str);
7344 free(new_id_str);
7345 free(logmsg);
7346 return err;
7349 static const struct got_error *
7350 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
7351 struct got_reference *branch, struct got_reference *new_base_branch,
7352 struct got_reference *tmp_branch, struct got_repository *repo)
7354 printf("Switching work tree to %s\n", got_ref_get_name(branch));
7355 return got_worktree_rebase_complete(worktree, fileindex,
7356 new_base_branch, tmp_branch, branch, repo);
7359 static const struct got_error *
7360 rebase_commit(struct got_pathlist_head *merged_paths,
7361 struct got_worktree *worktree, struct got_fileindex *fileindex,
7362 struct got_reference *tmp_branch,
7363 struct got_object_id *commit_id, struct got_repository *repo)
7365 const struct got_error *error;
7366 struct got_commit_object *commit;
7367 struct got_object_id *new_commit_id;
7369 error = got_object_open_as_commit(&commit, repo, commit_id);
7370 if (error)
7371 return error;
7373 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
7374 worktree, fileindex, tmp_branch, commit, commit_id, repo);
7375 if (error) {
7376 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
7377 goto done;
7378 error = show_rebase_progress(commit, commit_id, NULL);
7379 } else {
7380 error = show_rebase_progress(commit, commit_id, new_commit_id);
7381 free(new_commit_id);
7383 done:
7384 got_object_commit_close(commit);
7385 return error;
7388 struct check_path_prefix_arg {
7389 const char *path_prefix;
7390 size_t len;
7391 int errcode;
7394 static const struct got_error *
7395 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
7396 struct got_blob_object *blob2, struct got_object_id *id1,
7397 struct got_object_id *id2, const char *path1, const char *path2,
7398 mode_t mode1, mode_t mode2, struct got_repository *repo)
7400 struct check_path_prefix_arg *a = arg;
7402 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
7403 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
7404 return got_error(a->errcode);
7406 return NULL;
7409 static const struct got_error *
7410 check_path_prefix(struct got_object_id *parent_id,
7411 struct got_object_id *commit_id, const char *path_prefix,
7412 int errcode, struct got_repository *repo)
7414 const struct got_error *err;
7415 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7416 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7417 struct check_path_prefix_arg cpp_arg;
7419 if (got_path_is_root_dir(path_prefix))
7420 return NULL;
7422 err = got_object_open_as_commit(&commit, repo, commit_id);
7423 if (err)
7424 goto done;
7426 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7427 if (err)
7428 goto done;
7430 err = got_object_open_as_tree(&tree1, repo,
7431 got_object_commit_get_tree_id(parent_commit));
7432 if (err)
7433 goto done;
7435 err = got_object_open_as_tree(&tree2, repo,
7436 got_object_commit_get_tree_id(commit));
7437 if (err)
7438 goto done;
7440 cpp_arg.path_prefix = path_prefix;
7441 while (cpp_arg.path_prefix[0] == '/')
7442 cpp_arg.path_prefix++;
7443 cpp_arg.len = strlen(cpp_arg.path_prefix);
7444 cpp_arg.errcode = errcode;
7445 err = got_diff_tree(tree1, tree2, "", "", repo,
7446 check_path_prefix_in_diff, &cpp_arg, 0);
7447 done:
7448 if (tree1)
7449 got_object_tree_close(tree1);
7450 if (tree2)
7451 got_object_tree_close(tree2);
7452 if (commit)
7453 got_object_commit_close(commit);
7454 if (parent_commit)
7455 got_object_commit_close(parent_commit);
7456 return err;
7459 static const struct got_error *
7460 collect_commits(struct got_object_id_queue *commits,
7461 struct got_object_id *initial_commit_id,
7462 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7463 const char *path_prefix, int path_prefix_errcode,
7464 struct got_repository *repo)
7466 const struct got_error *err = NULL;
7467 struct got_commit_graph *graph = NULL;
7468 struct got_object_id *parent_id = NULL;
7469 struct got_object_qid *qid;
7470 struct got_object_id *commit_id = initial_commit_id;
7472 err = got_commit_graph_open(&graph, "/", 1);
7473 if (err)
7474 return err;
7476 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7477 check_cancelled, NULL);
7478 if (err)
7479 goto done;
7480 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7481 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7482 check_cancelled, NULL);
7483 if (err) {
7484 if (err->code == GOT_ERR_ITER_COMPLETED) {
7485 err = got_error_msg(GOT_ERR_ANCESTRY,
7486 "ran out of commits to rebase before "
7487 "youngest common ancestor commit has "
7488 "been reached?!?");
7490 goto done;
7491 } else {
7492 err = check_path_prefix(parent_id, commit_id,
7493 path_prefix, path_prefix_errcode, repo);
7494 if (err)
7495 goto done;
7497 err = got_object_qid_alloc(&qid, commit_id);
7498 if (err)
7499 goto done;
7500 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
7501 commit_id = parent_id;
7504 done:
7505 got_commit_graph_close(graph);
7506 return err;
7509 static const struct got_error *
7510 cmd_rebase(int argc, char *argv[])
7512 const struct got_error *error = NULL;
7513 struct got_worktree *worktree = NULL;
7514 struct got_repository *repo = NULL;
7515 struct got_fileindex *fileindex = NULL;
7516 char *cwd = NULL;
7517 struct got_reference *branch = NULL;
7518 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
7519 struct got_object_id *commit_id = NULL, *parent_id = NULL;
7520 struct got_object_id *resume_commit_id = NULL;
7521 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
7522 struct got_commit_object *commit = NULL;
7523 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
7524 int histedit_in_progress = 0;
7525 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7526 struct got_object_id_queue commits;
7527 struct got_pathlist_head merged_paths;
7528 const struct got_object_id_queue *parent_ids;
7529 struct got_object_qid *qid, *pid;
7531 SIMPLEQ_INIT(&commits);
7532 TAILQ_INIT(&merged_paths);
7534 while ((ch = getopt(argc, argv, "ac")) != -1) {
7535 switch (ch) {
7536 case 'a':
7537 abort_rebase = 1;
7538 break;
7539 case 'c':
7540 continue_rebase = 1;
7541 break;
7542 default:
7543 usage_rebase();
7544 /* NOTREACHED */
7548 argc -= optind;
7549 argv += optind;
7551 #ifndef PROFILE
7552 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7553 "unveil", NULL) == -1)
7554 err(1, "pledge");
7555 #endif
7556 if (abort_rebase && continue_rebase)
7557 usage_rebase();
7558 else if (abort_rebase || continue_rebase) {
7559 if (argc != 0)
7560 usage_rebase();
7561 } else if (argc != 1)
7562 usage_rebase();
7564 cwd = getcwd(NULL, 0);
7565 if (cwd == NULL) {
7566 error = got_error_from_errno("getcwd");
7567 goto done;
7569 error = got_worktree_open(&worktree, cwd);
7570 if (error) {
7571 if (error->code == GOT_ERR_NOT_WORKTREE)
7572 error = wrap_not_worktree_error(error, "rebase", cwd);
7573 goto done;
7576 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7577 NULL);
7578 if (error != NULL)
7579 goto done;
7581 error = apply_unveil(got_repo_get_path(repo), 0,
7582 got_worktree_get_root_path(worktree));
7583 if (error)
7584 goto done;
7586 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7587 worktree);
7588 if (error)
7589 goto done;
7590 if (histedit_in_progress) {
7591 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7592 goto done;
7595 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7596 if (error)
7597 goto done;
7599 if (abort_rebase) {
7600 struct got_update_progress_arg upa;
7601 if (!rebase_in_progress) {
7602 error = got_error(GOT_ERR_NOT_REBASING);
7603 goto done;
7605 error = got_worktree_rebase_continue(&resume_commit_id,
7606 &new_base_branch, &tmp_branch, &branch, &fileindex,
7607 worktree, repo);
7608 if (error)
7609 goto done;
7610 printf("Switching work tree to %s\n",
7611 got_ref_get_symref_target(new_base_branch));
7612 memset(&upa, 0, sizeof(upa));
7613 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7614 new_base_branch, update_progress, &upa);
7615 if (error)
7616 goto done;
7617 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7618 print_update_progress_stats(&upa);
7619 goto done; /* nothing else to do */
7622 if (continue_rebase) {
7623 if (!rebase_in_progress) {
7624 error = got_error(GOT_ERR_NOT_REBASING);
7625 goto done;
7627 error = got_worktree_rebase_continue(&resume_commit_id,
7628 &new_base_branch, &tmp_branch, &branch, &fileindex,
7629 worktree, repo);
7630 if (error)
7631 goto done;
7633 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7634 resume_commit_id, repo);
7635 if (error)
7636 goto done;
7638 yca_id = got_object_id_dup(resume_commit_id);
7639 if (yca_id == NULL) {
7640 error = got_error_from_errno("got_object_id_dup");
7641 goto done;
7643 } else {
7644 error = got_ref_open(&branch, repo, argv[0], 0);
7645 if (error != NULL)
7646 goto done;
7649 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7650 if (error)
7651 goto done;
7653 if (!continue_rebase) {
7654 struct got_object_id *base_commit_id;
7656 base_commit_id = got_worktree_get_base_commit_id(worktree);
7657 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7658 base_commit_id, branch_head_commit_id, repo,
7659 check_cancelled, NULL);
7660 if (error)
7661 goto done;
7662 if (yca_id == NULL) {
7663 error = got_error_msg(GOT_ERR_ANCESTRY,
7664 "specified branch shares no common ancestry "
7665 "with work tree's branch");
7666 goto done;
7669 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7670 if (error) {
7671 if (error->code != GOT_ERR_ANCESTRY)
7672 goto done;
7673 error = NULL;
7674 } else {
7675 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7676 "specified branch resolves to a commit which "
7677 "is already contained in work tree's branch");
7678 goto done;
7680 error = got_worktree_rebase_prepare(&new_base_branch,
7681 &tmp_branch, &fileindex, worktree, branch, repo);
7682 if (error)
7683 goto done;
7686 commit_id = branch_head_commit_id;
7687 error = got_object_open_as_commit(&commit, repo, commit_id);
7688 if (error)
7689 goto done;
7691 parent_ids = got_object_commit_get_parent_ids(commit);
7692 pid = SIMPLEQ_FIRST(parent_ids);
7693 if (pid == NULL) {
7694 if (!continue_rebase) {
7695 struct got_update_progress_arg upa;
7696 memset(&upa, 0, sizeof(upa));
7697 error = got_worktree_rebase_abort(worktree, fileindex,
7698 repo, new_base_branch, update_progress, &upa);
7699 if (error)
7700 goto done;
7701 printf("Rebase of %s aborted\n",
7702 got_ref_get_name(branch));
7703 print_update_progress_stats(&upa);
7706 error = got_error(GOT_ERR_EMPTY_REBASE);
7707 goto done;
7709 error = collect_commits(&commits, commit_id, pid->id,
7710 yca_id, got_worktree_get_path_prefix(worktree),
7711 GOT_ERR_REBASE_PATH, repo);
7712 got_object_commit_close(commit);
7713 commit = NULL;
7714 if (error)
7715 goto done;
7717 if (SIMPLEQ_EMPTY(&commits)) {
7718 if (continue_rebase) {
7719 error = rebase_complete(worktree, fileindex,
7720 branch, new_base_branch, tmp_branch, repo);
7721 goto done;
7722 } else {
7723 /* Fast-forward the reference of the branch. */
7724 struct got_object_id *new_head_commit_id;
7725 char *id_str;
7726 error = got_ref_resolve(&new_head_commit_id, repo,
7727 new_base_branch);
7728 if (error)
7729 goto done;
7730 error = got_object_id_str(&id_str, new_head_commit_id);
7731 printf("Forwarding %s to commit %s\n",
7732 got_ref_get_name(branch), id_str);
7733 free(id_str);
7734 error = got_ref_change_ref(branch,
7735 new_head_commit_id);
7736 if (error)
7737 goto done;
7741 pid = NULL;
7742 SIMPLEQ_FOREACH(qid, &commits, entry) {
7743 struct got_update_progress_arg upa;
7745 commit_id = qid->id;
7746 parent_id = pid ? pid->id : yca_id;
7747 pid = qid;
7749 memset(&upa, 0, sizeof(upa));
7750 error = got_worktree_rebase_merge_files(&merged_paths,
7751 worktree, fileindex, parent_id, commit_id, repo,
7752 update_progress, &upa, check_cancelled, NULL);
7753 if (error)
7754 goto done;
7756 print_update_progress_stats(&upa);
7757 if (upa.conflicts > 0)
7758 rebase_status = GOT_STATUS_CONFLICT;
7760 if (rebase_status == GOT_STATUS_CONFLICT) {
7761 error = show_rebase_merge_conflict(qid->id, repo);
7762 if (error)
7763 goto done;
7764 got_worktree_rebase_pathlist_free(&merged_paths);
7765 break;
7768 error = rebase_commit(&merged_paths, worktree, fileindex,
7769 tmp_branch, commit_id, repo);
7770 got_worktree_rebase_pathlist_free(&merged_paths);
7771 if (error)
7772 goto done;
7775 if (rebase_status == GOT_STATUS_CONFLICT) {
7776 error = got_worktree_rebase_postpone(worktree, fileindex);
7777 if (error)
7778 goto done;
7779 error = got_error_msg(GOT_ERR_CONFLICTS,
7780 "conflicts must be resolved before rebasing can continue");
7781 } else
7782 error = rebase_complete(worktree, fileindex, branch,
7783 new_base_branch, tmp_branch, repo);
7784 done:
7785 got_object_id_queue_free(&commits);
7786 free(branch_head_commit_id);
7787 free(resume_commit_id);
7788 free(yca_id);
7789 if (commit)
7790 got_object_commit_close(commit);
7791 if (branch)
7792 got_ref_close(branch);
7793 if (new_base_branch)
7794 got_ref_close(new_base_branch);
7795 if (tmp_branch)
7796 got_ref_close(tmp_branch);
7797 if (worktree)
7798 got_worktree_close(worktree);
7799 if (repo)
7800 got_repo_close(repo);
7801 return error;
7804 __dead static void
7805 usage_histedit(void)
7807 fprintf(stderr, "usage: %s histedit [-a] [-c] [-f] [-F histedit-script] [-m]\n",
7808 getprogname());
7809 exit(1);
7812 #define GOT_HISTEDIT_PICK 'p'
7813 #define GOT_HISTEDIT_EDIT 'e'
7814 #define GOT_HISTEDIT_FOLD 'f'
7815 #define GOT_HISTEDIT_DROP 'd'
7816 #define GOT_HISTEDIT_MESG 'm'
7818 static struct got_histedit_cmd {
7819 unsigned char code;
7820 const char *name;
7821 const char *desc;
7822 } got_histedit_cmds[] = {
7823 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7824 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7825 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7826 "be used" },
7827 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7828 { GOT_HISTEDIT_MESG, "mesg",
7829 "single-line log message for commit above (open editor if empty)" },
7832 struct got_histedit_list_entry {
7833 TAILQ_ENTRY(got_histedit_list_entry) entry;
7834 struct got_object_id *commit_id;
7835 const struct got_histedit_cmd *cmd;
7836 char *logmsg;
7838 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7840 static const struct got_error *
7841 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7842 FILE *f, struct got_repository *repo)
7844 const struct got_error *err = NULL;
7845 char *logmsg = NULL, *id_str = NULL;
7846 struct got_commit_object *commit = NULL;
7847 int n;
7849 err = got_object_open_as_commit(&commit, repo, commit_id);
7850 if (err)
7851 goto done;
7853 err = get_short_logmsg(&logmsg, 34, commit);
7854 if (err)
7855 goto done;
7857 err = got_object_id_str(&id_str, commit_id);
7858 if (err)
7859 goto done;
7861 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7862 if (n < 0)
7863 err = got_ferror(f, GOT_ERR_IO);
7864 done:
7865 if (commit)
7866 got_object_commit_close(commit);
7867 free(id_str);
7868 free(logmsg);
7869 return err;
7872 static const struct got_error *
7873 histedit_write_commit_list(struct got_object_id_queue *commits,
7874 FILE *f, int edit_logmsg_only, int fold_only, struct got_repository *repo)
7876 const struct got_error *err = NULL;
7877 struct got_object_qid *qid;
7878 const char *histedit_cmd = NULL;
7880 if (SIMPLEQ_EMPTY(commits))
7881 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7883 SIMPLEQ_FOREACH(qid, commits, entry) {
7884 histedit_cmd = got_histedit_cmds[0].name;
7885 if (fold_only && SIMPLEQ_NEXT(qid, entry) != NULL)
7886 histedit_cmd = "fold";
7887 err = histedit_write_commit(qid->id, histedit_cmd, f, repo);
7888 if (err)
7889 break;
7890 if (edit_logmsg_only) {
7891 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7892 if (n < 0) {
7893 err = got_ferror(f, GOT_ERR_IO);
7894 break;
7899 return err;
7902 static const struct got_error *
7903 write_cmd_list(FILE *f, const char *branch_name,
7904 struct got_object_id_queue *commits)
7906 const struct got_error *err = NULL;
7907 size_t i;
7908 int n;
7909 char *id_str;
7910 struct got_object_qid *qid;
7912 qid = SIMPLEQ_FIRST(commits);
7913 err = got_object_id_str(&id_str, qid->id);
7914 if (err)
7915 return err;
7917 n = fprintf(f,
7918 "# Editing the history of branch '%s' starting at\n"
7919 "# commit %s\n"
7920 "# Commits will be processed in order from top to "
7921 "bottom of this file.\n", branch_name, id_str);
7922 if (n < 0) {
7923 err = got_ferror(f, GOT_ERR_IO);
7924 goto done;
7927 n = fprintf(f, "# Available histedit commands:\n");
7928 if (n < 0) {
7929 err = got_ferror(f, GOT_ERR_IO);
7930 goto done;
7933 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7934 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7935 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7936 cmd->desc);
7937 if (n < 0) {
7938 err = got_ferror(f, GOT_ERR_IO);
7939 break;
7942 done:
7943 free(id_str);
7944 return err;
7947 static const struct got_error *
7948 histedit_syntax_error(int lineno)
7950 static char msg[42];
7951 int ret;
7953 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7954 lineno);
7955 if (ret == -1 || ret >= sizeof(msg))
7956 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7958 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7961 static const struct got_error *
7962 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7963 char *logmsg, struct got_repository *repo)
7965 const struct got_error *err;
7966 struct got_commit_object *folded_commit = NULL;
7967 char *id_str, *folded_logmsg = NULL;
7969 err = got_object_id_str(&id_str, hle->commit_id);
7970 if (err)
7971 return err;
7973 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7974 if (err)
7975 goto done;
7977 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7978 if (err)
7979 goto done;
7980 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7981 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7982 folded_logmsg) == -1) {
7983 err = got_error_from_errno("asprintf");
7985 done:
7986 if (folded_commit)
7987 got_object_commit_close(folded_commit);
7988 free(id_str);
7989 free(folded_logmsg);
7990 return err;
7993 static struct got_histedit_list_entry *
7994 get_folded_commits(struct got_histedit_list_entry *hle)
7996 struct got_histedit_list_entry *prev, *folded = NULL;
7998 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7999 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
8000 prev->cmd->code == GOT_HISTEDIT_DROP)) {
8001 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
8002 folded = prev;
8003 prev = TAILQ_PREV(prev, got_histedit_list, entry);
8006 return folded;
8009 static const struct got_error *
8010 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
8011 struct got_repository *repo)
8013 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
8014 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
8015 const struct got_error *err = NULL;
8016 struct got_commit_object *commit = NULL;
8017 int logmsg_len;
8018 int fd;
8019 struct got_histedit_list_entry *folded = NULL;
8021 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8022 if (err)
8023 return err;
8025 folded = get_folded_commits(hle);
8026 if (folded) {
8027 while (folded != hle) {
8028 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
8029 folded = TAILQ_NEXT(folded, entry);
8030 continue;
8032 err = append_folded_commit_msg(&new_msg, folded,
8033 logmsg, repo);
8034 if (err)
8035 goto done;
8036 free(logmsg);
8037 logmsg = new_msg;
8038 folded = TAILQ_NEXT(folded, entry);
8042 err = got_object_id_str(&id_str, hle->commit_id);
8043 if (err)
8044 goto done;
8045 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
8046 if (err)
8047 goto done;
8048 logmsg_len = asprintf(&new_msg,
8049 "%s\n# original log message of commit %s: %s",
8050 logmsg ? logmsg : "", id_str, orig_logmsg);
8051 if (logmsg_len == -1) {
8052 err = got_error_from_errno("asprintf");
8053 goto done;
8055 free(logmsg);
8056 logmsg = new_msg;
8058 err = got_object_id_str(&id_str, hle->commit_id);
8059 if (err)
8060 goto done;
8062 err = got_opentemp_named_fd(&logmsg_path, &fd,
8063 GOT_TMPDIR_STR "/got-logmsg");
8064 if (err)
8065 goto done;
8067 write(fd, logmsg, logmsg_len);
8068 close(fd);
8070 err = get_editor(&editor);
8071 if (err)
8072 goto done;
8074 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
8075 logmsg_len, 0);
8076 if (err) {
8077 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
8078 goto done;
8079 err = NULL;
8080 hle->logmsg = strdup(new_msg);
8081 if (hle->logmsg == NULL)
8082 err = got_error_from_errno("strdup");
8084 done:
8085 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
8086 err = got_error_from_errno2("unlink", logmsg_path);
8087 free(logmsg_path);
8088 free(logmsg);
8089 free(orig_logmsg);
8090 free(editor);
8091 if (commit)
8092 got_object_commit_close(commit);
8093 return err;
8096 static const struct got_error *
8097 histedit_parse_list(struct got_histedit_list *histedit_cmds,
8098 FILE *f, struct got_repository *repo)
8100 const struct got_error *err = NULL;
8101 char *line = NULL, *p, *end;
8102 size_t i, size;
8103 ssize_t len;
8104 int lineno = 0;
8105 const struct got_histedit_cmd *cmd;
8106 struct got_object_id *commit_id = NULL;
8107 struct got_histedit_list_entry *hle = NULL;
8109 for (;;) {
8110 len = getline(&line, &size, f);
8111 if (len == -1) {
8112 const struct got_error *getline_err;
8113 if (feof(f))
8114 break;
8115 getline_err = got_error_from_errno("getline");
8116 err = got_ferror(f, getline_err->code);
8117 break;
8119 lineno++;
8120 p = line;
8121 while (isspace((unsigned char)p[0]))
8122 p++;
8123 if (p[0] == '#' || p[0] == '\0') {
8124 free(line);
8125 line = NULL;
8126 continue;
8128 cmd = NULL;
8129 for (i = 0; i < nitems(got_histedit_cmds); i++) {
8130 cmd = &got_histedit_cmds[i];
8131 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
8132 isspace((unsigned char)p[strlen(cmd->name)])) {
8133 p += strlen(cmd->name);
8134 break;
8136 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
8137 p++;
8138 break;
8141 if (i == nitems(got_histedit_cmds)) {
8142 err = histedit_syntax_error(lineno);
8143 break;
8145 while (isspace((unsigned char)p[0]))
8146 p++;
8147 if (cmd->code == GOT_HISTEDIT_MESG) {
8148 if (hle == NULL || hle->logmsg != NULL) {
8149 err = got_error(GOT_ERR_HISTEDIT_CMD);
8150 break;
8152 if (p[0] == '\0') {
8153 err = histedit_edit_logmsg(hle, repo);
8154 if (err)
8155 break;
8156 } else {
8157 hle->logmsg = strdup(p);
8158 if (hle->logmsg == NULL) {
8159 err = got_error_from_errno("strdup");
8160 break;
8163 free(line);
8164 line = NULL;
8165 continue;
8166 } else {
8167 end = p;
8168 while (end[0] && !isspace((unsigned char)end[0]))
8169 end++;
8170 *end = '\0';
8172 err = got_object_resolve_id_str(&commit_id, repo, p);
8173 if (err) {
8174 /* override error code */
8175 err = histedit_syntax_error(lineno);
8176 break;
8179 hle = malloc(sizeof(*hle));
8180 if (hle == NULL) {
8181 err = got_error_from_errno("malloc");
8182 break;
8184 hle->cmd = cmd;
8185 hle->commit_id = commit_id;
8186 hle->logmsg = NULL;
8187 commit_id = NULL;
8188 free(line);
8189 line = NULL;
8190 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
8193 free(line);
8194 free(commit_id);
8195 return err;
8198 static const struct got_error *
8199 histedit_check_script(struct got_histedit_list *histedit_cmds,
8200 struct got_object_id_queue *commits, struct got_repository *repo)
8202 const struct got_error *err = NULL;
8203 struct got_object_qid *qid;
8204 struct got_histedit_list_entry *hle;
8205 static char msg[92];
8206 char *id_str;
8208 if (TAILQ_EMPTY(histedit_cmds))
8209 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
8210 "histedit script contains no commands");
8211 if (SIMPLEQ_EMPTY(commits))
8212 return got_error(GOT_ERR_EMPTY_HISTEDIT);
8214 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8215 struct got_histedit_list_entry *hle2;
8216 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
8217 if (hle == hle2)
8218 continue;
8219 if (got_object_id_cmp(hle->commit_id,
8220 hle2->commit_id) != 0)
8221 continue;
8222 err = got_object_id_str(&id_str, hle->commit_id);
8223 if (err)
8224 return err;
8225 snprintf(msg, sizeof(msg), "commit %s is listed "
8226 "more than once in histedit script", id_str);
8227 free(id_str);
8228 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8232 SIMPLEQ_FOREACH(qid, commits, entry) {
8233 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8234 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
8235 break;
8237 if (hle == NULL) {
8238 err = got_object_id_str(&id_str, qid->id);
8239 if (err)
8240 return err;
8241 snprintf(msg, sizeof(msg),
8242 "commit %s missing from histedit script", id_str);
8243 free(id_str);
8244 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8248 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
8249 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
8250 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
8251 "last commit in histedit script cannot be folded");
8253 return NULL;
8256 static const struct got_error *
8257 histedit_run_editor(struct got_histedit_list *histedit_cmds,
8258 const char *path, struct got_object_id_queue *commits,
8259 struct got_repository *repo)
8261 const struct got_error *err = NULL;
8262 char *editor;
8263 FILE *f = NULL;
8265 err = get_editor(&editor);
8266 if (err)
8267 return err;
8269 if (spawn_editor(editor, path) == -1) {
8270 err = got_error_from_errno("failed spawning editor");
8271 goto done;
8274 f = fopen(path, "r");
8275 if (f == NULL) {
8276 err = got_error_from_errno("fopen");
8277 goto done;
8279 err = histedit_parse_list(histedit_cmds, f, repo);
8280 if (err)
8281 goto done;
8283 err = histedit_check_script(histedit_cmds, commits, repo);
8284 done:
8285 if (f && fclose(f) != 0 && err == NULL)
8286 err = got_error_from_errno("fclose");
8287 free(editor);
8288 return err;
8291 static const struct got_error *
8292 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
8293 struct got_object_id_queue *, const char *, const char *,
8294 struct got_repository *);
8296 static const struct got_error *
8297 histedit_edit_script(struct got_histedit_list *histedit_cmds,
8298 struct got_object_id_queue *commits, const char *branch_name,
8299 int edit_logmsg_only, int fold_only, struct got_repository *repo)
8301 const struct got_error *err;
8302 FILE *f = NULL;
8303 char *path = NULL;
8305 err = got_opentemp_named(&path, &f, "got-histedit");
8306 if (err)
8307 return err;
8309 err = write_cmd_list(f, branch_name, commits);
8310 if (err)
8311 goto done;
8313 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
8314 fold_only, repo);
8315 if (err)
8316 goto done;
8318 if (edit_logmsg_only || fold_only) {
8319 rewind(f);
8320 err = histedit_parse_list(histedit_cmds, f, repo);
8321 } else {
8322 if (fclose(f) != 0) {
8323 err = got_error_from_errno("fclose");
8324 goto done;
8326 f = NULL;
8327 err = histedit_run_editor(histedit_cmds, path, commits, repo);
8328 if (err) {
8329 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8330 err->code != GOT_ERR_HISTEDIT_CMD)
8331 goto done;
8332 err = histedit_edit_list_retry(histedit_cmds, err,
8333 commits, path, branch_name, repo);
8336 done:
8337 if (f && fclose(f) != 0 && err == NULL)
8338 err = got_error_from_errno("fclose");
8339 if (path && unlink(path) != 0 && err == NULL)
8340 err = got_error_from_errno2("unlink", path);
8341 free(path);
8342 return err;
8345 static const struct got_error *
8346 histedit_save_list(struct got_histedit_list *histedit_cmds,
8347 struct got_worktree *worktree, struct got_repository *repo)
8349 const struct got_error *err = NULL;
8350 char *path = NULL;
8351 FILE *f = NULL;
8352 struct got_histedit_list_entry *hle;
8353 struct got_commit_object *commit = NULL;
8355 err = got_worktree_get_histedit_script_path(&path, worktree);
8356 if (err)
8357 return err;
8359 f = fopen(path, "w");
8360 if (f == NULL) {
8361 err = got_error_from_errno2("fopen", path);
8362 goto done;
8364 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8365 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
8366 repo);
8367 if (err)
8368 break;
8370 if (hle->logmsg) {
8371 int n = fprintf(f, "%c %s\n",
8372 GOT_HISTEDIT_MESG, hle->logmsg);
8373 if (n < 0) {
8374 err = got_ferror(f, GOT_ERR_IO);
8375 break;
8379 done:
8380 if (f && fclose(f) != 0 && err == NULL)
8381 err = got_error_from_errno("fclose");
8382 free(path);
8383 if (commit)
8384 got_object_commit_close(commit);
8385 return err;
8388 void
8389 histedit_free_list(struct got_histedit_list *histedit_cmds)
8391 struct got_histedit_list_entry *hle;
8393 while ((hle = TAILQ_FIRST(histedit_cmds))) {
8394 TAILQ_REMOVE(histedit_cmds, hle, entry);
8395 free(hle);
8399 static const struct got_error *
8400 histedit_load_list(struct got_histedit_list *histedit_cmds,
8401 const char *path, struct got_repository *repo)
8403 const struct got_error *err = NULL;
8404 FILE *f = NULL;
8406 f = fopen(path, "r");
8407 if (f == NULL) {
8408 err = got_error_from_errno2("fopen", path);
8409 goto done;
8412 err = histedit_parse_list(histedit_cmds, f, repo);
8413 done:
8414 if (f && fclose(f) != 0 && err == NULL)
8415 err = got_error_from_errno("fclose");
8416 return err;
8419 static const struct got_error *
8420 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
8421 const struct got_error *edit_err, struct got_object_id_queue *commits,
8422 const char *path, const char *branch_name, struct got_repository *repo)
8424 const struct got_error *err = NULL, *prev_err = edit_err;
8425 int resp = ' ';
8427 while (resp != 'c' && resp != 'r' && resp != 'a') {
8428 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
8429 "or (a)bort: ", getprogname(), prev_err->msg);
8430 resp = getchar();
8431 if (resp == '\n')
8432 resp = getchar();
8433 if (resp == 'c') {
8434 histedit_free_list(histedit_cmds);
8435 err = histedit_run_editor(histedit_cmds, path, commits,
8436 repo);
8437 if (err) {
8438 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8439 err->code != GOT_ERR_HISTEDIT_CMD)
8440 break;
8441 prev_err = err;
8442 resp = ' ';
8443 continue;
8445 break;
8446 } else if (resp == 'r') {
8447 histedit_free_list(histedit_cmds);
8448 err = histedit_edit_script(histedit_cmds,
8449 commits, branch_name, 0, 0, repo);
8450 if (err) {
8451 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8452 err->code != GOT_ERR_HISTEDIT_CMD)
8453 break;
8454 prev_err = err;
8455 resp = ' ';
8456 continue;
8458 break;
8459 } else if (resp == 'a') {
8460 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
8461 break;
8462 } else
8463 printf("invalid response '%c'\n", resp);
8466 return err;
8469 static const struct got_error *
8470 histedit_complete(struct got_worktree *worktree,
8471 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
8472 struct got_reference *branch, struct got_repository *repo)
8474 printf("Switching work tree to %s\n",
8475 got_ref_get_symref_target(branch));
8476 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
8477 branch, repo);
8480 static const struct got_error *
8481 show_histedit_progress(struct got_commit_object *commit,
8482 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
8484 const struct got_error *err;
8485 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8487 err = got_object_id_str(&old_id_str, hle->commit_id);
8488 if (err)
8489 goto done;
8491 if (new_id) {
8492 err = got_object_id_str(&new_id_str, new_id);
8493 if (err)
8494 goto done;
8497 old_id_str[12] = '\0';
8498 if (new_id_str)
8499 new_id_str[12] = '\0';
8501 if (hle->logmsg) {
8502 logmsg = strdup(hle->logmsg);
8503 if (logmsg == NULL) {
8504 err = got_error_from_errno("strdup");
8505 goto done;
8507 trim_logmsg(logmsg, 42);
8508 } else {
8509 err = get_short_logmsg(&logmsg, 42, commit);
8510 if (err)
8511 goto done;
8514 switch (hle->cmd->code) {
8515 case GOT_HISTEDIT_PICK:
8516 case GOT_HISTEDIT_EDIT:
8517 printf("%s -> %s: %s\n", old_id_str,
8518 new_id_str ? new_id_str : "no-op change", logmsg);
8519 break;
8520 case GOT_HISTEDIT_DROP:
8521 case GOT_HISTEDIT_FOLD:
8522 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
8523 logmsg);
8524 break;
8525 default:
8526 break;
8528 done:
8529 free(old_id_str);
8530 free(new_id_str);
8531 return err;
8534 static const struct got_error *
8535 histedit_commit(struct got_pathlist_head *merged_paths,
8536 struct got_worktree *worktree, struct got_fileindex *fileindex,
8537 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
8538 struct got_repository *repo)
8540 const struct got_error *err;
8541 struct got_commit_object *commit;
8542 struct got_object_id *new_commit_id;
8544 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
8545 && hle->logmsg == NULL) {
8546 err = histedit_edit_logmsg(hle, repo);
8547 if (err)
8548 return err;
8551 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8552 if (err)
8553 return err;
8555 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
8556 worktree, fileindex, tmp_branch, commit, hle->commit_id,
8557 hle->logmsg, repo);
8558 if (err) {
8559 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
8560 goto done;
8561 err = show_histedit_progress(commit, hle, NULL);
8562 } else {
8563 err = show_histedit_progress(commit, hle, new_commit_id);
8564 free(new_commit_id);
8566 done:
8567 got_object_commit_close(commit);
8568 return err;
8571 static const struct got_error *
8572 histedit_skip_commit(struct got_histedit_list_entry *hle,
8573 struct got_worktree *worktree, struct got_repository *repo)
8575 const struct got_error *error;
8576 struct got_commit_object *commit;
8578 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
8579 repo);
8580 if (error)
8581 return error;
8583 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
8584 if (error)
8585 return error;
8587 error = show_histedit_progress(commit, hle, NULL);
8588 got_object_commit_close(commit);
8589 return error;
8592 static const struct got_error *
8593 check_local_changes(void *arg, unsigned char status,
8594 unsigned char staged_status, const char *path,
8595 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8596 struct got_object_id *commit_id, int dirfd, const char *de_name)
8598 int *have_local_changes = arg;
8600 switch (status) {
8601 case GOT_STATUS_ADD:
8602 case GOT_STATUS_DELETE:
8603 case GOT_STATUS_MODIFY:
8604 case GOT_STATUS_CONFLICT:
8605 *have_local_changes = 1;
8606 return got_error(GOT_ERR_CANCELLED);
8607 default:
8608 break;
8611 switch (staged_status) {
8612 case GOT_STATUS_ADD:
8613 case GOT_STATUS_DELETE:
8614 case GOT_STATUS_MODIFY:
8615 *have_local_changes = 1;
8616 return got_error(GOT_ERR_CANCELLED);
8617 default:
8618 break;
8621 return NULL;
8624 static const struct got_error *
8625 cmd_histedit(int argc, char *argv[])
8627 const struct got_error *error = NULL;
8628 struct got_worktree *worktree = NULL;
8629 struct got_fileindex *fileindex = NULL;
8630 struct got_repository *repo = NULL;
8631 char *cwd = NULL;
8632 struct got_reference *branch = NULL;
8633 struct got_reference *tmp_branch = NULL;
8634 struct got_object_id *resume_commit_id = NULL;
8635 struct got_object_id *base_commit_id = NULL;
8636 struct got_object_id *head_commit_id = NULL;
8637 struct got_commit_object *commit = NULL;
8638 int ch, rebase_in_progress = 0;
8639 struct got_update_progress_arg upa;
8640 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8641 int edit_logmsg_only = 0, fold_only = 0;
8642 const char *edit_script_path = NULL;
8643 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8644 struct got_object_id_queue commits;
8645 struct got_pathlist_head merged_paths;
8646 const struct got_object_id_queue *parent_ids;
8647 struct got_object_qid *pid;
8648 struct got_histedit_list histedit_cmds;
8649 struct got_histedit_list_entry *hle;
8651 SIMPLEQ_INIT(&commits);
8652 TAILQ_INIT(&histedit_cmds);
8653 TAILQ_INIT(&merged_paths);
8654 memset(&upa, 0, sizeof(upa));
8656 while ((ch = getopt(argc, argv, "acfF:m")) != -1) {
8657 switch (ch) {
8658 case 'a':
8659 abort_edit = 1;
8660 break;
8661 case 'c':
8662 continue_edit = 1;
8663 break;
8664 case 'f':
8665 fold_only = 1;
8666 break;
8667 case 'F':
8668 edit_script_path = optarg;
8669 break;
8670 case 'm':
8671 edit_logmsg_only = 1;
8672 break;
8673 default:
8674 usage_histedit();
8675 /* NOTREACHED */
8679 argc -= optind;
8680 argv += optind;
8682 #ifndef PROFILE
8683 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8684 "unveil", NULL) == -1)
8685 err(1, "pledge");
8686 #endif
8687 if (abort_edit && continue_edit)
8688 option_conflict('a', 'c');
8689 if (edit_script_path && edit_logmsg_only)
8690 option_conflict('F', 'm');
8691 if (abort_edit && edit_logmsg_only)
8692 option_conflict('a', 'm');
8693 if (continue_edit && edit_logmsg_only)
8694 option_conflict('c', 'm');
8695 if (abort_edit && fold_only)
8696 option_conflict('a', 'f');
8697 if (continue_edit && fold_only)
8698 option_conflict('c', 'f');
8699 if (fold_only && edit_logmsg_only)
8700 option_conflict('f', 'm');
8701 if (edit_script_path && fold_only)
8702 option_conflict('F', 'f');
8703 if (argc != 0)
8704 usage_histedit();
8707 * This command cannot apply unveil(2) in all cases because the
8708 * user may choose to run an editor to edit the histedit script
8709 * and to edit individual commit log messages.
8710 * unveil(2) traverses exec(2); if an editor is used we have to
8711 * apply unveil after edit script and log messages have been written.
8712 * XXX TODO: Make use of unveil(2) where possible.
8715 cwd = getcwd(NULL, 0);
8716 if (cwd == NULL) {
8717 error = got_error_from_errno("getcwd");
8718 goto done;
8720 error = got_worktree_open(&worktree, cwd);
8721 if (error) {
8722 if (error->code == GOT_ERR_NOT_WORKTREE)
8723 error = wrap_not_worktree_error(error, "histedit", cwd);
8724 goto done;
8727 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8728 NULL);
8729 if (error != NULL)
8730 goto done;
8732 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8733 if (error)
8734 goto done;
8735 if (rebase_in_progress) {
8736 error = got_error(GOT_ERR_REBASING);
8737 goto done;
8740 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8741 if (error)
8742 goto done;
8744 if (edit_in_progress && edit_logmsg_only) {
8745 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8746 "histedit operation is in progress in this "
8747 "work tree and must be continued or aborted "
8748 "before the -m option can be used");
8749 goto done;
8751 if (edit_in_progress && fold_only) {
8752 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8753 "histedit operation is in progress in this "
8754 "work tree and must be continued or aborted "
8755 "before the -f option can be used");
8756 goto done;
8759 if (edit_in_progress && abort_edit) {
8760 error = got_worktree_histedit_continue(&resume_commit_id,
8761 &tmp_branch, &branch, &base_commit_id, &fileindex,
8762 worktree, repo);
8763 if (error)
8764 goto done;
8765 printf("Switching work tree to %s\n",
8766 got_ref_get_symref_target(branch));
8767 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8768 branch, base_commit_id, update_progress, &upa);
8769 if (error)
8770 goto done;
8771 printf("Histedit of %s aborted\n",
8772 got_ref_get_symref_target(branch));
8773 print_update_progress_stats(&upa);
8774 goto done; /* nothing else to do */
8775 } else if (abort_edit) {
8776 error = got_error(GOT_ERR_NOT_HISTEDIT);
8777 goto done;
8780 if (continue_edit) {
8781 char *path;
8783 if (!edit_in_progress) {
8784 error = got_error(GOT_ERR_NOT_HISTEDIT);
8785 goto done;
8788 error = got_worktree_get_histedit_script_path(&path, worktree);
8789 if (error)
8790 goto done;
8792 error = histedit_load_list(&histedit_cmds, path, repo);
8793 free(path);
8794 if (error)
8795 goto done;
8797 error = got_worktree_histedit_continue(&resume_commit_id,
8798 &tmp_branch, &branch, &base_commit_id, &fileindex,
8799 worktree, repo);
8800 if (error)
8801 goto done;
8803 error = got_ref_resolve(&head_commit_id, repo, branch);
8804 if (error)
8805 goto done;
8807 error = got_object_open_as_commit(&commit, repo,
8808 head_commit_id);
8809 if (error)
8810 goto done;
8811 parent_ids = got_object_commit_get_parent_ids(commit);
8812 pid = SIMPLEQ_FIRST(parent_ids);
8813 if (pid == NULL) {
8814 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8815 goto done;
8817 error = collect_commits(&commits, head_commit_id, pid->id,
8818 base_commit_id, got_worktree_get_path_prefix(worktree),
8819 GOT_ERR_HISTEDIT_PATH, repo);
8820 got_object_commit_close(commit);
8821 commit = NULL;
8822 if (error)
8823 goto done;
8824 } else {
8825 if (edit_in_progress) {
8826 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8827 goto done;
8830 error = got_ref_open(&branch, repo,
8831 got_worktree_get_head_ref_name(worktree), 0);
8832 if (error != NULL)
8833 goto done;
8835 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8836 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8837 "will not edit commit history of a branch outside "
8838 "the \"refs/heads/\" reference namespace");
8839 goto done;
8842 error = got_ref_resolve(&head_commit_id, repo, branch);
8843 got_ref_close(branch);
8844 branch = NULL;
8845 if (error)
8846 goto done;
8848 error = got_object_open_as_commit(&commit, repo,
8849 head_commit_id);
8850 if (error)
8851 goto done;
8852 parent_ids = got_object_commit_get_parent_ids(commit);
8853 pid = SIMPLEQ_FIRST(parent_ids);
8854 if (pid == NULL) {
8855 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8856 goto done;
8858 error = collect_commits(&commits, head_commit_id, pid->id,
8859 got_worktree_get_base_commit_id(worktree),
8860 got_worktree_get_path_prefix(worktree),
8861 GOT_ERR_HISTEDIT_PATH, repo);
8862 got_object_commit_close(commit);
8863 commit = NULL;
8864 if (error)
8865 goto done;
8867 if (SIMPLEQ_EMPTY(&commits)) {
8868 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8869 goto done;
8872 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8873 &base_commit_id, &fileindex, worktree, repo);
8874 if (error)
8875 goto done;
8877 if (edit_script_path) {
8878 error = histedit_load_list(&histedit_cmds,
8879 edit_script_path, repo);
8880 if (error) {
8881 got_worktree_histedit_abort(worktree, fileindex,
8882 repo, branch, base_commit_id,
8883 update_progress, &upa);
8884 print_update_progress_stats(&upa);
8885 goto done;
8887 } else {
8888 const char *branch_name;
8889 branch_name = got_ref_get_symref_target(branch);
8890 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8891 branch_name += 11;
8892 error = histedit_edit_script(&histedit_cmds, &commits,
8893 branch_name, edit_logmsg_only, fold_only, repo);
8894 if (error) {
8895 got_worktree_histedit_abort(worktree, fileindex,
8896 repo, branch, base_commit_id,
8897 update_progress, &upa);
8898 print_update_progress_stats(&upa);
8899 goto done;
8904 error = histedit_save_list(&histedit_cmds, worktree,
8905 repo);
8906 if (error) {
8907 got_worktree_histedit_abort(worktree, fileindex,
8908 repo, branch, base_commit_id,
8909 update_progress, &upa);
8910 print_update_progress_stats(&upa);
8911 goto done;
8916 error = histedit_check_script(&histedit_cmds, &commits, repo);
8917 if (error)
8918 goto done;
8920 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8921 if (resume_commit_id) {
8922 if (got_object_id_cmp(hle->commit_id,
8923 resume_commit_id) != 0)
8924 continue;
8926 resume_commit_id = NULL;
8927 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8928 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8929 error = histedit_skip_commit(hle, worktree,
8930 repo);
8931 if (error)
8932 goto done;
8933 } else {
8934 struct got_pathlist_head paths;
8935 int have_changes = 0;
8937 TAILQ_INIT(&paths);
8938 error = got_pathlist_append(&paths, "", NULL);
8939 if (error)
8940 goto done;
8941 error = got_worktree_status(worktree, &paths,
8942 repo, check_local_changes, &have_changes,
8943 check_cancelled, NULL);
8944 got_pathlist_free(&paths);
8945 if (error) {
8946 if (error->code != GOT_ERR_CANCELLED)
8947 goto done;
8948 if (sigint_received || sigpipe_received)
8949 goto done;
8951 if (have_changes) {
8952 error = histedit_commit(NULL, worktree,
8953 fileindex, tmp_branch, hle, repo);
8954 if (error)
8955 goto done;
8956 } else {
8957 error = got_object_open_as_commit(
8958 &commit, repo, hle->commit_id);
8959 if (error)
8960 goto done;
8961 error = show_histedit_progress(commit,
8962 hle, NULL);
8963 got_object_commit_close(commit);
8964 commit = NULL;
8965 if (error)
8966 goto done;
8969 continue;
8972 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8973 error = histedit_skip_commit(hle, worktree, repo);
8974 if (error)
8975 goto done;
8976 continue;
8979 error = got_object_open_as_commit(&commit, repo,
8980 hle->commit_id);
8981 if (error)
8982 goto done;
8983 parent_ids = got_object_commit_get_parent_ids(commit);
8984 pid = SIMPLEQ_FIRST(parent_ids);
8986 error = got_worktree_histedit_merge_files(&merged_paths,
8987 worktree, fileindex, pid->id, hle->commit_id, repo,
8988 update_progress, &upa, check_cancelled, NULL);
8989 if (error)
8990 goto done;
8991 got_object_commit_close(commit);
8992 commit = NULL;
8994 print_update_progress_stats(&upa);
8995 if (upa.conflicts > 0)
8996 rebase_status = GOT_STATUS_CONFLICT;
8998 if (rebase_status == GOT_STATUS_CONFLICT) {
8999 error = show_rebase_merge_conflict(hle->commit_id,
9000 repo);
9001 if (error)
9002 goto done;
9003 got_worktree_rebase_pathlist_free(&merged_paths);
9004 break;
9007 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
9008 char *id_str;
9009 error = got_object_id_str(&id_str, hle->commit_id);
9010 if (error)
9011 goto done;
9012 printf("Stopping histedit for amending commit %s\n",
9013 id_str);
9014 free(id_str);
9015 got_worktree_rebase_pathlist_free(&merged_paths);
9016 error = got_worktree_histedit_postpone(worktree,
9017 fileindex);
9018 goto done;
9021 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
9022 error = histedit_skip_commit(hle, worktree, repo);
9023 if (error)
9024 goto done;
9025 continue;
9028 error = histedit_commit(&merged_paths, worktree, fileindex,
9029 tmp_branch, hle, repo);
9030 got_worktree_rebase_pathlist_free(&merged_paths);
9031 if (error)
9032 goto done;
9035 if (rebase_status == GOT_STATUS_CONFLICT) {
9036 error = got_worktree_histedit_postpone(worktree, fileindex);
9037 if (error)
9038 goto done;
9039 error = got_error_msg(GOT_ERR_CONFLICTS,
9040 "conflicts must be resolved before histedit can continue");
9041 } else
9042 error = histedit_complete(worktree, fileindex, tmp_branch,
9043 branch, repo);
9044 done:
9045 got_object_id_queue_free(&commits);
9046 histedit_free_list(&histedit_cmds);
9047 free(head_commit_id);
9048 free(base_commit_id);
9049 free(resume_commit_id);
9050 if (commit)
9051 got_object_commit_close(commit);
9052 if (branch)
9053 got_ref_close(branch);
9054 if (tmp_branch)
9055 got_ref_close(tmp_branch);
9056 if (worktree)
9057 got_worktree_close(worktree);
9058 if (repo)
9059 got_repo_close(repo);
9060 return error;
9063 __dead static void
9064 usage_integrate(void)
9066 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
9067 exit(1);
9070 static const struct got_error *
9071 cmd_integrate(int argc, char *argv[])
9073 const struct got_error *error = NULL;
9074 struct got_repository *repo = NULL;
9075 struct got_worktree *worktree = NULL;
9076 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
9077 const char *branch_arg = NULL;
9078 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
9079 struct got_fileindex *fileindex = NULL;
9080 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
9081 int ch;
9082 struct got_update_progress_arg upa;
9084 while ((ch = getopt(argc, argv, "")) != -1) {
9085 switch (ch) {
9086 default:
9087 usage_integrate();
9088 /* NOTREACHED */
9092 argc -= optind;
9093 argv += optind;
9095 if (argc != 1)
9096 usage_integrate();
9097 branch_arg = argv[0];
9098 #ifndef PROFILE
9099 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9100 "unveil", NULL) == -1)
9101 err(1, "pledge");
9102 #endif
9103 cwd = getcwd(NULL, 0);
9104 if (cwd == NULL) {
9105 error = got_error_from_errno("getcwd");
9106 goto done;
9109 error = got_worktree_open(&worktree, cwd);
9110 if (error) {
9111 if (error->code == GOT_ERR_NOT_WORKTREE)
9112 error = wrap_not_worktree_error(error, "integrate",
9113 cwd);
9114 goto done;
9117 error = check_rebase_or_histedit_in_progress(worktree);
9118 if (error)
9119 goto done;
9121 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9122 NULL);
9123 if (error != NULL)
9124 goto done;
9126 error = apply_unveil(got_repo_get_path(repo), 0,
9127 got_worktree_get_root_path(worktree));
9128 if (error)
9129 goto done;
9131 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
9132 error = got_error_from_errno("asprintf");
9133 goto done;
9136 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
9137 &base_branch_ref, worktree, refname, repo);
9138 if (error)
9139 goto done;
9141 refname = strdup(got_ref_get_name(branch_ref));
9142 if (refname == NULL) {
9143 error = got_error_from_errno("strdup");
9144 got_worktree_integrate_abort(worktree, fileindex, repo,
9145 branch_ref, base_branch_ref);
9146 goto done;
9148 base_refname = strdup(got_ref_get_name(base_branch_ref));
9149 if (base_refname == NULL) {
9150 error = got_error_from_errno("strdup");
9151 got_worktree_integrate_abort(worktree, fileindex, repo,
9152 branch_ref, base_branch_ref);
9153 goto done;
9156 error = got_ref_resolve(&commit_id, repo, branch_ref);
9157 if (error)
9158 goto done;
9160 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
9161 if (error)
9162 goto done;
9164 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
9165 error = got_error_msg(GOT_ERR_SAME_BRANCH,
9166 "specified branch has already been integrated");
9167 got_worktree_integrate_abort(worktree, fileindex, repo,
9168 branch_ref, base_branch_ref);
9169 goto done;
9172 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
9173 if (error) {
9174 if (error->code == GOT_ERR_ANCESTRY)
9175 error = got_error(GOT_ERR_REBASE_REQUIRED);
9176 got_worktree_integrate_abort(worktree, fileindex, repo,
9177 branch_ref, base_branch_ref);
9178 goto done;
9181 memset(&upa, 0, sizeof(upa));
9182 error = got_worktree_integrate_continue(worktree, fileindex, repo,
9183 branch_ref, base_branch_ref, update_progress, &upa,
9184 check_cancelled, NULL);
9185 if (error)
9186 goto done;
9188 printf("Integrated %s into %s\n", refname, base_refname);
9189 print_update_progress_stats(&upa);
9190 done:
9191 if (repo)
9192 got_repo_close(repo);
9193 if (worktree)
9194 got_worktree_close(worktree);
9195 free(cwd);
9196 free(base_commit_id);
9197 free(commit_id);
9198 free(refname);
9199 free(base_refname);
9200 return error;
9203 __dead static void
9204 usage_stage(void)
9206 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
9207 "[-S] [file-path ...]\n",
9208 getprogname());
9209 exit(1);
9212 static const struct got_error *
9213 print_stage(void *arg, unsigned char status, unsigned char staged_status,
9214 const char *path, struct got_object_id *blob_id,
9215 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
9216 int dirfd, const char *de_name)
9218 const struct got_error *err = NULL;
9219 char *id_str = NULL;
9221 if (staged_status != GOT_STATUS_ADD &&
9222 staged_status != GOT_STATUS_MODIFY &&
9223 staged_status != GOT_STATUS_DELETE)
9224 return NULL;
9226 if (staged_status == GOT_STATUS_ADD ||
9227 staged_status == GOT_STATUS_MODIFY)
9228 err = got_object_id_str(&id_str, staged_blob_id);
9229 else
9230 err = got_object_id_str(&id_str, blob_id);
9231 if (err)
9232 return err;
9234 printf("%s %c %s\n", id_str, staged_status, path);
9235 free(id_str);
9236 return NULL;
9239 static const struct got_error *
9240 cmd_stage(int argc, char *argv[])
9242 const struct got_error *error = NULL;
9243 struct got_repository *repo = NULL;
9244 struct got_worktree *worktree = NULL;
9245 char *cwd = NULL;
9246 struct got_pathlist_head paths;
9247 struct got_pathlist_entry *pe;
9248 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
9249 FILE *patch_script_file = NULL;
9250 const char *patch_script_path = NULL;
9251 struct choose_patch_arg cpa;
9253 TAILQ_INIT(&paths);
9255 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
9256 switch (ch) {
9257 case 'l':
9258 list_stage = 1;
9259 break;
9260 case 'p':
9261 pflag = 1;
9262 break;
9263 case 'F':
9264 patch_script_path = optarg;
9265 break;
9266 case 'S':
9267 allow_bad_symlinks = 1;
9268 break;
9269 default:
9270 usage_stage();
9271 /* NOTREACHED */
9275 argc -= optind;
9276 argv += optind;
9278 #ifndef PROFILE
9279 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9280 "unveil", NULL) == -1)
9281 err(1, "pledge");
9282 #endif
9283 if (list_stage && (pflag || patch_script_path))
9284 errx(1, "-l option cannot be used with other options");
9285 if (patch_script_path && !pflag)
9286 errx(1, "-F option can only be used together with -p option");
9288 cwd = getcwd(NULL, 0);
9289 if (cwd == NULL) {
9290 error = got_error_from_errno("getcwd");
9291 goto done;
9294 error = got_worktree_open(&worktree, cwd);
9295 if (error) {
9296 if (error->code == GOT_ERR_NOT_WORKTREE)
9297 error = wrap_not_worktree_error(error, "stage", cwd);
9298 goto done;
9301 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9302 NULL);
9303 if (error != NULL)
9304 goto done;
9306 if (patch_script_path) {
9307 patch_script_file = fopen(patch_script_path, "r");
9308 if (patch_script_file == NULL) {
9309 error = got_error_from_errno2("fopen",
9310 patch_script_path);
9311 goto done;
9314 error = apply_unveil(got_repo_get_path(repo), 0,
9315 got_worktree_get_root_path(worktree));
9316 if (error)
9317 goto done;
9319 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9320 if (error)
9321 goto done;
9323 if (list_stage)
9324 error = got_worktree_status(worktree, &paths, repo,
9325 print_stage, NULL, check_cancelled, NULL);
9326 else {
9327 cpa.patch_script_file = patch_script_file;
9328 cpa.action = "stage";
9329 error = got_worktree_stage(worktree, &paths,
9330 pflag ? NULL : print_status, NULL,
9331 pflag ? choose_patch : NULL, &cpa,
9332 allow_bad_symlinks, repo);
9334 done:
9335 if (patch_script_file && fclose(patch_script_file) == EOF &&
9336 error == NULL)
9337 error = got_error_from_errno2("fclose", patch_script_path);
9338 if (repo)
9339 got_repo_close(repo);
9340 if (worktree)
9341 got_worktree_close(worktree);
9342 TAILQ_FOREACH(pe, &paths, entry)
9343 free((char *)pe->path);
9344 got_pathlist_free(&paths);
9345 free(cwd);
9346 return error;
9349 __dead static void
9350 usage_unstage(void)
9352 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
9353 "[file-path ...]\n",
9354 getprogname());
9355 exit(1);
9359 static const struct got_error *
9360 cmd_unstage(int argc, char *argv[])
9362 const struct got_error *error = NULL;
9363 struct got_repository *repo = NULL;
9364 struct got_worktree *worktree = NULL;
9365 char *cwd = NULL;
9366 struct got_pathlist_head paths;
9367 struct got_pathlist_entry *pe;
9368 int ch, pflag = 0;
9369 struct got_update_progress_arg upa;
9370 FILE *patch_script_file = NULL;
9371 const char *patch_script_path = NULL;
9372 struct choose_patch_arg cpa;
9374 TAILQ_INIT(&paths);
9376 while ((ch = getopt(argc, argv, "pF:")) != -1) {
9377 switch (ch) {
9378 case 'p':
9379 pflag = 1;
9380 break;
9381 case 'F':
9382 patch_script_path = optarg;
9383 break;
9384 default:
9385 usage_unstage();
9386 /* NOTREACHED */
9390 argc -= optind;
9391 argv += optind;
9393 #ifndef PROFILE
9394 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9395 "unveil", NULL) == -1)
9396 err(1, "pledge");
9397 #endif
9398 if (patch_script_path && !pflag)
9399 errx(1, "-F option can only be used together with -p option");
9401 cwd = getcwd(NULL, 0);
9402 if (cwd == NULL) {
9403 error = got_error_from_errno("getcwd");
9404 goto done;
9407 error = got_worktree_open(&worktree, cwd);
9408 if (error) {
9409 if (error->code == GOT_ERR_NOT_WORKTREE)
9410 error = wrap_not_worktree_error(error, "unstage", cwd);
9411 goto done;
9414 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9415 NULL);
9416 if (error != NULL)
9417 goto done;
9419 if (patch_script_path) {
9420 patch_script_file = fopen(patch_script_path, "r");
9421 if (patch_script_file == NULL) {
9422 error = got_error_from_errno2("fopen",
9423 patch_script_path);
9424 goto done;
9428 error = apply_unveil(got_repo_get_path(repo), 0,
9429 got_worktree_get_root_path(worktree));
9430 if (error)
9431 goto done;
9433 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9434 if (error)
9435 goto done;
9437 cpa.patch_script_file = patch_script_file;
9438 cpa.action = "unstage";
9439 memset(&upa, 0, sizeof(upa));
9440 error = got_worktree_unstage(worktree, &paths, update_progress,
9441 &upa, pflag ? choose_patch : NULL, &cpa, repo);
9442 if (!error)
9443 print_update_progress_stats(&upa);
9444 done:
9445 if (patch_script_file && fclose(patch_script_file) == EOF &&
9446 error == NULL)
9447 error = got_error_from_errno2("fclose", patch_script_path);
9448 if (repo)
9449 got_repo_close(repo);
9450 if (worktree)
9451 got_worktree_close(worktree);
9452 TAILQ_FOREACH(pe, &paths, entry)
9453 free((char *)pe->path);
9454 got_pathlist_free(&paths);
9455 free(cwd);
9456 return error;
9459 __dead static void
9460 usage_cat(void)
9462 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
9463 "arg1 [arg2 ...]\n", getprogname());
9464 exit(1);
9467 static const struct got_error *
9468 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9470 const struct got_error *err;
9471 struct got_blob_object *blob;
9473 err = got_object_open_as_blob(&blob, repo, id, 8192);
9474 if (err)
9475 return err;
9477 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
9478 got_object_blob_close(blob);
9479 return err;
9482 static const struct got_error *
9483 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9485 const struct got_error *err;
9486 struct got_tree_object *tree;
9487 int nentries, i;
9489 err = got_object_open_as_tree(&tree, repo, id);
9490 if (err)
9491 return err;
9493 nentries = got_object_tree_get_nentries(tree);
9494 for (i = 0; i < nentries; i++) {
9495 struct got_tree_entry *te;
9496 char *id_str;
9497 if (sigint_received || sigpipe_received)
9498 break;
9499 te = got_object_tree_get_entry(tree, i);
9500 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
9501 if (err)
9502 break;
9503 fprintf(outfile, "%s %.7o %s\n", id_str,
9504 got_tree_entry_get_mode(te),
9505 got_tree_entry_get_name(te));
9506 free(id_str);
9509 got_object_tree_close(tree);
9510 return err;
9513 static const struct got_error *
9514 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9516 const struct got_error *err;
9517 struct got_commit_object *commit;
9518 const struct got_object_id_queue *parent_ids;
9519 struct got_object_qid *pid;
9520 char *id_str = NULL;
9521 const char *logmsg = NULL;
9523 err = got_object_open_as_commit(&commit, repo, id);
9524 if (err)
9525 return err;
9527 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
9528 if (err)
9529 goto done;
9531 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
9532 parent_ids = got_object_commit_get_parent_ids(commit);
9533 fprintf(outfile, "numparents %d\n",
9534 got_object_commit_get_nparents(commit));
9535 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
9536 char *pid_str;
9537 err = got_object_id_str(&pid_str, pid->id);
9538 if (err)
9539 goto done;
9540 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
9541 free(pid_str);
9543 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
9544 got_object_commit_get_author(commit),
9545 (long long)got_object_commit_get_author_time(commit));
9547 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
9548 got_object_commit_get_author(commit),
9549 (long long)got_object_commit_get_committer_time(commit));
9551 logmsg = got_object_commit_get_logmsg_raw(commit);
9552 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
9553 fprintf(outfile, "%s", logmsg);
9554 done:
9555 free(id_str);
9556 got_object_commit_close(commit);
9557 return err;
9560 static const struct got_error *
9561 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9563 const struct got_error *err;
9564 struct got_tag_object *tag;
9565 char *id_str = NULL;
9566 const char *tagmsg = NULL;
9568 err = got_object_open_as_tag(&tag, repo, id);
9569 if (err)
9570 return err;
9572 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
9573 if (err)
9574 goto done;
9576 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
9578 switch (got_object_tag_get_object_type(tag)) {
9579 case GOT_OBJ_TYPE_BLOB:
9580 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9581 GOT_OBJ_LABEL_BLOB);
9582 break;
9583 case GOT_OBJ_TYPE_TREE:
9584 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9585 GOT_OBJ_LABEL_TREE);
9586 break;
9587 case GOT_OBJ_TYPE_COMMIT:
9588 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9589 GOT_OBJ_LABEL_COMMIT);
9590 break;
9591 case GOT_OBJ_TYPE_TAG:
9592 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9593 GOT_OBJ_LABEL_TAG);
9594 break;
9595 default:
9596 break;
9599 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
9600 got_object_tag_get_name(tag));
9602 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
9603 got_object_tag_get_tagger(tag),
9604 (long long)got_object_tag_get_tagger_time(tag));
9606 tagmsg = got_object_tag_get_message(tag);
9607 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
9608 fprintf(outfile, "%s", tagmsg);
9609 done:
9610 free(id_str);
9611 got_object_tag_close(tag);
9612 return err;
9615 static const struct got_error *
9616 cmd_cat(int argc, char *argv[])
9618 const struct got_error *error;
9619 struct got_repository *repo = NULL;
9620 struct got_worktree *worktree = NULL;
9621 char *cwd = NULL, *repo_path = NULL, *label = NULL;
9622 const char *commit_id_str = NULL;
9623 struct got_object_id *id = NULL, *commit_id = NULL;
9624 int ch, obj_type, i, force_path = 0;
9625 struct got_reflist_head refs;
9627 SIMPLEQ_INIT(&refs);
9629 #ifndef PROFILE
9630 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9631 NULL) == -1)
9632 err(1, "pledge");
9633 #endif
9635 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
9636 switch (ch) {
9637 case 'c':
9638 commit_id_str = optarg;
9639 break;
9640 case 'r':
9641 repo_path = realpath(optarg, NULL);
9642 if (repo_path == NULL)
9643 return got_error_from_errno2("realpath",
9644 optarg);
9645 got_path_strip_trailing_slashes(repo_path);
9646 break;
9647 case 'P':
9648 force_path = 1;
9649 break;
9650 default:
9651 usage_cat();
9652 /* NOTREACHED */
9656 argc -= optind;
9657 argv += optind;
9659 cwd = getcwd(NULL, 0);
9660 if (cwd == NULL) {
9661 error = got_error_from_errno("getcwd");
9662 goto done;
9664 error = got_worktree_open(&worktree, cwd);
9665 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9666 goto done;
9667 if (worktree) {
9668 if (repo_path == NULL) {
9669 repo_path = strdup(
9670 got_worktree_get_repo_path(worktree));
9671 if (repo_path == NULL) {
9672 error = got_error_from_errno("strdup");
9673 goto done;
9678 if (repo_path == NULL) {
9679 repo_path = getcwd(NULL, 0);
9680 if (repo_path == NULL)
9681 return got_error_from_errno("getcwd");
9684 error = got_repo_open(&repo, repo_path, NULL);
9685 free(repo_path);
9686 if (error != NULL)
9687 goto done;
9689 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9690 if (error)
9691 goto done;
9693 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9694 if (error)
9695 goto done;
9697 if (commit_id_str == NULL)
9698 commit_id_str = GOT_REF_HEAD;
9699 error = got_repo_match_object_id(&commit_id, NULL,
9700 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
9701 if (error)
9702 goto done;
9704 for (i = 0; i < argc; i++) {
9705 if (force_path) {
9706 error = got_object_id_by_path(&id, repo, commit_id,
9707 argv[i]);
9708 if (error)
9709 break;
9710 } else {
9711 error = got_repo_match_object_id(&id, &label, argv[i],
9712 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
9713 repo);
9714 if (error) {
9715 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9716 error->code != GOT_ERR_NOT_REF)
9717 break;
9718 error = got_object_id_by_path(&id, repo,
9719 commit_id, argv[i]);
9720 if (error)
9721 break;
9725 error = got_object_get_type(&obj_type, repo, id);
9726 if (error)
9727 break;
9729 switch (obj_type) {
9730 case GOT_OBJ_TYPE_BLOB:
9731 error = cat_blob(id, repo, stdout);
9732 break;
9733 case GOT_OBJ_TYPE_TREE:
9734 error = cat_tree(id, repo, stdout);
9735 break;
9736 case GOT_OBJ_TYPE_COMMIT:
9737 error = cat_commit(id, repo, stdout);
9738 break;
9739 case GOT_OBJ_TYPE_TAG:
9740 error = cat_tag(id, repo, stdout);
9741 break;
9742 default:
9743 error = got_error(GOT_ERR_OBJ_TYPE);
9744 break;
9746 if (error)
9747 break;
9748 free(label);
9749 label = NULL;
9750 free(id);
9751 id = NULL;
9753 done:
9754 free(label);
9755 free(id);
9756 free(commit_id);
9757 if (worktree)
9758 got_worktree_close(worktree);
9759 if (repo) {
9760 const struct got_error *repo_error;
9761 repo_error = got_repo_close(repo);
9762 if (error == NULL)
9763 error = repo_error;
9765 got_ref_list_free(&refs);
9766 return error;
9769 __dead static void
9770 usage_info(void)
9772 fprintf(stderr, "usage: %s info [path ...]\n",
9773 getprogname());
9774 exit(1);
9777 static const struct got_error *
9778 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
9779 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9780 struct got_object_id *commit_id)
9782 const struct got_error *err = NULL;
9783 char *id_str = NULL;
9784 char datebuf[128];
9785 struct tm mytm, *tm;
9786 struct got_pathlist_head *paths = arg;
9787 struct got_pathlist_entry *pe;
9790 * Clear error indication from any of the path arguments which
9791 * would cause this file index entry to be displayed.
9793 TAILQ_FOREACH(pe, paths, entry) {
9794 if (got_path_cmp(path, pe->path, strlen(path),
9795 pe->path_len) == 0 ||
9796 got_path_is_child(path, pe->path, pe->path_len))
9797 pe->data = NULL; /* no error */
9800 printf(GOT_COMMIT_SEP_STR);
9801 if (S_ISLNK(mode))
9802 printf("symlink: %s\n", path);
9803 else if (S_ISREG(mode)) {
9804 printf("file: %s\n", path);
9805 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
9806 } else if (S_ISDIR(mode))
9807 printf("directory: %s\n", path);
9808 else
9809 printf("something: %s\n", path);
9811 tm = localtime_r(&mtime, &mytm);
9812 if (tm == NULL)
9813 return NULL;
9814 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) >= sizeof(datebuf))
9815 return got_error(GOT_ERR_NO_SPACE);
9816 printf("timestamp: %s\n", datebuf);
9818 if (blob_id) {
9819 err = got_object_id_str(&id_str, blob_id);
9820 if (err)
9821 return err;
9822 printf("based on blob: %s\n", id_str);
9823 free(id_str);
9826 if (staged_blob_id) {
9827 err = got_object_id_str(&id_str, staged_blob_id);
9828 if (err)
9829 return err;
9830 printf("based on staged blob: %s\n", id_str);
9831 free(id_str);
9834 if (commit_id) {
9835 err = got_object_id_str(&id_str, commit_id);
9836 if (err)
9837 return err;
9838 printf("based on commit: %s\n", id_str);
9839 free(id_str);
9842 return NULL;
9845 static const struct got_error *
9846 cmd_info(int argc, char *argv[])
9848 const struct got_error *error = NULL;
9849 struct got_worktree *worktree = NULL;
9850 char *cwd = NULL, *id_str = NULL;
9851 struct got_pathlist_head paths;
9852 struct got_pathlist_entry *pe;
9853 char *uuidstr = NULL;
9854 int ch, show_files = 0;
9856 TAILQ_INIT(&paths);
9858 while ((ch = getopt(argc, argv, "")) != -1) {
9859 switch (ch) {
9860 default:
9861 usage_info();
9862 /* NOTREACHED */
9866 argc -= optind;
9867 argv += optind;
9869 #ifndef PROFILE
9870 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
9871 NULL) == -1)
9872 err(1, "pledge");
9873 #endif
9874 cwd = getcwd(NULL, 0);
9875 if (cwd == NULL) {
9876 error = got_error_from_errno("getcwd");
9877 goto done;
9880 error = got_worktree_open(&worktree, cwd);
9881 if (error) {
9882 if (error->code == GOT_ERR_NOT_WORKTREE)
9883 error = wrap_not_worktree_error(error, "status", cwd);
9884 goto done;
9887 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9888 if (error)
9889 goto done;
9891 if (argc >= 1) {
9892 error = get_worktree_paths_from_argv(&paths, argc, argv,
9893 worktree);
9894 if (error)
9895 goto done;
9896 show_files = 1;
9899 error = got_object_id_str(&id_str,
9900 got_worktree_get_base_commit_id(worktree));
9901 if (error)
9902 goto done;
9904 error = got_worktree_get_uuid(&uuidstr, worktree);
9905 if (error)
9906 goto done;
9908 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9909 printf("work tree base commit: %s\n", id_str);
9910 printf("work tree path prefix: %s\n",
9911 got_worktree_get_path_prefix(worktree));
9912 printf("work tree branch reference: %s\n",
9913 got_worktree_get_head_ref_name(worktree));
9914 printf("work tree UUID: %s\n", uuidstr);
9915 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
9917 if (show_files) {
9918 struct got_pathlist_entry *pe;
9919 TAILQ_FOREACH(pe, &paths, entry) {
9920 if (pe->path_len == 0)
9921 continue;
9923 * Assume this path will fail. This will be corrected
9924 * in print_path_info() in case the path does suceeed.
9926 pe->data = (void *)got_error_path(pe->path,
9927 GOT_ERR_BAD_PATH);
9929 error = got_worktree_path_info(worktree, &paths,
9930 print_path_info, &paths, check_cancelled, NULL);
9931 if (error)
9932 goto done;
9933 TAILQ_FOREACH(pe, &paths, entry) {
9934 if (pe->data != NULL) {
9935 error = pe->data; /* bad path */
9936 break;
9940 done:
9941 TAILQ_FOREACH(pe, &paths, entry)
9942 free((char *)pe->path);
9943 got_pathlist_free(&paths);
9944 free(cwd);
9945 free(id_str);
9946 free(uuidstr);
9947 return error;