Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/param.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
41 #include <util.h>
43 #include "got_version.h"
44 #include "got_error.h"
45 #include "got_object.h"
46 #include "got_reference.h"
47 #include "got_repository.h"
48 #include "got_path.h"
49 #include "got_cancel.h"
50 #include "got_worktree.h"
51 #include "got_diff.h"
52 #include "got_commit_graph.h"
53 #include "got_fetch.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_opentemp.h"
57 #include "got_gotconfig.h"
59 #ifndef nitems
60 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
61 #endif
63 static volatile sig_atomic_t sigint_received;
64 static volatile sig_atomic_t sigpipe_received;
66 static void
67 catch_sigint(int signo)
68 {
69 sigint_received = 1;
70 }
72 static void
73 catch_sigpipe(int signo)
74 {
75 sigpipe_received = 1;
76 }
79 struct got_cmd {
80 const char *cmd_name;
81 const struct got_error *(*cmd_main)(int, char *[]);
82 void (*cmd_usage)(void);
83 const char *cmd_alias;
84 };
86 __dead static void usage(int, int);
87 __dead static void usage_init(void);
88 __dead static void usage_import(void);
89 __dead static void usage_clone(void);
90 __dead static void usage_fetch(void);
91 __dead static void usage_checkout(void);
92 __dead static void usage_update(void);
93 __dead static void usage_log(void);
94 __dead static void usage_diff(void);
95 __dead static void usage_blame(void);
96 __dead static void usage_tree(void);
97 __dead static void usage_status(void);
98 __dead static void usage_ref(void);
99 __dead static void usage_branch(void);
100 __dead static void usage_tag(void);
101 __dead static void usage_add(void);
102 __dead static void usage_remove(void);
103 __dead static void usage_revert(void);
104 __dead static void usage_commit(void);
105 __dead static void usage_cherrypick(void);
106 __dead static void usage_backout(void);
107 __dead static void usage_rebase(void);
108 __dead static void usage_histedit(void);
109 __dead static void usage_integrate(void);
110 __dead static void usage_stage(void);
111 __dead static void usage_unstage(void);
112 __dead static void usage_cat(void);
113 __dead static void usage_info(void);
115 static const struct got_error* cmd_init(int, char *[]);
116 static const struct got_error* cmd_import(int, char *[]);
117 static const struct got_error* cmd_clone(int, char *[]);
118 static const struct got_error* cmd_fetch(int, char *[]);
119 static const struct got_error* cmd_checkout(int, char *[]);
120 static const struct got_error* cmd_update(int, char *[]);
121 static const struct got_error* cmd_log(int, char *[]);
122 static const struct got_error* cmd_diff(int, char *[]);
123 static const struct got_error* cmd_blame(int, char *[]);
124 static const struct got_error* cmd_tree(int, char *[]);
125 static const struct got_error* cmd_status(int, char *[]);
126 static const struct got_error* cmd_ref(int, char *[]);
127 static const struct got_error* cmd_branch(int, char *[]);
128 static const struct got_error* cmd_tag(int, char *[]);
129 static const struct got_error* cmd_add(int, char *[]);
130 static const struct got_error* cmd_remove(int, char *[]);
131 static const struct got_error* cmd_revert(int, char *[]);
132 static const struct got_error* cmd_commit(int, char *[]);
133 static const struct got_error* cmd_cherrypick(int, char *[]);
134 static const struct got_error* cmd_backout(int, char *[]);
135 static const struct got_error* cmd_rebase(int, char *[]);
136 static const struct got_error* cmd_histedit(int, char *[]);
137 static const struct got_error* cmd_integrate(int, char *[]);
138 static const struct got_error* cmd_stage(int, char *[]);
139 static const struct got_error* cmd_unstage(int, char *[]);
140 static const struct got_error* cmd_cat(int, char *[]);
141 static const struct got_error* cmd_info(int, char *[]);
143 static struct got_cmd got_commands[] = {
144 { "init", cmd_init, usage_init, "" },
145 { "import", cmd_import, usage_import, "im" },
146 { "clone", cmd_clone, usage_clone, "cl" },
147 { "fetch", cmd_fetch, usage_fetch, "fe" },
148 { "checkout", cmd_checkout, usage_checkout, "co" },
149 { "update", cmd_update, usage_update, "up" },
150 { "log", cmd_log, usage_log, "" },
151 { "diff", cmd_diff, usage_diff, "di" },
152 { "blame", cmd_blame, usage_blame, "bl" },
153 { "tree", cmd_tree, usage_tree, "tr" },
154 { "status", cmd_status, usage_status, "st" },
155 { "ref", cmd_ref, usage_ref, "" },
156 { "branch", cmd_branch, usage_branch, "br" },
157 { "tag", cmd_tag, usage_tag, "" },
158 { "add", cmd_add, usage_add, "" },
159 { "remove", cmd_remove, usage_remove, "rm" },
160 { "revert", cmd_revert, usage_revert, "rv" },
161 { "commit", cmd_commit, usage_commit, "ci" },
162 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
163 { "backout", cmd_backout, usage_backout, "bo" },
164 { "rebase", cmd_rebase, usage_rebase, "rb" },
165 { "histedit", cmd_histedit, usage_histedit, "he" },
166 { "integrate", cmd_integrate, usage_integrate,"ig" },
167 { "stage", cmd_stage, usage_stage, "sg" },
168 { "unstage", cmd_unstage, usage_unstage, "ug" },
169 { "cat", cmd_cat, usage_cat, "" },
170 { "info", cmd_info, usage_info, "" },
171 };
173 static void
174 list_commands(FILE *fp)
176 size_t i;
178 fprintf(fp, "commands:");
179 for (i = 0; i < nitems(got_commands); i++) {
180 struct got_cmd *cmd = &got_commands[i];
181 fprintf(fp, " %s", cmd->cmd_name);
183 fputc('\n', fp);
186 __dead static void
187 option_conflict(char a, char b)
189 errx(1, "-%c and -%c options are mutually exclusive", a, b);
192 int
193 main(int argc, char *argv[])
195 struct got_cmd *cmd;
196 size_t i;
197 int ch;
198 int hflag = 0, Vflag = 0;
199 static struct option longopts[] = {
200 { "version", no_argument, NULL, 'V' },
201 { NULL, 0, NULL, 0 }
202 };
204 setlocale(LC_CTYPE, "");
206 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
207 switch (ch) {
208 case 'h':
209 hflag = 1;
210 break;
211 case 'V':
212 Vflag = 1;
213 break;
214 default:
215 usage(hflag, 1);
216 /* NOTREACHED */
220 argc -= optind;
221 argv += optind;
222 optind = 1;
223 optreset = 1;
225 if (Vflag) {
226 got_version_print_str();
227 return 0;
230 if (argc <= 0)
231 usage(hflag, hflag ? 0 : 1);
233 signal(SIGINT, catch_sigint);
234 signal(SIGPIPE, catch_sigpipe);
236 for (i = 0; i < nitems(got_commands); i++) {
237 const struct got_error *error;
239 cmd = &got_commands[i];
241 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
242 strcmp(cmd->cmd_alias, argv[0]) != 0)
243 continue;
245 if (hflag)
246 got_commands[i].cmd_usage();
248 error = got_commands[i].cmd_main(argc, argv);
249 if (error && error->code != GOT_ERR_CANCELLED &&
250 error->code != GOT_ERR_PRIVSEP_EXIT &&
251 !(sigpipe_received &&
252 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
253 !(sigint_received &&
254 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
255 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
256 return 1;
259 return 0;
262 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
263 list_commands(stderr);
264 return 1;
267 __dead static void
268 usage(int hflag, int status)
270 FILE *fp = (status == 0) ? stdout : stderr;
272 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
273 getprogname());
274 if (hflag)
275 list_commands(fp);
276 exit(status);
279 static const struct got_error *
280 get_editor(char **abspath)
282 const struct got_error *err = NULL;
283 const char *editor;
285 *abspath = NULL;
287 editor = getenv("VISUAL");
288 if (editor == NULL)
289 editor = getenv("EDITOR");
291 if (editor) {
292 err = got_path_find_prog(abspath, editor);
293 if (err)
294 return err;
297 if (*abspath == NULL) {
298 *abspath = strdup("/bin/ed");
299 if (*abspath == NULL)
300 return got_error_from_errno("strdup");
303 return NULL;
306 static const struct got_error *
307 apply_unveil(const char *repo_path, int repo_read_only,
308 const char *worktree_path)
310 const struct got_error *err;
312 #ifdef PROFILE
313 if (unveil("gmon.out", "rwc") != 0)
314 return got_error_from_errno2("unveil", "gmon.out");
315 #endif
316 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
317 return got_error_from_errno2("unveil", repo_path);
319 if (worktree_path && unveil(worktree_path, "rwc") != 0)
320 return got_error_from_errno2("unveil", worktree_path);
322 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
323 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
325 err = got_privsep_unveil_exec_helpers();
326 if (err != NULL)
327 return err;
329 if (unveil(NULL, NULL) != 0)
330 return got_error_from_errno("unveil");
332 return NULL;
335 __dead static void
336 usage_init(void)
338 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
339 exit(1);
342 static const struct got_error *
343 cmd_init(int argc, char *argv[])
345 const struct got_error *error = NULL;
346 char *repo_path = NULL;
347 int ch;
349 while ((ch = getopt(argc, argv, "")) != -1) {
350 switch (ch) {
351 default:
352 usage_init();
353 /* NOTREACHED */
357 argc -= optind;
358 argv += optind;
360 #ifndef PROFILE
361 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
362 err(1, "pledge");
363 #endif
364 if (argc != 1)
365 usage_init();
367 repo_path = strdup(argv[0]);
368 if (repo_path == NULL)
369 return got_error_from_errno("strdup");
371 got_path_strip_trailing_slashes(repo_path);
373 error = got_path_mkdir(repo_path);
374 if (error &&
375 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
376 goto done;
378 error = apply_unveil(repo_path, 0, NULL);
379 if (error)
380 goto done;
382 error = got_repo_init(repo_path);
383 done:
384 free(repo_path);
385 return error;
388 __dead static void
389 usage_import(void)
391 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
392 "[-r repository-path] [-I pattern] path\n", getprogname());
393 exit(1);
396 int
397 spawn_editor(const char *editor, const char *file)
399 pid_t pid;
400 sig_t sighup, sigint, sigquit;
401 int st = -1;
403 sighup = signal(SIGHUP, SIG_IGN);
404 sigint = signal(SIGINT, SIG_IGN);
405 sigquit = signal(SIGQUIT, SIG_IGN);
407 switch (pid = fork()) {
408 case -1:
409 goto doneediting;
410 case 0:
411 execl(editor, editor, file, (char *)NULL);
412 _exit(127);
415 while (waitpid(pid, &st, 0) == -1)
416 if (errno != EINTR)
417 break;
419 doneediting:
420 (void)signal(SIGHUP, sighup);
421 (void)signal(SIGINT, sigint);
422 (void)signal(SIGQUIT, sigquit);
424 if (!WIFEXITED(st)) {
425 errno = EINTR;
426 return -1;
429 return WEXITSTATUS(st);
432 static const struct got_error *
433 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
434 const char *initial_content, size_t initial_content_len, int check_comments)
436 const struct got_error *err = NULL;
437 char *line = NULL;
438 size_t linesize = 0;
439 ssize_t linelen;
440 struct stat st, st2;
441 FILE *fp = NULL;
442 size_t len, logmsg_len;
443 char *initial_content_stripped = NULL, *buf = NULL, *s;
445 *logmsg = NULL;
447 if (stat(logmsg_path, &st) == -1)
448 return got_error_from_errno2("stat", logmsg_path);
450 if (spawn_editor(editor, logmsg_path) == -1)
451 return got_error_from_errno("failed spawning editor");
453 if (stat(logmsg_path, &st2) == -1)
454 return got_error_from_errno("stat");
456 if (st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
457 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
458 "no changes made to commit message, aborting");
460 /*
461 * Set up a stripped version of the initial content without comments
462 * and blank lines. We need this in order to check if the message
463 * has in fact been edited.
464 */
465 initial_content_stripped = malloc(initial_content_len + 1);
466 if (initial_content_stripped == NULL)
467 return got_error_from_errno("malloc");
468 initial_content_stripped[0] = '\0';
470 buf = strdup(initial_content);
471 if (buf == NULL) {
472 err = got_error_from_errno("strdup");
473 goto done;
475 s = buf;
476 len = 0;
477 while ((line = strsep(&s, "\n")) != NULL) {
478 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
479 continue; /* remove comments and leading empty lines */
480 len = strlcat(initial_content_stripped, line,
481 initial_content_len + 1);
482 if (len >= initial_content_len + 1) {
483 err = got_error(GOT_ERR_NO_SPACE);
484 goto done;
487 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
488 initial_content_stripped[len - 1] = '\0';
489 len--;
492 logmsg_len = st2.st_size;
493 *logmsg = malloc(logmsg_len + 1);
494 if (*logmsg == NULL)
495 return got_error_from_errno("malloc");
496 (*logmsg)[0] = '\0';
498 fp = fopen(logmsg_path, "r");
499 if (fp == NULL) {
500 err = got_error_from_errno("fopen");
501 goto done;
504 len = 0;
505 while ((linelen = getline(&line, &linesize, fp)) != -1) {
506 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
507 continue; /* remove comments and leading empty lines */
508 len = strlcat(*logmsg, line, logmsg_len + 1);
509 if (len >= logmsg_len + 1) {
510 err = got_error(GOT_ERR_NO_SPACE);
511 goto done;
514 free(line);
515 if (ferror(fp)) {
516 err = got_ferror(fp, GOT_ERR_IO);
517 goto done;
519 while (len > 0 && (*logmsg)[len - 1] == '\n') {
520 (*logmsg)[len - 1] = '\0';
521 len--;
524 if (len == 0) {
525 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
526 "commit message cannot be empty, aborting");
527 goto done;
529 if (check_comments && strcmp(*logmsg, initial_content_stripped) == 0)
530 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
531 "no changes made to commit message, aborting");
532 done:
533 free(initial_content_stripped);
534 free(buf);
535 if (fp && fclose(fp) == EOF && err == NULL)
536 err = got_error_from_errno("fclose");
537 if (err) {
538 free(*logmsg);
539 *logmsg = NULL;
541 return err;
544 static const struct got_error *
545 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
546 const char *path_dir, const char *branch_name)
548 char *initial_content = NULL;
549 const struct got_error *err = NULL;
550 int initial_content_len;
551 int fd = -1;
553 initial_content_len = asprintf(&initial_content,
554 "\n# %s to be imported to branch %s\n", path_dir,
555 branch_name);
556 if (initial_content_len == -1)
557 return got_error_from_errno("asprintf");
559 err = got_opentemp_named_fd(logmsg_path, &fd,
560 GOT_TMPDIR_STR "/got-importmsg");
561 if (err)
562 goto done;
564 if (write(fd, initial_content, initial_content_len) == -1) {
565 err = got_error_from_errno2("write", *logmsg_path);
566 goto done;
569 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
570 initial_content_len, 1);
571 done:
572 if (fd != -1 && close(fd) == -1 && err == NULL)
573 err = got_error_from_errno2("close", *logmsg_path);
574 free(initial_content);
575 if (err) {
576 free(*logmsg_path);
577 *logmsg_path = NULL;
579 return err;
582 static const struct got_error *
583 import_progress(void *arg, const char *path)
585 printf("A %s\n", path);
586 return NULL;
589 static const struct got_error *
590 get_author(char **author, struct got_repository *repo,
591 struct got_worktree *worktree)
593 const struct got_error *err = NULL;
594 const char *got_author = NULL, *name, *email;
595 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
597 *author = NULL;
599 if (worktree)
600 worktree_conf = got_worktree_get_gotconfig(worktree);
601 repo_conf = got_repo_get_gotconfig(repo);
603 /*
604 * Priority of potential author information sources, from most
605 * significant to least significant:
606 * 1) work tree's .got/got.conf file
607 * 2) repository's got.conf file
608 * 3) repository's git config file
609 * 4) environment variables
610 * 5) global git config files (in user's home directory or /etc)
611 */
613 if (worktree_conf)
614 got_author = got_gotconfig_get_author(worktree_conf);
615 if (got_author == NULL)
616 got_author = got_gotconfig_get_author(repo_conf);
617 if (got_author == NULL) {
618 name = got_repo_get_gitconfig_author_name(repo);
619 email = got_repo_get_gitconfig_author_email(repo);
620 if (name && email) {
621 if (asprintf(author, "%s <%s>", name, email) == -1)
622 return got_error_from_errno("asprintf");
623 return NULL;
626 got_author = getenv("GOT_AUTHOR");
627 if (got_author == NULL) {
628 name = got_repo_get_global_gitconfig_author_name(repo);
629 email = got_repo_get_global_gitconfig_author_email(
630 repo);
631 if (name && email) {
632 if (asprintf(author, "%s <%s>", name, email)
633 == -1)
634 return got_error_from_errno("asprintf");
635 return NULL;
637 /* TODO: Look up user in password database? */
638 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
642 *author = strdup(got_author);
643 if (*author == NULL)
644 return got_error_from_errno("strdup");
646 /*
647 * Really dumb email address check; we're only doing this to
648 * avoid git's object parser breaking on commits we create.
649 */
650 while (*got_author && *got_author != '<')
651 got_author++;
652 if (*got_author != '<') {
653 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
654 goto done;
656 while (*got_author && *got_author != '@')
657 got_author++;
658 if (*got_author != '@') {
659 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
660 goto done;
662 while (*got_author && *got_author != '>')
663 got_author++;
664 if (*got_author != '>')
665 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
666 done:
667 if (err) {
668 free(*author);
669 *author = NULL;
671 return err;
674 static const struct got_error *
675 get_gitconfig_path(char **gitconfig_path)
677 const char *homedir = getenv("HOME");
679 *gitconfig_path = NULL;
680 if (homedir) {
681 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
682 return got_error_from_errno("asprintf");
685 return NULL;
688 static const struct got_error *
689 cmd_import(int argc, char *argv[])
691 const struct got_error *error = NULL;
692 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
693 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
694 const char *branch_name = "main";
695 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
696 struct got_repository *repo = NULL;
697 struct got_reference *branch_ref = NULL, *head_ref = NULL;
698 struct got_object_id *new_commit_id = NULL;
699 int ch;
700 struct got_pathlist_head ignores;
701 struct got_pathlist_entry *pe;
702 int preserve_logmsg = 0;
704 TAILQ_INIT(&ignores);
706 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
707 switch (ch) {
708 case 'b':
709 branch_name = optarg;
710 break;
711 case 'm':
712 logmsg = strdup(optarg);
713 if (logmsg == NULL) {
714 error = got_error_from_errno("strdup");
715 goto done;
717 break;
718 case 'r':
719 repo_path = realpath(optarg, NULL);
720 if (repo_path == NULL) {
721 error = got_error_from_errno2("realpath",
722 optarg);
723 goto done;
725 break;
726 case 'I':
727 if (optarg[0] == '\0')
728 break;
729 error = got_pathlist_insert(&pe, &ignores, optarg,
730 NULL);
731 if (error)
732 goto done;
733 break;
734 default:
735 usage_import();
736 /* NOTREACHED */
740 argc -= optind;
741 argv += optind;
743 #ifndef PROFILE
744 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
745 "unveil",
746 NULL) == -1)
747 err(1, "pledge");
748 #endif
749 if (argc != 1)
750 usage_import();
752 if (repo_path == NULL) {
753 repo_path = getcwd(NULL, 0);
754 if (repo_path == NULL)
755 return got_error_from_errno("getcwd");
757 got_path_strip_trailing_slashes(repo_path);
758 error = get_gitconfig_path(&gitconfig_path);
759 if (error)
760 goto done;
761 error = got_repo_open(&repo, repo_path, gitconfig_path);
762 if (error)
763 goto done;
765 error = get_author(&author, repo, NULL);
766 if (error)
767 return error;
769 /*
770 * Don't let the user create a branch name with a leading '-'.
771 * While technically a valid reference name, this case is usually
772 * an unintended typo.
773 */
774 if (branch_name[0] == '-')
775 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
777 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
778 error = got_error_from_errno("asprintf");
779 goto done;
782 error = got_ref_open(&branch_ref, repo, refname, 0);
783 if (error) {
784 if (error->code != GOT_ERR_NOT_REF)
785 goto done;
786 } else {
787 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
788 "import target branch already exists");
789 goto done;
792 path_dir = realpath(argv[0], NULL);
793 if (path_dir == NULL) {
794 error = got_error_from_errno2("realpath", argv[0]);
795 goto done;
797 got_path_strip_trailing_slashes(path_dir);
799 /*
800 * unveil(2) traverses exec(2); if an editor is used we have
801 * to apply unveil after the log message has been written.
802 */
803 if (logmsg == NULL || strlen(logmsg) == 0) {
804 error = get_editor(&editor);
805 if (error)
806 goto done;
807 free(logmsg);
808 error = collect_import_msg(&logmsg, &logmsg_path, editor,
809 path_dir, refname);
810 if (error) {
811 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
812 logmsg_path != NULL)
813 preserve_logmsg = 1;
814 goto done;
818 if (unveil(path_dir, "r") != 0) {
819 error = got_error_from_errno2("unveil", path_dir);
820 if (logmsg_path)
821 preserve_logmsg = 1;
822 goto done;
825 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
826 if (error) {
827 if (logmsg_path)
828 preserve_logmsg = 1;
829 goto done;
832 error = got_repo_import(&new_commit_id, path_dir, logmsg,
833 author, &ignores, repo, import_progress, NULL);
834 if (error) {
835 if (logmsg_path)
836 preserve_logmsg = 1;
837 goto done;
840 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
841 if (error) {
842 if (logmsg_path)
843 preserve_logmsg = 1;
844 goto done;
847 error = got_ref_write(branch_ref, repo);
848 if (error) {
849 if (logmsg_path)
850 preserve_logmsg = 1;
851 goto done;
854 error = got_object_id_str(&id_str, new_commit_id);
855 if (error) {
856 if (logmsg_path)
857 preserve_logmsg = 1;
858 goto done;
861 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
862 if (error) {
863 if (error->code != GOT_ERR_NOT_REF) {
864 if (logmsg_path)
865 preserve_logmsg = 1;
866 goto done;
869 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
870 branch_ref);
871 if (error) {
872 if (logmsg_path)
873 preserve_logmsg = 1;
874 goto done;
877 error = got_ref_write(head_ref, repo);
878 if (error) {
879 if (logmsg_path)
880 preserve_logmsg = 1;
881 goto done;
885 printf("Created branch %s with commit %s\n",
886 got_ref_get_name(branch_ref), id_str);
887 done:
888 if (preserve_logmsg) {
889 fprintf(stderr, "%s: log message preserved in %s\n",
890 getprogname(), logmsg_path);
891 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
892 error = got_error_from_errno2("unlink", logmsg_path);
893 free(logmsg);
894 free(logmsg_path);
895 free(repo_path);
896 free(editor);
897 free(refname);
898 free(new_commit_id);
899 free(id_str);
900 free(author);
901 free(gitconfig_path);
902 if (branch_ref)
903 got_ref_close(branch_ref);
904 if (head_ref)
905 got_ref_close(head_ref);
906 return error;
909 __dead static void
910 usage_clone(void)
912 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
913 "[-R reference] repository-url [directory]\n", getprogname());
914 exit(1);
917 struct got_fetch_progress_arg {
918 char last_scaled_size[FMT_SCALED_STRSIZE];
919 int last_p_indexed;
920 int last_p_resolved;
921 int verbosity;
923 struct got_repository *repo;
925 int create_configs;
926 int configs_created;
927 struct {
928 struct got_pathlist_head *symrefs;
929 struct got_pathlist_head *wanted_branches;
930 const char *proto;
931 const char *host;
932 const char *port;
933 const char *remote_repo_path;
934 const char *git_url;
935 int fetch_all_branches;
936 int mirror_references;
937 } config_info;
938 };
940 /* XXX forward declaration */
941 static const struct got_error *
942 create_config_files(const char *proto, const char *host, const char *port,
943 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
944 int mirror_references, struct got_pathlist_head *symrefs,
945 struct got_pathlist_head *wanted_branches, struct got_repository *repo);
947 static const struct got_error *
948 fetch_progress(void *arg, const char *message, off_t packfile_size,
949 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
951 const struct got_error *err = NULL;
952 struct got_fetch_progress_arg *a = arg;
953 char scaled_size[FMT_SCALED_STRSIZE];
954 int p_indexed, p_resolved;
955 int print_size = 0, print_indexed = 0, print_resolved = 0;
957 /*
958 * In order to allow a failed clone to be resumed with 'got fetch'
959 * we try to create configuration files as soon as possible.
960 * Once the server has sent information about its default branch
961 * we have all required information.
962 */
963 if (a->create_configs && !a->configs_created &&
964 !TAILQ_EMPTY(a->config_info.symrefs)) {
965 err = create_config_files(a->config_info.proto,
966 a->config_info.host, a->config_info.port,
967 a->config_info.remote_repo_path,
968 a->config_info.git_url,
969 a->config_info.fetch_all_branches,
970 a->config_info.mirror_references,
971 a->config_info.symrefs,
972 a->config_info.wanted_branches, a->repo);
973 if (err)
974 return err;
975 a->configs_created = 1;
978 if (a->verbosity < 0)
979 return NULL;
981 if (message && message[0] != '\0') {
982 printf("\rserver: %s", message);
983 fflush(stdout);
984 return NULL;
987 if (packfile_size > 0 || nobj_indexed > 0) {
988 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
989 (a->last_scaled_size[0] == '\0' ||
990 strcmp(scaled_size, a->last_scaled_size)) != 0) {
991 print_size = 1;
992 if (strlcpy(a->last_scaled_size, scaled_size,
993 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
994 return got_error(GOT_ERR_NO_SPACE);
996 if (nobj_indexed > 0) {
997 p_indexed = (nobj_indexed * 100) / nobj_total;
998 if (p_indexed != a->last_p_indexed) {
999 a->last_p_indexed = p_indexed;
1000 print_indexed = 1;
1001 print_size = 1;
1004 if (nobj_resolved > 0) {
1005 p_resolved = (nobj_resolved * 100) /
1006 (nobj_total - nobj_loose);
1007 if (p_resolved != a->last_p_resolved) {
1008 a->last_p_resolved = p_resolved;
1009 print_resolved = 1;
1010 print_indexed = 1;
1011 print_size = 1;
1016 if (print_size || print_indexed || print_resolved)
1017 printf("\r");
1018 if (print_size)
1019 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
1020 if (print_indexed)
1021 printf("; indexing %d%%", p_indexed);
1022 if (print_resolved)
1023 printf("; resolving deltas %d%%", p_resolved);
1024 if (print_size || print_indexed || print_resolved)
1025 fflush(stdout);
1027 return NULL;
1030 static const struct got_error *
1031 create_symref(const char *refname, struct got_reference *target_ref,
1032 int verbosity, struct got_repository *repo)
1034 const struct got_error *err;
1035 struct got_reference *head_symref;
1037 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1038 if (err)
1039 return err;
1041 err = got_ref_write(head_symref, repo);
1042 if (err == NULL && verbosity > 0) {
1043 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1044 got_ref_get_name(target_ref));
1046 got_ref_close(head_symref);
1047 return err;
1050 static const struct got_error *
1051 list_remote_refs(struct got_pathlist_head *symrefs,
1052 struct got_pathlist_head *refs)
1054 const struct got_error *err;
1055 struct got_pathlist_entry *pe;
1057 TAILQ_FOREACH(pe, symrefs, entry) {
1058 const char *refname = pe->path;
1059 const char *targetref = pe->data;
1061 printf("%s: %s\n", refname, targetref);
1064 TAILQ_FOREACH(pe, refs, entry) {
1065 const char *refname = pe->path;
1066 struct got_object_id *id = pe->data;
1067 char *id_str;
1069 err = got_object_id_str(&id_str, id);
1070 if (err)
1071 return err;
1072 printf("%s: %s\n", refname, id_str);
1073 free(id_str);
1076 return NULL;
1079 static const struct got_error *
1080 create_ref(const char *refname, struct got_object_id *id,
1081 int verbosity, struct got_repository *repo)
1083 const struct got_error *err = NULL;
1084 struct got_reference *ref;
1085 char *id_str;
1087 err = got_object_id_str(&id_str, id);
1088 if (err)
1089 return err;
1091 err = got_ref_alloc(&ref, refname, id);
1092 if (err)
1093 goto done;
1095 err = got_ref_write(ref, repo);
1096 got_ref_close(ref);
1098 if (err == NULL && verbosity >= 0)
1099 printf("Created reference %s: %s\n", refname, id_str);
1100 done:
1101 free(id_str);
1102 return err;
1105 static int
1106 match_wanted_ref(const char *refname, const char *wanted_ref)
1108 if (strncmp(refname, "refs/", 5) != 0)
1109 return 0;
1110 refname += 5;
1113 * Prevent fetching of references that won't make any
1114 * sense outside of the remote repository's context.
1116 if (strncmp(refname, "got/", 4) == 0)
1117 return 0;
1118 if (strncmp(refname, "remotes/", 8) == 0)
1119 return 0;
1121 if (strncmp(wanted_ref, "refs/", 5) == 0)
1122 wanted_ref += 5;
1124 /* Allow prefix match. */
1125 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1126 return 1;
1128 /* Allow exact match. */
1129 return (strcmp(refname, wanted_ref) == 0);
1132 static int
1133 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1135 struct got_pathlist_entry *pe;
1137 TAILQ_FOREACH(pe, wanted_refs, entry) {
1138 if (match_wanted_ref(refname, pe->path))
1139 return 1;
1142 return 0;
1145 static const struct got_error *
1146 create_wanted_ref(const char *refname, struct got_object_id *id,
1147 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1149 const struct got_error *err;
1150 char *remote_refname;
1152 if (strncmp("refs/", refname, 5) == 0)
1153 refname += 5;
1155 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1156 remote_repo_name, refname) == -1)
1157 return got_error_from_errno("asprintf");
1159 err = create_ref(remote_refname, id, verbosity, repo);
1160 free(remote_refname);
1161 return err;
1164 static const struct got_error *
1165 create_gotconfig(const char *proto, const char *host, const char *port,
1166 const char *remote_repo_path, int fetch_all_branches, int mirror_references,
1167 struct got_repository *repo)
1169 const struct got_error *err = NULL;
1170 char *gotconfig_path = NULL;
1171 char *gotconfig = NULL;
1172 FILE *gotconfig_file = NULL;
1173 ssize_t n;
1175 /* Create got.conf(5). */
1176 gotconfig_path = got_repo_get_path_gotconfig(repo);
1177 if (gotconfig_path == NULL) {
1178 err = got_error_from_errno("got_repo_get_path_gotconfig");
1179 goto done;
1181 gotconfig_file = fopen(gotconfig_path, "a");
1182 if (gotconfig_file == NULL) {
1183 err = got_error_from_errno2("fopen", gotconfig_path);
1184 goto done;
1186 if (asprintf(&gotconfig,
1187 "remote \"%s\" {\n"
1188 "\tserver %s\n"
1189 "\tprotocol %s\n"
1190 "%s%s%s"
1191 "\trepository \"%s\"\n"
1192 "%s"
1193 "}\n",
1194 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1195 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1196 remote_repo_path,
1197 mirror_references ? "\tmirror-references yes\n" : "") == -1) {
1198 err = got_error_from_errno("asprintf");
1199 goto done;
1201 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1202 if (n != strlen(gotconfig)) {
1203 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1204 goto done;
1207 done:
1208 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1209 err = got_error_from_errno2("fclose", gotconfig_path);
1210 free(gotconfig_path);
1211 return err;
1214 static const struct got_error *
1215 create_gitconfig(const char *git_url, const char *default_branch,
1216 int fetch_all_branches, int mirror_references, struct got_repository *repo)
1218 const struct got_error *err = NULL;
1219 char *gitconfig_path = NULL;
1220 char *gitconfig = NULL;
1221 FILE *gitconfig_file = NULL;
1222 ssize_t n;
1224 /* Create a config file Git can understand. */
1225 gitconfig_path = got_repo_get_path_gitconfig(repo);
1226 if (gitconfig_path == NULL) {
1227 err = got_error_from_errno("got_repo_get_path_gitconfig");
1228 goto done;
1230 gitconfig_file = fopen(gitconfig_path, "a");
1231 if (gitconfig_file == NULL) {
1232 err = got_error_from_errno2("fopen", gitconfig_path);
1233 goto done;
1235 if (mirror_references) {
1236 if (asprintf(&gitconfig,
1237 "[remote \"%s\"]\n"
1238 "\turl = %s\n"
1239 "\tfetch = +refs/*:refs/*\n"
1240 "\tmirror = true\n",
1241 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1242 err = got_error_from_errno("asprintf");
1243 goto done;
1245 } else if (fetch_all_branches) {
1246 if (asprintf(&gitconfig,
1247 "[remote \"%s\"]\n"
1248 "\turl = %s\n"
1249 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1250 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1251 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1252 err = got_error_from_errno("asprintf");
1253 goto done;
1255 } else {
1256 const char *branchname;
1259 * If the server specified a default branch, use just that one.
1260 * Otherwise fall back to fetching all branches on next fetch.
1262 if (default_branch) {
1263 branchname = default_branch;
1264 if (strncmp(branchname, "refs/heads/", 11) == 0)
1265 branchname += 11;
1266 } else
1267 branchname = "*"; /* fall back to all branches */
1268 if (asprintf(&gitconfig,
1269 "[remote \"%s\"]\n"
1270 "\turl = %s\n"
1271 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1272 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1273 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1274 branchname) == -1) {
1275 err = got_error_from_errno("asprintf");
1276 goto done;
1279 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1280 if (n != strlen(gitconfig)) {
1281 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1282 goto done;
1284 done:
1285 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1286 err = got_error_from_errno2("fclose", gitconfig_path);
1287 free(gitconfig_path);
1288 return err;
1291 static const struct got_error *
1292 create_config_files(const char *proto, const char *host, const char *port,
1293 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1294 int mirror_references, struct got_pathlist_head *symrefs,
1295 struct got_pathlist_head *wanted_branches, struct got_repository *repo)
1297 const struct got_error *err = NULL;
1298 const char *default_branch = NULL;
1299 struct got_pathlist_entry *pe;
1302 * If we asked for a set of wanted branches then use the first
1303 * one of those.
1305 if (!TAILQ_EMPTY(wanted_branches)) {
1306 pe = TAILQ_FIRST(wanted_branches);
1307 default_branch = pe->path;
1308 } else {
1309 /* First HEAD ref listed by server is the default branch. */
1310 TAILQ_FOREACH(pe, symrefs, entry) {
1311 const char *refname = pe->path;
1312 const char *target = pe->data;
1314 if (strcmp(refname, GOT_REF_HEAD) != 0)
1315 continue;
1317 default_branch = target;
1318 break;
1322 /* Create got.conf(5). */
1323 err = create_gotconfig(proto, host, port, remote_repo_path,
1324 fetch_all_branches, mirror_references, repo);
1325 if (err)
1326 return err;
1328 /* Create a config file Git can understand. */
1329 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1330 mirror_references, repo);
1333 static const struct got_error *
1334 cmd_clone(int argc, char *argv[])
1336 const struct got_error *error = NULL;
1337 const char *uri, *dirname;
1338 char *proto, *host, *port, *repo_name, *server_path;
1339 char *default_destdir = NULL, *id_str = NULL;
1340 const char *repo_path;
1341 struct got_repository *repo = NULL;
1342 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1343 struct got_pathlist_entry *pe;
1344 struct got_object_id *pack_hash = NULL;
1345 int ch, fetchfd = -1, fetchstatus;
1346 pid_t fetchpid = -1;
1347 struct got_fetch_progress_arg fpa;
1348 char *git_url = NULL;
1349 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1350 int list_refs_only = 0;
1352 TAILQ_INIT(&refs);
1353 TAILQ_INIT(&symrefs);
1354 TAILQ_INIT(&wanted_branches);
1355 TAILQ_INIT(&wanted_refs);
1357 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1358 switch (ch) {
1359 case 'a':
1360 fetch_all_branches = 1;
1361 break;
1362 case 'b':
1363 error = got_pathlist_append(&wanted_branches,
1364 optarg, NULL);
1365 if (error)
1366 return error;
1367 break;
1368 case 'l':
1369 list_refs_only = 1;
1370 break;
1371 case 'm':
1372 mirror_references = 1;
1373 break;
1374 case 'v':
1375 if (verbosity < 0)
1376 verbosity = 0;
1377 else if (verbosity < 3)
1378 verbosity++;
1379 break;
1380 case 'q':
1381 verbosity = -1;
1382 break;
1383 case 'R':
1384 error = got_pathlist_append(&wanted_refs,
1385 optarg, NULL);
1386 if (error)
1387 return error;
1388 break;
1389 default:
1390 usage_clone();
1391 break;
1394 argc -= optind;
1395 argv += optind;
1397 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1398 option_conflict('a', 'b');
1399 if (list_refs_only) {
1400 if (!TAILQ_EMPTY(&wanted_branches))
1401 option_conflict('l', 'b');
1402 if (fetch_all_branches)
1403 option_conflict('l', 'a');
1404 if (mirror_references)
1405 option_conflict('l', 'm');
1406 if (verbosity == -1)
1407 option_conflict('l', 'q');
1408 if (!TAILQ_EMPTY(&wanted_refs))
1409 option_conflict('l', 'R');
1412 uri = argv[0];
1414 if (argc == 1)
1415 dirname = NULL;
1416 else if (argc == 2)
1417 dirname = argv[1];
1418 else
1419 usage_clone();
1421 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1422 &repo_name, uri);
1423 if (error)
1424 goto done;
1426 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1427 host, port ? ":" : "", port ? port : "",
1428 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1429 error = got_error_from_errno("asprintf");
1430 goto done;
1433 if (strcmp(proto, "git") == 0) {
1434 #ifndef PROFILE
1435 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1436 "sendfd dns inet unveil", NULL) == -1)
1437 err(1, "pledge");
1438 #endif
1439 } else if (strcmp(proto, "git+ssh") == 0 ||
1440 strcmp(proto, "ssh") == 0) {
1441 #ifndef PROFILE
1442 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1443 "sendfd unveil", NULL) == -1)
1444 err(1, "pledge");
1445 #endif
1446 } else if (strcmp(proto, "http") == 0 ||
1447 strcmp(proto, "git+http") == 0) {
1448 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1449 goto done;
1450 } else {
1451 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1452 goto done;
1454 if (dirname == NULL) {
1455 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1456 error = got_error_from_errno("asprintf");
1457 goto done;
1459 repo_path = default_destdir;
1460 } else
1461 repo_path = dirname;
1463 if (!list_refs_only) {
1464 error = got_path_mkdir(repo_path);
1465 if (error &&
1466 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1467 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1468 goto done;
1469 if (!got_path_dir_is_empty(repo_path)) {
1470 error = got_error_path(repo_path,
1471 GOT_ERR_DIR_NOT_EMPTY);
1472 goto done;
1476 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1477 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1478 error = got_error_from_errno2("unveil",
1479 GOT_FETCH_PATH_SSH);
1480 goto done;
1483 error = apply_unveil(repo_path, 0, NULL);
1484 if (error)
1485 goto done;
1487 if (verbosity >= 0)
1488 printf("Connecting to %s%s%s\n", host,
1489 port ? ":" : "", port ? port : "");
1491 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1492 server_path, verbosity);
1493 if (error)
1494 goto done;
1496 if (!list_refs_only) {
1497 error = got_repo_init(repo_path);
1498 if (error)
1499 goto done;
1500 error = got_repo_open(&repo, repo_path, NULL);
1501 if (error)
1502 goto done;
1505 fpa.last_scaled_size[0] = '\0';
1506 fpa.last_p_indexed = -1;
1507 fpa.last_p_resolved = -1;
1508 fpa.verbosity = verbosity;
1509 fpa.create_configs = 1;
1510 fpa.configs_created = 0;
1511 fpa.repo = repo;
1512 fpa.config_info.symrefs = &symrefs;
1513 fpa.config_info.wanted_branches = &wanted_branches;
1514 fpa.config_info.proto = proto;
1515 fpa.config_info.host = host;
1516 fpa.config_info.port = port;
1517 fpa.config_info.remote_repo_path = server_path;
1518 fpa.config_info.git_url = git_url;
1519 fpa.config_info.fetch_all_branches = fetch_all_branches;
1520 fpa.config_info.mirror_references = mirror_references;
1521 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1522 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1523 fetch_all_branches, &wanted_branches, &wanted_refs,
1524 list_refs_only, verbosity, fetchfd, repo,
1525 fetch_progress, &fpa);
1526 if (error)
1527 goto done;
1529 if (list_refs_only) {
1530 error = list_remote_refs(&symrefs, &refs);
1531 goto done;
1534 error = got_object_id_str(&id_str, pack_hash);
1535 if (error)
1536 goto done;
1537 if (verbosity >= 0)
1538 printf("\nFetched %s.pack\n", id_str);
1539 free(id_str);
1541 /* Set up references provided with the pack file. */
1542 TAILQ_FOREACH(pe, &refs, entry) {
1543 const char *refname = pe->path;
1544 struct got_object_id *id = pe->data;
1545 char *remote_refname;
1547 if (is_wanted_ref(&wanted_refs, refname) &&
1548 !mirror_references) {
1549 error = create_wanted_ref(refname, id,
1550 GOT_FETCH_DEFAULT_REMOTE_NAME,
1551 verbosity - 1, repo);
1552 if (error)
1553 goto done;
1554 continue;
1557 error = create_ref(refname, id, verbosity - 1, repo);
1558 if (error)
1559 goto done;
1561 if (mirror_references)
1562 continue;
1564 if (strncmp("refs/heads/", refname, 11) != 0)
1565 continue;
1567 if (asprintf(&remote_refname,
1568 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1569 refname + 11) == -1) {
1570 error = got_error_from_errno("asprintf");
1571 goto done;
1573 error = create_ref(remote_refname, id, verbosity - 1, repo);
1574 free(remote_refname);
1575 if (error)
1576 goto done;
1579 /* Set the HEAD reference if the server provided one. */
1580 TAILQ_FOREACH(pe, &symrefs, entry) {
1581 struct got_reference *target_ref;
1582 const char *refname = pe->path;
1583 const char *target = pe->data;
1584 char *remote_refname = NULL, *remote_target = NULL;
1586 if (strcmp(refname, GOT_REF_HEAD) != 0)
1587 continue;
1589 error = got_ref_open(&target_ref, repo, target, 0);
1590 if (error) {
1591 if (error->code == GOT_ERR_NOT_REF) {
1592 error = NULL;
1593 continue;
1595 goto done;
1598 error = create_symref(refname, target_ref, verbosity, repo);
1599 got_ref_close(target_ref);
1600 if (error)
1601 goto done;
1603 if (mirror_references)
1604 continue;
1606 if (strncmp("refs/heads/", target, 11) != 0)
1607 continue;
1609 if (asprintf(&remote_refname,
1610 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1611 refname) == -1) {
1612 error = got_error_from_errno("asprintf");
1613 goto done;
1615 if (asprintf(&remote_target,
1616 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1617 target + 11) == -1) {
1618 error = got_error_from_errno("asprintf");
1619 free(remote_refname);
1620 goto done;
1622 error = got_ref_open(&target_ref, repo, remote_target, 0);
1623 if (error) {
1624 free(remote_refname);
1625 free(remote_target);
1626 if (error->code == GOT_ERR_NOT_REF) {
1627 error = NULL;
1628 continue;
1630 goto done;
1632 error = create_symref(remote_refname, target_ref,
1633 verbosity - 1, repo);
1634 free(remote_refname);
1635 free(remote_target);
1636 got_ref_close(target_ref);
1637 if (error)
1638 goto done;
1640 if (pe == NULL) {
1642 * We failed to set the HEAD reference. If we asked for
1643 * a set of wanted branches use the first of one of those
1644 * which could be fetched instead.
1646 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1647 const char *target = pe->path;
1648 struct got_reference *target_ref;
1650 error = got_ref_open(&target_ref, repo, target, 0);
1651 if (error) {
1652 if (error->code == GOT_ERR_NOT_REF) {
1653 error = NULL;
1654 continue;
1656 goto done;
1659 error = create_symref(GOT_REF_HEAD, target_ref,
1660 verbosity, repo);
1661 got_ref_close(target_ref);
1662 if (error)
1663 goto done;
1664 break;
1668 if (verbosity >= 0)
1669 printf("Created %s repository '%s'\n",
1670 mirror_references ? "mirrored" : "cloned", repo_path);
1671 done:
1672 if (fetchpid > 0) {
1673 if (kill(fetchpid, SIGTERM) == -1)
1674 error = got_error_from_errno("kill");
1675 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1676 error = got_error_from_errno("waitpid");
1678 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1679 error = got_error_from_errno("close");
1680 if (repo)
1681 got_repo_close(repo);
1682 TAILQ_FOREACH(pe, &refs, entry) {
1683 free((void *)pe->path);
1684 free(pe->data);
1686 got_pathlist_free(&refs);
1687 TAILQ_FOREACH(pe, &symrefs, entry) {
1688 free((void *)pe->path);
1689 free(pe->data);
1691 got_pathlist_free(&symrefs);
1692 got_pathlist_free(&wanted_branches);
1693 got_pathlist_free(&wanted_refs);
1694 free(pack_hash);
1695 free(proto);
1696 free(host);
1697 free(port);
1698 free(server_path);
1699 free(repo_name);
1700 free(default_destdir);
1701 free(git_url);
1702 return error;
1705 static const struct got_error *
1706 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1707 int replace_tags, int verbosity, struct got_repository *repo)
1709 const struct got_error *err = NULL;
1710 char *new_id_str = NULL;
1711 struct got_object_id *old_id = NULL;
1713 err = got_object_id_str(&new_id_str, new_id);
1714 if (err)
1715 goto done;
1717 if (!replace_tags &&
1718 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1719 err = got_ref_resolve(&old_id, repo, ref);
1720 if (err)
1721 goto done;
1722 if (got_object_id_cmp(old_id, new_id) == 0)
1723 goto done;
1724 if (verbosity >= 0) {
1725 printf("Rejecting update of existing tag %s: %s\n",
1726 got_ref_get_name(ref), new_id_str);
1728 goto done;
1731 if (got_ref_is_symbolic(ref)) {
1732 if (verbosity >= 0) {
1733 printf("Replacing reference %s: %s\n",
1734 got_ref_get_name(ref),
1735 got_ref_get_symref_target(ref));
1737 err = got_ref_change_symref_to_ref(ref, new_id);
1738 if (err)
1739 goto done;
1740 err = got_ref_write(ref, repo);
1741 if (err)
1742 goto done;
1743 } else {
1744 err = got_ref_resolve(&old_id, repo, ref);
1745 if (err)
1746 goto done;
1747 if (got_object_id_cmp(old_id, new_id) == 0)
1748 goto done;
1750 err = got_ref_change_ref(ref, new_id);
1751 if (err)
1752 goto done;
1753 err = got_ref_write(ref, repo);
1754 if (err)
1755 goto done;
1758 if (verbosity >= 0)
1759 printf("Updated %s: %s\n", got_ref_get_name(ref),
1760 new_id_str);
1761 done:
1762 free(old_id);
1763 free(new_id_str);
1764 return err;
1767 static const struct got_error *
1768 update_symref(const char *refname, struct got_reference *target_ref,
1769 int verbosity, struct got_repository *repo)
1771 const struct got_error *err = NULL, *unlock_err;
1772 struct got_reference *symref;
1773 int symref_is_locked = 0;
1775 err = got_ref_open(&symref, repo, refname, 1);
1776 if (err) {
1777 if (err->code != GOT_ERR_NOT_REF)
1778 return err;
1779 err = got_ref_alloc_symref(&symref, refname, target_ref);
1780 if (err)
1781 goto done;
1783 err = got_ref_write(symref, repo);
1784 if (err)
1785 goto done;
1787 if (verbosity >= 0)
1788 printf("Created reference %s: %s\n",
1789 got_ref_get_name(symref),
1790 got_ref_get_symref_target(symref));
1791 } else {
1792 symref_is_locked = 1;
1794 if (strcmp(got_ref_get_symref_target(symref),
1795 got_ref_get_name(target_ref)) == 0)
1796 goto done;
1798 err = got_ref_change_symref(symref,
1799 got_ref_get_name(target_ref));
1800 if (err)
1801 goto done;
1803 err = got_ref_write(symref, repo);
1804 if (err)
1805 goto done;
1807 if (verbosity >= 0)
1808 printf("Updated %s: %s\n", got_ref_get_name(symref),
1809 got_ref_get_symref_target(symref));
1812 done:
1813 if (symref_is_locked) {
1814 unlock_err = got_ref_unlock(symref);
1815 if (unlock_err && err == NULL)
1816 err = unlock_err;
1818 got_ref_close(symref);
1819 return err;
1822 __dead static void
1823 usage_fetch(void)
1825 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1826 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1827 "[remote-repository-name]\n",
1828 getprogname());
1829 exit(1);
1832 static const struct got_error *
1833 delete_missing_ref(struct got_reference *ref,
1834 int verbosity, struct got_repository *repo)
1836 const struct got_error *err = NULL;
1837 struct got_object_id *id = NULL;
1838 char *id_str = NULL;
1840 if (got_ref_is_symbolic(ref)) {
1841 err = got_ref_delete(ref, repo);
1842 if (err)
1843 return err;
1844 if (verbosity >= 0) {
1845 printf("Deleted reference %s: %s\n",
1846 got_ref_get_name(ref),
1847 got_ref_get_symref_target(ref));
1849 } else {
1850 err = got_ref_resolve(&id, repo, ref);
1851 if (err)
1852 return err;
1853 err = got_object_id_str(&id_str, id);
1854 if (err)
1855 goto done;
1857 err = got_ref_delete(ref, repo);
1858 if (err)
1859 goto done;
1860 if (verbosity >= 0) {
1861 printf("Deleted reference %s: %s\n",
1862 got_ref_get_name(ref), id_str);
1865 done:
1866 free(id);
1867 free(id_str);
1868 return NULL;
1871 static const struct got_error *
1872 delete_missing_refs(struct got_pathlist_head *their_refs,
1873 struct got_pathlist_head *their_symrefs,
1874 const struct got_remote_repo *remote,
1875 int verbosity, struct got_repository *repo)
1877 const struct got_error *err = NULL, *unlock_err;
1878 struct got_reflist_head my_refs;
1879 struct got_reflist_entry *re;
1880 struct got_pathlist_entry *pe;
1881 char *remote_namespace = NULL;
1882 char *local_refname = NULL;
1884 TAILQ_INIT(&my_refs);
1886 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
1887 == -1)
1888 return got_error_from_errno("asprintf");
1890 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1891 if (err)
1892 goto done;
1894 TAILQ_FOREACH(re, &my_refs, entry) {
1895 const char *refname = got_ref_get_name(re->ref);
1897 if (!remote->mirror_references) {
1898 if (strncmp(refname, remote_namespace,
1899 strlen(remote_namespace)) == 0) {
1900 if (strcmp(refname + strlen(remote_namespace),
1901 GOT_REF_HEAD) == 0)
1902 continue;
1903 if (asprintf(&local_refname, "refs/heads/%s",
1904 refname + strlen(remote_namespace)) == -1) {
1905 err = got_error_from_errno("asprintf");
1906 goto done;
1908 } else if (strncmp(refname, "refs/tags/", 10) != 0)
1909 continue;
1912 TAILQ_FOREACH(pe, their_refs, entry) {
1913 if (strcmp(local_refname, pe->path) == 0)
1914 break;
1916 if (pe != NULL)
1917 continue;
1919 TAILQ_FOREACH(pe, their_symrefs, entry) {
1920 if (strcmp(local_refname, pe->path) == 0)
1921 break;
1923 if (pe != NULL)
1924 continue;
1926 err = delete_missing_ref(re->ref, verbosity, repo);
1927 if (err)
1928 break;
1930 if (local_refname) {
1931 struct got_reference *ref;
1932 err = got_ref_open(&ref, repo, local_refname, 1);
1933 if (err) {
1934 if (err->code != GOT_ERR_NOT_REF)
1935 break;
1936 free(local_refname);
1937 local_refname = NULL;
1938 continue;
1940 err = delete_missing_ref(ref, verbosity, repo);
1941 if (err)
1942 break;
1943 unlock_err = got_ref_unlock(ref);
1944 got_ref_close(ref);
1945 if (unlock_err && err == NULL) {
1946 err = unlock_err;
1947 break;
1950 free(local_refname);
1951 local_refname = NULL;
1954 done:
1955 free(remote_namespace);
1956 free(local_refname);
1957 return err;
1960 static const struct got_error *
1961 update_wanted_ref(const char *refname, struct got_object_id *id,
1962 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1964 const struct got_error *err, *unlock_err;
1965 char *remote_refname;
1966 struct got_reference *ref;
1968 if (strncmp("refs/", refname, 5) == 0)
1969 refname += 5;
1971 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1972 remote_repo_name, refname) == -1)
1973 return got_error_from_errno("asprintf");
1975 err = got_ref_open(&ref, repo, remote_refname, 1);
1976 if (err) {
1977 if (err->code != GOT_ERR_NOT_REF)
1978 goto done;
1979 err = create_ref(remote_refname, id, verbosity, repo);
1980 } else {
1981 err = update_ref(ref, id, 0, verbosity, repo);
1982 unlock_err = got_ref_unlock(ref);
1983 if (unlock_err && err == NULL)
1984 err = unlock_err;
1985 got_ref_close(ref);
1987 done:
1988 free(remote_refname);
1989 return err;
1992 static const struct got_error *
1993 cmd_fetch(int argc, char *argv[])
1995 const struct got_error *error = NULL, *unlock_err;
1996 char *cwd = NULL, *repo_path = NULL;
1997 const char *remote_name;
1998 char *proto = NULL, *host = NULL, *port = NULL;
1999 char *repo_name = NULL, *server_path = NULL;
2000 const struct got_remote_repo *remotes, *remote = NULL;
2001 int nremotes;
2002 char *id_str = NULL;
2003 struct got_repository *repo = NULL;
2004 struct got_worktree *worktree = NULL;
2005 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2006 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2007 struct got_pathlist_entry *pe;
2008 struct got_object_id *pack_hash = NULL;
2009 int i, ch, fetchfd = -1, fetchstatus;
2010 pid_t fetchpid = -1;
2011 struct got_fetch_progress_arg fpa;
2012 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2013 int delete_refs = 0, replace_tags = 0;
2015 TAILQ_INIT(&refs);
2016 TAILQ_INIT(&symrefs);
2017 TAILQ_INIT(&wanted_branches);
2018 TAILQ_INIT(&wanted_refs);
2020 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
2021 switch (ch) {
2022 case 'a':
2023 fetch_all_branches = 1;
2024 break;
2025 case 'b':
2026 error = got_pathlist_append(&wanted_branches,
2027 optarg, NULL);
2028 if (error)
2029 return error;
2030 break;
2031 case 'd':
2032 delete_refs = 1;
2033 break;
2034 case 'l':
2035 list_refs_only = 1;
2036 break;
2037 case 'r':
2038 repo_path = realpath(optarg, NULL);
2039 if (repo_path == NULL)
2040 return got_error_from_errno2("realpath",
2041 optarg);
2042 got_path_strip_trailing_slashes(repo_path);
2043 break;
2044 case 't':
2045 replace_tags = 1;
2046 break;
2047 case 'v':
2048 if (verbosity < 0)
2049 verbosity = 0;
2050 else if (verbosity < 3)
2051 verbosity++;
2052 break;
2053 case 'q':
2054 verbosity = -1;
2055 break;
2056 case 'R':
2057 error = got_pathlist_append(&wanted_refs,
2058 optarg, NULL);
2059 if (error)
2060 return error;
2061 break;
2062 default:
2063 usage_fetch();
2064 break;
2067 argc -= optind;
2068 argv += optind;
2070 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2071 option_conflict('a', 'b');
2072 if (list_refs_only) {
2073 if (!TAILQ_EMPTY(&wanted_branches))
2074 option_conflict('l', 'b');
2075 if (fetch_all_branches)
2076 option_conflict('l', 'a');
2077 if (delete_refs)
2078 option_conflict('l', 'd');
2079 if (verbosity == -1)
2080 option_conflict('l', 'q');
2083 if (argc == 0)
2084 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2085 else if (argc == 1)
2086 remote_name = argv[0];
2087 else
2088 usage_fetch();
2090 cwd = getcwd(NULL, 0);
2091 if (cwd == NULL) {
2092 error = got_error_from_errno("getcwd");
2093 goto done;
2096 if (repo_path == NULL) {
2097 error = got_worktree_open(&worktree, cwd);
2098 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2099 goto done;
2100 else
2101 error = NULL;
2102 if (worktree) {
2103 repo_path =
2104 strdup(got_worktree_get_repo_path(worktree));
2105 if (repo_path == NULL)
2106 error = got_error_from_errno("strdup");
2107 if (error)
2108 goto done;
2109 } else {
2110 repo_path = strdup(cwd);
2111 if (repo_path == NULL) {
2112 error = got_error_from_errno("strdup");
2113 goto done;
2118 error = got_repo_open(&repo, repo_path, NULL);
2119 if (error)
2120 goto done;
2122 if (worktree) {
2123 worktree_conf = got_worktree_get_gotconfig(worktree);
2124 if (worktree_conf) {
2125 got_gotconfig_get_remotes(&nremotes, &remotes,
2126 worktree_conf);
2127 for (i = 0; i < nremotes; i++) {
2128 if (strcmp(remotes[i].name, remote_name) == 0) {
2129 remote = &remotes[i];
2130 break;
2135 if (remote == NULL) {
2136 repo_conf = got_repo_get_gotconfig(repo);
2137 if (repo_conf) {
2138 got_gotconfig_get_remotes(&nremotes, &remotes,
2139 repo_conf);
2140 for (i = 0; i < nremotes; i++) {
2141 if (strcmp(remotes[i].name, remote_name) == 0) {
2142 remote = &remotes[i];
2143 break;
2148 if (remote == NULL) {
2149 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2150 for (i = 0; i < nremotes; i++) {
2151 if (strcmp(remotes[i].name, remote_name) == 0) {
2152 remote = &remotes[i];
2153 break;
2157 if (remote == NULL) {
2158 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2159 goto done;
2162 if (TAILQ_EMPTY(&wanted_branches) && remote->nbranches > 0) {
2163 for (i = 0; i < remote->nbranches; i++) {
2164 got_pathlist_append(&wanted_branches,
2165 remote->branches[i], NULL);
2170 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
2171 &repo_name, remote->url);
2172 if (error)
2173 goto done;
2175 if (strcmp(proto, "git") == 0) {
2176 #ifndef PROFILE
2177 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2178 "sendfd dns inet unveil", NULL) == -1)
2179 err(1, "pledge");
2180 #endif
2181 } else if (strcmp(proto, "git+ssh") == 0 ||
2182 strcmp(proto, "ssh") == 0) {
2183 #ifndef PROFILE
2184 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2185 "sendfd unveil", NULL) == -1)
2186 err(1, "pledge");
2187 #endif
2188 } else if (strcmp(proto, "http") == 0 ||
2189 strcmp(proto, "git+http") == 0) {
2190 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2191 goto done;
2192 } else {
2193 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2194 goto done;
2197 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
2198 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
2199 error = got_error_from_errno2("unveil",
2200 GOT_FETCH_PATH_SSH);
2201 goto done;
2204 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2205 if (error)
2206 goto done;
2208 if (verbosity >= 0)
2209 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2210 port ? ":" : "", port ? port : "");
2212 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2213 server_path, verbosity);
2214 if (error)
2215 goto done;
2217 fpa.last_scaled_size[0] = '\0';
2218 fpa.last_p_indexed = -1;
2219 fpa.last_p_resolved = -1;
2220 fpa.verbosity = verbosity;
2221 fpa.repo = repo;
2222 fpa.create_configs = 0;
2223 fpa.configs_created = 0;
2224 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2225 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2226 remote->mirror_references, fetch_all_branches, &wanted_branches,
2227 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2228 fetch_progress, &fpa);
2229 if (error)
2230 goto done;
2232 if (list_refs_only) {
2233 error = list_remote_refs(&symrefs, &refs);
2234 goto done;
2237 if (pack_hash == NULL) {
2238 if (verbosity >= 0)
2239 printf("Already up-to-date\n");
2240 } else if (verbosity >= 0) {
2241 error = got_object_id_str(&id_str, pack_hash);
2242 if (error)
2243 goto done;
2244 printf("\nFetched %s.pack\n", id_str);
2245 free(id_str);
2246 id_str = NULL;
2249 /* Update references provided with the pack file. */
2250 TAILQ_FOREACH(pe, &refs, entry) {
2251 const char *refname = pe->path;
2252 struct got_object_id *id = pe->data;
2253 struct got_reference *ref;
2254 char *remote_refname;
2256 if (is_wanted_ref(&wanted_refs, refname) &&
2257 !remote->mirror_references) {
2258 error = update_wanted_ref(refname, id,
2259 remote->name, verbosity, repo);
2260 if (error)
2261 goto done;
2262 continue;
2265 if (remote->mirror_references ||
2266 strncmp("refs/tags/", refname, 10) == 0) {
2267 error = got_ref_open(&ref, repo, refname, 1);
2268 if (error) {
2269 if (error->code != GOT_ERR_NOT_REF)
2270 goto done;
2271 error = create_ref(refname, id, verbosity,
2272 repo);
2273 if (error)
2274 goto done;
2275 } else {
2276 error = update_ref(ref, id, replace_tags,
2277 verbosity, repo);
2278 unlock_err = got_ref_unlock(ref);
2279 if (unlock_err && error == NULL)
2280 error = unlock_err;
2281 got_ref_close(ref);
2282 if (error)
2283 goto done;
2285 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2286 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2287 remote_name, refname + 11) == -1) {
2288 error = got_error_from_errno("asprintf");
2289 goto done;
2292 error = got_ref_open(&ref, repo, remote_refname, 1);
2293 if (error) {
2294 if (error->code != GOT_ERR_NOT_REF)
2295 goto done;
2296 error = create_ref(remote_refname, id,
2297 verbosity, repo);
2298 if (error)
2299 goto done;
2300 } else {
2301 error = update_ref(ref, id, replace_tags,
2302 verbosity, repo);
2303 unlock_err = got_ref_unlock(ref);
2304 if (unlock_err && error == NULL)
2305 error = unlock_err;
2306 got_ref_close(ref);
2307 if (error)
2308 goto done;
2311 /* Also create a local branch if none exists yet. */
2312 error = got_ref_open(&ref, repo, refname, 1);
2313 if (error) {
2314 if (error->code != GOT_ERR_NOT_REF)
2315 goto done;
2316 error = create_ref(refname, id, verbosity,
2317 repo);
2318 if (error)
2319 goto done;
2320 } else {
2321 unlock_err = got_ref_unlock(ref);
2322 if (unlock_err && error == NULL)
2323 error = unlock_err;
2324 got_ref_close(ref);
2328 if (delete_refs) {
2329 error = delete_missing_refs(&refs, &symrefs, remote,
2330 verbosity, repo);
2331 if (error)
2332 goto done;
2335 if (!remote->mirror_references) {
2336 /* Update remote HEAD reference if the server provided one. */
2337 TAILQ_FOREACH(pe, &symrefs, entry) {
2338 struct got_reference *target_ref;
2339 const char *refname = pe->path;
2340 const char *target = pe->data;
2341 char *remote_refname = NULL, *remote_target = NULL;
2343 if (strcmp(refname, GOT_REF_HEAD) != 0)
2344 continue;
2346 if (strncmp("refs/heads/", target, 11) != 0)
2347 continue;
2349 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2350 remote->name, refname) == -1) {
2351 error = got_error_from_errno("asprintf");
2352 goto done;
2354 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2355 remote->name, target + 11) == -1) {
2356 error = got_error_from_errno("asprintf");
2357 free(remote_refname);
2358 goto done;
2361 error = got_ref_open(&target_ref, repo, remote_target,
2362 0);
2363 if (error) {
2364 free(remote_refname);
2365 free(remote_target);
2366 if (error->code == GOT_ERR_NOT_REF) {
2367 error = NULL;
2368 continue;
2370 goto done;
2372 error = update_symref(remote_refname, target_ref,
2373 verbosity, repo);
2374 free(remote_refname);
2375 free(remote_target);
2376 got_ref_close(target_ref);
2377 if (error)
2378 goto done;
2381 done:
2382 if (fetchpid > 0) {
2383 if (kill(fetchpid, SIGTERM) == -1)
2384 error = got_error_from_errno("kill");
2385 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2386 error = got_error_from_errno("waitpid");
2388 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2389 error = got_error_from_errno("close");
2390 if (repo)
2391 got_repo_close(repo);
2392 if (worktree)
2393 got_worktree_close(worktree);
2394 TAILQ_FOREACH(pe, &refs, entry) {
2395 free((void *)pe->path);
2396 free(pe->data);
2398 got_pathlist_free(&refs);
2399 TAILQ_FOREACH(pe, &symrefs, entry) {
2400 free((void *)pe->path);
2401 free(pe->data);
2403 got_pathlist_free(&symrefs);
2404 got_pathlist_free(&wanted_branches);
2405 got_pathlist_free(&wanted_refs);
2406 free(id_str);
2407 free(cwd);
2408 free(repo_path);
2409 free(pack_hash);
2410 free(proto);
2411 free(host);
2412 free(port);
2413 free(server_path);
2414 free(repo_name);
2415 return error;
2419 __dead static void
2420 usage_checkout(void)
2422 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2423 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2424 exit(1);
2427 static void
2428 show_worktree_base_ref_warning(void)
2430 fprintf(stderr, "%s: warning: could not create a reference "
2431 "to the work tree's base commit; the commit could be "
2432 "garbage-collected by Git; making the repository "
2433 "writable and running 'got update' will prevent this\n",
2434 getprogname());
2437 struct got_checkout_progress_arg {
2438 const char *worktree_path;
2439 int had_base_commit_ref_error;
2442 static const struct got_error *
2443 checkout_progress(void *arg, unsigned char status, const char *path)
2445 struct got_checkout_progress_arg *a = arg;
2447 /* Base commit bump happens silently. */
2448 if (status == GOT_STATUS_BUMP_BASE)
2449 return NULL;
2451 if (status == GOT_STATUS_BASE_REF_ERR) {
2452 a->had_base_commit_ref_error = 1;
2453 return NULL;
2456 while (path[0] == '/')
2457 path++;
2459 printf("%c %s/%s\n", status, a->worktree_path, path);
2460 return NULL;
2463 static const struct got_error *
2464 check_cancelled(void *arg)
2466 if (sigint_received || sigpipe_received)
2467 return got_error(GOT_ERR_CANCELLED);
2468 return NULL;
2471 static const struct got_error *
2472 check_linear_ancestry(struct got_object_id *commit_id,
2473 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2474 struct got_repository *repo)
2476 const struct got_error *err = NULL;
2477 struct got_object_id *yca_id;
2479 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2480 commit_id, base_commit_id, repo, check_cancelled, NULL);
2481 if (err)
2482 return err;
2484 if (yca_id == NULL)
2485 return got_error(GOT_ERR_ANCESTRY);
2488 * Require a straight line of history between the target commit
2489 * and the work tree's base commit.
2491 * Non-linear situations such as this require a rebase:
2493 * (commit) D F (base_commit)
2494 * \ /
2495 * C E
2496 * \ /
2497 * B (yca)
2498 * |
2499 * A
2501 * 'got update' only handles linear cases:
2502 * Update forwards in time: A (base/yca) - B - C - D (commit)
2503 * Update backwards in time: D (base) - C - B - A (commit/yca)
2505 if (allow_forwards_in_time_only) {
2506 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2507 return got_error(GOT_ERR_ANCESTRY);
2508 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2509 got_object_id_cmp(base_commit_id, yca_id) != 0)
2510 return got_error(GOT_ERR_ANCESTRY);
2512 free(yca_id);
2513 return NULL;
2516 static const struct got_error *
2517 check_same_branch(struct got_object_id *commit_id,
2518 struct got_reference *head_ref, struct got_object_id *yca_id,
2519 struct got_repository *repo)
2521 const struct got_error *err = NULL;
2522 struct got_commit_graph *graph = NULL;
2523 struct got_object_id *head_commit_id = NULL;
2524 int is_same_branch = 0;
2526 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2527 if (err)
2528 goto done;
2530 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2531 is_same_branch = 1;
2532 goto done;
2534 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2535 is_same_branch = 1;
2536 goto done;
2539 err = got_commit_graph_open(&graph, "/", 1);
2540 if (err)
2541 goto done;
2543 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2544 check_cancelled, NULL);
2545 if (err)
2546 goto done;
2548 for (;;) {
2549 struct got_object_id *id;
2550 err = got_commit_graph_iter_next(&id, graph, repo,
2551 check_cancelled, NULL);
2552 if (err) {
2553 if (err->code == GOT_ERR_ITER_COMPLETED)
2554 err = NULL;
2555 break;
2558 if (id) {
2559 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2560 break;
2561 if (got_object_id_cmp(id, commit_id) == 0) {
2562 is_same_branch = 1;
2563 break;
2567 done:
2568 if (graph)
2569 got_commit_graph_close(graph);
2570 free(head_commit_id);
2571 if (!err && !is_same_branch)
2572 err = got_error(GOT_ERR_ANCESTRY);
2573 return err;
2576 static const struct got_error *
2577 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2579 static char msg[512];
2580 const char *branch_name;
2582 if (got_ref_is_symbolic(ref))
2583 branch_name = got_ref_get_symref_target(ref);
2584 else
2585 branch_name = got_ref_get_name(ref);
2587 if (strncmp("refs/heads/", branch_name, 11) == 0)
2588 branch_name += 11;
2590 snprintf(msg, sizeof(msg),
2591 "target commit is not contained in branch '%s'; "
2592 "the branch to use must be specified with -b; "
2593 "if necessary a new branch can be created for "
2594 "this commit with 'got branch -c %s BRANCH_NAME'",
2595 branch_name, commit_id_str);
2597 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2600 static const struct got_error *
2601 cmd_checkout(int argc, char *argv[])
2603 const struct got_error *error = NULL;
2604 struct got_repository *repo = NULL;
2605 struct got_reference *head_ref = NULL;
2606 struct got_worktree *worktree = NULL;
2607 char *repo_path = NULL;
2608 char *worktree_path = NULL;
2609 const char *path_prefix = "";
2610 const char *branch_name = GOT_REF_HEAD;
2611 char *commit_id_str = NULL;
2612 char *cwd = NULL;
2613 int ch, same_path_prefix, allow_nonempty = 0;
2614 struct got_pathlist_head paths;
2615 struct got_checkout_progress_arg cpa;
2617 TAILQ_INIT(&paths);
2619 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2620 switch (ch) {
2621 case 'b':
2622 branch_name = optarg;
2623 break;
2624 case 'c':
2625 commit_id_str = strdup(optarg);
2626 if (commit_id_str == NULL)
2627 return got_error_from_errno("strdup");
2628 break;
2629 case 'E':
2630 allow_nonempty = 1;
2631 break;
2632 case 'p':
2633 path_prefix = optarg;
2634 break;
2635 default:
2636 usage_checkout();
2637 /* NOTREACHED */
2641 argc -= optind;
2642 argv += optind;
2644 #ifndef PROFILE
2645 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2646 "unveil", NULL) == -1)
2647 err(1, "pledge");
2648 #endif
2649 if (argc == 1) {
2650 char *base, *dotgit;
2651 const char *path;
2652 repo_path = realpath(argv[0], NULL);
2653 if (repo_path == NULL)
2654 return got_error_from_errno2("realpath", argv[0]);
2655 cwd = getcwd(NULL, 0);
2656 if (cwd == NULL) {
2657 error = got_error_from_errno("getcwd");
2658 goto done;
2660 if (path_prefix[0])
2661 path = path_prefix;
2662 else
2663 path = repo_path;
2664 error = got_path_basename(&base, path);
2665 if (error)
2666 goto done;
2667 dotgit = strstr(base, ".git");
2668 if (dotgit)
2669 *dotgit = '\0';
2670 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2671 error = got_error_from_errno("asprintf");
2672 free(base);
2673 goto done;
2675 free(base);
2676 } else if (argc == 2) {
2677 repo_path = realpath(argv[0], NULL);
2678 if (repo_path == NULL) {
2679 error = got_error_from_errno2("realpath", argv[0]);
2680 goto done;
2682 worktree_path = realpath(argv[1], NULL);
2683 if (worktree_path == NULL) {
2684 if (errno != ENOENT) {
2685 error = got_error_from_errno2("realpath",
2686 argv[1]);
2687 goto done;
2689 worktree_path = strdup(argv[1]);
2690 if (worktree_path == NULL) {
2691 error = got_error_from_errno("strdup");
2692 goto done;
2695 } else
2696 usage_checkout();
2698 got_path_strip_trailing_slashes(repo_path);
2699 got_path_strip_trailing_slashes(worktree_path);
2701 error = got_repo_open(&repo, repo_path, NULL);
2702 if (error != NULL)
2703 goto done;
2705 /* Pre-create work tree path for unveil(2) */
2706 error = got_path_mkdir(worktree_path);
2707 if (error) {
2708 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2709 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2710 goto done;
2711 if (!allow_nonempty &&
2712 !got_path_dir_is_empty(worktree_path)) {
2713 error = got_error_path(worktree_path,
2714 GOT_ERR_DIR_NOT_EMPTY);
2715 goto done;
2719 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2720 if (error)
2721 goto done;
2723 error = got_ref_open(&head_ref, repo, branch_name, 0);
2724 if (error != NULL)
2725 goto done;
2727 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2728 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2729 goto done;
2731 error = got_worktree_open(&worktree, worktree_path);
2732 if (error != NULL)
2733 goto done;
2735 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2736 path_prefix);
2737 if (error != NULL)
2738 goto done;
2739 if (!same_path_prefix) {
2740 error = got_error(GOT_ERR_PATH_PREFIX);
2741 goto done;
2744 if (commit_id_str) {
2745 struct got_object_id *commit_id;
2746 struct got_reflist_head refs;
2747 TAILQ_INIT(&refs);
2748 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2749 NULL);
2750 if (error)
2751 goto done;
2752 error = got_repo_match_object_id(&commit_id, NULL,
2753 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2754 got_ref_list_free(&refs);
2755 if (error)
2756 goto done;
2757 error = check_linear_ancestry(commit_id,
2758 got_worktree_get_base_commit_id(worktree), 0, repo);
2759 if (error != NULL) {
2760 free(commit_id);
2761 if (error->code == GOT_ERR_ANCESTRY) {
2762 error = checkout_ancestry_error(
2763 head_ref, commit_id_str);
2765 goto done;
2767 error = check_same_branch(commit_id, head_ref, NULL, repo);
2768 if (error) {
2769 if (error->code == GOT_ERR_ANCESTRY) {
2770 error = checkout_ancestry_error(
2771 head_ref, commit_id_str);
2773 goto done;
2775 error = got_worktree_set_base_commit_id(worktree, repo,
2776 commit_id);
2777 free(commit_id);
2778 if (error)
2779 goto done;
2782 error = got_pathlist_append(&paths, "", NULL);
2783 if (error)
2784 goto done;
2785 cpa.worktree_path = worktree_path;
2786 cpa.had_base_commit_ref_error = 0;
2787 error = got_worktree_checkout_files(worktree, &paths, repo,
2788 checkout_progress, &cpa, check_cancelled, NULL);
2789 if (error != NULL)
2790 goto done;
2792 printf("Now shut up and hack\n");
2793 if (cpa.had_base_commit_ref_error)
2794 show_worktree_base_ref_warning();
2795 done:
2796 got_pathlist_free(&paths);
2797 free(commit_id_str);
2798 free(repo_path);
2799 free(worktree_path);
2800 free(cwd);
2801 return error;
2804 struct got_update_progress_arg {
2805 int did_something;
2806 int conflicts;
2807 int obstructed;
2808 int not_updated;
2811 void
2812 print_update_progress_stats(struct got_update_progress_arg *upa)
2814 if (!upa->did_something)
2815 return;
2817 if (upa->conflicts > 0)
2818 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2819 if (upa->obstructed > 0)
2820 printf("File paths obstructed by a non-regular file: %d\n",
2821 upa->obstructed);
2822 if (upa->not_updated > 0)
2823 printf("Files not updated because of existing merge "
2824 "conflicts: %d\n", upa->not_updated);
2827 __dead static void
2828 usage_update(void)
2830 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2831 getprogname());
2832 exit(1);
2835 static const struct got_error *
2836 update_progress(void *arg, unsigned char status, const char *path)
2838 struct got_update_progress_arg *upa = arg;
2840 if (status == GOT_STATUS_EXISTS ||
2841 status == GOT_STATUS_BASE_REF_ERR)
2842 return NULL;
2844 upa->did_something = 1;
2846 /* Base commit bump happens silently. */
2847 if (status == GOT_STATUS_BUMP_BASE)
2848 return NULL;
2850 if (status == GOT_STATUS_CONFLICT)
2851 upa->conflicts++;
2852 if (status == GOT_STATUS_OBSTRUCTED)
2853 upa->obstructed++;
2854 if (status == GOT_STATUS_CANNOT_UPDATE)
2855 upa->not_updated++;
2857 while (path[0] == '/')
2858 path++;
2859 printf("%c %s\n", status, path);
2860 return NULL;
2863 static const struct got_error *
2864 switch_head_ref(struct got_reference *head_ref,
2865 struct got_object_id *commit_id, struct got_worktree *worktree,
2866 struct got_repository *repo)
2868 const struct got_error *err = NULL;
2869 char *base_id_str;
2870 int ref_has_moved = 0;
2872 /* Trivial case: switching between two different references. */
2873 if (strcmp(got_ref_get_name(head_ref),
2874 got_worktree_get_head_ref_name(worktree)) != 0) {
2875 printf("Switching work tree from %s to %s\n",
2876 got_worktree_get_head_ref_name(worktree),
2877 got_ref_get_name(head_ref));
2878 return got_worktree_set_head_ref(worktree, head_ref);
2881 err = check_linear_ancestry(commit_id,
2882 got_worktree_get_base_commit_id(worktree), 0, repo);
2883 if (err) {
2884 if (err->code != GOT_ERR_ANCESTRY)
2885 return err;
2886 ref_has_moved = 1;
2888 if (!ref_has_moved)
2889 return NULL;
2891 /* Switching to a rebased branch with the same reference name. */
2892 err = got_object_id_str(&base_id_str,
2893 got_worktree_get_base_commit_id(worktree));
2894 if (err)
2895 return err;
2896 printf("Reference %s now points at a different branch\n",
2897 got_worktree_get_head_ref_name(worktree));
2898 printf("Switching work tree from %s to %s\n", base_id_str,
2899 got_worktree_get_head_ref_name(worktree));
2900 return NULL;
2903 static const struct got_error *
2904 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2906 const struct got_error *err;
2907 int in_progress;
2909 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2910 if (err)
2911 return err;
2912 if (in_progress)
2913 return got_error(GOT_ERR_REBASING);
2915 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2916 if (err)
2917 return err;
2918 if (in_progress)
2919 return got_error(GOT_ERR_HISTEDIT_BUSY);
2921 return NULL;
2924 static const struct got_error *
2925 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2926 char *argv[], struct got_worktree *worktree)
2928 const struct got_error *err = NULL;
2929 char *path;
2930 int i;
2932 if (argc == 0) {
2933 path = strdup("");
2934 if (path == NULL)
2935 return got_error_from_errno("strdup");
2936 return got_pathlist_append(paths, path, NULL);
2939 for (i = 0; i < argc; i++) {
2940 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2941 if (err)
2942 break;
2943 err = got_pathlist_append(paths, path, NULL);
2944 if (err) {
2945 free(path);
2946 break;
2950 return err;
2953 static const struct got_error *
2954 wrap_not_worktree_error(const struct got_error *orig_err,
2955 const char *cmdname, const char *path)
2957 const struct got_error *err;
2958 struct got_repository *repo;
2959 static char msg[512];
2961 err = got_repo_open(&repo, path, NULL);
2962 if (err)
2963 return orig_err;
2965 snprintf(msg, sizeof(msg),
2966 "'got %s' needs a work tree in addition to a git repository\n"
2967 "Work trees can be checked out from this Git repository with "
2968 "'got checkout'.\n"
2969 "The got(1) manual page contains more information.", cmdname);
2970 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2971 got_repo_close(repo);
2972 return err;
2975 static const struct got_error *
2976 cmd_update(int argc, char *argv[])
2978 const struct got_error *error = NULL;
2979 struct got_repository *repo = NULL;
2980 struct got_worktree *worktree = NULL;
2981 char *worktree_path = NULL;
2982 struct got_object_id *commit_id = NULL;
2983 char *commit_id_str = NULL;
2984 const char *branch_name = NULL;
2985 struct got_reference *head_ref = NULL;
2986 struct got_pathlist_head paths;
2987 struct got_pathlist_entry *pe;
2988 int ch;
2989 struct got_update_progress_arg upa;
2991 TAILQ_INIT(&paths);
2993 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2994 switch (ch) {
2995 case 'b':
2996 branch_name = optarg;
2997 break;
2998 case 'c':
2999 commit_id_str = strdup(optarg);
3000 if (commit_id_str == NULL)
3001 return got_error_from_errno("strdup");
3002 break;
3003 default:
3004 usage_update();
3005 /* NOTREACHED */
3009 argc -= optind;
3010 argv += optind;
3012 #ifndef PROFILE
3013 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3014 "unveil", NULL) == -1)
3015 err(1, "pledge");
3016 #endif
3017 worktree_path = getcwd(NULL, 0);
3018 if (worktree_path == NULL) {
3019 error = got_error_from_errno("getcwd");
3020 goto done;
3022 error = got_worktree_open(&worktree, worktree_path);
3023 if (error) {
3024 if (error->code == GOT_ERR_NOT_WORKTREE)
3025 error = wrap_not_worktree_error(error, "update",
3026 worktree_path);
3027 goto done;
3030 error = check_rebase_or_histedit_in_progress(worktree);
3031 if (error)
3032 goto done;
3034 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3035 NULL);
3036 if (error != NULL)
3037 goto done;
3039 error = apply_unveil(got_repo_get_path(repo), 0,
3040 got_worktree_get_root_path(worktree));
3041 if (error)
3042 goto done;
3044 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3045 if (error)
3046 goto done;
3048 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3049 got_worktree_get_head_ref_name(worktree), 0);
3050 if (error != NULL)
3051 goto done;
3052 if (commit_id_str == NULL) {
3053 error = got_ref_resolve(&commit_id, repo, head_ref);
3054 if (error != NULL)
3055 goto done;
3056 error = got_object_id_str(&commit_id_str, commit_id);
3057 if (error != NULL)
3058 goto done;
3059 } else {
3060 struct got_reflist_head refs;
3061 TAILQ_INIT(&refs);
3062 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3063 NULL);
3064 if (error)
3065 goto done;
3066 error = got_repo_match_object_id(&commit_id, NULL,
3067 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3068 got_ref_list_free(&refs);
3069 free(commit_id_str);
3070 commit_id_str = NULL;
3071 if (error)
3072 goto done;
3073 error = got_object_id_str(&commit_id_str, commit_id);
3074 if (error)
3075 goto done;
3078 if (branch_name) {
3079 struct got_object_id *head_commit_id;
3080 TAILQ_FOREACH(pe, &paths, entry) {
3081 if (pe->path_len == 0)
3082 continue;
3083 error = got_error_msg(GOT_ERR_BAD_PATH,
3084 "switching between branches requires that "
3085 "the entire work tree gets updated");
3086 goto done;
3088 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3089 if (error)
3090 goto done;
3091 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3092 repo);
3093 free(head_commit_id);
3094 if (error != NULL)
3095 goto done;
3096 error = check_same_branch(commit_id, head_ref, NULL, repo);
3097 if (error)
3098 goto done;
3099 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3100 if (error)
3101 goto done;
3102 } else {
3103 error = check_linear_ancestry(commit_id,
3104 got_worktree_get_base_commit_id(worktree), 0, repo);
3105 if (error != NULL) {
3106 if (error->code == GOT_ERR_ANCESTRY)
3107 error = got_error(GOT_ERR_BRANCH_MOVED);
3108 goto done;
3110 error = check_same_branch(commit_id, head_ref, NULL, repo);
3111 if (error)
3112 goto done;
3115 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3116 commit_id) != 0) {
3117 error = got_worktree_set_base_commit_id(worktree, repo,
3118 commit_id);
3119 if (error)
3120 goto done;
3123 memset(&upa, 0, sizeof(upa));
3124 error = got_worktree_checkout_files(worktree, &paths, repo,
3125 update_progress, &upa, check_cancelled, NULL);
3126 if (error != NULL)
3127 goto done;
3129 if (upa.did_something)
3130 printf("Updated to commit %s\n", commit_id_str);
3131 else
3132 printf("Already up-to-date\n");
3133 print_update_progress_stats(&upa);
3134 done:
3135 free(worktree_path);
3136 TAILQ_FOREACH(pe, &paths, entry)
3137 free((char *)pe->path);
3138 got_pathlist_free(&paths);
3139 free(commit_id);
3140 free(commit_id_str);
3141 return error;
3144 static const struct got_error *
3145 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3146 const char *path, int diff_context, int ignore_whitespace,
3147 int force_text_diff, struct got_repository *repo)
3149 const struct got_error *err = NULL;
3150 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3152 if (blob_id1) {
3153 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3154 if (err)
3155 goto done;
3158 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3159 if (err)
3160 goto done;
3162 while (path[0] == '/')
3163 path++;
3164 err = got_diff_blob(NULL, NULL, blob1, blob2, path, path,
3165 diff_context, ignore_whitespace, force_text_diff, stdout);
3166 done:
3167 if (blob1)
3168 got_object_blob_close(blob1);
3169 got_object_blob_close(blob2);
3170 return err;
3173 static const struct got_error *
3174 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3175 const char *path, int diff_context, int ignore_whitespace,
3176 int force_text_diff, struct got_repository *repo)
3178 const struct got_error *err = NULL;
3179 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3180 struct got_diff_blob_output_unidiff_arg arg;
3182 if (tree_id1) {
3183 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3184 if (err)
3185 goto done;
3188 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3189 if (err)
3190 goto done;
3192 arg.diff_context = diff_context;
3193 arg.ignore_whitespace = ignore_whitespace;
3194 arg.force_text_diff = force_text_diff;
3195 arg.outfile = stdout;
3196 arg.line_offsets = NULL;
3197 arg.nlines = 0;
3198 while (path[0] == '/')
3199 path++;
3200 err = got_diff_tree(tree1, tree2, path, path, repo,
3201 got_diff_blob_output_unidiff, &arg, 1);
3202 done:
3203 if (tree1)
3204 got_object_tree_close(tree1);
3205 if (tree2)
3206 got_object_tree_close(tree2);
3207 return err;
3210 static const struct got_error *
3211 get_changed_paths(struct got_pathlist_head *paths,
3212 struct got_commit_object *commit, struct got_repository *repo)
3214 const struct got_error *err = NULL;
3215 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3216 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3217 struct got_object_qid *qid;
3219 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3220 if (qid != NULL) {
3221 struct got_commit_object *pcommit;
3222 err = got_object_open_as_commit(&pcommit, repo,
3223 qid->id);
3224 if (err)
3225 return err;
3227 tree_id1 = got_object_commit_get_tree_id(pcommit);
3228 got_object_commit_close(pcommit);
3232 if (tree_id1) {
3233 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3234 if (err)
3235 goto done;
3238 tree_id2 = got_object_commit_get_tree_id(commit);
3239 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3240 if (err)
3241 goto done;
3243 err = got_diff_tree(tree1, tree2, "", "", repo,
3244 got_diff_tree_collect_changed_paths, paths, 0);
3245 done:
3246 if (tree1)
3247 got_object_tree_close(tree1);
3248 if (tree2)
3249 got_object_tree_close(tree2);
3250 return err;
3253 static const struct got_error *
3254 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3255 const char *path, int diff_context, struct got_repository *repo)
3257 const struct got_error *err = NULL;
3258 struct got_commit_object *pcommit = NULL;
3259 char *id_str1 = NULL, *id_str2 = NULL;
3260 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3261 struct got_object_qid *qid;
3263 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3264 if (qid != NULL) {
3265 err = got_object_open_as_commit(&pcommit, repo,
3266 qid->id);
3267 if (err)
3268 return err;
3271 if (path && path[0] != '\0') {
3272 int obj_type;
3273 err = got_object_id_by_path(&obj_id2, repo, id, path);
3274 if (err)
3275 goto done;
3276 err = got_object_id_str(&id_str2, obj_id2);
3277 if (err) {
3278 free(obj_id2);
3279 goto done;
3281 if (pcommit) {
3282 err = got_object_id_by_path(&obj_id1, repo,
3283 qid->id, path);
3284 if (err) {
3285 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3286 free(obj_id2);
3287 goto done;
3289 } else {
3290 err = got_object_id_str(&id_str1, obj_id1);
3291 if (err) {
3292 free(obj_id2);
3293 goto done;
3297 err = got_object_get_type(&obj_type, repo, obj_id2);
3298 if (err) {
3299 free(obj_id2);
3300 goto done;
3302 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3303 switch (obj_type) {
3304 case GOT_OBJ_TYPE_BLOB:
3305 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3306 0, 0, repo);
3307 break;
3308 case GOT_OBJ_TYPE_TREE:
3309 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3310 0, 0, repo);
3311 break;
3312 default:
3313 err = got_error(GOT_ERR_OBJ_TYPE);
3314 break;
3316 free(obj_id1);
3317 free(obj_id2);
3318 } else {
3319 obj_id2 = got_object_commit_get_tree_id(commit);
3320 err = got_object_id_str(&id_str2, obj_id2);
3321 if (err)
3322 goto done;
3323 if (pcommit) {
3324 obj_id1 = got_object_commit_get_tree_id(pcommit);
3325 err = got_object_id_str(&id_str1, obj_id1);
3326 if (err)
3327 goto done;
3329 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null",
3330 id_str2);
3331 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3332 repo);
3334 done:
3335 free(id_str1);
3336 free(id_str2);
3337 if (pcommit)
3338 got_object_commit_close(pcommit);
3339 return err;
3342 static char *
3343 get_datestr(time_t *time, char *datebuf)
3345 struct tm mytm, *tm;
3346 char *p, *s;
3348 tm = gmtime_r(time, &mytm);
3349 if (tm == NULL)
3350 return NULL;
3351 s = asctime_r(tm, datebuf);
3352 if (s == NULL)
3353 return NULL;
3354 p = strchr(s, '\n');
3355 if (p)
3356 *p = '\0';
3357 return s;
3360 static const struct got_error *
3361 match_logmsg(int *have_match, struct got_object_id *id,
3362 struct got_commit_object *commit, regex_t *regex)
3364 const struct got_error *err = NULL;
3365 regmatch_t regmatch;
3366 char *id_str = NULL, *logmsg = NULL;
3368 *have_match = 0;
3370 err = got_object_id_str(&id_str, id);
3371 if (err)
3372 return err;
3374 err = got_object_commit_get_logmsg(&logmsg, commit);
3375 if (err)
3376 goto done;
3378 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3379 *have_match = 1;
3380 done:
3381 free(id_str);
3382 free(logmsg);
3383 return err;
3386 static void
3387 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3388 regex_t *regex)
3390 regmatch_t regmatch;
3391 struct got_pathlist_entry *pe;
3393 *have_match = 0;
3395 TAILQ_FOREACH(pe, changed_paths, entry) {
3396 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3397 *have_match = 1;
3398 break;
3403 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3405 static const struct got_error*
3406 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3407 struct got_object_id *id, struct got_repository *repo)
3409 static const struct got_error *err = NULL;
3410 struct got_reflist_entry *re;
3411 char *s;
3412 const char *name;
3414 *refs_str = NULL;
3416 TAILQ_FOREACH(re, refs, entry) {
3417 struct got_tag_object *tag = NULL;
3418 struct got_object_id *ref_id;
3419 int cmp;
3421 name = got_ref_get_name(re->ref);
3422 if (strcmp(name, GOT_REF_HEAD) == 0)
3423 continue;
3424 if (strncmp(name, "refs/", 5) == 0)
3425 name += 5;
3426 if (strncmp(name, "got/", 4) == 0)
3427 continue;
3428 if (strncmp(name, "heads/", 6) == 0)
3429 name += 6;
3430 if (strncmp(name, "remotes/", 8) == 0) {
3431 name += 8;
3432 s = strstr(name, "/" GOT_REF_HEAD);
3433 if (s != NULL && s[strlen(s)] == '\0')
3434 continue;
3436 err = got_ref_resolve(&ref_id, repo, re->ref);
3437 if (err)
3438 break;
3439 if (strncmp(name, "tags/", 5) == 0) {
3440 err = got_object_open_as_tag(&tag, repo, ref_id);
3441 if (err) {
3442 if (err->code != GOT_ERR_OBJ_TYPE) {
3443 free(ref_id);
3444 break;
3446 /* Ref points at something other than a tag. */
3447 err = NULL;
3448 tag = NULL;
3451 cmp = got_object_id_cmp(tag ?
3452 got_object_tag_get_object_id(tag) : ref_id, id);
3453 free(ref_id);
3454 if (tag)
3455 got_object_tag_close(tag);
3456 if (cmp != 0)
3457 continue;
3458 s = *refs_str;
3459 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3460 s ? ", " : "", name) == -1) {
3461 err = got_error_from_errno("asprintf");
3462 free(s);
3463 *refs_str = NULL;
3464 break;
3466 free(s);
3469 return err;
3472 static const struct got_error *
3473 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3474 struct got_repository *repo, const char *path,
3475 struct got_pathlist_head *changed_paths, int show_patch,
3476 int diff_context, struct got_reflist_object_id_map *refs_idmap)
3478 const struct got_error *err = NULL;
3479 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3480 char datebuf[26];
3481 time_t committer_time;
3482 const char *author, *committer;
3483 char *refs_str = NULL;
3484 struct got_reflist_head *refs;
3486 err = got_object_id_str(&id_str, id);
3487 if (err)
3488 return err;
3490 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3491 if (refs) {
3492 err = build_refs_str(&refs_str, refs, id, repo);
3493 if (err)
3494 goto done;
3497 printf(GOT_COMMIT_SEP_STR);
3498 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3499 refs_str ? refs_str : "", refs_str ? ")" : "");
3500 free(id_str);
3501 id_str = NULL;
3502 free(refs_str);
3503 refs_str = NULL;
3504 printf("from: %s\n", got_object_commit_get_author(commit));
3505 committer_time = got_object_commit_get_committer_time(commit);
3506 datestr = get_datestr(&committer_time, datebuf);
3507 if (datestr)
3508 printf("date: %s UTC\n", datestr);
3509 author = got_object_commit_get_author(commit);
3510 committer = got_object_commit_get_committer(commit);
3511 if (strcmp(author, committer) != 0)
3512 printf("via: %s\n", committer);
3513 if (got_object_commit_get_nparents(commit) > 1) {
3514 const struct got_object_id_queue *parent_ids;
3515 struct got_object_qid *qid;
3516 int n = 1;
3517 parent_ids = got_object_commit_get_parent_ids(commit);
3518 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3519 err = got_object_id_str(&id_str, qid->id);
3520 if (err)
3521 goto done;
3522 printf("parent %d: %s\n", n++, id_str);
3523 free(id_str);
3524 id_str = NULL;
3528 err = got_object_commit_get_logmsg(&logmsg0, commit);
3529 if (err)
3530 goto done;
3532 logmsg = logmsg0;
3533 do {
3534 line = strsep(&logmsg, "\n");
3535 if (line)
3536 printf(" %s\n", line);
3537 } while (line);
3538 free(logmsg0);
3540 if (changed_paths) {
3541 struct got_pathlist_entry *pe;
3542 TAILQ_FOREACH(pe, changed_paths, entry) {
3543 struct got_diff_changed_path *cp = pe->data;
3544 printf(" %c %s\n", cp->status, pe->path);
3546 printf("\n");
3548 if (show_patch) {
3549 err = print_patch(commit, id, path, diff_context, repo);
3550 if (err == 0)
3551 printf("\n");
3554 if (fflush(stdout) != 0 && err == NULL)
3555 err = got_error_from_errno("fflush");
3556 done:
3557 free(id_str);
3558 free(refs_str);
3559 return err;
3562 static const struct got_error *
3563 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3564 struct got_repository *repo, const char *path, int show_changed_paths,
3565 int show_patch, const char *search_pattern, int diff_context, int limit,
3566 int log_branches, int reverse_display_order,
3567 struct got_reflist_object_id_map *refs_idmap)
3569 const struct got_error *err;
3570 struct got_commit_graph *graph;
3571 regex_t regex;
3572 int have_match;
3573 struct got_object_id_queue reversed_commits;
3574 struct got_object_qid *qid;
3575 struct got_commit_object *commit;
3576 struct got_pathlist_head changed_paths;
3577 struct got_pathlist_entry *pe;
3579 SIMPLEQ_INIT(&reversed_commits);
3580 TAILQ_INIT(&changed_paths);
3582 if (search_pattern && regcomp(&regex, search_pattern,
3583 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3584 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3586 err = got_commit_graph_open(&graph, path, !log_branches);
3587 if (err)
3588 return err;
3589 err = got_commit_graph_iter_start(graph, root_id, repo,
3590 check_cancelled, NULL);
3591 if (err)
3592 goto done;
3593 for (;;) {
3594 struct got_object_id *id;
3596 if (sigint_received || sigpipe_received)
3597 break;
3599 err = got_commit_graph_iter_next(&id, graph, repo,
3600 check_cancelled, NULL);
3601 if (err) {
3602 if (err->code == GOT_ERR_ITER_COMPLETED)
3603 err = NULL;
3604 break;
3606 if (id == NULL)
3607 break;
3609 err = got_object_open_as_commit(&commit, repo, id);
3610 if (err)
3611 break;
3613 if (show_changed_paths && !reverse_display_order) {
3614 err = get_changed_paths(&changed_paths, commit, repo);
3615 if (err)
3616 break;
3619 if (search_pattern) {
3620 err = match_logmsg(&have_match, id, commit, &regex);
3621 if (err) {
3622 got_object_commit_close(commit);
3623 break;
3625 if (have_match == 0 && show_changed_paths)
3626 match_changed_paths(&have_match,
3627 &changed_paths, &regex);
3628 if (have_match == 0) {
3629 got_object_commit_close(commit);
3630 TAILQ_FOREACH(pe, &changed_paths, entry) {
3631 free((char *)pe->path);
3632 free(pe->data);
3634 got_pathlist_free(&changed_paths);
3635 continue;
3639 if (reverse_display_order) {
3640 err = got_object_qid_alloc(&qid, id);
3641 if (err)
3642 break;
3643 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3644 got_object_commit_close(commit);
3645 } else {
3646 err = print_commit(commit, id, repo, path,
3647 show_changed_paths ? &changed_paths : NULL,
3648 show_patch, diff_context, refs_idmap);
3649 got_object_commit_close(commit);
3650 if (err)
3651 break;
3653 if ((limit && --limit == 0) ||
3654 (end_id && got_object_id_cmp(id, end_id) == 0))
3655 break;
3657 TAILQ_FOREACH(pe, &changed_paths, entry) {
3658 free((char *)pe->path);
3659 free(pe->data);
3661 got_pathlist_free(&changed_paths);
3663 if (reverse_display_order) {
3664 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3665 err = got_object_open_as_commit(&commit, repo, qid->id);
3666 if (err)
3667 break;
3668 if (show_changed_paths) {
3669 err = get_changed_paths(&changed_paths,
3670 commit, repo);
3671 if (err)
3672 break;
3674 err = print_commit(commit, qid->id, repo, path,
3675 show_changed_paths ? &changed_paths : NULL,
3676 show_patch, diff_context, refs_idmap);
3677 got_object_commit_close(commit);
3678 if (err)
3679 break;
3680 TAILQ_FOREACH(pe, &changed_paths, entry) {
3681 free((char *)pe->path);
3682 free(pe->data);
3684 got_pathlist_free(&changed_paths);
3687 done:
3688 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3689 qid = SIMPLEQ_FIRST(&reversed_commits);
3690 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3691 got_object_qid_free(qid);
3693 TAILQ_FOREACH(pe, &changed_paths, entry) {
3694 free((char *)pe->path);
3695 free(pe->data);
3697 got_pathlist_free(&changed_paths);
3698 if (search_pattern)
3699 regfree(&regex);
3700 got_commit_graph_close(graph);
3701 return err;
3704 __dead static void
3705 usage_log(void)
3707 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3708 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3709 "[-R] [path]\n", getprogname());
3710 exit(1);
3713 static int
3714 get_default_log_limit(void)
3716 const char *got_default_log_limit;
3717 long long n;
3718 const char *errstr;
3720 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3721 if (got_default_log_limit == NULL)
3722 return 0;
3723 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3724 if (errstr != NULL)
3725 return 0;
3726 return n;
3729 static const struct got_error *
3730 cmd_log(int argc, char *argv[])
3732 const struct got_error *error;
3733 struct got_repository *repo = NULL;
3734 struct got_worktree *worktree = NULL;
3735 struct got_object_id *start_id = NULL, *end_id = NULL;
3736 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3737 const char *start_commit = NULL, *end_commit = NULL;
3738 const char *search_pattern = NULL;
3739 int diff_context = -1, ch;
3740 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3741 int reverse_display_order = 0;
3742 const char *errstr;
3743 struct got_reflist_head refs;
3744 struct got_reflist_object_id_map *refs_idmap = NULL;
3746 TAILQ_INIT(&refs);
3748 #ifndef PROFILE
3749 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3750 NULL)
3751 == -1)
3752 err(1, "pledge");
3753 #endif
3755 limit = get_default_log_limit();
3757 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3758 switch (ch) {
3759 case 'p':
3760 show_patch = 1;
3761 break;
3762 case 'P':
3763 show_changed_paths = 1;
3764 break;
3765 case 'c':
3766 start_commit = optarg;
3767 break;
3768 case 'C':
3769 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3770 &errstr);
3771 if (errstr != NULL)
3772 err(1, "-C option %s", errstr);
3773 break;
3774 case 'l':
3775 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3776 if (errstr != NULL)
3777 err(1, "-l option %s", errstr);
3778 break;
3779 case 'b':
3780 log_branches = 1;
3781 break;
3782 case 'r':
3783 repo_path = realpath(optarg, NULL);
3784 if (repo_path == NULL)
3785 return got_error_from_errno2("realpath",
3786 optarg);
3787 got_path_strip_trailing_slashes(repo_path);
3788 break;
3789 case 'R':
3790 reverse_display_order = 1;
3791 break;
3792 case 's':
3793 search_pattern = optarg;
3794 break;
3795 case 'x':
3796 end_commit = optarg;
3797 break;
3798 default:
3799 usage_log();
3800 /* NOTREACHED */
3804 argc -= optind;
3805 argv += optind;
3807 if (diff_context == -1)
3808 diff_context = 3;
3809 else if (!show_patch)
3810 errx(1, "-C requires -p");
3812 cwd = getcwd(NULL, 0);
3813 if (cwd == NULL) {
3814 error = got_error_from_errno("getcwd");
3815 goto done;
3818 if (repo_path == NULL) {
3819 error = got_worktree_open(&worktree, cwd);
3820 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3821 goto done;
3822 error = NULL;
3825 if (argc == 1) {
3826 if (worktree) {
3827 error = got_worktree_resolve_path(&path, worktree,
3828 argv[0]);
3829 if (error)
3830 goto done;
3831 } else {
3832 path = strdup(argv[0]);
3833 if (path == NULL) {
3834 error = got_error_from_errno("strdup");
3835 goto done;
3838 } else if (argc != 0)
3839 usage_log();
3841 if (repo_path == NULL) {
3842 repo_path = worktree ?
3843 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3845 if (repo_path == NULL) {
3846 error = got_error_from_errno("strdup");
3847 goto done;
3850 error = got_repo_open(&repo, repo_path, NULL);
3851 if (error != NULL)
3852 goto done;
3854 error = apply_unveil(got_repo_get_path(repo), 1,
3855 worktree ? got_worktree_get_root_path(worktree) : NULL);
3856 if (error)
3857 goto done;
3859 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3860 if (error)
3861 goto done;
3863 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
3864 if (error)
3865 goto done;
3867 if (start_commit == NULL) {
3868 struct got_reference *head_ref;
3869 struct got_commit_object *commit = NULL;
3870 error = got_ref_open(&head_ref, repo,
3871 worktree ? got_worktree_get_head_ref_name(worktree)
3872 : GOT_REF_HEAD, 0);
3873 if (error != NULL)
3874 goto done;
3875 error = got_ref_resolve(&start_id, repo, head_ref);
3876 got_ref_close(head_ref);
3877 if (error != NULL)
3878 goto done;
3879 error = got_object_open_as_commit(&commit, repo,
3880 start_id);
3881 if (error != NULL)
3882 goto done;
3883 got_object_commit_close(commit);
3884 } else {
3885 error = got_repo_match_object_id(&start_id, NULL,
3886 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3887 if (error != NULL)
3888 goto done;
3890 if (end_commit != NULL) {
3891 error = got_repo_match_object_id(&end_id, NULL,
3892 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3893 if (error != NULL)
3894 goto done;
3897 if (worktree) {
3899 * If a path was specified on the command line it was resolved
3900 * to a path in the work tree above. Prepend the work tree's
3901 * path prefix to obtain the corresponding in-repository path.
3903 if (path) {
3904 const char *prefix;
3905 prefix = got_worktree_get_path_prefix(worktree);
3906 if (asprintf(&in_repo_path, "%s%s%s", prefix,
3907 (path[0] != '\0') ? "/" : "", path) == -1) {
3908 error = got_error_from_errno("asprintf");
3909 goto done;
3912 } else
3913 error = got_repo_map_path(&in_repo_path, repo,
3914 path ? path : "");
3915 if (error != NULL)
3916 goto done;
3917 if (in_repo_path) {
3918 free(path);
3919 path = in_repo_path;
3922 error = print_commits(start_id, end_id, repo, path ? path : "",
3923 show_changed_paths, show_patch, search_pattern, diff_context,
3924 limit, log_branches, reverse_display_order, refs_idmap);
3925 done:
3926 free(path);
3927 free(repo_path);
3928 free(cwd);
3929 if (worktree)
3930 got_worktree_close(worktree);
3931 if (repo) {
3932 const struct got_error *repo_error;
3933 repo_error = got_repo_close(repo);
3934 if (error == NULL)
3935 error = repo_error;
3937 if (refs_idmap)
3938 got_reflist_object_id_map_free(refs_idmap);
3939 got_ref_list_free(&refs);
3940 return error;
3943 __dead static void
3944 usage_diff(void)
3946 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
3947 "[-s] [-w] [object1 object2 | path]\n", getprogname());
3948 exit(1);
3951 struct print_diff_arg {
3952 struct got_repository *repo;
3953 struct got_worktree *worktree;
3954 int diff_context;
3955 const char *id_str;
3956 int header_shown;
3957 int diff_staged;
3958 int ignore_whitespace;
3959 int force_text_diff;
3963 * Create a file which contains the target path of a symlink so we can feed
3964 * it as content to the diff engine.
3966 static const struct got_error *
3967 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
3968 const char *abspath)
3970 const struct got_error *err = NULL;
3971 char target_path[PATH_MAX];
3972 ssize_t target_len, outlen;
3974 *fd = -1;
3976 if (dirfd != -1) {
3977 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
3978 if (target_len == -1)
3979 return got_error_from_errno2("readlinkat", abspath);
3980 } else {
3981 target_len = readlink(abspath, target_path, PATH_MAX);
3982 if (target_len == -1)
3983 return got_error_from_errno2("readlink", abspath);
3986 *fd = got_opentempfd();
3987 if (*fd == -1)
3988 return got_error_from_errno("got_opentempfd");
3990 outlen = write(*fd, target_path, target_len);
3991 if (outlen == -1) {
3992 err = got_error_from_errno("got_opentempfd");
3993 goto done;
3996 if (lseek(*fd, 0, SEEK_SET) == -1) {
3997 err = got_error_from_errno2("lseek", abspath);
3998 goto done;
4000 done:
4001 if (err) {
4002 close(*fd);
4003 *fd = -1;
4005 return err;
4008 static const struct got_error *
4009 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4010 const char *path, struct got_object_id *blob_id,
4011 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4012 int dirfd, const char *de_name)
4014 struct print_diff_arg *a = arg;
4015 const struct got_error *err = NULL;
4016 struct got_blob_object *blob1 = NULL;
4017 int fd = -1;
4018 FILE *f2 = NULL;
4019 char *abspath = NULL, *label1 = NULL;
4020 struct stat sb;
4022 if (a->diff_staged) {
4023 if (staged_status != GOT_STATUS_MODIFY &&
4024 staged_status != GOT_STATUS_ADD &&
4025 staged_status != GOT_STATUS_DELETE)
4026 return NULL;
4027 } else {
4028 if (staged_status == GOT_STATUS_DELETE)
4029 return NULL;
4030 if (status == GOT_STATUS_NONEXISTENT)
4031 return got_error_set_errno(ENOENT, path);
4032 if (status != GOT_STATUS_MODIFY &&
4033 status != GOT_STATUS_ADD &&
4034 status != GOT_STATUS_DELETE &&
4035 status != GOT_STATUS_CONFLICT)
4036 return NULL;
4039 if (!a->header_shown) {
4040 printf("diff %s %s%s\n", a->id_str,
4041 got_worktree_get_root_path(a->worktree),
4042 a->diff_staged ? " (staged changes)" : "");
4043 a->header_shown = 1;
4046 if (a->diff_staged) {
4047 const char *label1 = NULL, *label2 = NULL;
4048 switch (staged_status) {
4049 case GOT_STATUS_MODIFY:
4050 label1 = path;
4051 label2 = path;
4052 break;
4053 case GOT_STATUS_ADD:
4054 label2 = path;
4055 break;
4056 case GOT_STATUS_DELETE:
4057 label1 = path;
4058 break;
4059 default:
4060 return got_error(GOT_ERR_FILE_STATUS);
4062 return got_diff_objects_as_blobs(NULL, NULL, blob_id,
4063 staged_blob_id, label1, label2, a->diff_context,
4064 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4067 if (staged_status == GOT_STATUS_ADD ||
4068 staged_status == GOT_STATUS_MODIFY) {
4069 char *id_str;
4070 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4071 8192);
4072 if (err)
4073 goto done;
4074 err = got_object_id_str(&id_str, staged_blob_id);
4075 if (err)
4076 goto done;
4077 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4078 err = got_error_from_errno("asprintf");
4079 free(id_str);
4080 goto done;
4082 free(id_str);
4083 } else if (status != GOT_STATUS_ADD) {
4084 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4085 if (err)
4086 goto done;
4089 if (status != GOT_STATUS_DELETE) {
4090 if (asprintf(&abspath, "%s/%s",
4091 got_worktree_get_root_path(a->worktree), path) == -1) {
4092 err = got_error_from_errno("asprintf");
4093 goto done;
4096 if (dirfd != -1) {
4097 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
4098 if (fd == -1) {
4099 if (errno != ELOOP) {
4100 err = got_error_from_errno2("openat",
4101 abspath);
4102 goto done;
4104 err = get_symlink_target_file(&fd, dirfd,
4105 de_name, abspath);
4106 if (err)
4107 goto done;
4109 } else {
4110 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
4111 if (fd == -1) {
4112 if (errno != ELOOP) {
4113 err = got_error_from_errno2("open",
4114 abspath);
4115 goto done;
4117 err = get_symlink_target_file(&fd, dirfd,
4118 de_name, abspath);
4119 if (err)
4120 goto done;
4123 if (fstat(fd, &sb) == -1) {
4124 err = got_error_from_errno2("fstat", abspath);
4125 goto done;
4127 f2 = fdopen(fd, "r");
4128 if (f2 == NULL) {
4129 err = got_error_from_errno2("fdopen", abspath);
4130 goto done;
4132 fd = -1;
4133 } else
4134 sb.st_size = 0;
4136 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4137 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4138 done:
4139 if (blob1)
4140 got_object_blob_close(blob1);
4141 if (f2 && fclose(f2) == EOF && err == NULL)
4142 err = got_error_from_errno("fclose");
4143 if (fd != -1 && close(fd) == -1 && err == NULL)
4144 err = got_error_from_errno("close");
4145 free(abspath);
4146 return err;
4149 static const struct got_error *
4150 cmd_diff(int argc, char *argv[])
4152 const struct got_error *error;
4153 struct got_repository *repo = NULL;
4154 struct got_worktree *worktree = NULL;
4155 char *cwd = NULL, *repo_path = NULL;
4156 struct got_object_id *id1 = NULL, *id2 = NULL;
4157 const char *id_str1 = NULL, *id_str2 = NULL;
4158 char *label1 = NULL, *label2 = NULL;
4159 int type1, type2;
4160 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
4161 int force_text_diff = 0;
4162 const char *errstr;
4163 char *path = NULL;
4164 struct got_reflist_head refs;
4166 TAILQ_INIT(&refs);
4168 #ifndef PROFILE
4169 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4170 NULL) == -1)
4171 err(1, "pledge");
4172 #endif
4174 while ((ch = getopt(argc, argv, "aC:r:sw")) != -1) {
4175 switch (ch) {
4176 case 'a':
4177 force_text_diff = 1;
4178 break;
4179 case 'C':
4180 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4181 &errstr);
4182 if (errstr != NULL)
4183 err(1, "-C option %s", errstr);
4184 break;
4185 case 'r':
4186 repo_path = realpath(optarg, NULL);
4187 if (repo_path == NULL)
4188 return got_error_from_errno2("realpath",
4189 optarg);
4190 got_path_strip_trailing_slashes(repo_path);
4191 break;
4192 case 's':
4193 diff_staged = 1;
4194 break;
4195 case 'w':
4196 ignore_whitespace = 1;
4197 break;
4198 default:
4199 usage_diff();
4200 /* NOTREACHED */
4204 argc -= optind;
4205 argv += optind;
4207 cwd = getcwd(NULL, 0);
4208 if (cwd == NULL) {
4209 error = got_error_from_errno("getcwd");
4210 goto done;
4212 if (argc <= 1) {
4213 if (repo_path)
4214 errx(1,
4215 "-r option can't be used when diffing a work tree");
4216 error = got_worktree_open(&worktree, cwd);
4217 if (error) {
4218 if (error->code == GOT_ERR_NOT_WORKTREE)
4219 error = wrap_not_worktree_error(error, "diff",
4220 cwd);
4221 goto done;
4223 repo_path = strdup(got_worktree_get_repo_path(worktree));
4224 if (repo_path == NULL) {
4225 error = got_error_from_errno("strdup");
4226 goto done;
4228 if (argc == 1) {
4229 error = got_worktree_resolve_path(&path, worktree,
4230 argv[0]);
4231 if (error)
4232 goto done;
4233 } else {
4234 path = strdup("");
4235 if (path == NULL) {
4236 error = got_error_from_errno("strdup");
4237 goto done;
4240 } else if (argc == 2) {
4241 if (diff_staged)
4242 errx(1, "-s option can't be used when diffing "
4243 "objects in repository");
4244 id_str1 = argv[0];
4245 id_str2 = argv[1];
4246 if (repo_path == NULL) {
4247 error = got_worktree_open(&worktree, cwd);
4248 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4249 goto done;
4250 if (worktree) {
4251 repo_path = strdup(
4252 got_worktree_get_repo_path(worktree));
4253 if (repo_path == NULL) {
4254 error = got_error_from_errno("strdup");
4255 goto done;
4257 } else {
4258 repo_path = strdup(cwd);
4259 if (repo_path == NULL) {
4260 error = got_error_from_errno("strdup");
4261 goto done;
4265 } else
4266 usage_diff();
4268 error = got_repo_open(&repo, repo_path, NULL);
4269 free(repo_path);
4270 if (error != NULL)
4271 goto done;
4273 error = apply_unveil(got_repo_get_path(repo), 1,
4274 worktree ? got_worktree_get_root_path(worktree) : NULL);
4275 if (error)
4276 goto done;
4278 if (argc <= 1) {
4279 struct print_diff_arg arg;
4280 struct got_pathlist_head paths;
4281 char *id_str;
4283 TAILQ_INIT(&paths);
4285 error = got_object_id_str(&id_str,
4286 got_worktree_get_base_commit_id(worktree));
4287 if (error)
4288 goto done;
4289 arg.repo = repo;
4290 arg.worktree = worktree;
4291 arg.diff_context = diff_context;
4292 arg.id_str = id_str;
4293 arg.header_shown = 0;
4294 arg.diff_staged = diff_staged;
4295 arg.ignore_whitespace = ignore_whitespace;
4296 arg.force_text_diff = force_text_diff;
4298 error = got_pathlist_append(&paths, path, NULL);
4299 if (error)
4300 goto done;
4302 error = got_worktree_status(worktree, &paths, repo, print_diff,
4303 &arg, check_cancelled, NULL);
4304 free(id_str);
4305 got_pathlist_free(&paths);
4306 goto done;
4309 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4310 if (error)
4311 return error;
4313 error = got_repo_match_object_id(&id1, &label1, id_str1,
4314 GOT_OBJ_TYPE_ANY, &refs, repo);
4315 if (error)
4316 goto done;
4318 error = got_repo_match_object_id(&id2, &label2, id_str2,
4319 GOT_OBJ_TYPE_ANY, &refs, repo);
4320 if (error)
4321 goto done;
4323 error = got_object_get_type(&type1, repo, id1);
4324 if (error)
4325 goto done;
4327 error = got_object_get_type(&type2, repo, id2);
4328 if (error)
4329 goto done;
4331 if (type1 != type2) {
4332 error = got_error(GOT_ERR_OBJ_TYPE);
4333 goto done;
4336 switch (type1) {
4337 case GOT_OBJ_TYPE_BLOB:
4338 error = got_diff_objects_as_blobs(NULL, NULL, id1, id2,
4339 NULL, NULL, diff_context, ignore_whitespace,
4340 force_text_diff, repo, stdout);
4341 break;
4342 case GOT_OBJ_TYPE_TREE:
4343 error = got_diff_objects_as_trees(NULL, NULL, id1, id2,
4344 "", "", diff_context, ignore_whitespace, force_text_diff,
4345 repo, stdout);
4346 break;
4347 case GOT_OBJ_TYPE_COMMIT:
4348 printf("diff %s %s\n", label1, label2);
4349 error = got_diff_objects_as_commits(NULL, NULL, id1, id2,
4350 diff_context, ignore_whitespace, force_text_diff, repo,
4351 stdout);
4352 break;
4353 default:
4354 error = got_error(GOT_ERR_OBJ_TYPE);
4356 done:
4357 free(label1);
4358 free(label2);
4359 free(id1);
4360 free(id2);
4361 free(path);
4362 if (worktree)
4363 got_worktree_close(worktree);
4364 if (repo) {
4365 const struct got_error *repo_error;
4366 repo_error = got_repo_close(repo);
4367 if (error == NULL)
4368 error = repo_error;
4370 got_ref_list_free(&refs);
4371 return error;
4374 __dead static void
4375 usage_blame(void)
4377 fprintf(stderr,
4378 "usage: %s blame [-c commit] [-r repository-path] path\n",
4379 getprogname());
4380 exit(1);
4383 struct blame_line {
4384 int annotated;
4385 char *id_str;
4386 char *committer;
4387 char datebuf[11]; /* YYYY-MM-DD + NUL */
4390 struct blame_cb_args {
4391 struct blame_line *lines;
4392 int nlines;
4393 int nlines_prec;
4394 int lineno_cur;
4395 off_t *line_offsets;
4396 FILE *f;
4397 struct got_repository *repo;
4400 static const struct got_error *
4401 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4403 const struct got_error *err = NULL;
4404 struct blame_cb_args *a = arg;
4405 struct blame_line *bline;
4406 char *line = NULL;
4407 size_t linesize = 0;
4408 struct got_commit_object *commit = NULL;
4409 off_t offset;
4410 struct tm tm;
4411 time_t committer_time;
4413 if (nlines != a->nlines ||
4414 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4415 return got_error(GOT_ERR_RANGE);
4417 if (sigint_received)
4418 return got_error(GOT_ERR_ITER_COMPLETED);
4420 if (lineno == -1)
4421 return NULL; /* no change in this commit */
4423 /* Annotate this line. */
4424 bline = &a->lines[lineno - 1];
4425 if (bline->annotated)
4426 return NULL;
4427 err = got_object_id_str(&bline->id_str, id);
4428 if (err)
4429 return err;
4431 err = got_object_open_as_commit(&commit, a->repo, id);
4432 if (err)
4433 goto done;
4435 bline->committer = strdup(got_object_commit_get_committer(commit));
4436 if (bline->committer == NULL) {
4437 err = got_error_from_errno("strdup");
4438 goto done;
4441 committer_time = got_object_commit_get_committer_time(commit);
4442 if (localtime_r(&committer_time, &tm) == NULL)
4443 return got_error_from_errno("localtime_r");
4444 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4445 &tm) >= sizeof(bline->datebuf)) {
4446 err = got_error(GOT_ERR_NO_SPACE);
4447 goto done;
4449 bline->annotated = 1;
4451 /* Print lines annotated so far. */
4452 bline = &a->lines[a->lineno_cur - 1];
4453 if (!bline->annotated)
4454 goto done;
4456 offset = a->line_offsets[a->lineno_cur - 1];
4457 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4458 err = got_error_from_errno("fseeko");
4459 goto done;
4462 while (bline->annotated) {
4463 char *smallerthan, *at, *nl, *committer;
4464 size_t len;
4466 if (getline(&line, &linesize, a->f) == -1) {
4467 if (ferror(a->f))
4468 err = got_error_from_errno("getline");
4469 break;
4472 committer = bline->committer;
4473 smallerthan = strchr(committer, '<');
4474 if (smallerthan && smallerthan[1] != '\0')
4475 committer = smallerthan + 1;
4476 at = strchr(committer, '@');
4477 if (at)
4478 *at = '\0';
4479 len = strlen(committer);
4480 if (len >= 9)
4481 committer[8] = '\0';
4483 nl = strchr(line, '\n');
4484 if (nl)
4485 *nl = '\0';
4486 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4487 bline->id_str, bline->datebuf, committer, line);
4489 a->lineno_cur++;
4490 bline = &a->lines[a->lineno_cur - 1];
4492 done:
4493 if (commit)
4494 got_object_commit_close(commit);
4495 free(line);
4496 return err;
4499 static const struct got_error *
4500 cmd_blame(int argc, char *argv[])
4502 const struct got_error *error;
4503 struct got_repository *repo = NULL;
4504 struct got_worktree *worktree = NULL;
4505 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4506 char *link_target = NULL;
4507 struct got_object_id *obj_id = NULL;
4508 struct got_object_id *commit_id = NULL;
4509 struct got_blob_object *blob = NULL;
4510 char *commit_id_str = NULL;
4511 struct blame_cb_args bca;
4512 int ch, obj_type, i;
4513 off_t filesize;
4515 memset(&bca, 0, sizeof(bca));
4517 #ifndef PROFILE
4518 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4519 NULL) == -1)
4520 err(1, "pledge");
4521 #endif
4523 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4524 switch (ch) {
4525 case 'c':
4526 commit_id_str = optarg;
4527 break;
4528 case 'r':
4529 repo_path = realpath(optarg, NULL);
4530 if (repo_path == NULL)
4531 return got_error_from_errno2("realpath",
4532 optarg);
4533 got_path_strip_trailing_slashes(repo_path);
4534 break;
4535 default:
4536 usage_blame();
4537 /* NOTREACHED */
4541 argc -= optind;
4542 argv += optind;
4544 if (argc == 1)
4545 path = argv[0];
4546 else
4547 usage_blame();
4549 cwd = getcwd(NULL, 0);
4550 if (cwd == NULL) {
4551 error = got_error_from_errno("getcwd");
4552 goto done;
4554 if (repo_path == NULL) {
4555 error = got_worktree_open(&worktree, cwd);
4556 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4557 goto done;
4558 else
4559 error = NULL;
4560 if (worktree) {
4561 repo_path =
4562 strdup(got_worktree_get_repo_path(worktree));
4563 if (repo_path == NULL) {
4564 error = got_error_from_errno("strdup");
4565 if (error)
4566 goto done;
4568 } else {
4569 repo_path = strdup(cwd);
4570 if (repo_path == NULL) {
4571 error = got_error_from_errno("strdup");
4572 goto done;
4577 error = got_repo_open(&repo, repo_path, NULL);
4578 if (error != NULL)
4579 goto done;
4581 if (worktree) {
4582 const char *prefix = got_worktree_get_path_prefix(worktree);
4583 char *p;
4585 error = got_worktree_resolve_path(&p, worktree, path);
4586 if (error)
4587 goto done;
4588 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4589 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4590 p) == -1) {
4591 error = got_error_from_errno("asprintf");
4592 free(p);
4593 goto done;
4595 free(p);
4596 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4597 } else {
4598 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4599 if (error)
4600 goto done;
4601 error = got_repo_map_path(&in_repo_path, repo, path);
4603 if (error)
4604 goto done;
4606 if (commit_id_str == NULL) {
4607 struct got_reference *head_ref;
4608 error = got_ref_open(&head_ref, repo, worktree ?
4609 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4610 if (error != NULL)
4611 goto done;
4612 error = got_ref_resolve(&commit_id, repo, head_ref);
4613 got_ref_close(head_ref);
4614 if (error != NULL)
4615 goto done;
4616 } else {
4617 struct got_reflist_head refs;
4618 TAILQ_INIT(&refs);
4619 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4620 NULL);
4621 if (error)
4622 goto done;
4623 error = got_repo_match_object_id(&commit_id, NULL,
4624 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4625 got_ref_list_free(&refs);
4626 if (error)
4627 goto done;
4630 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4631 commit_id, repo);
4632 if (error)
4633 goto done;
4635 error = got_object_id_by_path(&obj_id, repo, commit_id,
4636 link_target ? link_target : in_repo_path);
4637 if (error)
4638 goto done;
4640 error = got_object_get_type(&obj_type, repo, obj_id);
4641 if (error)
4642 goto done;
4644 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4645 error = got_error_path(link_target ? link_target : in_repo_path,
4646 GOT_ERR_OBJ_TYPE);
4647 goto done;
4650 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4651 if (error)
4652 goto done;
4653 bca.f = got_opentemp();
4654 if (bca.f == NULL) {
4655 error = got_error_from_errno("got_opentemp");
4656 goto done;
4658 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4659 &bca.line_offsets, bca.f, blob);
4660 if (error || bca.nlines == 0)
4661 goto done;
4663 /* Don't include \n at EOF in the blame line count. */
4664 if (bca.line_offsets[bca.nlines - 1] == filesize)
4665 bca.nlines--;
4667 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4668 if (bca.lines == NULL) {
4669 error = got_error_from_errno("calloc");
4670 goto done;
4672 bca.lineno_cur = 1;
4673 bca.nlines_prec = 0;
4674 i = bca.nlines;
4675 while (i > 0) {
4676 i /= 10;
4677 bca.nlines_prec++;
4679 bca.repo = repo;
4681 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4682 repo, blame_cb, &bca, check_cancelled, NULL);
4683 done:
4684 free(in_repo_path);
4685 free(link_target);
4686 free(repo_path);
4687 free(cwd);
4688 free(commit_id);
4689 free(obj_id);
4690 if (blob)
4691 got_object_blob_close(blob);
4692 if (worktree)
4693 got_worktree_close(worktree);
4694 if (repo) {
4695 const struct got_error *repo_error;
4696 repo_error = got_repo_close(repo);
4697 if (error == NULL)
4698 error = repo_error;
4700 if (bca.lines) {
4701 for (i = 0; i < bca.nlines; i++) {
4702 struct blame_line *bline = &bca.lines[i];
4703 free(bline->id_str);
4704 free(bline->committer);
4706 free(bca.lines);
4708 free(bca.line_offsets);
4709 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4710 error = got_error_from_errno("fclose");
4711 return error;
4714 __dead static void
4715 usage_tree(void)
4717 fprintf(stderr,
4718 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4719 getprogname());
4720 exit(1);
4723 static const struct got_error *
4724 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4725 const char *root_path, struct got_repository *repo)
4727 const struct got_error *err = NULL;
4728 int is_root_path = (strcmp(path, root_path) == 0);
4729 const char *modestr = "";
4730 mode_t mode = got_tree_entry_get_mode(te);
4731 char *link_target = NULL;
4733 path += strlen(root_path);
4734 while (path[0] == '/')
4735 path++;
4737 if (got_object_tree_entry_is_submodule(te))
4738 modestr = "$";
4739 else if (S_ISLNK(mode)) {
4740 int i;
4742 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4743 if (err)
4744 return err;
4745 for (i = 0; i < strlen(link_target); i++) {
4746 if (!isprint((unsigned char)link_target[i]))
4747 link_target[i] = '?';
4750 modestr = "@";
4752 else if (S_ISDIR(mode))
4753 modestr = "/";
4754 else if (mode & S_IXUSR)
4755 modestr = "*";
4757 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4758 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4759 link_target ? " -> ": "", link_target ? link_target : "");
4761 free(link_target);
4762 return NULL;
4765 static const struct got_error *
4766 print_tree(const char *path, struct got_object_id *commit_id,
4767 int show_ids, int recurse, const char *root_path,
4768 struct got_repository *repo)
4770 const struct got_error *err = NULL;
4771 struct got_object_id *tree_id = NULL;
4772 struct got_tree_object *tree = NULL;
4773 int nentries, i;
4775 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4776 if (err)
4777 goto done;
4779 err = got_object_open_as_tree(&tree, repo, tree_id);
4780 if (err)
4781 goto done;
4782 nentries = got_object_tree_get_nentries(tree);
4783 for (i = 0; i < nentries; i++) {
4784 struct got_tree_entry *te;
4785 char *id = NULL;
4787 if (sigint_received || sigpipe_received)
4788 break;
4790 te = got_object_tree_get_entry(tree, i);
4791 if (show_ids) {
4792 char *id_str;
4793 err = got_object_id_str(&id_str,
4794 got_tree_entry_get_id(te));
4795 if (err)
4796 goto done;
4797 if (asprintf(&id, "%s ", id_str) == -1) {
4798 err = got_error_from_errno("asprintf");
4799 free(id_str);
4800 goto done;
4802 free(id_str);
4804 err = print_entry(te, id, path, root_path, repo);
4805 free(id);
4806 if (err)
4807 goto done;
4809 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4810 char *child_path;
4811 if (asprintf(&child_path, "%s%s%s", path,
4812 path[0] == '/' && path[1] == '\0' ? "" : "/",
4813 got_tree_entry_get_name(te)) == -1) {
4814 err = got_error_from_errno("asprintf");
4815 goto done;
4817 err = print_tree(child_path, commit_id, show_ids, 1,
4818 root_path, repo);
4819 free(child_path);
4820 if (err)
4821 goto done;
4824 done:
4825 if (tree)
4826 got_object_tree_close(tree);
4827 free(tree_id);
4828 return err;
4831 static const struct got_error *
4832 cmd_tree(int argc, char *argv[])
4834 const struct got_error *error;
4835 struct got_repository *repo = NULL;
4836 struct got_worktree *worktree = NULL;
4837 const char *path, *refname = NULL;
4838 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4839 struct got_object_id *commit_id = NULL;
4840 char *commit_id_str = NULL;
4841 int show_ids = 0, recurse = 0;
4842 int ch;
4844 #ifndef PROFILE
4845 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4846 NULL) == -1)
4847 err(1, "pledge");
4848 #endif
4850 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4851 switch (ch) {
4852 case 'c':
4853 commit_id_str = optarg;
4854 break;
4855 case 'r':
4856 repo_path = realpath(optarg, NULL);
4857 if (repo_path == NULL)
4858 return got_error_from_errno2("realpath",
4859 optarg);
4860 got_path_strip_trailing_slashes(repo_path);
4861 break;
4862 case 'i':
4863 show_ids = 1;
4864 break;
4865 case 'R':
4866 recurse = 1;
4867 break;
4868 default:
4869 usage_tree();
4870 /* NOTREACHED */
4874 argc -= optind;
4875 argv += optind;
4877 if (argc == 1)
4878 path = argv[0];
4879 else if (argc > 1)
4880 usage_tree();
4881 else
4882 path = NULL;
4884 cwd = getcwd(NULL, 0);
4885 if (cwd == NULL) {
4886 error = got_error_from_errno("getcwd");
4887 goto done;
4889 if (repo_path == NULL) {
4890 error = got_worktree_open(&worktree, cwd);
4891 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4892 goto done;
4893 else
4894 error = NULL;
4895 if (worktree) {
4896 repo_path =
4897 strdup(got_worktree_get_repo_path(worktree));
4898 if (repo_path == NULL)
4899 error = got_error_from_errno("strdup");
4900 if (error)
4901 goto done;
4902 } else {
4903 repo_path = strdup(cwd);
4904 if (repo_path == NULL) {
4905 error = got_error_from_errno("strdup");
4906 goto done;
4911 error = got_repo_open(&repo, repo_path, NULL);
4912 if (error != NULL)
4913 goto done;
4915 if (worktree) {
4916 const char *prefix = got_worktree_get_path_prefix(worktree);
4917 char *p;
4919 if (path == NULL)
4920 path = "";
4921 error = got_worktree_resolve_path(&p, worktree, path);
4922 if (error)
4923 goto done;
4924 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4925 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4926 p) == -1) {
4927 error = got_error_from_errno("asprintf");
4928 free(p);
4929 goto done;
4931 free(p);
4932 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4933 if (error)
4934 goto done;
4935 } else {
4936 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4937 if (error)
4938 goto done;
4939 if (path == NULL)
4940 path = "/";
4941 error = got_repo_map_path(&in_repo_path, repo, path);
4942 if (error != NULL)
4943 goto done;
4946 if (commit_id_str == NULL) {
4947 struct got_reference *head_ref;
4948 if (worktree)
4949 refname = got_worktree_get_head_ref_name(worktree);
4950 else
4951 refname = GOT_REF_HEAD;
4952 error = got_ref_open(&head_ref, repo, refname, 0);
4953 if (error != NULL)
4954 goto done;
4955 error = got_ref_resolve(&commit_id, repo, head_ref);
4956 got_ref_close(head_ref);
4957 if (error != NULL)
4958 goto done;
4959 } else {
4960 struct got_reflist_head refs;
4961 TAILQ_INIT(&refs);
4962 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4963 NULL);
4964 if (error)
4965 goto done;
4966 error = got_repo_match_object_id(&commit_id, NULL,
4967 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4968 got_ref_list_free(&refs);
4969 if (error)
4970 goto done;
4973 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4974 in_repo_path, repo);
4975 done:
4976 free(in_repo_path);
4977 free(repo_path);
4978 free(cwd);
4979 free(commit_id);
4980 if (worktree)
4981 got_worktree_close(worktree);
4982 if (repo) {
4983 const struct got_error *repo_error;
4984 repo_error = got_repo_close(repo);
4985 if (error == NULL)
4986 error = repo_error;
4988 return error;
4991 __dead static void
4992 usage_status(void)
4994 fprintf(stderr, "usage: %s status [-s status-codes ] [path ...]\n",
4995 getprogname());
4996 exit(1);
4999 static const struct got_error *
5000 print_status(void *arg, unsigned char status, unsigned char staged_status,
5001 const char *path, struct got_object_id *blob_id,
5002 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5003 int dirfd, const char *de_name)
5005 if (status == staged_status && (status == GOT_STATUS_DELETE))
5006 status = GOT_STATUS_NO_CHANGE;
5007 if (arg) {
5008 char *status_codes = arg;
5009 size_t ncodes = strlen(status_codes);
5010 int i;
5011 for (i = 0; i < ncodes ; i++) {
5012 if (status == status_codes[i] ||
5013 staged_status == status_codes[i])
5014 break;
5016 if (i == ncodes)
5017 return NULL;
5019 printf("%c%c %s\n", status, staged_status, path);
5020 return NULL;
5023 static const struct got_error *
5024 cmd_status(int argc, char *argv[])
5026 const struct got_error *error = NULL;
5027 struct got_repository *repo = NULL;
5028 struct got_worktree *worktree = NULL;
5029 char *cwd = NULL, *status_codes = NULL;;
5030 struct got_pathlist_head paths;
5031 struct got_pathlist_entry *pe;
5032 int ch, i;
5034 TAILQ_INIT(&paths);
5036 while ((ch = getopt(argc, argv, "s:")) != -1) {
5037 switch (ch) {
5038 case 's':
5039 for (i = 0; i < strlen(optarg); i++) {
5040 switch (optarg[i]) {
5041 case GOT_STATUS_MODIFY:
5042 case GOT_STATUS_ADD:
5043 case GOT_STATUS_DELETE:
5044 case GOT_STATUS_CONFLICT:
5045 case GOT_STATUS_MISSING:
5046 case GOT_STATUS_OBSTRUCTED:
5047 case GOT_STATUS_UNVERSIONED:
5048 case GOT_STATUS_MODE_CHANGE:
5049 case GOT_STATUS_NONEXISTENT:
5050 break;
5051 default:
5052 errx(1, "invalid status code '%c'",
5053 optarg[i]);
5056 status_codes = optarg;
5057 break;
5058 default:
5059 usage_status();
5060 /* NOTREACHED */
5064 argc -= optind;
5065 argv += optind;
5067 #ifndef PROFILE
5068 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5069 NULL) == -1)
5070 err(1, "pledge");
5071 #endif
5072 cwd = getcwd(NULL, 0);
5073 if (cwd == NULL) {
5074 error = got_error_from_errno("getcwd");
5075 goto done;
5078 error = got_worktree_open(&worktree, cwd);
5079 if (error) {
5080 if (error->code == GOT_ERR_NOT_WORKTREE)
5081 error = wrap_not_worktree_error(error, "status", cwd);
5082 goto done;
5085 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5086 NULL);
5087 if (error != NULL)
5088 goto done;
5090 error = apply_unveil(got_repo_get_path(repo), 1,
5091 got_worktree_get_root_path(worktree));
5092 if (error)
5093 goto done;
5095 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5096 if (error)
5097 goto done;
5099 error = got_worktree_status(worktree, &paths, repo, print_status,
5100 status_codes, check_cancelled, NULL);
5101 done:
5102 TAILQ_FOREACH(pe, &paths, entry)
5103 free((char *)pe->path);
5104 got_pathlist_free(&paths);
5105 free(cwd);
5106 return error;
5109 __dead static void
5110 usage_ref(void)
5112 fprintf(stderr,
5113 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
5114 "[-d] [name]\n",
5115 getprogname());
5116 exit(1);
5119 static const struct got_error *
5120 list_refs(struct got_repository *repo, const char *refname)
5122 static const struct got_error *err = NULL;
5123 struct got_reflist_head refs;
5124 struct got_reflist_entry *re;
5126 TAILQ_INIT(&refs);
5127 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
5128 if (err)
5129 return err;
5131 TAILQ_FOREACH(re, &refs, entry) {
5132 char *refstr;
5133 refstr = got_ref_to_str(re->ref);
5134 if (refstr == NULL)
5135 return got_error_from_errno("got_ref_to_str");
5136 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5137 free(refstr);
5140 got_ref_list_free(&refs);
5141 return NULL;
5144 static const struct got_error *
5145 delete_ref(struct got_repository *repo, const char *refname)
5147 const struct got_error *err = NULL;
5148 struct got_reference *ref;
5150 err = got_ref_open(&ref, repo, refname, 0);
5151 if (err)
5152 return err;
5154 err = got_ref_delete(ref, repo);
5155 got_ref_close(ref);
5156 return err;
5159 static const struct got_error *
5160 add_ref(struct got_repository *repo, const char *refname, const char *target)
5162 const struct got_error *err = NULL;
5163 struct got_object_id *id;
5164 struct got_reference *ref = NULL;
5167 * Don't let the user create a reference name with a leading '-'.
5168 * While technically a valid reference name, this case is usually
5169 * an unintended typo.
5171 if (refname[0] == '-')
5172 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5174 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5175 repo);
5176 if (err) {
5177 struct got_reference *target_ref;
5179 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5180 return err;
5181 err = got_ref_open(&target_ref, repo, target, 0);
5182 if (err)
5183 return err;
5184 err = got_ref_resolve(&id, repo, target_ref);
5185 got_ref_close(target_ref);
5186 if (err)
5187 return err;
5190 err = got_ref_alloc(&ref, refname, id);
5191 if (err)
5192 goto done;
5194 err = got_ref_write(ref, repo);
5195 done:
5196 if (ref)
5197 got_ref_close(ref);
5198 free(id);
5199 return err;
5202 static const struct got_error *
5203 add_symref(struct got_repository *repo, const char *refname, const char *target)
5205 const struct got_error *err = NULL;
5206 struct got_reference *ref = NULL;
5207 struct got_reference *target_ref = NULL;
5210 * Don't let the user create a reference name with a leading '-'.
5211 * While technically a valid reference name, this case is usually
5212 * an unintended typo.
5214 if (refname[0] == '-')
5215 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5217 err = got_ref_open(&target_ref, repo, target, 0);
5218 if (err)
5219 return err;
5221 err = got_ref_alloc_symref(&ref, refname, target_ref);
5222 if (err)
5223 goto done;
5225 err = got_ref_write(ref, repo);
5226 done:
5227 if (target_ref)
5228 got_ref_close(target_ref);
5229 if (ref)
5230 got_ref_close(ref);
5231 return err;
5234 static const struct got_error *
5235 cmd_ref(int argc, char *argv[])
5237 const struct got_error *error = NULL;
5238 struct got_repository *repo = NULL;
5239 struct got_worktree *worktree = NULL;
5240 char *cwd = NULL, *repo_path = NULL;
5241 int ch, do_list = 0, do_delete = 0;
5242 const char *obj_arg = NULL, *symref_target= NULL;
5243 char *refname = NULL;
5245 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5246 switch (ch) {
5247 case 'c':
5248 obj_arg = optarg;
5249 break;
5250 case 'd':
5251 do_delete = 1;
5252 break;
5253 case 'r':
5254 repo_path = realpath(optarg, NULL);
5255 if (repo_path == NULL)
5256 return got_error_from_errno2("realpath",
5257 optarg);
5258 got_path_strip_trailing_slashes(repo_path);
5259 break;
5260 case 'l':
5261 do_list = 1;
5262 break;
5263 case 's':
5264 symref_target = optarg;
5265 break;
5266 default:
5267 usage_ref();
5268 /* NOTREACHED */
5272 if (obj_arg && do_list)
5273 option_conflict('c', 'l');
5274 if (obj_arg && do_delete)
5275 option_conflict('c', 'd');
5276 if (obj_arg && symref_target)
5277 option_conflict('c', 's');
5278 if (symref_target && do_delete)
5279 option_conflict('s', 'd');
5280 if (symref_target && do_list)
5281 option_conflict('s', 'l');
5282 if (do_delete && do_list)
5283 option_conflict('d', 'l');
5285 argc -= optind;
5286 argv += optind;
5288 if (do_list) {
5289 if (argc != 0 && argc != 1)
5290 usage_ref();
5291 if (argc == 1) {
5292 refname = strdup(argv[0]);
5293 if (refname == NULL) {
5294 error = got_error_from_errno("strdup");
5295 goto done;
5298 } else {
5299 if (argc != 1)
5300 usage_ref();
5301 refname = strdup(argv[0]);
5302 if (refname == NULL) {
5303 error = got_error_from_errno("strdup");
5304 goto done;
5308 if (refname)
5309 got_path_strip_trailing_slashes(refname);
5311 #ifndef PROFILE
5312 if (do_list) {
5313 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5314 NULL) == -1)
5315 err(1, "pledge");
5316 } else {
5317 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5318 "sendfd unveil", NULL) == -1)
5319 err(1, "pledge");
5321 #endif
5322 cwd = getcwd(NULL, 0);
5323 if (cwd == NULL) {
5324 error = got_error_from_errno("getcwd");
5325 goto done;
5328 if (repo_path == NULL) {
5329 error = got_worktree_open(&worktree, cwd);
5330 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5331 goto done;
5332 else
5333 error = NULL;
5334 if (worktree) {
5335 repo_path =
5336 strdup(got_worktree_get_repo_path(worktree));
5337 if (repo_path == NULL)
5338 error = got_error_from_errno("strdup");
5339 if (error)
5340 goto done;
5341 } else {
5342 repo_path = strdup(cwd);
5343 if (repo_path == NULL) {
5344 error = got_error_from_errno("strdup");
5345 goto done;
5350 error = got_repo_open(&repo, repo_path, NULL);
5351 if (error != NULL)
5352 goto done;
5354 error = apply_unveil(got_repo_get_path(repo), do_list,
5355 worktree ? got_worktree_get_root_path(worktree) : NULL);
5356 if (error)
5357 goto done;
5359 if (do_list)
5360 error = list_refs(repo, refname);
5361 else if (do_delete)
5362 error = delete_ref(repo, refname);
5363 else if (symref_target)
5364 error = add_symref(repo, refname, symref_target);
5365 else {
5366 if (obj_arg == NULL)
5367 usage_ref();
5368 error = add_ref(repo, refname, obj_arg);
5370 done:
5371 free(refname);
5372 if (repo)
5373 got_repo_close(repo);
5374 if (worktree)
5375 got_worktree_close(worktree);
5376 free(cwd);
5377 free(repo_path);
5378 return error;
5381 __dead static void
5382 usage_branch(void)
5384 fprintf(stderr,
5385 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5386 "[name]\n", getprogname());
5387 exit(1);
5390 static const struct got_error *
5391 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5392 struct got_reference *ref)
5394 const struct got_error *err = NULL;
5395 const char *refname, *marker = " ";
5396 char *refstr;
5398 refname = got_ref_get_name(ref);
5399 if (worktree && strcmp(refname,
5400 got_worktree_get_head_ref_name(worktree)) == 0) {
5401 struct got_object_id *id = NULL;
5403 err = got_ref_resolve(&id, repo, ref);
5404 if (err)
5405 return err;
5406 if (got_object_id_cmp(id,
5407 got_worktree_get_base_commit_id(worktree)) == 0)
5408 marker = "* ";
5409 else
5410 marker = "~ ";
5411 free(id);
5414 if (strncmp(refname, "refs/heads/", 11) == 0)
5415 refname += 11;
5416 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5417 refname += 18;
5419 refstr = got_ref_to_str(ref);
5420 if (refstr == NULL)
5421 return got_error_from_errno("got_ref_to_str");
5423 printf("%s%s: %s\n", marker, refname, refstr);
5424 free(refstr);
5425 return NULL;
5428 static const struct got_error *
5429 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5431 const char *refname;
5433 if (worktree == NULL)
5434 return got_error(GOT_ERR_NOT_WORKTREE);
5436 refname = got_worktree_get_head_ref_name(worktree);
5438 if (strncmp(refname, "refs/heads/", 11) == 0)
5439 refname += 11;
5440 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5441 refname += 18;
5443 printf("%s\n", refname);
5445 return NULL;
5448 static const struct got_error *
5449 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5451 static const struct got_error *err = NULL;
5452 struct got_reflist_head refs;
5453 struct got_reflist_entry *re;
5454 struct got_reference *temp_ref = NULL;
5455 int rebase_in_progress, histedit_in_progress;
5457 TAILQ_INIT(&refs);
5459 if (worktree) {
5460 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5461 worktree);
5462 if (err)
5463 return err;
5465 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5466 worktree);
5467 if (err)
5468 return err;
5470 if (rebase_in_progress || histedit_in_progress) {
5471 err = got_ref_open(&temp_ref, repo,
5472 got_worktree_get_head_ref_name(worktree), 0);
5473 if (err)
5474 return err;
5475 list_branch(repo, worktree, temp_ref);
5476 got_ref_close(temp_ref);
5480 err = got_ref_list(&refs, repo, "refs/heads",
5481 got_ref_cmp_by_name, NULL);
5482 if (err)
5483 return err;
5485 TAILQ_FOREACH(re, &refs, entry)
5486 list_branch(repo, worktree, re->ref);
5488 got_ref_list_free(&refs);
5489 return NULL;
5492 static const struct got_error *
5493 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5494 const char *branch_name)
5496 const struct got_error *err = NULL;
5497 struct got_reference *ref = NULL;
5498 char *refname;
5500 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5501 return got_error_from_errno("asprintf");
5503 err = got_ref_open(&ref, repo, refname, 0);
5504 if (err)
5505 goto done;
5507 if (worktree &&
5508 strcmp(got_worktree_get_head_ref_name(worktree),
5509 got_ref_get_name(ref)) == 0) {
5510 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5511 "will not delete this work tree's current branch");
5512 goto done;
5515 err = got_ref_delete(ref, repo);
5516 done:
5517 if (ref)
5518 got_ref_close(ref);
5519 free(refname);
5520 return err;
5523 static const struct got_error *
5524 add_branch(struct got_repository *repo, const char *branch_name,
5525 struct got_object_id *base_commit_id)
5527 const struct got_error *err = NULL;
5528 struct got_reference *ref = NULL;
5529 char *base_refname = NULL, *refname = NULL;
5532 * Don't let the user create a branch name with a leading '-'.
5533 * While technically a valid reference name, this case is usually
5534 * an unintended typo.
5536 if (branch_name[0] == '-')
5537 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5539 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5540 err = got_error_from_errno("asprintf");
5541 goto done;
5544 err = got_ref_open(&ref, repo, refname, 0);
5545 if (err == NULL) {
5546 err = got_error(GOT_ERR_BRANCH_EXISTS);
5547 goto done;
5548 } else if (err->code != GOT_ERR_NOT_REF)
5549 goto done;
5551 err = got_ref_alloc(&ref, refname, base_commit_id);
5552 if (err)
5553 goto done;
5555 err = got_ref_write(ref, repo);
5556 done:
5557 if (ref)
5558 got_ref_close(ref);
5559 free(base_refname);
5560 free(refname);
5561 return err;
5564 static const struct got_error *
5565 cmd_branch(int argc, char *argv[])
5567 const struct got_error *error = NULL;
5568 struct got_repository *repo = NULL;
5569 struct got_worktree *worktree = NULL;
5570 char *cwd = NULL, *repo_path = NULL;
5571 int ch, do_list = 0, do_show = 0, do_update = 1;
5572 const char *delref = NULL, *commit_id_arg = NULL;
5573 struct got_reference *ref = NULL;
5574 struct got_pathlist_head paths;
5575 struct got_pathlist_entry *pe;
5576 struct got_object_id *commit_id = NULL;
5577 char *commit_id_str = NULL;
5579 TAILQ_INIT(&paths);
5581 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5582 switch (ch) {
5583 case 'c':
5584 commit_id_arg = optarg;
5585 break;
5586 case 'd':
5587 delref = optarg;
5588 break;
5589 case 'r':
5590 repo_path = realpath(optarg, NULL);
5591 if (repo_path == NULL)
5592 return got_error_from_errno2("realpath",
5593 optarg);
5594 got_path_strip_trailing_slashes(repo_path);
5595 break;
5596 case 'l':
5597 do_list = 1;
5598 break;
5599 case 'n':
5600 do_update = 0;
5601 break;
5602 default:
5603 usage_branch();
5604 /* NOTREACHED */
5608 if (do_list && delref)
5609 option_conflict('l', 'd');
5611 argc -= optind;
5612 argv += optind;
5614 if (!do_list && !delref && argc == 0)
5615 do_show = 1;
5617 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5618 errx(1, "-c option can only be used when creating a branch");
5620 if (do_list || delref) {
5621 if (argc > 0)
5622 usage_branch();
5623 } else if (!do_show && argc != 1)
5624 usage_branch();
5626 #ifndef PROFILE
5627 if (do_list || do_show) {
5628 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5629 NULL) == -1)
5630 err(1, "pledge");
5631 } else {
5632 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5633 "sendfd unveil", NULL) == -1)
5634 err(1, "pledge");
5636 #endif
5637 cwd = getcwd(NULL, 0);
5638 if (cwd == NULL) {
5639 error = got_error_from_errno("getcwd");
5640 goto done;
5643 if (repo_path == NULL) {
5644 error = got_worktree_open(&worktree, cwd);
5645 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5646 goto done;
5647 else
5648 error = NULL;
5649 if (worktree) {
5650 repo_path =
5651 strdup(got_worktree_get_repo_path(worktree));
5652 if (repo_path == NULL)
5653 error = got_error_from_errno("strdup");
5654 if (error)
5655 goto done;
5656 } else {
5657 repo_path = strdup(cwd);
5658 if (repo_path == NULL) {
5659 error = got_error_from_errno("strdup");
5660 goto done;
5665 error = got_repo_open(&repo, repo_path, NULL);
5666 if (error != NULL)
5667 goto done;
5669 error = apply_unveil(got_repo_get_path(repo), do_list,
5670 worktree ? got_worktree_get_root_path(worktree) : NULL);
5671 if (error)
5672 goto done;
5674 if (do_show)
5675 error = show_current_branch(repo, worktree);
5676 else if (do_list)
5677 error = list_branches(repo, worktree);
5678 else if (delref)
5679 error = delete_branch(repo, worktree, delref);
5680 else {
5681 struct got_reflist_head refs;
5682 TAILQ_INIT(&refs);
5683 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5684 NULL);
5685 if (error)
5686 goto done;
5687 if (commit_id_arg == NULL)
5688 commit_id_arg = worktree ?
5689 got_worktree_get_head_ref_name(worktree) :
5690 GOT_REF_HEAD;
5691 error = got_repo_match_object_id(&commit_id, NULL,
5692 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5693 got_ref_list_free(&refs);
5694 if (error)
5695 goto done;
5696 error = add_branch(repo, argv[0], commit_id);
5697 if (error)
5698 goto done;
5699 if (worktree && do_update) {
5700 struct got_update_progress_arg upa;
5701 char *branch_refname = NULL;
5703 error = got_object_id_str(&commit_id_str, commit_id);
5704 if (error)
5705 goto done;
5706 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5707 worktree);
5708 if (error)
5709 goto done;
5710 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5711 == -1) {
5712 error = got_error_from_errno("asprintf");
5713 goto done;
5715 error = got_ref_open(&ref, repo, branch_refname, 0);
5716 free(branch_refname);
5717 if (error)
5718 goto done;
5719 error = switch_head_ref(ref, commit_id, worktree,
5720 repo);
5721 if (error)
5722 goto done;
5723 error = got_worktree_set_base_commit_id(worktree, repo,
5724 commit_id);
5725 if (error)
5726 goto done;
5727 memset(&upa, 0, sizeof(upa));
5728 error = got_worktree_checkout_files(worktree, &paths,
5729 repo, update_progress, &upa, check_cancelled,
5730 NULL);
5731 if (error)
5732 goto done;
5733 if (upa.did_something)
5734 printf("Updated to commit %s\n", commit_id_str);
5735 print_update_progress_stats(&upa);
5738 done:
5739 if (ref)
5740 got_ref_close(ref);
5741 if (repo)
5742 got_repo_close(repo);
5743 if (worktree)
5744 got_worktree_close(worktree);
5745 free(cwd);
5746 free(repo_path);
5747 free(commit_id);
5748 free(commit_id_str);
5749 TAILQ_FOREACH(pe, &paths, entry)
5750 free((char *)pe->path);
5751 got_pathlist_free(&paths);
5752 return error;
5756 __dead static void
5757 usage_tag(void)
5759 fprintf(stderr,
5760 "usage: %s tag [-c commit] [-r repository] [-l] "
5761 "[-m message] name\n", getprogname());
5762 exit(1);
5765 #if 0
5766 static const struct got_error *
5767 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5769 const struct got_error *err = NULL;
5770 struct got_reflist_entry *re, *se, *new;
5771 struct got_object_id *re_id, *se_id;
5772 struct got_tag_object *re_tag, *se_tag;
5773 time_t re_time, se_time;
5775 SIMPLEQ_FOREACH(re, tags, entry) {
5776 se = SIMPLEQ_FIRST(sorted);
5777 if (se == NULL) {
5778 err = got_reflist_entry_dup(&new, re);
5779 if (err)
5780 return err;
5781 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5782 continue;
5783 } else {
5784 err = got_ref_resolve(&re_id, repo, re->ref);
5785 if (err)
5786 break;
5787 err = got_object_open_as_tag(&re_tag, repo, re_id);
5788 free(re_id);
5789 if (err)
5790 break;
5791 re_time = got_object_tag_get_tagger_time(re_tag);
5792 got_object_tag_close(re_tag);
5795 while (se) {
5796 err = got_ref_resolve(&se_id, repo, re->ref);
5797 if (err)
5798 break;
5799 err = got_object_open_as_tag(&se_tag, repo, se_id);
5800 free(se_id);
5801 if (err)
5802 break;
5803 se_time = got_object_tag_get_tagger_time(se_tag);
5804 got_object_tag_close(se_tag);
5806 if (se_time > re_time) {
5807 err = got_reflist_entry_dup(&new, re);
5808 if (err)
5809 return err;
5810 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5811 break;
5813 se = SIMPLEQ_NEXT(se, entry);
5814 continue;
5817 done:
5818 return err;
5820 #endif
5822 static const struct got_error *
5823 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5825 static const struct got_error *err = NULL;
5826 struct got_reflist_head refs;
5827 struct got_reflist_entry *re;
5829 TAILQ_INIT(&refs);
5831 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5832 if (err)
5833 return err;
5835 TAILQ_FOREACH(re, &refs, entry) {
5836 const char *refname;
5837 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5838 char datebuf[26];
5839 const char *tagger;
5840 time_t tagger_time;
5841 struct got_object_id *id;
5842 struct got_tag_object *tag;
5843 struct got_commit_object *commit = NULL;
5845 refname = got_ref_get_name(re->ref);
5846 if (strncmp(refname, "refs/tags/", 10) != 0)
5847 continue;
5848 refname += 10;
5849 refstr = got_ref_to_str(re->ref);
5850 if (refstr == NULL) {
5851 err = got_error_from_errno("got_ref_to_str");
5852 break;
5854 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5855 free(refstr);
5857 err = got_ref_resolve(&id, repo, re->ref);
5858 if (err)
5859 break;
5860 err = got_object_open_as_tag(&tag, repo, id);
5861 if (err) {
5862 if (err->code != GOT_ERR_OBJ_TYPE) {
5863 free(id);
5864 break;
5866 /* "lightweight" tag */
5867 err = got_object_open_as_commit(&commit, repo, id);
5868 if (err) {
5869 free(id);
5870 break;
5872 tagger = got_object_commit_get_committer(commit);
5873 tagger_time =
5874 got_object_commit_get_committer_time(commit);
5875 err = got_object_id_str(&id_str, id);
5876 free(id);
5877 if (err)
5878 break;
5879 } else {
5880 free(id);
5881 tagger = got_object_tag_get_tagger(tag);
5882 tagger_time = got_object_tag_get_tagger_time(tag);
5883 err = got_object_id_str(&id_str,
5884 got_object_tag_get_object_id(tag));
5885 if (err)
5886 break;
5888 printf("from: %s\n", tagger);
5889 datestr = get_datestr(&tagger_time, datebuf);
5890 if (datestr)
5891 printf("date: %s UTC\n", datestr);
5892 if (commit)
5893 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5894 else {
5895 switch (got_object_tag_get_object_type(tag)) {
5896 case GOT_OBJ_TYPE_BLOB:
5897 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5898 id_str);
5899 break;
5900 case GOT_OBJ_TYPE_TREE:
5901 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5902 id_str);
5903 break;
5904 case GOT_OBJ_TYPE_COMMIT:
5905 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5906 id_str);
5907 break;
5908 case GOT_OBJ_TYPE_TAG:
5909 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5910 id_str);
5911 break;
5912 default:
5913 break;
5916 free(id_str);
5917 if (commit) {
5918 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5919 if (err)
5920 break;
5921 got_object_commit_close(commit);
5922 } else {
5923 tagmsg0 = strdup(got_object_tag_get_message(tag));
5924 got_object_tag_close(tag);
5925 if (tagmsg0 == NULL) {
5926 err = got_error_from_errno("strdup");
5927 break;
5931 tagmsg = tagmsg0;
5932 do {
5933 line = strsep(&tagmsg, "\n");
5934 if (line)
5935 printf(" %s\n", line);
5936 } while (line);
5937 free(tagmsg0);
5940 got_ref_list_free(&refs);
5941 return NULL;
5944 static const struct got_error *
5945 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5946 const char *tag_name, const char *repo_path)
5948 const struct got_error *err = NULL;
5949 char *template = NULL, *initial_content = NULL;
5950 char *editor = NULL;
5951 int initial_content_len;
5952 int fd = -1;
5954 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5955 err = got_error_from_errno("asprintf");
5956 goto done;
5959 initial_content_len = asprintf(&initial_content,
5960 "\n# tagging commit %s as %s\n",
5961 commit_id_str, tag_name);
5962 if (initial_content_len == -1) {
5963 err = got_error_from_errno("asprintf");
5964 goto done;
5967 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5968 if (err)
5969 goto done;
5971 if (write(fd, initial_content, initial_content_len) == -1) {
5972 err = got_error_from_errno2("write", *tagmsg_path);
5973 goto done;
5976 err = get_editor(&editor);
5977 if (err)
5978 goto done;
5979 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
5980 initial_content_len, 1);
5981 done:
5982 free(initial_content);
5983 free(template);
5984 free(editor);
5986 if (fd != -1 && close(fd) == -1 && err == NULL)
5987 err = got_error_from_errno2("close", *tagmsg_path);
5989 /* Editor is done; we can now apply unveil(2) */
5990 if (err == NULL)
5991 err = apply_unveil(repo_path, 0, NULL);
5992 if (err) {
5993 free(*tagmsg);
5994 *tagmsg = NULL;
5996 return err;
5999 static const struct got_error *
6000 add_tag(struct got_repository *repo, struct got_worktree *worktree,
6001 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6003 const struct got_error *err = NULL;
6004 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6005 char *label = NULL, *commit_id_str = NULL;
6006 struct got_reference *ref = NULL;
6007 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
6008 char *tagmsg_path = NULL, *tag_id_str = NULL;
6009 int preserve_tagmsg = 0;
6010 struct got_reflist_head refs;
6012 TAILQ_INIT(&refs);
6015 * Don't let the user create a tag name with a leading '-'.
6016 * While technically a valid reference name, this case is usually
6017 * an unintended typo.
6019 if (tag_name[0] == '-')
6020 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6022 err = get_author(&tagger, repo, worktree);
6023 if (err)
6024 return err;
6026 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6027 if (err)
6028 goto done;
6030 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6031 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6032 if (err)
6033 goto done;
6035 err = got_object_id_str(&commit_id_str, commit_id);
6036 if (err)
6037 goto done;
6039 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6040 refname = strdup(tag_name);
6041 if (refname == NULL) {
6042 err = got_error_from_errno("strdup");
6043 goto done;
6045 tag_name += 10;
6046 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6047 err = got_error_from_errno("asprintf");
6048 goto done;
6051 err = got_ref_open(&ref, repo, refname, 0);
6052 if (err == NULL) {
6053 err = got_error(GOT_ERR_TAG_EXISTS);
6054 goto done;
6055 } else if (err->code != GOT_ERR_NOT_REF)
6056 goto done;
6058 if (tagmsg_arg == NULL) {
6059 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6060 tag_name, got_repo_get_path(repo));
6061 if (err) {
6062 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6063 tagmsg_path != NULL)
6064 preserve_tagmsg = 1;
6065 goto done;
6069 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6070 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6071 if (err) {
6072 if (tagmsg_path)
6073 preserve_tagmsg = 1;
6074 goto done;
6077 err = got_ref_alloc(&ref, refname, tag_id);
6078 if (err) {
6079 if (tagmsg_path)
6080 preserve_tagmsg = 1;
6081 goto done;
6084 err = got_ref_write(ref, repo);
6085 if (err) {
6086 if (tagmsg_path)
6087 preserve_tagmsg = 1;
6088 goto done;
6091 err = got_object_id_str(&tag_id_str, tag_id);
6092 if (err) {
6093 if (tagmsg_path)
6094 preserve_tagmsg = 1;
6095 goto done;
6097 printf("Created tag %s\n", tag_id_str);
6098 done:
6099 if (preserve_tagmsg) {
6100 fprintf(stderr, "%s: tag message preserved in %s\n",
6101 getprogname(), tagmsg_path);
6102 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6103 err = got_error_from_errno2("unlink", tagmsg_path);
6104 free(tag_id_str);
6105 if (ref)
6106 got_ref_close(ref);
6107 free(commit_id);
6108 free(commit_id_str);
6109 free(refname);
6110 free(tagmsg);
6111 free(tagmsg_path);
6112 free(tagger);
6113 got_ref_list_free(&refs);
6114 return err;
6117 static const struct got_error *
6118 cmd_tag(int argc, char *argv[])
6120 const struct got_error *error = NULL;
6121 struct got_repository *repo = NULL;
6122 struct got_worktree *worktree = NULL;
6123 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6124 char *gitconfig_path = NULL;
6125 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6126 int ch, do_list = 0;
6128 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6129 switch (ch) {
6130 case 'c':
6131 commit_id_arg = optarg;
6132 break;
6133 case 'm':
6134 tagmsg = optarg;
6135 break;
6136 case 'r':
6137 repo_path = realpath(optarg, NULL);
6138 if (repo_path == NULL)
6139 return got_error_from_errno2("realpath",
6140 optarg);
6141 got_path_strip_trailing_slashes(repo_path);
6142 break;
6143 case 'l':
6144 do_list = 1;
6145 break;
6146 default:
6147 usage_tag();
6148 /* NOTREACHED */
6152 argc -= optind;
6153 argv += optind;
6155 if (do_list) {
6156 if (commit_id_arg != NULL)
6157 errx(1,
6158 "-c option can only be used when creating a tag");
6159 if (tagmsg)
6160 option_conflict('l', 'm');
6161 if (argc > 0)
6162 usage_tag();
6163 } else if (argc != 1)
6164 usage_tag();
6166 tag_name = argv[0];
6168 #ifndef PROFILE
6169 if (do_list) {
6170 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6171 NULL) == -1)
6172 err(1, "pledge");
6173 } else {
6174 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6175 "sendfd unveil", NULL) == -1)
6176 err(1, "pledge");
6178 #endif
6179 cwd = getcwd(NULL, 0);
6180 if (cwd == NULL) {
6181 error = got_error_from_errno("getcwd");
6182 goto done;
6185 if (repo_path == NULL) {
6186 error = got_worktree_open(&worktree, cwd);
6187 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6188 goto done;
6189 else
6190 error = NULL;
6191 if (worktree) {
6192 repo_path =
6193 strdup(got_worktree_get_repo_path(worktree));
6194 if (repo_path == NULL)
6195 error = got_error_from_errno("strdup");
6196 if (error)
6197 goto done;
6198 } else {
6199 repo_path = strdup(cwd);
6200 if (repo_path == NULL) {
6201 error = got_error_from_errno("strdup");
6202 goto done;
6207 if (do_list) {
6208 error = got_repo_open(&repo, repo_path, NULL);
6209 if (error != NULL)
6210 goto done;
6211 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6212 if (error)
6213 goto done;
6214 error = list_tags(repo, worktree);
6215 } else {
6216 error = get_gitconfig_path(&gitconfig_path);
6217 if (error)
6218 goto done;
6219 error = got_repo_open(&repo, repo_path, gitconfig_path);
6220 if (error != NULL)
6221 goto done;
6223 if (tagmsg) {
6224 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6225 if (error)
6226 goto done;
6229 if (commit_id_arg == NULL) {
6230 struct got_reference *head_ref;
6231 struct got_object_id *commit_id;
6232 error = got_ref_open(&head_ref, repo,
6233 worktree ? got_worktree_get_head_ref_name(worktree)
6234 : GOT_REF_HEAD, 0);
6235 if (error)
6236 goto done;
6237 error = got_ref_resolve(&commit_id, repo, head_ref);
6238 got_ref_close(head_ref);
6239 if (error)
6240 goto done;
6241 error = got_object_id_str(&commit_id_str, commit_id);
6242 free(commit_id);
6243 if (error)
6244 goto done;
6247 error = add_tag(repo, worktree, tag_name,
6248 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6250 done:
6251 if (repo)
6252 got_repo_close(repo);
6253 if (worktree)
6254 got_worktree_close(worktree);
6255 free(cwd);
6256 free(repo_path);
6257 free(gitconfig_path);
6258 free(commit_id_str);
6259 return error;
6262 __dead static void
6263 usage_add(void)
6265 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6266 getprogname());
6267 exit(1);
6270 static const struct got_error *
6271 add_progress(void *arg, unsigned char status, const char *path)
6273 while (path[0] == '/')
6274 path++;
6275 printf("%c %s\n", status, path);
6276 return NULL;
6279 static const struct got_error *
6280 cmd_add(int argc, char *argv[])
6282 const struct got_error *error = NULL;
6283 struct got_repository *repo = NULL;
6284 struct got_worktree *worktree = NULL;
6285 char *cwd = NULL;
6286 struct got_pathlist_head paths;
6287 struct got_pathlist_entry *pe;
6288 int ch, can_recurse = 0, no_ignores = 0;
6290 TAILQ_INIT(&paths);
6292 while ((ch = getopt(argc, argv, "IR")) != -1) {
6293 switch (ch) {
6294 case 'I':
6295 no_ignores = 1;
6296 break;
6297 case 'R':
6298 can_recurse = 1;
6299 break;
6300 default:
6301 usage_add();
6302 /* NOTREACHED */
6306 argc -= optind;
6307 argv += optind;
6309 #ifndef PROFILE
6310 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6311 NULL) == -1)
6312 err(1, "pledge");
6313 #endif
6314 if (argc < 1)
6315 usage_add();
6317 cwd = getcwd(NULL, 0);
6318 if (cwd == NULL) {
6319 error = got_error_from_errno("getcwd");
6320 goto done;
6323 error = got_worktree_open(&worktree, cwd);
6324 if (error) {
6325 if (error->code == GOT_ERR_NOT_WORKTREE)
6326 error = wrap_not_worktree_error(error, "add", cwd);
6327 goto done;
6330 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6331 NULL);
6332 if (error != NULL)
6333 goto done;
6335 error = apply_unveil(got_repo_get_path(repo), 1,
6336 got_worktree_get_root_path(worktree));
6337 if (error)
6338 goto done;
6340 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6341 if (error)
6342 goto done;
6344 if (!can_recurse && no_ignores) {
6345 error = got_error_msg(GOT_ERR_BAD_PATH,
6346 "disregarding ignores requires -R option");
6347 goto done;
6351 if (!can_recurse) {
6352 char *ondisk_path;
6353 struct stat sb;
6354 TAILQ_FOREACH(pe, &paths, entry) {
6355 if (asprintf(&ondisk_path, "%s/%s",
6356 got_worktree_get_root_path(worktree),
6357 pe->path) == -1) {
6358 error = got_error_from_errno("asprintf");
6359 goto done;
6361 if (lstat(ondisk_path, &sb) == -1) {
6362 if (errno == ENOENT) {
6363 free(ondisk_path);
6364 continue;
6366 error = got_error_from_errno2("lstat",
6367 ondisk_path);
6368 free(ondisk_path);
6369 goto done;
6371 free(ondisk_path);
6372 if (S_ISDIR(sb.st_mode)) {
6373 error = got_error_msg(GOT_ERR_BAD_PATH,
6374 "adding directories requires -R option");
6375 goto done;
6380 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6381 NULL, repo, no_ignores);
6382 done:
6383 if (repo)
6384 got_repo_close(repo);
6385 if (worktree)
6386 got_worktree_close(worktree);
6387 TAILQ_FOREACH(pe, &paths, entry)
6388 free((char *)pe->path);
6389 got_pathlist_free(&paths);
6390 free(cwd);
6391 return error;
6394 __dead static void
6395 usage_remove(void)
6397 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6398 "path ...\n", getprogname());
6399 exit(1);
6402 static const struct got_error *
6403 print_remove_status(void *arg, unsigned char status,
6404 unsigned char staged_status, const char *path)
6406 while (path[0] == '/')
6407 path++;
6408 if (status == GOT_STATUS_NONEXISTENT)
6409 return NULL;
6410 if (status == staged_status && (status == GOT_STATUS_DELETE))
6411 status = GOT_STATUS_NO_CHANGE;
6412 printf("%c%c %s\n", status, staged_status, path);
6413 return NULL;
6416 static const struct got_error *
6417 cmd_remove(int argc, char *argv[])
6419 const struct got_error *error = NULL;
6420 struct got_worktree *worktree = NULL;
6421 struct got_repository *repo = NULL;
6422 const char *status_codes = NULL;
6423 char *cwd = NULL;
6424 struct got_pathlist_head paths;
6425 struct got_pathlist_entry *pe;
6426 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6428 TAILQ_INIT(&paths);
6430 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6431 switch (ch) {
6432 case 'f':
6433 delete_local_mods = 1;
6434 break;
6435 case 'k':
6436 keep_on_disk = 1;
6437 break;
6438 case 'R':
6439 can_recurse = 1;
6440 break;
6441 case 's':
6442 for (i = 0; i < strlen(optarg); i++) {
6443 switch (optarg[i]) {
6444 case GOT_STATUS_MODIFY:
6445 delete_local_mods = 1;
6446 break;
6447 case GOT_STATUS_MISSING:
6448 break;
6449 default:
6450 errx(1, "invalid status code '%c'",
6451 optarg[i]);
6454 status_codes = optarg;
6455 break;
6456 default:
6457 usage_remove();
6458 /* NOTREACHED */
6462 argc -= optind;
6463 argv += optind;
6465 #ifndef PROFILE
6466 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6467 NULL) == -1)
6468 err(1, "pledge");
6469 #endif
6470 if (argc < 1)
6471 usage_remove();
6473 cwd = getcwd(NULL, 0);
6474 if (cwd == NULL) {
6475 error = got_error_from_errno("getcwd");
6476 goto done;
6478 error = got_worktree_open(&worktree, cwd);
6479 if (error) {
6480 if (error->code == GOT_ERR_NOT_WORKTREE)
6481 error = wrap_not_worktree_error(error, "remove", cwd);
6482 goto done;
6485 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6486 NULL);
6487 if (error)
6488 goto done;
6490 error = apply_unveil(got_repo_get_path(repo), 1,
6491 got_worktree_get_root_path(worktree));
6492 if (error)
6493 goto done;
6495 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6496 if (error)
6497 goto done;
6499 if (!can_recurse) {
6500 char *ondisk_path;
6501 struct stat sb;
6502 TAILQ_FOREACH(pe, &paths, entry) {
6503 if (asprintf(&ondisk_path, "%s/%s",
6504 got_worktree_get_root_path(worktree),
6505 pe->path) == -1) {
6506 error = got_error_from_errno("asprintf");
6507 goto done;
6509 if (lstat(ondisk_path, &sb) == -1) {
6510 if (errno == ENOENT) {
6511 free(ondisk_path);
6512 continue;
6514 error = got_error_from_errno2("lstat",
6515 ondisk_path);
6516 free(ondisk_path);
6517 goto done;
6519 free(ondisk_path);
6520 if (S_ISDIR(sb.st_mode)) {
6521 error = got_error_msg(GOT_ERR_BAD_PATH,
6522 "removing directories requires -R option");
6523 goto done;
6528 error = got_worktree_schedule_delete(worktree, &paths,
6529 delete_local_mods, status_codes, print_remove_status, NULL,
6530 repo, keep_on_disk);
6531 done:
6532 if (repo)
6533 got_repo_close(repo);
6534 if (worktree)
6535 got_worktree_close(worktree);
6536 TAILQ_FOREACH(pe, &paths, entry)
6537 free((char *)pe->path);
6538 got_pathlist_free(&paths);
6539 free(cwd);
6540 return error;
6543 __dead static void
6544 usage_revert(void)
6546 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6547 "path ...\n", getprogname());
6548 exit(1);
6551 static const struct got_error *
6552 revert_progress(void *arg, unsigned char status, const char *path)
6554 if (status == GOT_STATUS_UNVERSIONED)
6555 return NULL;
6557 while (path[0] == '/')
6558 path++;
6559 printf("%c %s\n", status, path);
6560 return NULL;
6563 struct choose_patch_arg {
6564 FILE *patch_script_file;
6565 const char *action;
6568 static const struct got_error *
6569 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6570 int nchanges, const char *action)
6572 char *line = NULL;
6573 size_t linesize = 0;
6574 ssize_t linelen;
6576 switch (status) {
6577 case GOT_STATUS_ADD:
6578 printf("A %s\n%s this addition? [y/n] ", path, action);
6579 break;
6580 case GOT_STATUS_DELETE:
6581 printf("D %s\n%s this deletion? [y/n] ", path, action);
6582 break;
6583 case GOT_STATUS_MODIFY:
6584 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6585 return got_error_from_errno("fseek");
6586 printf(GOT_COMMIT_SEP_STR);
6587 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6588 printf("%s", line);
6589 if (ferror(patch_file))
6590 return got_error_from_errno("getline");
6591 printf(GOT_COMMIT_SEP_STR);
6592 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6593 path, n, nchanges, action);
6594 break;
6595 default:
6596 return got_error_path(path, GOT_ERR_FILE_STATUS);
6599 return NULL;
6602 static const struct got_error *
6603 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6604 FILE *patch_file, int n, int nchanges)
6606 const struct got_error *err = NULL;
6607 char *line = NULL;
6608 size_t linesize = 0;
6609 ssize_t linelen;
6610 int resp = ' ';
6611 struct choose_patch_arg *a = arg;
6613 *choice = GOT_PATCH_CHOICE_NONE;
6615 if (a->patch_script_file) {
6616 char *nl;
6617 err = show_change(status, path, patch_file, n, nchanges,
6618 a->action);
6619 if (err)
6620 return err;
6621 linelen = getline(&line, &linesize, a->patch_script_file);
6622 if (linelen == -1) {
6623 if (ferror(a->patch_script_file))
6624 return got_error_from_errno("getline");
6625 return NULL;
6627 nl = strchr(line, '\n');
6628 if (nl)
6629 *nl = '\0';
6630 if (strcmp(line, "y") == 0) {
6631 *choice = GOT_PATCH_CHOICE_YES;
6632 printf("y\n");
6633 } else if (strcmp(line, "n") == 0) {
6634 *choice = GOT_PATCH_CHOICE_NO;
6635 printf("n\n");
6636 } else if (strcmp(line, "q") == 0 &&
6637 status == GOT_STATUS_MODIFY) {
6638 *choice = GOT_PATCH_CHOICE_QUIT;
6639 printf("q\n");
6640 } else
6641 printf("invalid response '%s'\n", line);
6642 free(line);
6643 return NULL;
6646 while (resp != 'y' && resp != 'n' && resp != 'q') {
6647 err = show_change(status, path, patch_file, n, nchanges,
6648 a->action);
6649 if (err)
6650 return err;
6651 resp = getchar();
6652 if (resp == '\n')
6653 resp = getchar();
6654 if (status == GOT_STATUS_MODIFY) {
6655 if (resp != 'y' && resp != 'n' && resp != 'q') {
6656 printf("invalid response '%c'\n", resp);
6657 resp = ' ';
6659 } else if (resp != 'y' && resp != 'n') {
6660 printf("invalid response '%c'\n", resp);
6661 resp = ' ';
6665 if (resp == 'y')
6666 *choice = GOT_PATCH_CHOICE_YES;
6667 else if (resp == 'n')
6668 *choice = GOT_PATCH_CHOICE_NO;
6669 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6670 *choice = GOT_PATCH_CHOICE_QUIT;
6672 return NULL;
6676 static const struct got_error *
6677 cmd_revert(int argc, char *argv[])
6679 const struct got_error *error = NULL;
6680 struct got_worktree *worktree = NULL;
6681 struct got_repository *repo = NULL;
6682 char *cwd = NULL, *path = NULL;
6683 struct got_pathlist_head paths;
6684 struct got_pathlist_entry *pe;
6685 int ch, can_recurse = 0, pflag = 0;
6686 FILE *patch_script_file = NULL;
6687 const char *patch_script_path = NULL;
6688 struct choose_patch_arg cpa;
6690 TAILQ_INIT(&paths);
6692 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6693 switch (ch) {
6694 case 'p':
6695 pflag = 1;
6696 break;
6697 case 'F':
6698 patch_script_path = optarg;
6699 break;
6700 case 'R':
6701 can_recurse = 1;
6702 break;
6703 default:
6704 usage_revert();
6705 /* NOTREACHED */
6709 argc -= optind;
6710 argv += optind;
6712 #ifndef PROFILE
6713 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6714 "unveil", NULL) == -1)
6715 err(1, "pledge");
6716 #endif
6717 if (argc < 1)
6718 usage_revert();
6719 if (patch_script_path && !pflag)
6720 errx(1, "-F option can only be used together with -p option");
6722 cwd = getcwd(NULL, 0);
6723 if (cwd == NULL) {
6724 error = got_error_from_errno("getcwd");
6725 goto done;
6727 error = got_worktree_open(&worktree, cwd);
6728 if (error) {
6729 if (error->code == GOT_ERR_NOT_WORKTREE)
6730 error = wrap_not_worktree_error(error, "revert", cwd);
6731 goto done;
6734 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6735 NULL);
6736 if (error != NULL)
6737 goto done;
6739 if (patch_script_path) {
6740 patch_script_file = fopen(patch_script_path, "r");
6741 if (patch_script_file == NULL) {
6742 error = got_error_from_errno2("fopen",
6743 patch_script_path);
6744 goto done;
6747 error = apply_unveil(got_repo_get_path(repo), 1,
6748 got_worktree_get_root_path(worktree));
6749 if (error)
6750 goto done;
6752 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6753 if (error)
6754 goto done;
6756 if (!can_recurse) {
6757 char *ondisk_path;
6758 struct stat sb;
6759 TAILQ_FOREACH(pe, &paths, entry) {
6760 if (asprintf(&ondisk_path, "%s/%s",
6761 got_worktree_get_root_path(worktree),
6762 pe->path) == -1) {
6763 error = got_error_from_errno("asprintf");
6764 goto done;
6766 if (lstat(ondisk_path, &sb) == -1) {
6767 if (errno == ENOENT) {
6768 free(ondisk_path);
6769 continue;
6771 error = got_error_from_errno2("lstat",
6772 ondisk_path);
6773 free(ondisk_path);
6774 goto done;
6776 free(ondisk_path);
6777 if (S_ISDIR(sb.st_mode)) {
6778 error = got_error_msg(GOT_ERR_BAD_PATH,
6779 "reverting directories requires -R option");
6780 goto done;
6785 cpa.patch_script_file = patch_script_file;
6786 cpa.action = "revert";
6787 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6788 pflag ? choose_patch : NULL, &cpa, repo);
6789 done:
6790 if (patch_script_file && fclose(patch_script_file) == EOF &&
6791 error == NULL)
6792 error = got_error_from_errno2("fclose", patch_script_path);
6793 if (repo)
6794 got_repo_close(repo);
6795 if (worktree)
6796 got_worktree_close(worktree);
6797 free(path);
6798 free(cwd);
6799 return error;
6802 __dead static void
6803 usage_commit(void)
6805 fprintf(stderr, "usage: %s commit [-m msg] [-S] [path ...]\n",
6806 getprogname());
6807 exit(1);
6810 struct collect_commit_logmsg_arg {
6811 const char *cmdline_log;
6812 const char *editor;
6813 const char *worktree_path;
6814 const char *branch_name;
6815 const char *repo_path;
6816 char *logmsg_path;
6820 static const struct got_error *
6821 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6822 void *arg)
6824 char *initial_content = NULL;
6825 struct got_pathlist_entry *pe;
6826 const struct got_error *err = NULL;
6827 char *template = NULL;
6828 struct collect_commit_logmsg_arg *a = arg;
6829 int initial_content_len;
6830 int fd = -1;
6831 size_t len;
6833 /* if a message was specified on the command line, just use it */
6834 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6835 len = strlen(a->cmdline_log) + 1;
6836 *logmsg = malloc(len + 1);
6837 if (*logmsg == NULL)
6838 return got_error_from_errno("malloc");
6839 strlcpy(*logmsg, a->cmdline_log, len);
6840 return NULL;
6843 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6844 return got_error_from_errno("asprintf");
6846 initial_content_len = asprintf(&initial_content,
6847 "\n# changes to be committed on branch %s:\n",
6848 a->branch_name);
6849 if (initial_content_len == -1)
6850 return got_error_from_errno("asprintf");
6852 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6853 if (err)
6854 goto done;
6856 if (write(fd, initial_content, initial_content_len) == -1) {
6857 err = got_error_from_errno2("write", a->logmsg_path);
6858 goto done;
6861 TAILQ_FOREACH(pe, commitable_paths, entry) {
6862 struct got_commitable *ct = pe->data;
6863 dprintf(fd, "# %c %s\n",
6864 got_commitable_get_status(ct),
6865 got_commitable_get_path(ct));
6868 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
6869 initial_content_len, 1);
6870 done:
6871 free(initial_content);
6872 free(template);
6874 if (fd != -1 && close(fd) == -1 && err == NULL)
6875 err = got_error_from_errno2("close", a->logmsg_path);
6877 /* Editor is done; we can now apply unveil(2) */
6878 if (err == NULL)
6879 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6880 if (err) {
6881 free(*logmsg);
6882 *logmsg = NULL;
6884 return err;
6887 static const struct got_error *
6888 cmd_commit(int argc, char *argv[])
6890 const struct got_error *error = NULL;
6891 struct got_worktree *worktree = NULL;
6892 struct got_repository *repo = NULL;
6893 char *cwd = NULL, *id_str = NULL;
6894 struct got_object_id *id = NULL;
6895 const char *logmsg = NULL;
6896 struct collect_commit_logmsg_arg cl_arg;
6897 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6898 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6899 int allow_bad_symlinks = 0;
6900 struct got_pathlist_head paths;
6902 TAILQ_INIT(&paths);
6903 cl_arg.logmsg_path = NULL;
6905 while ((ch = getopt(argc, argv, "m:S")) != -1) {
6906 switch (ch) {
6907 case 'm':
6908 logmsg = optarg;
6909 break;
6910 case 'S':
6911 allow_bad_symlinks = 1;
6912 break;
6913 default:
6914 usage_commit();
6915 /* NOTREACHED */
6919 argc -= optind;
6920 argv += optind;
6922 #ifndef PROFILE
6923 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6924 "unveil", NULL) == -1)
6925 err(1, "pledge");
6926 #endif
6927 cwd = getcwd(NULL, 0);
6928 if (cwd == NULL) {
6929 error = got_error_from_errno("getcwd");
6930 goto done;
6932 error = got_worktree_open(&worktree, cwd);
6933 if (error) {
6934 if (error->code == GOT_ERR_NOT_WORKTREE)
6935 error = wrap_not_worktree_error(error, "commit", cwd);
6936 goto done;
6939 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6940 if (error)
6941 goto done;
6942 if (rebase_in_progress) {
6943 error = got_error(GOT_ERR_REBASING);
6944 goto done;
6947 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6948 worktree);
6949 if (error)
6950 goto done;
6952 error = get_gitconfig_path(&gitconfig_path);
6953 if (error)
6954 goto done;
6955 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6956 gitconfig_path);
6957 if (error != NULL)
6958 goto done;
6960 error = get_author(&author, repo, worktree);
6961 if (error)
6962 return error;
6965 * unveil(2) traverses exec(2); if an editor is used we have
6966 * to apply unveil after the log message has been written.
6968 if (logmsg == NULL || strlen(logmsg) == 0)
6969 error = get_editor(&editor);
6970 else
6971 error = apply_unveil(got_repo_get_path(repo), 0,
6972 got_worktree_get_root_path(worktree));
6973 if (error)
6974 goto done;
6976 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6977 if (error)
6978 goto done;
6980 cl_arg.editor = editor;
6981 cl_arg.cmdline_log = logmsg;
6982 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6983 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6984 if (!histedit_in_progress) {
6985 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6986 error = got_error(GOT_ERR_COMMIT_BRANCH);
6987 goto done;
6989 cl_arg.branch_name += 11;
6991 cl_arg.repo_path = got_repo_get_path(repo);
6992 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6993 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
6994 print_status, NULL, repo);
6995 if (error) {
6996 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6997 cl_arg.logmsg_path != NULL)
6998 preserve_logmsg = 1;
6999 goto done;
7002 error = got_object_id_str(&id_str, id);
7003 if (error)
7004 goto done;
7005 printf("Created commit %s\n", id_str);
7006 done:
7007 if (preserve_logmsg) {
7008 fprintf(stderr, "%s: log message preserved in %s\n",
7009 getprogname(), cl_arg.logmsg_path);
7010 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
7011 error == NULL)
7012 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
7013 free(cl_arg.logmsg_path);
7014 if (repo)
7015 got_repo_close(repo);
7016 if (worktree)
7017 got_worktree_close(worktree);
7018 free(cwd);
7019 free(id_str);
7020 free(gitconfig_path);
7021 free(editor);
7022 free(author);
7023 return error;
7026 __dead static void
7027 usage_cherrypick(void)
7029 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
7030 exit(1);
7033 static const struct got_error *
7034 cmd_cherrypick(int argc, char *argv[])
7036 const struct got_error *error = NULL;
7037 struct got_worktree *worktree = NULL;
7038 struct got_repository *repo = NULL;
7039 char *cwd = NULL, *commit_id_str = NULL;
7040 struct got_object_id *commit_id = NULL;
7041 struct got_commit_object *commit = NULL;
7042 struct got_object_qid *pid;
7043 struct got_reference *head_ref = NULL;
7044 int ch;
7045 struct got_update_progress_arg upa;
7047 while ((ch = getopt(argc, argv, "")) != -1) {
7048 switch (ch) {
7049 default:
7050 usage_cherrypick();
7051 /* NOTREACHED */
7055 argc -= optind;
7056 argv += optind;
7058 #ifndef PROFILE
7059 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7060 "unveil", NULL) == -1)
7061 err(1, "pledge");
7062 #endif
7063 if (argc != 1)
7064 usage_cherrypick();
7066 cwd = getcwd(NULL, 0);
7067 if (cwd == NULL) {
7068 error = got_error_from_errno("getcwd");
7069 goto done;
7071 error = got_worktree_open(&worktree, cwd);
7072 if (error) {
7073 if (error->code == GOT_ERR_NOT_WORKTREE)
7074 error = wrap_not_worktree_error(error, "cherrypick",
7075 cwd);
7076 goto done;
7079 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7080 NULL);
7081 if (error != NULL)
7082 goto done;
7084 error = apply_unveil(got_repo_get_path(repo), 0,
7085 got_worktree_get_root_path(worktree));
7086 if (error)
7087 goto done;
7089 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7090 GOT_OBJ_TYPE_COMMIT, repo);
7091 if (error != NULL) {
7092 struct got_reference *ref;
7093 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7094 goto done;
7095 error = got_ref_open(&ref, repo, argv[0], 0);
7096 if (error != NULL)
7097 goto done;
7098 error = got_ref_resolve(&commit_id, repo, ref);
7099 got_ref_close(ref);
7100 if (error != NULL)
7101 goto done;
7103 error = got_object_id_str(&commit_id_str, commit_id);
7104 if (error)
7105 goto done;
7107 error = got_ref_open(&head_ref, repo,
7108 got_worktree_get_head_ref_name(worktree), 0);
7109 if (error != NULL)
7110 goto done;
7112 error = check_same_branch(commit_id, head_ref, NULL, repo);
7113 if (error) {
7114 if (error->code != GOT_ERR_ANCESTRY)
7115 goto done;
7116 error = NULL;
7117 } else {
7118 error = got_error(GOT_ERR_SAME_BRANCH);
7119 goto done;
7122 error = got_object_open_as_commit(&commit, repo, commit_id);
7123 if (error)
7124 goto done;
7125 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7126 memset(&upa, 0, sizeof(upa));
7127 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
7128 commit_id, repo, update_progress, &upa, check_cancelled,
7129 NULL);
7130 if (error != NULL)
7131 goto done;
7133 if (upa.did_something)
7134 printf("Merged commit %s\n", commit_id_str);
7135 print_update_progress_stats(&upa);
7136 done:
7137 if (commit)
7138 got_object_commit_close(commit);
7139 free(commit_id_str);
7140 if (head_ref)
7141 got_ref_close(head_ref);
7142 if (worktree)
7143 got_worktree_close(worktree);
7144 if (repo)
7145 got_repo_close(repo);
7146 return error;
7149 __dead static void
7150 usage_backout(void)
7152 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
7153 exit(1);
7156 static const struct got_error *
7157 cmd_backout(int argc, char *argv[])
7159 const struct got_error *error = NULL;
7160 struct got_worktree *worktree = NULL;
7161 struct got_repository *repo = NULL;
7162 char *cwd = NULL, *commit_id_str = NULL;
7163 struct got_object_id *commit_id = NULL;
7164 struct got_commit_object *commit = NULL;
7165 struct got_object_qid *pid;
7166 struct got_reference *head_ref = NULL;
7167 int ch;
7168 struct got_update_progress_arg upa;
7170 while ((ch = getopt(argc, argv, "")) != -1) {
7171 switch (ch) {
7172 default:
7173 usage_backout();
7174 /* NOTREACHED */
7178 argc -= optind;
7179 argv += optind;
7181 #ifndef PROFILE
7182 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7183 "unveil", NULL) == -1)
7184 err(1, "pledge");
7185 #endif
7186 if (argc != 1)
7187 usage_backout();
7189 cwd = getcwd(NULL, 0);
7190 if (cwd == NULL) {
7191 error = got_error_from_errno("getcwd");
7192 goto done;
7194 error = got_worktree_open(&worktree, cwd);
7195 if (error) {
7196 if (error->code == GOT_ERR_NOT_WORKTREE)
7197 error = wrap_not_worktree_error(error, "backout", cwd);
7198 goto done;
7201 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7202 NULL);
7203 if (error != NULL)
7204 goto done;
7206 error = apply_unveil(got_repo_get_path(repo), 0,
7207 got_worktree_get_root_path(worktree));
7208 if (error)
7209 goto done;
7211 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7212 GOT_OBJ_TYPE_COMMIT, repo);
7213 if (error != NULL) {
7214 struct got_reference *ref;
7215 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7216 goto done;
7217 error = got_ref_open(&ref, repo, argv[0], 0);
7218 if (error != NULL)
7219 goto done;
7220 error = got_ref_resolve(&commit_id, repo, ref);
7221 got_ref_close(ref);
7222 if (error != NULL)
7223 goto done;
7225 error = got_object_id_str(&commit_id_str, commit_id);
7226 if (error)
7227 goto done;
7229 error = got_ref_open(&head_ref, repo,
7230 got_worktree_get_head_ref_name(worktree), 0);
7231 if (error != NULL)
7232 goto done;
7234 error = check_same_branch(commit_id, head_ref, NULL, repo);
7235 if (error)
7236 goto done;
7238 error = got_object_open_as_commit(&commit, repo, commit_id);
7239 if (error)
7240 goto done;
7241 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7242 if (pid == NULL) {
7243 error = got_error(GOT_ERR_ROOT_COMMIT);
7244 goto done;
7247 memset(&upa, 0, sizeof(upa));
7248 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
7249 update_progress, &upa, check_cancelled, NULL);
7250 if (error != NULL)
7251 goto done;
7253 if (upa.did_something)
7254 printf("Backed out commit %s\n", commit_id_str);
7255 print_update_progress_stats(&upa);
7256 done:
7257 if (commit)
7258 got_object_commit_close(commit);
7259 free(commit_id_str);
7260 if (head_ref)
7261 got_ref_close(head_ref);
7262 if (worktree)
7263 got_worktree_close(worktree);
7264 if (repo)
7265 got_repo_close(repo);
7266 return error;
7269 __dead static void
7270 usage_rebase(void)
7272 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
7273 getprogname());
7274 exit(1);
7277 void
7278 trim_logmsg(char *logmsg, int limit)
7280 char *nl;
7281 size_t len;
7283 len = strlen(logmsg);
7284 if (len > limit)
7285 len = limit;
7286 logmsg[len] = '\0';
7287 nl = strchr(logmsg, '\n');
7288 if (nl)
7289 *nl = '\0';
7292 static const struct got_error *
7293 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
7295 const struct got_error *err;
7296 char *logmsg0 = NULL;
7297 const char *s;
7299 err = got_object_commit_get_logmsg(&logmsg0, commit);
7300 if (err)
7301 return err;
7303 s = logmsg0;
7304 while (isspace((unsigned char)s[0]))
7305 s++;
7307 *logmsg = strdup(s);
7308 if (*logmsg == NULL) {
7309 err = got_error_from_errno("strdup");
7310 goto done;
7313 trim_logmsg(*logmsg, limit);
7314 done:
7315 free(logmsg0);
7316 return err;
7319 static const struct got_error *
7320 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
7322 const struct got_error *err;
7323 struct got_commit_object *commit = NULL;
7324 char *id_str = NULL, *logmsg = NULL;
7326 err = got_object_open_as_commit(&commit, repo, id);
7327 if (err)
7328 return err;
7330 err = got_object_id_str(&id_str, id);
7331 if (err)
7332 goto done;
7334 id_str[12] = '\0';
7336 err = get_short_logmsg(&logmsg, 42, commit);
7337 if (err)
7338 goto done;
7340 printf("%s -> merge conflict: %s\n", id_str, logmsg);
7341 done:
7342 free(id_str);
7343 got_object_commit_close(commit);
7344 free(logmsg);
7345 return err;
7348 static const struct got_error *
7349 show_rebase_progress(struct got_commit_object *commit,
7350 struct got_object_id *old_id, struct got_object_id *new_id)
7352 const struct got_error *err;
7353 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7355 err = got_object_id_str(&old_id_str, old_id);
7356 if (err)
7357 goto done;
7359 if (new_id) {
7360 err = got_object_id_str(&new_id_str, new_id);
7361 if (err)
7362 goto done;
7365 old_id_str[12] = '\0';
7366 if (new_id_str)
7367 new_id_str[12] = '\0';
7369 err = get_short_logmsg(&logmsg, 42, commit);
7370 if (err)
7371 goto done;
7373 printf("%s -> %s: %s\n", old_id_str,
7374 new_id_str ? new_id_str : "no-op change", logmsg);
7375 done:
7376 free(old_id_str);
7377 free(new_id_str);
7378 free(logmsg);
7379 return err;
7382 static const struct got_error *
7383 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
7384 struct got_reference *branch, struct got_reference *new_base_branch,
7385 struct got_reference *tmp_branch, struct got_repository *repo)
7387 printf("Switching work tree to %s\n", got_ref_get_name(branch));
7388 return got_worktree_rebase_complete(worktree, fileindex,
7389 new_base_branch, tmp_branch, branch, repo);
7392 static const struct got_error *
7393 rebase_commit(struct got_pathlist_head *merged_paths,
7394 struct got_worktree *worktree, struct got_fileindex *fileindex,
7395 struct got_reference *tmp_branch,
7396 struct got_object_id *commit_id, struct got_repository *repo)
7398 const struct got_error *error;
7399 struct got_commit_object *commit;
7400 struct got_object_id *new_commit_id;
7402 error = got_object_open_as_commit(&commit, repo, commit_id);
7403 if (error)
7404 return error;
7406 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
7407 worktree, fileindex, tmp_branch, commit, commit_id, repo);
7408 if (error) {
7409 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
7410 goto done;
7411 error = show_rebase_progress(commit, commit_id, NULL);
7412 } else {
7413 error = show_rebase_progress(commit, commit_id, new_commit_id);
7414 free(new_commit_id);
7416 done:
7417 got_object_commit_close(commit);
7418 return error;
7421 struct check_path_prefix_arg {
7422 const char *path_prefix;
7423 size_t len;
7424 int errcode;
7427 static const struct got_error *
7428 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
7429 struct got_blob_object *blob2, struct got_object_id *id1,
7430 struct got_object_id *id2, const char *path1, const char *path2,
7431 mode_t mode1, mode_t mode2, struct got_repository *repo)
7433 struct check_path_prefix_arg *a = arg;
7435 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
7436 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
7437 return got_error(a->errcode);
7439 return NULL;
7442 static const struct got_error *
7443 check_path_prefix(struct got_object_id *parent_id,
7444 struct got_object_id *commit_id, const char *path_prefix,
7445 int errcode, struct got_repository *repo)
7447 const struct got_error *err;
7448 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7449 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7450 struct check_path_prefix_arg cpp_arg;
7452 if (got_path_is_root_dir(path_prefix))
7453 return NULL;
7455 err = got_object_open_as_commit(&commit, repo, commit_id);
7456 if (err)
7457 goto done;
7459 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7460 if (err)
7461 goto done;
7463 err = got_object_open_as_tree(&tree1, repo,
7464 got_object_commit_get_tree_id(parent_commit));
7465 if (err)
7466 goto done;
7468 err = got_object_open_as_tree(&tree2, repo,
7469 got_object_commit_get_tree_id(commit));
7470 if (err)
7471 goto done;
7473 cpp_arg.path_prefix = path_prefix;
7474 while (cpp_arg.path_prefix[0] == '/')
7475 cpp_arg.path_prefix++;
7476 cpp_arg.len = strlen(cpp_arg.path_prefix);
7477 cpp_arg.errcode = errcode;
7478 err = got_diff_tree(tree1, tree2, "", "", repo,
7479 check_path_prefix_in_diff, &cpp_arg, 0);
7480 done:
7481 if (tree1)
7482 got_object_tree_close(tree1);
7483 if (tree2)
7484 got_object_tree_close(tree2);
7485 if (commit)
7486 got_object_commit_close(commit);
7487 if (parent_commit)
7488 got_object_commit_close(parent_commit);
7489 return err;
7492 static const struct got_error *
7493 collect_commits(struct got_object_id_queue *commits,
7494 struct got_object_id *initial_commit_id,
7495 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7496 const char *path_prefix, int path_prefix_errcode,
7497 struct got_repository *repo)
7499 const struct got_error *err = NULL;
7500 struct got_commit_graph *graph = NULL;
7501 struct got_object_id *parent_id = NULL;
7502 struct got_object_qid *qid;
7503 struct got_object_id *commit_id = initial_commit_id;
7505 err = got_commit_graph_open(&graph, "/", 1);
7506 if (err)
7507 return err;
7509 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7510 check_cancelled, NULL);
7511 if (err)
7512 goto done;
7513 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7514 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7515 check_cancelled, NULL);
7516 if (err) {
7517 if (err->code == GOT_ERR_ITER_COMPLETED) {
7518 err = got_error_msg(GOT_ERR_ANCESTRY,
7519 "ran out of commits to rebase before "
7520 "youngest common ancestor commit has "
7521 "been reached?!?");
7523 goto done;
7524 } else {
7525 err = check_path_prefix(parent_id, commit_id,
7526 path_prefix, path_prefix_errcode, repo);
7527 if (err)
7528 goto done;
7530 err = got_object_qid_alloc(&qid, commit_id);
7531 if (err)
7532 goto done;
7533 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
7534 commit_id = parent_id;
7537 done:
7538 got_commit_graph_close(graph);
7539 return err;
7542 static const struct got_error *
7543 cmd_rebase(int argc, char *argv[])
7545 const struct got_error *error = NULL;
7546 struct got_worktree *worktree = NULL;
7547 struct got_repository *repo = NULL;
7548 struct got_fileindex *fileindex = NULL;
7549 char *cwd = NULL;
7550 struct got_reference *branch = NULL;
7551 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
7552 struct got_object_id *commit_id = NULL, *parent_id = NULL;
7553 struct got_object_id *resume_commit_id = NULL;
7554 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
7555 struct got_commit_object *commit = NULL;
7556 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
7557 int histedit_in_progress = 0;
7558 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7559 struct got_object_id_queue commits;
7560 struct got_pathlist_head merged_paths;
7561 const struct got_object_id_queue *parent_ids;
7562 struct got_object_qid *qid, *pid;
7564 SIMPLEQ_INIT(&commits);
7565 TAILQ_INIT(&merged_paths);
7567 while ((ch = getopt(argc, argv, "ac")) != -1) {
7568 switch (ch) {
7569 case 'a':
7570 abort_rebase = 1;
7571 break;
7572 case 'c':
7573 continue_rebase = 1;
7574 break;
7575 default:
7576 usage_rebase();
7577 /* NOTREACHED */
7581 argc -= optind;
7582 argv += optind;
7584 #ifndef PROFILE
7585 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7586 "unveil", NULL) == -1)
7587 err(1, "pledge");
7588 #endif
7589 if (abort_rebase && continue_rebase)
7590 usage_rebase();
7591 else if (abort_rebase || continue_rebase) {
7592 if (argc != 0)
7593 usage_rebase();
7594 } else if (argc != 1)
7595 usage_rebase();
7597 cwd = getcwd(NULL, 0);
7598 if (cwd == NULL) {
7599 error = got_error_from_errno("getcwd");
7600 goto done;
7602 error = got_worktree_open(&worktree, cwd);
7603 if (error) {
7604 if (error->code == GOT_ERR_NOT_WORKTREE)
7605 error = wrap_not_worktree_error(error, "rebase", cwd);
7606 goto done;
7609 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7610 NULL);
7611 if (error != NULL)
7612 goto done;
7614 error = apply_unveil(got_repo_get_path(repo), 0,
7615 got_worktree_get_root_path(worktree));
7616 if (error)
7617 goto done;
7619 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7620 worktree);
7621 if (error)
7622 goto done;
7623 if (histedit_in_progress) {
7624 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7625 goto done;
7628 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7629 if (error)
7630 goto done;
7632 if (abort_rebase) {
7633 struct got_update_progress_arg upa;
7634 if (!rebase_in_progress) {
7635 error = got_error(GOT_ERR_NOT_REBASING);
7636 goto done;
7638 error = got_worktree_rebase_continue(&resume_commit_id,
7639 &new_base_branch, &tmp_branch, &branch, &fileindex,
7640 worktree, repo);
7641 if (error)
7642 goto done;
7643 printf("Switching work tree to %s\n",
7644 got_ref_get_symref_target(new_base_branch));
7645 memset(&upa, 0, sizeof(upa));
7646 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7647 new_base_branch, update_progress, &upa);
7648 if (error)
7649 goto done;
7650 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7651 print_update_progress_stats(&upa);
7652 goto done; /* nothing else to do */
7655 if (continue_rebase) {
7656 if (!rebase_in_progress) {
7657 error = got_error(GOT_ERR_NOT_REBASING);
7658 goto done;
7660 error = got_worktree_rebase_continue(&resume_commit_id,
7661 &new_base_branch, &tmp_branch, &branch, &fileindex,
7662 worktree, repo);
7663 if (error)
7664 goto done;
7666 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7667 resume_commit_id, repo);
7668 if (error)
7669 goto done;
7671 yca_id = got_object_id_dup(resume_commit_id);
7672 if (yca_id == NULL) {
7673 error = got_error_from_errno("got_object_id_dup");
7674 goto done;
7676 } else {
7677 error = got_ref_open(&branch, repo, argv[0], 0);
7678 if (error != NULL)
7679 goto done;
7682 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7683 if (error)
7684 goto done;
7686 if (!continue_rebase) {
7687 struct got_object_id *base_commit_id;
7689 base_commit_id = got_worktree_get_base_commit_id(worktree);
7690 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7691 base_commit_id, branch_head_commit_id, repo,
7692 check_cancelled, NULL);
7693 if (error)
7694 goto done;
7695 if (yca_id == NULL) {
7696 error = got_error_msg(GOT_ERR_ANCESTRY,
7697 "specified branch shares no common ancestry "
7698 "with work tree's branch");
7699 goto done;
7702 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7703 if (error) {
7704 if (error->code != GOT_ERR_ANCESTRY)
7705 goto done;
7706 error = NULL;
7707 } else {
7708 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7709 "specified branch resolves to a commit which "
7710 "is already contained in work tree's branch");
7711 goto done;
7713 error = got_worktree_rebase_prepare(&new_base_branch,
7714 &tmp_branch, &fileindex, worktree, branch, repo);
7715 if (error)
7716 goto done;
7719 commit_id = branch_head_commit_id;
7720 error = got_object_open_as_commit(&commit, repo, commit_id);
7721 if (error)
7722 goto done;
7724 parent_ids = got_object_commit_get_parent_ids(commit);
7725 pid = SIMPLEQ_FIRST(parent_ids);
7726 if (pid == NULL) {
7727 if (!continue_rebase) {
7728 struct got_update_progress_arg upa;
7729 memset(&upa, 0, sizeof(upa));
7730 error = got_worktree_rebase_abort(worktree, fileindex,
7731 repo, new_base_branch, update_progress, &upa);
7732 if (error)
7733 goto done;
7734 printf("Rebase of %s aborted\n",
7735 got_ref_get_name(branch));
7736 print_update_progress_stats(&upa);
7739 error = got_error(GOT_ERR_EMPTY_REBASE);
7740 goto done;
7742 error = collect_commits(&commits, commit_id, pid->id,
7743 yca_id, got_worktree_get_path_prefix(worktree),
7744 GOT_ERR_REBASE_PATH, repo);
7745 got_object_commit_close(commit);
7746 commit = NULL;
7747 if (error)
7748 goto done;
7750 if (SIMPLEQ_EMPTY(&commits)) {
7751 if (continue_rebase) {
7752 error = rebase_complete(worktree, fileindex,
7753 branch, new_base_branch, tmp_branch, repo);
7754 goto done;
7755 } else {
7756 /* Fast-forward the reference of the branch. */
7757 struct got_object_id *new_head_commit_id;
7758 char *id_str;
7759 error = got_ref_resolve(&new_head_commit_id, repo,
7760 new_base_branch);
7761 if (error)
7762 goto done;
7763 error = got_object_id_str(&id_str, new_head_commit_id);
7764 printf("Forwarding %s to commit %s\n",
7765 got_ref_get_name(branch), id_str);
7766 free(id_str);
7767 error = got_ref_change_ref(branch,
7768 new_head_commit_id);
7769 if (error)
7770 goto done;
7774 pid = NULL;
7775 SIMPLEQ_FOREACH(qid, &commits, entry) {
7776 struct got_update_progress_arg upa;
7778 commit_id = qid->id;
7779 parent_id = pid ? pid->id : yca_id;
7780 pid = qid;
7782 memset(&upa, 0, sizeof(upa));
7783 error = got_worktree_rebase_merge_files(&merged_paths,
7784 worktree, fileindex, parent_id, commit_id, repo,
7785 update_progress, &upa, check_cancelled, NULL);
7786 if (error)
7787 goto done;
7789 print_update_progress_stats(&upa);
7790 if (upa.conflicts > 0)
7791 rebase_status = GOT_STATUS_CONFLICT;
7793 if (rebase_status == GOT_STATUS_CONFLICT) {
7794 error = show_rebase_merge_conflict(qid->id, repo);
7795 if (error)
7796 goto done;
7797 got_worktree_rebase_pathlist_free(&merged_paths);
7798 break;
7801 error = rebase_commit(&merged_paths, worktree, fileindex,
7802 tmp_branch, commit_id, repo);
7803 got_worktree_rebase_pathlist_free(&merged_paths);
7804 if (error)
7805 goto done;
7808 if (rebase_status == GOT_STATUS_CONFLICT) {
7809 error = got_worktree_rebase_postpone(worktree, fileindex);
7810 if (error)
7811 goto done;
7812 error = got_error_msg(GOT_ERR_CONFLICTS,
7813 "conflicts must be resolved before rebasing can continue");
7814 } else
7815 error = rebase_complete(worktree, fileindex, branch,
7816 new_base_branch, tmp_branch, repo);
7817 done:
7818 got_object_id_queue_free(&commits);
7819 free(branch_head_commit_id);
7820 free(resume_commit_id);
7821 free(yca_id);
7822 if (commit)
7823 got_object_commit_close(commit);
7824 if (branch)
7825 got_ref_close(branch);
7826 if (new_base_branch)
7827 got_ref_close(new_base_branch);
7828 if (tmp_branch)
7829 got_ref_close(tmp_branch);
7830 if (worktree)
7831 got_worktree_close(worktree);
7832 if (repo)
7833 got_repo_close(repo);
7834 return error;
7837 __dead static void
7838 usage_histedit(void)
7840 fprintf(stderr, "usage: %s histedit [-a] [-c] [-f] [-F histedit-script] [-m]\n",
7841 getprogname());
7842 exit(1);
7845 #define GOT_HISTEDIT_PICK 'p'
7846 #define GOT_HISTEDIT_EDIT 'e'
7847 #define GOT_HISTEDIT_FOLD 'f'
7848 #define GOT_HISTEDIT_DROP 'd'
7849 #define GOT_HISTEDIT_MESG 'm'
7851 static struct got_histedit_cmd {
7852 unsigned char code;
7853 const char *name;
7854 const char *desc;
7855 } got_histedit_cmds[] = {
7856 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7857 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7858 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7859 "be used" },
7860 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7861 { GOT_HISTEDIT_MESG, "mesg",
7862 "single-line log message for commit above (open editor if empty)" },
7865 struct got_histedit_list_entry {
7866 TAILQ_ENTRY(got_histedit_list_entry) entry;
7867 struct got_object_id *commit_id;
7868 const struct got_histedit_cmd *cmd;
7869 char *logmsg;
7871 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7873 static const struct got_error *
7874 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7875 FILE *f, struct got_repository *repo)
7877 const struct got_error *err = NULL;
7878 char *logmsg = NULL, *id_str = NULL;
7879 struct got_commit_object *commit = NULL;
7880 int n;
7882 err = got_object_open_as_commit(&commit, repo, commit_id);
7883 if (err)
7884 goto done;
7886 err = get_short_logmsg(&logmsg, 34, commit);
7887 if (err)
7888 goto done;
7890 err = got_object_id_str(&id_str, commit_id);
7891 if (err)
7892 goto done;
7894 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7895 if (n < 0)
7896 err = got_ferror(f, GOT_ERR_IO);
7897 done:
7898 if (commit)
7899 got_object_commit_close(commit);
7900 free(id_str);
7901 free(logmsg);
7902 return err;
7905 static const struct got_error *
7906 histedit_write_commit_list(struct got_object_id_queue *commits,
7907 FILE *f, int edit_logmsg_only, int fold_only, struct got_repository *repo)
7909 const struct got_error *err = NULL;
7910 struct got_object_qid *qid;
7911 const char *histedit_cmd = NULL;
7913 if (SIMPLEQ_EMPTY(commits))
7914 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7916 SIMPLEQ_FOREACH(qid, commits, entry) {
7917 histedit_cmd = got_histedit_cmds[0].name;
7918 if (fold_only && SIMPLEQ_NEXT(qid, entry) != NULL)
7919 histedit_cmd = "fold";
7920 err = histedit_write_commit(qid->id, histedit_cmd, f, repo);
7921 if (err)
7922 break;
7923 if (edit_logmsg_only) {
7924 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7925 if (n < 0) {
7926 err = got_ferror(f, GOT_ERR_IO);
7927 break;
7932 return err;
7935 static const struct got_error *
7936 write_cmd_list(FILE *f, const char *branch_name,
7937 struct got_object_id_queue *commits)
7939 const struct got_error *err = NULL;
7940 size_t i;
7941 int n;
7942 char *id_str;
7943 struct got_object_qid *qid;
7945 qid = SIMPLEQ_FIRST(commits);
7946 err = got_object_id_str(&id_str, qid->id);
7947 if (err)
7948 return err;
7950 n = fprintf(f,
7951 "# Editing the history of branch '%s' starting at\n"
7952 "# commit %s\n"
7953 "# Commits will be processed in order from top to "
7954 "bottom of this file.\n", branch_name, id_str);
7955 if (n < 0) {
7956 err = got_ferror(f, GOT_ERR_IO);
7957 goto done;
7960 n = fprintf(f, "# Available histedit commands:\n");
7961 if (n < 0) {
7962 err = got_ferror(f, GOT_ERR_IO);
7963 goto done;
7966 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7967 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7968 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7969 cmd->desc);
7970 if (n < 0) {
7971 err = got_ferror(f, GOT_ERR_IO);
7972 break;
7975 done:
7976 free(id_str);
7977 return err;
7980 static const struct got_error *
7981 histedit_syntax_error(int lineno)
7983 static char msg[42];
7984 int ret;
7986 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7987 lineno);
7988 if (ret == -1 || ret >= sizeof(msg))
7989 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7991 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7994 static const struct got_error *
7995 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7996 char *logmsg, struct got_repository *repo)
7998 const struct got_error *err;
7999 struct got_commit_object *folded_commit = NULL;
8000 char *id_str, *folded_logmsg = NULL;
8002 err = got_object_id_str(&id_str, hle->commit_id);
8003 if (err)
8004 return err;
8006 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
8007 if (err)
8008 goto done;
8010 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
8011 if (err)
8012 goto done;
8013 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
8014 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
8015 folded_logmsg) == -1) {
8016 err = got_error_from_errno("asprintf");
8018 done:
8019 if (folded_commit)
8020 got_object_commit_close(folded_commit);
8021 free(id_str);
8022 free(folded_logmsg);
8023 return err;
8026 static struct got_histedit_list_entry *
8027 get_folded_commits(struct got_histedit_list_entry *hle)
8029 struct got_histedit_list_entry *prev, *folded = NULL;
8031 prev = TAILQ_PREV(hle, got_histedit_list, entry);
8032 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
8033 prev->cmd->code == GOT_HISTEDIT_DROP)) {
8034 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
8035 folded = prev;
8036 prev = TAILQ_PREV(prev, got_histedit_list, entry);
8039 return folded;
8042 static const struct got_error *
8043 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
8044 struct got_repository *repo)
8046 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
8047 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
8048 const struct got_error *err = NULL;
8049 struct got_commit_object *commit = NULL;
8050 int logmsg_len;
8051 int fd;
8052 struct got_histedit_list_entry *folded = NULL;
8054 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8055 if (err)
8056 return err;
8058 folded = get_folded_commits(hle);
8059 if (folded) {
8060 while (folded != hle) {
8061 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
8062 folded = TAILQ_NEXT(folded, entry);
8063 continue;
8065 err = append_folded_commit_msg(&new_msg, folded,
8066 logmsg, repo);
8067 if (err)
8068 goto done;
8069 free(logmsg);
8070 logmsg = new_msg;
8071 folded = TAILQ_NEXT(folded, entry);
8075 err = got_object_id_str(&id_str, hle->commit_id);
8076 if (err)
8077 goto done;
8078 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
8079 if (err)
8080 goto done;
8081 logmsg_len = asprintf(&new_msg,
8082 "%s\n# original log message of commit %s: %s",
8083 logmsg ? logmsg : "", id_str, orig_logmsg);
8084 if (logmsg_len == -1) {
8085 err = got_error_from_errno("asprintf");
8086 goto done;
8088 free(logmsg);
8089 logmsg = new_msg;
8091 err = got_object_id_str(&id_str, hle->commit_id);
8092 if (err)
8093 goto done;
8095 err = got_opentemp_named_fd(&logmsg_path, &fd,
8096 GOT_TMPDIR_STR "/got-logmsg");
8097 if (err)
8098 goto done;
8100 write(fd, logmsg, logmsg_len);
8101 close(fd);
8103 err = get_editor(&editor);
8104 if (err)
8105 goto done;
8107 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
8108 logmsg_len, 0);
8109 if (err) {
8110 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
8111 goto done;
8112 err = NULL;
8113 hle->logmsg = strdup(new_msg);
8114 if (hle->logmsg == NULL)
8115 err = got_error_from_errno("strdup");
8117 done:
8118 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
8119 err = got_error_from_errno2("unlink", logmsg_path);
8120 free(logmsg_path);
8121 free(logmsg);
8122 free(orig_logmsg);
8123 free(editor);
8124 if (commit)
8125 got_object_commit_close(commit);
8126 return err;
8129 static const struct got_error *
8130 histedit_parse_list(struct got_histedit_list *histedit_cmds,
8131 FILE *f, struct got_repository *repo)
8133 const struct got_error *err = NULL;
8134 char *line = NULL, *p, *end;
8135 size_t i, size;
8136 ssize_t len;
8137 int lineno = 0;
8138 const struct got_histedit_cmd *cmd;
8139 struct got_object_id *commit_id = NULL;
8140 struct got_histedit_list_entry *hle = NULL;
8142 for (;;) {
8143 len = getline(&line, &size, f);
8144 if (len == -1) {
8145 const struct got_error *getline_err;
8146 if (feof(f))
8147 break;
8148 getline_err = got_error_from_errno("getline");
8149 err = got_ferror(f, getline_err->code);
8150 break;
8152 lineno++;
8153 p = line;
8154 while (isspace((unsigned char)p[0]))
8155 p++;
8156 if (p[0] == '#' || p[0] == '\0') {
8157 free(line);
8158 line = NULL;
8159 continue;
8161 cmd = NULL;
8162 for (i = 0; i < nitems(got_histedit_cmds); i++) {
8163 cmd = &got_histedit_cmds[i];
8164 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
8165 isspace((unsigned char)p[strlen(cmd->name)])) {
8166 p += strlen(cmd->name);
8167 break;
8169 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
8170 p++;
8171 break;
8174 if (i == nitems(got_histedit_cmds)) {
8175 err = histedit_syntax_error(lineno);
8176 break;
8178 while (isspace((unsigned char)p[0]))
8179 p++;
8180 if (cmd->code == GOT_HISTEDIT_MESG) {
8181 if (hle == NULL || hle->logmsg != NULL) {
8182 err = got_error(GOT_ERR_HISTEDIT_CMD);
8183 break;
8185 if (p[0] == '\0') {
8186 err = histedit_edit_logmsg(hle, repo);
8187 if (err)
8188 break;
8189 } else {
8190 hle->logmsg = strdup(p);
8191 if (hle->logmsg == NULL) {
8192 err = got_error_from_errno("strdup");
8193 break;
8196 free(line);
8197 line = NULL;
8198 continue;
8199 } else {
8200 end = p;
8201 while (end[0] && !isspace((unsigned char)end[0]))
8202 end++;
8203 *end = '\0';
8205 err = got_object_resolve_id_str(&commit_id, repo, p);
8206 if (err) {
8207 /* override error code */
8208 err = histedit_syntax_error(lineno);
8209 break;
8212 hle = malloc(sizeof(*hle));
8213 if (hle == NULL) {
8214 err = got_error_from_errno("malloc");
8215 break;
8217 hle->cmd = cmd;
8218 hle->commit_id = commit_id;
8219 hle->logmsg = NULL;
8220 commit_id = NULL;
8221 free(line);
8222 line = NULL;
8223 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
8226 free(line);
8227 free(commit_id);
8228 return err;
8231 static const struct got_error *
8232 histedit_check_script(struct got_histedit_list *histedit_cmds,
8233 struct got_object_id_queue *commits, struct got_repository *repo)
8235 const struct got_error *err = NULL;
8236 struct got_object_qid *qid;
8237 struct got_histedit_list_entry *hle;
8238 static char msg[92];
8239 char *id_str;
8241 if (TAILQ_EMPTY(histedit_cmds))
8242 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
8243 "histedit script contains no commands");
8244 if (SIMPLEQ_EMPTY(commits))
8245 return got_error(GOT_ERR_EMPTY_HISTEDIT);
8247 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8248 struct got_histedit_list_entry *hle2;
8249 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
8250 if (hle == hle2)
8251 continue;
8252 if (got_object_id_cmp(hle->commit_id,
8253 hle2->commit_id) != 0)
8254 continue;
8255 err = got_object_id_str(&id_str, hle->commit_id);
8256 if (err)
8257 return err;
8258 snprintf(msg, sizeof(msg), "commit %s is listed "
8259 "more than once in histedit script", id_str);
8260 free(id_str);
8261 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8265 SIMPLEQ_FOREACH(qid, commits, entry) {
8266 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8267 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
8268 break;
8270 if (hle == NULL) {
8271 err = got_object_id_str(&id_str, qid->id);
8272 if (err)
8273 return err;
8274 snprintf(msg, sizeof(msg),
8275 "commit %s missing from histedit script", id_str);
8276 free(id_str);
8277 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8281 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
8282 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
8283 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
8284 "last commit in histedit script cannot be folded");
8286 return NULL;
8289 static const struct got_error *
8290 histedit_run_editor(struct got_histedit_list *histedit_cmds,
8291 const char *path, struct got_object_id_queue *commits,
8292 struct got_repository *repo)
8294 const struct got_error *err = NULL;
8295 char *editor;
8296 FILE *f = NULL;
8298 err = get_editor(&editor);
8299 if (err)
8300 return err;
8302 if (spawn_editor(editor, path) == -1) {
8303 err = got_error_from_errno("failed spawning editor");
8304 goto done;
8307 f = fopen(path, "r");
8308 if (f == NULL) {
8309 err = got_error_from_errno("fopen");
8310 goto done;
8312 err = histedit_parse_list(histedit_cmds, f, repo);
8313 if (err)
8314 goto done;
8316 err = histedit_check_script(histedit_cmds, commits, repo);
8317 done:
8318 if (f && fclose(f) != 0 && err == NULL)
8319 err = got_error_from_errno("fclose");
8320 free(editor);
8321 return err;
8324 static const struct got_error *
8325 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
8326 struct got_object_id_queue *, const char *, const char *,
8327 struct got_repository *);
8329 static const struct got_error *
8330 histedit_edit_script(struct got_histedit_list *histedit_cmds,
8331 struct got_object_id_queue *commits, const char *branch_name,
8332 int edit_logmsg_only, int fold_only, struct got_repository *repo)
8334 const struct got_error *err;
8335 FILE *f = NULL;
8336 char *path = NULL;
8338 err = got_opentemp_named(&path, &f, "got-histedit");
8339 if (err)
8340 return err;
8342 err = write_cmd_list(f, branch_name, commits);
8343 if (err)
8344 goto done;
8346 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
8347 fold_only, repo);
8348 if (err)
8349 goto done;
8351 if (edit_logmsg_only || fold_only) {
8352 rewind(f);
8353 err = histedit_parse_list(histedit_cmds, f, repo);
8354 } else {
8355 if (fclose(f) != 0) {
8356 err = got_error_from_errno("fclose");
8357 goto done;
8359 f = NULL;
8360 err = histedit_run_editor(histedit_cmds, path, commits, repo);
8361 if (err) {
8362 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8363 err->code != GOT_ERR_HISTEDIT_CMD)
8364 goto done;
8365 err = histedit_edit_list_retry(histedit_cmds, err,
8366 commits, path, branch_name, repo);
8369 done:
8370 if (f && fclose(f) != 0 && err == NULL)
8371 err = got_error_from_errno("fclose");
8372 if (path && unlink(path) != 0 && err == NULL)
8373 err = got_error_from_errno2("unlink", path);
8374 free(path);
8375 return err;
8378 static const struct got_error *
8379 histedit_save_list(struct got_histedit_list *histedit_cmds,
8380 struct got_worktree *worktree, struct got_repository *repo)
8382 const struct got_error *err = NULL;
8383 char *path = NULL;
8384 FILE *f = NULL;
8385 struct got_histedit_list_entry *hle;
8386 struct got_commit_object *commit = NULL;
8388 err = got_worktree_get_histedit_script_path(&path, worktree);
8389 if (err)
8390 return err;
8392 f = fopen(path, "w");
8393 if (f == NULL) {
8394 err = got_error_from_errno2("fopen", path);
8395 goto done;
8397 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8398 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
8399 repo);
8400 if (err)
8401 break;
8403 if (hle->logmsg) {
8404 int n = fprintf(f, "%c %s\n",
8405 GOT_HISTEDIT_MESG, hle->logmsg);
8406 if (n < 0) {
8407 err = got_ferror(f, GOT_ERR_IO);
8408 break;
8412 done:
8413 if (f && fclose(f) != 0 && err == NULL)
8414 err = got_error_from_errno("fclose");
8415 free(path);
8416 if (commit)
8417 got_object_commit_close(commit);
8418 return err;
8421 void
8422 histedit_free_list(struct got_histedit_list *histedit_cmds)
8424 struct got_histedit_list_entry *hle;
8426 while ((hle = TAILQ_FIRST(histedit_cmds))) {
8427 TAILQ_REMOVE(histedit_cmds, hle, entry);
8428 free(hle);
8432 static const struct got_error *
8433 histedit_load_list(struct got_histedit_list *histedit_cmds,
8434 const char *path, struct got_repository *repo)
8436 const struct got_error *err = NULL;
8437 FILE *f = NULL;
8439 f = fopen(path, "r");
8440 if (f == NULL) {
8441 err = got_error_from_errno2("fopen", path);
8442 goto done;
8445 err = histedit_parse_list(histedit_cmds, f, repo);
8446 done:
8447 if (f && fclose(f) != 0 && err == NULL)
8448 err = got_error_from_errno("fclose");
8449 return err;
8452 static const struct got_error *
8453 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
8454 const struct got_error *edit_err, struct got_object_id_queue *commits,
8455 const char *path, const char *branch_name, struct got_repository *repo)
8457 const struct got_error *err = NULL, *prev_err = edit_err;
8458 int resp = ' ';
8460 while (resp != 'c' && resp != 'r' && resp != 'a') {
8461 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
8462 "or (a)bort: ", getprogname(), prev_err->msg);
8463 resp = getchar();
8464 if (resp == '\n')
8465 resp = getchar();
8466 if (resp == 'c') {
8467 histedit_free_list(histedit_cmds);
8468 err = histedit_run_editor(histedit_cmds, path, commits,
8469 repo);
8470 if (err) {
8471 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8472 err->code != GOT_ERR_HISTEDIT_CMD)
8473 break;
8474 prev_err = err;
8475 resp = ' ';
8476 continue;
8478 break;
8479 } else if (resp == 'r') {
8480 histedit_free_list(histedit_cmds);
8481 err = histedit_edit_script(histedit_cmds,
8482 commits, branch_name, 0, 0, repo);
8483 if (err) {
8484 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8485 err->code != GOT_ERR_HISTEDIT_CMD)
8486 break;
8487 prev_err = err;
8488 resp = ' ';
8489 continue;
8491 break;
8492 } else if (resp == 'a') {
8493 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
8494 break;
8495 } else
8496 printf("invalid response '%c'\n", resp);
8499 return err;
8502 static const struct got_error *
8503 histedit_complete(struct got_worktree *worktree,
8504 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
8505 struct got_reference *branch, struct got_repository *repo)
8507 printf("Switching work tree to %s\n",
8508 got_ref_get_symref_target(branch));
8509 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
8510 branch, repo);
8513 static const struct got_error *
8514 show_histedit_progress(struct got_commit_object *commit,
8515 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
8517 const struct got_error *err;
8518 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8520 err = got_object_id_str(&old_id_str, hle->commit_id);
8521 if (err)
8522 goto done;
8524 if (new_id) {
8525 err = got_object_id_str(&new_id_str, new_id);
8526 if (err)
8527 goto done;
8530 old_id_str[12] = '\0';
8531 if (new_id_str)
8532 new_id_str[12] = '\0';
8534 if (hle->logmsg) {
8535 logmsg = strdup(hle->logmsg);
8536 if (logmsg == NULL) {
8537 err = got_error_from_errno("strdup");
8538 goto done;
8540 trim_logmsg(logmsg, 42);
8541 } else {
8542 err = get_short_logmsg(&logmsg, 42, commit);
8543 if (err)
8544 goto done;
8547 switch (hle->cmd->code) {
8548 case GOT_HISTEDIT_PICK:
8549 case GOT_HISTEDIT_EDIT:
8550 printf("%s -> %s: %s\n", old_id_str,
8551 new_id_str ? new_id_str : "no-op change", logmsg);
8552 break;
8553 case GOT_HISTEDIT_DROP:
8554 case GOT_HISTEDIT_FOLD:
8555 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
8556 logmsg);
8557 break;
8558 default:
8559 break;
8561 done:
8562 free(old_id_str);
8563 free(new_id_str);
8564 return err;
8567 static const struct got_error *
8568 histedit_commit(struct got_pathlist_head *merged_paths,
8569 struct got_worktree *worktree, struct got_fileindex *fileindex,
8570 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
8571 struct got_repository *repo)
8573 const struct got_error *err;
8574 struct got_commit_object *commit;
8575 struct got_object_id *new_commit_id;
8577 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
8578 && hle->logmsg == NULL) {
8579 err = histedit_edit_logmsg(hle, repo);
8580 if (err)
8581 return err;
8584 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8585 if (err)
8586 return err;
8588 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
8589 worktree, fileindex, tmp_branch, commit, hle->commit_id,
8590 hle->logmsg, repo);
8591 if (err) {
8592 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
8593 goto done;
8594 err = show_histedit_progress(commit, hle, NULL);
8595 } else {
8596 err = show_histedit_progress(commit, hle, new_commit_id);
8597 free(new_commit_id);
8599 done:
8600 got_object_commit_close(commit);
8601 return err;
8604 static const struct got_error *
8605 histedit_skip_commit(struct got_histedit_list_entry *hle,
8606 struct got_worktree *worktree, struct got_repository *repo)
8608 const struct got_error *error;
8609 struct got_commit_object *commit;
8611 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
8612 repo);
8613 if (error)
8614 return error;
8616 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
8617 if (error)
8618 return error;
8620 error = show_histedit_progress(commit, hle, NULL);
8621 got_object_commit_close(commit);
8622 return error;
8625 static const struct got_error *
8626 check_local_changes(void *arg, unsigned char status,
8627 unsigned char staged_status, const char *path,
8628 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8629 struct got_object_id *commit_id, int dirfd, const char *de_name)
8631 int *have_local_changes = arg;
8633 switch (status) {
8634 case GOT_STATUS_ADD:
8635 case GOT_STATUS_DELETE:
8636 case GOT_STATUS_MODIFY:
8637 case GOT_STATUS_CONFLICT:
8638 *have_local_changes = 1;
8639 return got_error(GOT_ERR_CANCELLED);
8640 default:
8641 break;
8644 switch (staged_status) {
8645 case GOT_STATUS_ADD:
8646 case GOT_STATUS_DELETE:
8647 case GOT_STATUS_MODIFY:
8648 *have_local_changes = 1;
8649 return got_error(GOT_ERR_CANCELLED);
8650 default:
8651 break;
8654 return NULL;
8657 static const struct got_error *
8658 cmd_histedit(int argc, char *argv[])
8660 const struct got_error *error = NULL;
8661 struct got_worktree *worktree = NULL;
8662 struct got_fileindex *fileindex = NULL;
8663 struct got_repository *repo = NULL;
8664 char *cwd = NULL;
8665 struct got_reference *branch = NULL;
8666 struct got_reference *tmp_branch = NULL;
8667 struct got_object_id *resume_commit_id = NULL;
8668 struct got_object_id *base_commit_id = NULL;
8669 struct got_object_id *head_commit_id = NULL;
8670 struct got_commit_object *commit = NULL;
8671 int ch, rebase_in_progress = 0;
8672 struct got_update_progress_arg upa;
8673 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8674 int edit_logmsg_only = 0, fold_only = 0;
8675 const char *edit_script_path = NULL;
8676 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8677 struct got_object_id_queue commits;
8678 struct got_pathlist_head merged_paths;
8679 const struct got_object_id_queue *parent_ids;
8680 struct got_object_qid *pid;
8681 struct got_histedit_list histedit_cmds;
8682 struct got_histedit_list_entry *hle;
8684 SIMPLEQ_INIT(&commits);
8685 TAILQ_INIT(&histedit_cmds);
8686 TAILQ_INIT(&merged_paths);
8687 memset(&upa, 0, sizeof(upa));
8689 while ((ch = getopt(argc, argv, "acfF:m")) != -1) {
8690 switch (ch) {
8691 case 'a':
8692 abort_edit = 1;
8693 break;
8694 case 'c':
8695 continue_edit = 1;
8696 break;
8697 case 'f':
8698 fold_only = 1;
8699 break;
8700 case 'F':
8701 edit_script_path = optarg;
8702 break;
8703 case 'm':
8704 edit_logmsg_only = 1;
8705 break;
8706 default:
8707 usage_histedit();
8708 /* NOTREACHED */
8712 argc -= optind;
8713 argv += optind;
8715 #ifndef PROFILE
8716 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8717 "unveil", NULL) == -1)
8718 err(1, "pledge");
8719 #endif
8720 if (abort_edit && continue_edit)
8721 option_conflict('a', 'c');
8722 if (edit_script_path && edit_logmsg_only)
8723 option_conflict('F', 'm');
8724 if (abort_edit && edit_logmsg_only)
8725 option_conflict('a', 'm');
8726 if (continue_edit && edit_logmsg_only)
8727 option_conflict('c', 'm');
8728 if (abort_edit && fold_only)
8729 option_conflict('a', 'f');
8730 if (continue_edit && fold_only)
8731 option_conflict('c', 'f');
8732 if (fold_only && edit_logmsg_only)
8733 option_conflict('f', 'm');
8734 if (edit_script_path && fold_only)
8735 option_conflict('F', 'f');
8736 if (argc != 0)
8737 usage_histedit();
8740 * This command cannot apply unveil(2) in all cases because the
8741 * user may choose to run an editor to edit the histedit script
8742 * and to edit individual commit log messages.
8743 * unveil(2) traverses exec(2); if an editor is used we have to
8744 * apply unveil after edit script and log messages have been written.
8745 * XXX TODO: Make use of unveil(2) where possible.
8748 cwd = getcwd(NULL, 0);
8749 if (cwd == NULL) {
8750 error = got_error_from_errno("getcwd");
8751 goto done;
8753 error = got_worktree_open(&worktree, cwd);
8754 if (error) {
8755 if (error->code == GOT_ERR_NOT_WORKTREE)
8756 error = wrap_not_worktree_error(error, "histedit", cwd);
8757 goto done;
8760 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8761 NULL);
8762 if (error != NULL)
8763 goto done;
8765 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8766 if (error)
8767 goto done;
8768 if (rebase_in_progress) {
8769 error = got_error(GOT_ERR_REBASING);
8770 goto done;
8773 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8774 if (error)
8775 goto done;
8777 if (edit_in_progress && edit_logmsg_only) {
8778 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8779 "histedit operation is in progress in this "
8780 "work tree and must be continued or aborted "
8781 "before the -m option can be used");
8782 goto done;
8784 if (edit_in_progress && fold_only) {
8785 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8786 "histedit operation is in progress in this "
8787 "work tree and must be continued or aborted "
8788 "before the -f option can be used");
8789 goto done;
8792 if (edit_in_progress && abort_edit) {
8793 error = got_worktree_histedit_continue(&resume_commit_id,
8794 &tmp_branch, &branch, &base_commit_id, &fileindex,
8795 worktree, repo);
8796 if (error)
8797 goto done;
8798 printf("Switching work tree to %s\n",
8799 got_ref_get_symref_target(branch));
8800 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8801 branch, base_commit_id, update_progress, &upa);
8802 if (error)
8803 goto done;
8804 printf("Histedit of %s aborted\n",
8805 got_ref_get_symref_target(branch));
8806 print_update_progress_stats(&upa);
8807 goto done; /* nothing else to do */
8808 } else if (abort_edit) {
8809 error = got_error(GOT_ERR_NOT_HISTEDIT);
8810 goto done;
8813 if (continue_edit) {
8814 char *path;
8816 if (!edit_in_progress) {
8817 error = got_error(GOT_ERR_NOT_HISTEDIT);
8818 goto done;
8821 error = got_worktree_get_histedit_script_path(&path, worktree);
8822 if (error)
8823 goto done;
8825 error = histedit_load_list(&histedit_cmds, path, repo);
8826 free(path);
8827 if (error)
8828 goto done;
8830 error = got_worktree_histedit_continue(&resume_commit_id,
8831 &tmp_branch, &branch, &base_commit_id, &fileindex,
8832 worktree, repo);
8833 if (error)
8834 goto done;
8836 error = got_ref_resolve(&head_commit_id, repo, branch);
8837 if (error)
8838 goto done;
8840 error = got_object_open_as_commit(&commit, repo,
8841 head_commit_id);
8842 if (error)
8843 goto done;
8844 parent_ids = got_object_commit_get_parent_ids(commit);
8845 pid = SIMPLEQ_FIRST(parent_ids);
8846 if (pid == NULL) {
8847 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8848 goto done;
8850 error = collect_commits(&commits, head_commit_id, pid->id,
8851 base_commit_id, got_worktree_get_path_prefix(worktree),
8852 GOT_ERR_HISTEDIT_PATH, repo);
8853 got_object_commit_close(commit);
8854 commit = NULL;
8855 if (error)
8856 goto done;
8857 } else {
8858 if (edit_in_progress) {
8859 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8860 goto done;
8863 error = got_ref_open(&branch, repo,
8864 got_worktree_get_head_ref_name(worktree), 0);
8865 if (error != NULL)
8866 goto done;
8868 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8869 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8870 "will not edit commit history of a branch outside "
8871 "the \"refs/heads/\" reference namespace");
8872 goto done;
8875 error = got_ref_resolve(&head_commit_id, repo, branch);
8876 got_ref_close(branch);
8877 branch = NULL;
8878 if (error)
8879 goto done;
8881 error = got_object_open_as_commit(&commit, repo,
8882 head_commit_id);
8883 if (error)
8884 goto done;
8885 parent_ids = got_object_commit_get_parent_ids(commit);
8886 pid = SIMPLEQ_FIRST(parent_ids);
8887 if (pid == NULL) {
8888 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8889 goto done;
8891 error = collect_commits(&commits, head_commit_id, pid->id,
8892 got_worktree_get_base_commit_id(worktree),
8893 got_worktree_get_path_prefix(worktree),
8894 GOT_ERR_HISTEDIT_PATH, repo);
8895 got_object_commit_close(commit);
8896 commit = NULL;
8897 if (error)
8898 goto done;
8900 if (SIMPLEQ_EMPTY(&commits)) {
8901 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8902 goto done;
8905 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8906 &base_commit_id, &fileindex, worktree, repo);
8907 if (error)
8908 goto done;
8910 if (edit_script_path) {
8911 error = histedit_load_list(&histedit_cmds,
8912 edit_script_path, repo);
8913 if (error) {
8914 got_worktree_histedit_abort(worktree, fileindex,
8915 repo, branch, base_commit_id,
8916 update_progress, &upa);
8917 print_update_progress_stats(&upa);
8918 goto done;
8920 } else {
8921 const char *branch_name;
8922 branch_name = got_ref_get_symref_target(branch);
8923 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8924 branch_name += 11;
8925 error = histedit_edit_script(&histedit_cmds, &commits,
8926 branch_name, edit_logmsg_only, fold_only, repo);
8927 if (error) {
8928 got_worktree_histedit_abort(worktree, fileindex,
8929 repo, branch, base_commit_id,
8930 update_progress, &upa);
8931 print_update_progress_stats(&upa);
8932 goto done;
8937 error = histedit_save_list(&histedit_cmds, worktree,
8938 repo);
8939 if (error) {
8940 got_worktree_histedit_abort(worktree, fileindex,
8941 repo, branch, base_commit_id,
8942 update_progress, &upa);
8943 print_update_progress_stats(&upa);
8944 goto done;
8949 error = histedit_check_script(&histedit_cmds, &commits, repo);
8950 if (error)
8951 goto done;
8953 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8954 if (resume_commit_id) {
8955 if (got_object_id_cmp(hle->commit_id,
8956 resume_commit_id) != 0)
8957 continue;
8959 resume_commit_id = NULL;
8960 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8961 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8962 error = histedit_skip_commit(hle, worktree,
8963 repo);
8964 if (error)
8965 goto done;
8966 } else {
8967 struct got_pathlist_head paths;
8968 int have_changes = 0;
8970 TAILQ_INIT(&paths);
8971 error = got_pathlist_append(&paths, "", NULL);
8972 if (error)
8973 goto done;
8974 error = got_worktree_status(worktree, &paths,
8975 repo, check_local_changes, &have_changes,
8976 check_cancelled, NULL);
8977 got_pathlist_free(&paths);
8978 if (error) {
8979 if (error->code != GOT_ERR_CANCELLED)
8980 goto done;
8981 if (sigint_received || sigpipe_received)
8982 goto done;
8984 if (have_changes) {
8985 error = histedit_commit(NULL, worktree,
8986 fileindex, tmp_branch, hle, repo);
8987 if (error)
8988 goto done;
8989 } else {
8990 error = got_object_open_as_commit(
8991 &commit, repo, hle->commit_id);
8992 if (error)
8993 goto done;
8994 error = show_histedit_progress(commit,
8995 hle, NULL);
8996 got_object_commit_close(commit);
8997 commit = NULL;
8998 if (error)
8999 goto done;
9002 continue;
9005 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
9006 error = histedit_skip_commit(hle, worktree, repo);
9007 if (error)
9008 goto done;
9009 continue;
9012 error = got_object_open_as_commit(&commit, repo,
9013 hle->commit_id);
9014 if (error)
9015 goto done;
9016 parent_ids = got_object_commit_get_parent_ids(commit);
9017 pid = SIMPLEQ_FIRST(parent_ids);
9019 error = got_worktree_histedit_merge_files(&merged_paths,
9020 worktree, fileindex, pid->id, hle->commit_id, repo,
9021 update_progress, &upa, check_cancelled, NULL);
9022 if (error)
9023 goto done;
9024 got_object_commit_close(commit);
9025 commit = NULL;
9027 print_update_progress_stats(&upa);
9028 if (upa.conflicts > 0)
9029 rebase_status = GOT_STATUS_CONFLICT;
9031 if (rebase_status == GOT_STATUS_CONFLICT) {
9032 error = show_rebase_merge_conflict(hle->commit_id,
9033 repo);
9034 if (error)
9035 goto done;
9036 got_worktree_rebase_pathlist_free(&merged_paths);
9037 break;
9040 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
9041 char *id_str;
9042 error = got_object_id_str(&id_str, hle->commit_id);
9043 if (error)
9044 goto done;
9045 printf("Stopping histedit for amending commit %s\n",
9046 id_str);
9047 free(id_str);
9048 got_worktree_rebase_pathlist_free(&merged_paths);
9049 error = got_worktree_histedit_postpone(worktree,
9050 fileindex);
9051 goto done;
9054 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
9055 error = histedit_skip_commit(hle, worktree, repo);
9056 if (error)
9057 goto done;
9058 continue;
9061 error = histedit_commit(&merged_paths, worktree, fileindex,
9062 tmp_branch, hle, repo);
9063 got_worktree_rebase_pathlist_free(&merged_paths);
9064 if (error)
9065 goto done;
9068 if (rebase_status == GOT_STATUS_CONFLICT) {
9069 error = got_worktree_histedit_postpone(worktree, fileindex);
9070 if (error)
9071 goto done;
9072 error = got_error_msg(GOT_ERR_CONFLICTS,
9073 "conflicts must be resolved before histedit can continue");
9074 } else
9075 error = histedit_complete(worktree, fileindex, tmp_branch,
9076 branch, repo);
9077 done:
9078 got_object_id_queue_free(&commits);
9079 histedit_free_list(&histedit_cmds);
9080 free(head_commit_id);
9081 free(base_commit_id);
9082 free(resume_commit_id);
9083 if (commit)
9084 got_object_commit_close(commit);
9085 if (branch)
9086 got_ref_close(branch);
9087 if (tmp_branch)
9088 got_ref_close(tmp_branch);
9089 if (worktree)
9090 got_worktree_close(worktree);
9091 if (repo)
9092 got_repo_close(repo);
9093 return error;
9096 __dead static void
9097 usage_integrate(void)
9099 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
9100 exit(1);
9103 static const struct got_error *
9104 cmd_integrate(int argc, char *argv[])
9106 const struct got_error *error = NULL;
9107 struct got_repository *repo = NULL;
9108 struct got_worktree *worktree = NULL;
9109 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
9110 const char *branch_arg = NULL;
9111 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
9112 struct got_fileindex *fileindex = NULL;
9113 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
9114 int ch;
9115 struct got_update_progress_arg upa;
9117 while ((ch = getopt(argc, argv, "")) != -1) {
9118 switch (ch) {
9119 default:
9120 usage_integrate();
9121 /* NOTREACHED */
9125 argc -= optind;
9126 argv += optind;
9128 if (argc != 1)
9129 usage_integrate();
9130 branch_arg = argv[0];
9131 #ifndef PROFILE
9132 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9133 "unveil", NULL) == -1)
9134 err(1, "pledge");
9135 #endif
9136 cwd = getcwd(NULL, 0);
9137 if (cwd == NULL) {
9138 error = got_error_from_errno("getcwd");
9139 goto done;
9142 error = got_worktree_open(&worktree, cwd);
9143 if (error) {
9144 if (error->code == GOT_ERR_NOT_WORKTREE)
9145 error = wrap_not_worktree_error(error, "integrate",
9146 cwd);
9147 goto done;
9150 error = check_rebase_or_histedit_in_progress(worktree);
9151 if (error)
9152 goto done;
9154 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9155 NULL);
9156 if (error != NULL)
9157 goto done;
9159 error = apply_unveil(got_repo_get_path(repo), 0,
9160 got_worktree_get_root_path(worktree));
9161 if (error)
9162 goto done;
9164 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
9165 error = got_error_from_errno("asprintf");
9166 goto done;
9169 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
9170 &base_branch_ref, worktree, refname, repo);
9171 if (error)
9172 goto done;
9174 refname = strdup(got_ref_get_name(branch_ref));
9175 if (refname == NULL) {
9176 error = got_error_from_errno("strdup");
9177 got_worktree_integrate_abort(worktree, fileindex, repo,
9178 branch_ref, base_branch_ref);
9179 goto done;
9181 base_refname = strdup(got_ref_get_name(base_branch_ref));
9182 if (base_refname == NULL) {
9183 error = got_error_from_errno("strdup");
9184 got_worktree_integrate_abort(worktree, fileindex, repo,
9185 branch_ref, base_branch_ref);
9186 goto done;
9189 error = got_ref_resolve(&commit_id, repo, branch_ref);
9190 if (error)
9191 goto done;
9193 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
9194 if (error)
9195 goto done;
9197 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
9198 error = got_error_msg(GOT_ERR_SAME_BRANCH,
9199 "specified branch has already been integrated");
9200 got_worktree_integrate_abort(worktree, fileindex, repo,
9201 branch_ref, base_branch_ref);
9202 goto done;
9205 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
9206 if (error) {
9207 if (error->code == GOT_ERR_ANCESTRY)
9208 error = got_error(GOT_ERR_REBASE_REQUIRED);
9209 got_worktree_integrate_abort(worktree, fileindex, repo,
9210 branch_ref, base_branch_ref);
9211 goto done;
9214 memset(&upa, 0, sizeof(upa));
9215 error = got_worktree_integrate_continue(worktree, fileindex, repo,
9216 branch_ref, base_branch_ref, update_progress, &upa,
9217 check_cancelled, NULL);
9218 if (error)
9219 goto done;
9221 printf("Integrated %s into %s\n", refname, base_refname);
9222 print_update_progress_stats(&upa);
9223 done:
9224 if (repo)
9225 got_repo_close(repo);
9226 if (worktree)
9227 got_worktree_close(worktree);
9228 free(cwd);
9229 free(base_commit_id);
9230 free(commit_id);
9231 free(refname);
9232 free(base_refname);
9233 return error;
9236 __dead static void
9237 usage_stage(void)
9239 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
9240 "[-S] [file-path ...]\n",
9241 getprogname());
9242 exit(1);
9245 static const struct got_error *
9246 print_stage(void *arg, unsigned char status, unsigned char staged_status,
9247 const char *path, struct got_object_id *blob_id,
9248 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
9249 int dirfd, const char *de_name)
9251 const struct got_error *err = NULL;
9252 char *id_str = NULL;
9254 if (staged_status != GOT_STATUS_ADD &&
9255 staged_status != GOT_STATUS_MODIFY &&
9256 staged_status != GOT_STATUS_DELETE)
9257 return NULL;
9259 if (staged_status == GOT_STATUS_ADD ||
9260 staged_status == GOT_STATUS_MODIFY)
9261 err = got_object_id_str(&id_str, staged_blob_id);
9262 else
9263 err = got_object_id_str(&id_str, blob_id);
9264 if (err)
9265 return err;
9267 printf("%s %c %s\n", id_str, staged_status, path);
9268 free(id_str);
9269 return NULL;
9272 static const struct got_error *
9273 cmd_stage(int argc, char *argv[])
9275 const struct got_error *error = NULL;
9276 struct got_repository *repo = NULL;
9277 struct got_worktree *worktree = NULL;
9278 char *cwd = NULL;
9279 struct got_pathlist_head paths;
9280 struct got_pathlist_entry *pe;
9281 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
9282 FILE *patch_script_file = NULL;
9283 const char *patch_script_path = NULL;
9284 struct choose_patch_arg cpa;
9286 TAILQ_INIT(&paths);
9288 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
9289 switch (ch) {
9290 case 'l':
9291 list_stage = 1;
9292 break;
9293 case 'p':
9294 pflag = 1;
9295 break;
9296 case 'F':
9297 patch_script_path = optarg;
9298 break;
9299 case 'S':
9300 allow_bad_symlinks = 1;
9301 break;
9302 default:
9303 usage_stage();
9304 /* NOTREACHED */
9308 argc -= optind;
9309 argv += optind;
9311 #ifndef PROFILE
9312 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9313 "unveil", NULL) == -1)
9314 err(1, "pledge");
9315 #endif
9316 if (list_stage && (pflag || patch_script_path))
9317 errx(1, "-l option cannot be used with other options");
9318 if (patch_script_path && !pflag)
9319 errx(1, "-F option can only be used together with -p option");
9321 cwd = getcwd(NULL, 0);
9322 if (cwd == NULL) {
9323 error = got_error_from_errno("getcwd");
9324 goto done;
9327 error = got_worktree_open(&worktree, cwd);
9328 if (error) {
9329 if (error->code == GOT_ERR_NOT_WORKTREE)
9330 error = wrap_not_worktree_error(error, "stage", cwd);
9331 goto done;
9334 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9335 NULL);
9336 if (error != NULL)
9337 goto done;
9339 if (patch_script_path) {
9340 patch_script_file = fopen(patch_script_path, "r");
9341 if (patch_script_file == NULL) {
9342 error = got_error_from_errno2("fopen",
9343 patch_script_path);
9344 goto done;
9347 error = apply_unveil(got_repo_get_path(repo), 0,
9348 got_worktree_get_root_path(worktree));
9349 if (error)
9350 goto done;
9352 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9353 if (error)
9354 goto done;
9356 if (list_stage)
9357 error = got_worktree_status(worktree, &paths, repo,
9358 print_stage, NULL, check_cancelled, NULL);
9359 else {
9360 cpa.patch_script_file = patch_script_file;
9361 cpa.action = "stage";
9362 error = got_worktree_stage(worktree, &paths,
9363 pflag ? NULL : print_status, NULL,
9364 pflag ? choose_patch : NULL, &cpa,
9365 allow_bad_symlinks, repo);
9367 done:
9368 if (patch_script_file && fclose(patch_script_file) == EOF &&
9369 error == NULL)
9370 error = got_error_from_errno2("fclose", patch_script_path);
9371 if (repo)
9372 got_repo_close(repo);
9373 if (worktree)
9374 got_worktree_close(worktree);
9375 TAILQ_FOREACH(pe, &paths, entry)
9376 free((char *)pe->path);
9377 got_pathlist_free(&paths);
9378 free(cwd);
9379 return error;
9382 __dead static void
9383 usage_unstage(void)
9385 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
9386 "[file-path ...]\n",
9387 getprogname());
9388 exit(1);
9392 static const struct got_error *
9393 cmd_unstage(int argc, char *argv[])
9395 const struct got_error *error = NULL;
9396 struct got_repository *repo = NULL;
9397 struct got_worktree *worktree = NULL;
9398 char *cwd = NULL;
9399 struct got_pathlist_head paths;
9400 struct got_pathlist_entry *pe;
9401 int ch, pflag = 0;
9402 struct got_update_progress_arg upa;
9403 FILE *patch_script_file = NULL;
9404 const char *patch_script_path = NULL;
9405 struct choose_patch_arg cpa;
9407 TAILQ_INIT(&paths);
9409 while ((ch = getopt(argc, argv, "pF:")) != -1) {
9410 switch (ch) {
9411 case 'p':
9412 pflag = 1;
9413 break;
9414 case 'F':
9415 patch_script_path = optarg;
9416 break;
9417 default:
9418 usage_unstage();
9419 /* NOTREACHED */
9423 argc -= optind;
9424 argv += optind;
9426 #ifndef PROFILE
9427 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9428 "unveil", NULL) == -1)
9429 err(1, "pledge");
9430 #endif
9431 if (patch_script_path && !pflag)
9432 errx(1, "-F option can only be used together with -p option");
9434 cwd = getcwd(NULL, 0);
9435 if (cwd == NULL) {
9436 error = got_error_from_errno("getcwd");
9437 goto done;
9440 error = got_worktree_open(&worktree, cwd);
9441 if (error) {
9442 if (error->code == GOT_ERR_NOT_WORKTREE)
9443 error = wrap_not_worktree_error(error, "unstage", cwd);
9444 goto done;
9447 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9448 NULL);
9449 if (error != NULL)
9450 goto done;
9452 if (patch_script_path) {
9453 patch_script_file = fopen(patch_script_path, "r");
9454 if (patch_script_file == NULL) {
9455 error = got_error_from_errno2("fopen",
9456 patch_script_path);
9457 goto done;
9461 error = apply_unveil(got_repo_get_path(repo), 0,
9462 got_worktree_get_root_path(worktree));
9463 if (error)
9464 goto done;
9466 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9467 if (error)
9468 goto done;
9470 cpa.patch_script_file = patch_script_file;
9471 cpa.action = "unstage";
9472 memset(&upa, 0, sizeof(upa));
9473 error = got_worktree_unstage(worktree, &paths, update_progress,
9474 &upa, pflag ? choose_patch : NULL, &cpa, repo);
9475 if (!error)
9476 print_update_progress_stats(&upa);
9477 done:
9478 if (patch_script_file && fclose(patch_script_file) == EOF &&
9479 error == NULL)
9480 error = got_error_from_errno2("fclose", patch_script_path);
9481 if (repo)
9482 got_repo_close(repo);
9483 if (worktree)
9484 got_worktree_close(worktree);
9485 TAILQ_FOREACH(pe, &paths, entry)
9486 free((char *)pe->path);
9487 got_pathlist_free(&paths);
9488 free(cwd);
9489 return error;
9492 __dead static void
9493 usage_cat(void)
9495 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
9496 "arg1 [arg2 ...]\n", getprogname());
9497 exit(1);
9500 static const struct got_error *
9501 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9503 const struct got_error *err;
9504 struct got_blob_object *blob;
9506 err = got_object_open_as_blob(&blob, repo, id, 8192);
9507 if (err)
9508 return err;
9510 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
9511 got_object_blob_close(blob);
9512 return err;
9515 static const struct got_error *
9516 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9518 const struct got_error *err;
9519 struct got_tree_object *tree;
9520 int nentries, i;
9522 err = got_object_open_as_tree(&tree, repo, id);
9523 if (err)
9524 return err;
9526 nentries = got_object_tree_get_nentries(tree);
9527 for (i = 0; i < nentries; i++) {
9528 struct got_tree_entry *te;
9529 char *id_str;
9530 if (sigint_received || sigpipe_received)
9531 break;
9532 te = got_object_tree_get_entry(tree, i);
9533 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
9534 if (err)
9535 break;
9536 fprintf(outfile, "%s %.7o %s\n", id_str,
9537 got_tree_entry_get_mode(te),
9538 got_tree_entry_get_name(te));
9539 free(id_str);
9542 got_object_tree_close(tree);
9543 return err;
9546 static const struct got_error *
9547 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9549 const struct got_error *err;
9550 struct got_commit_object *commit;
9551 const struct got_object_id_queue *parent_ids;
9552 struct got_object_qid *pid;
9553 char *id_str = NULL;
9554 const char *logmsg = NULL;
9556 err = got_object_open_as_commit(&commit, repo, id);
9557 if (err)
9558 return err;
9560 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
9561 if (err)
9562 goto done;
9564 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
9565 parent_ids = got_object_commit_get_parent_ids(commit);
9566 fprintf(outfile, "numparents %d\n",
9567 got_object_commit_get_nparents(commit));
9568 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
9569 char *pid_str;
9570 err = got_object_id_str(&pid_str, pid->id);
9571 if (err)
9572 goto done;
9573 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
9574 free(pid_str);
9576 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
9577 got_object_commit_get_author(commit),
9578 (long long)got_object_commit_get_author_time(commit));
9580 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
9581 got_object_commit_get_author(commit),
9582 (long long)got_object_commit_get_committer_time(commit));
9584 logmsg = got_object_commit_get_logmsg_raw(commit);
9585 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
9586 fprintf(outfile, "%s", logmsg);
9587 done:
9588 free(id_str);
9589 got_object_commit_close(commit);
9590 return err;
9593 static const struct got_error *
9594 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9596 const struct got_error *err;
9597 struct got_tag_object *tag;
9598 char *id_str = NULL;
9599 const char *tagmsg = NULL;
9601 err = got_object_open_as_tag(&tag, repo, id);
9602 if (err)
9603 return err;
9605 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
9606 if (err)
9607 goto done;
9609 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
9611 switch (got_object_tag_get_object_type(tag)) {
9612 case GOT_OBJ_TYPE_BLOB:
9613 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9614 GOT_OBJ_LABEL_BLOB);
9615 break;
9616 case GOT_OBJ_TYPE_TREE:
9617 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9618 GOT_OBJ_LABEL_TREE);
9619 break;
9620 case GOT_OBJ_TYPE_COMMIT:
9621 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9622 GOT_OBJ_LABEL_COMMIT);
9623 break;
9624 case GOT_OBJ_TYPE_TAG:
9625 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9626 GOT_OBJ_LABEL_TAG);
9627 break;
9628 default:
9629 break;
9632 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
9633 got_object_tag_get_name(tag));
9635 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
9636 got_object_tag_get_tagger(tag),
9637 (long long)got_object_tag_get_tagger_time(tag));
9639 tagmsg = got_object_tag_get_message(tag);
9640 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
9641 fprintf(outfile, "%s", tagmsg);
9642 done:
9643 free(id_str);
9644 got_object_tag_close(tag);
9645 return err;
9648 static const struct got_error *
9649 cmd_cat(int argc, char *argv[])
9651 const struct got_error *error;
9652 struct got_repository *repo = NULL;
9653 struct got_worktree *worktree = NULL;
9654 char *cwd = NULL, *repo_path = NULL, *label = NULL;
9655 const char *commit_id_str = NULL;
9656 struct got_object_id *id = NULL, *commit_id = NULL;
9657 int ch, obj_type, i, force_path = 0;
9658 struct got_reflist_head refs;
9660 TAILQ_INIT(&refs);
9662 #ifndef PROFILE
9663 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9664 NULL) == -1)
9665 err(1, "pledge");
9666 #endif
9668 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
9669 switch (ch) {
9670 case 'c':
9671 commit_id_str = optarg;
9672 break;
9673 case 'r':
9674 repo_path = realpath(optarg, NULL);
9675 if (repo_path == NULL)
9676 return got_error_from_errno2("realpath",
9677 optarg);
9678 got_path_strip_trailing_slashes(repo_path);
9679 break;
9680 case 'P':
9681 force_path = 1;
9682 break;
9683 default:
9684 usage_cat();
9685 /* NOTREACHED */
9689 argc -= optind;
9690 argv += optind;
9692 cwd = getcwd(NULL, 0);
9693 if (cwd == NULL) {
9694 error = got_error_from_errno("getcwd");
9695 goto done;
9697 error = got_worktree_open(&worktree, cwd);
9698 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9699 goto done;
9700 if (worktree) {
9701 if (repo_path == NULL) {
9702 repo_path = strdup(
9703 got_worktree_get_repo_path(worktree));
9704 if (repo_path == NULL) {
9705 error = got_error_from_errno("strdup");
9706 goto done;
9711 if (repo_path == NULL) {
9712 repo_path = getcwd(NULL, 0);
9713 if (repo_path == NULL)
9714 return got_error_from_errno("getcwd");
9717 error = got_repo_open(&repo, repo_path, NULL);
9718 free(repo_path);
9719 if (error != NULL)
9720 goto done;
9722 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9723 if (error)
9724 goto done;
9726 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9727 if (error)
9728 goto done;
9730 if (commit_id_str == NULL)
9731 commit_id_str = GOT_REF_HEAD;
9732 error = got_repo_match_object_id(&commit_id, NULL,
9733 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
9734 if (error)
9735 goto done;
9737 for (i = 0; i < argc; i++) {
9738 if (force_path) {
9739 error = got_object_id_by_path(&id, repo, commit_id,
9740 argv[i]);
9741 if (error)
9742 break;
9743 } else {
9744 error = got_repo_match_object_id(&id, &label, argv[i],
9745 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
9746 repo);
9747 if (error) {
9748 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9749 error->code != GOT_ERR_NOT_REF)
9750 break;
9751 error = got_object_id_by_path(&id, repo,
9752 commit_id, argv[i]);
9753 if (error)
9754 break;
9758 error = got_object_get_type(&obj_type, repo, id);
9759 if (error)
9760 break;
9762 switch (obj_type) {
9763 case GOT_OBJ_TYPE_BLOB:
9764 error = cat_blob(id, repo, stdout);
9765 break;
9766 case GOT_OBJ_TYPE_TREE:
9767 error = cat_tree(id, repo, stdout);
9768 break;
9769 case GOT_OBJ_TYPE_COMMIT:
9770 error = cat_commit(id, repo, stdout);
9771 break;
9772 case GOT_OBJ_TYPE_TAG:
9773 error = cat_tag(id, repo, stdout);
9774 break;
9775 default:
9776 error = got_error(GOT_ERR_OBJ_TYPE);
9777 break;
9779 if (error)
9780 break;
9781 free(label);
9782 label = NULL;
9783 free(id);
9784 id = NULL;
9786 done:
9787 free(label);
9788 free(id);
9789 free(commit_id);
9790 if (worktree)
9791 got_worktree_close(worktree);
9792 if (repo) {
9793 const struct got_error *repo_error;
9794 repo_error = got_repo_close(repo);
9795 if (error == NULL)
9796 error = repo_error;
9798 got_ref_list_free(&refs);
9799 return error;
9802 __dead static void
9803 usage_info(void)
9805 fprintf(stderr, "usage: %s info [path ...]\n",
9806 getprogname());
9807 exit(1);
9810 static const struct got_error *
9811 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
9812 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9813 struct got_object_id *commit_id)
9815 const struct got_error *err = NULL;
9816 char *id_str = NULL;
9817 char datebuf[128];
9818 struct tm mytm, *tm;
9819 struct got_pathlist_head *paths = arg;
9820 struct got_pathlist_entry *pe;
9823 * Clear error indication from any of the path arguments which
9824 * would cause this file index entry to be displayed.
9826 TAILQ_FOREACH(pe, paths, entry) {
9827 if (got_path_cmp(path, pe->path, strlen(path),
9828 pe->path_len) == 0 ||
9829 got_path_is_child(path, pe->path, pe->path_len))
9830 pe->data = NULL; /* no error */
9833 printf(GOT_COMMIT_SEP_STR);
9834 if (S_ISLNK(mode))
9835 printf("symlink: %s\n", path);
9836 else if (S_ISREG(mode)) {
9837 printf("file: %s\n", path);
9838 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
9839 } else if (S_ISDIR(mode))
9840 printf("directory: %s\n", path);
9841 else
9842 printf("something: %s\n", path);
9844 tm = localtime_r(&mtime, &mytm);
9845 if (tm == NULL)
9846 return NULL;
9847 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) >= sizeof(datebuf))
9848 return got_error(GOT_ERR_NO_SPACE);
9849 printf("timestamp: %s\n", datebuf);
9851 if (blob_id) {
9852 err = got_object_id_str(&id_str, blob_id);
9853 if (err)
9854 return err;
9855 printf("based on blob: %s\n", id_str);
9856 free(id_str);
9859 if (staged_blob_id) {
9860 err = got_object_id_str(&id_str, staged_blob_id);
9861 if (err)
9862 return err;
9863 printf("based on staged blob: %s\n", id_str);
9864 free(id_str);
9867 if (commit_id) {
9868 err = got_object_id_str(&id_str, commit_id);
9869 if (err)
9870 return err;
9871 printf("based on commit: %s\n", id_str);
9872 free(id_str);
9875 return NULL;
9878 static const struct got_error *
9879 cmd_info(int argc, char *argv[])
9881 const struct got_error *error = NULL;
9882 struct got_worktree *worktree = NULL;
9883 char *cwd = NULL, *id_str = NULL;
9884 struct got_pathlist_head paths;
9885 struct got_pathlist_entry *pe;
9886 char *uuidstr = NULL;
9887 int ch, show_files = 0;
9889 TAILQ_INIT(&paths);
9891 while ((ch = getopt(argc, argv, "")) != -1) {
9892 switch (ch) {
9893 default:
9894 usage_info();
9895 /* NOTREACHED */
9899 argc -= optind;
9900 argv += optind;
9902 #ifndef PROFILE
9903 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
9904 NULL) == -1)
9905 err(1, "pledge");
9906 #endif
9907 cwd = getcwd(NULL, 0);
9908 if (cwd == NULL) {
9909 error = got_error_from_errno("getcwd");
9910 goto done;
9913 error = got_worktree_open(&worktree, cwd);
9914 if (error) {
9915 if (error->code == GOT_ERR_NOT_WORKTREE)
9916 error = wrap_not_worktree_error(error, "status", cwd);
9917 goto done;
9920 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9921 if (error)
9922 goto done;
9924 if (argc >= 1) {
9925 error = get_worktree_paths_from_argv(&paths, argc, argv,
9926 worktree);
9927 if (error)
9928 goto done;
9929 show_files = 1;
9932 error = got_object_id_str(&id_str,
9933 got_worktree_get_base_commit_id(worktree));
9934 if (error)
9935 goto done;
9937 error = got_worktree_get_uuid(&uuidstr, worktree);
9938 if (error)
9939 goto done;
9941 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9942 printf("work tree base commit: %s\n", id_str);
9943 printf("work tree path prefix: %s\n",
9944 got_worktree_get_path_prefix(worktree));
9945 printf("work tree branch reference: %s\n",
9946 got_worktree_get_head_ref_name(worktree));
9947 printf("work tree UUID: %s\n", uuidstr);
9948 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
9950 if (show_files) {
9951 struct got_pathlist_entry *pe;
9952 TAILQ_FOREACH(pe, &paths, entry) {
9953 if (pe->path_len == 0)
9954 continue;
9956 * Assume this path will fail. This will be corrected
9957 * in print_path_info() in case the path does suceeed.
9959 pe->data = (void *)got_error_path(pe->path,
9960 GOT_ERR_BAD_PATH);
9962 error = got_worktree_path_info(worktree, &paths,
9963 print_path_info, &paths, check_cancelled, NULL);
9964 if (error)
9965 goto done;
9966 TAILQ_FOREACH(pe, &paths, entry) {
9967 if (pe->data != NULL) {
9968 error = pe->data; /* bad path */
9969 break;
9973 done:
9974 TAILQ_FOREACH(pe, &paths, entry)
9975 free((char *)pe->path);
9976 got_pathlist_free(&paths);
9977 free(cwd);
9978 free(id_str);
9979 free(uuidstr);
9980 return error;