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, const char *default_branch,
1167 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1168 int mirror_references, struct got_repository *repo)
1170 const struct got_error *err = NULL;
1171 char *gotconfig_path = NULL;
1172 char *gotconfig = NULL;
1173 FILE *gotconfig_file = NULL;
1174 const char *branchname = NULL;
1175 char *branches = NULL;
1176 ssize_t n;
1178 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1179 struct got_pathlist_entry *pe;
1180 TAILQ_FOREACH(pe, wanted_branches, entry) {
1181 char *s;
1182 branchname = pe->path;
1183 if (strncmp(branchname, "refs/heads/", 11) == 0)
1184 branchname += 11;
1185 if (asprintf(&s, "%s\"%s\" ",
1186 branches ? branches : "", branchname) == -1) {
1187 err = got_error_from_errno("asprintf");
1188 goto done;
1190 free(branches);
1191 branches = s;
1193 } else if (!fetch_all_branches && default_branch) {
1194 branchname = default_branch;
1195 if (strncmp(branchname, "refs/heads/", 11) == 0)
1196 branchname += 11;
1197 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1198 err = got_error_from_errno("asprintf");
1199 goto done;
1203 /* Create got.conf(5). */
1204 gotconfig_path = got_repo_get_path_gotconfig(repo);
1205 if (gotconfig_path == NULL) {
1206 err = got_error_from_errno("got_repo_get_path_gotconfig");
1207 goto done;
1209 gotconfig_file = fopen(gotconfig_path, "a");
1210 if (gotconfig_file == NULL) {
1211 err = got_error_from_errno2("fopen", gotconfig_path);
1212 goto done;
1214 if (asprintf(&gotconfig,
1215 "remote \"%s\" {\n"
1216 "\tserver %s\n"
1217 "\tprotocol %s\n"
1218 "%s%s%s"
1219 "\trepository \"%s\"\n"
1220 "%s%s%s"
1221 "%s"
1222 "%s"
1223 "}\n",
1224 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1225 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1226 remote_repo_path, branches ? "\tbranch { " : "",
1227 branches ? branches : "", branches ? "}\n" : "",
1228 mirror_references ? "\tmirror-references yes\n" : "",
1229 fetch_all_branches ? "\tfetch-all-branches yes\n" : "") == -1) {
1230 err = got_error_from_errno("asprintf");
1231 goto done;
1233 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1234 if (n != strlen(gotconfig)) {
1235 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1236 goto done;
1239 done:
1240 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1241 err = got_error_from_errno2("fclose", gotconfig_path);
1242 free(gotconfig_path);
1243 free(branches);
1244 return err;
1247 static const struct got_error *
1248 create_gitconfig(const char *git_url, const char *default_branch,
1249 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1250 int mirror_references, struct got_repository *repo)
1252 const struct got_error *err = NULL;
1253 char *gitconfig_path = NULL;
1254 char *gitconfig = NULL;
1255 FILE *gitconfig_file = NULL;
1256 char *branches = NULL;
1257 const char *branchname, *mirror = NULL;
1258 ssize_t n;
1260 /* Create a config file Git can understand. */
1261 gitconfig_path = got_repo_get_path_gitconfig(repo);
1262 if (gitconfig_path == NULL) {
1263 err = got_error_from_errno("got_repo_get_path_gitconfig");
1264 goto done;
1266 gitconfig_file = fopen(gitconfig_path, "a");
1267 if (gitconfig_file == NULL) {
1268 err = got_error_from_errno2("fopen", gitconfig_path);
1269 goto done;
1271 if (mirror_references) {
1272 mirror = "\tmirror = true\n";
1273 branches = strdup("\tfetch = +refs/*:refs/*\n");
1274 if (branches == NULL) {
1275 err = got_error_from_errno("strdup");
1276 goto done;
1278 } else if (fetch_all_branches) {
1279 if (asprintf(&branches,
1280 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1281 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1282 err = got_error_from_errno("asprintf");
1283 goto done;
1285 } else if (!TAILQ_EMPTY(wanted_branches)) {
1286 struct got_pathlist_entry *pe;
1287 TAILQ_FOREACH(pe, wanted_branches, entry) {
1288 char *s;
1289 branchname = pe->path;
1290 if (strncmp(branchname, "refs/heads/", 11) == 0)
1291 branchname += 11;
1292 if (asprintf(&s,
1293 "%s\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1294 branches ? branches : "",
1295 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1296 branchname) == -1) {
1297 err = got_error_from_errno("asprintf");
1298 goto done;
1300 free(branches);
1301 branches = s;
1303 } else {
1305 * If the server specified a default branch, use just that one.
1306 * Otherwise fall back to fetching all branches on next fetch.
1308 if (default_branch) {
1309 branchname = default_branch;
1310 if (strncmp(branchname, "refs/heads/", 11) == 0)
1311 branchname += 11;
1312 } else
1313 branchname = "*"; /* fall back to all branches */
1314 if (asprintf(&branches,
1315 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1316 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1317 branchname) == -1) {
1318 err = got_error_from_errno("asprintf");
1319 goto done;
1322 if (asprintf(&gitconfig,
1323 "[remote \"%s\"]\n"
1324 "\turl = %s\n"
1325 "%s"
1326 "%s",
1327 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1328 mirror ? mirror : "") == -1) {
1329 err = got_error_from_errno("asprintf");
1330 goto done;
1332 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1333 if (n != strlen(gitconfig)) {
1334 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1335 goto done;
1337 done:
1338 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1339 err = got_error_from_errno2("fclose", gitconfig_path);
1340 free(gitconfig_path);
1341 free(branches);
1342 return err;
1345 static const struct got_error *
1346 create_config_files(const char *proto, const char *host, const char *port,
1347 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1348 int mirror_references, struct got_pathlist_head *symrefs,
1349 struct got_pathlist_head *wanted_branches, struct got_repository *repo)
1351 const struct got_error *err = NULL;
1352 const char *default_branch = NULL;
1353 struct got_pathlist_entry *pe;
1356 * If we asked for a set of wanted branches then use the first
1357 * one of those.
1359 if (!TAILQ_EMPTY(wanted_branches)) {
1360 pe = TAILQ_FIRST(wanted_branches);
1361 default_branch = pe->path;
1362 } else {
1363 /* First HEAD ref listed by server is the default branch. */
1364 TAILQ_FOREACH(pe, symrefs, entry) {
1365 const char *refname = pe->path;
1366 const char *target = pe->data;
1368 if (strcmp(refname, GOT_REF_HEAD) != 0)
1369 continue;
1371 default_branch = target;
1372 break;
1376 /* Create got.conf(5). */
1377 err = create_gotconfig(proto, host, port, remote_repo_path,
1378 default_branch, fetch_all_branches, wanted_branches,
1379 mirror_references, repo);
1380 if (err)
1381 return err;
1383 /* Create a config file Git can understand. */
1384 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1385 wanted_branches, mirror_references, repo);
1388 static const struct got_error *
1389 cmd_clone(int argc, char *argv[])
1391 const struct got_error *error = NULL;
1392 const char *uri, *dirname;
1393 char *proto, *host, *port, *repo_name, *server_path;
1394 char *default_destdir = NULL, *id_str = NULL;
1395 const char *repo_path;
1396 struct got_repository *repo = NULL;
1397 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1398 struct got_pathlist_entry *pe;
1399 struct got_object_id *pack_hash = NULL;
1400 int ch, fetchfd = -1, fetchstatus;
1401 pid_t fetchpid = -1;
1402 struct got_fetch_progress_arg fpa;
1403 char *git_url = NULL;
1404 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1405 int list_refs_only = 0;
1407 TAILQ_INIT(&refs);
1408 TAILQ_INIT(&symrefs);
1409 TAILQ_INIT(&wanted_branches);
1410 TAILQ_INIT(&wanted_refs);
1412 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1413 switch (ch) {
1414 case 'a':
1415 fetch_all_branches = 1;
1416 break;
1417 case 'b':
1418 error = got_pathlist_append(&wanted_branches,
1419 optarg, NULL);
1420 if (error)
1421 return error;
1422 break;
1423 case 'l':
1424 list_refs_only = 1;
1425 break;
1426 case 'm':
1427 mirror_references = 1;
1428 break;
1429 case 'v':
1430 if (verbosity < 0)
1431 verbosity = 0;
1432 else if (verbosity < 3)
1433 verbosity++;
1434 break;
1435 case 'q':
1436 verbosity = -1;
1437 break;
1438 case 'R':
1439 error = got_pathlist_append(&wanted_refs,
1440 optarg, NULL);
1441 if (error)
1442 return error;
1443 break;
1444 default:
1445 usage_clone();
1446 break;
1449 argc -= optind;
1450 argv += optind;
1452 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1453 option_conflict('a', 'b');
1454 if (list_refs_only) {
1455 if (!TAILQ_EMPTY(&wanted_branches))
1456 option_conflict('l', 'b');
1457 if (fetch_all_branches)
1458 option_conflict('l', 'a');
1459 if (mirror_references)
1460 option_conflict('l', 'm');
1461 if (verbosity == -1)
1462 option_conflict('l', 'q');
1463 if (!TAILQ_EMPTY(&wanted_refs))
1464 option_conflict('l', 'R');
1467 uri = argv[0];
1469 if (argc == 1)
1470 dirname = NULL;
1471 else if (argc == 2)
1472 dirname = argv[1];
1473 else
1474 usage_clone();
1476 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1477 &repo_name, uri);
1478 if (error)
1479 goto done;
1481 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1482 host, port ? ":" : "", port ? port : "",
1483 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1484 error = got_error_from_errno("asprintf");
1485 goto done;
1488 if (strcmp(proto, "git") == 0) {
1489 #ifndef PROFILE
1490 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1491 "sendfd dns inet unveil", NULL) == -1)
1492 err(1, "pledge");
1493 #endif
1494 } else if (strcmp(proto, "git+ssh") == 0 ||
1495 strcmp(proto, "ssh") == 0) {
1496 #ifndef PROFILE
1497 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1498 "sendfd unveil", NULL) == -1)
1499 err(1, "pledge");
1500 #endif
1501 } else if (strcmp(proto, "http") == 0 ||
1502 strcmp(proto, "git+http") == 0) {
1503 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1504 goto done;
1505 } else {
1506 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1507 goto done;
1509 if (dirname == NULL) {
1510 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1511 error = got_error_from_errno("asprintf");
1512 goto done;
1514 repo_path = default_destdir;
1515 } else
1516 repo_path = dirname;
1518 if (!list_refs_only) {
1519 error = got_path_mkdir(repo_path);
1520 if (error &&
1521 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1522 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1523 goto done;
1524 if (!got_path_dir_is_empty(repo_path)) {
1525 error = got_error_path(repo_path,
1526 GOT_ERR_DIR_NOT_EMPTY);
1527 goto done;
1531 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1532 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1533 error = got_error_from_errno2("unveil",
1534 GOT_FETCH_PATH_SSH);
1535 goto done;
1538 error = apply_unveil(repo_path, 0, NULL);
1539 if (error)
1540 goto done;
1542 if (verbosity >= 0)
1543 printf("Connecting to %s%s%s\n", host,
1544 port ? ":" : "", port ? port : "");
1546 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1547 server_path, verbosity);
1548 if (error)
1549 goto done;
1551 if (!list_refs_only) {
1552 error = got_repo_init(repo_path);
1553 if (error)
1554 goto done;
1555 error = got_repo_open(&repo, repo_path, NULL);
1556 if (error)
1557 goto done;
1560 fpa.last_scaled_size[0] = '\0';
1561 fpa.last_p_indexed = -1;
1562 fpa.last_p_resolved = -1;
1563 fpa.verbosity = verbosity;
1564 fpa.create_configs = 1;
1565 fpa.configs_created = 0;
1566 fpa.repo = repo;
1567 fpa.config_info.symrefs = &symrefs;
1568 fpa.config_info.wanted_branches = &wanted_branches;
1569 fpa.config_info.proto = proto;
1570 fpa.config_info.host = host;
1571 fpa.config_info.port = port;
1572 fpa.config_info.remote_repo_path = server_path;
1573 fpa.config_info.git_url = git_url;
1574 fpa.config_info.fetch_all_branches = fetch_all_branches;
1575 fpa.config_info.mirror_references = mirror_references;
1576 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1577 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1578 fetch_all_branches, &wanted_branches, &wanted_refs,
1579 list_refs_only, verbosity, fetchfd, repo,
1580 fetch_progress, &fpa);
1581 if (error)
1582 goto done;
1584 if (list_refs_only) {
1585 error = list_remote_refs(&symrefs, &refs);
1586 goto done;
1589 error = got_object_id_str(&id_str, pack_hash);
1590 if (error)
1591 goto done;
1592 if (verbosity >= 0)
1593 printf("\nFetched %s.pack\n", id_str);
1594 free(id_str);
1596 /* Set up references provided with the pack file. */
1597 TAILQ_FOREACH(pe, &refs, entry) {
1598 const char *refname = pe->path;
1599 struct got_object_id *id = pe->data;
1600 char *remote_refname;
1602 if (is_wanted_ref(&wanted_refs, refname) &&
1603 !mirror_references) {
1604 error = create_wanted_ref(refname, id,
1605 GOT_FETCH_DEFAULT_REMOTE_NAME,
1606 verbosity - 1, repo);
1607 if (error)
1608 goto done;
1609 continue;
1612 error = create_ref(refname, id, verbosity - 1, repo);
1613 if (error)
1614 goto done;
1616 if (mirror_references)
1617 continue;
1619 if (strncmp("refs/heads/", refname, 11) != 0)
1620 continue;
1622 if (asprintf(&remote_refname,
1623 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1624 refname + 11) == -1) {
1625 error = got_error_from_errno("asprintf");
1626 goto done;
1628 error = create_ref(remote_refname, id, verbosity - 1, repo);
1629 free(remote_refname);
1630 if (error)
1631 goto done;
1634 /* Set the HEAD reference if the server provided one. */
1635 TAILQ_FOREACH(pe, &symrefs, entry) {
1636 struct got_reference *target_ref;
1637 const char *refname = pe->path;
1638 const char *target = pe->data;
1639 char *remote_refname = NULL, *remote_target = NULL;
1641 if (strcmp(refname, GOT_REF_HEAD) != 0)
1642 continue;
1644 error = got_ref_open(&target_ref, repo, target, 0);
1645 if (error) {
1646 if (error->code == GOT_ERR_NOT_REF) {
1647 error = NULL;
1648 continue;
1650 goto done;
1653 error = create_symref(refname, target_ref, verbosity, repo);
1654 got_ref_close(target_ref);
1655 if (error)
1656 goto done;
1658 if (mirror_references)
1659 continue;
1661 if (strncmp("refs/heads/", target, 11) != 0)
1662 continue;
1664 if (asprintf(&remote_refname,
1665 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1666 refname) == -1) {
1667 error = got_error_from_errno("asprintf");
1668 goto done;
1670 if (asprintf(&remote_target,
1671 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1672 target + 11) == -1) {
1673 error = got_error_from_errno("asprintf");
1674 free(remote_refname);
1675 goto done;
1677 error = got_ref_open(&target_ref, repo, remote_target, 0);
1678 if (error) {
1679 free(remote_refname);
1680 free(remote_target);
1681 if (error->code == GOT_ERR_NOT_REF) {
1682 error = NULL;
1683 continue;
1685 goto done;
1687 error = create_symref(remote_refname, target_ref,
1688 verbosity - 1, repo);
1689 free(remote_refname);
1690 free(remote_target);
1691 got_ref_close(target_ref);
1692 if (error)
1693 goto done;
1695 if (pe == NULL) {
1697 * We failed to set the HEAD reference. If we asked for
1698 * a set of wanted branches use the first of one of those
1699 * which could be fetched instead.
1701 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1702 const char *target = pe->path;
1703 struct got_reference *target_ref;
1705 error = got_ref_open(&target_ref, repo, target, 0);
1706 if (error) {
1707 if (error->code == GOT_ERR_NOT_REF) {
1708 error = NULL;
1709 continue;
1711 goto done;
1714 error = create_symref(GOT_REF_HEAD, target_ref,
1715 verbosity, repo);
1716 got_ref_close(target_ref);
1717 if (error)
1718 goto done;
1719 break;
1723 if (verbosity >= 0)
1724 printf("Created %s repository '%s'\n",
1725 mirror_references ? "mirrored" : "cloned", repo_path);
1726 done:
1727 if (fetchpid > 0) {
1728 if (kill(fetchpid, SIGTERM) == -1)
1729 error = got_error_from_errno("kill");
1730 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1731 error = got_error_from_errno("waitpid");
1733 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1734 error = got_error_from_errno("close");
1735 if (repo)
1736 got_repo_close(repo);
1737 TAILQ_FOREACH(pe, &refs, entry) {
1738 free((void *)pe->path);
1739 free(pe->data);
1741 got_pathlist_free(&refs);
1742 TAILQ_FOREACH(pe, &symrefs, entry) {
1743 free((void *)pe->path);
1744 free(pe->data);
1746 got_pathlist_free(&symrefs);
1747 got_pathlist_free(&wanted_branches);
1748 got_pathlist_free(&wanted_refs);
1749 free(pack_hash);
1750 free(proto);
1751 free(host);
1752 free(port);
1753 free(server_path);
1754 free(repo_name);
1755 free(default_destdir);
1756 free(git_url);
1757 return error;
1760 static const struct got_error *
1761 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1762 int replace_tags, int verbosity, struct got_repository *repo)
1764 const struct got_error *err = NULL;
1765 char *new_id_str = NULL;
1766 struct got_object_id *old_id = NULL;
1768 err = got_object_id_str(&new_id_str, new_id);
1769 if (err)
1770 goto done;
1772 if (!replace_tags &&
1773 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1774 err = got_ref_resolve(&old_id, repo, ref);
1775 if (err)
1776 goto done;
1777 if (got_object_id_cmp(old_id, new_id) == 0)
1778 goto done;
1779 if (verbosity >= 0) {
1780 printf("Rejecting update of existing tag %s: %s\n",
1781 got_ref_get_name(ref), new_id_str);
1783 goto done;
1786 if (got_ref_is_symbolic(ref)) {
1787 if (verbosity >= 0) {
1788 printf("Replacing reference %s: %s\n",
1789 got_ref_get_name(ref),
1790 got_ref_get_symref_target(ref));
1792 err = got_ref_change_symref_to_ref(ref, new_id);
1793 if (err)
1794 goto done;
1795 err = got_ref_write(ref, repo);
1796 if (err)
1797 goto done;
1798 } else {
1799 err = got_ref_resolve(&old_id, repo, ref);
1800 if (err)
1801 goto done;
1802 if (got_object_id_cmp(old_id, new_id) == 0)
1803 goto done;
1805 err = got_ref_change_ref(ref, new_id);
1806 if (err)
1807 goto done;
1808 err = got_ref_write(ref, repo);
1809 if (err)
1810 goto done;
1813 if (verbosity >= 0)
1814 printf("Updated %s: %s\n", got_ref_get_name(ref),
1815 new_id_str);
1816 done:
1817 free(old_id);
1818 free(new_id_str);
1819 return err;
1822 static const struct got_error *
1823 update_symref(const char *refname, struct got_reference *target_ref,
1824 int verbosity, struct got_repository *repo)
1826 const struct got_error *err = NULL, *unlock_err;
1827 struct got_reference *symref;
1828 int symref_is_locked = 0;
1830 err = got_ref_open(&symref, repo, refname, 1);
1831 if (err) {
1832 if (err->code != GOT_ERR_NOT_REF)
1833 return err;
1834 err = got_ref_alloc_symref(&symref, refname, target_ref);
1835 if (err)
1836 goto done;
1838 err = got_ref_write(symref, repo);
1839 if (err)
1840 goto done;
1842 if (verbosity >= 0)
1843 printf("Created reference %s: %s\n",
1844 got_ref_get_name(symref),
1845 got_ref_get_symref_target(symref));
1846 } else {
1847 symref_is_locked = 1;
1849 if (strcmp(got_ref_get_symref_target(symref),
1850 got_ref_get_name(target_ref)) == 0)
1851 goto done;
1853 err = got_ref_change_symref(symref,
1854 got_ref_get_name(target_ref));
1855 if (err)
1856 goto done;
1858 err = got_ref_write(symref, repo);
1859 if (err)
1860 goto done;
1862 if (verbosity >= 0)
1863 printf("Updated %s: %s\n", got_ref_get_name(symref),
1864 got_ref_get_symref_target(symref));
1867 done:
1868 if (symref_is_locked) {
1869 unlock_err = got_ref_unlock(symref);
1870 if (unlock_err && err == NULL)
1871 err = unlock_err;
1873 got_ref_close(symref);
1874 return err;
1877 __dead static void
1878 usage_fetch(void)
1880 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1881 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1882 "[remote-repository-name]\n",
1883 getprogname());
1884 exit(1);
1887 static const struct got_error *
1888 delete_missing_ref(struct got_reference *ref,
1889 int verbosity, struct got_repository *repo)
1891 const struct got_error *err = NULL;
1892 struct got_object_id *id = NULL;
1893 char *id_str = NULL;
1895 if (got_ref_is_symbolic(ref)) {
1896 err = got_ref_delete(ref, repo);
1897 if (err)
1898 return err;
1899 if (verbosity >= 0) {
1900 printf("Deleted reference %s: %s\n",
1901 got_ref_get_name(ref),
1902 got_ref_get_symref_target(ref));
1904 } else {
1905 err = got_ref_resolve(&id, repo, ref);
1906 if (err)
1907 return err;
1908 err = got_object_id_str(&id_str, id);
1909 if (err)
1910 goto done;
1912 err = got_ref_delete(ref, repo);
1913 if (err)
1914 goto done;
1915 if (verbosity >= 0) {
1916 printf("Deleted reference %s: %s\n",
1917 got_ref_get_name(ref), id_str);
1920 done:
1921 free(id);
1922 free(id_str);
1923 return NULL;
1926 static const struct got_error *
1927 delete_missing_refs(struct got_pathlist_head *their_refs,
1928 struct got_pathlist_head *their_symrefs,
1929 const struct got_remote_repo *remote,
1930 int verbosity, struct got_repository *repo)
1932 const struct got_error *err = NULL, *unlock_err;
1933 struct got_reflist_head my_refs;
1934 struct got_reflist_entry *re;
1935 struct got_pathlist_entry *pe;
1936 char *remote_namespace = NULL;
1937 char *local_refname = NULL;
1939 TAILQ_INIT(&my_refs);
1941 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
1942 == -1)
1943 return got_error_from_errno("asprintf");
1945 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1946 if (err)
1947 goto done;
1949 TAILQ_FOREACH(re, &my_refs, entry) {
1950 const char *refname = got_ref_get_name(re->ref);
1952 if (!remote->mirror_references) {
1953 if (strncmp(refname, remote_namespace,
1954 strlen(remote_namespace)) == 0) {
1955 if (strcmp(refname + strlen(remote_namespace),
1956 GOT_REF_HEAD) == 0)
1957 continue;
1958 if (asprintf(&local_refname, "refs/heads/%s",
1959 refname + strlen(remote_namespace)) == -1) {
1960 err = got_error_from_errno("asprintf");
1961 goto done;
1963 } else if (strncmp(refname, "refs/tags/", 10) != 0)
1964 continue;
1967 TAILQ_FOREACH(pe, their_refs, entry) {
1968 if (strcmp(local_refname, pe->path) == 0)
1969 break;
1971 if (pe != NULL)
1972 continue;
1974 TAILQ_FOREACH(pe, their_symrefs, entry) {
1975 if (strcmp(local_refname, pe->path) == 0)
1976 break;
1978 if (pe != NULL)
1979 continue;
1981 err = delete_missing_ref(re->ref, verbosity, repo);
1982 if (err)
1983 break;
1985 if (local_refname) {
1986 struct got_reference *ref;
1987 err = got_ref_open(&ref, repo, local_refname, 1);
1988 if (err) {
1989 if (err->code != GOT_ERR_NOT_REF)
1990 break;
1991 free(local_refname);
1992 local_refname = NULL;
1993 continue;
1995 err = delete_missing_ref(ref, verbosity, repo);
1996 if (err)
1997 break;
1998 unlock_err = got_ref_unlock(ref);
1999 got_ref_close(ref);
2000 if (unlock_err && err == NULL) {
2001 err = unlock_err;
2002 break;
2005 free(local_refname);
2006 local_refname = NULL;
2009 done:
2010 free(remote_namespace);
2011 free(local_refname);
2012 return err;
2015 static const struct got_error *
2016 update_wanted_ref(const char *refname, struct got_object_id *id,
2017 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2019 const struct got_error *err, *unlock_err;
2020 char *remote_refname;
2021 struct got_reference *ref;
2023 if (strncmp("refs/", refname, 5) == 0)
2024 refname += 5;
2026 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2027 remote_repo_name, refname) == -1)
2028 return got_error_from_errno("asprintf");
2030 err = got_ref_open(&ref, repo, remote_refname, 1);
2031 if (err) {
2032 if (err->code != GOT_ERR_NOT_REF)
2033 goto done;
2034 err = create_ref(remote_refname, id, verbosity, repo);
2035 } else {
2036 err = update_ref(ref, id, 0, verbosity, repo);
2037 unlock_err = got_ref_unlock(ref);
2038 if (unlock_err && err == NULL)
2039 err = unlock_err;
2040 got_ref_close(ref);
2042 done:
2043 free(remote_refname);
2044 return err;
2047 static const struct got_error *
2048 cmd_fetch(int argc, char *argv[])
2050 const struct got_error *error = NULL, *unlock_err;
2051 char *cwd = NULL, *repo_path = NULL;
2052 const char *remote_name;
2053 char *proto = NULL, *host = NULL, *port = NULL;
2054 char *repo_name = NULL, *server_path = NULL;
2055 const struct got_remote_repo *remotes, *remote = NULL;
2056 int nremotes;
2057 char *id_str = NULL;
2058 struct got_repository *repo = NULL;
2059 struct got_worktree *worktree = NULL;
2060 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2061 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2062 struct got_pathlist_entry *pe;
2063 struct got_object_id *pack_hash = NULL;
2064 int i, ch, fetchfd = -1, fetchstatus;
2065 pid_t fetchpid = -1;
2066 struct got_fetch_progress_arg fpa;
2067 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2068 int delete_refs = 0, replace_tags = 0;
2070 TAILQ_INIT(&refs);
2071 TAILQ_INIT(&symrefs);
2072 TAILQ_INIT(&wanted_branches);
2073 TAILQ_INIT(&wanted_refs);
2075 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
2076 switch (ch) {
2077 case 'a':
2078 fetch_all_branches = 1;
2079 break;
2080 case 'b':
2081 error = got_pathlist_append(&wanted_branches,
2082 optarg, NULL);
2083 if (error)
2084 return error;
2085 break;
2086 case 'd':
2087 delete_refs = 1;
2088 break;
2089 case 'l':
2090 list_refs_only = 1;
2091 break;
2092 case 'r':
2093 repo_path = realpath(optarg, NULL);
2094 if (repo_path == NULL)
2095 return got_error_from_errno2("realpath",
2096 optarg);
2097 got_path_strip_trailing_slashes(repo_path);
2098 break;
2099 case 't':
2100 replace_tags = 1;
2101 break;
2102 case 'v':
2103 if (verbosity < 0)
2104 verbosity = 0;
2105 else if (verbosity < 3)
2106 verbosity++;
2107 break;
2108 case 'q':
2109 verbosity = -1;
2110 break;
2111 case 'R':
2112 error = got_pathlist_append(&wanted_refs,
2113 optarg, NULL);
2114 if (error)
2115 return error;
2116 break;
2117 default:
2118 usage_fetch();
2119 break;
2122 argc -= optind;
2123 argv += optind;
2125 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2126 option_conflict('a', 'b');
2127 if (list_refs_only) {
2128 if (!TAILQ_EMPTY(&wanted_branches))
2129 option_conflict('l', 'b');
2130 if (fetch_all_branches)
2131 option_conflict('l', 'a');
2132 if (delete_refs)
2133 option_conflict('l', 'd');
2136 if (argc == 0)
2137 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2138 else if (argc == 1)
2139 remote_name = argv[0];
2140 else
2141 usage_fetch();
2143 cwd = getcwd(NULL, 0);
2144 if (cwd == NULL) {
2145 error = got_error_from_errno("getcwd");
2146 goto done;
2149 if (repo_path == NULL) {
2150 error = got_worktree_open(&worktree, cwd);
2151 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2152 goto done;
2153 else
2154 error = NULL;
2155 if (worktree) {
2156 repo_path =
2157 strdup(got_worktree_get_repo_path(worktree));
2158 if (repo_path == NULL)
2159 error = got_error_from_errno("strdup");
2160 if (error)
2161 goto done;
2162 } else {
2163 repo_path = strdup(cwd);
2164 if (repo_path == NULL) {
2165 error = got_error_from_errno("strdup");
2166 goto done;
2171 error = got_repo_open(&repo, repo_path, NULL);
2172 if (error)
2173 goto done;
2175 if (worktree) {
2176 worktree_conf = got_worktree_get_gotconfig(worktree);
2177 if (worktree_conf) {
2178 got_gotconfig_get_remotes(&nremotes, &remotes,
2179 worktree_conf);
2180 for (i = 0; i < nremotes; i++) {
2181 if (strcmp(remotes[i].name, remote_name) == 0) {
2182 remote = &remotes[i];
2183 break;
2188 if (remote == NULL) {
2189 repo_conf = got_repo_get_gotconfig(repo);
2190 if (repo_conf) {
2191 got_gotconfig_get_remotes(&nremotes, &remotes,
2192 repo_conf);
2193 for (i = 0; i < nremotes; i++) {
2194 if (strcmp(remotes[i].name, remote_name) == 0) {
2195 remote = &remotes[i];
2196 break;
2201 if (remote == NULL) {
2202 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2203 for (i = 0; i < nremotes; i++) {
2204 if (strcmp(remotes[i].name, remote_name) == 0) {
2205 remote = &remotes[i];
2206 break;
2210 if (remote == NULL) {
2211 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2212 goto done;
2215 if (TAILQ_EMPTY(&wanted_branches)) {
2216 if (!fetch_all_branches)
2217 fetch_all_branches = remote->fetch_all_branches;
2218 for (i = 0; i < remote->nbranches; i++) {
2219 got_pathlist_append(&wanted_branches,
2220 remote->branches[i], NULL);
2224 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
2225 &repo_name, remote->url);
2226 if (error)
2227 goto done;
2229 if (strcmp(proto, "git") == 0) {
2230 #ifndef PROFILE
2231 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2232 "sendfd dns inet unveil", NULL) == -1)
2233 err(1, "pledge");
2234 #endif
2235 } else if (strcmp(proto, "git+ssh") == 0 ||
2236 strcmp(proto, "ssh") == 0) {
2237 #ifndef PROFILE
2238 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2239 "sendfd unveil", NULL) == -1)
2240 err(1, "pledge");
2241 #endif
2242 } else if (strcmp(proto, "http") == 0 ||
2243 strcmp(proto, "git+http") == 0) {
2244 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2245 goto done;
2246 } else {
2247 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2248 goto done;
2251 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
2252 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
2253 error = got_error_from_errno2("unveil",
2254 GOT_FETCH_PATH_SSH);
2255 goto done;
2258 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2259 if (error)
2260 goto done;
2262 if (verbosity >= 0)
2263 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2264 port ? ":" : "", port ? port : "");
2266 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2267 server_path, verbosity);
2268 if (error)
2269 goto done;
2271 fpa.last_scaled_size[0] = '\0';
2272 fpa.last_p_indexed = -1;
2273 fpa.last_p_resolved = -1;
2274 fpa.verbosity = verbosity;
2275 fpa.repo = repo;
2276 fpa.create_configs = 0;
2277 fpa.configs_created = 0;
2278 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2279 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2280 remote->mirror_references, fetch_all_branches, &wanted_branches,
2281 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2282 fetch_progress, &fpa);
2283 if (error)
2284 goto done;
2286 if (list_refs_only) {
2287 error = list_remote_refs(&symrefs, &refs);
2288 goto done;
2291 if (pack_hash == NULL) {
2292 if (verbosity >= 0)
2293 printf("Already up-to-date\n");
2294 } else if (verbosity >= 0) {
2295 error = got_object_id_str(&id_str, pack_hash);
2296 if (error)
2297 goto done;
2298 printf("\nFetched %s.pack\n", id_str);
2299 free(id_str);
2300 id_str = NULL;
2303 /* Update references provided with the pack file. */
2304 TAILQ_FOREACH(pe, &refs, entry) {
2305 const char *refname = pe->path;
2306 struct got_object_id *id = pe->data;
2307 struct got_reference *ref;
2308 char *remote_refname;
2310 if (is_wanted_ref(&wanted_refs, refname) &&
2311 !remote->mirror_references) {
2312 error = update_wanted_ref(refname, id,
2313 remote->name, verbosity, repo);
2314 if (error)
2315 goto done;
2316 continue;
2319 if (remote->mirror_references ||
2320 strncmp("refs/tags/", refname, 10) == 0) {
2321 error = got_ref_open(&ref, repo, refname, 1);
2322 if (error) {
2323 if (error->code != GOT_ERR_NOT_REF)
2324 goto done;
2325 error = create_ref(refname, id, verbosity,
2326 repo);
2327 if (error)
2328 goto done;
2329 } else {
2330 error = update_ref(ref, id, replace_tags,
2331 verbosity, repo);
2332 unlock_err = got_ref_unlock(ref);
2333 if (unlock_err && error == NULL)
2334 error = unlock_err;
2335 got_ref_close(ref);
2336 if (error)
2337 goto done;
2339 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2340 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2341 remote_name, refname + 11) == -1) {
2342 error = got_error_from_errno("asprintf");
2343 goto done;
2346 error = got_ref_open(&ref, repo, remote_refname, 1);
2347 if (error) {
2348 if (error->code != GOT_ERR_NOT_REF)
2349 goto done;
2350 error = create_ref(remote_refname, id,
2351 verbosity, repo);
2352 if (error)
2353 goto done;
2354 } else {
2355 error = update_ref(ref, id, replace_tags,
2356 verbosity, repo);
2357 unlock_err = got_ref_unlock(ref);
2358 if (unlock_err && error == NULL)
2359 error = unlock_err;
2360 got_ref_close(ref);
2361 if (error)
2362 goto done;
2365 /* Also create a local branch if none exists yet. */
2366 error = got_ref_open(&ref, repo, refname, 1);
2367 if (error) {
2368 if (error->code != GOT_ERR_NOT_REF)
2369 goto done;
2370 error = create_ref(refname, id, verbosity,
2371 repo);
2372 if (error)
2373 goto done;
2374 } else {
2375 unlock_err = got_ref_unlock(ref);
2376 if (unlock_err && error == NULL)
2377 error = unlock_err;
2378 got_ref_close(ref);
2382 if (delete_refs) {
2383 error = delete_missing_refs(&refs, &symrefs, remote,
2384 verbosity, repo);
2385 if (error)
2386 goto done;
2389 if (!remote->mirror_references) {
2390 /* Update remote HEAD reference if the server provided one. */
2391 TAILQ_FOREACH(pe, &symrefs, entry) {
2392 struct got_reference *target_ref;
2393 const char *refname = pe->path;
2394 const char *target = pe->data;
2395 char *remote_refname = NULL, *remote_target = NULL;
2397 if (strcmp(refname, GOT_REF_HEAD) != 0)
2398 continue;
2400 if (strncmp("refs/heads/", target, 11) != 0)
2401 continue;
2403 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2404 remote->name, refname) == -1) {
2405 error = got_error_from_errno("asprintf");
2406 goto done;
2408 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2409 remote->name, target + 11) == -1) {
2410 error = got_error_from_errno("asprintf");
2411 free(remote_refname);
2412 goto done;
2415 error = got_ref_open(&target_ref, repo, remote_target,
2416 0);
2417 if (error) {
2418 free(remote_refname);
2419 free(remote_target);
2420 if (error->code == GOT_ERR_NOT_REF) {
2421 error = NULL;
2422 continue;
2424 goto done;
2426 error = update_symref(remote_refname, target_ref,
2427 verbosity, repo);
2428 free(remote_refname);
2429 free(remote_target);
2430 got_ref_close(target_ref);
2431 if (error)
2432 goto done;
2435 done:
2436 if (fetchpid > 0) {
2437 if (kill(fetchpid, SIGTERM) == -1)
2438 error = got_error_from_errno("kill");
2439 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2440 error = got_error_from_errno("waitpid");
2442 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2443 error = got_error_from_errno("close");
2444 if (repo)
2445 got_repo_close(repo);
2446 if (worktree)
2447 got_worktree_close(worktree);
2448 TAILQ_FOREACH(pe, &refs, entry) {
2449 free((void *)pe->path);
2450 free(pe->data);
2452 got_pathlist_free(&refs);
2453 TAILQ_FOREACH(pe, &symrefs, entry) {
2454 free((void *)pe->path);
2455 free(pe->data);
2457 got_pathlist_free(&symrefs);
2458 got_pathlist_free(&wanted_branches);
2459 got_pathlist_free(&wanted_refs);
2460 free(id_str);
2461 free(cwd);
2462 free(repo_path);
2463 free(pack_hash);
2464 free(proto);
2465 free(host);
2466 free(port);
2467 free(server_path);
2468 free(repo_name);
2469 return error;
2473 __dead static void
2474 usage_checkout(void)
2476 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2477 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2478 exit(1);
2481 static void
2482 show_worktree_base_ref_warning(void)
2484 fprintf(stderr, "%s: warning: could not create a reference "
2485 "to the work tree's base commit; the commit could be "
2486 "garbage-collected by Git; making the repository "
2487 "writable and running 'got update' will prevent this\n",
2488 getprogname());
2491 struct got_checkout_progress_arg {
2492 const char *worktree_path;
2493 int had_base_commit_ref_error;
2496 static const struct got_error *
2497 checkout_progress(void *arg, unsigned char status, const char *path)
2499 struct got_checkout_progress_arg *a = arg;
2501 /* Base commit bump happens silently. */
2502 if (status == GOT_STATUS_BUMP_BASE)
2503 return NULL;
2505 if (status == GOT_STATUS_BASE_REF_ERR) {
2506 a->had_base_commit_ref_error = 1;
2507 return NULL;
2510 while (path[0] == '/')
2511 path++;
2513 printf("%c %s/%s\n", status, a->worktree_path, path);
2514 return NULL;
2517 static const struct got_error *
2518 check_cancelled(void *arg)
2520 if (sigint_received || sigpipe_received)
2521 return got_error(GOT_ERR_CANCELLED);
2522 return NULL;
2525 static const struct got_error *
2526 check_linear_ancestry(struct got_object_id *commit_id,
2527 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2528 struct got_repository *repo)
2530 const struct got_error *err = NULL;
2531 struct got_object_id *yca_id;
2533 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2534 commit_id, base_commit_id, repo, check_cancelled, NULL);
2535 if (err)
2536 return err;
2538 if (yca_id == NULL)
2539 return got_error(GOT_ERR_ANCESTRY);
2542 * Require a straight line of history between the target commit
2543 * and the work tree's base commit.
2545 * Non-linear situations such as this require a rebase:
2547 * (commit) D F (base_commit)
2548 * \ /
2549 * C E
2550 * \ /
2551 * B (yca)
2552 * |
2553 * A
2555 * 'got update' only handles linear cases:
2556 * Update forwards in time: A (base/yca) - B - C - D (commit)
2557 * Update backwards in time: D (base) - C - B - A (commit/yca)
2559 if (allow_forwards_in_time_only) {
2560 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2561 return got_error(GOT_ERR_ANCESTRY);
2562 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2563 got_object_id_cmp(base_commit_id, yca_id) != 0)
2564 return got_error(GOT_ERR_ANCESTRY);
2566 free(yca_id);
2567 return NULL;
2570 static const struct got_error *
2571 check_same_branch(struct got_object_id *commit_id,
2572 struct got_reference *head_ref, struct got_object_id *yca_id,
2573 struct got_repository *repo)
2575 const struct got_error *err = NULL;
2576 struct got_commit_graph *graph = NULL;
2577 struct got_object_id *head_commit_id = NULL;
2578 int is_same_branch = 0;
2580 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2581 if (err)
2582 goto done;
2584 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2585 is_same_branch = 1;
2586 goto done;
2588 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2589 is_same_branch = 1;
2590 goto done;
2593 err = got_commit_graph_open(&graph, "/", 1);
2594 if (err)
2595 goto done;
2597 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2598 check_cancelled, NULL);
2599 if (err)
2600 goto done;
2602 for (;;) {
2603 struct got_object_id *id;
2604 err = got_commit_graph_iter_next(&id, graph, repo,
2605 check_cancelled, NULL);
2606 if (err) {
2607 if (err->code == GOT_ERR_ITER_COMPLETED)
2608 err = NULL;
2609 break;
2612 if (id) {
2613 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2614 break;
2615 if (got_object_id_cmp(id, commit_id) == 0) {
2616 is_same_branch = 1;
2617 break;
2621 done:
2622 if (graph)
2623 got_commit_graph_close(graph);
2624 free(head_commit_id);
2625 if (!err && !is_same_branch)
2626 err = got_error(GOT_ERR_ANCESTRY);
2627 return err;
2630 static const struct got_error *
2631 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2633 static char msg[512];
2634 const char *branch_name;
2636 if (got_ref_is_symbolic(ref))
2637 branch_name = got_ref_get_symref_target(ref);
2638 else
2639 branch_name = got_ref_get_name(ref);
2641 if (strncmp("refs/heads/", branch_name, 11) == 0)
2642 branch_name += 11;
2644 snprintf(msg, sizeof(msg),
2645 "target commit is not contained in branch '%s'; "
2646 "the branch to use must be specified with -b; "
2647 "if necessary a new branch can be created for "
2648 "this commit with 'got branch -c %s BRANCH_NAME'",
2649 branch_name, commit_id_str);
2651 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2654 static const struct got_error *
2655 cmd_checkout(int argc, char *argv[])
2657 const struct got_error *error = NULL;
2658 struct got_repository *repo = NULL;
2659 struct got_reference *head_ref = NULL;
2660 struct got_worktree *worktree = NULL;
2661 char *repo_path = NULL;
2662 char *worktree_path = NULL;
2663 const char *path_prefix = "";
2664 const char *branch_name = GOT_REF_HEAD;
2665 char *commit_id_str = NULL;
2666 char *cwd = NULL;
2667 int ch, same_path_prefix, allow_nonempty = 0;
2668 struct got_pathlist_head paths;
2669 struct got_checkout_progress_arg cpa;
2671 TAILQ_INIT(&paths);
2673 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2674 switch (ch) {
2675 case 'b':
2676 branch_name = optarg;
2677 break;
2678 case 'c':
2679 commit_id_str = strdup(optarg);
2680 if (commit_id_str == NULL)
2681 return got_error_from_errno("strdup");
2682 break;
2683 case 'E':
2684 allow_nonempty = 1;
2685 break;
2686 case 'p':
2687 path_prefix = optarg;
2688 break;
2689 default:
2690 usage_checkout();
2691 /* NOTREACHED */
2695 argc -= optind;
2696 argv += optind;
2698 #ifndef PROFILE
2699 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2700 "unveil", NULL) == -1)
2701 err(1, "pledge");
2702 #endif
2703 if (argc == 1) {
2704 char *base, *dotgit;
2705 const char *path;
2706 repo_path = realpath(argv[0], NULL);
2707 if (repo_path == NULL)
2708 return got_error_from_errno2("realpath", argv[0]);
2709 cwd = getcwd(NULL, 0);
2710 if (cwd == NULL) {
2711 error = got_error_from_errno("getcwd");
2712 goto done;
2714 if (path_prefix[0])
2715 path = path_prefix;
2716 else
2717 path = repo_path;
2718 error = got_path_basename(&base, path);
2719 if (error)
2720 goto done;
2721 dotgit = strstr(base, ".git");
2722 if (dotgit)
2723 *dotgit = '\0';
2724 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2725 error = got_error_from_errno("asprintf");
2726 free(base);
2727 goto done;
2729 free(base);
2730 } else if (argc == 2) {
2731 repo_path = realpath(argv[0], NULL);
2732 if (repo_path == NULL) {
2733 error = got_error_from_errno2("realpath", argv[0]);
2734 goto done;
2736 worktree_path = realpath(argv[1], NULL);
2737 if (worktree_path == NULL) {
2738 if (errno != ENOENT) {
2739 error = got_error_from_errno2("realpath",
2740 argv[1]);
2741 goto done;
2743 worktree_path = strdup(argv[1]);
2744 if (worktree_path == NULL) {
2745 error = got_error_from_errno("strdup");
2746 goto done;
2749 } else
2750 usage_checkout();
2752 got_path_strip_trailing_slashes(repo_path);
2753 got_path_strip_trailing_slashes(worktree_path);
2755 error = got_repo_open(&repo, repo_path, NULL);
2756 if (error != NULL)
2757 goto done;
2759 /* Pre-create work tree path for unveil(2) */
2760 error = got_path_mkdir(worktree_path);
2761 if (error) {
2762 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2763 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2764 goto done;
2765 if (!allow_nonempty &&
2766 !got_path_dir_is_empty(worktree_path)) {
2767 error = got_error_path(worktree_path,
2768 GOT_ERR_DIR_NOT_EMPTY);
2769 goto done;
2773 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2774 if (error)
2775 goto done;
2777 error = got_ref_open(&head_ref, repo, branch_name, 0);
2778 if (error != NULL)
2779 goto done;
2781 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2782 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2783 goto done;
2785 error = got_worktree_open(&worktree, worktree_path);
2786 if (error != NULL)
2787 goto done;
2789 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2790 path_prefix);
2791 if (error != NULL)
2792 goto done;
2793 if (!same_path_prefix) {
2794 error = got_error(GOT_ERR_PATH_PREFIX);
2795 goto done;
2798 if (commit_id_str) {
2799 struct got_object_id *commit_id;
2800 struct got_reflist_head refs;
2801 TAILQ_INIT(&refs);
2802 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2803 NULL);
2804 if (error)
2805 goto done;
2806 error = got_repo_match_object_id(&commit_id, NULL,
2807 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2808 got_ref_list_free(&refs);
2809 if (error)
2810 goto done;
2811 error = check_linear_ancestry(commit_id,
2812 got_worktree_get_base_commit_id(worktree), 0, repo);
2813 if (error != NULL) {
2814 free(commit_id);
2815 if (error->code == GOT_ERR_ANCESTRY) {
2816 error = checkout_ancestry_error(
2817 head_ref, commit_id_str);
2819 goto done;
2821 error = check_same_branch(commit_id, head_ref, NULL, repo);
2822 if (error) {
2823 if (error->code == GOT_ERR_ANCESTRY) {
2824 error = checkout_ancestry_error(
2825 head_ref, commit_id_str);
2827 goto done;
2829 error = got_worktree_set_base_commit_id(worktree, repo,
2830 commit_id);
2831 free(commit_id);
2832 if (error)
2833 goto done;
2836 error = got_pathlist_append(&paths, "", NULL);
2837 if (error)
2838 goto done;
2839 cpa.worktree_path = worktree_path;
2840 cpa.had_base_commit_ref_error = 0;
2841 error = got_worktree_checkout_files(worktree, &paths, repo,
2842 checkout_progress, &cpa, check_cancelled, NULL);
2843 if (error != NULL)
2844 goto done;
2846 printf("Now shut up and hack\n");
2847 if (cpa.had_base_commit_ref_error)
2848 show_worktree_base_ref_warning();
2849 done:
2850 got_pathlist_free(&paths);
2851 free(commit_id_str);
2852 free(repo_path);
2853 free(worktree_path);
2854 free(cwd);
2855 return error;
2858 struct got_update_progress_arg {
2859 int did_something;
2860 int conflicts;
2861 int obstructed;
2862 int not_updated;
2865 void
2866 print_update_progress_stats(struct got_update_progress_arg *upa)
2868 if (!upa->did_something)
2869 return;
2871 if (upa->conflicts > 0)
2872 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2873 if (upa->obstructed > 0)
2874 printf("File paths obstructed by a non-regular file: %d\n",
2875 upa->obstructed);
2876 if (upa->not_updated > 0)
2877 printf("Files not updated because of existing merge "
2878 "conflicts: %d\n", upa->not_updated);
2881 __dead static void
2882 usage_update(void)
2884 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2885 getprogname());
2886 exit(1);
2889 static const struct got_error *
2890 update_progress(void *arg, unsigned char status, const char *path)
2892 struct got_update_progress_arg *upa = arg;
2894 if (status == GOT_STATUS_EXISTS ||
2895 status == GOT_STATUS_BASE_REF_ERR)
2896 return NULL;
2898 upa->did_something = 1;
2900 /* Base commit bump happens silently. */
2901 if (status == GOT_STATUS_BUMP_BASE)
2902 return NULL;
2904 if (status == GOT_STATUS_CONFLICT)
2905 upa->conflicts++;
2906 if (status == GOT_STATUS_OBSTRUCTED)
2907 upa->obstructed++;
2908 if (status == GOT_STATUS_CANNOT_UPDATE)
2909 upa->not_updated++;
2911 while (path[0] == '/')
2912 path++;
2913 printf("%c %s\n", status, path);
2914 return NULL;
2917 static const struct got_error *
2918 switch_head_ref(struct got_reference *head_ref,
2919 struct got_object_id *commit_id, struct got_worktree *worktree,
2920 struct got_repository *repo)
2922 const struct got_error *err = NULL;
2923 char *base_id_str;
2924 int ref_has_moved = 0;
2926 /* Trivial case: switching between two different references. */
2927 if (strcmp(got_ref_get_name(head_ref),
2928 got_worktree_get_head_ref_name(worktree)) != 0) {
2929 printf("Switching work tree from %s to %s\n",
2930 got_worktree_get_head_ref_name(worktree),
2931 got_ref_get_name(head_ref));
2932 return got_worktree_set_head_ref(worktree, head_ref);
2935 err = check_linear_ancestry(commit_id,
2936 got_worktree_get_base_commit_id(worktree), 0, repo);
2937 if (err) {
2938 if (err->code != GOT_ERR_ANCESTRY)
2939 return err;
2940 ref_has_moved = 1;
2942 if (!ref_has_moved)
2943 return NULL;
2945 /* Switching to a rebased branch with the same reference name. */
2946 err = got_object_id_str(&base_id_str,
2947 got_worktree_get_base_commit_id(worktree));
2948 if (err)
2949 return err;
2950 printf("Reference %s now points at a different branch\n",
2951 got_worktree_get_head_ref_name(worktree));
2952 printf("Switching work tree from %s to %s\n", base_id_str,
2953 got_worktree_get_head_ref_name(worktree));
2954 return NULL;
2957 static const struct got_error *
2958 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2960 const struct got_error *err;
2961 int in_progress;
2963 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2964 if (err)
2965 return err;
2966 if (in_progress)
2967 return got_error(GOT_ERR_REBASING);
2969 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2970 if (err)
2971 return err;
2972 if (in_progress)
2973 return got_error(GOT_ERR_HISTEDIT_BUSY);
2975 return NULL;
2978 static const struct got_error *
2979 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2980 char *argv[], struct got_worktree *worktree)
2982 const struct got_error *err = NULL;
2983 char *path;
2984 int i;
2986 if (argc == 0) {
2987 path = strdup("");
2988 if (path == NULL)
2989 return got_error_from_errno("strdup");
2990 return got_pathlist_append(paths, path, NULL);
2993 for (i = 0; i < argc; i++) {
2994 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2995 if (err)
2996 break;
2997 err = got_pathlist_append(paths, path, NULL);
2998 if (err) {
2999 free(path);
3000 break;
3004 return err;
3007 static const struct got_error *
3008 wrap_not_worktree_error(const struct got_error *orig_err,
3009 const char *cmdname, const char *path)
3011 const struct got_error *err;
3012 struct got_repository *repo;
3013 static char msg[512];
3015 err = got_repo_open(&repo, path, NULL);
3016 if (err)
3017 return orig_err;
3019 snprintf(msg, sizeof(msg),
3020 "'got %s' needs a work tree in addition to a git repository\n"
3021 "Work trees can be checked out from this Git repository with "
3022 "'got checkout'.\n"
3023 "The got(1) manual page contains more information.", cmdname);
3024 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3025 got_repo_close(repo);
3026 return err;
3029 static const struct got_error *
3030 cmd_update(int argc, char *argv[])
3032 const struct got_error *error = NULL;
3033 struct got_repository *repo = NULL;
3034 struct got_worktree *worktree = NULL;
3035 char *worktree_path = NULL;
3036 struct got_object_id *commit_id = NULL;
3037 char *commit_id_str = NULL;
3038 const char *branch_name = NULL;
3039 struct got_reference *head_ref = NULL;
3040 struct got_pathlist_head paths;
3041 struct got_pathlist_entry *pe;
3042 int ch;
3043 struct got_update_progress_arg upa;
3045 TAILQ_INIT(&paths);
3047 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
3048 switch (ch) {
3049 case 'b':
3050 branch_name = optarg;
3051 break;
3052 case 'c':
3053 commit_id_str = strdup(optarg);
3054 if (commit_id_str == NULL)
3055 return got_error_from_errno("strdup");
3056 break;
3057 default:
3058 usage_update();
3059 /* NOTREACHED */
3063 argc -= optind;
3064 argv += optind;
3066 #ifndef PROFILE
3067 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3068 "unveil", NULL) == -1)
3069 err(1, "pledge");
3070 #endif
3071 worktree_path = getcwd(NULL, 0);
3072 if (worktree_path == NULL) {
3073 error = got_error_from_errno("getcwd");
3074 goto done;
3076 error = got_worktree_open(&worktree, worktree_path);
3077 if (error) {
3078 if (error->code == GOT_ERR_NOT_WORKTREE)
3079 error = wrap_not_worktree_error(error, "update",
3080 worktree_path);
3081 goto done;
3084 error = check_rebase_or_histedit_in_progress(worktree);
3085 if (error)
3086 goto done;
3088 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3089 NULL);
3090 if (error != NULL)
3091 goto done;
3093 error = apply_unveil(got_repo_get_path(repo), 0,
3094 got_worktree_get_root_path(worktree));
3095 if (error)
3096 goto done;
3098 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3099 if (error)
3100 goto done;
3102 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3103 got_worktree_get_head_ref_name(worktree), 0);
3104 if (error != NULL)
3105 goto done;
3106 if (commit_id_str == NULL) {
3107 error = got_ref_resolve(&commit_id, repo, head_ref);
3108 if (error != NULL)
3109 goto done;
3110 error = got_object_id_str(&commit_id_str, commit_id);
3111 if (error != NULL)
3112 goto done;
3113 } else {
3114 struct got_reflist_head refs;
3115 TAILQ_INIT(&refs);
3116 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3117 NULL);
3118 if (error)
3119 goto done;
3120 error = got_repo_match_object_id(&commit_id, NULL,
3121 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3122 got_ref_list_free(&refs);
3123 free(commit_id_str);
3124 commit_id_str = NULL;
3125 if (error)
3126 goto done;
3127 error = got_object_id_str(&commit_id_str, commit_id);
3128 if (error)
3129 goto done;
3132 if (branch_name) {
3133 struct got_object_id *head_commit_id;
3134 TAILQ_FOREACH(pe, &paths, entry) {
3135 if (pe->path_len == 0)
3136 continue;
3137 error = got_error_msg(GOT_ERR_BAD_PATH,
3138 "switching between branches requires that "
3139 "the entire work tree gets updated");
3140 goto done;
3142 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3143 if (error)
3144 goto done;
3145 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3146 repo);
3147 free(head_commit_id);
3148 if (error != NULL)
3149 goto done;
3150 error = check_same_branch(commit_id, head_ref, NULL, repo);
3151 if (error)
3152 goto done;
3153 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3154 if (error)
3155 goto done;
3156 } else {
3157 error = check_linear_ancestry(commit_id,
3158 got_worktree_get_base_commit_id(worktree), 0, repo);
3159 if (error != NULL) {
3160 if (error->code == GOT_ERR_ANCESTRY)
3161 error = got_error(GOT_ERR_BRANCH_MOVED);
3162 goto done;
3164 error = check_same_branch(commit_id, head_ref, NULL, repo);
3165 if (error)
3166 goto done;
3169 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3170 commit_id) != 0) {
3171 error = got_worktree_set_base_commit_id(worktree, repo,
3172 commit_id);
3173 if (error)
3174 goto done;
3177 memset(&upa, 0, sizeof(upa));
3178 error = got_worktree_checkout_files(worktree, &paths, repo,
3179 update_progress, &upa, check_cancelled, NULL);
3180 if (error != NULL)
3181 goto done;
3183 if (upa.did_something)
3184 printf("Updated to commit %s\n", commit_id_str);
3185 else
3186 printf("Already up-to-date\n");
3187 print_update_progress_stats(&upa);
3188 done:
3189 free(worktree_path);
3190 TAILQ_FOREACH(pe, &paths, entry)
3191 free((char *)pe->path);
3192 got_pathlist_free(&paths);
3193 free(commit_id);
3194 free(commit_id_str);
3195 return error;
3198 static const struct got_error *
3199 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3200 const char *path, int diff_context, int ignore_whitespace,
3201 int force_text_diff, struct got_repository *repo)
3203 const struct got_error *err = NULL;
3204 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3206 if (blob_id1) {
3207 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3208 if (err)
3209 goto done;
3212 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3213 if (err)
3214 goto done;
3216 while (path[0] == '/')
3217 path++;
3218 err = got_diff_blob(NULL, NULL, blob1, blob2, path, path,
3219 diff_context, ignore_whitespace, force_text_diff, stdout);
3220 done:
3221 if (blob1)
3222 got_object_blob_close(blob1);
3223 got_object_blob_close(blob2);
3224 return err;
3227 static const struct got_error *
3228 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3229 const char *path, int diff_context, int ignore_whitespace,
3230 int force_text_diff, struct got_repository *repo)
3232 const struct got_error *err = NULL;
3233 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3234 struct got_diff_blob_output_unidiff_arg arg;
3236 if (tree_id1) {
3237 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3238 if (err)
3239 goto done;
3242 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3243 if (err)
3244 goto done;
3246 arg.diff_context = diff_context;
3247 arg.ignore_whitespace = ignore_whitespace;
3248 arg.force_text_diff = force_text_diff;
3249 arg.outfile = stdout;
3250 arg.line_offsets = NULL;
3251 arg.nlines = 0;
3252 while (path[0] == '/')
3253 path++;
3254 err = got_diff_tree(tree1, tree2, path, path, repo,
3255 got_diff_blob_output_unidiff, &arg, 1);
3256 done:
3257 if (tree1)
3258 got_object_tree_close(tree1);
3259 if (tree2)
3260 got_object_tree_close(tree2);
3261 return err;
3264 static const struct got_error *
3265 get_changed_paths(struct got_pathlist_head *paths,
3266 struct got_commit_object *commit, struct got_repository *repo)
3268 const struct got_error *err = NULL;
3269 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3270 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3271 struct got_object_qid *qid;
3273 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3274 if (qid != NULL) {
3275 struct got_commit_object *pcommit;
3276 err = got_object_open_as_commit(&pcommit, repo,
3277 qid->id);
3278 if (err)
3279 return err;
3281 tree_id1 = got_object_commit_get_tree_id(pcommit);
3282 got_object_commit_close(pcommit);
3286 if (tree_id1) {
3287 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3288 if (err)
3289 goto done;
3292 tree_id2 = got_object_commit_get_tree_id(commit);
3293 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3294 if (err)
3295 goto done;
3297 err = got_diff_tree(tree1, tree2, "", "", repo,
3298 got_diff_tree_collect_changed_paths, paths, 0);
3299 done:
3300 if (tree1)
3301 got_object_tree_close(tree1);
3302 if (tree2)
3303 got_object_tree_close(tree2);
3304 return err;
3307 static const struct got_error *
3308 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3309 const char *path, int diff_context, struct got_repository *repo)
3311 const struct got_error *err = NULL;
3312 struct got_commit_object *pcommit = NULL;
3313 char *id_str1 = NULL, *id_str2 = NULL;
3314 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3315 struct got_object_qid *qid;
3317 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3318 if (qid != NULL) {
3319 err = got_object_open_as_commit(&pcommit, repo,
3320 qid->id);
3321 if (err)
3322 return err;
3325 if (path && path[0] != '\0') {
3326 int obj_type;
3327 err = got_object_id_by_path(&obj_id2, repo, id, path);
3328 if (err)
3329 goto done;
3330 err = got_object_id_str(&id_str2, obj_id2);
3331 if (err) {
3332 free(obj_id2);
3333 goto done;
3335 if (pcommit) {
3336 err = got_object_id_by_path(&obj_id1, repo,
3337 qid->id, path);
3338 if (err) {
3339 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3340 free(obj_id2);
3341 goto done;
3343 } else {
3344 err = got_object_id_str(&id_str1, obj_id1);
3345 if (err) {
3346 free(obj_id2);
3347 goto done;
3351 err = got_object_get_type(&obj_type, repo, obj_id2);
3352 if (err) {
3353 free(obj_id2);
3354 goto done;
3356 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3357 switch (obj_type) {
3358 case GOT_OBJ_TYPE_BLOB:
3359 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3360 0, 0, repo);
3361 break;
3362 case GOT_OBJ_TYPE_TREE:
3363 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3364 0, 0, repo);
3365 break;
3366 default:
3367 err = got_error(GOT_ERR_OBJ_TYPE);
3368 break;
3370 free(obj_id1);
3371 free(obj_id2);
3372 } else {
3373 obj_id2 = got_object_commit_get_tree_id(commit);
3374 err = got_object_id_str(&id_str2, obj_id2);
3375 if (err)
3376 goto done;
3377 if (pcommit) {
3378 obj_id1 = got_object_commit_get_tree_id(pcommit);
3379 err = got_object_id_str(&id_str1, obj_id1);
3380 if (err)
3381 goto done;
3383 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null",
3384 id_str2);
3385 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3386 repo);
3388 done:
3389 free(id_str1);
3390 free(id_str2);
3391 if (pcommit)
3392 got_object_commit_close(pcommit);
3393 return err;
3396 static char *
3397 get_datestr(time_t *time, char *datebuf)
3399 struct tm mytm, *tm;
3400 char *p, *s;
3402 tm = gmtime_r(time, &mytm);
3403 if (tm == NULL)
3404 return NULL;
3405 s = asctime_r(tm, datebuf);
3406 if (s == NULL)
3407 return NULL;
3408 p = strchr(s, '\n');
3409 if (p)
3410 *p = '\0';
3411 return s;
3414 static const struct got_error *
3415 match_logmsg(int *have_match, struct got_object_id *id,
3416 struct got_commit_object *commit, regex_t *regex)
3418 const struct got_error *err = NULL;
3419 regmatch_t regmatch;
3420 char *id_str = NULL, *logmsg = NULL;
3422 *have_match = 0;
3424 err = got_object_id_str(&id_str, id);
3425 if (err)
3426 return err;
3428 err = got_object_commit_get_logmsg(&logmsg, commit);
3429 if (err)
3430 goto done;
3432 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3433 *have_match = 1;
3434 done:
3435 free(id_str);
3436 free(logmsg);
3437 return err;
3440 static void
3441 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3442 regex_t *regex)
3444 regmatch_t regmatch;
3445 struct got_pathlist_entry *pe;
3447 *have_match = 0;
3449 TAILQ_FOREACH(pe, changed_paths, entry) {
3450 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3451 *have_match = 1;
3452 break;
3457 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3459 static const struct got_error*
3460 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3461 struct got_object_id *id, struct got_repository *repo)
3463 static const struct got_error *err = NULL;
3464 struct got_reflist_entry *re;
3465 char *s;
3466 const char *name;
3468 *refs_str = NULL;
3470 TAILQ_FOREACH(re, refs, entry) {
3471 struct got_tag_object *tag = NULL;
3472 struct got_object_id *ref_id;
3473 int cmp;
3475 name = got_ref_get_name(re->ref);
3476 if (strcmp(name, GOT_REF_HEAD) == 0)
3477 continue;
3478 if (strncmp(name, "refs/", 5) == 0)
3479 name += 5;
3480 if (strncmp(name, "got/", 4) == 0)
3481 continue;
3482 if (strncmp(name, "heads/", 6) == 0)
3483 name += 6;
3484 if (strncmp(name, "remotes/", 8) == 0) {
3485 name += 8;
3486 s = strstr(name, "/" GOT_REF_HEAD);
3487 if (s != NULL && s[strlen(s)] == '\0')
3488 continue;
3490 err = got_ref_resolve(&ref_id, repo, re->ref);
3491 if (err)
3492 break;
3493 if (strncmp(name, "tags/", 5) == 0) {
3494 err = got_object_open_as_tag(&tag, repo, ref_id);
3495 if (err) {
3496 if (err->code != GOT_ERR_OBJ_TYPE) {
3497 free(ref_id);
3498 break;
3500 /* Ref points at something other than a tag. */
3501 err = NULL;
3502 tag = NULL;
3505 cmp = got_object_id_cmp(tag ?
3506 got_object_tag_get_object_id(tag) : ref_id, id);
3507 free(ref_id);
3508 if (tag)
3509 got_object_tag_close(tag);
3510 if (cmp != 0)
3511 continue;
3512 s = *refs_str;
3513 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3514 s ? ", " : "", name) == -1) {
3515 err = got_error_from_errno("asprintf");
3516 free(s);
3517 *refs_str = NULL;
3518 break;
3520 free(s);
3523 return err;
3526 static const struct got_error *
3527 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3528 struct got_repository *repo, const char *path,
3529 struct got_pathlist_head *changed_paths, int show_patch,
3530 int diff_context, struct got_reflist_object_id_map *refs_idmap)
3532 const struct got_error *err = NULL;
3533 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3534 char datebuf[26];
3535 time_t committer_time;
3536 const char *author, *committer;
3537 char *refs_str = NULL;
3538 struct got_reflist_head *refs;
3540 err = got_object_id_str(&id_str, id);
3541 if (err)
3542 return err;
3544 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3545 if (refs) {
3546 err = build_refs_str(&refs_str, refs, id, repo);
3547 if (err)
3548 goto done;
3551 printf(GOT_COMMIT_SEP_STR);
3552 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3553 refs_str ? refs_str : "", refs_str ? ")" : "");
3554 free(id_str);
3555 id_str = NULL;
3556 free(refs_str);
3557 refs_str = NULL;
3558 printf("from: %s\n", got_object_commit_get_author(commit));
3559 committer_time = got_object_commit_get_committer_time(commit);
3560 datestr = get_datestr(&committer_time, datebuf);
3561 if (datestr)
3562 printf("date: %s UTC\n", datestr);
3563 author = got_object_commit_get_author(commit);
3564 committer = got_object_commit_get_committer(commit);
3565 if (strcmp(author, committer) != 0)
3566 printf("via: %s\n", committer);
3567 if (got_object_commit_get_nparents(commit) > 1) {
3568 const struct got_object_id_queue *parent_ids;
3569 struct got_object_qid *qid;
3570 int n = 1;
3571 parent_ids = got_object_commit_get_parent_ids(commit);
3572 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3573 err = got_object_id_str(&id_str, qid->id);
3574 if (err)
3575 goto done;
3576 printf("parent %d: %s\n", n++, id_str);
3577 free(id_str);
3578 id_str = NULL;
3582 err = got_object_commit_get_logmsg(&logmsg0, commit);
3583 if (err)
3584 goto done;
3586 logmsg = logmsg0;
3587 do {
3588 line = strsep(&logmsg, "\n");
3589 if (line)
3590 printf(" %s\n", line);
3591 } while (line);
3592 free(logmsg0);
3594 if (changed_paths) {
3595 struct got_pathlist_entry *pe;
3596 TAILQ_FOREACH(pe, changed_paths, entry) {
3597 struct got_diff_changed_path *cp = pe->data;
3598 printf(" %c %s\n", cp->status, pe->path);
3600 printf("\n");
3602 if (show_patch) {
3603 err = print_patch(commit, id, path, diff_context, repo);
3604 if (err == 0)
3605 printf("\n");
3608 if (fflush(stdout) != 0 && err == NULL)
3609 err = got_error_from_errno("fflush");
3610 done:
3611 free(id_str);
3612 free(refs_str);
3613 return err;
3616 static const struct got_error *
3617 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3618 struct got_repository *repo, const char *path, int show_changed_paths,
3619 int show_patch, const char *search_pattern, int diff_context, int limit,
3620 int log_branches, int reverse_display_order,
3621 struct got_reflist_object_id_map *refs_idmap)
3623 const struct got_error *err;
3624 struct got_commit_graph *graph;
3625 regex_t regex;
3626 int have_match;
3627 struct got_object_id_queue reversed_commits;
3628 struct got_object_qid *qid;
3629 struct got_commit_object *commit;
3630 struct got_pathlist_head changed_paths;
3631 struct got_pathlist_entry *pe;
3633 SIMPLEQ_INIT(&reversed_commits);
3634 TAILQ_INIT(&changed_paths);
3636 if (search_pattern && regcomp(&regex, search_pattern,
3637 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3638 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3640 err = got_commit_graph_open(&graph, path, !log_branches);
3641 if (err)
3642 return err;
3643 err = got_commit_graph_iter_start(graph, root_id, repo,
3644 check_cancelled, NULL);
3645 if (err)
3646 goto done;
3647 for (;;) {
3648 struct got_object_id *id;
3650 if (sigint_received || sigpipe_received)
3651 break;
3653 err = got_commit_graph_iter_next(&id, graph, repo,
3654 check_cancelled, NULL);
3655 if (err) {
3656 if (err->code == GOT_ERR_ITER_COMPLETED)
3657 err = NULL;
3658 break;
3660 if (id == NULL)
3661 break;
3663 err = got_object_open_as_commit(&commit, repo, id);
3664 if (err)
3665 break;
3667 if (show_changed_paths && !reverse_display_order) {
3668 err = get_changed_paths(&changed_paths, commit, repo);
3669 if (err)
3670 break;
3673 if (search_pattern) {
3674 err = match_logmsg(&have_match, id, commit, &regex);
3675 if (err) {
3676 got_object_commit_close(commit);
3677 break;
3679 if (have_match == 0 && show_changed_paths)
3680 match_changed_paths(&have_match,
3681 &changed_paths, &regex);
3682 if (have_match == 0) {
3683 got_object_commit_close(commit);
3684 TAILQ_FOREACH(pe, &changed_paths, entry) {
3685 free((char *)pe->path);
3686 free(pe->data);
3688 got_pathlist_free(&changed_paths);
3689 continue;
3693 if (reverse_display_order) {
3694 err = got_object_qid_alloc(&qid, id);
3695 if (err)
3696 break;
3697 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3698 got_object_commit_close(commit);
3699 } else {
3700 err = print_commit(commit, id, repo, path,
3701 show_changed_paths ? &changed_paths : NULL,
3702 show_patch, diff_context, refs_idmap);
3703 got_object_commit_close(commit);
3704 if (err)
3705 break;
3707 if ((limit && --limit == 0) ||
3708 (end_id && got_object_id_cmp(id, end_id) == 0))
3709 break;
3711 TAILQ_FOREACH(pe, &changed_paths, entry) {
3712 free((char *)pe->path);
3713 free(pe->data);
3715 got_pathlist_free(&changed_paths);
3717 if (reverse_display_order) {
3718 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3719 err = got_object_open_as_commit(&commit, repo, qid->id);
3720 if (err)
3721 break;
3722 if (show_changed_paths) {
3723 err = get_changed_paths(&changed_paths,
3724 commit, repo);
3725 if (err)
3726 break;
3728 err = print_commit(commit, qid->id, repo, path,
3729 show_changed_paths ? &changed_paths : NULL,
3730 show_patch, diff_context, refs_idmap);
3731 got_object_commit_close(commit);
3732 if (err)
3733 break;
3734 TAILQ_FOREACH(pe, &changed_paths, entry) {
3735 free((char *)pe->path);
3736 free(pe->data);
3738 got_pathlist_free(&changed_paths);
3741 done:
3742 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3743 qid = SIMPLEQ_FIRST(&reversed_commits);
3744 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3745 got_object_qid_free(qid);
3747 TAILQ_FOREACH(pe, &changed_paths, entry) {
3748 free((char *)pe->path);
3749 free(pe->data);
3751 got_pathlist_free(&changed_paths);
3752 if (search_pattern)
3753 regfree(&regex);
3754 got_commit_graph_close(graph);
3755 return err;
3758 __dead static void
3759 usage_log(void)
3761 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3762 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3763 "[-R] [path]\n", getprogname());
3764 exit(1);
3767 static int
3768 get_default_log_limit(void)
3770 const char *got_default_log_limit;
3771 long long n;
3772 const char *errstr;
3774 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3775 if (got_default_log_limit == NULL)
3776 return 0;
3777 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3778 if (errstr != NULL)
3779 return 0;
3780 return n;
3783 static const struct got_error *
3784 cmd_log(int argc, char *argv[])
3786 const struct got_error *error;
3787 struct got_repository *repo = NULL;
3788 struct got_worktree *worktree = NULL;
3789 struct got_object_id *start_id = NULL, *end_id = NULL;
3790 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3791 const char *start_commit = NULL, *end_commit = NULL;
3792 const char *search_pattern = NULL;
3793 int diff_context = -1, ch;
3794 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3795 int reverse_display_order = 0;
3796 const char *errstr;
3797 struct got_reflist_head refs;
3798 struct got_reflist_object_id_map *refs_idmap = NULL;
3800 TAILQ_INIT(&refs);
3802 #ifndef PROFILE
3803 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3804 NULL)
3805 == -1)
3806 err(1, "pledge");
3807 #endif
3809 limit = get_default_log_limit();
3811 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3812 switch (ch) {
3813 case 'p':
3814 show_patch = 1;
3815 break;
3816 case 'P':
3817 show_changed_paths = 1;
3818 break;
3819 case 'c':
3820 start_commit = optarg;
3821 break;
3822 case 'C':
3823 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3824 &errstr);
3825 if (errstr != NULL)
3826 err(1, "-C option %s", errstr);
3827 break;
3828 case 'l':
3829 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3830 if (errstr != NULL)
3831 err(1, "-l option %s", errstr);
3832 break;
3833 case 'b':
3834 log_branches = 1;
3835 break;
3836 case 'r':
3837 repo_path = realpath(optarg, NULL);
3838 if (repo_path == NULL)
3839 return got_error_from_errno2("realpath",
3840 optarg);
3841 got_path_strip_trailing_slashes(repo_path);
3842 break;
3843 case 'R':
3844 reverse_display_order = 1;
3845 break;
3846 case 's':
3847 search_pattern = optarg;
3848 break;
3849 case 'x':
3850 end_commit = optarg;
3851 break;
3852 default:
3853 usage_log();
3854 /* NOTREACHED */
3858 argc -= optind;
3859 argv += optind;
3861 if (diff_context == -1)
3862 diff_context = 3;
3863 else if (!show_patch)
3864 errx(1, "-C requires -p");
3866 cwd = getcwd(NULL, 0);
3867 if (cwd == NULL) {
3868 error = got_error_from_errno("getcwd");
3869 goto done;
3872 if (repo_path == NULL) {
3873 error = got_worktree_open(&worktree, cwd);
3874 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3875 goto done;
3876 error = NULL;
3879 if (argc == 1) {
3880 if (worktree) {
3881 error = got_worktree_resolve_path(&path, worktree,
3882 argv[0]);
3883 if (error)
3884 goto done;
3885 } else {
3886 path = strdup(argv[0]);
3887 if (path == NULL) {
3888 error = got_error_from_errno("strdup");
3889 goto done;
3892 } else if (argc != 0)
3893 usage_log();
3895 if (repo_path == NULL) {
3896 repo_path = worktree ?
3897 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3899 if (repo_path == NULL) {
3900 error = got_error_from_errno("strdup");
3901 goto done;
3904 error = got_repo_open(&repo, repo_path, NULL);
3905 if (error != NULL)
3906 goto done;
3908 error = apply_unveil(got_repo_get_path(repo), 1,
3909 worktree ? got_worktree_get_root_path(worktree) : NULL);
3910 if (error)
3911 goto done;
3913 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3914 if (error)
3915 goto done;
3917 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
3918 if (error)
3919 goto done;
3921 if (start_commit == NULL) {
3922 struct got_reference *head_ref;
3923 struct got_commit_object *commit = NULL;
3924 error = got_ref_open(&head_ref, repo,
3925 worktree ? got_worktree_get_head_ref_name(worktree)
3926 : GOT_REF_HEAD, 0);
3927 if (error != NULL)
3928 goto done;
3929 error = got_ref_resolve(&start_id, repo, head_ref);
3930 got_ref_close(head_ref);
3931 if (error != NULL)
3932 goto done;
3933 error = got_object_open_as_commit(&commit, repo,
3934 start_id);
3935 if (error != NULL)
3936 goto done;
3937 got_object_commit_close(commit);
3938 } else {
3939 error = got_repo_match_object_id(&start_id, NULL,
3940 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3941 if (error != NULL)
3942 goto done;
3944 if (end_commit != NULL) {
3945 error = got_repo_match_object_id(&end_id, NULL,
3946 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3947 if (error != NULL)
3948 goto done;
3951 if (worktree) {
3953 * If a path was specified on the command line it was resolved
3954 * to a path in the work tree above. Prepend the work tree's
3955 * path prefix to obtain the corresponding in-repository path.
3957 if (path) {
3958 const char *prefix;
3959 prefix = got_worktree_get_path_prefix(worktree);
3960 if (asprintf(&in_repo_path, "%s%s%s", prefix,
3961 (path[0] != '\0') ? "/" : "", path) == -1) {
3962 error = got_error_from_errno("asprintf");
3963 goto done;
3966 } else
3967 error = got_repo_map_path(&in_repo_path, repo,
3968 path ? path : "");
3969 if (error != NULL)
3970 goto done;
3971 if (in_repo_path) {
3972 free(path);
3973 path = in_repo_path;
3976 error = print_commits(start_id, end_id, repo, path ? path : "",
3977 show_changed_paths, show_patch, search_pattern, diff_context,
3978 limit, log_branches, reverse_display_order, refs_idmap);
3979 done:
3980 free(path);
3981 free(repo_path);
3982 free(cwd);
3983 if (worktree)
3984 got_worktree_close(worktree);
3985 if (repo) {
3986 const struct got_error *repo_error;
3987 repo_error = got_repo_close(repo);
3988 if (error == NULL)
3989 error = repo_error;
3991 if (refs_idmap)
3992 got_reflist_object_id_map_free(refs_idmap);
3993 got_ref_list_free(&refs);
3994 return error;
3997 __dead static void
3998 usage_diff(void)
4000 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
4001 "[-s] [-w] [object1 object2 | path]\n", getprogname());
4002 exit(1);
4005 struct print_diff_arg {
4006 struct got_repository *repo;
4007 struct got_worktree *worktree;
4008 int diff_context;
4009 const char *id_str;
4010 int header_shown;
4011 int diff_staged;
4012 int ignore_whitespace;
4013 int force_text_diff;
4017 * Create a file which contains the target path of a symlink so we can feed
4018 * it as content to the diff engine.
4020 static const struct got_error *
4021 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4022 const char *abspath)
4024 const struct got_error *err = NULL;
4025 char target_path[PATH_MAX];
4026 ssize_t target_len, outlen;
4028 *fd = -1;
4030 if (dirfd != -1) {
4031 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4032 if (target_len == -1)
4033 return got_error_from_errno2("readlinkat", abspath);
4034 } else {
4035 target_len = readlink(abspath, target_path, PATH_MAX);
4036 if (target_len == -1)
4037 return got_error_from_errno2("readlink", abspath);
4040 *fd = got_opentempfd();
4041 if (*fd == -1)
4042 return got_error_from_errno("got_opentempfd");
4044 outlen = write(*fd, target_path, target_len);
4045 if (outlen == -1) {
4046 err = got_error_from_errno("got_opentempfd");
4047 goto done;
4050 if (lseek(*fd, 0, SEEK_SET) == -1) {
4051 err = got_error_from_errno2("lseek", abspath);
4052 goto done;
4054 done:
4055 if (err) {
4056 close(*fd);
4057 *fd = -1;
4059 return err;
4062 static const struct got_error *
4063 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4064 const char *path, struct got_object_id *blob_id,
4065 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4066 int dirfd, const char *de_name)
4068 struct print_diff_arg *a = arg;
4069 const struct got_error *err = NULL;
4070 struct got_blob_object *blob1 = NULL;
4071 int fd = -1;
4072 FILE *f2 = NULL;
4073 char *abspath = NULL, *label1 = NULL;
4074 struct stat sb;
4076 if (a->diff_staged) {
4077 if (staged_status != GOT_STATUS_MODIFY &&
4078 staged_status != GOT_STATUS_ADD &&
4079 staged_status != GOT_STATUS_DELETE)
4080 return NULL;
4081 } else {
4082 if (staged_status == GOT_STATUS_DELETE)
4083 return NULL;
4084 if (status == GOT_STATUS_NONEXISTENT)
4085 return got_error_set_errno(ENOENT, path);
4086 if (status != GOT_STATUS_MODIFY &&
4087 status != GOT_STATUS_ADD &&
4088 status != GOT_STATUS_DELETE &&
4089 status != GOT_STATUS_CONFLICT)
4090 return NULL;
4093 if (!a->header_shown) {
4094 printf("diff %s %s%s\n", a->id_str,
4095 got_worktree_get_root_path(a->worktree),
4096 a->diff_staged ? " (staged changes)" : "");
4097 a->header_shown = 1;
4100 if (a->diff_staged) {
4101 const char *label1 = NULL, *label2 = NULL;
4102 switch (staged_status) {
4103 case GOT_STATUS_MODIFY:
4104 label1 = path;
4105 label2 = path;
4106 break;
4107 case GOT_STATUS_ADD:
4108 label2 = path;
4109 break;
4110 case GOT_STATUS_DELETE:
4111 label1 = path;
4112 break;
4113 default:
4114 return got_error(GOT_ERR_FILE_STATUS);
4116 return got_diff_objects_as_blobs(NULL, NULL, blob_id,
4117 staged_blob_id, label1, label2, a->diff_context,
4118 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4121 if (staged_status == GOT_STATUS_ADD ||
4122 staged_status == GOT_STATUS_MODIFY) {
4123 char *id_str;
4124 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4125 8192);
4126 if (err)
4127 goto done;
4128 err = got_object_id_str(&id_str, staged_blob_id);
4129 if (err)
4130 goto done;
4131 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4132 err = got_error_from_errno("asprintf");
4133 free(id_str);
4134 goto done;
4136 free(id_str);
4137 } else if (status != GOT_STATUS_ADD) {
4138 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4139 if (err)
4140 goto done;
4143 if (status != GOT_STATUS_DELETE) {
4144 if (asprintf(&abspath, "%s/%s",
4145 got_worktree_get_root_path(a->worktree), path) == -1) {
4146 err = got_error_from_errno("asprintf");
4147 goto done;
4150 if (dirfd != -1) {
4151 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
4152 if (fd == -1) {
4153 if (errno != ELOOP) {
4154 err = got_error_from_errno2("openat",
4155 abspath);
4156 goto done;
4158 err = get_symlink_target_file(&fd, dirfd,
4159 de_name, abspath);
4160 if (err)
4161 goto done;
4163 } else {
4164 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
4165 if (fd == -1) {
4166 if (errno != ELOOP) {
4167 err = got_error_from_errno2("open",
4168 abspath);
4169 goto done;
4171 err = get_symlink_target_file(&fd, dirfd,
4172 de_name, abspath);
4173 if (err)
4174 goto done;
4177 if (fstat(fd, &sb) == -1) {
4178 err = got_error_from_errno2("fstat", abspath);
4179 goto done;
4181 f2 = fdopen(fd, "r");
4182 if (f2 == NULL) {
4183 err = got_error_from_errno2("fdopen", abspath);
4184 goto done;
4186 fd = -1;
4187 } else
4188 sb.st_size = 0;
4190 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4191 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4192 done:
4193 if (blob1)
4194 got_object_blob_close(blob1);
4195 if (f2 && fclose(f2) == EOF && err == NULL)
4196 err = got_error_from_errno("fclose");
4197 if (fd != -1 && close(fd) == -1 && err == NULL)
4198 err = got_error_from_errno("close");
4199 free(abspath);
4200 return err;
4203 static const struct got_error *
4204 cmd_diff(int argc, char *argv[])
4206 const struct got_error *error;
4207 struct got_repository *repo = NULL;
4208 struct got_worktree *worktree = NULL;
4209 char *cwd = NULL, *repo_path = NULL;
4210 struct got_object_id *id1 = NULL, *id2 = NULL;
4211 const char *id_str1 = NULL, *id_str2 = NULL;
4212 char *label1 = NULL, *label2 = NULL;
4213 int type1, type2;
4214 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
4215 int force_text_diff = 0;
4216 const char *errstr;
4217 char *path = NULL;
4218 struct got_reflist_head refs;
4220 TAILQ_INIT(&refs);
4222 #ifndef PROFILE
4223 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4224 NULL) == -1)
4225 err(1, "pledge");
4226 #endif
4228 while ((ch = getopt(argc, argv, "aC:r:sw")) != -1) {
4229 switch (ch) {
4230 case 'a':
4231 force_text_diff = 1;
4232 break;
4233 case 'C':
4234 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4235 &errstr);
4236 if (errstr != NULL)
4237 err(1, "-C option %s", errstr);
4238 break;
4239 case 'r':
4240 repo_path = realpath(optarg, NULL);
4241 if (repo_path == NULL)
4242 return got_error_from_errno2("realpath",
4243 optarg);
4244 got_path_strip_trailing_slashes(repo_path);
4245 break;
4246 case 's':
4247 diff_staged = 1;
4248 break;
4249 case 'w':
4250 ignore_whitespace = 1;
4251 break;
4252 default:
4253 usage_diff();
4254 /* NOTREACHED */
4258 argc -= optind;
4259 argv += optind;
4261 cwd = getcwd(NULL, 0);
4262 if (cwd == NULL) {
4263 error = got_error_from_errno("getcwd");
4264 goto done;
4266 if (argc <= 1) {
4267 if (repo_path)
4268 errx(1,
4269 "-r option can't be used when diffing a work tree");
4270 error = got_worktree_open(&worktree, cwd);
4271 if (error) {
4272 if (error->code == GOT_ERR_NOT_WORKTREE)
4273 error = wrap_not_worktree_error(error, "diff",
4274 cwd);
4275 goto done;
4277 repo_path = strdup(got_worktree_get_repo_path(worktree));
4278 if (repo_path == NULL) {
4279 error = got_error_from_errno("strdup");
4280 goto done;
4282 if (argc == 1) {
4283 error = got_worktree_resolve_path(&path, worktree,
4284 argv[0]);
4285 if (error)
4286 goto done;
4287 } else {
4288 path = strdup("");
4289 if (path == NULL) {
4290 error = got_error_from_errno("strdup");
4291 goto done;
4294 } else if (argc == 2) {
4295 if (diff_staged)
4296 errx(1, "-s option can't be used when diffing "
4297 "objects in repository");
4298 id_str1 = argv[0];
4299 id_str2 = argv[1];
4300 if (repo_path == NULL) {
4301 error = got_worktree_open(&worktree, cwd);
4302 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4303 goto done;
4304 if (worktree) {
4305 repo_path = strdup(
4306 got_worktree_get_repo_path(worktree));
4307 if (repo_path == NULL) {
4308 error = got_error_from_errno("strdup");
4309 goto done;
4311 } else {
4312 repo_path = strdup(cwd);
4313 if (repo_path == NULL) {
4314 error = got_error_from_errno("strdup");
4315 goto done;
4319 } else
4320 usage_diff();
4322 error = got_repo_open(&repo, repo_path, NULL);
4323 free(repo_path);
4324 if (error != NULL)
4325 goto done;
4327 error = apply_unveil(got_repo_get_path(repo), 1,
4328 worktree ? got_worktree_get_root_path(worktree) : NULL);
4329 if (error)
4330 goto done;
4332 if (argc <= 1) {
4333 struct print_diff_arg arg;
4334 struct got_pathlist_head paths;
4335 char *id_str;
4337 TAILQ_INIT(&paths);
4339 error = got_object_id_str(&id_str,
4340 got_worktree_get_base_commit_id(worktree));
4341 if (error)
4342 goto done;
4343 arg.repo = repo;
4344 arg.worktree = worktree;
4345 arg.diff_context = diff_context;
4346 arg.id_str = id_str;
4347 arg.header_shown = 0;
4348 arg.diff_staged = diff_staged;
4349 arg.ignore_whitespace = ignore_whitespace;
4350 arg.force_text_diff = force_text_diff;
4352 error = got_pathlist_append(&paths, path, NULL);
4353 if (error)
4354 goto done;
4356 error = got_worktree_status(worktree, &paths, repo, print_diff,
4357 &arg, check_cancelled, NULL);
4358 free(id_str);
4359 got_pathlist_free(&paths);
4360 goto done;
4363 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4364 if (error)
4365 return error;
4367 error = got_repo_match_object_id(&id1, &label1, id_str1,
4368 GOT_OBJ_TYPE_ANY, &refs, repo);
4369 if (error)
4370 goto done;
4372 error = got_repo_match_object_id(&id2, &label2, id_str2,
4373 GOT_OBJ_TYPE_ANY, &refs, repo);
4374 if (error)
4375 goto done;
4377 error = got_object_get_type(&type1, repo, id1);
4378 if (error)
4379 goto done;
4381 error = got_object_get_type(&type2, repo, id2);
4382 if (error)
4383 goto done;
4385 if (type1 != type2) {
4386 error = got_error(GOT_ERR_OBJ_TYPE);
4387 goto done;
4390 switch (type1) {
4391 case GOT_OBJ_TYPE_BLOB:
4392 error = got_diff_objects_as_blobs(NULL, NULL, id1, id2,
4393 NULL, NULL, diff_context, ignore_whitespace,
4394 force_text_diff, repo, stdout);
4395 break;
4396 case GOT_OBJ_TYPE_TREE:
4397 error = got_diff_objects_as_trees(NULL, NULL, id1, id2,
4398 "", "", diff_context, ignore_whitespace, force_text_diff,
4399 repo, stdout);
4400 break;
4401 case GOT_OBJ_TYPE_COMMIT:
4402 printf("diff %s %s\n", label1, label2);
4403 error = got_diff_objects_as_commits(NULL, NULL, id1, id2,
4404 diff_context, ignore_whitespace, force_text_diff, repo,
4405 stdout);
4406 break;
4407 default:
4408 error = got_error(GOT_ERR_OBJ_TYPE);
4410 done:
4411 free(label1);
4412 free(label2);
4413 free(id1);
4414 free(id2);
4415 free(path);
4416 if (worktree)
4417 got_worktree_close(worktree);
4418 if (repo) {
4419 const struct got_error *repo_error;
4420 repo_error = got_repo_close(repo);
4421 if (error == NULL)
4422 error = repo_error;
4424 got_ref_list_free(&refs);
4425 return error;
4428 __dead static void
4429 usage_blame(void)
4431 fprintf(stderr,
4432 "usage: %s blame [-c commit] [-r repository-path] path\n",
4433 getprogname());
4434 exit(1);
4437 struct blame_line {
4438 int annotated;
4439 char *id_str;
4440 char *committer;
4441 char datebuf[11]; /* YYYY-MM-DD + NUL */
4444 struct blame_cb_args {
4445 struct blame_line *lines;
4446 int nlines;
4447 int nlines_prec;
4448 int lineno_cur;
4449 off_t *line_offsets;
4450 FILE *f;
4451 struct got_repository *repo;
4454 static const struct got_error *
4455 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4457 const struct got_error *err = NULL;
4458 struct blame_cb_args *a = arg;
4459 struct blame_line *bline;
4460 char *line = NULL;
4461 size_t linesize = 0;
4462 struct got_commit_object *commit = NULL;
4463 off_t offset;
4464 struct tm tm;
4465 time_t committer_time;
4467 if (nlines != a->nlines ||
4468 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4469 return got_error(GOT_ERR_RANGE);
4471 if (sigint_received)
4472 return got_error(GOT_ERR_ITER_COMPLETED);
4474 if (lineno == -1)
4475 return NULL; /* no change in this commit */
4477 /* Annotate this line. */
4478 bline = &a->lines[lineno - 1];
4479 if (bline->annotated)
4480 return NULL;
4481 err = got_object_id_str(&bline->id_str, id);
4482 if (err)
4483 return err;
4485 err = got_object_open_as_commit(&commit, a->repo, id);
4486 if (err)
4487 goto done;
4489 bline->committer = strdup(got_object_commit_get_committer(commit));
4490 if (bline->committer == NULL) {
4491 err = got_error_from_errno("strdup");
4492 goto done;
4495 committer_time = got_object_commit_get_committer_time(commit);
4496 if (localtime_r(&committer_time, &tm) == NULL)
4497 return got_error_from_errno("localtime_r");
4498 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4499 &tm) >= sizeof(bline->datebuf)) {
4500 err = got_error(GOT_ERR_NO_SPACE);
4501 goto done;
4503 bline->annotated = 1;
4505 /* Print lines annotated so far. */
4506 bline = &a->lines[a->lineno_cur - 1];
4507 if (!bline->annotated)
4508 goto done;
4510 offset = a->line_offsets[a->lineno_cur - 1];
4511 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4512 err = got_error_from_errno("fseeko");
4513 goto done;
4516 while (bline->annotated) {
4517 char *smallerthan, *at, *nl, *committer;
4518 size_t len;
4520 if (getline(&line, &linesize, a->f) == -1) {
4521 if (ferror(a->f))
4522 err = got_error_from_errno("getline");
4523 break;
4526 committer = bline->committer;
4527 smallerthan = strchr(committer, '<');
4528 if (smallerthan && smallerthan[1] != '\0')
4529 committer = smallerthan + 1;
4530 at = strchr(committer, '@');
4531 if (at)
4532 *at = '\0';
4533 len = strlen(committer);
4534 if (len >= 9)
4535 committer[8] = '\0';
4537 nl = strchr(line, '\n');
4538 if (nl)
4539 *nl = '\0';
4540 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4541 bline->id_str, bline->datebuf, committer, line);
4543 a->lineno_cur++;
4544 bline = &a->lines[a->lineno_cur - 1];
4546 done:
4547 if (commit)
4548 got_object_commit_close(commit);
4549 free(line);
4550 return err;
4553 static const struct got_error *
4554 cmd_blame(int argc, char *argv[])
4556 const struct got_error *error;
4557 struct got_repository *repo = NULL;
4558 struct got_worktree *worktree = NULL;
4559 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4560 char *link_target = NULL;
4561 struct got_object_id *obj_id = NULL;
4562 struct got_object_id *commit_id = NULL;
4563 struct got_blob_object *blob = NULL;
4564 char *commit_id_str = NULL;
4565 struct blame_cb_args bca;
4566 int ch, obj_type, i;
4567 off_t filesize;
4569 memset(&bca, 0, sizeof(bca));
4571 #ifndef PROFILE
4572 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4573 NULL) == -1)
4574 err(1, "pledge");
4575 #endif
4577 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4578 switch (ch) {
4579 case 'c':
4580 commit_id_str = optarg;
4581 break;
4582 case 'r':
4583 repo_path = realpath(optarg, NULL);
4584 if (repo_path == NULL)
4585 return got_error_from_errno2("realpath",
4586 optarg);
4587 got_path_strip_trailing_slashes(repo_path);
4588 break;
4589 default:
4590 usage_blame();
4591 /* NOTREACHED */
4595 argc -= optind;
4596 argv += optind;
4598 if (argc == 1)
4599 path = argv[0];
4600 else
4601 usage_blame();
4603 cwd = getcwd(NULL, 0);
4604 if (cwd == NULL) {
4605 error = got_error_from_errno("getcwd");
4606 goto done;
4608 if (repo_path == NULL) {
4609 error = got_worktree_open(&worktree, cwd);
4610 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4611 goto done;
4612 else
4613 error = NULL;
4614 if (worktree) {
4615 repo_path =
4616 strdup(got_worktree_get_repo_path(worktree));
4617 if (repo_path == NULL) {
4618 error = got_error_from_errno("strdup");
4619 if (error)
4620 goto done;
4622 } else {
4623 repo_path = strdup(cwd);
4624 if (repo_path == NULL) {
4625 error = got_error_from_errno("strdup");
4626 goto done;
4631 error = got_repo_open(&repo, repo_path, NULL);
4632 if (error != NULL)
4633 goto done;
4635 if (worktree) {
4636 const char *prefix = got_worktree_get_path_prefix(worktree);
4637 char *p;
4639 error = got_worktree_resolve_path(&p, worktree, path);
4640 if (error)
4641 goto done;
4642 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4643 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4644 p) == -1) {
4645 error = got_error_from_errno("asprintf");
4646 free(p);
4647 goto done;
4649 free(p);
4650 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4651 } else {
4652 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4653 if (error)
4654 goto done;
4655 error = got_repo_map_path(&in_repo_path, repo, path);
4657 if (error)
4658 goto done;
4660 if (commit_id_str == NULL) {
4661 struct got_reference *head_ref;
4662 error = got_ref_open(&head_ref, repo, worktree ?
4663 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4664 if (error != NULL)
4665 goto done;
4666 error = got_ref_resolve(&commit_id, repo, head_ref);
4667 got_ref_close(head_ref);
4668 if (error != NULL)
4669 goto done;
4670 } else {
4671 struct got_reflist_head refs;
4672 TAILQ_INIT(&refs);
4673 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4674 NULL);
4675 if (error)
4676 goto done;
4677 error = got_repo_match_object_id(&commit_id, NULL,
4678 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4679 got_ref_list_free(&refs);
4680 if (error)
4681 goto done;
4684 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4685 commit_id, repo);
4686 if (error)
4687 goto done;
4689 error = got_object_id_by_path(&obj_id, repo, commit_id,
4690 link_target ? link_target : in_repo_path);
4691 if (error)
4692 goto done;
4694 error = got_object_get_type(&obj_type, repo, obj_id);
4695 if (error)
4696 goto done;
4698 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4699 error = got_error_path(link_target ? link_target : in_repo_path,
4700 GOT_ERR_OBJ_TYPE);
4701 goto done;
4704 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4705 if (error)
4706 goto done;
4707 bca.f = got_opentemp();
4708 if (bca.f == NULL) {
4709 error = got_error_from_errno("got_opentemp");
4710 goto done;
4712 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4713 &bca.line_offsets, bca.f, blob);
4714 if (error || bca.nlines == 0)
4715 goto done;
4717 /* Don't include \n at EOF in the blame line count. */
4718 if (bca.line_offsets[bca.nlines - 1] == filesize)
4719 bca.nlines--;
4721 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4722 if (bca.lines == NULL) {
4723 error = got_error_from_errno("calloc");
4724 goto done;
4726 bca.lineno_cur = 1;
4727 bca.nlines_prec = 0;
4728 i = bca.nlines;
4729 while (i > 0) {
4730 i /= 10;
4731 bca.nlines_prec++;
4733 bca.repo = repo;
4735 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4736 repo, blame_cb, &bca, check_cancelled, NULL);
4737 done:
4738 free(in_repo_path);
4739 free(link_target);
4740 free(repo_path);
4741 free(cwd);
4742 free(commit_id);
4743 free(obj_id);
4744 if (blob)
4745 got_object_blob_close(blob);
4746 if (worktree)
4747 got_worktree_close(worktree);
4748 if (repo) {
4749 const struct got_error *repo_error;
4750 repo_error = got_repo_close(repo);
4751 if (error == NULL)
4752 error = repo_error;
4754 if (bca.lines) {
4755 for (i = 0; i < bca.nlines; i++) {
4756 struct blame_line *bline = &bca.lines[i];
4757 free(bline->id_str);
4758 free(bline->committer);
4760 free(bca.lines);
4762 free(bca.line_offsets);
4763 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4764 error = got_error_from_errno("fclose");
4765 return error;
4768 __dead static void
4769 usage_tree(void)
4771 fprintf(stderr,
4772 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4773 getprogname());
4774 exit(1);
4777 static const struct got_error *
4778 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4779 const char *root_path, struct got_repository *repo)
4781 const struct got_error *err = NULL;
4782 int is_root_path = (strcmp(path, root_path) == 0);
4783 const char *modestr = "";
4784 mode_t mode = got_tree_entry_get_mode(te);
4785 char *link_target = NULL;
4787 path += strlen(root_path);
4788 while (path[0] == '/')
4789 path++;
4791 if (got_object_tree_entry_is_submodule(te))
4792 modestr = "$";
4793 else if (S_ISLNK(mode)) {
4794 int i;
4796 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4797 if (err)
4798 return err;
4799 for (i = 0; i < strlen(link_target); i++) {
4800 if (!isprint((unsigned char)link_target[i]))
4801 link_target[i] = '?';
4804 modestr = "@";
4806 else if (S_ISDIR(mode))
4807 modestr = "/";
4808 else if (mode & S_IXUSR)
4809 modestr = "*";
4811 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4812 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4813 link_target ? " -> ": "", link_target ? link_target : "");
4815 free(link_target);
4816 return NULL;
4819 static const struct got_error *
4820 print_tree(const char *path, struct got_object_id *commit_id,
4821 int show_ids, int recurse, const char *root_path,
4822 struct got_repository *repo)
4824 const struct got_error *err = NULL;
4825 struct got_object_id *tree_id = NULL;
4826 struct got_tree_object *tree = NULL;
4827 int nentries, i;
4829 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4830 if (err)
4831 goto done;
4833 err = got_object_open_as_tree(&tree, repo, tree_id);
4834 if (err)
4835 goto done;
4836 nentries = got_object_tree_get_nentries(tree);
4837 for (i = 0; i < nentries; i++) {
4838 struct got_tree_entry *te;
4839 char *id = NULL;
4841 if (sigint_received || sigpipe_received)
4842 break;
4844 te = got_object_tree_get_entry(tree, i);
4845 if (show_ids) {
4846 char *id_str;
4847 err = got_object_id_str(&id_str,
4848 got_tree_entry_get_id(te));
4849 if (err)
4850 goto done;
4851 if (asprintf(&id, "%s ", id_str) == -1) {
4852 err = got_error_from_errno("asprintf");
4853 free(id_str);
4854 goto done;
4856 free(id_str);
4858 err = print_entry(te, id, path, root_path, repo);
4859 free(id);
4860 if (err)
4861 goto done;
4863 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4864 char *child_path;
4865 if (asprintf(&child_path, "%s%s%s", path,
4866 path[0] == '/' && path[1] == '\0' ? "" : "/",
4867 got_tree_entry_get_name(te)) == -1) {
4868 err = got_error_from_errno("asprintf");
4869 goto done;
4871 err = print_tree(child_path, commit_id, show_ids, 1,
4872 root_path, repo);
4873 free(child_path);
4874 if (err)
4875 goto done;
4878 done:
4879 if (tree)
4880 got_object_tree_close(tree);
4881 free(tree_id);
4882 return err;
4885 static const struct got_error *
4886 cmd_tree(int argc, char *argv[])
4888 const struct got_error *error;
4889 struct got_repository *repo = NULL;
4890 struct got_worktree *worktree = NULL;
4891 const char *path, *refname = NULL;
4892 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4893 struct got_object_id *commit_id = NULL;
4894 char *commit_id_str = NULL;
4895 int show_ids = 0, recurse = 0;
4896 int ch;
4898 #ifndef PROFILE
4899 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4900 NULL) == -1)
4901 err(1, "pledge");
4902 #endif
4904 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4905 switch (ch) {
4906 case 'c':
4907 commit_id_str = optarg;
4908 break;
4909 case 'r':
4910 repo_path = realpath(optarg, NULL);
4911 if (repo_path == NULL)
4912 return got_error_from_errno2("realpath",
4913 optarg);
4914 got_path_strip_trailing_slashes(repo_path);
4915 break;
4916 case 'i':
4917 show_ids = 1;
4918 break;
4919 case 'R':
4920 recurse = 1;
4921 break;
4922 default:
4923 usage_tree();
4924 /* NOTREACHED */
4928 argc -= optind;
4929 argv += optind;
4931 if (argc == 1)
4932 path = argv[0];
4933 else if (argc > 1)
4934 usage_tree();
4935 else
4936 path = NULL;
4938 cwd = getcwd(NULL, 0);
4939 if (cwd == NULL) {
4940 error = got_error_from_errno("getcwd");
4941 goto done;
4943 if (repo_path == NULL) {
4944 error = got_worktree_open(&worktree, cwd);
4945 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4946 goto done;
4947 else
4948 error = NULL;
4949 if (worktree) {
4950 repo_path =
4951 strdup(got_worktree_get_repo_path(worktree));
4952 if (repo_path == NULL)
4953 error = got_error_from_errno("strdup");
4954 if (error)
4955 goto done;
4956 } else {
4957 repo_path = strdup(cwd);
4958 if (repo_path == NULL) {
4959 error = got_error_from_errno("strdup");
4960 goto done;
4965 error = got_repo_open(&repo, repo_path, NULL);
4966 if (error != NULL)
4967 goto done;
4969 if (worktree) {
4970 const char *prefix = got_worktree_get_path_prefix(worktree);
4971 char *p;
4973 if (path == NULL)
4974 path = "";
4975 error = got_worktree_resolve_path(&p, worktree, path);
4976 if (error)
4977 goto done;
4978 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4979 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4980 p) == -1) {
4981 error = got_error_from_errno("asprintf");
4982 free(p);
4983 goto done;
4985 free(p);
4986 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4987 if (error)
4988 goto done;
4989 } else {
4990 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4991 if (error)
4992 goto done;
4993 if (path == NULL)
4994 path = "/";
4995 error = got_repo_map_path(&in_repo_path, repo, path);
4996 if (error != NULL)
4997 goto done;
5000 if (commit_id_str == NULL) {
5001 struct got_reference *head_ref;
5002 if (worktree)
5003 refname = got_worktree_get_head_ref_name(worktree);
5004 else
5005 refname = GOT_REF_HEAD;
5006 error = got_ref_open(&head_ref, repo, refname, 0);
5007 if (error != NULL)
5008 goto done;
5009 error = got_ref_resolve(&commit_id, repo, head_ref);
5010 got_ref_close(head_ref);
5011 if (error != NULL)
5012 goto done;
5013 } else {
5014 struct got_reflist_head refs;
5015 TAILQ_INIT(&refs);
5016 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5017 NULL);
5018 if (error)
5019 goto done;
5020 error = got_repo_match_object_id(&commit_id, NULL,
5021 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5022 got_ref_list_free(&refs);
5023 if (error)
5024 goto done;
5027 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
5028 in_repo_path, repo);
5029 done:
5030 free(in_repo_path);
5031 free(repo_path);
5032 free(cwd);
5033 free(commit_id);
5034 if (worktree)
5035 got_worktree_close(worktree);
5036 if (repo) {
5037 const struct got_error *repo_error;
5038 repo_error = got_repo_close(repo);
5039 if (error == NULL)
5040 error = repo_error;
5042 return error;
5045 __dead static void
5046 usage_status(void)
5048 fprintf(stderr, "usage: %s status [-s status-codes ] [path ...]\n",
5049 getprogname());
5050 exit(1);
5053 static const struct got_error *
5054 print_status(void *arg, unsigned char status, unsigned char staged_status,
5055 const char *path, struct got_object_id *blob_id,
5056 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5057 int dirfd, const char *de_name)
5059 if (status == staged_status && (status == GOT_STATUS_DELETE))
5060 status = GOT_STATUS_NO_CHANGE;
5061 if (arg) {
5062 char *status_codes = arg;
5063 size_t ncodes = strlen(status_codes);
5064 int i;
5065 for (i = 0; i < ncodes ; i++) {
5066 if (status == status_codes[i] ||
5067 staged_status == status_codes[i])
5068 break;
5070 if (i == ncodes)
5071 return NULL;
5073 printf("%c%c %s\n", status, staged_status, path);
5074 return NULL;
5077 static const struct got_error *
5078 cmd_status(int argc, char *argv[])
5080 const struct got_error *error = NULL;
5081 struct got_repository *repo = NULL;
5082 struct got_worktree *worktree = NULL;
5083 char *cwd = NULL, *status_codes = NULL;;
5084 struct got_pathlist_head paths;
5085 struct got_pathlist_entry *pe;
5086 int ch, i;
5088 TAILQ_INIT(&paths);
5090 while ((ch = getopt(argc, argv, "s:")) != -1) {
5091 switch (ch) {
5092 case 's':
5093 for (i = 0; i < strlen(optarg); i++) {
5094 switch (optarg[i]) {
5095 case GOT_STATUS_MODIFY:
5096 case GOT_STATUS_ADD:
5097 case GOT_STATUS_DELETE:
5098 case GOT_STATUS_CONFLICT:
5099 case GOT_STATUS_MISSING:
5100 case GOT_STATUS_OBSTRUCTED:
5101 case GOT_STATUS_UNVERSIONED:
5102 case GOT_STATUS_MODE_CHANGE:
5103 case GOT_STATUS_NONEXISTENT:
5104 break;
5105 default:
5106 errx(1, "invalid status code '%c'",
5107 optarg[i]);
5110 status_codes = optarg;
5111 break;
5112 default:
5113 usage_status();
5114 /* NOTREACHED */
5118 argc -= optind;
5119 argv += optind;
5121 #ifndef PROFILE
5122 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5123 NULL) == -1)
5124 err(1, "pledge");
5125 #endif
5126 cwd = getcwd(NULL, 0);
5127 if (cwd == NULL) {
5128 error = got_error_from_errno("getcwd");
5129 goto done;
5132 error = got_worktree_open(&worktree, cwd);
5133 if (error) {
5134 if (error->code == GOT_ERR_NOT_WORKTREE)
5135 error = wrap_not_worktree_error(error, "status", cwd);
5136 goto done;
5139 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5140 NULL);
5141 if (error != NULL)
5142 goto done;
5144 error = apply_unveil(got_repo_get_path(repo), 1,
5145 got_worktree_get_root_path(worktree));
5146 if (error)
5147 goto done;
5149 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5150 if (error)
5151 goto done;
5153 error = got_worktree_status(worktree, &paths, repo, print_status,
5154 status_codes, check_cancelled, NULL);
5155 done:
5156 TAILQ_FOREACH(pe, &paths, entry)
5157 free((char *)pe->path);
5158 got_pathlist_free(&paths);
5159 free(cwd);
5160 return error;
5163 __dead static void
5164 usage_ref(void)
5166 fprintf(stderr,
5167 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
5168 "[-d] [name]\n",
5169 getprogname());
5170 exit(1);
5173 static const struct got_error *
5174 list_refs(struct got_repository *repo, const char *refname)
5176 static const struct got_error *err = NULL;
5177 struct got_reflist_head refs;
5178 struct got_reflist_entry *re;
5180 TAILQ_INIT(&refs);
5181 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
5182 if (err)
5183 return err;
5185 TAILQ_FOREACH(re, &refs, entry) {
5186 char *refstr;
5187 refstr = got_ref_to_str(re->ref);
5188 if (refstr == NULL)
5189 return got_error_from_errno("got_ref_to_str");
5190 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5191 free(refstr);
5194 got_ref_list_free(&refs);
5195 return NULL;
5198 static const struct got_error *
5199 delete_ref(struct got_repository *repo, const char *refname)
5201 const struct got_error *err = NULL;
5202 struct got_reference *ref;
5204 err = got_ref_open(&ref, repo, refname, 0);
5205 if (err)
5206 return err;
5208 err = got_ref_delete(ref, repo);
5209 got_ref_close(ref);
5210 return err;
5213 static const struct got_error *
5214 add_ref(struct got_repository *repo, const char *refname, const char *target)
5216 const struct got_error *err = NULL;
5217 struct got_object_id *id;
5218 struct got_reference *ref = NULL;
5221 * Don't let the user create a reference name with a leading '-'.
5222 * While technically a valid reference name, this case is usually
5223 * an unintended typo.
5225 if (refname[0] == '-')
5226 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5228 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5229 repo);
5230 if (err) {
5231 struct got_reference *target_ref;
5233 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5234 return err;
5235 err = got_ref_open(&target_ref, repo, target, 0);
5236 if (err)
5237 return err;
5238 err = got_ref_resolve(&id, repo, target_ref);
5239 got_ref_close(target_ref);
5240 if (err)
5241 return err;
5244 err = got_ref_alloc(&ref, refname, id);
5245 if (err)
5246 goto done;
5248 err = got_ref_write(ref, repo);
5249 done:
5250 if (ref)
5251 got_ref_close(ref);
5252 free(id);
5253 return err;
5256 static const struct got_error *
5257 add_symref(struct got_repository *repo, const char *refname, const char *target)
5259 const struct got_error *err = NULL;
5260 struct got_reference *ref = NULL;
5261 struct got_reference *target_ref = NULL;
5264 * Don't let the user create a reference name with a leading '-'.
5265 * While technically a valid reference name, this case is usually
5266 * an unintended typo.
5268 if (refname[0] == '-')
5269 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5271 err = got_ref_open(&target_ref, repo, target, 0);
5272 if (err)
5273 return err;
5275 err = got_ref_alloc_symref(&ref, refname, target_ref);
5276 if (err)
5277 goto done;
5279 err = got_ref_write(ref, repo);
5280 done:
5281 if (target_ref)
5282 got_ref_close(target_ref);
5283 if (ref)
5284 got_ref_close(ref);
5285 return err;
5288 static const struct got_error *
5289 cmd_ref(int argc, char *argv[])
5291 const struct got_error *error = NULL;
5292 struct got_repository *repo = NULL;
5293 struct got_worktree *worktree = NULL;
5294 char *cwd = NULL, *repo_path = NULL;
5295 int ch, do_list = 0, do_delete = 0;
5296 const char *obj_arg = NULL, *symref_target= NULL;
5297 char *refname = NULL;
5299 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5300 switch (ch) {
5301 case 'c':
5302 obj_arg = optarg;
5303 break;
5304 case 'd':
5305 do_delete = 1;
5306 break;
5307 case 'r':
5308 repo_path = realpath(optarg, NULL);
5309 if (repo_path == NULL)
5310 return got_error_from_errno2("realpath",
5311 optarg);
5312 got_path_strip_trailing_slashes(repo_path);
5313 break;
5314 case 'l':
5315 do_list = 1;
5316 break;
5317 case 's':
5318 symref_target = optarg;
5319 break;
5320 default:
5321 usage_ref();
5322 /* NOTREACHED */
5326 if (obj_arg && do_list)
5327 option_conflict('c', 'l');
5328 if (obj_arg && do_delete)
5329 option_conflict('c', 'd');
5330 if (obj_arg && symref_target)
5331 option_conflict('c', 's');
5332 if (symref_target && do_delete)
5333 option_conflict('s', 'd');
5334 if (symref_target && do_list)
5335 option_conflict('s', 'l');
5336 if (do_delete && do_list)
5337 option_conflict('d', 'l');
5339 argc -= optind;
5340 argv += optind;
5342 if (do_list) {
5343 if (argc != 0 && argc != 1)
5344 usage_ref();
5345 if (argc == 1) {
5346 refname = strdup(argv[0]);
5347 if (refname == NULL) {
5348 error = got_error_from_errno("strdup");
5349 goto done;
5352 } else {
5353 if (argc != 1)
5354 usage_ref();
5355 refname = strdup(argv[0]);
5356 if (refname == NULL) {
5357 error = got_error_from_errno("strdup");
5358 goto done;
5362 if (refname)
5363 got_path_strip_trailing_slashes(refname);
5365 #ifndef PROFILE
5366 if (do_list) {
5367 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5368 NULL) == -1)
5369 err(1, "pledge");
5370 } else {
5371 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5372 "sendfd unveil", NULL) == -1)
5373 err(1, "pledge");
5375 #endif
5376 cwd = getcwd(NULL, 0);
5377 if (cwd == NULL) {
5378 error = got_error_from_errno("getcwd");
5379 goto done;
5382 if (repo_path == NULL) {
5383 error = got_worktree_open(&worktree, cwd);
5384 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5385 goto done;
5386 else
5387 error = NULL;
5388 if (worktree) {
5389 repo_path =
5390 strdup(got_worktree_get_repo_path(worktree));
5391 if (repo_path == NULL)
5392 error = got_error_from_errno("strdup");
5393 if (error)
5394 goto done;
5395 } else {
5396 repo_path = strdup(cwd);
5397 if (repo_path == NULL) {
5398 error = got_error_from_errno("strdup");
5399 goto done;
5404 error = got_repo_open(&repo, repo_path, NULL);
5405 if (error != NULL)
5406 goto done;
5408 error = apply_unveil(got_repo_get_path(repo), do_list,
5409 worktree ? got_worktree_get_root_path(worktree) : NULL);
5410 if (error)
5411 goto done;
5413 if (do_list)
5414 error = list_refs(repo, refname);
5415 else if (do_delete)
5416 error = delete_ref(repo, refname);
5417 else if (symref_target)
5418 error = add_symref(repo, refname, symref_target);
5419 else {
5420 if (obj_arg == NULL)
5421 usage_ref();
5422 error = add_ref(repo, refname, obj_arg);
5424 done:
5425 free(refname);
5426 if (repo)
5427 got_repo_close(repo);
5428 if (worktree)
5429 got_worktree_close(worktree);
5430 free(cwd);
5431 free(repo_path);
5432 return error;
5435 __dead static void
5436 usage_branch(void)
5438 fprintf(stderr,
5439 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5440 "[name]\n", getprogname());
5441 exit(1);
5444 static const struct got_error *
5445 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5446 struct got_reference *ref)
5448 const struct got_error *err = NULL;
5449 const char *refname, *marker = " ";
5450 char *refstr;
5452 refname = got_ref_get_name(ref);
5453 if (worktree && strcmp(refname,
5454 got_worktree_get_head_ref_name(worktree)) == 0) {
5455 struct got_object_id *id = NULL;
5457 err = got_ref_resolve(&id, repo, ref);
5458 if (err)
5459 return err;
5460 if (got_object_id_cmp(id,
5461 got_worktree_get_base_commit_id(worktree)) == 0)
5462 marker = "* ";
5463 else
5464 marker = "~ ";
5465 free(id);
5468 if (strncmp(refname, "refs/heads/", 11) == 0)
5469 refname += 11;
5470 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5471 refname += 18;
5473 refstr = got_ref_to_str(ref);
5474 if (refstr == NULL)
5475 return got_error_from_errno("got_ref_to_str");
5477 printf("%s%s: %s\n", marker, refname, refstr);
5478 free(refstr);
5479 return NULL;
5482 static const struct got_error *
5483 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5485 const char *refname;
5487 if (worktree == NULL)
5488 return got_error(GOT_ERR_NOT_WORKTREE);
5490 refname = got_worktree_get_head_ref_name(worktree);
5492 if (strncmp(refname, "refs/heads/", 11) == 0)
5493 refname += 11;
5494 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5495 refname += 18;
5497 printf("%s\n", refname);
5499 return NULL;
5502 static const struct got_error *
5503 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5505 static const struct got_error *err = NULL;
5506 struct got_reflist_head refs;
5507 struct got_reflist_entry *re;
5508 struct got_reference *temp_ref = NULL;
5509 int rebase_in_progress, histedit_in_progress;
5511 TAILQ_INIT(&refs);
5513 if (worktree) {
5514 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5515 worktree);
5516 if (err)
5517 return err;
5519 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5520 worktree);
5521 if (err)
5522 return err;
5524 if (rebase_in_progress || histedit_in_progress) {
5525 err = got_ref_open(&temp_ref, repo,
5526 got_worktree_get_head_ref_name(worktree), 0);
5527 if (err)
5528 return err;
5529 list_branch(repo, worktree, temp_ref);
5530 got_ref_close(temp_ref);
5534 err = got_ref_list(&refs, repo, "refs/heads",
5535 got_ref_cmp_by_name, NULL);
5536 if (err)
5537 return err;
5539 TAILQ_FOREACH(re, &refs, entry)
5540 list_branch(repo, worktree, re->ref);
5542 got_ref_list_free(&refs);
5543 return NULL;
5546 static const struct got_error *
5547 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5548 const char *branch_name)
5550 const struct got_error *err = NULL;
5551 struct got_reference *ref = NULL;
5552 char *refname;
5554 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5555 return got_error_from_errno("asprintf");
5557 err = got_ref_open(&ref, repo, refname, 0);
5558 if (err)
5559 goto done;
5561 if (worktree &&
5562 strcmp(got_worktree_get_head_ref_name(worktree),
5563 got_ref_get_name(ref)) == 0) {
5564 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5565 "will not delete this work tree's current branch");
5566 goto done;
5569 err = got_ref_delete(ref, repo);
5570 done:
5571 if (ref)
5572 got_ref_close(ref);
5573 free(refname);
5574 return err;
5577 static const struct got_error *
5578 add_branch(struct got_repository *repo, const char *branch_name,
5579 struct got_object_id *base_commit_id)
5581 const struct got_error *err = NULL;
5582 struct got_reference *ref = NULL;
5583 char *base_refname = NULL, *refname = NULL;
5586 * Don't let the user create a branch name with a leading '-'.
5587 * While technically a valid reference name, this case is usually
5588 * an unintended typo.
5590 if (branch_name[0] == '-')
5591 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5593 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5594 err = got_error_from_errno("asprintf");
5595 goto done;
5598 err = got_ref_open(&ref, repo, refname, 0);
5599 if (err == NULL) {
5600 err = got_error(GOT_ERR_BRANCH_EXISTS);
5601 goto done;
5602 } else if (err->code != GOT_ERR_NOT_REF)
5603 goto done;
5605 err = got_ref_alloc(&ref, refname, base_commit_id);
5606 if (err)
5607 goto done;
5609 err = got_ref_write(ref, repo);
5610 done:
5611 if (ref)
5612 got_ref_close(ref);
5613 free(base_refname);
5614 free(refname);
5615 return err;
5618 static const struct got_error *
5619 cmd_branch(int argc, char *argv[])
5621 const struct got_error *error = NULL;
5622 struct got_repository *repo = NULL;
5623 struct got_worktree *worktree = NULL;
5624 char *cwd = NULL, *repo_path = NULL;
5625 int ch, do_list = 0, do_show = 0, do_update = 1;
5626 const char *delref = NULL, *commit_id_arg = NULL;
5627 struct got_reference *ref = NULL;
5628 struct got_pathlist_head paths;
5629 struct got_pathlist_entry *pe;
5630 struct got_object_id *commit_id = NULL;
5631 char *commit_id_str = NULL;
5633 TAILQ_INIT(&paths);
5635 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5636 switch (ch) {
5637 case 'c':
5638 commit_id_arg = optarg;
5639 break;
5640 case 'd':
5641 delref = optarg;
5642 break;
5643 case 'r':
5644 repo_path = realpath(optarg, NULL);
5645 if (repo_path == NULL)
5646 return got_error_from_errno2("realpath",
5647 optarg);
5648 got_path_strip_trailing_slashes(repo_path);
5649 break;
5650 case 'l':
5651 do_list = 1;
5652 break;
5653 case 'n':
5654 do_update = 0;
5655 break;
5656 default:
5657 usage_branch();
5658 /* NOTREACHED */
5662 if (do_list && delref)
5663 option_conflict('l', 'd');
5665 argc -= optind;
5666 argv += optind;
5668 if (!do_list && !delref && argc == 0)
5669 do_show = 1;
5671 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5672 errx(1, "-c option can only be used when creating a branch");
5674 if (do_list || delref) {
5675 if (argc > 0)
5676 usage_branch();
5677 } else if (!do_show && argc != 1)
5678 usage_branch();
5680 #ifndef PROFILE
5681 if (do_list || do_show) {
5682 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5683 NULL) == -1)
5684 err(1, "pledge");
5685 } else {
5686 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5687 "sendfd unveil", NULL) == -1)
5688 err(1, "pledge");
5690 #endif
5691 cwd = getcwd(NULL, 0);
5692 if (cwd == NULL) {
5693 error = got_error_from_errno("getcwd");
5694 goto done;
5697 if (repo_path == NULL) {
5698 error = got_worktree_open(&worktree, cwd);
5699 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5700 goto done;
5701 else
5702 error = NULL;
5703 if (worktree) {
5704 repo_path =
5705 strdup(got_worktree_get_repo_path(worktree));
5706 if (repo_path == NULL)
5707 error = got_error_from_errno("strdup");
5708 if (error)
5709 goto done;
5710 } else {
5711 repo_path = strdup(cwd);
5712 if (repo_path == NULL) {
5713 error = got_error_from_errno("strdup");
5714 goto done;
5719 error = got_repo_open(&repo, repo_path, NULL);
5720 if (error != NULL)
5721 goto done;
5723 error = apply_unveil(got_repo_get_path(repo), do_list,
5724 worktree ? got_worktree_get_root_path(worktree) : NULL);
5725 if (error)
5726 goto done;
5728 if (do_show)
5729 error = show_current_branch(repo, worktree);
5730 else if (do_list)
5731 error = list_branches(repo, worktree);
5732 else if (delref)
5733 error = delete_branch(repo, worktree, delref);
5734 else {
5735 struct got_reflist_head refs;
5736 TAILQ_INIT(&refs);
5737 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5738 NULL);
5739 if (error)
5740 goto done;
5741 if (commit_id_arg == NULL)
5742 commit_id_arg = worktree ?
5743 got_worktree_get_head_ref_name(worktree) :
5744 GOT_REF_HEAD;
5745 error = got_repo_match_object_id(&commit_id, NULL,
5746 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5747 got_ref_list_free(&refs);
5748 if (error)
5749 goto done;
5750 error = add_branch(repo, argv[0], commit_id);
5751 if (error)
5752 goto done;
5753 if (worktree && do_update) {
5754 struct got_update_progress_arg upa;
5755 char *branch_refname = NULL;
5757 error = got_object_id_str(&commit_id_str, commit_id);
5758 if (error)
5759 goto done;
5760 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5761 worktree);
5762 if (error)
5763 goto done;
5764 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5765 == -1) {
5766 error = got_error_from_errno("asprintf");
5767 goto done;
5769 error = got_ref_open(&ref, repo, branch_refname, 0);
5770 free(branch_refname);
5771 if (error)
5772 goto done;
5773 error = switch_head_ref(ref, commit_id, worktree,
5774 repo);
5775 if (error)
5776 goto done;
5777 error = got_worktree_set_base_commit_id(worktree, repo,
5778 commit_id);
5779 if (error)
5780 goto done;
5781 memset(&upa, 0, sizeof(upa));
5782 error = got_worktree_checkout_files(worktree, &paths,
5783 repo, update_progress, &upa, check_cancelled,
5784 NULL);
5785 if (error)
5786 goto done;
5787 if (upa.did_something)
5788 printf("Updated to commit %s\n", commit_id_str);
5789 print_update_progress_stats(&upa);
5792 done:
5793 if (ref)
5794 got_ref_close(ref);
5795 if (repo)
5796 got_repo_close(repo);
5797 if (worktree)
5798 got_worktree_close(worktree);
5799 free(cwd);
5800 free(repo_path);
5801 free(commit_id);
5802 free(commit_id_str);
5803 TAILQ_FOREACH(pe, &paths, entry)
5804 free((char *)pe->path);
5805 got_pathlist_free(&paths);
5806 return error;
5810 __dead static void
5811 usage_tag(void)
5813 fprintf(stderr,
5814 "usage: %s tag [-c commit] [-r repository] [-l] "
5815 "[-m message] name\n", getprogname());
5816 exit(1);
5819 #if 0
5820 static const struct got_error *
5821 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5823 const struct got_error *err = NULL;
5824 struct got_reflist_entry *re, *se, *new;
5825 struct got_object_id *re_id, *se_id;
5826 struct got_tag_object *re_tag, *se_tag;
5827 time_t re_time, se_time;
5829 SIMPLEQ_FOREACH(re, tags, entry) {
5830 se = SIMPLEQ_FIRST(sorted);
5831 if (se == NULL) {
5832 err = got_reflist_entry_dup(&new, re);
5833 if (err)
5834 return err;
5835 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5836 continue;
5837 } else {
5838 err = got_ref_resolve(&re_id, repo, re->ref);
5839 if (err)
5840 break;
5841 err = got_object_open_as_tag(&re_tag, repo, re_id);
5842 free(re_id);
5843 if (err)
5844 break;
5845 re_time = got_object_tag_get_tagger_time(re_tag);
5846 got_object_tag_close(re_tag);
5849 while (se) {
5850 err = got_ref_resolve(&se_id, repo, re->ref);
5851 if (err)
5852 break;
5853 err = got_object_open_as_tag(&se_tag, repo, se_id);
5854 free(se_id);
5855 if (err)
5856 break;
5857 se_time = got_object_tag_get_tagger_time(se_tag);
5858 got_object_tag_close(se_tag);
5860 if (se_time > re_time) {
5861 err = got_reflist_entry_dup(&new, re);
5862 if (err)
5863 return err;
5864 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5865 break;
5867 se = SIMPLEQ_NEXT(se, entry);
5868 continue;
5871 done:
5872 return err;
5874 #endif
5876 static const struct got_error *
5877 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5879 static const struct got_error *err = NULL;
5880 struct got_reflist_head refs;
5881 struct got_reflist_entry *re;
5883 TAILQ_INIT(&refs);
5885 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5886 if (err)
5887 return err;
5889 TAILQ_FOREACH(re, &refs, entry) {
5890 const char *refname;
5891 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5892 char datebuf[26];
5893 const char *tagger;
5894 time_t tagger_time;
5895 struct got_object_id *id;
5896 struct got_tag_object *tag;
5897 struct got_commit_object *commit = NULL;
5899 refname = got_ref_get_name(re->ref);
5900 if (strncmp(refname, "refs/tags/", 10) != 0)
5901 continue;
5902 refname += 10;
5903 refstr = got_ref_to_str(re->ref);
5904 if (refstr == NULL) {
5905 err = got_error_from_errno("got_ref_to_str");
5906 break;
5908 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5909 free(refstr);
5911 err = got_ref_resolve(&id, repo, re->ref);
5912 if (err)
5913 break;
5914 err = got_object_open_as_tag(&tag, repo, id);
5915 if (err) {
5916 if (err->code != GOT_ERR_OBJ_TYPE) {
5917 free(id);
5918 break;
5920 /* "lightweight" tag */
5921 err = got_object_open_as_commit(&commit, repo, id);
5922 if (err) {
5923 free(id);
5924 break;
5926 tagger = got_object_commit_get_committer(commit);
5927 tagger_time =
5928 got_object_commit_get_committer_time(commit);
5929 err = got_object_id_str(&id_str, id);
5930 free(id);
5931 if (err)
5932 break;
5933 } else {
5934 free(id);
5935 tagger = got_object_tag_get_tagger(tag);
5936 tagger_time = got_object_tag_get_tagger_time(tag);
5937 err = got_object_id_str(&id_str,
5938 got_object_tag_get_object_id(tag));
5939 if (err)
5940 break;
5942 printf("from: %s\n", tagger);
5943 datestr = get_datestr(&tagger_time, datebuf);
5944 if (datestr)
5945 printf("date: %s UTC\n", datestr);
5946 if (commit)
5947 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5948 else {
5949 switch (got_object_tag_get_object_type(tag)) {
5950 case GOT_OBJ_TYPE_BLOB:
5951 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5952 id_str);
5953 break;
5954 case GOT_OBJ_TYPE_TREE:
5955 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5956 id_str);
5957 break;
5958 case GOT_OBJ_TYPE_COMMIT:
5959 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5960 id_str);
5961 break;
5962 case GOT_OBJ_TYPE_TAG:
5963 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5964 id_str);
5965 break;
5966 default:
5967 break;
5970 free(id_str);
5971 if (commit) {
5972 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5973 if (err)
5974 break;
5975 got_object_commit_close(commit);
5976 } else {
5977 tagmsg0 = strdup(got_object_tag_get_message(tag));
5978 got_object_tag_close(tag);
5979 if (tagmsg0 == NULL) {
5980 err = got_error_from_errno("strdup");
5981 break;
5985 tagmsg = tagmsg0;
5986 do {
5987 line = strsep(&tagmsg, "\n");
5988 if (line)
5989 printf(" %s\n", line);
5990 } while (line);
5991 free(tagmsg0);
5994 got_ref_list_free(&refs);
5995 return NULL;
5998 static const struct got_error *
5999 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6000 const char *tag_name, const char *repo_path)
6002 const struct got_error *err = NULL;
6003 char *template = NULL, *initial_content = NULL;
6004 char *editor = NULL;
6005 int initial_content_len;
6006 int fd = -1;
6008 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6009 err = got_error_from_errno("asprintf");
6010 goto done;
6013 initial_content_len = asprintf(&initial_content,
6014 "\n# tagging commit %s as %s\n",
6015 commit_id_str, tag_name);
6016 if (initial_content_len == -1) {
6017 err = got_error_from_errno("asprintf");
6018 goto done;
6021 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6022 if (err)
6023 goto done;
6025 if (write(fd, initial_content, initial_content_len) == -1) {
6026 err = got_error_from_errno2("write", *tagmsg_path);
6027 goto done;
6030 err = get_editor(&editor);
6031 if (err)
6032 goto done;
6033 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6034 initial_content_len, 1);
6035 done:
6036 free(initial_content);
6037 free(template);
6038 free(editor);
6040 if (fd != -1 && close(fd) == -1 && err == NULL)
6041 err = got_error_from_errno2("close", *tagmsg_path);
6043 /* Editor is done; we can now apply unveil(2) */
6044 if (err == NULL)
6045 err = apply_unveil(repo_path, 0, NULL);
6046 if (err) {
6047 free(*tagmsg);
6048 *tagmsg = NULL;
6050 return err;
6053 static const struct got_error *
6054 add_tag(struct got_repository *repo, struct got_worktree *worktree,
6055 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6057 const struct got_error *err = NULL;
6058 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6059 char *label = NULL, *commit_id_str = NULL;
6060 struct got_reference *ref = NULL;
6061 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
6062 char *tagmsg_path = NULL, *tag_id_str = NULL;
6063 int preserve_tagmsg = 0;
6064 struct got_reflist_head refs;
6066 TAILQ_INIT(&refs);
6069 * Don't let the user create a tag name with a leading '-'.
6070 * While technically a valid reference name, this case is usually
6071 * an unintended typo.
6073 if (tag_name[0] == '-')
6074 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6076 err = get_author(&tagger, repo, worktree);
6077 if (err)
6078 return err;
6080 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6081 if (err)
6082 goto done;
6084 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6085 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6086 if (err)
6087 goto done;
6089 err = got_object_id_str(&commit_id_str, commit_id);
6090 if (err)
6091 goto done;
6093 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6094 refname = strdup(tag_name);
6095 if (refname == NULL) {
6096 err = got_error_from_errno("strdup");
6097 goto done;
6099 tag_name += 10;
6100 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6101 err = got_error_from_errno("asprintf");
6102 goto done;
6105 err = got_ref_open(&ref, repo, refname, 0);
6106 if (err == NULL) {
6107 err = got_error(GOT_ERR_TAG_EXISTS);
6108 goto done;
6109 } else if (err->code != GOT_ERR_NOT_REF)
6110 goto done;
6112 if (tagmsg_arg == NULL) {
6113 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6114 tag_name, got_repo_get_path(repo));
6115 if (err) {
6116 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6117 tagmsg_path != NULL)
6118 preserve_tagmsg = 1;
6119 goto done;
6123 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6124 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6125 if (err) {
6126 if (tagmsg_path)
6127 preserve_tagmsg = 1;
6128 goto done;
6131 err = got_ref_alloc(&ref, refname, tag_id);
6132 if (err) {
6133 if (tagmsg_path)
6134 preserve_tagmsg = 1;
6135 goto done;
6138 err = got_ref_write(ref, repo);
6139 if (err) {
6140 if (tagmsg_path)
6141 preserve_tagmsg = 1;
6142 goto done;
6145 err = got_object_id_str(&tag_id_str, tag_id);
6146 if (err) {
6147 if (tagmsg_path)
6148 preserve_tagmsg = 1;
6149 goto done;
6151 printf("Created tag %s\n", tag_id_str);
6152 done:
6153 if (preserve_tagmsg) {
6154 fprintf(stderr, "%s: tag message preserved in %s\n",
6155 getprogname(), tagmsg_path);
6156 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6157 err = got_error_from_errno2("unlink", tagmsg_path);
6158 free(tag_id_str);
6159 if (ref)
6160 got_ref_close(ref);
6161 free(commit_id);
6162 free(commit_id_str);
6163 free(refname);
6164 free(tagmsg);
6165 free(tagmsg_path);
6166 free(tagger);
6167 got_ref_list_free(&refs);
6168 return err;
6171 static const struct got_error *
6172 cmd_tag(int argc, char *argv[])
6174 const struct got_error *error = NULL;
6175 struct got_repository *repo = NULL;
6176 struct got_worktree *worktree = NULL;
6177 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6178 char *gitconfig_path = NULL;
6179 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6180 int ch, do_list = 0;
6182 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6183 switch (ch) {
6184 case 'c':
6185 commit_id_arg = optarg;
6186 break;
6187 case 'm':
6188 tagmsg = optarg;
6189 break;
6190 case 'r':
6191 repo_path = realpath(optarg, NULL);
6192 if (repo_path == NULL)
6193 return got_error_from_errno2("realpath",
6194 optarg);
6195 got_path_strip_trailing_slashes(repo_path);
6196 break;
6197 case 'l':
6198 do_list = 1;
6199 break;
6200 default:
6201 usage_tag();
6202 /* NOTREACHED */
6206 argc -= optind;
6207 argv += optind;
6209 if (do_list) {
6210 if (commit_id_arg != NULL)
6211 errx(1,
6212 "-c option can only be used when creating a tag");
6213 if (tagmsg)
6214 option_conflict('l', 'm');
6215 if (argc > 0)
6216 usage_tag();
6217 } else if (argc != 1)
6218 usage_tag();
6220 tag_name = argv[0];
6222 #ifndef PROFILE
6223 if (do_list) {
6224 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6225 NULL) == -1)
6226 err(1, "pledge");
6227 } else {
6228 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6229 "sendfd unveil", NULL) == -1)
6230 err(1, "pledge");
6232 #endif
6233 cwd = getcwd(NULL, 0);
6234 if (cwd == NULL) {
6235 error = got_error_from_errno("getcwd");
6236 goto done;
6239 if (repo_path == NULL) {
6240 error = got_worktree_open(&worktree, cwd);
6241 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6242 goto done;
6243 else
6244 error = NULL;
6245 if (worktree) {
6246 repo_path =
6247 strdup(got_worktree_get_repo_path(worktree));
6248 if (repo_path == NULL)
6249 error = got_error_from_errno("strdup");
6250 if (error)
6251 goto done;
6252 } else {
6253 repo_path = strdup(cwd);
6254 if (repo_path == NULL) {
6255 error = got_error_from_errno("strdup");
6256 goto done;
6261 if (do_list) {
6262 error = got_repo_open(&repo, repo_path, NULL);
6263 if (error != NULL)
6264 goto done;
6265 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6266 if (error)
6267 goto done;
6268 error = list_tags(repo, worktree);
6269 } else {
6270 error = get_gitconfig_path(&gitconfig_path);
6271 if (error)
6272 goto done;
6273 error = got_repo_open(&repo, repo_path, gitconfig_path);
6274 if (error != NULL)
6275 goto done;
6277 if (tagmsg) {
6278 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6279 if (error)
6280 goto done;
6283 if (commit_id_arg == NULL) {
6284 struct got_reference *head_ref;
6285 struct got_object_id *commit_id;
6286 error = got_ref_open(&head_ref, repo,
6287 worktree ? got_worktree_get_head_ref_name(worktree)
6288 : GOT_REF_HEAD, 0);
6289 if (error)
6290 goto done;
6291 error = got_ref_resolve(&commit_id, repo, head_ref);
6292 got_ref_close(head_ref);
6293 if (error)
6294 goto done;
6295 error = got_object_id_str(&commit_id_str, commit_id);
6296 free(commit_id);
6297 if (error)
6298 goto done;
6301 error = add_tag(repo, worktree, tag_name,
6302 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6304 done:
6305 if (repo)
6306 got_repo_close(repo);
6307 if (worktree)
6308 got_worktree_close(worktree);
6309 free(cwd);
6310 free(repo_path);
6311 free(gitconfig_path);
6312 free(commit_id_str);
6313 return error;
6316 __dead static void
6317 usage_add(void)
6319 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6320 getprogname());
6321 exit(1);
6324 static const struct got_error *
6325 add_progress(void *arg, unsigned char status, const char *path)
6327 while (path[0] == '/')
6328 path++;
6329 printf("%c %s\n", status, path);
6330 return NULL;
6333 static const struct got_error *
6334 cmd_add(int argc, char *argv[])
6336 const struct got_error *error = NULL;
6337 struct got_repository *repo = NULL;
6338 struct got_worktree *worktree = NULL;
6339 char *cwd = NULL;
6340 struct got_pathlist_head paths;
6341 struct got_pathlist_entry *pe;
6342 int ch, can_recurse = 0, no_ignores = 0;
6344 TAILQ_INIT(&paths);
6346 while ((ch = getopt(argc, argv, "IR")) != -1) {
6347 switch (ch) {
6348 case 'I':
6349 no_ignores = 1;
6350 break;
6351 case 'R':
6352 can_recurse = 1;
6353 break;
6354 default:
6355 usage_add();
6356 /* NOTREACHED */
6360 argc -= optind;
6361 argv += optind;
6363 #ifndef PROFILE
6364 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6365 NULL) == -1)
6366 err(1, "pledge");
6367 #endif
6368 if (argc < 1)
6369 usage_add();
6371 cwd = getcwd(NULL, 0);
6372 if (cwd == NULL) {
6373 error = got_error_from_errno("getcwd");
6374 goto done;
6377 error = got_worktree_open(&worktree, cwd);
6378 if (error) {
6379 if (error->code == GOT_ERR_NOT_WORKTREE)
6380 error = wrap_not_worktree_error(error, "add", cwd);
6381 goto done;
6384 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6385 NULL);
6386 if (error != NULL)
6387 goto done;
6389 error = apply_unveil(got_repo_get_path(repo), 1,
6390 got_worktree_get_root_path(worktree));
6391 if (error)
6392 goto done;
6394 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6395 if (error)
6396 goto done;
6398 if (!can_recurse && no_ignores) {
6399 error = got_error_msg(GOT_ERR_BAD_PATH,
6400 "disregarding ignores requires -R option");
6401 goto done;
6405 if (!can_recurse) {
6406 char *ondisk_path;
6407 struct stat sb;
6408 TAILQ_FOREACH(pe, &paths, entry) {
6409 if (asprintf(&ondisk_path, "%s/%s",
6410 got_worktree_get_root_path(worktree),
6411 pe->path) == -1) {
6412 error = got_error_from_errno("asprintf");
6413 goto done;
6415 if (lstat(ondisk_path, &sb) == -1) {
6416 if (errno == ENOENT) {
6417 free(ondisk_path);
6418 continue;
6420 error = got_error_from_errno2("lstat",
6421 ondisk_path);
6422 free(ondisk_path);
6423 goto done;
6425 free(ondisk_path);
6426 if (S_ISDIR(sb.st_mode)) {
6427 error = got_error_msg(GOT_ERR_BAD_PATH,
6428 "adding directories requires -R option");
6429 goto done;
6434 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6435 NULL, repo, no_ignores);
6436 done:
6437 if (repo)
6438 got_repo_close(repo);
6439 if (worktree)
6440 got_worktree_close(worktree);
6441 TAILQ_FOREACH(pe, &paths, entry)
6442 free((char *)pe->path);
6443 got_pathlist_free(&paths);
6444 free(cwd);
6445 return error;
6448 __dead static void
6449 usage_remove(void)
6451 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6452 "path ...\n", getprogname());
6453 exit(1);
6456 static const struct got_error *
6457 print_remove_status(void *arg, unsigned char status,
6458 unsigned char staged_status, const char *path)
6460 while (path[0] == '/')
6461 path++;
6462 if (status == GOT_STATUS_NONEXISTENT)
6463 return NULL;
6464 if (status == staged_status && (status == GOT_STATUS_DELETE))
6465 status = GOT_STATUS_NO_CHANGE;
6466 printf("%c%c %s\n", status, staged_status, path);
6467 return NULL;
6470 static const struct got_error *
6471 cmd_remove(int argc, char *argv[])
6473 const struct got_error *error = NULL;
6474 struct got_worktree *worktree = NULL;
6475 struct got_repository *repo = NULL;
6476 const char *status_codes = NULL;
6477 char *cwd = NULL;
6478 struct got_pathlist_head paths;
6479 struct got_pathlist_entry *pe;
6480 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6482 TAILQ_INIT(&paths);
6484 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6485 switch (ch) {
6486 case 'f':
6487 delete_local_mods = 1;
6488 break;
6489 case 'k':
6490 keep_on_disk = 1;
6491 break;
6492 case 'R':
6493 can_recurse = 1;
6494 break;
6495 case 's':
6496 for (i = 0; i < strlen(optarg); i++) {
6497 switch (optarg[i]) {
6498 case GOT_STATUS_MODIFY:
6499 delete_local_mods = 1;
6500 break;
6501 case GOT_STATUS_MISSING:
6502 break;
6503 default:
6504 errx(1, "invalid status code '%c'",
6505 optarg[i]);
6508 status_codes = optarg;
6509 break;
6510 default:
6511 usage_remove();
6512 /* NOTREACHED */
6516 argc -= optind;
6517 argv += optind;
6519 #ifndef PROFILE
6520 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6521 NULL) == -1)
6522 err(1, "pledge");
6523 #endif
6524 if (argc < 1)
6525 usage_remove();
6527 cwd = getcwd(NULL, 0);
6528 if (cwd == NULL) {
6529 error = got_error_from_errno("getcwd");
6530 goto done;
6532 error = got_worktree_open(&worktree, cwd);
6533 if (error) {
6534 if (error->code == GOT_ERR_NOT_WORKTREE)
6535 error = wrap_not_worktree_error(error, "remove", cwd);
6536 goto done;
6539 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6540 NULL);
6541 if (error)
6542 goto done;
6544 error = apply_unveil(got_repo_get_path(repo), 1,
6545 got_worktree_get_root_path(worktree));
6546 if (error)
6547 goto done;
6549 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6550 if (error)
6551 goto done;
6553 if (!can_recurse) {
6554 char *ondisk_path;
6555 struct stat sb;
6556 TAILQ_FOREACH(pe, &paths, entry) {
6557 if (asprintf(&ondisk_path, "%s/%s",
6558 got_worktree_get_root_path(worktree),
6559 pe->path) == -1) {
6560 error = got_error_from_errno("asprintf");
6561 goto done;
6563 if (lstat(ondisk_path, &sb) == -1) {
6564 if (errno == ENOENT) {
6565 free(ondisk_path);
6566 continue;
6568 error = got_error_from_errno2("lstat",
6569 ondisk_path);
6570 free(ondisk_path);
6571 goto done;
6573 free(ondisk_path);
6574 if (S_ISDIR(sb.st_mode)) {
6575 error = got_error_msg(GOT_ERR_BAD_PATH,
6576 "removing directories requires -R option");
6577 goto done;
6582 error = got_worktree_schedule_delete(worktree, &paths,
6583 delete_local_mods, status_codes, print_remove_status, NULL,
6584 repo, keep_on_disk);
6585 done:
6586 if (repo)
6587 got_repo_close(repo);
6588 if (worktree)
6589 got_worktree_close(worktree);
6590 TAILQ_FOREACH(pe, &paths, entry)
6591 free((char *)pe->path);
6592 got_pathlist_free(&paths);
6593 free(cwd);
6594 return error;
6597 __dead static void
6598 usage_revert(void)
6600 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6601 "path ...\n", getprogname());
6602 exit(1);
6605 static const struct got_error *
6606 revert_progress(void *arg, unsigned char status, const char *path)
6608 if (status == GOT_STATUS_UNVERSIONED)
6609 return NULL;
6611 while (path[0] == '/')
6612 path++;
6613 printf("%c %s\n", status, path);
6614 return NULL;
6617 struct choose_patch_arg {
6618 FILE *patch_script_file;
6619 const char *action;
6622 static const struct got_error *
6623 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6624 int nchanges, const char *action)
6626 char *line = NULL;
6627 size_t linesize = 0;
6628 ssize_t linelen;
6630 switch (status) {
6631 case GOT_STATUS_ADD:
6632 printf("A %s\n%s this addition? [y/n] ", path, action);
6633 break;
6634 case GOT_STATUS_DELETE:
6635 printf("D %s\n%s this deletion? [y/n] ", path, action);
6636 break;
6637 case GOT_STATUS_MODIFY:
6638 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6639 return got_error_from_errno("fseek");
6640 printf(GOT_COMMIT_SEP_STR);
6641 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6642 printf("%s", line);
6643 if (ferror(patch_file))
6644 return got_error_from_errno("getline");
6645 printf(GOT_COMMIT_SEP_STR);
6646 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6647 path, n, nchanges, action);
6648 break;
6649 default:
6650 return got_error_path(path, GOT_ERR_FILE_STATUS);
6653 return NULL;
6656 static const struct got_error *
6657 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6658 FILE *patch_file, int n, int nchanges)
6660 const struct got_error *err = NULL;
6661 char *line = NULL;
6662 size_t linesize = 0;
6663 ssize_t linelen;
6664 int resp = ' ';
6665 struct choose_patch_arg *a = arg;
6667 *choice = GOT_PATCH_CHOICE_NONE;
6669 if (a->patch_script_file) {
6670 char *nl;
6671 err = show_change(status, path, patch_file, n, nchanges,
6672 a->action);
6673 if (err)
6674 return err;
6675 linelen = getline(&line, &linesize, a->patch_script_file);
6676 if (linelen == -1) {
6677 if (ferror(a->patch_script_file))
6678 return got_error_from_errno("getline");
6679 return NULL;
6681 nl = strchr(line, '\n');
6682 if (nl)
6683 *nl = '\0';
6684 if (strcmp(line, "y") == 0) {
6685 *choice = GOT_PATCH_CHOICE_YES;
6686 printf("y\n");
6687 } else if (strcmp(line, "n") == 0) {
6688 *choice = GOT_PATCH_CHOICE_NO;
6689 printf("n\n");
6690 } else if (strcmp(line, "q") == 0 &&
6691 status == GOT_STATUS_MODIFY) {
6692 *choice = GOT_PATCH_CHOICE_QUIT;
6693 printf("q\n");
6694 } else
6695 printf("invalid response '%s'\n", line);
6696 free(line);
6697 return NULL;
6700 while (resp != 'y' && resp != 'n' && resp != 'q') {
6701 err = show_change(status, path, patch_file, n, nchanges,
6702 a->action);
6703 if (err)
6704 return err;
6705 resp = getchar();
6706 if (resp == '\n')
6707 resp = getchar();
6708 if (status == GOT_STATUS_MODIFY) {
6709 if (resp != 'y' && resp != 'n' && resp != 'q') {
6710 printf("invalid response '%c'\n", resp);
6711 resp = ' ';
6713 } else if (resp != 'y' && resp != 'n') {
6714 printf("invalid response '%c'\n", resp);
6715 resp = ' ';
6719 if (resp == 'y')
6720 *choice = GOT_PATCH_CHOICE_YES;
6721 else if (resp == 'n')
6722 *choice = GOT_PATCH_CHOICE_NO;
6723 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6724 *choice = GOT_PATCH_CHOICE_QUIT;
6726 return NULL;
6730 static const struct got_error *
6731 cmd_revert(int argc, char *argv[])
6733 const struct got_error *error = NULL;
6734 struct got_worktree *worktree = NULL;
6735 struct got_repository *repo = NULL;
6736 char *cwd = NULL, *path = NULL;
6737 struct got_pathlist_head paths;
6738 struct got_pathlist_entry *pe;
6739 int ch, can_recurse = 0, pflag = 0;
6740 FILE *patch_script_file = NULL;
6741 const char *patch_script_path = NULL;
6742 struct choose_patch_arg cpa;
6744 TAILQ_INIT(&paths);
6746 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6747 switch (ch) {
6748 case 'p':
6749 pflag = 1;
6750 break;
6751 case 'F':
6752 patch_script_path = optarg;
6753 break;
6754 case 'R':
6755 can_recurse = 1;
6756 break;
6757 default:
6758 usage_revert();
6759 /* NOTREACHED */
6763 argc -= optind;
6764 argv += optind;
6766 #ifndef PROFILE
6767 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6768 "unveil", NULL) == -1)
6769 err(1, "pledge");
6770 #endif
6771 if (argc < 1)
6772 usage_revert();
6773 if (patch_script_path && !pflag)
6774 errx(1, "-F option can only be used together with -p option");
6776 cwd = getcwd(NULL, 0);
6777 if (cwd == NULL) {
6778 error = got_error_from_errno("getcwd");
6779 goto done;
6781 error = got_worktree_open(&worktree, cwd);
6782 if (error) {
6783 if (error->code == GOT_ERR_NOT_WORKTREE)
6784 error = wrap_not_worktree_error(error, "revert", cwd);
6785 goto done;
6788 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6789 NULL);
6790 if (error != NULL)
6791 goto done;
6793 if (patch_script_path) {
6794 patch_script_file = fopen(patch_script_path, "r");
6795 if (patch_script_file == NULL) {
6796 error = got_error_from_errno2("fopen",
6797 patch_script_path);
6798 goto done;
6801 error = apply_unveil(got_repo_get_path(repo), 1,
6802 got_worktree_get_root_path(worktree));
6803 if (error)
6804 goto done;
6806 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6807 if (error)
6808 goto done;
6810 if (!can_recurse) {
6811 char *ondisk_path;
6812 struct stat sb;
6813 TAILQ_FOREACH(pe, &paths, entry) {
6814 if (asprintf(&ondisk_path, "%s/%s",
6815 got_worktree_get_root_path(worktree),
6816 pe->path) == -1) {
6817 error = got_error_from_errno("asprintf");
6818 goto done;
6820 if (lstat(ondisk_path, &sb) == -1) {
6821 if (errno == ENOENT) {
6822 free(ondisk_path);
6823 continue;
6825 error = got_error_from_errno2("lstat",
6826 ondisk_path);
6827 free(ondisk_path);
6828 goto done;
6830 free(ondisk_path);
6831 if (S_ISDIR(sb.st_mode)) {
6832 error = got_error_msg(GOT_ERR_BAD_PATH,
6833 "reverting directories requires -R option");
6834 goto done;
6839 cpa.patch_script_file = patch_script_file;
6840 cpa.action = "revert";
6841 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6842 pflag ? choose_patch : NULL, &cpa, repo);
6843 done:
6844 if (patch_script_file && fclose(patch_script_file) == EOF &&
6845 error == NULL)
6846 error = got_error_from_errno2("fclose", patch_script_path);
6847 if (repo)
6848 got_repo_close(repo);
6849 if (worktree)
6850 got_worktree_close(worktree);
6851 free(path);
6852 free(cwd);
6853 return error;
6856 __dead static void
6857 usage_commit(void)
6859 fprintf(stderr, "usage: %s commit [-m msg] [-S] [path ...]\n",
6860 getprogname());
6861 exit(1);
6864 struct collect_commit_logmsg_arg {
6865 const char *cmdline_log;
6866 const char *editor;
6867 const char *worktree_path;
6868 const char *branch_name;
6869 const char *repo_path;
6870 char *logmsg_path;
6874 static const struct got_error *
6875 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6876 void *arg)
6878 char *initial_content = NULL;
6879 struct got_pathlist_entry *pe;
6880 const struct got_error *err = NULL;
6881 char *template = NULL;
6882 struct collect_commit_logmsg_arg *a = arg;
6883 int initial_content_len;
6884 int fd = -1;
6885 size_t len;
6887 /* if a message was specified on the command line, just use it */
6888 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6889 len = strlen(a->cmdline_log) + 1;
6890 *logmsg = malloc(len + 1);
6891 if (*logmsg == NULL)
6892 return got_error_from_errno("malloc");
6893 strlcpy(*logmsg, a->cmdline_log, len);
6894 return NULL;
6897 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6898 return got_error_from_errno("asprintf");
6900 initial_content_len = asprintf(&initial_content,
6901 "\n# changes to be committed on branch %s:\n",
6902 a->branch_name);
6903 if (initial_content_len == -1)
6904 return got_error_from_errno("asprintf");
6906 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6907 if (err)
6908 goto done;
6910 if (write(fd, initial_content, initial_content_len) == -1) {
6911 err = got_error_from_errno2("write", a->logmsg_path);
6912 goto done;
6915 TAILQ_FOREACH(pe, commitable_paths, entry) {
6916 struct got_commitable *ct = pe->data;
6917 dprintf(fd, "# %c %s\n",
6918 got_commitable_get_status(ct),
6919 got_commitable_get_path(ct));
6922 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
6923 initial_content_len, 1);
6924 done:
6925 free(initial_content);
6926 free(template);
6928 if (fd != -1 && close(fd) == -1 && err == NULL)
6929 err = got_error_from_errno2("close", a->logmsg_path);
6931 /* Editor is done; we can now apply unveil(2) */
6932 if (err == NULL)
6933 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6934 if (err) {
6935 free(*logmsg);
6936 *logmsg = NULL;
6938 return err;
6941 static const struct got_error *
6942 cmd_commit(int argc, char *argv[])
6944 const struct got_error *error = NULL;
6945 struct got_worktree *worktree = NULL;
6946 struct got_repository *repo = NULL;
6947 char *cwd = NULL, *id_str = NULL;
6948 struct got_object_id *id = NULL;
6949 const char *logmsg = NULL;
6950 struct collect_commit_logmsg_arg cl_arg;
6951 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6952 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6953 int allow_bad_symlinks = 0;
6954 struct got_pathlist_head paths;
6956 TAILQ_INIT(&paths);
6957 cl_arg.logmsg_path = NULL;
6959 while ((ch = getopt(argc, argv, "m:S")) != -1) {
6960 switch (ch) {
6961 case 'm':
6962 logmsg = optarg;
6963 break;
6964 case 'S':
6965 allow_bad_symlinks = 1;
6966 break;
6967 default:
6968 usage_commit();
6969 /* NOTREACHED */
6973 argc -= optind;
6974 argv += optind;
6976 #ifndef PROFILE
6977 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6978 "unveil", NULL) == -1)
6979 err(1, "pledge");
6980 #endif
6981 cwd = getcwd(NULL, 0);
6982 if (cwd == NULL) {
6983 error = got_error_from_errno("getcwd");
6984 goto done;
6986 error = got_worktree_open(&worktree, cwd);
6987 if (error) {
6988 if (error->code == GOT_ERR_NOT_WORKTREE)
6989 error = wrap_not_worktree_error(error, "commit", cwd);
6990 goto done;
6993 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6994 if (error)
6995 goto done;
6996 if (rebase_in_progress) {
6997 error = got_error(GOT_ERR_REBASING);
6998 goto done;
7001 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7002 worktree);
7003 if (error)
7004 goto done;
7006 error = get_gitconfig_path(&gitconfig_path);
7007 if (error)
7008 goto done;
7009 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7010 gitconfig_path);
7011 if (error != NULL)
7012 goto done;
7014 error = get_author(&author, repo, worktree);
7015 if (error)
7016 return error;
7019 * unveil(2) traverses exec(2); if an editor is used we have
7020 * to apply unveil after the log message has been written.
7022 if (logmsg == NULL || strlen(logmsg) == 0)
7023 error = get_editor(&editor);
7024 else
7025 error = apply_unveil(got_repo_get_path(repo), 0,
7026 got_worktree_get_root_path(worktree));
7027 if (error)
7028 goto done;
7030 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7031 if (error)
7032 goto done;
7034 cl_arg.editor = editor;
7035 cl_arg.cmdline_log = logmsg;
7036 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
7037 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
7038 if (!histedit_in_progress) {
7039 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
7040 error = got_error(GOT_ERR_COMMIT_BRANCH);
7041 goto done;
7043 cl_arg.branch_name += 11;
7045 cl_arg.repo_path = got_repo_get_path(repo);
7046 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
7047 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
7048 print_status, NULL, repo);
7049 if (error) {
7050 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7051 cl_arg.logmsg_path != NULL)
7052 preserve_logmsg = 1;
7053 goto done;
7056 error = got_object_id_str(&id_str, id);
7057 if (error)
7058 goto done;
7059 printf("Created commit %s\n", id_str);
7060 done:
7061 if (preserve_logmsg) {
7062 fprintf(stderr, "%s: log message preserved in %s\n",
7063 getprogname(), cl_arg.logmsg_path);
7064 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
7065 error == NULL)
7066 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
7067 free(cl_arg.logmsg_path);
7068 if (repo)
7069 got_repo_close(repo);
7070 if (worktree)
7071 got_worktree_close(worktree);
7072 free(cwd);
7073 free(id_str);
7074 free(gitconfig_path);
7075 free(editor);
7076 free(author);
7077 return error;
7080 __dead static void
7081 usage_cherrypick(void)
7083 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
7084 exit(1);
7087 static const struct got_error *
7088 cmd_cherrypick(int argc, char *argv[])
7090 const struct got_error *error = NULL;
7091 struct got_worktree *worktree = NULL;
7092 struct got_repository *repo = NULL;
7093 char *cwd = NULL, *commit_id_str = NULL;
7094 struct got_object_id *commit_id = NULL;
7095 struct got_commit_object *commit = NULL;
7096 struct got_object_qid *pid;
7097 struct got_reference *head_ref = NULL;
7098 int ch;
7099 struct got_update_progress_arg upa;
7101 while ((ch = getopt(argc, argv, "")) != -1) {
7102 switch (ch) {
7103 default:
7104 usage_cherrypick();
7105 /* NOTREACHED */
7109 argc -= optind;
7110 argv += optind;
7112 #ifndef PROFILE
7113 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7114 "unveil", NULL) == -1)
7115 err(1, "pledge");
7116 #endif
7117 if (argc != 1)
7118 usage_cherrypick();
7120 cwd = getcwd(NULL, 0);
7121 if (cwd == NULL) {
7122 error = got_error_from_errno("getcwd");
7123 goto done;
7125 error = got_worktree_open(&worktree, cwd);
7126 if (error) {
7127 if (error->code == GOT_ERR_NOT_WORKTREE)
7128 error = wrap_not_worktree_error(error, "cherrypick",
7129 cwd);
7130 goto done;
7133 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7134 NULL);
7135 if (error != NULL)
7136 goto done;
7138 error = apply_unveil(got_repo_get_path(repo), 0,
7139 got_worktree_get_root_path(worktree));
7140 if (error)
7141 goto done;
7143 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7144 GOT_OBJ_TYPE_COMMIT, repo);
7145 if (error != NULL) {
7146 struct got_reference *ref;
7147 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7148 goto done;
7149 error = got_ref_open(&ref, repo, argv[0], 0);
7150 if (error != NULL)
7151 goto done;
7152 error = got_ref_resolve(&commit_id, repo, ref);
7153 got_ref_close(ref);
7154 if (error != NULL)
7155 goto done;
7157 error = got_object_id_str(&commit_id_str, commit_id);
7158 if (error)
7159 goto done;
7161 error = got_ref_open(&head_ref, repo,
7162 got_worktree_get_head_ref_name(worktree), 0);
7163 if (error != NULL)
7164 goto done;
7166 error = check_same_branch(commit_id, head_ref, NULL, repo);
7167 if (error) {
7168 if (error->code != GOT_ERR_ANCESTRY)
7169 goto done;
7170 error = NULL;
7171 } else {
7172 error = got_error(GOT_ERR_SAME_BRANCH);
7173 goto done;
7176 error = got_object_open_as_commit(&commit, repo, commit_id);
7177 if (error)
7178 goto done;
7179 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7180 memset(&upa, 0, sizeof(upa));
7181 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
7182 commit_id, repo, update_progress, &upa, check_cancelled,
7183 NULL);
7184 if (error != NULL)
7185 goto done;
7187 if (upa.did_something)
7188 printf("Merged commit %s\n", commit_id_str);
7189 print_update_progress_stats(&upa);
7190 done:
7191 if (commit)
7192 got_object_commit_close(commit);
7193 free(commit_id_str);
7194 if (head_ref)
7195 got_ref_close(head_ref);
7196 if (worktree)
7197 got_worktree_close(worktree);
7198 if (repo)
7199 got_repo_close(repo);
7200 return error;
7203 __dead static void
7204 usage_backout(void)
7206 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
7207 exit(1);
7210 static const struct got_error *
7211 cmd_backout(int argc, char *argv[])
7213 const struct got_error *error = NULL;
7214 struct got_worktree *worktree = NULL;
7215 struct got_repository *repo = NULL;
7216 char *cwd = NULL, *commit_id_str = NULL;
7217 struct got_object_id *commit_id = NULL;
7218 struct got_commit_object *commit = NULL;
7219 struct got_object_qid *pid;
7220 struct got_reference *head_ref = NULL;
7221 int ch;
7222 struct got_update_progress_arg upa;
7224 while ((ch = getopt(argc, argv, "")) != -1) {
7225 switch (ch) {
7226 default:
7227 usage_backout();
7228 /* NOTREACHED */
7232 argc -= optind;
7233 argv += optind;
7235 #ifndef PROFILE
7236 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7237 "unveil", NULL) == -1)
7238 err(1, "pledge");
7239 #endif
7240 if (argc != 1)
7241 usage_backout();
7243 cwd = getcwd(NULL, 0);
7244 if (cwd == NULL) {
7245 error = got_error_from_errno("getcwd");
7246 goto done;
7248 error = got_worktree_open(&worktree, cwd);
7249 if (error) {
7250 if (error->code == GOT_ERR_NOT_WORKTREE)
7251 error = wrap_not_worktree_error(error, "backout", cwd);
7252 goto done;
7255 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7256 NULL);
7257 if (error != NULL)
7258 goto done;
7260 error = apply_unveil(got_repo_get_path(repo), 0,
7261 got_worktree_get_root_path(worktree));
7262 if (error)
7263 goto done;
7265 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7266 GOT_OBJ_TYPE_COMMIT, repo);
7267 if (error != NULL) {
7268 struct got_reference *ref;
7269 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7270 goto done;
7271 error = got_ref_open(&ref, repo, argv[0], 0);
7272 if (error != NULL)
7273 goto done;
7274 error = got_ref_resolve(&commit_id, repo, ref);
7275 got_ref_close(ref);
7276 if (error != NULL)
7277 goto done;
7279 error = got_object_id_str(&commit_id_str, commit_id);
7280 if (error)
7281 goto done;
7283 error = got_ref_open(&head_ref, repo,
7284 got_worktree_get_head_ref_name(worktree), 0);
7285 if (error != NULL)
7286 goto done;
7288 error = check_same_branch(commit_id, head_ref, NULL, repo);
7289 if (error)
7290 goto done;
7292 error = got_object_open_as_commit(&commit, repo, commit_id);
7293 if (error)
7294 goto done;
7295 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7296 if (pid == NULL) {
7297 error = got_error(GOT_ERR_ROOT_COMMIT);
7298 goto done;
7301 memset(&upa, 0, sizeof(upa));
7302 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
7303 update_progress, &upa, check_cancelled, NULL);
7304 if (error != NULL)
7305 goto done;
7307 if (upa.did_something)
7308 printf("Backed out commit %s\n", commit_id_str);
7309 print_update_progress_stats(&upa);
7310 done:
7311 if (commit)
7312 got_object_commit_close(commit);
7313 free(commit_id_str);
7314 if (head_ref)
7315 got_ref_close(head_ref);
7316 if (worktree)
7317 got_worktree_close(worktree);
7318 if (repo)
7319 got_repo_close(repo);
7320 return error;
7323 __dead static void
7324 usage_rebase(void)
7326 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
7327 getprogname());
7328 exit(1);
7331 void
7332 trim_logmsg(char *logmsg, int limit)
7334 char *nl;
7335 size_t len;
7337 len = strlen(logmsg);
7338 if (len > limit)
7339 len = limit;
7340 logmsg[len] = '\0';
7341 nl = strchr(logmsg, '\n');
7342 if (nl)
7343 *nl = '\0';
7346 static const struct got_error *
7347 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
7349 const struct got_error *err;
7350 char *logmsg0 = NULL;
7351 const char *s;
7353 err = got_object_commit_get_logmsg(&logmsg0, commit);
7354 if (err)
7355 return err;
7357 s = logmsg0;
7358 while (isspace((unsigned char)s[0]))
7359 s++;
7361 *logmsg = strdup(s);
7362 if (*logmsg == NULL) {
7363 err = got_error_from_errno("strdup");
7364 goto done;
7367 trim_logmsg(*logmsg, limit);
7368 done:
7369 free(logmsg0);
7370 return err;
7373 static const struct got_error *
7374 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
7376 const struct got_error *err;
7377 struct got_commit_object *commit = NULL;
7378 char *id_str = NULL, *logmsg = NULL;
7380 err = got_object_open_as_commit(&commit, repo, id);
7381 if (err)
7382 return err;
7384 err = got_object_id_str(&id_str, id);
7385 if (err)
7386 goto done;
7388 id_str[12] = '\0';
7390 err = get_short_logmsg(&logmsg, 42, commit);
7391 if (err)
7392 goto done;
7394 printf("%s -> merge conflict: %s\n", id_str, logmsg);
7395 done:
7396 free(id_str);
7397 got_object_commit_close(commit);
7398 free(logmsg);
7399 return err;
7402 static const struct got_error *
7403 show_rebase_progress(struct got_commit_object *commit,
7404 struct got_object_id *old_id, struct got_object_id *new_id)
7406 const struct got_error *err;
7407 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7409 err = got_object_id_str(&old_id_str, old_id);
7410 if (err)
7411 goto done;
7413 if (new_id) {
7414 err = got_object_id_str(&new_id_str, new_id);
7415 if (err)
7416 goto done;
7419 old_id_str[12] = '\0';
7420 if (new_id_str)
7421 new_id_str[12] = '\0';
7423 err = get_short_logmsg(&logmsg, 42, commit);
7424 if (err)
7425 goto done;
7427 printf("%s -> %s: %s\n", old_id_str,
7428 new_id_str ? new_id_str : "no-op change", logmsg);
7429 done:
7430 free(old_id_str);
7431 free(new_id_str);
7432 free(logmsg);
7433 return err;
7436 static const struct got_error *
7437 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
7438 struct got_reference *branch, struct got_reference *new_base_branch,
7439 struct got_reference *tmp_branch, struct got_repository *repo)
7441 printf("Switching work tree to %s\n", got_ref_get_name(branch));
7442 return got_worktree_rebase_complete(worktree, fileindex,
7443 new_base_branch, tmp_branch, branch, repo);
7446 static const struct got_error *
7447 rebase_commit(struct got_pathlist_head *merged_paths,
7448 struct got_worktree *worktree, struct got_fileindex *fileindex,
7449 struct got_reference *tmp_branch,
7450 struct got_object_id *commit_id, struct got_repository *repo)
7452 const struct got_error *error;
7453 struct got_commit_object *commit;
7454 struct got_object_id *new_commit_id;
7456 error = got_object_open_as_commit(&commit, repo, commit_id);
7457 if (error)
7458 return error;
7460 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
7461 worktree, fileindex, tmp_branch, commit, commit_id, repo);
7462 if (error) {
7463 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
7464 goto done;
7465 error = show_rebase_progress(commit, commit_id, NULL);
7466 } else {
7467 error = show_rebase_progress(commit, commit_id, new_commit_id);
7468 free(new_commit_id);
7470 done:
7471 got_object_commit_close(commit);
7472 return error;
7475 struct check_path_prefix_arg {
7476 const char *path_prefix;
7477 size_t len;
7478 int errcode;
7481 static const struct got_error *
7482 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
7483 struct got_blob_object *blob2, struct got_object_id *id1,
7484 struct got_object_id *id2, const char *path1, const char *path2,
7485 mode_t mode1, mode_t mode2, struct got_repository *repo)
7487 struct check_path_prefix_arg *a = arg;
7489 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
7490 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
7491 return got_error(a->errcode);
7493 return NULL;
7496 static const struct got_error *
7497 check_path_prefix(struct got_object_id *parent_id,
7498 struct got_object_id *commit_id, const char *path_prefix,
7499 int errcode, struct got_repository *repo)
7501 const struct got_error *err;
7502 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7503 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7504 struct check_path_prefix_arg cpp_arg;
7506 if (got_path_is_root_dir(path_prefix))
7507 return NULL;
7509 err = got_object_open_as_commit(&commit, repo, commit_id);
7510 if (err)
7511 goto done;
7513 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7514 if (err)
7515 goto done;
7517 err = got_object_open_as_tree(&tree1, repo,
7518 got_object_commit_get_tree_id(parent_commit));
7519 if (err)
7520 goto done;
7522 err = got_object_open_as_tree(&tree2, repo,
7523 got_object_commit_get_tree_id(commit));
7524 if (err)
7525 goto done;
7527 cpp_arg.path_prefix = path_prefix;
7528 while (cpp_arg.path_prefix[0] == '/')
7529 cpp_arg.path_prefix++;
7530 cpp_arg.len = strlen(cpp_arg.path_prefix);
7531 cpp_arg.errcode = errcode;
7532 err = got_diff_tree(tree1, tree2, "", "", repo,
7533 check_path_prefix_in_diff, &cpp_arg, 0);
7534 done:
7535 if (tree1)
7536 got_object_tree_close(tree1);
7537 if (tree2)
7538 got_object_tree_close(tree2);
7539 if (commit)
7540 got_object_commit_close(commit);
7541 if (parent_commit)
7542 got_object_commit_close(parent_commit);
7543 return err;
7546 static const struct got_error *
7547 collect_commits(struct got_object_id_queue *commits,
7548 struct got_object_id *initial_commit_id,
7549 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7550 const char *path_prefix, int path_prefix_errcode,
7551 struct got_repository *repo)
7553 const struct got_error *err = NULL;
7554 struct got_commit_graph *graph = NULL;
7555 struct got_object_id *parent_id = NULL;
7556 struct got_object_qid *qid;
7557 struct got_object_id *commit_id = initial_commit_id;
7559 err = got_commit_graph_open(&graph, "/", 1);
7560 if (err)
7561 return err;
7563 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7564 check_cancelled, NULL);
7565 if (err)
7566 goto done;
7567 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7568 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7569 check_cancelled, NULL);
7570 if (err) {
7571 if (err->code == GOT_ERR_ITER_COMPLETED) {
7572 err = got_error_msg(GOT_ERR_ANCESTRY,
7573 "ran out of commits to rebase before "
7574 "youngest common ancestor commit has "
7575 "been reached?!?");
7577 goto done;
7578 } else {
7579 err = check_path_prefix(parent_id, commit_id,
7580 path_prefix, path_prefix_errcode, repo);
7581 if (err)
7582 goto done;
7584 err = got_object_qid_alloc(&qid, commit_id);
7585 if (err)
7586 goto done;
7587 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
7588 commit_id = parent_id;
7591 done:
7592 got_commit_graph_close(graph);
7593 return err;
7596 static const struct got_error *
7597 cmd_rebase(int argc, char *argv[])
7599 const struct got_error *error = NULL;
7600 struct got_worktree *worktree = NULL;
7601 struct got_repository *repo = NULL;
7602 struct got_fileindex *fileindex = NULL;
7603 char *cwd = NULL;
7604 struct got_reference *branch = NULL;
7605 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
7606 struct got_object_id *commit_id = NULL, *parent_id = NULL;
7607 struct got_object_id *resume_commit_id = NULL;
7608 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
7609 struct got_commit_object *commit = NULL;
7610 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
7611 int histedit_in_progress = 0;
7612 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7613 struct got_object_id_queue commits;
7614 struct got_pathlist_head merged_paths;
7615 const struct got_object_id_queue *parent_ids;
7616 struct got_object_qid *qid, *pid;
7618 SIMPLEQ_INIT(&commits);
7619 TAILQ_INIT(&merged_paths);
7621 while ((ch = getopt(argc, argv, "ac")) != -1) {
7622 switch (ch) {
7623 case 'a':
7624 abort_rebase = 1;
7625 break;
7626 case 'c':
7627 continue_rebase = 1;
7628 break;
7629 default:
7630 usage_rebase();
7631 /* NOTREACHED */
7635 argc -= optind;
7636 argv += optind;
7638 #ifndef PROFILE
7639 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7640 "unveil", NULL) == -1)
7641 err(1, "pledge");
7642 #endif
7643 if (abort_rebase && continue_rebase)
7644 usage_rebase();
7645 else if (abort_rebase || continue_rebase) {
7646 if (argc != 0)
7647 usage_rebase();
7648 } else if (argc != 1)
7649 usage_rebase();
7651 cwd = getcwd(NULL, 0);
7652 if (cwd == NULL) {
7653 error = got_error_from_errno("getcwd");
7654 goto done;
7656 error = got_worktree_open(&worktree, cwd);
7657 if (error) {
7658 if (error->code == GOT_ERR_NOT_WORKTREE)
7659 error = wrap_not_worktree_error(error, "rebase", cwd);
7660 goto done;
7663 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7664 NULL);
7665 if (error != NULL)
7666 goto done;
7668 error = apply_unveil(got_repo_get_path(repo), 0,
7669 got_worktree_get_root_path(worktree));
7670 if (error)
7671 goto done;
7673 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7674 worktree);
7675 if (error)
7676 goto done;
7677 if (histedit_in_progress) {
7678 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7679 goto done;
7682 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7683 if (error)
7684 goto done;
7686 if (abort_rebase) {
7687 struct got_update_progress_arg upa;
7688 if (!rebase_in_progress) {
7689 error = got_error(GOT_ERR_NOT_REBASING);
7690 goto done;
7692 error = got_worktree_rebase_continue(&resume_commit_id,
7693 &new_base_branch, &tmp_branch, &branch, &fileindex,
7694 worktree, repo);
7695 if (error)
7696 goto done;
7697 printf("Switching work tree to %s\n",
7698 got_ref_get_symref_target(new_base_branch));
7699 memset(&upa, 0, sizeof(upa));
7700 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7701 new_base_branch, update_progress, &upa);
7702 if (error)
7703 goto done;
7704 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7705 print_update_progress_stats(&upa);
7706 goto done; /* nothing else to do */
7709 if (continue_rebase) {
7710 if (!rebase_in_progress) {
7711 error = got_error(GOT_ERR_NOT_REBASING);
7712 goto done;
7714 error = got_worktree_rebase_continue(&resume_commit_id,
7715 &new_base_branch, &tmp_branch, &branch, &fileindex,
7716 worktree, repo);
7717 if (error)
7718 goto done;
7720 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7721 resume_commit_id, repo);
7722 if (error)
7723 goto done;
7725 yca_id = got_object_id_dup(resume_commit_id);
7726 if (yca_id == NULL) {
7727 error = got_error_from_errno("got_object_id_dup");
7728 goto done;
7730 } else {
7731 error = got_ref_open(&branch, repo, argv[0], 0);
7732 if (error != NULL)
7733 goto done;
7736 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7737 if (error)
7738 goto done;
7740 if (!continue_rebase) {
7741 struct got_object_id *base_commit_id;
7743 base_commit_id = got_worktree_get_base_commit_id(worktree);
7744 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7745 base_commit_id, branch_head_commit_id, repo,
7746 check_cancelled, NULL);
7747 if (error)
7748 goto done;
7749 if (yca_id == NULL) {
7750 error = got_error_msg(GOT_ERR_ANCESTRY,
7751 "specified branch shares no common ancestry "
7752 "with work tree's branch");
7753 goto done;
7756 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7757 if (error) {
7758 if (error->code != GOT_ERR_ANCESTRY)
7759 goto done;
7760 error = NULL;
7761 } else {
7762 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7763 "specified branch resolves to a commit which "
7764 "is already contained in work tree's branch");
7765 goto done;
7767 error = got_worktree_rebase_prepare(&new_base_branch,
7768 &tmp_branch, &fileindex, worktree, branch, repo);
7769 if (error)
7770 goto done;
7773 commit_id = branch_head_commit_id;
7774 error = got_object_open_as_commit(&commit, repo, commit_id);
7775 if (error)
7776 goto done;
7778 parent_ids = got_object_commit_get_parent_ids(commit);
7779 pid = SIMPLEQ_FIRST(parent_ids);
7780 if (pid == NULL) {
7781 if (!continue_rebase) {
7782 struct got_update_progress_arg upa;
7783 memset(&upa, 0, sizeof(upa));
7784 error = got_worktree_rebase_abort(worktree, fileindex,
7785 repo, new_base_branch, update_progress, &upa);
7786 if (error)
7787 goto done;
7788 printf("Rebase of %s aborted\n",
7789 got_ref_get_name(branch));
7790 print_update_progress_stats(&upa);
7793 error = got_error(GOT_ERR_EMPTY_REBASE);
7794 goto done;
7796 error = collect_commits(&commits, commit_id, pid->id,
7797 yca_id, got_worktree_get_path_prefix(worktree),
7798 GOT_ERR_REBASE_PATH, repo);
7799 got_object_commit_close(commit);
7800 commit = NULL;
7801 if (error)
7802 goto done;
7804 if (SIMPLEQ_EMPTY(&commits)) {
7805 if (continue_rebase) {
7806 error = rebase_complete(worktree, fileindex,
7807 branch, new_base_branch, tmp_branch, repo);
7808 goto done;
7809 } else {
7810 /* Fast-forward the reference of the branch. */
7811 struct got_object_id *new_head_commit_id;
7812 char *id_str;
7813 error = got_ref_resolve(&new_head_commit_id, repo,
7814 new_base_branch);
7815 if (error)
7816 goto done;
7817 error = got_object_id_str(&id_str, new_head_commit_id);
7818 printf("Forwarding %s to commit %s\n",
7819 got_ref_get_name(branch), id_str);
7820 free(id_str);
7821 error = got_ref_change_ref(branch,
7822 new_head_commit_id);
7823 if (error)
7824 goto done;
7828 pid = NULL;
7829 SIMPLEQ_FOREACH(qid, &commits, entry) {
7830 struct got_update_progress_arg upa;
7832 commit_id = qid->id;
7833 parent_id = pid ? pid->id : yca_id;
7834 pid = qid;
7836 memset(&upa, 0, sizeof(upa));
7837 error = got_worktree_rebase_merge_files(&merged_paths,
7838 worktree, fileindex, parent_id, commit_id, repo,
7839 update_progress, &upa, check_cancelled, NULL);
7840 if (error)
7841 goto done;
7843 print_update_progress_stats(&upa);
7844 if (upa.conflicts > 0)
7845 rebase_status = GOT_STATUS_CONFLICT;
7847 if (rebase_status == GOT_STATUS_CONFLICT) {
7848 error = show_rebase_merge_conflict(qid->id, repo);
7849 if (error)
7850 goto done;
7851 got_worktree_rebase_pathlist_free(&merged_paths);
7852 break;
7855 error = rebase_commit(&merged_paths, worktree, fileindex,
7856 tmp_branch, commit_id, repo);
7857 got_worktree_rebase_pathlist_free(&merged_paths);
7858 if (error)
7859 goto done;
7862 if (rebase_status == GOT_STATUS_CONFLICT) {
7863 error = got_worktree_rebase_postpone(worktree, fileindex);
7864 if (error)
7865 goto done;
7866 error = got_error_msg(GOT_ERR_CONFLICTS,
7867 "conflicts must be resolved before rebasing can continue");
7868 } else
7869 error = rebase_complete(worktree, fileindex, branch,
7870 new_base_branch, tmp_branch, repo);
7871 done:
7872 got_object_id_queue_free(&commits);
7873 free(branch_head_commit_id);
7874 free(resume_commit_id);
7875 free(yca_id);
7876 if (commit)
7877 got_object_commit_close(commit);
7878 if (branch)
7879 got_ref_close(branch);
7880 if (new_base_branch)
7881 got_ref_close(new_base_branch);
7882 if (tmp_branch)
7883 got_ref_close(tmp_branch);
7884 if (worktree)
7885 got_worktree_close(worktree);
7886 if (repo)
7887 got_repo_close(repo);
7888 return error;
7891 __dead static void
7892 usage_histedit(void)
7894 fprintf(stderr, "usage: %s histedit [-a] [-c] [-f] [-F histedit-script] [-m]\n",
7895 getprogname());
7896 exit(1);
7899 #define GOT_HISTEDIT_PICK 'p'
7900 #define GOT_HISTEDIT_EDIT 'e'
7901 #define GOT_HISTEDIT_FOLD 'f'
7902 #define GOT_HISTEDIT_DROP 'd'
7903 #define GOT_HISTEDIT_MESG 'm'
7905 static struct got_histedit_cmd {
7906 unsigned char code;
7907 const char *name;
7908 const char *desc;
7909 } got_histedit_cmds[] = {
7910 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7911 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7912 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7913 "be used" },
7914 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7915 { GOT_HISTEDIT_MESG, "mesg",
7916 "single-line log message for commit above (open editor if empty)" },
7919 struct got_histedit_list_entry {
7920 TAILQ_ENTRY(got_histedit_list_entry) entry;
7921 struct got_object_id *commit_id;
7922 const struct got_histedit_cmd *cmd;
7923 char *logmsg;
7925 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7927 static const struct got_error *
7928 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7929 FILE *f, struct got_repository *repo)
7931 const struct got_error *err = NULL;
7932 char *logmsg = NULL, *id_str = NULL;
7933 struct got_commit_object *commit = NULL;
7934 int n;
7936 err = got_object_open_as_commit(&commit, repo, commit_id);
7937 if (err)
7938 goto done;
7940 err = get_short_logmsg(&logmsg, 34, commit);
7941 if (err)
7942 goto done;
7944 err = got_object_id_str(&id_str, commit_id);
7945 if (err)
7946 goto done;
7948 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7949 if (n < 0)
7950 err = got_ferror(f, GOT_ERR_IO);
7951 done:
7952 if (commit)
7953 got_object_commit_close(commit);
7954 free(id_str);
7955 free(logmsg);
7956 return err;
7959 static const struct got_error *
7960 histedit_write_commit_list(struct got_object_id_queue *commits,
7961 FILE *f, int edit_logmsg_only, int fold_only, struct got_repository *repo)
7963 const struct got_error *err = NULL;
7964 struct got_object_qid *qid;
7965 const char *histedit_cmd = NULL;
7967 if (SIMPLEQ_EMPTY(commits))
7968 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7970 SIMPLEQ_FOREACH(qid, commits, entry) {
7971 histedit_cmd = got_histedit_cmds[0].name;
7972 if (fold_only && SIMPLEQ_NEXT(qid, entry) != NULL)
7973 histedit_cmd = "fold";
7974 err = histedit_write_commit(qid->id, histedit_cmd, f, repo);
7975 if (err)
7976 break;
7977 if (edit_logmsg_only) {
7978 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7979 if (n < 0) {
7980 err = got_ferror(f, GOT_ERR_IO);
7981 break;
7986 return err;
7989 static const struct got_error *
7990 write_cmd_list(FILE *f, const char *branch_name,
7991 struct got_object_id_queue *commits)
7993 const struct got_error *err = NULL;
7994 size_t i;
7995 int n;
7996 char *id_str;
7997 struct got_object_qid *qid;
7999 qid = SIMPLEQ_FIRST(commits);
8000 err = got_object_id_str(&id_str, qid->id);
8001 if (err)
8002 return err;
8004 n = fprintf(f,
8005 "# Editing the history of branch '%s' starting at\n"
8006 "# commit %s\n"
8007 "# Commits will be processed in order from top to "
8008 "bottom of this file.\n", branch_name, id_str);
8009 if (n < 0) {
8010 err = got_ferror(f, GOT_ERR_IO);
8011 goto done;
8014 n = fprintf(f, "# Available histedit commands:\n");
8015 if (n < 0) {
8016 err = got_ferror(f, GOT_ERR_IO);
8017 goto done;
8020 for (i = 0; i < nitems(got_histedit_cmds); i++) {
8021 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
8022 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
8023 cmd->desc);
8024 if (n < 0) {
8025 err = got_ferror(f, GOT_ERR_IO);
8026 break;
8029 done:
8030 free(id_str);
8031 return err;
8034 static const struct got_error *
8035 histedit_syntax_error(int lineno)
8037 static char msg[42];
8038 int ret;
8040 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
8041 lineno);
8042 if (ret == -1 || ret >= sizeof(msg))
8043 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
8045 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
8048 static const struct got_error *
8049 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
8050 char *logmsg, struct got_repository *repo)
8052 const struct got_error *err;
8053 struct got_commit_object *folded_commit = NULL;
8054 char *id_str, *folded_logmsg = NULL;
8056 err = got_object_id_str(&id_str, hle->commit_id);
8057 if (err)
8058 return err;
8060 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
8061 if (err)
8062 goto done;
8064 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
8065 if (err)
8066 goto done;
8067 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
8068 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
8069 folded_logmsg) == -1) {
8070 err = got_error_from_errno("asprintf");
8072 done:
8073 if (folded_commit)
8074 got_object_commit_close(folded_commit);
8075 free(id_str);
8076 free(folded_logmsg);
8077 return err;
8080 static struct got_histedit_list_entry *
8081 get_folded_commits(struct got_histedit_list_entry *hle)
8083 struct got_histedit_list_entry *prev, *folded = NULL;
8085 prev = TAILQ_PREV(hle, got_histedit_list, entry);
8086 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
8087 prev->cmd->code == GOT_HISTEDIT_DROP)) {
8088 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
8089 folded = prev;
8090 prev = TAILQ_PREV(prev, got_histedit_list, entry);
8093 return folded;
8096 static const struct got_error *
8097 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
8098 struct got_repository *repo)
8100 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
8101 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
8102 const struct got_error *err = NULL;
8103 struct got_commit_object *commit = NULL;
8104 int logmsg_len;
8105 int fd;
8106 struct got_histedit_list_entry *folded = NULL;
8108 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8109 if (err)
8110 return err;
8112 folded = get_folded_commits(hle);
8113 if (folded) {
8114 while (folded != hle) {
8115 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
8116 folded = TAILQ_NEXT(folded, entry);
8117 continue;
8119 err = append_folded_commit_msg(&new_msg, folded,
8120 logmsg, repo);
8121 if (err)
8122 goto done;
8123 free(logmsg);
8124 logmsg = new_msg;
8125 folded = TAILQ_NEXT(folded, entry);
8129 err = got_object_id_str(&id_str, hle->commit_id);
8130 if (err)
8131 goto done;
8132 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
8133 if (err)
8134 goto done;
8135 logmsg_len = asprintf(&new_msg,
8136 "%s\n# original log message of commit %s: %s",
8137 logmsg ? logmsg : "", id_str, orig_logmsg);
8138 if (logmsg_len == -1) {
8139 err = got_error_from_errno("asprintf");
8140 goto done;
8142 free(logmsg);
8143 logmsg = new_msg;
8145 err = got_object_id_str(&id_str, hle->commit_id);
8146 if (err)
8147 goto done;
8149 err = got_opentemp_named_fd(&logmsg_path, &fd,
8150 GOT_TMPDIR_STR "/got-logmsg");
8151 if (err)
8152 goto done;
8154 write(fd, logmsg, logmsg_len);
8155 close(fd);
8157 err = get_editor(&editor);
8158 if (err)
8159 goto done;
8161 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
8162 logmsg_len, 0);
8163 if (err) {
8164 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
8165 goto done;
8166 err = NULL;
8167 hle->logmsg = strdup(new_msg);
8168 if (hle->logmsg == NULL)
8169 err = got_error_from_errno("strdup");
8171 done:
8172 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
8173 err = got_error_from_errno2("unlink", logmsg_path);
8174 free(logmsg_path);
8175 free(logmsg);
8176 free(orig_logmsg);
8177 free(editor);
8178 if (commit)
8179 got_object_commit_close(commit);
8180 return err;
8183 static const struct got_error *
8184 histedit_parse_list(struct got_histedit_list *histedit_cmds,
8185 FILE *f, struct got_repository *repo)
8187 const struct got_error *err = NULL;
8188 char *line = NULL, *p, *end;
8189 size_t i, size;
8190 ssize_t len;
8191 int lineno = 0;
8192 const struct got_histedit_cmd *cmd;
8193 struct got_object_id *commit_id = NULL;
8194 struct got_histedit_list_entry *hle = NULL;
8196 for (;;) {
8197 len = getline(&line, &size, f);
8198 if (len == -1) {
8199 const struct got_error *getline_err;
8200 if (feof(f))
8201 break;
8202 getline_err = got_error_from_errno("getline");
8203 err = got_ferror(f, getline_err->code);
8204 break;
8206 lineno++;
8207 p = line;
8208 while (isspace((unsigned char)p[0]))
8209 p++;
8210 if (p[0] == '#' || p[0] == '\0') {
8211 free(line);
8212 line = NULL;
8213 continue;
8215 cmd = NULL;
8216 for (i = 0; i < nitems(got_histedit_cmds); i++) {
8217 cmd = &got_histedit_cmds[i];
8218 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
8219 isspace((unsigned char)p[strlen(cmd->name)])) {
8220 p += strlen(cmd->name);
8221 break;
8223 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
8224 p++;
8225 break;
8228 if (i == nitems(got_histedit_cmds)) {
8229 err = histedit_syntax_error(lineno);
8230 break;
8232 while (isspace((unsigned char)p[0]))
8233 p++;
8234 if (cmd->code == GOT_HISTEDIT_MESG) {
8235 if (hle == NULL || hle->logmsg != NULL) {
8236 err = got_error(GOT_ERR_HISTEDIT_CMD);
8237 break;
8239 if (p[0] == '\0') {
8240 err = histedit_edit_logmsg(hle, repo);
8241 if (err)
8242 break;
8243 } else {
8244 hle->logmsg = strdup(p);
8245 if (hle->logmsg == NULL) {
8246 err = got_error_from_errno("strdup");
8247 break;
8250 free(line);
8251 line = NULL;
8252 continue;
8253 } else {
8254 end = p;
8255 while (end[0] && !isspace((unsigned char)end[0]))
8256 end++;
8257 *end = '\0';
8259 err = got_object_resolve_id_str(&commit_id, repo, p);
8260 if (err) {
8261 /* override error code */
8262 err = histedit_syntax_error(lineno);
8263 break;
8266 hle = malloc(sizeof(*hle));
8267 if (hle == NULL) {
8268 err = got_error_from_errno("malloc");
8269 break;
8271 hle->cmd = cmd;
8272 hle->commit_id = commit_id;
8273 hle->logmsg = NULL;
8274 commit_id = NULL;
8275 free(line);
8276 line = NULL;
8277 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
8280 free(line);
8281 free(commit_id);
8282 return err;
8285 static const struct got_error *
8286 histedit_check_script(struct got_histedit_list *histedit_cmds,
8287 struct got_object_id_queue *commits, struct got_repository *repo)
8289 const struct got_error *err = NULL;
8290 struct got_object_qid *qid;
8291 struct got_histedit_list_entry *hle;
8292 static char msg[92];
8293 char *id_str;
8295 if (TAILQ_EMPTY(histedit_cmds))
8296 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
8297 "histedit script contains no commands");
8298 if (SIMPLEQ_EMPTY(commits))
8299 return got_error(GOT_ERR_EMPTY_HISTEDIT);
8301 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8302 struct got_histedit_list_entry *hle2;
8303 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
8304 if (hle == hle2)
8305 continue;
8306 if (got_object_id_cmp(hle->commit_id,
8307 hle2->commit_id) != 0)
8308 continue;
8309 err = got_object_id_str(&id_str, hle->commit_id);
8310 if (err)
8311 return err;
8312 snprintf(msg, sizeof(msg), "commit %s is listed "
8313 "more than once in histedit script", id_str);
8314 free(id_str);
8315 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8319 SIMPLEQ_FOREACH(qid, commits, entry) {
8320 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8321 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
8322 break;
8324 if (hle == NULL) {
8325 err = got_object_id_str(&id_str, qid->id);
8326 if (err)
8327 return err;
8328 snprintf(msg, sizeof(msg),
8329 "commit %s missing from histedit script", id_str);
8330 free(id_str);
8331 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8335 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
8336 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
8337 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
8338 "last commit in histedit script cannot be folded");
8340 return NULL;
8343 static const struct got_error *
8344 histedit_run_editor(struct got_histedit_list *histedit_cmds,
8345 const char *path, struct got_object_id_queue *commits,
8346 struct got_repository *repo)
8348 const struct got_error *err = NULL;
8349 char *editor;
8350 FILE *f = NULL;
8352 err = get_editor(&editor);
8353 if (err)
8354 return err;
8356 if (spawn_editor(editor, path) == -1) {
8357 err = got_error_from_errno("failed spawning editor");
8358 goto done;
8361 f = fopen(path, "r");
8362 if (f == NULL) {
8363 err = got_error_from_errno("fopen");
8364 goto done;
8366 err = histedit_parse_list(histedit_cmds, f, repo);
8367 if (err)
8368 goto done;
8370 err = histedit_check_script(histedit_cmds, commits, repo);
8371 done:
8372 if (f && fclose(f) != 0 && err == NULL)
8373 err = got_error_from_errno("fclose");
8374 free(editor);
8375 return err;
8378 static const struct got_error *
8379 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
8380 struct got_object_id_queue *, const char *, const char *,
8381 struct got_repository *);
8383 static const struct got_error *
8384 histedit_edit_script(struct got_histedit_list *histedit_cmds,
8385 struct got_object_id_queue *commits, const char *branch_name,
8386 int edit_logmsg_only, int fold_only, struct got_repository *repo)
8388 const struct got_error *err;
8389 FILE *f = NULL;
8390 char *path = NULL;
8392 err = got_opentemp_named(&path, &f, "got-histedit");
8393 if (err)
8394 return err;
8396 err = write_cmd_list(f, branch_name, commits);
8397 if (err)
8398 goto done;
8400 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
8401 fold_only, repo);
8402 if (err)
8403 goto done;
8405 if (edit_logmsg_only || fold_only) {
8406 rewind(f);
8407 err = histedit_parse_list(histedit_cmds, f, repo);
8408 } else {
8409 if (fclose(f) != 0) {
8410 err = got_error_from_errno("fclose");
8411 goto done;
8413 f = NULL;
8414 err = histedit_run_editor(histedit_cmds, path, commits, repo);
8415 if (err) {
8416 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8417 err->code != GOT_ERR_HISTEDIT_CMD)
8418 goto done;
8419 err = histedit_edit_list_retry(histedit_cmds, err,
8420 commits, path, branch_name, repo);
8423 done:
8424 if (f && fclose(f) != 0 && err == NULL)
8425 err = got_error_from_errno("fclose");
8426 if (path && unlink(path) != 0 && err == NULL)
8427 err = got_error_from_errno2("unlink", path);
8428 free(path);
8429 return err;
8432 static const struct got_error *
8433 histedit_save_list(struct got_histedit_list *histedit_cmds,
8434 struct got_worktree *worktree, struct got_repository *repo)
8436 const struct got_error *err = NULL;
8437 char *path = NULL;
8438 FILE *f = NULL;
8439 struct got_histedit_list_entry *hle;
8440 struct got_commit_object *commit = NULL;
8442 err = got_worktree_get_histedit_script_path(&path, worktree);
8443 if (err)
8444 return err;
8446 f = fopen(path, "w");
8447 if (f == NULL) {
8448 err = got_error_from_errno2("fopen", path);
8449 goto done;
8451 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8452 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
8453 repo);
8454 if (err)
8455 break;
8457 if (hle->logmsg) {
8458 int n = fprintf(f, "%c %s\n",
8459 GOT_HISTEDIT_MESG, hle->logmsg);
8460 if (n < 0) {
8461 err = got_ferror(f, GOT_ERR_IO);
8462 break;
8466 done:
8467 if (f && fclose(f) != 0 && err == NULL)
8468 err = got_error_from_errno("fclose");
8469 free(path);
8470 if (commit)
8471 got_object_commit_close(commit);
8472 return err;
8475 void
8476 histedit_free_list(struct got_histedit_list *histedit_cmds)
8478 struct got_histedit_list_entry *hle;
8480 while ((hle = TAILQ_FIRST(histedit_cmds))) {
8481 TAILQ_REMOVE(histedit_cmds, hle, entry);
8482 free(hle);
8486 static const struct got_error *
8487 histedit_load_list(struct got_histedit_list *histedit_cmds,
8488 const char *path, struct got_repository *repo)
8490 const struct got_error *err = NULL;
8491 FILE *f = NULL;
8493 f = fopen(path, "r");
8494 if (f == NULL) {
8495 err = got_error_from_errno2("fopen", path);
8496 goto done;
8499 err = histedit_parse_list(histedit_cmds, f, repo);
8500 done:
8501 if (f && fclose(f) != 0 && err == NULL)
8502 err = got_error_from_errno("fclose");
8503 return err;
8506 static const struct got_error *
8507 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
8508 const struct got_error *edit_err, struct got_object_id_queue *commits,
8509 const char *path, const char *branch_name, struct got_repository *repo)
8511 const struct got_error *err = NULL, *prev_err = edit_err;
8512 int resp = ' ';
8514 while (resp != 'c' && resp != 'r' && resp != 'a') {
8515 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
8516 "or (a)bort: ", getprogname(), prev_err->msg);
8517 resp = getchar();
8518 if (resp == '\n')
8519 resp = getchar();
8520 if (resp == 'c') {
8521 histedit_free_list(histedit_cmds);
8522 err = histedit_run_editor(histedit_cmds, path, commits,
8523 repo);
8524 if (err) {
8525 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8526 err->code != GOT_ERR_HISTEDIT_CMD)
8527 break;
8528 prev_err = err;
8529 resp = ' ';
8530 continue;
8532 break;
8533 } else if (resp == 'r') {
8534 histedit_free_list(histedit_cmds);
8535 err = histedit_edit_script(histedit_cmds,
8536 commits, branch_name, 0, 0, repo);
8537 if (err) {
8538 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8539 err->code != GOT_ERR_HISTEDIT_CMD)
8540 break;
8541 prev_err = err;
8542 resp = ' ';
8543 continue;
8545 break;
8546 } else if (resp == 'a') {
8547 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
8548 break;
8549 } else
8550 printf("invalid response '%c'\n", resp);
8553 return err;
8556 static const struct got_error *
8557 histedit_complete(struct got_worktree *worktree,
8558 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
8559 struct got_reference *branch, struct got_repository *repo)
8561 printf("Switching work tree to %s\n",
8562 got_ref_get_symref_target(branch));
8563 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
8564 branch, repo);
8567 static const struct got_error *
8568 show_histedit_progress(struct got_commit_object *commit,
8569 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
8571 const struct got_error *err;
8572 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8574 err = got_object_id_str(&old_id_str, hle->commit_id);
8575 if (err)
8576 goto done;
8578 if (new_id) {
8579 err = got_object_id_str(&new_id_str, new_id);
8580 if (err)
8581 goto done;
8584 old_id_str[12] = '\0';
8585 if (new_id_str)
8586 new_id_str[12] = '\0';
8588 if (hle->logmsg) {
8589 logmsg = strdup(hle->logmsg);
8590 if (logmsg == NULL) {
8591 err = got_error_from_errno("strdup");
8592 goto done;
8594 trim_logmsg(logmsg, 42);
8595 } else {
8596 err = get_short_logmsg(&logmsg, 42, commit);
8597 if (err)
8598 goto done;
8601 switch (hle->cmd->code) {
8602 case GOT_HISTEDIT_PICK:
8603 case GOT_HISTEDIT_EDIT:
8604 printf("%s -> %s: %s\n", old_id_str,
8605 new_id_str ? new_id_str : "no-op change", logmsg);
8606 break;
8607 case GOT_HISTEDIT_DROP:
8608 case GOT_HISTEDIT_FOLD:
8609 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
8610 logmsg);
8611 break;
8612 default:
8613 break;
8615 done:
8616 free(old_id_str);
8617 free(new_id_str);
8618 return err;
8621 static const struct got_error *
8622 histedit_commit(struct got_pathlist_head *merged_paths,
8623 struct got_worktree *worktree, struct got_fileindex *fileindex,
8624 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
8625 struct got_repository *repo)
8627 const struct got_error *err;
8628 struct got_commit_object *commit;
8629 struct got_object_id *new_commit_id;
8631 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
8632 && hle->logmsg == NULL) {
8633 err = histedit_edit_logmsg(hle, repo);
8634 if (err)
8635 return err;
8638 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8639 if (err)
8640 return err;
8642 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
8643 worktree, fileindex, tmp_branch, commit, hle->commit_id,
8644 hle->logmsg, repo);
8645 if (err) {
8646 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
8647 goto done;
8648 err = show_histedit_progress(commit, hle, NULL);
8649 } else {
8650 err = show_histedit_progress(commit, hle, new_commit_id);
8651 free(new_commit_id);
8653 done:
8654 got_object_commit_close(commit);
8655 return err;
8658 static const struct got_error *
8659 histedit_skip_commit(struct got_histedit_list_entry *hle,
8660 struct got_worktree *worktree, struct got_repository *repo)
8662 const struct got_error *error;
8663 struct got_commit_object *commit;
8665 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
8666 repo);
8667 if (error)
8668 return error;
8670 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
8671 if (error)
8672 return error;
8674 error = show_histedit_progress(commit, hle, NULL);
8675 got_object_commit_close(commit);
8676 return error;
8679 static const struct got_error *
8680 check_local_changes(void *arg, unsigned char status,
8681 unsigned char staged_status, const char *path,
8682 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8683 struct got_object_id *commit_id, int dirfd, const char *de_name)
8685 int *have_local_changes = arg;
8687 switch (status) {
8688 case GOT_STATUS_ADD:
8689 case GOT_STATUS_DELETE:
8690 case GOT_STATUS_MODIFY:
8691 case GOT_STATUS_CONFLICT:
8692 *have_local_changes = 1;
8693 return got_error(GOT_ERR_CANCELLED);
8694 default:
8695 break;
8698 switch (staged_status) {
8699 case GOT_STATUS_ADD:
8700 case GOT_STATUS_DELETE:
8701 case GOT_STATUS_MODIFY:
8702 *have_local_changes = 1;
8703 return got_error(GOT_ERR_CANCELLED);
8704 default:
8705 break;
8708 return NULL;
8711 static const struct got_error *
8712 cmd_histedit(int argc, char *argv[])
8714 const struct got_error *error = NULL;
8715 struct got_worktree *worktree = NULL;
8716 struct got_fileindex *fileindex = NULL;
8717 struct got_repository *repo = NULL;
8718 char *cwd = NULL;
8719 struct got_reference *branch = NULL;
8720 struct got_reference *tmp_branch = NULL;
8721 struct got_object_id *resume_commit_id = NULL;
8722 struct got_object_id *base_commit_id = NULL;
8723 struct got_object_id *head_commit_id = NULL;
8724 struct got_commit_object *commit = NULL;
8725 int ch, rebase_in_progress = 0;
8726 struct got_update_progress_arg upa;
8727 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8728 int edit_logmsg_only = 0, fold_only = 0;
8729 const char *edit_script_path = NULL;
8730 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8731 struct got_object_id_queue commits;
8732 struct got_pathlist_head merged_paths;
8733 const struct got_object_id_queue *parent_ids;
8734 struct got_object_qid *pid;
8735 struct got_histedit_list histedit_cmds;
8736 struct got_histedit_list_entry *hle;
8738 SIMPLEQ_INIT(&commits);
8739 TAILQ_INIT(&histedit_cmds);
8740 TAILQ_INIT(&merged_paths);
8741 memset(&upa, 0, sizeof(upa));
8743 while ((ch = getopt(argc, argv, "acfF:m")) != -1) {
8744 switch (ch) {
8745 case 'a':
8746 abort_edit = 1;
8747 break;
8748 case 'c':
8749 continue_edit = 1;
8750 break;
8751 case 'f':
8752 fold_only = 1;
8753 break;
8754 case 'F':
8755 edit_script_path = optarg;
8756 break;
8757 case 'm':
8758 edit_logmsg_only = 1;
8759 break;
8760 default:
8761 usage_histedit();
8762 /* NOTREACHED */
8766 argc -= optind;
8767 argv += optind;
8769 #ifndef PROFILE
8770 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8771 "unveil", NULL) == -1)
8772 err(1, "pledge");
8773 #endif
8774 if (abort_edit && continue_edit)
8775 option_conflict('a', 'c');
8776 if (edit_script_path && edit_logmsg_only)
8777 option_conflict('F', 'm');
8778 if (abort_edit && edit_logmsg_only)
8779 option_conflict('a', 'm');
8780 if (continue_edit && edit_logmsg_only)
8781 option_conflict('c', 'm');
8782 if (abort_edit && fold_only)
8783 option_conflict('a', 'f');
8784 if (continue_edit && fold_only)
8785 option_conflict('c', 'f');
8786 if (fold_only && edit_logmsg_only)
8787 option_conflict('f', 'm');
8788 if (edit_script_path && fold_only)
8789 option_conflict('F', 'f');
8790 if (argc != 0)
8791 usage_histedit();
8794 * This command cannot apply unveil(2) in all cases because the
8795 * user may choose to run an editor to edit the histedit script
8796 * and to edit individual commit log messages.
8797 * unveil(2) traverses exec(2); if an editor is used we have to
8798 * apply unveil after edit script and log messages have been written.
8799 * XXX TODO: Make use of unveil(2) where possible.
8802 cwd = getcwd(NULL, 0);
8803 if (cwd == NULL) {
8804 error = got_error_from_errno("getcwd");
8805 goto done;
8807 error = got_worktree_open(&worktree, cwd);
8808 if (error) {
8809 if (error->code == GOT_ERR_NOT_WORKTREE)
8810 error = wrap_not_worktree_error(error, "histedit", cwd);
8811 goto done;
8814 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8815 NULL);
8816 if (error != NULL)
8817 goto done;
8819 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8820 if (error)
8821 goto done;
8822 if (rebase_in_progress) {
8823 error = got_error(GOT_ERR_REBASING);
8824 goto done;
8827 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8828 if (error)
8829 goto done;
8831 if (edit_in_progress && edit_logmsg_only) {
8832 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8833 "histedit operation is in progress in this "
8834 "work tree and must be continued or aborted "
8835 "before the -m option can be used");
8836 goto done;
8838 if (edit_in_progress && fold_only) {
8839 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8840 "histedit operation is in progress in this "
8841 "work tree and must be continued or aborted "
8842 "before the -f option can be used");
8843 goto done;
8846 if (edit_in_progress && abort_edit) {
8847 error = got_worktree_histedit_continue(&resume_commit_id,
8848 &tmp_branch, &branch, &base_commit_id, &fileindex,
8849 worktree, repo);
8850 if (error)
8851 goto done;
8852 printf("Switching work tree to %s\n",
8853 got_ref_get_symref_target(branch));
8854 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8855 branch, base_commit_id, update_progress, &upa);
8856 if (error)
8857 goto done;
8858 printf("Histedit of %s aborted\n",
8859 got_ref_get_symref_target(branch));
8860 print_update_progress_stats(&upa);
8861 goto done; /* nothing else to do */
8862 } else if (abort_edit) {
8863 error = got_error(GOT_ERR_NOT_HISTEDIT);
8864 goto done;
8867 if (continue_edit) {
8868 char *path;
8870 if (!edit_in_progress) {
8871 error = got_error(GOT_ERR_NOT_HISTEDIT);
8872 goto done;
8875 error = got_worktree_get_histedit_script_path(&path, worktree);
8876 if (error)
8877 goto done;
8879 error = histedit_load_list(&histedit_cmds, path, repo);
8880 free(path);
8881 if (error)
8882 goto done;
8884 error = got_worktree_histedit_continue(&resume_commit_id,
8885 &tmp_branch, &branch, &base_commit_id, &fileindex,
8886 worktree, repo);
8887 if (error)
8888 goto done;
8890 error = got_ref_resolve(&head_commit_id, repo, branch);
8891 if (error)
8892 goto done;
8894 error = got_object_open_as_commit(&commit, repo,
8895 head_commit_id);
8896 if (error)
8897 goto done;
8898 parent_ids = got_object_commit_get_parent_ids(commit);
8899 pid = SIMPLEQ_FIRST(parent_ids);
8900 if (pid == NULL) {
8901 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8902 goto done;
8904 error = collect_commits(&commits, head_commit_id, pid->id,
8905 base_commit_id, got_worktree_get_path_prefix(worktree),
8906 GOT_ERR_HISTEDIT_PATH, repo);
8907 got_object_commit_close(commit);
8908 commit = NULL;
8909 if (error)
8910 goto done;
8911 } else {
8912 if (edit_in_progress) {
8913 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8914 goto done;
8917 error = got_ref_open(&branch, repo,
8918 got_worktree_get_head_ref_name(worktree), 0);
8919 if (error != NULL)
8920 goto done;
8922 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8923 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8924 "will not edit commit history of a branch outside "
8925 "the \"refs/heads/\" reference namespace");
8926 goto done;
8929 error = got_ref_resolve(&head_commit_id, repo, branch);
8930 got_ref_close(branch);
8931 branch = NULL;
8932 if (error)
8933 goto done;
8935 error = got_object_open_as_commit(&commit, repo,
8936 head_commit_id);
8937 if (error)
8938 goto done;
8939 parent_ids = got_object_commit_get_parent_ids(commit);
8940 pid = SIMPLEQ_FIRST(parent_ids);
8941 if (pid == NULL) {
8942 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8943 goto done;
8945 error = collect_commits(&commits, head_commit_id, pid->id,
8946 got_worktree_get_base_commit_id(worktree),
8947 got_worktree_get_path_prefix(worktree),
8948 GOT_ERR_HISTEDIT_PATH, repo);
8949 got_object_commit_close(commit);
8950 commit = NULL;
8951 if (error)
8952 goto done;
8954 if (SIMPLEQ_EMPTY(&commits)) {
8955 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8956 goto done;
8959 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8960 &base_commit_id, &fileindex, worktree, repo);
8961 if (error)
8962 goto done;
8964 if (edit_script_path) {
8965 error = histedit_load_list(&histedit_cmds,
8966 edit_script_path, repo);
8967 if (error) {
8968 got_worktree_histedit_abort(worktree, fileindex,
8969 repo, branch, base_commit_id,
8970 update_progress, &upa);
8971 print_update_progress_stats(&upa);
8972 goto done;
8974 } else {
8975 const char *branch_name;
8976 branch_name = got_ref_get_symref_target(branch);
8977 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8978 branch_name += 11;
8979 error = histedit_edit_script(&histedit_cmds, &commits,
8980 branch_name, edit_logmsg_only, fold_only, repo);
8981 if (error) {
8982 got_worktree_histedit_abort(worktree, fileindex,
8983 repo, branch, base_commit_id,
8984 update_progress, &upa);
8985 print_update_progress_stats(&upa);
8986 goto done;
8991 error = histedit_save_list(&histedit_cmds, worktree,
8992 repo);
8993 if (error) {
8994 got_worktree_histedit_abort(worktree, fileindex,
8995 repo, branch, base_commit_id,
8996 update_progress, &upa);
8997 print_update_progress_stats(&upa);
8998 goto done;
9003 error = histedit_check_script(&histedit_cmds, &commits, repo);
9004 if (error)
9005 goto done;
9007 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
9008 if (resume_commit_id) {
9009 if (got_object_id_cmp(hle->commit_id,
9010 resume_commit_id) != 0)
9011 continue;
9013 resume_commit_id = NULL;
9014 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
9015 hle->cmd->code == GOT_HISTEDIT_FOLD) {
9016 error = histedit_skip_commit(hle, worktree,
9017 repo);
9018 if (error)
9019 goto done;
9020 } else {
9021 struct got_pathlist_head paths;
9022 int have_changes = 0;
9024 TAILQ_INIT(&paths);
9025 error = got_pathlist_append(&paths, "", NULL);
9026 if (error)
9027 goto done;
9028 error = got_worktree_status(worktree, &paths,
9029 repo, check_local_changes, &have_changes,
9030 check_cancelled, NULL);
9031 got_pathlist_free(&paths);
9032 if (error) {
9033 if (error->code != GOT_ERR_CANCELLED)
9034 goto done;
9035 if (sigint_received || sigpipe_received)
9036 goto done;
9038 if (have_changes) {
9039 error = histedit_commit(NULL, worktree,
9040 fileindex, tmp_branch, hle, repo);
9041 if (error)
9042 goto done;
9043 } else {
9044 error = got_object_open_as_commit(
9045 &commit, repo, hle->commit_id);
9046 if (error)
9047 goto done;
9048 error = show_histedit_progress(commit,
9049 hle, NULL);
9050 got_object_commit_close(commit);
9051 commit = NULL;
9052 if (error)
9053 goto done;
9056 continue;
9059 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
9060 error = histedit_skip_commit(hle, worktree, repo);
9061 if (error)
9062 goto done;
9063 continue;
9066 error = got_object_open_as_commit(&commit, repo,
9067 hle->commit_id);
9068 if (error)
9069 goto done;
9070 parent_ids = got_object_commit_get_parent_ids(commit);
9071 pid = SIMPLEQ_FIRST(parent_ids);
9073 error = got_worktree_histedit_merge_files(&merged_paths,
9074 worktree, fileindex, pid->id, hle->commit_id, repo,
9075 update_progress, &upa, check_cancelled, NULL);
9076 if (error)
9077 goto done;
9078 got_object_commit_close(commit);
9079 commit = NULL;
9081 print_update_progress_stats(&upa);
9082 if (upa.conflicts > 0)
9083 rebase_status = GOT_STATUS_CONFLICT;
9085 if (rebase_status == GOT_STATUS_CONFLICT) {
9086 error = show_rebase_merge_conflict(hle->commit_id,
9087 repo);
9088 if (error)
9089 goto done;
9090 got_worktree_rebase_pathlist_free(&merged_paths);
9091 break;
9094 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
9095 char *id_str;
9096 error = got_object_id_str(&id_str, hle->commit_id);
9097 if (error)
9098 goto done;
9099 printf("Stopping histedit for amending commit %s\n",
9100 id_str);
9101 free(id_str);
9102 got_worktree_rebase_pathlist_free(&merged_paths);
9103 error = got_worktree_histedit_postpone(worktree,
9104 fileindex);
9105 goto done;
9108 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
9109 error = histedit_skip_commit(hle, worktree, repo);
9110 if (error)
9111 goto done;
9112 continue;
9115 error = histedit_commit(&merged_paths, worktree, fileindex,
9116 tmp_branch, hle, repo);
9117 got_worktree_rebase_pathlist_free(&merged_paths);
9118 if (error)
9119 goto done;
9122 if (rebase_status == GOT_STATUS_CONFLICT) {
9123 error = got_worktree_histedit_postpone(worktree, fileindex);
9124 if (error)
9125 goto done;
9126 error = got_error_msg(GOT_ERR_CONFLICTS,
9127 "conflicts must be resolved before histedit can continue");
9128 } else
9129 error = histedit_complete(worktree, fileindex, tmp_branch,
9130 branch, repo);
9131 done:
9132 got_object_id_queue_free(&commits);
9133 histedit_free_list(&histedit_cmds);
9134 free(head_commit_id);
9135 free(base_commit_id);
9136 free(resume_commit_id);
9137 if (commit)
9138 got_object_commit_close(commit);
9139 if (branch)
9140 got_ref_close(branch);
9141 if (tmp_branch)
9142 got_ref_close(tmp_branch);
9143 if (worktree)
9144 got_worktree_close(worktree);
9145 if (repo)
9146 got_repo_close(repo);
9147 return error;
9150 __dead static void
9151 usage_integrate(void)
9153 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
9154 exit(1);
9157 static const struct got_error *
9158 cmd_integrate(int argc, char *argv[])
9160 const struct got_error *error = NULL;
9161 struct got_repository *repo = NULL;
9162 struct got_worktree *worktree = NULL;
9163 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
9164 const char *branch_arg = NULL;
9165 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
9166 struct got_fileindex *fileindex = NULL;
9167 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
9168 int ch;
9169 struct got_update_progress_arg upa;
9171 while ((ch = getopt(argc, argv, "")) != -1) {
9172 switch (ch) {
9173 default:
9174 usage_integrate();
9175 /* NOTREACHED */
9179 argc -= optind;
9180 argv += optind;
9182 if (argc != 1)
9183 usage_integrate();
9184 branch_arg = argv[0];
9185 #ifndef PROFILE
9186 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9187 "unveil", NULL) == -1)
9188 err(1, "pledge");
9189 #endif
9190 cwd = getcwd(NULL, 0);
9191 if (cwd == NULL) {
9192 error = got_error_from_errno("getcwd");
9193 goto done;
9196 error = got_worktree_open(&worktree, cwd);
9197 if (error) {
9198 if (error->code == GOT_ERR_NOT_WORKTREE)
9199 error = wrap_not_worktree_error(error, "integrate",
9200 cwd);
9201 goto done;
9204 error = check_rebase_or_histedit_in_progress(worktree);
9205 if (error)
9206 goto done;
9208 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9209 NULL);
9210 if (error != NULL)
9211 goto done;
9213 error = apply_unveil(got_repo_get_path(repo), 0,
9214 got_worktree_get_root_path(worktree));
9215 if (error)
9216 goto done;
9218 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
9219 error = got_error_from_errno("asprintf");
9220 goto done;
9223 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
9224 &base_branch_ref, worktree, refname, repo);
9225 if (error)
9226 goto done;
9228 refname = strdup(got_ref_get_name(branch_ref));
9229 if (refname == NULL) {
9230 error = got_error_from_errno("strdup");
9231 got_worktree_integrate_abort(worktree, fileindex, repo,
9232 branch_ref, base_branch_ref);
9233 goto done;
9235 base_refname = strdup(got_ref_get_name(base_branch_ref));
9236 if (base_refname == NULL) {
9237 error = got_error_from_errno("strdup");
9238 got_worktree_integrate_abort(worktree, fileindex, repo,
9239 branch_ref, base_branch_ref);
9240 goto done;
9243 error = got_ref_resolve(&commit_id, repo, branch_ref);
9244 if (error)
9245 goto done;
9247 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
9248 if (error)
9249 goto done;
9251 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
9252 error = got_error_msg(GOT_ERR_SAME_BRANCH,
9253 "specified branch has already been integrated");
9254 got_worktree_integrate_abort(worktree, fileindex, repo,
9255 branch_ref, base_branch_ref);
9256 goto done;
9259 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
9260 if (error) {
9261 if (error->code == GOT_ERR_ANCESTRY)
9262 error = got_error(GOT_ERR_REBASE_REQUIRED);
9263 got_worktree_integrate_abort(worktree, fileindex, repo,
9264 branch_ref, base_branch_ref);
9265 goto done;
9268 memset(&upa, 0, sizeof(upa));
9269 error = got_worktree_integrate_continue(worktree, fileindex, repo,
9270 branch_ref, base_branch_ref, update_progress, &upa,
9271 check_cancelled, NULL);
9272 if (error)
9273 goto done;
9275 printf("Integrated %s into %s\n", refname, base_refname);
9276 print_update_progress_stats(&upa);
9277 done:
9278 if (repo)
9279 got_repo_close(repo);
9280 if (worktree)
9281 got_worktree_close(worktree);
9282 free(cwd);
9283 free(base_commit_id);
9284 free(commit_id);
9285 free(refname);
9286 free(base_refname);
9287 return error;
9290 __dead static void
9291 usage_stage(void)
9293 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
9294 "[-S] [file-path ...]\n",
9295 getprogname());
9296 exit(1);
9299 static const struct got_error *
9300 print_stage(void *arg, unsigned char status, unsigned char staged_status,
9301 const char *path, struct got_object_id *blob_id,
9302 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
9303 int dirfd, const char *de_name)
9305 const struct got_error *err = NULL;
9306 char *id_str = NULL;
9308 if (staged_status != GOT_STATUS_ADD &&
9309 staged_status != GOT_STATUS_MODIFY &&
9310 staged_status != GOT_STATUS_DELETE)
9311 return NULL;
9313 if (staged_status == GOT_STATUS_ADD ||
9314 staged_status == GOT_STATUS_MODIFY)
9315 err = got_object_id_str(&id_str, staged_blob_id);
9316 else
9317 err = got_object_id_str(&id_str, blob_id);
9318 if (err)
9319 return err;
9321 printf("%s %c %s\n", id_str, staged_status, path);
9322 free(id_str);
9323 return NULL;
9326 static const struct got_error *
9327 cmd_stage(int argc, char *argv[])
9329 const struct got_error *error = NULL;
9330 struct got_repository *repo = NULL;
9331 struct got_worktree *worktree = NULL;
9332 char *cwd = NULL;
9333 struct got_pathlist_head paths;
9334 struct got_pathlist_entry *pe;
9335 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
9336 FILE *patch_script_file = NULL;
9337 const char *patch_script_path = NULL;
9338 struct choose_patch_arg cpa;
9340 TAILQ_INIT(&paths);
9342 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
9343 switch (ch) {
9344 case 'l':
9345 list_stage = 1;
9346 break;
9347 case 'p':
9348 pflag = 1;
9349 break;
9350 case 'F':
9351 patch_script_path = optarg;
9352 break;
9353 case 'S':
9354 allow_bad_symlinks = 1;
9355 break;
9356 default:
9357 usage_stage();
9358 /* NOTREACHED */
9362 argc -= optind;
9363 argv += optind;
9365 #ifndef PROFILE
9366 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9367 "unveil", NULL) == -1)
9368 err(1, "pledge");
9369 #endif
9370 if (list_stage && (pflag || patch_script_path))
9371 errx(1, "-l option cannot be used with other options");
9372 if (patch_script_path && !pflag)
9373 errx(1, "-F option can only be used together with -p option");
9375 cwd = getcwd(NULL, 0);
9376 if (cwd == NULL) {
9377 error = got_error_from_errno("getcwd");
9378 goto done;
9381 error = got_worktree_open(&worktree, cwd);
9382 if (error) {
9383 if (error->code == GOT_ERR_NOT_WORKTREE)
9384 error = wrap_not_worktree_error(error, "stage", cwd);
9385 goto done;
9388 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9389 NULL);
9390 if (error != NULL)
9391 goto done;
9393 if (patch_script_path) {
9394 patch_script_file = fopen(patch_script_path, "r");
9395 if (patch_script_file == NULL) {
9396 error = got_error_from_errno2("fopen",
9397 patch_script_path);
9398 goto done;
9401 error = apply_unveil(got_repo_get_path(repo), 0,
9402 got_worktree_get_root_path(worktree));
9403 if (error)
9404 goto done;
9406 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9407 if (error)
9408 goto done;
9410 if (list_stage)
9411 error = got_worktree_status(worktree, &paths, repo,
9412 print_stage, NULL, check_cancelled, NULL);
9413 else {
9414 cpa.patch_script_file = patch_script_file;
9415 cpa.action = "stage";
9416 error = got_worktree_stage(worktree, &paths,
9417 pflag ? NULL : print_status, NULL,
9418 pflag ? choose_patch : NULL, &cpa,
9419 allow_bad_symlinks, repo);
9421 done:
9422 if (patch_script_file && fclose(patch_script_file) == EOF &&
9423 error == NULL)
9424 error = got_error_from_errno2("fclose", patch_script_path);
9425 if (repo)
9426 got_repo_close(repo);
9427 if (worktree)
9428 got_worktree_close(worktree);
9429 TAILQ_FOREACH(pe, &paths, entry)
9430 free((char *)pe->path);
9431 got_pathlist_free(&paths);
9432 free(cwd);
9433 return error;
9436 __dead static void
9437 usage_unstage(void)
9439 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
9440 "[file-path ...]\n",
9441 getprogname());
9442 exit(1);
9446 static const struct got_error *
9447 cmd_unstage(int argc, char *argv[])
9449 const struct got_error *error = NULL;
9450 struct got_repository *repo = NULL;
9451 struct got_worktree *worktree = NULL;
9452 char *cwd = NULL;
9453 struct got_pathlist_head paths;
9454 struct got_pathlist_entry *pe;
9455 int ch, pflag = 0;
9456 struct got_update_progress_arg upa;
9457 FILE *patch_script_file = NULL;
9458 const char *patch_script_path = NULL;
9459 struct choose_patch_arg cpa;
9461 TAILQ_INIT(&paths);
9463 while ((ch = getopt(argc, argv, "pF:")) != -1) {
9464 switch (ch) {
9465 case 'p':
9466 pflag = 1;
9467 break;
9468 case 'F':
9469 patch_script_path = optarg;
9470 break;
9471 default:
9472 usage_unstage();
9473 /* NOTREACHED */
9477 argc -= optind;
9478 argv += optind;
9480 #ifndef PROFILE
9481 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9482 "unveil", NULL) == -1)
9483 err(1, "pledge");
9484 #endif
9485 if (patch_script_path && !pflag)
9486 errx(1, "-F option can only be used together with -p option");
9488 cwd = getcwd(NULL, 0);
9489 if (cwd == NULL) {
9490 error = got_error_from_errno("getcwd");
9491 goto done;
9494 error = got_worktree_open(&worktree, cwd);
9495 if (error) {
9496 if (error->code == GOT_ERR_NOT_WORKTREE)
9497 error = wrap_not_worktree_error(error, "unstage", cwd);
9498 goto done;
9501 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9502 NULL);
9503 if (error != NULL)
9504 goto done;
9506 if (patch_script_path) {
9507 patch_script_file = fopen(patch_script_path, "r");
9508 if (patch_script_file == NULL) {
9509 error = got_error_from_errno2("fopen",
9510 patch_script_path);
9511 goto done;
9515 error = apply_unveil(got_repo_get_path(repo), 0,
9516 got_worktree_get_root_path(worktree));
9517 if (error)
9518 goto done;
9520 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9521 if (error)
9522 goto done;
9524 cpa.patch_script_file = patch_script_file;
9525 cpa.action = "unstage";
9526 memset(&upa, 0, sizeof(upa));
9527 error = got_worktree_unstage(worktree, &paths, update_progress,
9528 &upa, pflag ? choose_patch : NULL, &cpa, repo);
9529 if (!error)
9530 print_update_progress_stats(&upa);
9531 done:
9532 if (patch_script_file && fclose(patch_script_file) == EOF &&
9533 error == NULL)
9534 error = got_error_from_errno2("fclose", patch_script_path);
9535 if (repo)
9536 got_repo_close(repo);
9537 if (worktree)
9538 got_worktree_close(worktree);
9539 TAILQ_FOREACH(pe, &paths, entry)
9540 free((char *)pe->path);
9541 got_pathlist_free(&paths);
9542 free(cwd);
9543 return error;
9546 __dead static void
9547 usage_cat(void)
9549 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
9550 "arg1 [arg2 ...]\n", getprogname());
9551 exit(1);
9554 static const struct got_error *
9555 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9557 const struct got_error *err;
9558 struct got_blob_object *blob;
9560 err = got_object_open_as_blob(&blob, repo, id, 8192);
9561 if (err)
9562 return err;
9564 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
9565 got_object_blob_close(blob);
9566 return err;
9569 static const struct got_error *
9570 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9572 const struct got_error *err;
9573 struct got_tree_object *tree;
9574 int nentries, i;
9576 err = got_object_open_as_tree(&tree, repo, id);
9577 if (err)
9578 return err;
9580 nentries = got_object_tree_get_nentries(tree);
9581 for (i = 0; i < nentries; i++) {
9582 struct got_tree_entry *te;
9583 char *id_str;
9584 if (sigint_received || sigpipe_received)
9585 break;
9586 te = got_object_tree_get_entry(tree, i);
9587 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
9588 if (err)
9589 break;
9590 fprintf(outfile, "%s %.7o %s\n", id_str,
9591 got_tree_entry_get_mode(te),
9592 got_tree_entry_get_name(te));
9593 free(id_str);
9596 got_object_tree_close(tree);
9597 return err;
9600 static const struct got_error *
9601 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9603 const struct got_error *err;
9604 struct got_commit_object *commit;
9605 const struct got_object_id_queue *parent_ids;
9606 struct got_object_qid *pid;
9607 char *id_str = NULL;
9608 const char *logmsg = NULL;
9610 err = got_object_open_as_commit(&commit, repo, id);
9611 if (err)
9612 return err;
9614 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
9615 if (err)
9616 goto done;
9618 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
9619 parent_ids = got_object_commit_get_parent_ids(commit);
9620 fprintf(outfile, "numparents %d\n",
9621 got_object_commit_get_nparents(commit));
9622 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
9623 char *pid_str;
9624 err = got_object_id_str(&pid_str, pid->id);
9625 if (err)
9626 goto done;
9627 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
9628 free(pid_str);
9630 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
9631 got_object_commit_get_author(commit),
9632 (long long)got_object_commit_get_author_time(commit));
9634 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
9635 got_object_commit_get_author(commit),
9636 (long long)got_object_commit_get_committer_time(commit));
9638 logmsg = got_object_commit_get_logmsg_raw(commit);
9639 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
9640 fprintf(outfile, "%s", logmsg);
9641 done:
9642 free(id_str);
9643 got_object_commit_close(commit);
9644 return err;
9647 static const struct got_error *
9648 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9650 const struct got_error *err;
9651 struct got_tag_object *tag;
9652 char *id_str = NULL;
9653 const char *tagmsg = NULL;
9655 err = got_object_open_as_tag(&tag, repo, id);
9656 if (err)
9657 return err;
9659 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
9660 if (err)
9661 goto done;
9663 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
9665 switch (got_object_tag_get_object_type(tag)) {
9666 case GOT_OBJ_TYPE_BLOB:
9667 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9668 GOT_OBJ_LABEL_BLOB);
9669 break;
9670 case GOT_OBJ_TYPE_TREE:
9671 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9672 GOT_OBJ_LABEL_TREE);
9673 break;
9674 case GOT_OBJ_TYPE_COMMIT:
9675 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9676 GOT_OBJ_LABEL_COMMIT);
9677 break;
9678 case GOT_OBJ_TYPE_TAG:
9679 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9680 GOT_OBJ_LABEL_TAG);
9681 break;
9682 default:
9683 break;
9686 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
9687 got_object_tag_get_name(tag));
9689 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
9690 got_object_tag_get_tagger(tag),
9691 (long long)got_object_tag_get_tagger_time(tag));
9693 tagmsg = got_object_tag_get_message(tag);
9694 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
9695 fprintf(outfile, "%s", tagmsg);
9696 done:
9697 free(id_str);
9698 got_object_tag_close(tag);
9699 return err;
9702 static const struct got_error *
9703 cmd_cat(int argc, char *argv[])
9705 const struct got_error *error;
9706 struct got_repository *repo = NULL;
9707 struct got_worktree *worktree = NULL;
9708 char *cwd = NULL, *repo_path = NULL, *label = NULL;
9709 const char *commit_id_str = NULL;
9710 struct got_object_id *id = NULL, *commit_id = NULL;
9711 int ch, obj_type, i, force_path = 0;
9712 struct got_reflist_head refs;
9714 TAILQ_INIT(&refs);
9716 #ifndef PROFILE
9717 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9718 NULL) == -1)
9719 err(1, "pledge");
9720 #endif
9722 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
9723 switch (ch) {
9724 case 'c':
9725 commit_id_str = optarg;
9726 break;
9727 case 'r':
9728 repo_path = realpath(optarg, NULL);
9729 if (repo_path == NULL)
9730 return got_error_from_errno2("realpath",
9731 optarg);
9732 got_path_strip_trailing_slashes(repo_path);
9733 break;
9734 case 'P':
9735 force_path = 1;
9736 break;
9737 default:
9738 usage_cat();
9739 /* NOTREACHED */
9743 argc -= optind;
9744 argv += optind;
9746 cwd = getcwd(NULL, 0);
9747 if (cwd == NULL) {
9748 error = got_error_from_errno("getcwd");
9749 goto done;
9751 error = got_worktree_open(&worktree, cwd);
9752 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9753 goto done;
9754 if (worktree) {
9755 if (repo_path == NULL) {
9756 repo_path = strdup(
9757 got_worktree_get_repo_path(worktree));
9758 if (repo_path == NULL) {
9759 error = got_error_from_errno("strdup");
9760 goto done;
9765 if (repo_path == NULL) {
9766 repo_path = getcwd(NULL, 0);
9767 if (repo_path == NULL)
9768 return got_error_from_errno("getcwd");
9771 error = got_repo_open(&repo, repo_path, NULL);
9772 free(repo_path);
9773 if (error != NULL)
9774 goto done;
9776 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9777 if (error)
9778 goto done;
9780 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9781 if (error)
9782 goto done;
9784 if (commit_id_str == NULL)
9785 commit_id_str = GOT_REF_HEAD;
9786 error = got_repo_match_object_id(&commit_id, NULL,
9787 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
9788 if (error)
9789 goto done;
9791 for (i = 0; i < argc; i++) {
9792 if (force_path) {
9793 error = got_object_id_by_path(&id, repo, commit_id,
9794 argv[i]);
9795 if (error)
9796 break;
9797 } else {
9798 error = got_repo_match_object_id(&id, &label, argv[i],
9799 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
9800 repo);
9801 if (error) {
9802 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9803 error->code != GOT_ERR_NOT_REF)
9804 break;
9805 error = got_object_id_by_path(&id, repo,
9806 commit_id, argv[i]);
9807 if (error)
9808 break;
9812 error = got_object_get_type(&obj_type, repo, id);
9813 if (error)
9814 break;
9816 switch (obj_type) {
9817 case GOT_OBJ_TYPE_BLOB:
9818 error = cat_blob(id, repo, stdout);
9819 break;
9820 case GOT_OBJ_TYPE_TREE:
9821 error = cat_tree(id, repo, stdout);
9822 break;
9823 case GOT_OBJ_TYPE_COMMIT:
9824 error = cat_commit(id, repo, stdout);
9825 break;
9826 case GOT_OBJ_TYPE_TAG:
9827 error = cat_tag(id, repo, stdout);
9828 break;
9829 default:
9830 error = got_error(GOT_ERR_OBJ_TYPE);
9831 break;
9833 if (error)
9834 break;
9835 free(label);
9836 label = NULL;
9837 free(id);
9838 id = NULL;
9840 done:
9841 free(label);
9842 free(id);
9843 free(commit_id);
9844 if (worktree)
9845 got_worktree_close(worktree);
9846 if (repo) {
9847 const struct got_error *repo_error;
9848 repo_error = got_repo_close(repo);
9849 if (error == NULL)
9850 error = repo_error;
9852 got_ref_list_free(&refs);
9853 return error;
9856 __dead static void
9857 usage_info(void)
9859 fprintf(stderr, "usage: %s info [path ...]\n",
9860 getprogname());
9861 exit(1);
9864 static const struct got_error *
9865 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
9866 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9867 struct got_object_id *commit_id)
9869 const struct got_error *err = NULL;
9870 char *id_str = NULL;
9871 char datebuf[128];
9872 struct tm mytm, *tm;
9873 struct got_pathlist_head *paths = arg;
9874 struct got_pathlist_entry *pe;
9877 * Clear error indication from any of the path arguments which
9878 * would cause this file index entry to be displayed.
9880 TAILQ_FOREACH(pe, paths, entry) {
9881 if (got_path_cmp(path, pe->path, strlen(path),
9882 pe->path_len) == 0 ||
9883 got_path_is_child(path, pe->path, pe->path_len))
9884 pe->data = NULL; /* no error */
9887 printf(GOT_COMMIT_SEP_STR);
9888 if (S_ISLNK(mode))
9889 printf("symlink: %s\n", path);
9890 else if (S_ISREG(mode)) {
9891 printf("file: %s\n", path);
9892 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
9893 } else if (S_ISDIR(mode))
9894 printf("directory: %s\n", path);
9895 else
9896 printf("something: %s\n", path);
9898 tm = localtime_r(&mtime, &mytm);
9899 if (tm == NULL)
9900 return NULL;
9901 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) >= sizeof(datebuf))
9902 return got_error(GOT_ERR_NO_SPACE);
9903 printf("timestamp: %s\n", datebuf);
9905 if (blob_id) {
9906 err = got_object_id_str(&id_str, blob_id);
9907 if (err)
9908 return err;
9909 printf("based on blob: %s\n", id_str);
9910 free(id_str);
9913 if (staged_blob_id) {
9914 err = got_object_id_str(&id_str, staged_blob_id);
9915 if (err)
9916 return err;
9917 printf("based on staged blob: %s\n", id_str);
9918 free(id_str);
9921 if (commit_id) {
9922 err = got_object_id_str(&id_str, commit_id);
9923 if (err)
9924 return err;
9925 printf("based on commit: %s\n", id_str);
9926 free(id_str);
9929 return NULL;
9932 static const struct got_error *
9933 cmd_info(int argc, char *argv[])
9935 const struct got_error *error = NULL;
9936 struct got_worktree *worktree = NULL;
9937 char *cwd = NULL, *id_str = NULL;
9938 struct got_pathlist_head paths;
9939 struct got_pathlist_entry *pe;
9940 char *uuidstr = NULL;
9941 int ch, show_files = 0;
9943 TAILQ_INIT(&paths);
9945 while ((ch = getopt(argc, argv, "")) != -1) {
9946 switch (ch) {
9947 default:
9948 usage_info();
9949 /* NOTREACHED */
9953 argc -= optind;
9954 argv += optind;
9956 #ifndef PROFILE
9957 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
9958 NULL) == -1)
9959 err(1, "pledge");
9960 #endif
9961 cwd = getcwd(NULL, 0);
9962 if (cwd == NULL) {
9963 error = got_error_from_errno("getcwd");
9964 goto done;
9967 error = got_worktree_open(&worktree, cwd);
9968 if (error) {
9969 if (error->code == GOT_ERR_NOT_WORKTREE)
9970 error = wrap_not_worktree_error(error, "status", cwd);
9971 goto done;
9974 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9975 if (error)
9976 goto done;
9978 if (argc >= 1) {
9979 error = get_worktree_paths_from_argv(&paths, argc, argv,
9980 worktree);
9981 if (error)
9982 goto done;
9983 show_files = 1;
9986 error = got_object_id_str(&id_str,
9987 got_worktree_get_base_commit_id(worktree));
9988 if (error)
9989 goto done;
9991 error = got_worktree_get_uuid(&uuidstr, worktree);
9992 if (error)
9993 goto done;
9995 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9996 printf("work tree base commit: %s\n", id_str);
9997 printf("work tree path prefix: %s\n",
9998 got_worktree_get_path_prefix(worktree));
9999 printf("work tree branch reference: %s\n",
10000 got_worktree_get_head_ref_name(worktree));
10001 printf("work tree UUID: %s\n", uuidstr);
10002 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
10004 if (show_files) {
10005 struct got_pathlist_entry *pe;
10006 TAILQ_FOREACH(pe, &paths, entry) {
10007 if (pe->path_len == 0)
10008 continue;
10010 * Assume this path will fail. This will be corrected
10011 * in print_path_info() in case the path does suceeed.
10013 pe->data = (void *)got_error_path(pe->path,
10014 GOT_ERR_BAD_PATH);
10016 error = got_worktree_path_info(worktree, &paths,
10017 print_path_info, &paths, check_cancelled, NULL);
10018 if (error)
10019 goto done;
10020 TAILQ_FOREACH(pe, &paths, entry) {
10021 if (pe->data != NULL) {
10022 error = pe->data; /* bad path */
10023 break;
10027 done:
10028 TAILQ_FOREACH(pe, &paths, entry)
10029 free((char *)pe->path);
10030 got_pathlist_free(&paths);
10031 free(cwd);
10032 free(id_str);
10033 free(uuidstr);
10034 return error;