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 int 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 unsigned int 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)
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 (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);
571 done:
572 if (fd != -1 && close(fd) == -1 && err == NULL)
573 err = got_error_from_errno2("close", *logmsg_path);
574 free(initial_content);
575 if (err) {
576 free(*logmsg_path);
577 *logmsg_path = NULL;
579 return err;
582 static const struct got_error *
583 import_progress(void *arg, const char *path)
585 printf("A %s\n", path);
586 return NULL;
589 static const struct got_error *
590 get_author(char **author, struct got_repository *repo,
591 struct got_worktree *worktree)
593 const struct got_error *err = NULL;
594 const char *got_author = NULL, *name, *email;
595 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
597 *author = NULL;
599 if (worktree)
600 worktree_conf = got_worktree_get_gotconfig(worktree);
601 repo_conf = got_repo_get_gotconfig(repo);
603 /*
604 * Priority of potential author information sources, from most
605 * significant to least significant:
606 * 1) work tree's .got/got.conf file
607 * 2) repository's got.conf file
608 * 3) repository's git config file
609 * 4) environment variables
610 * 5) global git config files (in user's home directory or /etc)
611 */
613 if (worktree_conf)
614 got_author = got_gotconfig_get_author(worktree_conf);
615 if (got_author == NULL)
616 got_author = got_gotconfig_get_author(repo_conf);
617 if (got_author == NULL) {
618 name = got_repo_get_gitconfig_author_name(repo);
619 email = got_repo_get_gitconfig_author_email(repo);
620 if (name && email) {
621 if (asprintf(author, "%s <%s>", name, email) == -1)
622 return got_error_from_errno("asprintf");
623 return NULL;
626 got_author = getenv("GOT_AUTHOR");
627 if (got_author == NULL) {
628 name = got_repo_get_global_gitconfig_author_name(repo);
629 email = got_repo_get_global_gitconfig_author_email(
630 repo);
631 if (name && email) {
632 if (asprintf(author, "%s <%s>", name, email)
633 == -1)
634 return got_error_from_errno("asprintf");
635 return NULL;
637 /* TODO: Look up user in password database? */
638 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
642 *author = strdup(got_author);
643 if (*author == NULL)
644 return got_error_from_errno("strdup");
646 /*
647 * Really dumb email address check; we're only doing this to
648 * avoid git's object parser breaking on commits we create.
649 */
650 while (*got_author && *got_author != '<')
651 got_author++;
652 if (*got_author != '<') {
653 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
654 goto done;
656 while (*got_author && *got_author != '@')
657 got_author++;
658 if (*got_author != '@') {
659 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
660 goto done;
662 while (*got_author && *got_author != '>')
663 got_author++;
664 if (*got_author != '>')
665 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
666 done:
667 if (err) {
668 free(*author);
669 *author = NULL;
671 return err;
674 static const struct got_error *
675 get_gitconfig_path(char **gitconfig_path)
677 const char *homedir = getenv("HOME");
679 *gitconfig_path = NULL;
680 if (homedir) {
681 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
682 return got_error_from_errno("asprintf");
685 return NULL;
688 static const struct got_error *
689 cmd_import(int argc, char *argv[])
691 const struct got_error *error = NULL;
692 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
693 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
694 const char *branch_name = "main";
695 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
696 struct got_repository *repo = NULL;
697 struct got_reference *branch_ref = NULL, *head_ref = NULL;
698 struct got_object_id *new_commit_id = NULL;
699 int ch;
700 struct got_pathlist_head ignores;
701 struct got_pathlist_entry *pe;
702 int preserve_logmsg = 0;
704 TAILQ_INIT(&ignores);
706 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
707 switch (ch) {
708 case 'b':
709 branch_name = optarg;
710 break;
711 case 'm':
712 logmsg = strdup(optarg);
713 if (logmsg == NULL) {
714 error = got_error_from_errno("strdup");
715 goto done;
717 break;
718 case 'r':
719 repo_path = realpath(optarg, NULL);
720 if (repo_path == NULL) {
721 error = got_error_from_errno2("realpath",
722 optarg);
723 goto done;
725 break;
726 case 'I':
727 if (optarg[0] == '\0')
728 break;
729 error = got_pathlist_insert(&pe, &ignores, optarg,
730 NULL);
731 if (error)
732 goto done;
733 break;
734 default:
735 usage_import();
736 /* NOTREACHED */
740 argc -= optind;
741 argv += optind;
743 #ifndef PROFILE
744 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
745 "unveil",
746 NULL) == -1)
747 err(1, "pledge");
748 #endif
749 if (argc != 1)
750 usage_import();
752 if (repo_path == NULL) {
753 repo_path = getcwd(NULL, 0);
754 if (repo_path == NULL)
755 return got_error_from_errno("getcwd");
757 got_path_strip_trailing_slashes(repo_path);
758 error = get_gitconfig_path(&gitconfig_path);
759 if (error)
760 goto done;
761 error = got_repo_open(&repo, repo_path, gitconfig_path);
762 if (error)
763 goto done;
765 error = get_author(&author, repo, NULL);
766 if (error)
767 return error;
769 /*
770 * Don't let the user create a branch name with a leading '-'.
771 * While technically a valid reference name, this case is usually
772 * an unintended typo.
773 */
774 if (branch_name[0] == '-')
775 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
777 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
778 error = got_error_from_errno("asprintf");
779 goto done;
782 error = got_ref_open(&branch_ref, repo, refname, 0);
783 if (error) {
784 if (error->code != GOT_ERR_NOT_REF)
785 goto done;
786 } else {
787 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
788 "import target branch already exists");
789 goto done;
792 path_dir = realpath(argv[0], NULL);
793 if (path_dir == NULL) {
794 error = got_error_from_errno2("realpath", argv[0]);
795 goto done;
797 got_path_strip_trailing_slashes(path_dir);
799 /*
800 * unveil(2) traverses exec(2); if an editor is used we have
801 * to apply unveil after the log message has been written.
802 */
803 if (logmsg == NULL || strlen(logmsg) == 0) {
804 error = get_editor(&editor);
805 if (error)
806 goto done;
807 free(logmsg);
808 error = collect_import_msg(&logmsg, &logmsg_path, editor,
809 path_dir, refname);
810 if (error) {
811 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
812 logmsg_path != NULL)
813 preserve_logmsg = 1;
814 goto done;
818 if (unveil(path_dir, "r") != 0) {
819 error = got_error_from_errno2("unveil", path_dir);
820 if (logmsg_path)
821 preserve_logmsg = 1;
822 goto done;
825 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
826 if (error) {
827 if (logmsg_path)
828 preserve_logmsg = 1;
829 goto done;
832 error = got_repo_import(&new_commit_id, path_dir, logmsg,
833 author, &ignores, repo, import_progress, NULL);
834 if (error) {
835 if (logmsg_path)
836 preserve_logmsg = 1;
837 goto done;
840 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
841 if (error) {
842 if (logmsg_path)
843 preserve_logmsg = 1;
844 goto done;
847 error = got_ref_write(branch_ref, repo);
848 if (error) {
849 if (logmsg_path)
850 preserve_logmsg = 1;
851 goto done;
854 error = got_object_id_str(&id_str, new_commit_id);
855 if (error) {
856 if (logmsg_path)
857 preserve_logmsg = 1;
858 goto done;
861 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
862 if (error) {
863 if (error->code != GOT_ERR_NOT_REF) {
864 if (logmsg_path)
865 preserve_logmsg = 1;
866 goto done;
869 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
870 branch_ref);
871 if (error) {
872 if (logmsg_path)
873 preserve_logmsg = 1;
874 goto done;
877 error = got_ref_write(head_ref, repo);
878 if (error) {
879 if (logmsg_path)
880 preserve_logmsg = 1;
881 goto done;
885 printf("Created branch %s with commit %s\n",
886 got_ref_get_name(branch_ref), id_str);
887 done:
888 if (preserve_logmsg) {
889 fprintf(stderr, "%s: log message preserved in %s\n",
890 getprogname(), logmsg_path);
891 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
892 error = got_error_from_errno2("unlink", logmsg_path);
893 free(logmsg);
894 free(logmsg_path);
895 free(repo_path);
896 free(editor);
897 free(refname);
898 free(new_commit_id);
899 free(id_str);
900 free(author);
901 free(gitconfig_path);
902 if (branch_ref)
903 got_ref_close(branch_ref);
904 if (head_ref)
905 got_ref_close(head_ref);
906 return error;
909 __dead static void
910 usage_clone(void)
912 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
913 "[-R reference] repository-url [directory]\n", getprogname());
914 exit(1);
917 struct got_fetch_progress_arg {
918 char last_scaled_size[FMT_SCALED_STRSIZE];
919 int last_p_indexed;
920 int last_p_resolved;
921 int verbosity;
923 struct got_repository *repo;
925 int create_configs;
926 int configs_created;
927 struct {
928 struct got_pathlist_head *symrefs;
929 struct got_pathlist_head *wanted_branches;
930 const char *proto;
931 const char *host;
932 const char *port;
933 const char *remote_repo_path;
934 const char *git_url;
935 int fetch_all_branches;
936 int mirror_references;
937 } config_info;
938 };
940 /* XXX forward declaration */
941 static const struct got_error *
942 create_config_files(const char *proto, const char *host, const char *port,
943 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
944 int mirror_references, struct got_pathlist_head *symrefs,
945 struct got_pathlist_head *wanted_branches, struct got_repository *repo);
947 static const struct got_error *
948 fetch_progress(void *arg, const char *message, off_t packfile_size,
949 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
951 const struct got_error *err = NULL;
952 struct got_fetch_progress_arg *a = arg;
953 char scaled_size[FMT_SCALED_STRSIZE];
954 int p_indexed, p_resolved;
955 int print_size = 0, print_indexed = 0, print_resolved = 0;
957 /*
958 * In order to allow a failed clone to be resumed with 'got fetch'
959 * we try to create configuration files as soon as possible.
960 * Once the server has sent information about its default branch
961 * we have all required information.
962 */
963 if (a->create_configs && !a->configs_created &&
964 !TAILQ_EMPTY(a->config_info.symrefs)) {
965 err = create_config_files(a->config_info.proto,
966 a->config_info.host, a->config_info.port,
967 a->config_info.remote_repo_path,
968 a->config_info.git_url,
969 a->config_info.fetch_all_branches,
970 a->config_info.mirror_references,
971 a->config_info.symrefs,
972 a->config_info.wanted_branches, a->repo);
973 if (err)
974 return err;
975 a->configs_created = 1;
978 if (a->verbosity < 0)
979 return NULL;
981 if (message && message[0] != '\0') {
982 printf("\rserver: %s", message);
983 fflush(stdout);
984 return NULL;
987 if (packfile_size > 0 || nobj_indexed > 0) {
988 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
989 (a->last_scaled_size[0] == '\0' ||
990 strcmp(scaled_size, a->last_scaled_size)) != 0) {
991 print_size = 1;
992 if (strlcpy(a->last_scaled_size, scaled_size,
993 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
994 return got_error(GOT_ERR_NO_SPACE);
996 if (nobj_indexed > 0) {
997 p_indexed = (nobj_indexed * 100) / nobj_total;
998 if (p_indexed != a->last_p_indexed) {
999 a->last_p_indexed = p_indexed;
1000 print_indexed = 1;
1001 print_size = 1;
1004 if (nobj_resolved > 0) {
1005 p_resolved = (nobj_resolved * 100) /
1006 (nobj_total - nobj_loose);
1007 if (p_resolved != a->last_p_resolved) {
1008 a->last_p_resolved = p_resolved;
1009 print_resolved = 1;
1010 print_indexed = 1;
1011 print_size = 1;
1016 if (print_size || print_indexed || print_resolved)
1017 printf("\r");
1018 if (print_size)
1019 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
1020 if (print_indexed)
1021 printf("; indexing %d%%", p_indexed);
1022 if (print_resolved)
1023 printf("; resolving deltas %d%%", p_resolved);
1024 if (print_size || print_indexed || print_resolved)
1025 fflush(stdout);
1027 return NULL;
1030 static const struct got_error *
1031 create_symref(const char *refname, struct got_reference *target_ref,
1032 int verbosity, struct got_repository *repo)
1034 const struct got_error *err;
1035 struct got_reference *head_symref;
1037 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1038 if (err)
1039 return err;
1041 err = got_ref_write(head_symref, repo);
1042 if (err == NULL && verbosity > 0) {
1043 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1044 got_ref_get_name(target_ref));
1046 got_ref_close(head_symref);
1047 return err;
1050 static const struct got_error *
1051 list_remote_refs(struct got_pathlist_head *symrefs,
1052 struct got_pathlist_head *refs)
1054 const struct got_error *err;
1055 struct got_pathlist_entry *pe;
1057 TAILQ_FOREACH(pe, symrefs, entry) {
1058 const char *refname = pe->path;
1059 const char *targetref = pe->data;
1061 printf("%s: %s\n", refname, targetref);
1064 TAILQ_FOREACH(pe, refs, entry) {
1065 const char *refname = pe->path;
1066 struct got_object_id *id = pe->data;
1067 char *id_str;
1069 err = got_object_id_str(&id_str, id);
1070 if (err)
1071 return err;
1072 printf("%s: %s\n", refname, id_str);
1073 free(id_str);
1076 return NULL;
1079 static const struct got_error *
1080 create_ref(const char *refname, struct got_object_id *id,
1081 int verbosity, struct got_repository *repo)
1083 const struct got_error *err = NULL;
1084 struct got_reference *ref;
1085 char *id_str;
1087 err = got_object_id_str(&id_str, id);
1088 if (err)
1089 return err;
1091 err = got_ref_alloc(&ref, refname, id);
1092 if (err)
1093 goto done;
1095 err = got_ref_write(ref, repo);
1096 got_ref_close(ref);
1098 if (err == NULL && verbosity >= 0)
1099 printf("Created reference %s: %s\n", refname, id_str);
1100 done:
1101 free(id_str);
1102 return err;
1105 static int
1106 match_wanted_ref(const char *refname, const char *wanted_ref)
1108 if (strncmp(refname, "refs/", 5) != 0)
1109 return 0;
1110 refname += 5;
1113 * Prevent fetching of references that won't make any
1114 * sense outside of the remote repository's context.
1116 if (strncmp(refname, "got/", 4) == 0)
1117 return 0;
1118 if (strncmp(refname, "remotes/", 8) == 0)
1119 return 0;
1121 if (strncmp(wanted_ref, "refs/", 5) == 0)
1122 wanted_ref += 5;
1124 /* Allow prefix match. */
1125 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1126 return 1;
1128 /* Allow exact match. */
1129 return (strcmp(refname, wanted_ref) == 0);
1132 static int
1133 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1135 struct got_pathlist_entry *pe;
1137 TAILQ_FOREACH(pe, wanted_refs, entry) {
1138 if (match_wanted_ref(refname, pe->path))
1139 return 1;
1142 return 0;
1145 static const struct got_error *
1146 create_wanted_ref(const char *refname, struct got_object_id *id,
1147 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1149 const struct got_error *err;
1150 char *remote_refname;
1152 if (strncmp("refs/", refname, 5) == 0)
1153 refname += 5;
1155 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1156 remote_repo_name, refname) == -1)
1157 return got_error_from_errno("asprintf");
1159 err = create_ref(remote_refname, id, verbosity, repo);
1160 free(remote_refname);
1161 return err;
1164 static const struct got_error *
1165 create_gotconfig(const char *proto, const char *host, const char *port,
1166 const char *remote_repo_path, int fetch_all_branches, int mirror_references,
1167 struct got_repository *repo)
1169 const struct got_error *err = NULL;
1170 char *gotconfig_path = NULL;
1171 char *gotconfig = NULL;
1172 FILE *gotconfig_file = NULL;
1173 ssize_t n;
1175 /* Create got.conf(5). */
1176 gotconfig_path = got_repo_get_path_gotconfig(repo);
1177 if (gotconfig_path == NULL) {
1178 err = got_error_from_errno("got_repo_get_path_gotconfig");
1179 goto done;
1181 gotconfig_file = fopen(gotconfig_path, "a");
1182 if (gotconfig_file == NULL) {
1183 err = got_error_from_errno2("fopen", gotconfig_path);
1184 goto done;
1186 if (asprintf(&gotconfig,
1187 "remote \"%s\" {\n"
1188 "\tserver %s\n"
1189 "\tprotocol %s\n"
1190 "%s%s%s"
1191 "\trepository \"%s\"\n"
1192 "%s"
1193 "}\n",
1194 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1195 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1196 remote_repo_path,
1197 mirror_references ? "\tmirror-references yes\n" : "") == -1) {
1198 err = got_error_from_errno("asprintf");
1199 goto done;
1201 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1202 if (n != strlen(gotconfig)) {
1203 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1204 goto done;
1207 done:
1208 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1209 err = got_error_from_errno2("fclose", gotconfig_path);
1210 free(gotconfig_path);
1211 return err;
1214 static const struct got_error *
1215 create_gitconfig(const char *git_url, const char *default_branch,
1216 int fetch_all_branches, int mirror_references, struct got_repository *repo)
1218 const struct got_error *err = NULL;
1219 char *gitconfig_path = NULL;
1220 char *gitconfig = NULL;
1221 FILE *gitconfig_file = NULL;
1222 ssize_t n;
1224 /* Create a config file Git can understand. */
1225 gitconfig_path = got_repo_get_path_gitconfig(repo);
1226 if (gitconfig_path == NULL) {
1227 err = got_error_from_errno("got_repo_get_path_gitconfig");
1228 goto done;
1230 gitconfig_file = fopen(gitconfig_path, "a");
1231 if (gitconfig_file == NULL) {
1232 err = got_error_from_errno2("fopen", gitconfig_path);
1233 goto done;
1235 if (mirror_references) {
1236 if (asprintf(&gitconfig,
1237 "[remote \"%s\"]\n"
1238 "\turl = %s\n"
1239 "\tfetch = +refs/*:refs/*\n"
1240 "\tmirror = true\n",
1241 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1242 err = got_error_from_errno("asprintf");
1243 goto done;
1245 } else if (fetch_all_branches) {
1246 if (asprintf(&gitconfig,
1247 "[remote \"%s\"]\n"
1248 "\turl = %s\n"
1249 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1250 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1251 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1252 err = got_error_from_errno("asprintf");
1253 goto done;
1255 } else {
1256 const char *branchname;
1259 * If the server specified a default branch, use just that one.
1260 * Otherwise fall back to fetching all branches on next fetch.
1262 if (default_branch) {
1263 branchname = default_branch;
1264 if (strncmp(branchname, "refs/heads/", 11) == 0)
1265 branchname += 11;
1266 } else
1267 branchname = "*"; /* fall back to all branches */
1268 if (asprintf(&gitconfig,
1269 "[remote \"%s\"]\n"
1270 "\turl = %s\n"
1271 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1272 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1273 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1274 branchname) == -1) {
1275 err = got_error_from_errno("asprintf");
1276 goto done;
1279 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1280 if (n != strlen(gitconfig)) {
1281 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1282 goto done;
1284 done:
1285 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1286 err = got_error_from_errno2("fclose", gitconfig_path);
1287 free(gitconfig_path);
1288 return err;
1291 static const struct got_error *
1292 create_config_files(const char *proto, const char *host, const char *port,
1293 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1294 int mirror_references, struct got_pathlist_head *symrefs,
1295 struct got_pathlist_head *wanted_branches, struct got_repository *repo)
1297 const struct got_error *err = NULL;
1298 const char *default_branch = NULL;
1299 struct got_pathlist_entry *pe;
1302 * If we asked for a set of wanted branches then use the first
1303 * one of those.
1305 if (!TAILQ_EMPTY(wanted_branches)) {
1306 pe = TAILQ_FIRST(wanted_branches);
1307 default_branch = pe->path;
1308 } else {
1309 /* First HEAD ref listed by server is the default branch. */
1310 TAILQ_FOREACH(pe, symrefs, entry) {
1311 const char *refname = pe->path;
1312 const char *target = pe->data;
1314 if (strcmp(refname, GOT_REF_HEAD) != 0)
1315 continue;
1317 default_branch = target;
1318 break;
1322 /* Create got.conf(5). */
1323 err = create_gotconfig(proto, host, port, remote_repo_path,
1324 fetch_all_branches, mirror_references, repo);
1325 if (err)
1326 return err;
1328 /* Create a config file Git can understand. */
1329 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1330 mirror_references, repo);
1333 static const struct got_error *
1334 cmd_clone(int argc, char *argv[])
1336 const struct got_error *error = NULL;
1337 const char *uri, *dirname;
1338 char *proto, *host, *port, *repo_name, *server_path;
1339 char *default_destdir = NULL, *id_str = NULL;
1340 const char *repo_path;
1341 struct got_repository *repo = NULL;
1342 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1343 struct got_pathlist_entry *pe;
1344 struct got_object_id *pack_hash = NULL;
1345 int ch, fetchfd = -1, fetchstatus;
1346 pid_t fetchpid = -1;
1347 struct got_fetch_progress_arg fpa;
1348 char *git_url = NULL;
1349 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1350 int list_refs_only = 0;
1352 TAILQ_INIT(&refs);
1353 TAILQ_INIT(&symrefs);
1354 TAILQ_INIT(&wanted_branches);
1355 TAILQ_INIT(&wanted_refs);
1357 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1358 switch (ch) {
1359 case 'a':
1360 fetch_all_branches = 1;
1361 break;
1362 case 'b':
1363 error = got_pathlist_append(&wanted_branches,
1364 optarg, NULL);
1365 if (error)
1366 return error;
1367 break;
1368 case 'l':
1369 list_refs_only = 1;
1370 break;
1371 case 'm':
1372 mirror_references = 1;
1373 break;
1374 case 'v':
1375 if (verbosity < 0)
1376 verbosity = 0;
1377 else if (verbosity < 3)
1378 verbosity++;
1379 break;
1380 case 'q':
1381 verbosity = -1;
1382 break;
1383 case 'R':
1384 error = got_pathlist_append(&wanted_refs,
1385 optarg, NULL);
1386 if (error)
1387 return error;
1388 break;
1389 default:
1390 usage_clone();
1391 break;
1394 argc -= optind;
1395 argv += optind;
1397 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1398 option_conflict('a', 'b');
1399 if (list_refs_only) {
1400 if (!TAILQ_EMPTY(&wanted_branches))
1401 option_conflict('l', 'b');
1402 if (fetch_all_branches)
1403 option_conflict('l', 'a');
1404 if (mirror_references)
1405 option_conflict('l', 'm');
1406 if (verbosity == -1)
1407 option_conflict('l', 'q');
1408 if (!TAILQ_EMPTY(&wanted_refs))
1409 option_conflict('l', 'R');
1412 uri = argv[0];
1414 if (argc == 1)
1415 dirname = NULL;
1416 else if (argc == 2)
1417 dirname = argv[1];
1418 else
1419 usage_clone();
1421 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1422 &repo_name, uri);
1423 if (error)
1424 goto done;
1426 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1427 host, port ? ":" : "", port ? port : "",
1428 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1429 error = got_error_from_errno("asprintf");
1430 goto done;
1433 if (strcmp(proto, "git") == 0) {
1434 #ifndef PROFILE
1435 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1436 "sendfd dns inet unveil", NULL) == -1)
1437 err(1, "pledge");
1438 #endif
1439 } else if (strcmp(proto, "git+ssh") == 0 ||
1440 strcmp(proto, "ssh") == 0) {
1441 #ifndef PROFILE
1442 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1443 "sendfd unveil", NULL) == -1)
1444 err(1, "pledge");
1445 #endif
1446 } else if (strcmp(proto, "http") == 0 ||
1447 strcmp(proto, "git+http") == 0) {
1448 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1449 goto done;
1450 } else {
1451 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1452 goto done;
1454 if (dirname == NULL) {
1455 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1456 error = got_error_from_errno("asprintf");
1457 goto done;
1459 repo_path = default_destdir;
1460 } else
1461 repo_path = dirname;
1463 if (!list_refs_only) {
1464 error = got_path_mkdir(repo_path);
1465 if (error &&
1466 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1467 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1468 goto done;
1469 if (!got_path_dir_is_empty(repo_path)) {
1470 error = got_error_path(repo_path,
1471 GOT_ERR_DIR_NOT_EMPTY);
1472 goto done;
1476 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1477 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1478 error = got_error_from_errno2("unveil",
1479 GOT_FETCH_PATH_SSH);
1480 goto done;
1483 error = apply_unveil(repo_path, 0, NULL);
1484 if (error)
1485 goto done;
1487 if (verbosity >= 0)
1488 printf("Connecting to %s%s%s\n", host,
1489 port ? ":" : "", port ? port : "");
1491 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1492 server_path, verbosity);
1493 if (error)
1494 goto done;
1496 if (!list_refs_only) {
1497 error = got_repo_init(repo_path);
1498 if (error)
1499 goto done;
1500 error = got_repo_open(&repo, repo_path, NULL);
1501 if (error)
1502 goto done;
1505 fpa.last_scaled_size[0] = '\0';
1506 fpa.last_p_indexed = -1;
1507 fpa.last_p_resolved = -1;
1508 fpa.verbosity = verbosity;
1509 fpa.create_configs = 1;
1510 fpa.configs_created = 0;
1511 fpa.repo = repo;
1512 fpa.config_info.symrefs = &symrefs;
1513 fpa.config_info.wanted_branches = &wanted_branches;
1514 fpa.config_info.proto = proto;
1515 fpa.config_info.host = host;
1516 fpa.config_info.port = port;
1517 fpa.config_info.remote_repo_path = server_path;
1518 fpa.config_info.git_url = git_url;
1519 fpa.config_info.fetch_all_branches = fetch_all_branches;
1520 fpa.config_info.mirror_references = mirror_references;
1521 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1522 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1523 fetch_all_branches, &wanted_branches, &wanted_refs,
1524 list_refs_only, verbosity, fetchfd, repo,
1525 fetch_progress, &fpa);
1526 if (error)
1527 goto done;
1529 if (list_refs_only) {
1530 error = list_remote_refs(&symrefs, &refs);
1531 goto done;
1534 error = got_object_id_str(&id_str, pack_hash);
1535 if (error)
1536 goto done;
1537 if (verbosity >= 0)
1538 printf("\nFetched %s.pack\n", id_str);
1539 free(id_str);
1541 /* Set up references provided with the pack file. */
1542 TAILQ_FOREACH(pe, &refs, entry) {
1543 const char *refname = pe->path;
1544 struct got_object_id *id = pe->data;
1545 char *remote_refname;
1547 if (is_wanted_ref(&wanted_refs, refname) &&
1548 !mirror_references) {
1549 error = create_wanted_ref(refname, id,
1550 GOT_FETCH_DEFAULT_REMOTE_NAME,
1551 verbosity - 1, repo);
1552 if (error)
1553 goto done;
1554 continue;
1557 error = create_ref(refname, id, verbosity - 1, repo);
1558 if (error)
1559 goto done;
1561 if (mirror_references)
1562 continue;
1564 if (strncmp("refs/heads/", refname, 11) != 0)
1565 continue;
1567 if (asprintf(&remote_refname,
1568 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1569 refname + 11) == -1) {
1570 error = got_error_from_errno("asprintf");
1571 goto done;
1573 error = create_ref(remote_refname, id, verbosity - 1, repo);
1574 free(remote_refname);
1575 if (error)
1576 goto done;
1579 /* Set the HEAD reference if the server provided one. */
1580 TAILQ_FOREACH(pe, &symrefs, entry) {
1581 struct got_reference *target_ref;
1582 const char *refname = pe->path;
1583 const char *target = pe->data;
1584 char *remote_refname = NULL, *remote_target = NULL;
1586 if (strcmp(refname, GOT_REF_HEAD) != 0)
1587 continue;
1589 error = got_ref_open(&target_ref, repo, target, 0);
1590 if (error) {
1591 if (error->code == GOT_ERR_NOT_REF) {
1592 error = NULL;
1593 continue;
1595 goto done;
1598 error = create_symref(refname, target_ref, verbosity, repo);
1599 got_ref_close(target_ref);
1600 if (error)
1601 goto done;
1603 if (mirror_references)
1604 continue;
1606 if (strncmp("refs/heads/", target, 11) != 0)
1607 continue;
1609 if (asprintf(&remote_refname,
1610 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1611 refname) == -1) {
1612 error = got_error_from_errno("asprintf");
1613 goto done;
1615 if (asprintf(&remote_target,
1616 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1617 target + 11) == -1) {
1618 error = got_error_from_errno("asprintf");
1619 free(remote_refname);
1620 goto done;
1622 error = got_ref_open(&target_ref, repo, remote_target, 0);
1623 if (error) {
1624 free(remote_refname);
1625 free(remote_target);
1626 if (error->code == GOT_ERR_NOT_REF) {
1627 error = NULL;
1628 continue;
1630 goto done;
1632 error = create_symref(remote_refname, target_ref,
1633 verbosity - 1, repo);
1634 free(remote_refname);
1635 free(remote_target);
1636 got_ref_close(target_ref);
1637 if (error)
1638 goto done;
1640 if (pe == NULL) {
1642 * We failed to set the HEAD reference. If we asked for
1643 * a set of wanted branches use the first of one of those
1644 * which could be fetched instead.
1646 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1647 const char *target = pe->path;
1648 struct got_reference *target_ref;
1650 error = got_ref_open(&target_ref, repo, target, 0);
1651 if (error) {
1652 if (error->code == GOT_ERR_NOT_REF) {
1653 error = NULL;
1654 continue;
1656 goto done;
1659 error = create_symref(GOT_REF_HEAD, target_ref,
1660 verbosity, repo);
1661 got_ref_close(target_ref);
1662 if (error)
1663 goto done;
1664 break;
1668 if (verbosity >= 0)
1669 printf("Created %s repository '%s'\n",
1670 mirror_references ? "mirrored" : "cloned", repo_path);
1671 done:
1672 if (fetchpid > 0) {
1673 if (kill(fetchpid, SIGTERM) == -1)
1674 error = got_error_from_errno("kill");
1675 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1676 error = got_error_from_errno("waitpid");
1678 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1679 error = got_error_from_errno("close");
1680 if (repo)
1681 got_repo_close(repo);
1682 TAILQ_FOREACH(pe, &refs, entry) {
1683 free((void *)pe->path);
1684 free(pe->data);
1686 got_pathlist_free(&refs);
1687 TAILQ_FOREACH(pe, &symrefs, entry) {
1688 free((void *)pe->path);
1689 free(pe->data);
1691 got_pathlist_free(&symrefs);
1692 got_pathlist_free(&wanted_branches);
1693 got_pathlist_free(&wanted_refs);
1694 free(pack_hash);
1695 free(proto);
1696 free(host);
1697 free(port);
1698 free(server_path);
1699 free(repo_name);
1700 free(default_destdir);
1701 free(git_url);
1702 return error;
1705 static const struct got_error *
1706 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1707 int replace_tags, int verbosity, struct got_repository *repo)
1709 const struct got_error *err = NULL;
1710 char *new_id_str = NULL;
1711 struct got_object_id *old_id = NULL;
1713 err = got_object_id_str(&new_id_str, new_id);
1714 if (err)
1715 goto done;
1717 if (!replace_tags &&
1718 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1719 err = got_ref_resolve(&old_id, repo, ref);
1720 if (err)
1721 goto done;
1722 if (got_object_id_cmp(old_id, new_id) == 0)
1723 goto done;
1724 if (verbosity >= 0) {
1725 printf("Rejecting update of existing tag %s: %s\n",
1726 got_ref_get_name(ref), new_id_str);
1728 goto done;
1731 if (got_ref_is_symbolic(ref)) {
1732 if (verbosity >= 0) {
1733 printf("Replacing reference %s: %s\n",
1734 got_ref_get_name(ref),
1735 got_ref_get_symref_target(ref));
1737 err = got_ref_change_symref_to_ref(ref, new_id);
1738 if (err)
1739 goto done;
1740 err = got_ref_write(ref, repo);
1741 if (err)
1742 goto done;
1743 } else {
1744 err = got_ref_resolve(&old_id, repo, ref);
1745 if (err)
1746 goto done;
1747 if (got_object_id_cmp(old_id, new_id) == 0)
1748 goto done;
1750 err = got_ref_change_ref(ref, new_id);
1751 if (err)
1752 goto done;
1753 err = got_ref_write(ref, repo);
1754 if (err)
1755 goto done;
1758 if (verbosity >= 0)
1759 printf("Updated %s: %s\n", got_ref_get_name(ref),
1760 new_id_str);
1761 done:
1762 free(old_id);
1763 free(new_id_str);
1764 return err;
1767 static const struct got_error *
1768 update_symref(const char *refname, struct got_reference *target_ref,
1769 int verbosity, struct got_repository *repo)
1771 const struct got_error *err = NULL, *unlock_err;
1772 struct got_reference *symref;
1773 int symref_is_locked = 0;
1775 err = got_ref_open(&symref, repo, refname, 1);
1776 if (err) {
1777 if (err->code != GOT_ERR_NOT_REF)
1778 return err;
1779 err = got_ref_alloc_symref(&symref, refname, target_ref);
1780 if (err)
1781 goto done;
1783 err = got_ref_write(symref, repo);
1784 if (err)
1785 goto done;
1787 if (verbosity >= 0)
1788 printf("Created reference %s: %s\n",
1789 got_ref_get_name(symref),
1790 got_ref_get_symref_target(symref));
1791 } else {
1792 symref_is_locked = 1;
1794 if (strcmp(got_ref_get_symref_target(symref),
1795 got_ref_get_name(target_ref)) == 0)
1796 goto done;
1798 err = got_ref_change_symref(symref,
1799 got_ref_get_name(target_ref));
1800 if (err)
1801 goto done;
1803 err = got_ref_write(symref, repo);
1804 if (err)
1805 goto done;
1807 if (verbosity >= 0)
1808 printf("Updated %s: %s\n", got_ref_get_name(symref),
1809 got_ref_get_symref_target(symref));
1812 done:
1813 if (symref_is_locked) {
1814 unlock_err = got_ref_unlock(symref);
1815 if (unlock_err && err == NULL)
1816 err = unlock_err;
1818 got_ref_close(symref);
1819 return err;
1822 __dead static void
1823 usage_fetch(void)
1825 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1826 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1827 "[remote-repository-name]\n",
1828 getprogname());
1829 exit(1);
1832 static const struct got_error *
1833 delete_missing_ref(struct got_reference *ref,
1834 int verbosity, struct got_repository *repo)
1836 const struct got_error *err = NULL;
1837 struct got_object_id *id = NULL;
1838 char *id_str = NULL;
1840 if (got_ref_is_symbolic(ref)) {
1841 err = got_ref_delete(ref, repo);
1842 if (err)
1843 return err;
1844 if (verbosity >= 0) {
1845 printf("Deleted reference %s: %s\n",
1846 got_ref_get_name(ref),
1847 got_ref_get_symref_target(ref));
1849 } else {
1850 err = got_ref_resolve(&id, repo, ref);
1851 if (err)
1852 return err;
1853 err = got_object_id_str(&id_str, id);
1854 if (err)
1855 goto done;
1857 err = got_ref_delete(ref, repo);
1858 if (err)
1859 goto done;
1860 if (verbosity >= 0) {
1861 printf("Deleted reference %s: %s\n",
1862 got_ref_get_name(ref), id_str);
1865 done:
1866 free(id);
1867 free(id_str);
1868 return NULL;
1871 static const struct got_error *
1872 delete_missing_refs(struct got_pathlist_head *their_refs,
1873 struct got_pathlist_head *their_symrefs,
1874 const struct got_remote_repo *remote,
1875 int verbosity, struct got_repository *repo)
1877 const struct got_error *err = NULL, *unlock_err;
1878 struct got_reflist_head my_refs;
1879 struct got_reflist_entry *re;
1880 struct got_pathlist_entry *pe;
1881 char *remote_namespace = NULL;
1882 char *local_refname = NULL;
1884 SIMPLEQ_INIT(&my_refs);
1886 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
1887 == -1)
1888 return got_error_from_errno("asprintf");
1890 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1891 if (err)
1892 goto done;
1894 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1895 const char *refname = got_ref_get_name(re->ref);
1897 if (!remote->mirror_references) {
1898 if (strncmp(refname, remote_namespace,
1899 strlen(remote_namespace)) == 0) {
1900 if (strcmp(refname + strlen(remote_namespace),
1901 GOT_REF_HEAD) == 0)
1902 continue;
1903 if (asprintf(&local_refname, "refs/heads/%s",
1904 refname + strlen(remote_namespace)) == -1) {
1905 err = got_error_from_errno("asprintf");
1906 goto done;
1908 } else if (strncmp(refname, "refs/tags/", 10) != 0)
1909 continue;
1912 TAILQ_FOREACH(pe, their_refs, entry) {
1913 if (strcmp(local_refname, pe->path) == 0)
1914 break;
1916 if (pe != NULL)
1917 continue;
1919 TAILQ_FOREACH(pe, their_symrefs, entry) {
1920 if (strcmp(local_refname, pe->path) == 0)
1921 break;
1923 if (pe != NULL)
1924 continue;
1926 err = delete_missing_ref(re->ref, verbosity, repo);
1927 if (err)
1928 break;
1930 if (local_refname) {
1931 struct got_reference *ref;
1932 err = got_ref_open(&ref, repo, local_refname, 1);
1933 if (err) {
1934 if (err->code != GOT_ERR_NOT_REF)
1935 break;
1936 free(local_refname);
1937 local_refname = NULL;
1938 continue;
1940 err = delete_missing_ref(ref, verbosity, repo);
1941 if (err)
1942 break;
1943 unlock_err = got_ref_unlock(ref);
1944 got_ref_close(ref);
1945 if (unlock_err && err == NULL) {
1946 err = unlock_err;
1947 break;
1950 free(local_refname);
1951 local_refname = NULL;
1954 done:
1955 free(remote_namespace);
1956 free(local_refname);
1957 return err;
1960 static const struct got_error *
1961 update_wanted_ref(const char *refname, struct got_object_id *id,
1962 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1964 const struct got_error *err, *unlock_err;
1965 char *remote_refname;
1966 struct got_reference *ref;
1968 if (strncmp("refs/", refname, 5) == 0)
1969 refname += 5;
1971 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1972 remote_repo_name, refname) == -1)
1973 return got_error_from_errno("asprintf");
1975 err = got_ref_open(&ref, repo, remote_refname, 1);
1976 if (err) {
1977 if (err->code != GOT_ERR_NOT_REF)
1978 goto done;
1979 err = create_ref(remote_refname, id, verbosity, repo);
1980 } else {
1981 err = update_ref(ref, id, 0, verbosity, repo);
1982 unlock_err = got_ref_unlock(ref);
1983 if (unlock_err && err == NULL)
1984 err = unlock_err;
1985 got_ref_close(ref);
1987 done:
1988 free(remote_refname);
1989 return err;
1992 static const struct got_error *
1993 cmd_fetch(int argc, char *argv[])
1995 const struct got_error *error = NULL, *unlock_err;
1996 char *cwd = NULL, *repo_path = NULL;
1997 const char *remote_name;
1998 char *proto = NULL, *host = NULL, *port = NULL;
1999 char *repo_name = NULL, *server_path = NULL;
2000 const struct got_remote_repo *remotes, *remote = NULL;
2001 int nremotes;
2002 char *id_str = NULL;
2003 struct got_repository *repo = NULL;
2004 struct got_worktree *worktree = NULL;
2005 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2006 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2007 struct got_pathlist_entry *pe;
2008 struct got_object_id *pack_hash = NULL;
2009 int i, ch, fetchfd = -1, fetchstatus;
2010 pid_t fetchpid = -1;
2011 struct got_fetch_progress_arg fpa;
2012 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2013 int delete_refs = 0, replace_tags = 0;
2015 TAILQ_INIT(&refs);
2016 TAILQ_INIT(&symrefs);
2017 TAILQ_INIT(&wanted_branches);
2018 TAILQ_INIT(&wanted_refs);
2020 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
2021 switch (ch) {
2022 case 'a':
2023 fetch_all_branches = 1;
2024 break;
2025 case 'b':
2026 error = got_pathlist_append(&wanted_branches,
2027 optarg, NULL);
2028 if (error)
2029 return error;
2030 break;
2031 case 'd':
2032 delete_refs = 1;
2033 break;
2034 case 'l':
2035 list_refs_only = 1;
2036 break;
2037 case 'r':
2038 repo_path = realpath(optarg, NULL);
2039 if (repo_path == NULL)
2040 return got_error_from_errno2("realpath",
2041 optarg);
2042 got_path_strip_trailing_slashes(repo_path);
2043 break;
2044 case 't':
2045 replace_tags = 1;
2046 break;
2047 case 'v':
2048 if (verbosity < 0)
2049 verbosity = 0;
2050 else if (verbosity < 3)
2051 verbosity++;
2052 break;
2053 case 'q':
2054 verbosity = -1;
2055 break;
2056 case 'R':
2057 error = got_pathlist_append(&wanted_refs,
2058 optarg, NULL);
2059 if (error)
2060 return error;
2061 break;
2062 default:
2063 usage_fetch();
2064 break;
2067 argc -= optind;
2068 argv += optind;
2070 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2071 option_conflict('a', 'b');
2072 if (list_refs_only) {
2073 if (!TAILQ_EMPTY(&wanted_branches))
2074 option_conflict('l', 'b');
2075 if (fetch_all_branches)
2076 option_conflict('l', 'a');
2077 if (delete_refs)
2078 option_conflict('l', 'd');
2079 if (verbosity == -1)
2080 option_conflict('l', 'q');
2083 if (argc == 0)
2084 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2085 else if (argc == 1)
2086 remote_name = argv[0];
2087 else
2088 usage_fetch();
2090 cwd = getcwd(NULL, 0);
2091 if (cwd == NULL) {
2092 error = got_error_from_errno("getcwd");
2093 goto done;
2096 if (repo_path == NULL) {
2097 error = got_worktree_open(&worktree, cwd);
2098 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2099 goto done;
2100 else
2101 error = NULL;
2102 if (worktree) {
2103 repo_path =
2104 strdup(got_worktree_get_repo_path(worktree));
2105 if (repo_path == NULL)
2106 error = got_error_from_errno("strdup");
2107 if (error)
2108 goto done;
2109 } else {
2110 repo_path = strdup(cwd);
2111 if (repo_path == NULL) {
2112 error = got_error_from_errno("strdup");
2113 goto done;
2118 error = got_repo_open(&repo, repo_path, NULL);
2119 if (error)
2120 goto done;
2122 if (worktree) {
2123 worktree_conf = got_worktree_get_gotconfig(worktree);
2124 if (worktree_conf) {
2125 got_gotconfig_get_remotes(&nremotes, &remotes,
2126 worktree_conf);
2127 for (i = 0; i < nremotes; i++) {
2128 if (strcmp(remotes[i].name, remote_name) == 0) {
2129 remote = &remotes[i];
2130 break;
2135 if (remote == NULL) {
2136 repo_conf = got_repo_get_gotconfig(repo);
2137 if (repo_conf) {
2138 got_gotconfig_get_remotes(&nremotes, &remotes,
2139 repo_conf);
2140 for (i = 0; i < nremotes; i++) {
2141 if (strcmp(remotes[i].name, remote_name) == 0) {
2142 remote = &remotes[i];
2143 break;
2148 if (remote == NULL) {
2149 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2150 for (i = 0; i < nremotes; i++) {
2151 if (strcmp(remotes[i].name, remote_name) == 0) {
2152 remote = &remotes[i];
2153 break;
2157 if (remote == NULL) {
2158 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2159 goto done;
2162 if (TAILQ_EMPTY(&wanted_branches) && remote->nbranches > 0) {
2163 for (i = 0; i < remote->nbranches; i++) {
2164 got_pathlist_append(&wanted_branches,
2165 remote->branches[i], NULL);
2170 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
2171 &repo_name, remote->url);
2172 if (error)
2173 goto done;
2175 if (strcmp(proto, "git") == 0) {
2176 #ifndef PROFILE
2177 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2178 "sendfd dns inet unveil", NULL) == -1)
2179 err(1, "pledge");
2180 #endif
2181 } else if (strcmp(proto, "git+ssh") == 0 ||
2182 strcmp(proto, "ssh") == 0) {
2183 #ifndef PROFILE
2184 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2185 "sendfd unveil", NULL) == -1)
2186 err(1, "pledge");
2187 #endif
2188 } else if (strcmp(proto, "http") == 0 ||
2189 strcmp(proto, "git+http") == 0) {
2190 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2191 goto done;
2192 } else {
2193 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2194 goto done;
2197 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
2198 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
2199 error = got_error_from_errno2("unveil",
2200 GOT_FETCH_PATH_SSH);
2201 goto done;
2204 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2205 if (error)
2206 goto done;
2208 if (verbosity >= 0)
2209 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2210 port ? ":" : "", port ? port : "");
2212 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2213 server_path, verbosity);
2214 if (error)
2215 goto done;
2217 fpa.last_scaled_size[0] = '\0';
2218 fpa.last_p_indexed = -1;
2219 fpa.last_p_resolved = -1;
2220 fpa.verbosity = verbosity;
2221 fpa.repo = repo;
2222 fpa.create_configs = 0;
2223 fpa.configs_created = 0;
2224 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2225 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2226 remote->mirror_references, fetch_all_branches, &wanted_branches,
2227 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2228 fetch_progress, &fpa);
2229 if (error)
2230 goto done;
2232 if (list_refs_only) {
2233 error = list_remote_refs(&symrefs, &refs);
2234 goto done;
2237 if (pack_hash == NULL) {
2238 if (verbosity >= 0)
2239 printf("Already up-to-date\n");
2240 } else if (verbosity >= 0) {
2241 error = got_object_id_str(&id_str, pack_hash);
2242 if (error)
2243 goto done;
2244 printf("\nFetched %s.pack\n", id_str);
2245 free(id_str);
2246 id_str = NULL;
2249 /* Update references provided with the pack file. */
2250 TAILQ_FOREACH(pe, &refs, entry) {
2251 const char *refname = pe->path;
2252 struct got_object_id *id = pe->data;
2253 struct got_reference *ref;
2254 char *remote_refname;
2256 if (is_wanted_ref(&wanted_refs, refname) &&
2257 !remote->mirror_references) {
2258 error = update_wanted_ref(refname, id,
2259 remote->name, verbosity, repo);
2260 if (error)
2261 goto done;
2262 continue;
2265 if (remote->mirror_references ||
2266 strncmp("refs/tags/", refname, 10) == 0) {
2267 error = got_ref_open(&ref, repo, refname, 1);
2268 if (error) {
2269 if (error->code != GOT_ERR_NOT_REF)
2270 goto done;
2271 error = create_ref(refname, id, verbosity,
2272 repo);
2273 if (error)
2274 goto done;
2275 } else {
2276 error = update_ref(ref, id, replace_tags,
2277 verbosity, repo);
2278 unlock_err = got_ref_unlock(ref);
2279 if (unlock_err && error == NULL)
2280 error = unlock_err;
2281 got_ref_close(ref);
2282 if (error)
2283 goto done;
2285 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2286 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2287 remote_name, refname + 11) == -1) {
2288 error = got_error_from_errno("asprintf");
2289 goto done;
2292 error = got_ref_open(&ref, repo, remote_refname, 1);
2293 if (error) {
2294 if (error->code != GOT_ERR_NOT_REF)
2295 goto done;
2296 error = create_ref(remote_refname, id,
2297 verbosity, repo);
2298 if (error)
2299 goto done;
2300 } else {
2301 error = update_ref(ref, id, replace_tags,
2302 verbosity, repo);
2303 unlock_err = got_ref_unlock(ref);
2304 if (unlock_err && error == NULL)
2305 error = unlock_err;
2306 got_ref_close(ref);
2307 if (error)
2308 goto done;
2311 /* Also create a local branch if none exists yet. */
2312 error = got_ref_open(&ref, repo, refname, 1);
2313 if (error) {
2314 if (error->code != GOT_ERR_NOT_REF)
2315 goto done;
2316 error = create_ref(refname, id, verbosity,
2317 repo);
2318 if (error)
2319 goto done;
2320 } else {
2321 unlock_err = got_ref_unlock(ref);
2322 if (unlock_err && error == NULL)
2323 error = unlock_err;
2324 got_ref_close(ref);
2328 if (delete_refs) {
2329 error = delete_missing_refs(&refs, &symrefs, remote,
2330 verbosity, repo);
2331 if (error)
2332 goto done;
2335 if (!remote->mirror_references) {
2336 /* Update remote HEAD reference if the server provided one. */
2337 TAILQ_FOREACH(pe, &symrefs, entry) {
2338 struct got_reference *target_ref;
2339 const char *refname = pe->path;
2340 const char *target = pe->data;
2341 char *remote_refname = NULL, *remote_target = NULL;
2343 if (strcmp(refname, GOT_REF_HEAD) != 0)
2344 continue;
2346 if (strncmp("refs/heads/", target, 11) != 0)
2347 continue;
2349 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2350 remote->name, refname) == -1) {
2351 error = got_error_from_errno("asprintf");
2352 goto done;
2354 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2355 remote->name, target + 11) == -1) {
2356 error = got_error_from_errno("asprintf");
2357 free(remote_refname);
2358 goto done;
2361 error = got_ref_open(&target_ref, repo, remote_target,
2362 0);
2363 if (error) {
2364 free(remote_refname);
2365 free(remote_target);
2366 if (error->code == GOT_ERR_NOT_REF) {
2367 error = NULL;
2368 continue;
2370 goto done;
2372 error = update_symref(remote_refname, target_ref,
2373 verbosity, repo);
2374 free(remote_refname);
2375 free(remote_target);
2376 got_ref_close(target_ref);
2377 if (error)
2378 goto done;
2381 done:
2382 if (fetchpid > 0) {
2383 if (kill(fetchpid, SIGTERM) == -1)
2384 error = got_error_from_errno("kill");
2385 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2386 error = got_error_from_errno("waitpid");
2388 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2389 error = got_error_from_errno("close");
2390 if (repo)
2391 got_repo_close(repo);
2392 if (worktree)
2393 got_worktree_close(worktree);
2394 TAILQ_FOREACH(pe, &refs, entry) {
2395 free((void *)pe->path);
2396 free(pe->data);
2398 got_pathlist_free(&refs);
2399 TAILQ_FOREACH(pe, &symrefs, entry) {
2400 free((void *)pe->path);
2401 free(pe->data);
2403 got_pathlist_free(&symrefs);
2404 got_pathlist_free(&wanted_branches);
2405 got_pathlist_free(&wanted_refs);
2406 free(id_str);
2407 free(cwd);
2408 free(repo_path);
2409 free(pack_hash);
2410 free(proto);
2411 free(host);
2412 free(port);
2413 free(server_path);
2414 free(repo_name);
2415 return error;
2419 __dead static void
2420 usage_checkout(void)
2422 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2423 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2424 exit(1);
2427 static void
2428 show_worktree_base_ref_warning(void)
2430 fprintf(stderr, "%s: warning: could not create a reference "
2431 "to the work tree's base commit; the commit could be "
2432 "garbage-collected by Git; making the repository "
2433 "writable and running 'got update' will prevent this\n",
2434 getprogname());
2437 struct got_checkout_progress_arg {
2438 const char *worktree_path;
2439 int had_base_commit_ref_error;
2442 static const struct got_error *
2443 checkout_progress(void *arg, unsigned char status, const char *path)
2445 struct got_checkout_progress_arg *a = arg;
2447 /* Base commit bump happens silently. */
2448 if (status == GOT_STATUS_BUMP_BASE)
2449 return NULL;
2451 if (status == GOT_STATUS_BASE_REF_ERR) {
2452 a->had_base_commit_ref_error = 1;
2453 return NULL;
2456 while (path[0] == '/')
2457 path++;
2459 printf("%c %s/%s\n", status, a->worktree_path, path);
2460 return NULL;
2463 static const struct got_error *
2464 check_cancelled(void *arg)
2466 if (sigint_received || sigpipe_received)
2467 return got_error(GOT_ERR_CANCELLED);
2468 return NULL;
2471 static const struct got_error *
2472 check_linear_ancestry(struct got_object_id *commit_id,
2473 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2474 struct got_repository *repo)
2476 const struct got_error *err = NULL;
2477 struct got_object_id *yca_id;
2479 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2480 commit_id, base_commit_id, repo, check_cancelled, NULL);
2481 if (err)
2482 return err;
2484 if (yca_id == NULL)
2485 return got_error(GOT_ERR_ANCESTRY);
2488 * Require a straight line of history between the target commit
2489 * and the work tree's base commit.
2491 * Non-linear situations such as this require a rebase:
2493 * (commit) D F (base_commit)
2494 * \ /
2495 * C E
2496 * \ /
2497 * B (yca)
2498 * |
2499 * A
2501 * 'got update' only handles linear cases:
2502 * Update forwards in time: A (base/yca) - B - C - D (commit)
2503 * Update backwards in time: D (base) - C - B - A (commit/yca)
2505 if (allow_forwards_in_time_only) {
2506 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2507 return got_error(GOT_ERR_ANCESTRY);
2508 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2509 got_object_id_cmp(base_commit_id, yca_id) != 0)
2510 return got_error(GOT_ERR_ANCESTRY);
2512 free(yca_id);
2513 return NULL;
2516 static const struct got_error *
2517 check_same_branch(struct got_object_id *commit_id,
2518 struct got_reference *head_ref, struct got_object_id *yca_id,
2519 struct got_repository *repo)
2521 const struct got_error *err = NULL;
2522 struct got_commit_graph *graph = NULL;
2523 struct got_object_id *head_commit_id = NULL;
2524 int is_same_branch = 0;
2526 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2527 if (err)
2528 goto done;
2530 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2531 is_same_branch = 1;
2532 goto done;
2534 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2535 is_same_branch = 1;
2536 goto done;
2539 err = got_commit_graph_open(&graph, "/", 1);
2540 if (err)
2541 goto done;
2543 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2544 check_cancelled, NULL);
2545 if (err)
2546 goto done;
2548 for (;;) {
2549 struct got_object_id *id;
2550 err = got_commit_graph_iter_next(&id, graph, repo,
2551 check_cancelled, NULL);
2552 if (err) {
2553 if (err->code == GOT_ERR_ITER_COMPLETED)
2554 err = NULL;
2555 break;
2558 if (id) {
2559 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2560 break;
2561 if (got_object_id_cmp(id, commit_id) == 0) {
2562 is_same_branch = 1;
2563 break;
2567 done:
2568 if (graph)
2569 got_commit_graph_close(graph);
2570 free(head_commit_id);
2571 if (!err && !is_same_branch)
2572 err = got_error(GOT_ERR_ANCESTRY);
2573 return err;
2576 static const struct got_error *
2577 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2579 static char msg[512];
2580 const char *branch_name;
2582 if (got_ref_is_symbolic(ref))
2583 branch_name = got_ref_get_symref_target(ref);
2584 else
2585 branch_name = got_ref_get_name(ref);
2587 if (strncmp("refs/heads/", branch_name, 11) == 0)
2588 branch_name += 11;
2590 snprintf(msg, sizeof(msg),
2591 "target commit is not contained in branch '%s'; "
2592 "the branch to use must be specified with -b; "
2593 "if necessary a new branch can be created for "
2594 "this commit with 'got branch -c %s BRANCH_NAME'",
2595 branch_name, commit_id_str);
2597 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2600 static const struct got_error *
2601 cmd_checkout(int argc, char *argv[])
2603 const struct got_error *error = NULL;
2604 struct got_repository *repo = NULL;
2605 struct got_reference *head_ref = NULL;
2606 struct got_worktree *worktree = NULL;
2607 char *repo_path = NULL;
2608 char *worktree_path = NULL;
2609 const char *path_prefix = "";
2610 const char *branch_name = GOT_REF_HEAD;
2611 char *commit_id_str = NULL;
2612 char *cwd = NULL;
2613 int ch, same_path_prefix, allow_nonempty = 0;
2614 struct got_pathlist_head paths;
2615 struct got_checkout_progress_arg cpa;
2617 TAILQ_INIT(&paths);
2619 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2620 switch (ch) {
2621 case 'b':
2622 branch_name = optarg;
2623 break;
2624 case 'c':
2625 commit_id_str = strdup(optarg);
2626 if (commit_id_str == NULL)
2627 return got_error_from_errno("strdup");
2628 break;
2629 case 'E':
2630 allow_nonempty = 1;
2631 break;
2632 case 'p':
2633 path_prefix = optarg;
2634 break;
2635 default:
2636 usage_checkout();
2637 /* NOTREACHED */
2641 argc -= optind;
2642 argv += optind;
2644 #ifndef PROFILE
2645 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2646 "unveil", NULL) == -1)
2647 err(1, "pledge");
2648 #endif
2649 if (argc == 1) {
2650 char *base, *dotgit;
2651 const char *path;
2652 repo_path = realpath(argv[0], NULL);
2653 if (repo_path == NULL)
2654 return got_error_from_errno2("realpath", argv[0]);
2655 cwd = getcwd(NULL, 0);
2656 if (cwd == NULL) {
2657 error = got_error_from_errno("getcwd");
2658 goto done;
2660 if (path_prefix[0])
2661 path = path_prefix;
2662 else
2663 path = repo_path;
2664 error = got_path_basename(&base, path);
2665 if (error)
2666 goto done;
2667 dotgit = strstr(base, ".git");
2668 if (dotgit)
2669 *dotgit = '\0';
2670 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2671 error = got_error_from_errno("asprintf");
2672 free(base);
2673 goto done;
2675 free(base);
2676 } else if (argc == 2) {
2677 repo_path = realpath(argv[0], NULL);
2678 if (repo_path == NULL) {
2679 error = got_error_from_errno2("realpath", argv[0]);
2680 goto done;
2682 worktree_path = realpath(argv[1], NULL);
2683 if (worktree_path == NULL) {
2684 if (errno != ENOENT) {
2685 error = got_error_from_errno2("realpath",
2686 argv[1]);
2687 goto done;
2689 worktree_path = strdup(argv[1]);
2690 if (worktree_path == NULL) {
2691 error = got_error_from_errno("strdup");
2692 goto done;
2695 } else
2696 usage_checkout();
2698 got_path_strip_trailing_slashes(repo_path);
2699 got_path_strip_trailing_slashes(worktree_path);
2701 error = got_repo_open(&repo, repo_path, NULL);
2702 if (error != NULL)
2703 goto done;
2705 /* Pre-create work tree path for unveil(2) */
2706 error = got_path_mkdir(worktree_path);
2707 if (error) {
2708 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2709 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2710 goto done;
2711 if (!allow_nonempty &&
2712 !got_path_dir_is_empty(worktree_path)) {
2713 error = got_error_path(worktree_path,
2714 GOT_ERR_DIR_NOT_EMPTY);
2715 goto done;
2719 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2720 if (error)
2721 goto done;
2723 error = got_ref_open(&head_ref, repo, branch_name, 0);
2724 if (error != NULL)
2725 goto done;
2727 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2728 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2729 goto done;
2731 error = got_worktree_open(&worktree, worktree_path);
2732 if (error != NULL)
2733 goto done;
2735 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2736 path_prefix);
2737 if (error != NULL)
2738 goto done;
2739 if (!same_path_prefix) {
2740 error = got_error(GOT_ERR_PATH_PREFIX);
2741 goto done;
2744 if (commit_id_str) {
2745 struct got_object_id *commit_id;
2746 error = got_repo_match_object_id(&commit_id, NULL,
2747 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2748 if (error)
2749 goto done;
2750 error = check_linear_ancestry(commit_id,
2751 got_worktree_get_base_commit_id(worktree), 0, repo);
2752 if (error != NULL) {
2753 free(commit_id);
2754 if (error->code == GOT_ERR_ANCESTRY) {
2755 error = checkout_ancestry_error(
2756 head_ref, commit_id_str);
2758 goto done;
2760 error = check_same_branch(commit_id, head_ref, NULL, repo);
2761 if (error) {
2762 if (error->code == GOT_ERR_ANCESTRY) {
2763 error = checkout_ancestry_error(
2764 head_ref, commit_id_str);
2766 goto done;
2768 error = got_worktree_set_base_commit_id(worktree, repo,
2769 commit_id);
2770 free(commit_id);
2771 if (error)
2772 goto done;
2775 error = got_pathlist_append(&paths, "", NULL);
2776 if (error)
2777 goto done;
2778 cpa.worktree_path = worktree_path;
2779 cpa.had_base_commit_ref_error = 0;
2780 error = got_worktree_checkout_files(worktree, &paths, repo,
2781 checkout_progress, &cpa, check_cancelled, NULL);
2782 if (error != NULL)
2783 goto done;
2785 printf("Now shut up and hack\n");
2786 if (cpa.had_base_commit_ref_error)
2787 show_worktree_base_ref_warning();
2788 done:
2789 got_pathlist_free(&paths);
2790 free(commit_id_str);
2791 free(repo_path);
2792 free(worktree_path);
2793 free(cwd);
2794 return error;
2797 struct got_update_progress_arg {
2798 int did_something;
2799 int conflicts;
2800 int obstructed;
2801 int not_updated;
2804 void
2805 print_update_progress_stats(struct got_update_progress_arg *upa)
2807 if (!upa->did_something)
2808 return;
2810 if (upa->conflicts > 0)
2811 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2812 if (upa->obstructed > 0)
2813 printf("File paths obstructed by a non-regular file: %d\n",
2814 upa->obstructed);
2815 if (upa->not_updated > 0)
2816 printf("Files not updated because of existing merge "
2817 "conflicts: %d\n", upa->not_updated);
2820 __dead static void
2821 usage_update(void)
2823 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2824 getprogname());
2825 exit(1);
2828 static const struct got_error *
2829 update_progress(void *arg, unsigned char status, const char *path)
2831 struct got_update_progress_arg *upa = arg;
2833 if (status == GOT_STATUS_EXISTS ||
2834 status == GOT_STATUS_BASE_REF_ERR)
2835 return NULL;
2837 upa->did_something = 1;
2839 /* Base commit bump happens silently. */
2840 if (status == GOT_STATUS_BUMP_BASE)
2841 return NULL;
2843 if (status == GOT_STATUS_CONFLICT)
2844 upa->conflicts++;
2845 if (status == GOT_STATUS_OBSTRUCTED)
2846 upa->obstructed++;
2847 if (status == GOT_STATUS_CANNOT_UPDATE)
2848 upa->not_updated++;
2850 while (path[0] == '/')
2851 path++;
2852 printf("%c %s\n", status, path);
2853 return NULL;
2856 static const struct got_error *
2857 switch_head_ref(struct got_reference *head_ref,
2858 struct got_object_id *commit_id, struct got_worktree *worktree,
2859 struct got_repository *repo)
2861 const struct got_error *err = NULL;
2862 char *base_id_str;
2863 int ref_has_moved = 0;
2865 /* Trivial case: switching between two different references. */
2866 if (strcmp(got_ref_get_name(head_ref),
2867 got_worktree_get_head_ref_name(worktree)) != 0) {
2868 printf("Switching work tree from %s to %s\n",
2869 got_worktree_get_head_ref_name(worktree),
2870 got_ref_get_name(head_ref));
2871 return got_worktree_set_head_ref(worktree, head_ref);
2874 err = check_linear_ancestry(commit_id,
2875 got_worktree_get_base_commit_id(worktree), 0, repo);
2876 if (err) {
2877 if (err->code != GOT_ERR_ANCESTRY)
2878 return err;
2879 ref_has_moved = 1;
2881 if (!ref_has_moved)
2882 return NULL;
2884 /* Switching to a rebased branch with the same reference name. */
2885 err = got_object_id_str(&base_id_str,
2886 got_worktree_get_base_commit_id(worktree));
2887 if (err)
2888 return err;
2889 printf("Reference %s now points at a different branch\n",
2890 got_worktree_get_head_ref_name(worktree));
2891 printf("Switching work tree from %s to %s\n", base_id_str,
2892 got_worktree_get_head_ref_name(worktree));
2893 return NULL;
2896 static const struct got_error *
2897 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2899 const struct got_error *err;
2900 int in_progress;
2902 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2903 if (err)
2904 return err;
2905 if (in_progress)
2906 return got_error(GOT_ERR_REBASING);
2908 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2909 if (err)
2910 return err;
2911 if (in_progress)
2912 return got_error(GOT_ERR_HISTEDIT_BUSY);
2914 return NULL;
2917 static const struct got_error *
2918 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2919 char *argv[], struct got_worktree *worktree)
2921 const struct got_error *err = NULL;
2922 char *path;
2923 int i;
2925 if (argc == 0) {
2926 path = strdup("");
2927 if (path == NULL)
2928 return got_error_from_errno("strdup");
2929 return got_pathlist_append(paths, path, NULL);
2932 for (i = 0; i < argc; i++) {
2933 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2934 if (err)
2935 break;
2936 err = got_pathlist_append(paths, path, NULL);
2937 if (err) {
2938 free(path);
2939 break;
2943 return err;
2946 static const struct got_error *
2947 wrap_not_worktree_error(const struct got_error *orig_err,
2948 const char *cmdname, const char *path)
2950 const struct got_error *err;
2951 struct got_repository *repo;
2952 static char msg[512];
2954 err = got_repo_open(&repo, path, NULL);
2955 if (err)
2956 return orig_err;
2958 snprintf(msg, sizeof(msg),
2959 "'got %s' needs a work tree in addition to a git repository\n"
2960 "Work trees can be checked out from this Git repository with "
2961 "'got checkout'.\n"
2962 "The got(1) manual page contains more information.", cmdname);
2963 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2964 got_repo_close(repo);
2965 return err;
2968 static const struct got_error *
2969 cmd_update(int argc, char *argv[])
2971 const struct got_error *error = NULL;
2972 struct got_repository *repo = NULL;
2973 struct got_worktree *worktree = NULL;
2974 char *worktree_path = NULL;
2975 struct got_object_id *commit_id = NULL;
2976 char *commit_id_str = NULL;
2977 const char *branch_name = NULL;
2978 struct got_reference *head_ref = NULL;
2979 struct got_pathlist_head paths;
2980 struct got_pathlist_entry *pe;
2981 int ch;
2982 struct got_update_progress_arg upa;
2984 TAILQ_INIT(&paths);
2986 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2987 switch (ch) {
2988 case 'b':
2989 branch_name = optarg;
2990 break;
2991 case 'c':
2992 commit_id_str = strdup(optarg);
2993 if (commit_id_str == NULL)
2994 return got_error_from_errno("strdup");
2995 break;
2996 default:
2997 usage_update();
2998 /* NOTREACHED */
3002 argc -= optind;
3003 argv += optind;
3005 #ifndef PROFILE
3006 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3007 "unveil", NULL) == -1)
3008 err(1, "pledge");
3009 #endif
3010 worktree_path = getcwd(NULL, 0);
3011 if (worktree_path == NULL) {
3012 error = got_error_from_errno("getcwd");
3013 goto done;
3015 error = got_worktree_open(&worktree, worktree_path);
3016 if (error) {
3017 if (error->code == GOT_ERR_NOT_WORKTREE)
3018 error = wrap_not_worktree_error(error, "update",
3019 worktree_path);
3020 goto done;
3023 error = check_rebase_or_histedit_in_progress(worktree);
3024 if (error)
3025 goto done;
3027 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3028 NULL);
3029 if (error != NULL)
3030 goto done;
3032 error = apply_unveil(got_repo_get_path(repo), 0,
3033 got_worktree_get_root_path(worktree));
3034 if (error)
3035 goto done;
3037 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3038 if (error)
3039 goto done;
3041 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3042 got_worktree_get_head_ref_name(worktree), 0);
3043 if (error != NULL)
3044 goto done;
3045 if (commit_id_str == NULL) {
3046 error = got_ref_resolve(&commit_id, repo, head_ref);
3047 if (error != NULL)
3048 goto done;
3049 error = got_object_id_str(&commit_id_str, commit_id);
3050 if (error != NULL)
3051 goto done;
3052 } else {
3053 error = got_repo_match_object_id(&commit_id, NULL,
3054 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
3055 free(commit_id_str);
3056 commit_id_str = NULL;
3057 if (error)
3058 goto done;
3059 error = got_object_id_str(&commit_id_str, commit_id);
3060 if (error)
3061 goto done;
3064 if (branch_name) {
3065 struct got_object_id *head_commit_id;
3066 TAILQ_FOREACH(pe, &paths, entry) {
3067 if (pe->path_len == 0)
3068 continue;
3069 error = got_error_msg(GOT_ERR_BAD_PATH,
3070 "switching between branches requires that "
3071 "the entire work tree gets updated");
3072 goto done;
3074 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3075 if (error)
3076 goto done;
3077 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3078 repo);
3079 free(head_commit_id);
3080 if (error != NULL)
3081 goto done;
3082 error = check_same_branch(commit_id, head_ref, NULL, repo);
3083 if (error)
3084 goto done;
3085 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3086 if (error)
3087 goto done;
3088 } else {
3089 error = check_linear_ancestry(commit_id,
3090 got_worktree_get_base_commit_id(worktree), 0, repo);
3091 if (error != NULL) {
3092 if (error->code == GOT_ERR_ANCESTRY)
3093 error = got_error(GOT_ERR_BRANCH_MOVED);
3094 goto done;
3096 error = check_same_branch(commit_id, head_ref, NULL, repo);
3097 if (error)
3098 goto done;
3101 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3102 commit_id) != 0) {
3103 error = got_worktree_set_base_commit_id(worktree, repo,
3104 commit_id);
3105 if (error)
3106 goto done;
3109 memset(&upa, 0, sizeof(upa));
3110 error = got_worktree_checkout_files(worktree, &paths, repo,
3111 update_progress, &upa, check_cancelled, NULL);
3112 if (error != NULL)
3113 goto done;
3115 if (upa.did_something)
3116 printf("Updated to commit %s\n", commit_id_str);
3117 else
3118 printf("Already up-to-date\n");
3119 print_update_progress_stats(&upa);
3120 done:
3121 free(worktree_path);
3122 TAILQ_FOREACH(pe, &paths, entry)
3123 free((char *)pe->path);
3124 got_pathlist_free(&paths);
3125 free(commit_id);
3126 free(commit_id_str);
3127 return error;
3130 static const struct got_error *
3131 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3132 const char *path, int diff_context, int ignore_whitespace,
3133 int force_text_diff, struct got_repository *repo)
3135 const struct got_error *err = NULL;
3136 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3138 if (blob_id1) {
3139 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3140 if (err)
3141 goto done;
3144 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3145 if (err)
3146 goto done;
3148 while (path[0] == '/')
3149 path++;
3150 err = got_diff_blob(NULL, NULL, blob1, blob2, path, path,
3151 diff_context, ignore_whitespace, force_text_diff, stdout);
3152 done:
3153 if (blob1)
3154 got_object_blob_close(blob1);
3155 got_object_blob_close(blob2);
3156 return err;
3159 static const struct got_error *
3160 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3161 const char *path, int diff_context, int ignore_whitespace,
3162 int force_text_diff, struct got_repository *repo)
3164 const struct got_error *err = NULL;
3165 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3166 struct got_diff_blob_output_unidiff_arg arg;
3168 if (tree_id1) {
3169 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3170 if (err)
3171 goto done;
3174 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3175 if (err)
3176 goto done;
3178 arg.diff_context = diff_context;
3179 arg.ignore_whitespace = ignore_whitespace;
3180 arg.force_text_diff = force_text_diff;
3181 arg.outfile = stdout;
3182 arg.line_offsets = NULL;
3183 arg.nlines = 0;
3184 while (path[0] == '/')
3185 path++;
3186 err = got_diff_tree(tree1, tree2, path, path, repo,
3187 got_diff_blob_output_unidiff, &arg, 1);
3188 done:
3189 if (tree1)
3190 got_object_tree_close(tree1);
3191 if (tree2)
3192 got_object_tree_close(tree2);
3193 return err;
3196 static const struct got_error *
3197 get_changed_paths(struct got_pathlist_head *paths,
3198 struct got_commit_object *commit, struct got_repository *repo)
3200 const struct got_error *err = NULL;
3201 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3202 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3203 struct got_object_qid *qid;
3205 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3206 if (qid != NULL) {
3207 struct got_commit_object *pcommit;
3208 err = got_object_open_as_commit(&pcommit, repo,
3209 qid->id);
3210 if (err)
3211 return err;
3213 tree_id1 = got_object_commit_get_tree_id(pcommit);
3214 got_object_commit_close(pcommit);
3218 if (tree_id1) {
3219 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3220 if (err)
3221 goto done;
3224 tree_id2 = got_object_commit_get_tree_id(commit);
3225 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3226 if (err)
3227 goto done;
3229 err = got_diff_tree(tree1, tree2, "", "", repo,
3230 got_diff_tree_collect_changed_paths, paths, 0);
3231 done:
3232 if (tree1)
3233 got_object_tree_close(tree1);
3234 if (tree2)
3235 got_object_tree_close(tree2);
3236 return err;
3239 static const struct got_error *
3240 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3241 const char *path, int diff_context, struct got_repository *repo)
3243 const struct got_error *err = NULL;
3244 struct got_commit_object *pcommit = NULL;
3245 char *id_str1 = NULL, *id_str2 = NULL;
3246 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3247 struct got_object_qid *qid;
3249 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3250 if (qid != NULL) {
3251 err = got_object_open_as_commit(&pcommit, repo,
3252 qid->id);
3253 if (err)
3254 return err;
3257 if (path && path[0] != '\0') {
3258 int obj_type;
3259 err = got_object_id_by_path(&obj_id2, repo, id, path);
3260 if (err)
3261 goto done;
3262 err = got_object_id_str(&id_str2, obj_id2);
3263 if (err) {
3264 free(obj_id2);
3265 goto done;
3267 if (pcommit) {
3268 err = got_object_id_by_path(&obj_id1, repo,
3269 qid->id, path);
3270 if (err) {
3271 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3272 free(obj_id2);
3273 goto done;
3275 } else {
3276 err = got_object_id_str(&id_str1, obj_id1);
3277 if (err) {
3278 free(obj_id2);
3279 goto done;
3283 err = got_object_get_type(&obj_type, repo, obj_id2);
3284 if (err) {
3285 free(obj_id2);
3286 goto done;
3288 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3289 switch (obj_type) {
3290 case GOT_OBJ_TYPE_BLOB:
3291 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3292 0, 0, repo);
3293 break;
3294 case GOT_OBJ_TYPE_TREE:
3295 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3296 0, 0, repo);
3297 break;
3298 default:
3299 err = got_error(GOT_ERR_OBJ_TYPE);
3300 break;
3302 free(obj_id1);
3303 free(obj_id2);
3304 } else {
3305 obj_id2 = got_object_commit_get_tree_id(commit);
3306 err = got_object_id_str(&id_str2, obj_id2);
3307 if (err)
3308 goto done;
3309 if (pcommit) {
3310 obj_id1 = got_object_commit_get_tree_id(pcommit);
3311 err = got_object_id_str(&id_str1, obj_id1);
3312 if (err)
3313 goto done;
3315 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null",
3316 id_str2);
3317 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3318 repo);
3320 done:
3321 free(id_str1);
3322 free(id_str2);
3323 if (pcommit)
3324 got_object_commit_close(pcommit);
3325 return err;
3328 static char *
3329 get_datestr(time_t *time, char *datebuf)
3331 struct tm mytm, *tm;
3332 char *p, *s;
3334 tm = gmtime_r(time, &mytm);
3335 if (tm == NULL)
3336 return NULL;
3337 s = asctime_r(tm, datebuf);
3338 if (s == NULL)
3339 return NULL;
3340 p = strchr(s, '\n');
3341 if (p)
3342 *p = '\0';
3343 return s;
3346 static const struct got_error *
3347 match_logmsg(int *have_match, struct got_object_id *id,
3348 struct got_commit_object *commit, regex_t *regex)
3350 const struct got_error *err = NULL;
3351 regmatch_t regmatch;
3352 char *id_str = NULL, *logmsg = NULL;
3354 *have_match = 0;
3356 err = got_object_id_str(&id_str, id);
3357 if (err)
3358 return err;
3360 err = got_object_commit_get_logmsg(&logmsg, commit);
3361 if (err)
3362 goto done;
3364 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3365 *have_match = 1;
3366 done:
3367 free(id_str);
3368 free(logmsg);
3369 return err;
3372 static void
3373 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3374 regex_t *regex)
3376 regmatch_t regmatch;
3377 struct got_pathlist_entry *pe;
3379 *have_match = 0;
3381 TAILQ_FOREACH(pe, changed_paths, entry) {
3382 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3383 *have_match = 1;
3384 break;
3389 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3391 static const struct got_error *
3392 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3393 struct got_repository *repo, const char *path,
3394 struct got_pathlist_head *changed_paths, int show_patch,
3395 int diff_context, struct got_reflist_head *refs)
3397 const struct got_error *err = NULL;
3398 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3399 char datebuf[26];
3400 time_t committer_time;
3401 const char *author, *committer;
3402 char *refs_str = NULL;
3403 struct got_reflist_entry *re;
3405 SIMPLEQ_FOREACH(re, refs, entry) {
3406 char *s;
3407 const char *name;
3408 struct got_tag_object *tag = NULL;
3409 struct got_object_id *ref_id;
3410 int cmp;
3412 name = got_ref_get_name(re->ref);
3413 if (strcmp(name, GOT_REF_HEAD) == 0)
3414 continue;
3415 if (strncmp(name, "refs/", 5) == 0)
3416 name += 5;
3417 if (strncmp(name, "got/", 4) == 0)
3418 continue;
3419 if (strncmp(name, "heads/", 6) == 0)
3420 name += 6;
3421 if (strncmp(name, "remotes/", 8) == 0) {
3422 name += 8;
3423 s = strstr(name, "/" GOT_REF_HEAD);
3424 if (s != NULL && s[strlen(s)] == '\0')
3425 continue;
3427 err = got_ref_resolve(&ref_id, repo, re->ref);
3428 if (err)
3429 return err;
3430 if (strncmp(name, "tags/", 5) == 0) {
3431 err = got_object_open_as_tag(&tag, repo, ref_id);
3432 if (err) {
3433 if (err->code != GOT_ERR_OBJ_TYPE) {
3434 free(ref_id);
3435 return err;
3437 /* Ref points at something other than a tag. */
3438 err = NULL;
3439 tag = NULL;
3442 cmp = got_object_id_cmp(tag ?
3443 got_object_tag_get_object_id(tag) : ref_id, id);
3444 free(ref_id);
3445 if (tag)
3446 got_object_tag_close(tag);
3447 if (cmp != 0)
3448 continue;
3449 s = refs_str;
3450 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3451 name) == -1) {
3452 err = got_error_from_errno("asprintf");
3453 free(s);
3454 return err;
3456 free(s);
3458 err = got_object_id_str(&id_str, id);
3459 if (err)
3460 return err;
3462 printf(GOT_COMMIT_SEP_STR);
3463 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3464 refs_str ? refs_str : "", refs_str ? ")" : "");
3465 free(id_str);
3466 id_str = NULL;
3467 free(refs_str);
3468 refs_str = NULL;
3469 printf("from: %s\n", got_object_commit_get_author(commit));
3470 committer_time = got_object_commit_get_committer_time(commit);
3471 datestr = get_datestr(&committer_time, datebuf);
3472 if (datestr)
3473 printf("date: %s UTC\n", datestr);
3474 author = got_object_commit_get_author(commit);
3475 committer = got_object_commit_get_committer(commit);
3476 if (strcmp(author, committer) != 0)
3477 printf("via: %s\n", committer);
3478 if (got_object_commit_get_nparents(commit) > 1) {
3479 const struct got_object_id_queue *parent_ids;
3480 struct got_object_qid *qid;
3481 int n = 1;
3482 parent_ids = got_object_commit_get_parent_ids(commit);
3483 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3484 err = got_object_id_str(&id_str, qid->id);
3485 if (err)
3486 return err;
3487 printf("parent %d: %s\n", n++, id_str);
3488 free(id_str);
3492 err = got_object_commit_get_logmsg(&logmsg0, commit);
3493 if (err)
3494 return err;
3496 logmsg = logmsg0;
3497 do {
3498 line = strsep(&logmsg, "\n");
3499 if (line)
3500 printf(" %s\n", line);
3501 } while (line);
3502 free(logmsg0);
3504 if (changed_paths) {
3505 struct got_pathlist_entry *pe;
3506 TAILQ_FOREACH(pe, changed_paths, entry) {
3507 struct got_diff_changed_path *cp = pe->data;
3508 printf(" %c %s\n", cp->status, pe->path);
3510 printf("\n");
3512 if (show_patch) {
3513 err = print_patch(commit, id, path, diff_context, repo);
3514 if (err == 0)
3515 printf("\n");
3518 if (fflush(stdout) != 0 && err == NULL)
3519 err = got_error_from_errno("fflush");
3520 return err;
3523 static const struct got_error *
3524 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3525 struct got_repository *repo, const char *path, int show_changed_paths,
3526 int show_patch, const char *search_pattern, int diff_context, int limit,
3527 int log_branches, int reverse_display_order, struct got_reflist_head *refs)
3529 const struct got_error *err;
3530 struct got_commit_graph *graph;
3531 regex_t regex;
3532 int have_match;
3533 struct got_object_id_queue reversed_commits;
3534 struct got_object_qid *qid;
3535 struct got_commit_object *commit;
3536 struct got_pathlist_head changed_paths;
3537 struct got_pathlist_entry *pe;
3539 SIMPLEQ_INIT(&reversed_commits);
3540 TAILQ_INIT(&changed_paths);
3542 if (search_pattern && regcomp(&regex, search_pattern,
3543 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3544 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3546 err = got_commit_graph_open(&graph, path, !log_branches);
3547 if (err)
3548 return err;
3549 err = got_commit_graph_iter_start(graph, root_id, repo,
3550 check_cancelled, NULL);
3551 if (err)
3552 goto done;
3553 for (;;) {
3554 struct got_object_id *id;
3556 if (sigint_received || sigpipe_received)
3557 break;
3559 err = got_commit_graph_iter_next(&id, graph, repo,
3560 check_cancelled, NULL);
3561 if (err) {
3562 if (err->code == GOT_ERR_ITER_COMPLETED)
3563 err = NULL;
3564 break;
3566 if (id == NULL)
3567 break;
3569 err = got_object_open_as_commit(&commit, repo, id);
3570 if (err)
3571 break;
3573 if (show_changed_paths && !reverse_display_order) {
3574 err = get_changed_paths(&changed_paths, commit, repo);
3575 if (err)
3576 break;
3579 if (search_pattern) {
3580 err = match_logmsg(&have_match, id, commit, &regex);
3581 if (err) {
3582 got_object_commit_close(commit);
3583 break;
3585 if (have_match == 0 && show_changed_paths)
3586 match_changed_paths(&have_match,
3587 &changed_paths, &regex);
3588 if (have_match == 0) {
3589 got_object_commit_close(commit);
3590 TAILQ_FOREACH(pe, &changed_paths, entry) {
3591 free((char *)pe->path);
3592 free(pe->data);
3594 got_pathlist_free(&changed_paths);
3595 continue;
3599 if (reverse_display_order) {
3600 err = got_object_qid_alloc(&qid, id);
3601 if (err)
3602 break;
3603 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3604 got_object_commit_close(commit);
3605 } else {
3606 err = print_commit(commit, id, repo, path,
3607 show_changed_paths ? &changed_paths : NULL,
3608 show_patch, diff_context, refs);
3609 got_object_commit_close(commit);
3610 if (err)
3611 break;
3613 if ((limit && --limit == 0) ||
3614 (end_id && got_object_id_cmp(id, end_id) == 0))
3615 break;
3617 TAILQ_FOREACH(pe, &changed_paths, entry) {
3618 free((char *)pe->path);
3619 free(pe->data);
3621 got_pathlist_free(&changed_paths);
3623 if (reverse_display_order) {
3624 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3625 err = got_object_open_as_commit(&commit, repo, qid->id);
3626 if (err)
3627 break;
3628 if (show_changed_paths) {
3629 err = get_changed_paths(&changed_paths,
3630 commit, repo);
3631 if (err)
3632 break;
3634 err = print_commit(commit, qid->id, repo, path,
3635 show_changed_paths ? &changed_paths : NULL,
3636 show_patch, diff_context, refs);
3637 got_object_commit_close(commit);
3638 if (err)
3639 break;
3640 TAILQ_FOREACH(pe, &changed_paths, entry) {
3641 free((char *)pe->path);
3642 free(pe->data);
3644 got_pathlist_free(&changed_paths);
3647 done:
3648 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3649 qid = SIMPLEQ_FIRST(&reversed_commits);
3650 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3651 got_object_qid_free(qid);
3653 TAILQ_FOREACH(pe, &changed_paths, entry) {
3654 free((char *)pe->path);
3655 free(pe->data);
3657 got_pathlist_free(&changed_paths);
3658 if (search_pattern)
3659 regfree(&regex);
3660 got_commit_graph_close(graph);
3661 return err;
3664 __dead static void
3665 usage_log(void)
3667 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3668 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3669 "[-R] [path]\n", getprogname());
3670 exit(1);
3673 static int
3674 get_default_log_limit(void)
3676 const char *got_default_log_limit;
3677 long long n;
3678 const char *errstr;
3680 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3681 if (got_default_log_limit == NULL)
3682 return 0;
3683 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3684 if (errstr != NULL)
3685 return 0;
3686 return n;
3689 static const struct got_error *
3690 cmd_log(int argc, char *argv[])
3692 const struct got_error *error;
3693 struct got_repository *repo = NULL;
3694 struct got_worktree *worktree = NULL;
3695 struct got_object_id *start_id = NULL, *end_id = NULL;
3696 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3697 const char *start_commit = NULL, *end_commit = NULL;
3698 const char *search_pattern = NULL;
3699 int diff_context = -1, ch;
3700 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3701 int reverse_display_order = 0;
3702 const char *errstr;
3703 struct got_reflist_head refs;
3705 SIMPLEQ_INIT(&refs);
3707 #ifndef PROFILE
3708 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3709 NULL)
3710 == -1)
3711 err(1, "pledge");
3712 #endif
3714 limit = get_default_log_limit();
3716 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3717 switch (ch) {
3718 case 'p':
3719 show_patch = 1;
3720 break;
3721 case 'P':
3722 show_changed_paths = 1;
3723 break;
3724 case 'c':
3725 start_commit = optarg;
3726 break;
3727 case 'C':
3728 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3729 &errstr);
3730 if (errstr != NULL)
3731 err(1, "-C option %s", errstr);
3732 break;
3733 case 'l':
3734 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3735 if (errstr != NULL)
3736 err(1, "-l option %s", errstr);
3737 break;
3738 case 'b':
3739 log_branches = 1;
3740 break;
3741 case 'r':
3742 repo_path = realpath(optarg, NULL);
3743 if (repo_path == NULL)
3744 return got_error_from_errno2("realpath",
3745 optarg);
3746 got_path_strip_trailing_slashes(repo_path);
3747 break;
3748 case 'R':
3749 reverse_display_order = 1;
3750 break;
3751 case 's':
3752 search_pattern = optarg;
3753 break;
3754 case 'x':
3755 end_commit = optarg;
3756 break;
3757 default:
3758 usage_log();
3759 /* NOTREACHED */
3763 argc -= optind;
3764 argv += optind;
3766 if (diff_context == -1)
3767 diff_context = 3;
3768 else if (!show_patch)
3769 errx(1, "-C requires -p");
3771 cwd = getcwd(NULL, 0);
3772 if (cwd == NULL) {
3773 error = got_error_from_errno("getcwd");
3774 goto done;
3777 if (repo_path == NULL) {
3778 error = got_worktree_open(&worktree, cwd);
3779 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3780 goto done;
3781 error = NULL;
3784 if (argc == 1) {
3785 if (worktree) {
3786 error = got_worktree_resolve_path(&path, worktree,
3787 argv[0]);
3788 if (error)
3789 goto done;
3790 } else {
3791 path = strdup(argv[0]);
3792 if (path == NULL) {
3793 error = got_error_from_errno("strdup");
3794 goto done;
3797 } else if (argc != 0)
3798 usage_log();
3800 if (repo_path == NULL) {
3801 repo_path = worktree ?
3802 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3804 if (repo_path == NULL) {
3805 error = got_error_from_errno("strdup");
3806 goto done;
3809 error = got_repo_open(&repo, repo_path, NULL);
3810 if (error != NULL)
3811 goto done;
3813 error = apply_unveil(got_repo_get_path(repo), 1,
3814 worktree ? got_worktree_get_root_path(worktree) : NULL);
3815 if (error)
3816 goto done;
3818 if (start_commit == NULL) {
3819 struct got_reference *head_ref;
3820 struct got_commit_object *commit = NULL;
3821 error = got_ref_open(&head_ref, repo,
3822 worktree ? got_worktree_get_head_ref_name(worktree)
3823 : GOT_REF_HEAD, 0);
3824 if (error != NULL)
3825 goto done;
3826 error = got_ref_resolve(&start_id, repo, head_ref);
3827 got_ref_close(head_ref);
3828 if (error != NULL)
3829 goto done;
3830 error = got_object_open_as_commit(&commit, repo,
3831 start_id);
3832 if (error != NULL)
3833 goto done;
3834 got_object_commit_close(commit);
3835 } else {
3836 error = got_repo_match_object_id(&start_id, NULL,
3837 start_commit, GOT_OBJ_TYPE_COMMIT, 1, repo);
3838 if (error != NULL)
3839 goto done;
3841 if (end_commit != NULL) {
3842 error = got_repo_match_object_id(&end_id, NULL,
3843 end_commit, GOT_OBJ_TYPE_COMMIT, 1, repo);
3844 if (error != NULL)
3845 goto done;
3848 if (worktree) {
3850 * If a path was specified on the command line it was resolved
3851 * to a path in the work tree above. Prepend the work tree's
3852 * path prefix to obtain the corresponding in-repository path.
3854 if (path) {
3855 const char *prefix;
3856 prefix = got_worktree_get_path_prefix(worktree);
3857 if (asprintf(&in_repo_path, "%s%s%s", prefix,
3858 (path[0] != '\0') ? "/" : "", path) == -1) {
3859 error = got_error_from_errno("asprintf");
3860 goto done;
3863 } else
3864 error = got_repo_map_path(&in_repo_path, repo,
3865 path ? path : "");
3866 if (error != NULL)
3867 goto done;
3868 if (in_repo_path) {
3869 free(path);
3870 path = in_repo_path;
3873 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3874 if (error)
3875 goto done;
3877 error = print_commits(start_id, end_id, repo, path ? path : "",
3878 show_changed_paths, show_patch, search_pattern, diff_context,
3879 limit, log_branches, reverse_display_order, &refs);
3880 done:
3881 free(path);
3882 free(repo_path);
3883 free(cwd);
3884 if (worktree)
3885 got_worktree_close(worktree);
3886 if (repo) {
3887 const struct got_error *repo_error;
3888 repo_error = got_repo_close(repo);
3889 if (error == NULL)
3890 error = repo_error;
3892 got_ref_list_free(&refs);
3893 return error;
3896 __dead static void
3897 usage_diff(void)
3899 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
3900 "[-s] [-w] [object1 object2 | path]\n", getprogname());
3901 exit(1);
3904 struct print_diff_arg {
3905 struct got_repository *repo;
3906 struct got_worktree *worktree;
3907 int diff_context;
3908 const char *id_str;
3909 int header_shown;
3910 int diff_staged;
3911 int ignore_whitespace;
3912 int force_text_diff;
3916 * Create a file which contains the target path of a symlink so we can feed
3917 * it as content to the diff engine.
3919 static const struct got_error *
3920 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
3921 const char *abspath)
3923 const struct got_error *err = NULL;
3924 char target_path[PATH_MAX];
3925 ssize_t target_len, outlen;
3927 *fd = -1;
3929 if (dirfd != -1) {
3930 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
3931 if (target_len == -1)
3932 return got_error_from_errno2("readlinkat", abspath);
3933 } else {
3934 target_len = readlink(abspath, target_path, PATH_MAX);
3935 if (target_len == -1)
3936 return got_error_from_errno2("readlink", abspath);
3939 *fd = got_opentempfd();
3940 if (*fd == -1)
3941 return got_error_from_errno("got_opentempfd");
3943 outlen = write(*fd, target_path, target_len);
3944 if (outlen == -1) {
3945 err = got_error_from_errno("got_opentempfd");
3946 goto done;
3949 if (lseek(*fd, 0, SEEK_SET) == -1) {
3950 err = got_error_from_errno2("lseek", abspath);
3951 goto done;
3953 done:
3954 if (err) {
3955 close(*fd);
3956 *fd = -1;
3958 return err;
3961 static const struct got_error *
3962 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3963 const char *path, struct got_object_id *blob_id,
3964 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3965 int dirfd, const char *de_name)
3967 struct print_diff_arg *a = arg;
3968 const struct got_error *err = NULL;
3969 struct got_blob_object *blob1 = NULL;
3970 int fd = -1;
3971 FILE *f2 = NULL;
3972 char *abspath = NULL, *label1 = NULL;
3973 struct stat sb;
3975 if (a->diff_staged) {
3976 if (staged_status != GOT_STATUS_MODIFY &&
3977 staged_status != GOT_STATUS_ADD &&
3978 staged_status != GOT_STATUS_DELETE)
3979 return NULL;
3980 } else {
3981 if (staged_status == GOT_STATUS_DELETE)
3982 return NULL;
3983 if (status == GOT_STATUS_NONEXISTENT)
3984 return got_error_set_errno(ENOENT, path);
3985 if (status != GOT_STATUS_MODIFY &&
3986 status != GOT_STATUS_ADD &&
3987 status != GOT_STATUS_DELETE &&
3988 status != GOT_STATUS_CONFLICT)
3989 return NULL;
3992 if (!a->header_shown) {
3993 printf("diff %s %s%s\n", a->id_str,
3994 got_worktree_get_root_path(a->worktree),
3995 a->diff_staged ? " (staged changes)" : "");
3996 a->header_shown = 1;
3999 if (a->diff_staged) {
4000 const char *label1 = NULL, *label2 = NULL;
4001 switch (staged_status) {
4002 case GOT_STATUS_MODIFY:
4003 label1 = path;
4004 label2 = path;
4005 break;
4006 case GOT_STATUS_ADD:
4007 label2 = path;
4008 break;
4009 case GOT_STATUS_DELETE:
4010 label1 = path;
4011 break;
4012 default:
4013 return got_error(GOT_ERR_FILE_STATUS);
4015 return got_diff_objects_as_blobs(NULL, NULL, blob_id,
4016 staged_blob_id, label1, label2, a->diff_context,
4017 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4020 if (staged_status == GOT_STATUS_ADD ||
4021 staged_status == GOT_STATUS_MODIFY) {
4022 char *id_str;
4023 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4024 8192);
4025 if (err)
4026 goto done;
4027 err = got_object_id_str(&id_str, staged_blob_id);
4028 if (err)
4029 goto done;
4030 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4031 err = got_error_from_errno("asprintf");
4032 free(id_str);
4033 goto done;
4035 free(id_str);
4036 } else if (status != GOT_STATUS_ADD) {
4037 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4038 if (err)
4039 goto done;
4042 if (status != GOT_STATUS_DELETE) {
4043 if (asprintf(&abspath, "%s/%s",
4044 got_worktree_get_root_path(a->worktree), path) == -1) {
4045 err = got_error_from_errno("asprintf");
4046 goto done;
4049 if (dirfd != -1) {
4050 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
4051 if (fd == -1) {
4052 if (errno != ELOOP) {
4053 err = got_error_from_errno2("openat",
4054 abspath);
4055 goto done;
4057 err = get_symlink_target_file(&fd, dirfd,
4058 de_name, abspath);
4059 if (err)
4060 goto done;
4062 } else {
4063 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
4064 if (fd == -1) {
4065 if (errno != ELOOP) {
4066 err = got_error_from_errno2("open",
4067 abspath);
4068 goto done;
4070 err = get_symlink_target_file(&fd, dirfd,
4071 de_name, abspath);
4072 if (err)
4073 goto done;
4076 if (fstat(fd, &sb) == -1) {
4077 err = got_error_from_errno2("fstat", abspath);
4078 goto done;
4080 f2 = fdopen(fd, "r");
4081 if (f2 == NULL) {
4082 err = got_error_from_errno2("fdopen", abspath);
4083 goto done;
4085 fd = -1;
4086 } else
4087 sb.st_size = 0;
4089 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4090 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4091 done:
4092 if (blob1)
4093 got_object_blob_close(blob1);
4094 if (f2 && fclose(f2) == EOF && err == NULL)
4095 err = got_error_from_errno("fclose");
4096 if (fd != -1 && close(fd) == -1 && err == NULL)
4097 err = got_error_from_errno("close");
4098 free(abspath);
4099 return err;
4102 static const struct got_error *
4103 cmd_diff(int argc, char *argv[])
4105 const struct got_error *error;
4106 struct got_repository *repo = NULL;
4107 struct got_worktree *worktree = NULL;
4108 char *cwd = NULL, *repo_path = NULL;
4109 struct got_object_id *id1 = NULL, *id2 = NULL;
4110 const char *id_str1 = NULL, *id_str2 = NULL;
4111 char *label1 = NULL, *label2 = NULL;
4112 int type1, type2;
4113 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
4114 int force_text_diff = 0;
4115 const char *errstr;
4116 char *path = NULL;
4118 #ifndef PROFILE
4119 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4120 NULL) == -1)
4121 err(1, "pledge");
4122 #endif
4124 while ((ch = getopt(argc, argv, "aC:r:sw")) != -1) {
4125 switch (ch) {
4126 case 'a':
4127 force_text_diff = 1;
4128 break;
4129 case 'C':
4130 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4131 &errstr);
4132 if (errstr != NULL)
4133 err(1, "-C option %s", errstr);
4134 break;
4135 case 'r':
4136 repo_path = realpath(optarg, NULL);
4137 if (repo_path == NULL)
4138 return got_error_from_errno2("realpath",
4139 optarg);
4140 got_path_strip_trailing_slashes(repo_path);
4141 break;
4142 case 's':
4143 diff_staged = 1;
4144 break;
4145 case 'w':
4146 ignore_whitespace = 1;
4147 break;
4148 default:
4149 usage_diff();
4150 /* NOTREACHED */
4154 argc -= optind;
4155 argv += optind;
4157 cwd = getcwd(NULL, 0);
4158 if (cwd == NULL) {
4159 error = got_error_from_errno("getcwd");
4160 goto done;
4162 if (argc <= 1) {
4163 if (repo_path)
4164 errx(1,
4165 "-r option can't be used when diffing a work tree");
4166 error = got_worktree_open(&worktree, cwd);
4167 if (error) {
4168 if (error->code == GOT_ERR_NOT_WORKTREE)
4169 error = wrap_not_worktree_error(error, "diff",
4170 cwd);
4171 goto done;
4173 repo_path = strdup(got_worktree_get_repo_path(worktree));
4174 if (repo_path == NULL) {
4175 error = got_error_from_errno("strdup");
4176 goto done;
4178 if (argc == 1) {
4179 error = got_worktree_resolve_path(&path, worktree,
4180 argv[0]);
4181 if (error)
4182 goto done;
4183 } else {
4184 path = strdup("");
4185 if (path == NULL) {
4186 error = got_error_from_errno("strdup");
4187 goto done;
4190 } else if (argc == 2) {
4191 if (diff_staged)
4192 errx(1, "-s option can't be used when diffing "
4193 "objects in repository");
4194 id_str1 = argv[0];
4195 id_str2 = argv[1];
4196 if (repo_path == NULL) {
4197 error = got_worktree_open(&worktree, cwd);
4198 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4199 goto done;
4200 if (worktree) {
4201 repo_path = strdup(
4202 got_worktree_get_repo_path(worktree));
4203 if (repo_path == NULL) {
4204 error = got_error_from_errno("strdup");
4205 goto done;
4207 } else {
4208 repo_path = strdup(cwd);
4209 if (repo_path == NULL) {
4210 error = got_error_from_errno("strdup");
4211 goto done;
4215 } else
4216 usage_diff();
4218 error = got_repo_open(&repo, repo_path, NULL);
4219 free(repo_path);
4220 if (error != NULL)
4221 goto done;
4223 error = apply_unveil(got_repo_get_path(repo), 1,
4224 worktree ? got_worktree_get_root_path(worktree) : NULL);
4225 if (error)
4226 goto done;
4228 if (argc <= 1) {
4229 struct print_diff_arg arg;
4230 struct got_pathlist_head paths;
4231 char *id_str;
4233 TAILQ_INIT(&paths);
4235 error = got_object_id_str(&id_str,
4236 got_worktree_get_base_commit_id(worktree));
4237 if (error)
4238 goto done;
4239 arg.repo = repo;
4240 arg.worktree = worktree;
4241 arg.diff_context = diff_context;
4242 arg.id_str = id_str;
4243 arg.header_shown = 0;
4244 arg.diff_staged = diff_staged;
4245 arg.ignore_whitespace = ignore_whitespace;
4246 arg.force_text_diff = force_text_diff;
4248 error = got_pathlist_append(&paths, path, NULL);
4249 if (error)
4250 goto done;
4252 error = got_worktree_status(worktree, &paths, repo, print_diff,
4253 &arg, check_cancelled, NULL);
4254 free(id_str);
4255 got_pathlist_free(&paths);
4256 goto done;
4259 error = got_repo_match_object_id(&id1, &label1, id_str1,
4260 GOT_OBJ_TYPE_ANY, 1, repo);
4261 if (error)
4262 goto done;
4264 error = got_repo_match_object_id(&id2, &label2, id_str2,
4265 GOT_OBJ_TYPE_ANY, 1, repo);
4266 if (error)
4267 goto done;
4269 error = got_object_get_type(&type1, repo, id1);
4270 if (error)
4271 goto done;
4273 error = got_object_get_type(&type2, repo, id2);
4274 if (error)
4275 goto done;
4277 if (type1 != type2) {
4278 error = got_error(GOT_ERR_OBJ_TYPE);
4279 goto done;
4282 switch (type1) {
4283 case GOT_OBJ_TYPE_BLOB:
4284 error = got_diff_objects_as_blobs(NULL, NULL, id1, id2,
4285 NULL, NULL, diff_context, ignore_whitespace,
4286 force_text_diff, repo, stdout);
4287 break;
4288 case GOT_OBJ_TYPE_TREE:
4289 error = got_diff_objects_as_trees(NULL, NULL, id1, id2,
4290 "", "", diff_context, ignore_whitespace, force_text_diff,
4291 repo, stdout);
4292 break;
4293 case GOT_OBJ_TYPE_COMMIT:
4294 printf("diff %s %s\n", label1, label2);
4295 error = got_diff_objects_as_commits(NULL, NULL, id1, id2,
4296 diff_context, ignore_whitespace, force_text_diff, repo,
4297 stdout);
4298 break;
4299 default:
4300 error = got_error(GOT_ERR_OBJ_TYPE);
4302 done:
4303 free(label1);
4304 free(label2);
4305 free(id1);
4306 free(id2);
4307 free(path);
4308 if (worktree)
4309 got_worktree_close(worktree);
4310 if (repo) {
4311 const struct got_error *repo_error;
4312 repo_error = got_repo_close(repo);
4313 if (error == NULL)
4314 error = repo_error;
4316 return error;
4319 __dead static void
4320 usage_blame(void)
4322 fprintf(stderr,
4323 "usage: %s blame [-c commit] [-r repository-path] path\n",
4324 getprogname());
4325 exit(1);
4328 struct blame_line {
4329 int annotated;
4330 char *id_str;
4331 char *committer;
4332 char datebuf[11]; /* YYYY-MM-DD + NUL */
4335 struct blame_cb_args {
4336 struct blame_line *lines;
4337 int nlines;
4338 int nlines_prec;
4339 int lineno_cur;
4340 off_t *line_offsets;
4341 FILE *f;
4342 struct got_repository *repo;
4345 static const struct got_error *
4346 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4348 const struct got_error *err = NULL;
4349 struct blame_cb_args *a = arg;
4350 struct blame_line *bline;
4351 char *line = NULL;
4352 size_t linesize = 0;
4353 struct got_commit_object *commit = NULL;
4354 off_t offset;
4355 struct tm tm;
4356 time_t committer_time;
4358 if (nlines != a->nlines ||
4359 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4360 return got_error(GOT_ERR_RANGE);
4362 if (sigint_received)
4363 return got_error(GOT_ERR_ITER_COMPLETED);
4365 if (lineno == -1)
4366 return NULL; /* no change in this commit */
4368 /* Annotate this line. */
4369 bline = &a->lines[lineno - 1];
4370 if (bline->annotated)
4371 return NULL;
4372 err = got_object_id_str(&bline->id_str, id);
4373 if (err)
4374 return err;
4376 err = got_object_open_as_commit(&commit, a->repo, id);
4377 if (err)
4378 goto done;
4380 bline->committer = strdup(got_object_commit_get_committer(commit));
4381 if (bline->committer == NULL) {
4382 err = got_error_from_errno("strdup");
4383 goto done;
4386 committer_time = got_object_commit_get_committer_time(commit);
4387 if (localtime_r(&committer_time, &tm) == NULL)
4388 return got_error_from_errno("localtime_r");
4389 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4390 &tm) >= sizeof(bline->datebuf)) {
4391 err = got_error(GOT_ERR_NO_SPACE);
4392 goto done;
4394 bline->annotated = 1;
4396 /* Print lines annotated so far. */
4397 bline = &a->lines[a->lineno_cur - 1];
4398 if (!bline->annotated)
4399 goto done;
4401 offset = a->line_offsets[a->lineno_cur - 1];
4402 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4403 err = got_error_from_errno("fseeko");
4404 goto done;
4407 while (bline->annotated) {
4408 char *smallerthan, *at, *nl, *committer;
4409 size_t len;
4411 if (getline(&line, &linesize, a->f) == -1) {
4412 if (ferror(a->f))
4413 err = got_error_from_errno("getline");
4414 break;
4417 committer = bline->committer;
4418 smallerthan = strchr(committer, '<');
4419 if (smallerthan && smallerthan[1] != '\0')
4420 committer = smallerthan + 1;
4421 at = strchr(committer, '@');
4422 if (at)
4423 *at = '\0';
4424 len = strlen(committer);
4425 if (len >= 9)
4426 committer[8] = '\0';
4428 nl = strchr(line, '\n');
4429 if (nl)
4430 *nl = '\0';
4431 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4432 bline->id_str, bline->datebuf, committer, line);
4434 a->lineno_cur++;
4435 bline = &a->lines[a->lineno_cur - 1];
4437 done:
4438 if (commit)
4439 got_object_commit_close(commit);
4440 free(line);
4441 return err;
4444 static const struct got_error *
4445 cmd_blame(int argc, char *argv[])
4447 const struct got_error *error;
4448 struct got_repository *repo = NULL;
4449 struct got_worktree *worktree = NULL;
4450 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4451 char *link_target = NULL;
4452 struct got_object_id *obj_id = NULL;
4453 struct got_object_id *commit_id = NULL;
4454 struct got_blob_object *blob = NULL;
4455 char *commit_id_str = NULL;
4456 struct blame_cb_args bca;
4457 int ch, obj_type, i;
4458 off_t filesize;
4460 memset(&bca, 0, sizeof(bca));
4462 #ifndef PROFILE
4463 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4464 NULL) == -1)
4465 err(1, "pledge");
4466 #endif
4468 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4469 switch (ch) {
4470 case 'c':
4471 commit_id_str = optarg;
4472 break;
4473 case 'r':
4474 repo_path = realpath(optarg, NULL);
4475 if (repo_path == NULL)
4476 return got_error_from_errno2("realpath",
4477 optarg);
4478 got_path_strip_trailing_slashes(repo_path);
4479 break;
4480 default:
4481 usage_blame();
4482 /* NOTREACHED */
4486 argc -= optind;
4487 argv += optind;
4489 if (argc == 1)
4490 path = argv[0];
4491 else
4492 usage_blame();
4494 cwd = getcwd(NULL, 0);
4495 if (cwd == NULL) {
4496 error = got_error_from_errno("getcwd");
4497 goto done;
4499 if (repo_path == NULL) {
4500 error = got_worktree_open(&worktree, cwd);
4501 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4502 goto done;
4503 else
4504 error = NULL;
4505 if (worktree) {
4506 repo_path =
4507 strdup(got_worktree_get_repo_path(worktree));
4508 if (repo_path == NULL) {
4509 error = got_error_from_errno("strdup");
4510 if (error)
4511 goto done;
4513 } else {
4514 repo_path = strdup(cwd);
4515 if (repo_path == NULL) {
4516 error = got_error_from_errno("strdup");
4517 goto done;
4522 error = got_repo_open(&repo, repo_path, NULL);
4523 if (error != NULL)
4524 goto done;
4526 if (worktree) {
4527 const char *prefix = got_worktree_get_path_prefix(worktree);
4528 char *p;
4530 error = got_worktree_resolve_path(&p, worktree, path);
4531 if (error)
4532 goto done;
4533 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4534 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4535 p) == -1) {
4536 error = got_error_from_errno("asprintf");
4537 free(p);
4538 goto done;
4540 free(p);
4541 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4542 } else {
4543 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4544 if (error)
4545 goto done;
4546 error = got_repo_map_path(&in_repo_path, repo, path);
4548 if (error)
4549 goto done;
4551 if (commit_id_str == NULL) {
4552 struct got_reference *head_ref;
4553 error = got_ref_open(&head_ref, repo, worktree ?
4554 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4555 if (error != NULL)
4556 goto done;
4557 error = got_ref_resolve(&commit_id, repo, head_ref);
4558 got_ref_close(head_ref);
4559 if (error != NULL)
4560 goto done;
4561 } else {
4562 error = got_repo_match_object_id(&commit_id, NULL,
4563 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4564 if (error)
4565 goto done;
4568 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4569 commit_id, repo);
4570 if (error)
4571 goto done;
4573 error = got_object_id_by_path(&obj_id, repo, commit_id,
4574 link_target ? link_target : in_repo_path);
4575 if (error)
4576 goto done;
4578 error = got_object_get_type(&obj_type, repo, obj_id);
4579 if (error)
4580 goto done;
4582 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4583 error = got_error_path(link_target ? link_target : in_repo_path,
4584 GOT_ERR_OBJ_TYPE);
4585 goto done;
4588 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4589 if (error)
4590 goto done;
4591 bca.f = got_opentemp();
4592 if (bca.f == NULL) {
4593 error = got_error_from_errno("got_opentemp");
4594 goto done;
4596 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4597 &bca.line_offsets, bca.f, blob);
4598 if (error || bca.nlines == 0)
4599 goto done;
4601 /* Don't include \n at EOF in the blame line count. */
4602 if (bca.line_offsets[bca.nlines - 1] == filesize)
4603 bca.nlines--;
4605 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4606 if (bca.lines == NULL) {
4607 error = got_error_from_errno("calloc");
4608 goto done;
4610 bca.lineno_cur = 1;
4611 bca.nlines_prec = 0;
4612 i = bca.nlines;
4613 while (i > 0) {
4614 i /= 10;
4615 bca.nlines_prec++;
4617 bca.repo = repo;
4619 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4620 repo, blame_cb, &bca, check_cancelled, NULL);
4621 done:
4622 free(in_repo_path);
4623 free(link_target);
4624 free(repo_path);
4625 free(cwd);
4626 free(commit_id);
4627 free(obj_id);
4628 if (blob)
4629 got_object_blob_close(blob);
4630 if (worktree)
4631 got_worktree_close(worktree);
4632 if (repo) {
4633 const struct got_error *repo_error;
4634 repo_error = got_repo_close(repo);
4635 if (error == NULL)
4636 error = repo_error;
4638 if (bca.lines) {
4639 for (i = 0; i < bca.nlines; i++) {
4640 struct blame_line *bline = &bca.lines[i];
4641 free(bline->id_str);
4642 free(bline->committer);
4644 free(bca.lines);
4646 free(bca.line_offsets);
4647 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4648 error = got_error_from_errno("fclose");
4649 return error;
4652 __dead static void
4653 usage_tree(void)
4655 fprintf(stderr,
4656 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4657 getprogname());
4658 exit(1);
4661 static const struct got_error *
4662 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4663 const char *root_path, struct got_repository *repo)
4665 const struct got_error *err = NULL;
4666 int is_root_path = (strcmp(path, root_path) == 0);
4667 const char *modestr = "";
4668 mode_t mode = got_tree_entry_get_mode(te);
4669 char *link_target = NULL;
4671 path += strlen(root_path);
4672 while (path[0] == '/')
4673 path++;
4675 if (got_object_tree_entry_is_submodule(te))
4676 modestr = "$";
4677 else if (S_ISLNK(mode)) {
4678 int i;
4680 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4681 if (err)
4682 return err;
4683 for (i = 0; i < strlen(link_target); i++) {
4684 if (!isprint((unsigned char)link_target[i]))
4685 link_target[i] = '?';
4688 modestr = "@";
4690 else if (S_ISDIR(mode))
4691 modestr = "/";
4692 else if (mode & S_IXUSR)
4693 modestr = "*";
4695 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4696 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4697 link_target ? " -> ": "", link_target ? link_target : "");
4699 free(link_target);
4700 return NULL;
4703 static const struct got_error *
4704 print_tree(const char *path, struct got_object_id *commit_id,
4705 int show_ids, int recurse, const char *root_path,
4706 struct got_repository *repo)
4708 const struct got_error *err = NULL;
4709 struct got_object_id *tree_id = NULL;
4710 struct got_tree_object *tree = NULL;
4711 int nentries, i;
4713 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4714 if (err)
4715 goto done;
4717 err = got_object_open_as_tree(&tree, repo, tree_id);
4718 if (err)
4719 goto done;
4720 nentries = got_object_tree_get_nentries(tree);
4721 for (i = 0; i < nentries; i++) {
4722 struct got_tree_entry *te;
4723 char *id = NULL;
4725 if (sigint_received || sigpipe_received)
4726 break;
4728 te = got_object_tree_get_entry(tree, i);
4729 if (show_ids) {
4730 char *id_str;
4731 err = got_object_id_str(&id_str,
4732 got_tree_entry_get_id(te));
4733 if (err)
4734 goto done;
4735 if (asprintf(&id, "%s ", id_str) == -1) {
4736 err = got_error_from_errno("asprintf");
4737 free(id_str);
4738 goto done;
4740 free(id_str);
4742 err = print_entry(te, id, path, root_path, repo);
4743 free(id);
4744 if (err)
4745 goto done;
4747 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4748 char *child_path;
4749 if (asprintf(&child_path, "%s%s%s", path,
4750 path[0] == '/' && path[1] == '\0' ? "" : "/",
4751 got_tree_entry_get_name(te)) == -1) {
4752 err = got_error_from_errno("asprintf");
4753 goto done;
4755 err = print_tree(child_path, commit_id, show_ids, 1,
4756 root_path, repo);
4757 free(child_path);
4758 if (err)
4759 goto done;
4762 done:
4763 if (tree)
4764 got_object_tree_close(tree);
4765 free(tree_id);
4766 return err;
4769 static const struct got_error *
4770 cmd_tree(int argc, char *argv[])
4772 const struct got_error *error;
4773 struct got_repository *repo = NULL;
4774 struct got_worktree *worktree = NULL;
4775 const char *path, *refname = NULL;
4776 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4777 struct got_object_id *commit_id = NULL;
4778 char *commit_id_str = NULL;
4779 int show_ids = 0, recurse = 0;
4780 int ch;
4782 #ifndef PROFILE
4783 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4784 NULL) == -1)
4785 err(1, "pledge");
4786 #endif
4788 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4789 switch (ch) {
4790 case 'c':
4791 commit_id_str = optarg;
4792 break;
4793 case 'r':
4794 repo_path = realpath(optarg, NULL);
4795 if (repo_path == NULL)
4796 return got_error_from_errno2("realpath",
4797 optarg);
4798 got_path_strip_trailing_slashes(repo_path);
4799 break;
4800 case 'i':
4801 show_ids = 1;
4802 break;
4803 case 'R':
4804 recurse = 1;
4805 break;
4806 default:
4807 usage_tree();
4808 /* NOTREACHED */
4812 argc -= optind;
4813 argv += optind;
4815 if (argc == 1)
4816 path = argv[0];
4817 else if (argc > 1)
4818 usage_tree();
4819 else
4820 path = NULL;
4822 cwd = getcwd(NULL, 0);
4823 if (cwd == NULL) {
4824 error = got_error_from_errno("getcwd");
4825 goto done;
4827 if (repo_path == NULL) {
4828 error = got_worktree_open(&worktree, cwd);
4829 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4830 goto done;
4831 else
4832 error = NULL;
4833 if (worktree) {
4834 repo_path =
4835 strdup(got_worktree_get_repo_path(worktree));
4836 if (repo_path == NULL)
4837 error = got_error_from_errno("strdup");
4838 if (error)
4839 goto done;
4840 } else {
4841 repo_path = strdup(cwd);
4842 if (repo_path == NULL) {
4843 error = got_error_from_errno("strdup");
4844 goto done;
4849 error = got_repo_open(&repo, repo_path, NULL);
4850 if (error != NULL)
4851 goto done;
4853 if (worktree) {
4854 const char *prefix = got_worktree_get_path_prefix(worktree);
4855 char *p;
4857 if (path == NULL)
4858 path = "";
4859 error = got_worktree_resolve_path(&p, worktree, path);
4860 if (error)
4861 goto done;
4862 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4863 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4864 p) == -1) {
4865 error = got_error_from_errno("asprintf");
4866 free(p);
4867 goto done;
4869 free(p);
4870 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4871 if (error)
4872 goto done;
4873 } else {
4874 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4875 if (error)
4876 goto done;
4877 if (path == NULL)
4878 path = "/";
4879 error = got_repo_map_path(&in_repo_path, repo, path);
4880 if (error != NULL)
4881 goto done;
4884 if (commit_id_str == NULL) {
4885 struct got_reference *head_ref;
4886 if (worktree)
4887 refname = got_worktree_get_head_ref_name(worktree);
4888 else
4889 refname = GOT_REF_HEAD;
4890 error = got_ref_open(&head_ref, repo, refname, 0);
4891 if (error != NULL)
4892 goto done;
4893 error = got_ref_resolve(&commit_id, repo, head_ref);
4894 got_ref_close(head_ref);
4895 if (error != NULL)
4896 goto done;
4897 } else {
4898 error = got_repo_match_object_id(&commit_id, NULL,
4899 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4900 if (error)
4901 goto done;
4904 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4905 in_repo_path, repo);
4906 done:
4907 free(in_repo_path);
4908 free(repo_path);
4909 free(cwd);
4910 free(commit_id);
4911 if (worktree)
4912 got_worktree_close(worktree);
4913 if (repo) {
4914 const struct got_error *repo_error;
4915 repo_error = got_repo_close(repo);
4916 if (error == NULL)
4917 error = repo_error;
4919 return error;
4922 __dead static void
4923 usage_status(void)
4925 fprintf(stderr, "usage: %s status [-s status-codes ] [path ...]\n",
4926 getprogname());
4927 exit(1);
4930 static const struct got_error *
4931 print_status(void *arg, unsigned char status, unsigned char staged_status,
4932 const char *path, struct got_object_id *blob_id,
4933 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4934 int dirfd, const char *de_name)
4936 if (status == staged_status && (status == GOT_STATUS_DELETE))
4937 status = GOT_STATUS_NO_CHANGE;
4938 if (arg) {
4939 char *status_codes = arg;
4940 size_t ncodes = strlen(status_codes);
4941 int i;
4942 for (i = 0; i < ncodes ; i++) {
4943 if (status == status_codes[i] ||
4944 staged_status == status_codes[i])
4945 break;
4947 if (i == ncodes)
4948 return NULL;
4950 printf("%c%c %s\n", status, staged_status, path);
4951 return NULL;
4954 static const struct got_error *
4955 cmd_status(int argc, char *argv[])
4957 const struct got_error *error = NULL;
4958 struct got_repository *repo = NULL;
4959 struct got_worktree *worktree = NULL;
4960 char *cwd = NULL, *status_codes = NULL;;
4961 struct got_pathlist_head paths;
4962 struct got_pathlist_entry *pe;
4963 int ch, i;
4965 TAILQ_INIT(&paths);
4967 while ((ch = getopt(argc, argv, "s:")) != -1) {
4968 switch (ch) {
4969 case 's':
4970 for (i = 0; i < strlen(optarg); i++) {
4971 switch (optarg[i]) {
4972 case GOT_STATUS_MODIFY:
4973 case GOT_STATUS_ADD:
4974 case GOT_STATUS_DELETE:
4975 case GOT_STATUS_CONFLICT:
4976 case GOT_STATUS_MISSING:
4977 case GOT_STATUS_OBSTRUCTED:
4978 case GOT_STATUS_UNVERSIONED:
4979 case GOT_STATUS_MODE_CHANGE:
4980 case GOT_STATUS_NONEXISTENT:
4981 break;
4982 default:
4983 errx(1, "invalid status code '%c'",
4984 optarg[i]);
4987 status_codes = optarg;
4988 break;
4989 default:
4990 usage_status();
4991 /* NOTREACHED */
4995 argc -= optind;
4996 argv += optind;
4998 #ifndef PROFILE
4999 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5000 NULL) == -1)
5001 err(1, "pledge");
5002 #endif
5003 cwd = getcwd(NULL, 0);
5004 if (cwd == NULL) {
5005 error = got_error_from_errno("getcwd");
5006 goto done;
5009 error = got_worktree_open(&worktree, cwd);
5010 if (error) {
5011 if (error->code == GOT_ERR_NOT_WORKTREE)
5012 error = wrap_not_worktree_error(error, "status", cwd);
5013 goto done;
5016 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5017 NULL);
5018 if (error != NULL)
5019 goto done;
5021 error = apply_unveil(got_repo_get_path(repo), 1,
5022 got_worktree_get_root_path(worktree));
5023 if (error)
5024 goto done;
5026 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5027 if (error)
5028 goto done;
5030 error = got_worktree_status(worktree, &paths, repo, print_status,
5031 status_codes, check_cancelled, NULL);
5032 done:
5033 TAILQ_FOREACH(pe, &paths, entry)
5034 free((char *)pe->path);
5035 got_pathlist_free(&paths);
5036 free(cwd);
5037 return error;
5040 __dead static void
5041 usage_ref(void)
5043 fprintf(stderr,
5044 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
5045 "[-d] [name]\n",
5046 getprogname());
5047 exit(1);
5050 static const struct got_error *
5051 list_refs(struct got_repository *repo, const char *refname)
5053 static const struct got_error *err = NULL;
5054 struct got_reflist_head refs;
5055 struct got_reflist_entry *re;
5057 SIMPLEQ_INIT(&refs);
5058 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
5059 if (err)
5060 return err;
5062 SIMPLEQ_FOREACH(re, &refs, entry) {
5063 char *refstr;
5064 refstr = got_ref_to_str(re->ref);
5065 if (refstr == NULL)
5066 return got_error_from_errno("got_ref_to_str");
5067 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5068 free(refstr);
5071 got_ref_list_free(&refs);
5072 return NULL;
5075 static const struct got_error *
5076 delete_ref(struct got_repository *repo, const char *refname)
5078 const struct got_error *err = NULL;
5079 struct got_reference *ref;
5081 err = got_ref_open(&ref, repo, refname, 0);
5082 if (err)
5083 return err;
5085 err = got_ref_delete(ref, repo);
5086 got_ref_close(ref);
5087 return err;
5090 static const struct got_error *
5091 add_ref(struct got_repository *repo, const char *refname, const char *target)
5093 const struct got_error *err = NULL;
5094 struct got_object_id *id;
5095 struct got_reference *ref = NULL;
5098 * Don't let the user create a reference name with a leading '-'.
5099 * While technically a valid reference name, this case is usually
5100 * an unintended typo.
5102 if (refname[0] == '-')
5103 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5105 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5106 repo);
5107 if (err) {
5108 struct got_reference *target_ref;
5110 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5111 return err;
5112 err = got_ref_open(&target_ref, repo, target, 0);
5113 if (err)
5114 return err;
5115 err = got_ref_resolve(&id, repo, target_ref);
5116 got_ref_close(target_ref);
5117 if (err)
5118 return err;
5121 err = got_ref_alloc(&ref, refname, id);
5122 if (err)
5123 goto done;
5125 err = got_ref_write(ref, repo);
5126 done:
5127 if (ref)
5128 got_ref_close(ref);
5129 free(id);
5130 return err;
5133 static const struct got_error *
5134 add_symref(struct got_repository *repo, const char *refname, const char *target)
5136 const struct got_error *err = NULL;
5137 struct got_reference *ref = NULL;
5138 struct got_reference *target_ref = NULL;
5141 * Don't let the user create a reference name with a leading '-'.
5142 * While technically a valid reference name, this case is usually
5143 * an unintended typo.
5145 if (refname[0] == '-')
5146 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5148 err = got_ref_open(&target_ref, repo, target, 0);
5149 if (err)
5150 return err;
5152 err = got_ref_alloc_symref(&ref, refname, target_ref);
5153 if (err)
5154 goto done;
5156 err = got_ref_write(ref, repo);
5157 done:
5158 if (target_ref)
5159 got_ref_close(target_ref);
5160 if (ref)
5161 got_ref_close(ref);
5162 return err;
5165 static const struct got_error *
5166 cmd_ref(int argc, char *argv[])
5168 const struct got_error *error = NULL;
5169 struct got_repository *repo = NULL;
5170 struct got_worktree *worktree = NULL;
5171 char *cwd = NULL, *repo_path = NULL;
5172 int ch, do_list = 0, do_delete = 0;
5173 const char *obj_arg = NULL, *symref_target= NULL;
5174 char *refname = NULL;
5176 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5177 switch (ch) {
5178 case 'c':
5179 obj_arg = optarg;
5180 break;
5181 case 'd':
5182 do_delete = 1;
5183 break;
5184 case 'r':
5185 repo_path = realpath(optarg, NULL);
5186 if (repo_path == NULL)
5187 return got_error_from_errno2("realpath",
5188 optarg);
5189 got_path_strip_trailing_slashes(repo_path);
5190 break;
5191 case 'l':
5192 do_list = 1;
5193 break;
5194 case 's':
5195 symref_target = optarg;
5196 break;
5197 default:
5198 usage_ref();
5199 /* NOTREACHED */
5203 if (obj_arg && do_list)
5204 option_conflict('c', 'l');
5205 if (obj_arg && do_delete)
5206 option_conflict('c', 'd');
5207 if (obj_arg && symref_target)
5208 option_conflict('c', 's');
5209 if (symref_target && do_delete)
5210 option_conflict('s', 'd');
5211 if (symref_target && do_list)
5212 option_conflict('s', 'l');
5213 if (do_delete && do_list)
5214 option_conflict('d', 'l');
5216 argc -= optind;
5217 argv += optind;
5219 if (do_list) {
5220 if (argc != 0 && argc != 1)
5221 usage_ref();
5222 if (argc == 1) {
5223 refname = strdup(argv[0]);
5224 if (refname == NULL) {
5225 error = got_error_from_errno("strdup");
5226 goto done;
5229 } else {
5230 if (argc != 1)
5231 usage_ref();
5232 refname = strdup(argv[0]);
5233 if (refname == NULL) {
5234 error = got_error_from_errno("strdup");
5235 goto done;
5239 if (refname)
5240 got_path_strip_trailing_slashes(refname);
5242 #ifndef PROFILE
5243 if (do_list) {
5244 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5245 NULL) == -1)
5246 err(1, "pledge");
5247 } else {
5248 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5249 "sendfd unveil", NULL) == -1)
5250 err(1, "pledge");
5252 #endif
5253 cwd = getcwd(NULL, 0);
5254 if (cwd == NULL) {
5255 error = got_error_from_errno("getcwd");
5256 goto done;
5259 if (repo_path == NULL) {
5260 error = got_worktree_open(&worktree, cwd);
5261 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5262 goto done;
5263 else
5264 error = NULL;
5265 if (worktree) {
5266 repo_path =
5267 strdup(got_worktree_get_repo_path(worktree));
5268 if (repo_path == NULL)
5269 error = got_error_from_errno("strdup");
5270 if (error)
5271 goto done;
5272 } else {
5273 repo_path = strdup(cwd);
5274 if (repo_path == NULL) {
5275 error = got_error_from_errno("strdup");
5276 goto done;
5281 error = got_repo_open(&repo, repo_path, NULL);
5282 if (error != NULL)
5283 goto done;
5285 error = apply_unveil(got_repo_get_path(repo), do_list,
5286 worktree ? got_worktree_get_root_path(worktree) : NULL);
5287 if (error)
5288 goto done;
5290 if (do_list)
5291 error = list_refs(repo, refname);
5292 else if (do_delete)
5293 error = delete_ref(repo, refname);
5294 else if (symref_target)
5295 error = add_symref(repo, refname, symref_target);
5296 else {
5297 if (obj_arg == NULL)
5298 usage_ref();
5299 error = add_ref(repo, refname, obj_arg);
5301 done:
5302 free(refname);
5303 if (repo)
5304 got_repo_close(repo);
5305 if (worktree)
5306 got_worktree_close(worktree);
5307 free(cwd);
5308 free(repo_path);
5309 return error;
5312 __dead static void
5313 usage_branch(void)
5315 fprintf(stderr,
5316 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5317 "[name]\n", getprogname());
5318 exit(1);
5321 static const struct got_error *
5322 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5323 struct got_reference *ref)
5325 const struct got_error *err = NULL;
5326 const char *refname, *marker = " ";
5327 char *refstr;
5329 refname = got_ref_get_name(ref);
5330 if (worktree && strcmp(refname,
5331 got_worktree_get_head_ref_name(worktree)) == 0) {
5332 struct got_object_id *id = NULL;
5334 err = got_ref_resolve(&id, repo, ref);
5335 if (err)
5336 return err;
5337 if (got_object_id_cmp(id,
5338 got_worktree_get_base_commit_id(worktree)) == 0)
5339 marker = "* ";
5340 else
5341 marker = "~ ";
5342 free(id);
5345 if (strncmp(refname, "refs/heads/", 11) == 0)
5346 refname += 11;
5347 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5348 refname += 18;
5350 refstr = got_ref_to_str(ref);
5351 if (refstr == NULL)
5352 return got_error_from_errno("got_ref_to_str");
5354 printf("%s%s: %s\n", marker, refname, refstr);
5355 free(refstr);
5356 return NULL;
5359 static const struct got_error *
5360 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5362 const char *refname;
5364 if (worktree == NULL)
5365 return got_error(GOT_ERR_NOT_WORKTREE);
5367 refname = got_worktree_get_head_ref_name(worktree);
5369 if (strncmp(refname, "refs/heads/", 11) == 0)
5370 refname += 11;
5371 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5372 refname += 18;
5374 printf("%s\n", refname);
5376 return NULL;
5379 static const struct got_error *
5380 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5382 static const struct got_error *err = NULL;
5383 struct got_reflist_head refs;
5384 struct got_reflist_entry *re;
5385 struct got_reference *temp_ref = NULL;
5386 int rebase_in_progress, histedit_in_progress;
5388 SIMPLEQ_INIT(&refs);
5390 if (worktree) {
5391 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5392 worktree);
5393 if (err)
5394 return err;
5396 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5397 worktree);
5398 if (err)
5399 return err;
5401 if (rebase_in_progress || histedit_in_progress) {
5402 err = got_ref_open(&temp_ref, repo,
5403 got_worktree_get_head_ref_name(worktree), 0);
5404 if (err)
5405 return err;
5406 list_branch(repo, worktree, temp_ref);
5407 got_ref_close(temp_ref);
5411 err = got_ref_list(&refs, repo, "refs/heads",
5412 got_ref_cmp_by_name, NULL);
5413 if (err)
5414 return err;
5416 SIMPLEQ_FOREACH(re, &refs, entry)
5417 list_branch(repo, worktree, re->ref);
5419 got_ref_list_free(&refs);
5420 return NULL;
5423 static const struct got_error *
5424 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5425 const char *branch_name)
5427 const struct got_error *err = NULL;
5428 struct got_reference *ref = NULL;
5429 char *refname;
5431 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5432 return got_error_from_errno("asprintf");
5434 err = got_ref_open(&ref, repo, refname, 0);
5435 if (err)
5436 goto done;
5438 if (worktree &&
5439 strcmp(got_worktree_get_head_ref_name(worktree),
5440 got_ref_get_name(ref)) == 0) {
5441 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5442 "will not delete this work tree's current branch");
5443 goto done;
5446 err = got_ref_delete(ref, repo);
5447 done:
5448 if (ref)
5449 got_ref_close(ref);
5450 free(refname);
5451 return err;
5454 static const struct got_error *
5455 add_branch(struct got_repository *repo, const char *branch_name,
5456 struct got_object_id *base_commit_id)
5458 const struct got_error *err = NULL;
5459 struct got_reference *ref = NULL;
5460 char *base_refname = NULL, *refname = NULL;
5463 * Don't let the user create a branch name with a leading '-'.
5464 * While technically a valid reference name, this case is usually
5465 * an unintended typo.
5467 if (branch_name[0] == '-')
5468 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5470 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5471 err = got_error_from_errno("asprintf");
5472 goto done;
5475 err = got_ref_open(&ref, repo, refname, 0);
5476 if (err == NULL) {
5477 err = got_error(GOT_ERR_BRANCH_EXISTS);
5478 goto done;
5479 } else if (err->code != GOT_ERR_NOT_REF)
5480 goto done;
5482 err = got_ref_alloc(&ref, refname, base_commit_id);
5483 if (err)
5484 goto done;
5486 err = got_ref_write(ref, repo);
5487 done:
5488 if (ref)
5489 got_ref_close(ref);
5490 free(base_refname);
5491 free(refname);
5492 return err;
5495 static const struct got_error *
5496 cmd_branch(int argc, char *argv[])
5498 const struct got_error *error = NULL;
5499 struct got_repository *repo = NULL;
5500 struct got_worktree *worktree = NULL;
5501 char *cwd = NULL, *repo_path = NULL;
5502 int ch, do_list = 0, do_show = 0, do_update = 1;
5503 const char *delref = NULL, *commit_id_arg = NULL;
5504 struct got_reference *ref = NULL;
5505 struct got_pathlist_head paths;
5506 struct got_pathlist_entry *pe;
5507 struct got_object_id *commit_id = NULL;
5508 char *commit_id_str = NULL;
5510 TAILQ_INIT(&paths);
5512 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5513 switch (ch) {
5514 case 'c':
5515 commit_id_arg = optarg;
5516 break;
5517 case 'd':
5518 delref = optarg;
5519 break;
5520 case 'r':
5521 repo_path = realpath(optarg, NULL);
5522 if (repo_path == NULL)
5523 return got_error_from_errno2("realpath",
5524 optarg);
5525 got_path_strip_trailing_slashes(repo_path);
5526 break;
5527 case 'l':
5528 do_list = 1;
5529 break;
5530 case 'n':
5531 do_update = 0;
5532 break;
5533 default:
5534 usage_branch();
5535 /* NOTREACHED */
5539 if (do_list && delref)
5540 option_conflict('l', 'd');
5542 argc -= optind;
5543 argv += optind;
5545 if (!do_list && !delref && argc == 0)
5546 do_show = 1;
5548 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5549 errx(1, "-c option can only be used when creating a branch");
5551 if (do_list || delref) {
5552 if (argc > 0)
5553 usage_branch();
5554 } else if (!do_show && argc != 1)
5555 usage_branch();
5557 #ifndef PROFILE
5558 if (do_list || do_show) {
5559 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5560 NULL) == -1)
5561 err(1, "pledge");
5562 } else {
5563 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5564 "sendfd unveil", NULL) == -1)
5565 err(1, "pledge");
5567 #endif
5568 cwd = getcwd(NULL, 0);
5569 if (cwd == NULL) {
5570 error = got_error_from_errno("getcwd");
5571 goto done;
5574 if (repo_path == NULL) {
5575 error = got_worktree_open(&worktree, cwd);
5576 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5577 goto done;
5578 else
5579 error = NULL;
5580 if (worktree) {
5581 repo_path =
5582 strdup(got_worktree_get_repo_path(worktree));
5583 if (repo_path == NULL)
5584 error = got_error_from_errno("strdup");
5585 if (error)
5586 goto done;
5587 } else {
5588 repo_path = strdup(cwd);
5589 if (repo_path == NULL) {
5590 error = got_error_from_errno("strdup");
5591 goto done;
5596 error = got_repo_open(&repo, repo_path, NULL);
5597 if (error != NULL)
5598 goto done;
5600 error = apply_unveil(got_repo_get_path(repo), do_list,
5601 worktree ? got_worktree_get_root_path(worktree) : NULL);
5602 if (error)
5603 goto done;
5605 if (do_show)
5606 error = show_current_branch(repo, worktree);
5607 else if (do_list)
5608 error = list_branches(repo, worktree);
5609 else if (delref)
5610 error = delete_branch(repo, worktree, delref);
5611 else {
5612 if (commit_id_arg == NULL)
5613 commit_id_arg = worktree ?
5614 got_worktree_get_head_ref_name(worktree) :
5615 GOT_REF_HEAD;
5616 error = got_repo_match_object_id(&commit_id, NULL,
5617 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5618 if (error)
5619 goto done;
5620 error = add_branch(repo, argv[0], commit_id);
5621 if (error)
5622 goto done;
5623 if (worktree && do_update) {
5624 struct got_update_progress_arg upa;
5625 char *branch_refname = NULL;
5627 error = got_object_id_str(&commit_id_str, commit_id);
5628 if (error)
5629 goto done;
5630 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5631 worktree);
5632 if (error)
5633 goto done;
5634 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5635 == -1) {
5636 error = got_error_from_errno("asprintf");
5637 goto done;
5639 error = got_ref_open(&ref, repo, branch_refname, 0);
5640 free(branch_refname);
5641 if (error)
5642 goto done;
5643 error = switch_head_ref(ref, commit_id, worktree,
5644 repo);
5645 if (error)
5646 goto done;
5647 error = got_worktree_set_base_commit_id(worktree, repo,
5648 commit_id);
5649 if (error)
5650 goto done;
5651 memset(&upa, 0, sizeof(upa));
5652 error = got_worktree_checkout_files(worktree, &paths,
5653 repo, update_progress, &upa, check_cancelled,
5654 NULL);
5655 if (error)
5656 goto done;
5657 if (upa.did_something)
5658 printf("Updated to commit %s\n", commit_id_str);
5659 print_update_progress_stats(&upa);
5662 done:
5663 if (ref)
5664 got_ref_close(ref);
5665 if (repo)
5666 got_repo_close(repo);
5667 if (worktree)
5668 got_worktree_close(worktree);
5669 free(cwd);
5670 free(repo_path);
5671 free(commit_id);
5672 free(commit_id_str);
5673 TAILQ_FOREACH(pe, &paths, entry)
5674 free((char *)pe->path);
5675 got_pathlist_free(&paths);
5676 return error;
5680 __dead static void
5681 usage_tag(void)
5683 fprintf(stderr,
5684 "usage: %s tag [-c commit] [-r repository] [-l] "
5685 "[-m message] name\n", getprogname());
5686 exit(1);
5689 #if 0
5690 static const struct got_error *
5691 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5693 const struct got_error *err = NULL;
5694 struct got_reflist_entry *re, *se, *new;
5695 struct got_object_id *re_id, *se_id;
5696 struct got_tag_object *re_tag, *se_tag;
5697 time_t re_time, se_time;
5699 SIMPLEQ_FOREACH(re, tags, entry) {
5700 se = SIMPLEQ_FIRST(sorted);
5701 if (se == NULL) {
5702 err = got_reflist_entry_dup(&new, re);
5703 if (err)
5704 return err;
5705 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5706 continue;
5707 } else {
5708 err = got_ref_resolve(&re_id, repo, re->ref);
5709 if (err)
5710 break;
5711 err = got_object_open_as_tag(&re_tag, repo, re_id);
5712 free(re_id);
5713 if (err)
5714 break;
5715 re_time = got_object_tag_get_tagger_time(re_tag);
5716 got_object_tag_close(re_tag);
5719 while (se) {
5720 err = got_ref_resolve(&se_id, repo, re->ref);
5721 if (err)
5722 break;
5723 err = got_object_open_as_tag(&se_tag, repo, se_id);
5724 free(se_id);
5725 if (err)
5726 break;
5727 se_time = got_object_tag_get_tagger_time(se_tag);
5728 got_object_tag_close(se_tag);
5730 if (se_time > re_time) {
5731 err = got_reflist_entry_dup(&new, re);
5732 if (err)
5733 return err;
5734 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5735 break;
5737 se = SIMPLEQ_NEXT(se, entry);
5738 continue;
5741 done:
5742 return err;
5744 #endif
5746 static const struct got_error *
5747 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5749 static const struct got_error *err = NULL;
5750 struct got_reflist_head refs;
5751 struct got_reflist_entry *re;
5753 SIMPLEQ_INIT(&refs);
5755 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5756 if (err)
5757 return err;
5759 SIMPLEQ_FOREACH(re, &refs, entry) {
5760 const char *refname;
5761 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5762 char datebuf[26];
5763 const char *tagger;
5764 time_t tagger_time;
5765 struct got_object_id *id;
5766 struct got_tag_object *tag;
5767 struct got_commit_object *commit = NULL;
5769 refname = got_ref_get_name(re->ref);
5770 if (strncmp(refname, "refs/tags/", 10) != 0)
5771 continue;
5772 refname += 10;
5773 refstr = got_ref_to_str(re->ref);
5774 if (refstr == NULL) {
5775 err = got_error_from_errno("got_ref_to_str");
5776 break;
5778 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5779 free(refstr);
5781 err = got_ref_resolve(&id, repo, re->ref);
5782 if (err)
5783 break;
5784 err = got_object_open_as_tag(&tag, repo, id);
5785 if (err) {
5786 if (err->code != GOT_ERR_OBJ_TYPE) {
5787 free(id);
5788 break;
5790 /* "lightweight" tag */
5791 err = got_object_open_as_commit(&commit, repo, id);
5792 if (err) {
5793 free(id);
5794 break;
5796 tagger = got_object_commit_get_committer(commit);
5797 tagger_time =
5798 got_object_commit_get_committer_time(commit);
5799 err = got_object_id_str(&id_str, id);
5800 free(id);
5801 if (err)
5802 break;
5803 } else {
5804 free(id);
5805 tagger = got_object_tag_get_tagger(tag);
5806 tagger_time = got_object_tag_get_tagger_time(tag);
5807 err = got_object_id_str(&id_str,
5808 got_object_tag_get_object_id(tag));
5809 if (err)
5810 break;
5812 printf("from: %s\n", tagger);
5813 datestr = get_datestr(&tagger_time, datebuf);
5814 if (datestr)
5815 printf("date: %s UTC\n", datestr);
5816 if (commit)
5817 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5818 else {
5819 switch (got_object_tag_get_object_type(tag)) {
5820 case GOT_OBJ_TYPE_BLOB:
5821 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5822 id_str);
5823 break;
5824 case GOT_OBJ_TYPE_TREE:
5825 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5826 id_str);
5827 break;
5828 case GOT_OBJ_TYPE_COMMIT:
5829 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5830 id_str);
5831 break;
5832 case GOT_OBJ_TYPE_TAG:
5833 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5834 id_str);
5835 break;
5836 default:
5837 break;
5840 free(id_str);
5841 if (commit) {
5842 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5843 if (err)
5844 break;
5845 got_object_commit_close(commit);
5846 } else {
5847 tagmsg0 = strdup(got_object_tag_get_message(tag));
5848 got_object_tag_close(tag);
5849 if (tagmsg0 == NULL) {
5850 err = got_error_from_errno("strdup");
5851 break;
5855 tagmsg = tagmsg0;
5856 do {
5857 line = strsep(&tagmsg, "\n");
5858 if (line)
5859 printf(" %s\n", line);
5860 } while (line);
5861 free(tagmsg0);
5864 got_ref_list_free(&refs);
5865 return NULL;
5868 static const struct got_error *
5869 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5870 const char *tag_name, const char *repo_path)
5872 const struct got_error *err = NULL;
5873 char *template = NULL, *initial_content = NULL;
5874 char *editor = NULL;
5875 int initial_content_len;
5876 int fd = -1;
5878 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5879 err = got_error_from_errno("asprintf");
5880 goto done;
5883 initial_content_len = asprintf(&initial_content,
5884 "\n# tagging commit %s as %s\n",
5885 commit_id_str, tag_name);
5886 if (initial_content_len == -1) {
5887 err = got_error_from_errno("asprintf");
5888 goto done;
5891 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5892 if (err)
5893 goto done;
5895 if (write(fd, initial_content, initial_content_len) == -1) {
5896 err = got_error_from_errno2("write", *tagmsg_path);
5897 goto done;
5900 err = get_editor(&editor);
5901 if (err)
5902 goto done;
5903 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
5904 initial_content_len);
5905 done:
5906 free(initial_content);
5907 free(template);
5908 free(editor);
5910 if (fd != -1 && close(fd) == -1 && err == NULL)
5911 err = got_error_from_errno2("close", *tagmsg_path);
5913 /* Editor is done; we can now apply unveil(2) */
5914 if (err == NULL)
5915 err = apply_unveil(repo_path, 0, NULL);
5916 if (err) {
5917 free(*tagmsg);
5918 *tagmsg = NULL;
5920 return err;
5923 static const struct got_error *
5924 add_tag(struct got_repository *repo, struct got_worktree *worktree,
5925 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
5927 const struct got_error *err = NULL;
5928 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5929 char *label = NULL, *commit_id_str = NULL;
5930 struct got_reference *ref = NULL;
5931 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5932 char *tagmsg_path = NULL, *tag_id_str = NULL;
5933 int preserve_tagmsg = 0;
5936 * Don't let the user create a tag name with a leading '-'.
5937 * While technically a valid reference name, this case is usually
5938 * an unintended typo.
5940 if (tag_name[0] == '-')
5941 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5943 err = get_author(&tagger, repo, worktree);
5944 if (err)
5945 return err;
5947 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5948 GOT_OBJ_TYPE_COMMIT, 1, repo);
5949 if (err)
5950 goto done;
5952 err = got_object_id_str(&commit_id_str, commit_id);
5953 if (err)
5954 goto done;
5956 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5957 refname = strdup(tag_name);
5958 if (refname == NULL) {
5959 err = got_error_from_errno("strdup");
5960 goto done;
5962 tag_name += 10;
5963 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5964 err = got_error_from_errno("asprintf");
5965 goto done;
5968 err = got_ref_open(&ref, repo, refname, 0);
5969 if (err == NULL) {
5970 err = got_error(GOT_ERR_TAG_EXISTS);
5971 goto done;
5972 } else if (err->code != GOT_ERR_NOT_REF)
5973 goto done;
5975 if (tagmsg_arg == NULL) {
5976 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5977 tag_name, got_repo_get_path(repo));
5978 if (err) {
5979 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5980 tagmsg_path != NULL)
5981 preserve_tagmsg = 1;
5982 goto done;
5986 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5987 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5988 if (err) {
5989 if (tagmsg_path)
5990 preserve_tagmsg = 1;
5991 goto done;
5994 err = got_ref_alloc(&ref, refname, tag_id);
5995 if (err) {
5996 if (tagmsg_path)
5997 preserve_tagmsg = 1;
5998 goto done;
6001 err = got_ref_write(ref, repo);
6002 if (err) {
6003 if (tagmsg_path)
6004 preserve_tagmsg = 1;
6005 goto done;
6008 err = got_object_id_str(&tag_id_str, tag_id);
6009 if (err) {
6010 if (tagmsg_path)
6011 preserve_tagmsg = 1;
6012 goto done;
6014 printf("Created tag %s\n", tag_id_str);
6015 done:
6016 if (preserve_tagmsg) {
6017 fprintf(stderr, "%s: tag message preserved in %s\n",
6018 getprogname(), tagmsg_path);
6019 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6020 err = got_error_from_errno2("unlink", tagmsg_path);
6021 free(tag_id_str);
6022 if (ref)
6023 got_ref_close(ref);
6024 free(commit_id);
6025 free(commit_id_str);
6026 free(refname);
6027 free(tagmsg);
6028 free(tagmsg_path);
6029 free(tagger);
6030 return err;
6033 static const struct got_error *
6034 cmd_tag(int argc, char *argv[])
6036 const struct got_error *error = NULL;
6037 struct got_repository *repo = NULL;
6038 struct got_worktree *worktree = NULL;
6039 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6040 char *gitconfig_path = NULL;
6041 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6042 int ch, do_list = 0;
6044 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6045 switch (ch) {
6046 case 'c':
6047 commit_id_arg = optarg;
6048 break;
6049 case 'm':
6050 tagmsg = optarg;
6051 break;
6052 case 'r':
6053 repo_path = realpath(optarg, NULL);
6054 if (repo_path == NULL)
6055 return got_error_from_errno2("realpath",
6056 optarg);
6057 got_path_strip_trailing_slashes(repo_path);
6058 break;
6059 case 'l':
6060 do_list = 1;
6061 break;
6062 default:
6063 usage_tag();
6064 /* NOTREACHED */
6068 argc -= optind;
6069 argv += optind;
6071 if (do_list) {
6072 if (commit_id_arg != NULL)
6073 errx(1,
6074 "-c option can only be used when creating a tag");
6075 if (tagmsg)
6076 option_conflict('l', 'm');
6077 if (argc > 0)
6078 usage_tag();
6079 } else if (argc != 1)
6080 usage_tag();
6082 tag_name = argv[0];
6084 #ifndef PROFILE
6085 if (do_list) {
6086 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6087 NULL) == -1)
6088 err(1, "pledge");
6089 } else {
6090 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6091 "sendfd unveil", NULL) == -1)
6092 err(1, "pledge");
6094 #endif
6095 cwd = getcwd(NULL, 0);
6096 if (cwd == NULL) {
6097 error = got_error_from_errno("getcwd");
6098 goto done;
6101 if (repo_path == NULL) {
6102 error = got_worktree_open(&worktree, cwd);
6103 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6104 goto done;
6105 else
6106 error = NULL;
6107 if (worktree) {
6108 repo_path =
6109 strdup(got_worktree_get_repo_path(worktree));
6110 if (repo_path == NULL)
6111 error = got_error_from_errno("strdup");
6112 if (error)
6113 goto done;
6114 } else {
6115 repo_path = strdup(cwd);
6116 if (repo_path == NULL) {
6117 error = got_error_from_errno("strdup");
6118 goto done;
6123 if (do_list) {
6124 error = got_repo_open(&repo, repo_path, NULL);
6125 if (error != NULL)
6126 goto done;
6127 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6128 if (error)
6129 goto done;
6130 error = list_tags(repo, worktree);
6131 } else {
6132 error = get_gitconfig_path(&gitconfig_path);
6133 if (error)
6134 goto done;
6135 error = got_repo_open(&repo, repo_path, gitconfig_path);
6136 if (error != NULL)
6137 goto done;
6139 if (tagmsg) {
6140 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6141 if (error)
6142 goto done;
6145 if (commit_id_arg == NULL) {
6146 struct got_reference *head_ref;
6147 struct got_object_id *commit_id;
6148 error = got_ref_open(&head_ref, repo,
6149 worktree ? got_worktree_get_head_ref_name(worktree)
6150 : GOT_REF_HEAD, 0);
6151 if (error)
6152 goto done;
6153 error = got_ref_resolve(&commit_id, repo, head_ref);
6154 got_ref_close(head_ref);
6155 if (error)
6156 goto done;
6157 error = got_object_id_str(&commit_id_str, commit_id);
6158 free(commit_id);
6159 if (error)
6160 goto done;
6163 error = add_tag(repo, worktree, tag_name,
6164 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6166 done:
6167 if (repo)
6168 got_repo_close(repo);
6169 if (worktree)
6170 got_worktree_close(worktree);
6171 free(cwd);
6172 free(repo_path);
6173 free(gitconfig_path);
6174 free(commit_id_str);
6175 return error;
6178 __dead static void
6179 usage_add(void)
6181 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6182 getprogname());
6183 exit(1);
6186 static const struct got_error *
6187 add_progress(void *arg, unsigned char status, const char *path)
6189 while (path[0] == '/')
6190 path++;
6191 printf("%c %s\n", status, path);
6192 return NULL;
6195 static const struct got_error *
6196 cmd_add(int argc, char *argv[])
6198 const struct got_error *error = NULL;
6199 struct got_repository *repo = NULL;
6200 struct got_worktree *worktree = NULL;
6201 char *cwd = NULL;
6202 struct got_pathlist_head paths;
6203 struct got_pathlist_entry *pe;
6204 int ch, can_recurse = 0, no_ignores = 0;
6206 TAILQ_INIT(&paths);
6208 while ((ch = getopt(argc, argv, "IR")) != -1) {
6209 switch (ch) {
6210 case 'I':
6211 no_ignores = 1;
6212 break;
6213 case 'R':
6214 can_recurse = 1;
6215 break;
6216 default:
6217 usage_add();
6218 /* NOTREACHED */
6222 argc -= optind;
6223 argv += optind;
6225 #ifndef PROFILE
6226 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6227 NULL) == -1)
6228 err(1, "pledge");
6229 #endif
6230 if (argc < 1)
6231 usage_add();
6233 cwd = getcwd(NULL, 0);
6234 if (cwd == NULL) {
6235 error = got_error_from_errno("getcwd");
6236 goto done;
6239 error = got_worktree_open(&worktree, cwd);
6240 if (error) {
6241 if (error->code == GOT_ERR_NOT_WORKTREE)
6242 error = wrap_not_worktree_error(error, "add", cwd);
6243 goto done;
6246 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6247 NULL);
6248 if (error != NULL)
6249 goto done;
6251 error = apply_unveil(got_repo_get_path(repo), 1,
6252 got_worktree_get_root_path(worktree));
6253 if (error)
6254 goto done;
6256 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6257 if (error)
6258 goto done;
6260 if (!can_recurse && no_ignores) {
6261 error = got_error_msg(GOT_ERR_BAD_PATH,
6262 "disregarding ignores requires -R option");
6263 goto done;
6267 if (!can_recurse) {
6268 char *ondisk_path;
6269 struct stat sb;
6270 TAILQ_FOREACH(pe, &paths, entry) {
6271 if (asprintf(&ondisk_path, "%s/%s",
6272 got_worktree_get_root_path(worktree),
6273 pe->path) == -1) {
6274 error = got_error_from_errno("asprintf");
6275 goto done;
6277 if (lstat(ondisk_path, &sb) == -1) {
6278 if (errno == ENOENT) {
6279 free(ondisk_path);
6280 continue;
6282 error = got_error_from_errno2("lstat",
6283 ondisk_path);
6284 free(ondisk_path);
6285 goto done;
6287 free(ondisk_path);
6288 if (S_ISDIR(sb.st_mode)) {
6289 error = got_error_msg(GOT_ERR_BAD_PATH,
6290 "adding directories requires -R option");
6291 goto done;
6296 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6297 NULL, repo, no_ignores);
6298 done:
6299 if (repo)
6300 got_repo_close(repo);
6301 if (worktree)
6302 got_worktree_close(worktree);
6303 TAILQ_FOREACH(pe, &paths, entry)
6304 free((char *)pe->path);
6305 got_pathlist_free(&paths);
6306 free(cwd);
6307 return error;
6310 __dead static void
6311 usage_remove(void)
6313 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6314 "path ...\n", getprogname());
6315 exit(1);
6318 static const struct got_error *
6319 print_remove_status(void *arg, unsigned char status,
6320 unsigned char staged_status, const char *path)
6322 while (path[0] == '/')
6323 path++;
6324 if (status == GOT_STATUS_NONEXISTENT)
6325 return NULL;
6326 if (status == staged_status && (status == GOT_STATUS_DELETE))
6327 status = GOT_STATUS_NO_CHANGE;
6328 printf("%c%c %s\n", status, staged_status, path);
6329 return NULL;
6332 static const struct got_error *
6333 cmd_remove(int argc, char *argv[])
6335 const struct got_error *error = NULL;
6336 struct got_worktree *worktree = NULL;
6337 struct got_repository *repo = NULL;
6338 const char *status_codes = NULL;
6339 char *cwd = NULL;
6340 struct got_pathlist_head paths;
6341 struct got_pathlist_entry *pe;
6342 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6344 TAILQ_INIT(&paths);
6346 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6347 switch (ch) {
6348 case 'f':
6349 delete_local_mods = 1;
6350 break;
6351 case 'k':
6352 keep_on_disk = 1;
6353 break;
6354 case 'R':
6355 can_recurse = 1;
6356 break;
6357 case 's':
6358 for (i = 0; i < strlen(optarg); i++) {
6359 switch (optarg[i]) {
6360 case GOT_STATUS_MODIFY:
6361 delete_local_mods = 1;
6362 break;
6363 case GOT_STATUS_MISSING:
6364 break;
6365 default:
6366 errx(1, "invalid status code '%c'",
6367 optarg[i]);
6370 status_codes = optarg;
6371 break;
6372 default:
6373 usage_remove();
6374 /* NOTREACHED */
6378 argc -= optind;
6379 argv += optind;
6381 #ifndef PROFILE
6382 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6383 NULL) == -1)
6384 err(1, "pledge");
6385 #endif
6386 if (argc < 1)
6387 usage_remove();
6389 cwd = getcwd(NULL, 0);
6390 if (cwd == NULL) {
6391 error = got_error_from_errno("getcwd");
6392 goto done;
6394 error = got_worktree_open(&worktree, cwd);
6395 if (error) {
6396 if (error->code == GOT_ERR_NOT_WORKTREE)
6397 error = wrap_not_worktree_error(error, "remove", cwd);
6398 goto done;
6401 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6402 NULL);
6403 if (error)
6404 goto done;
6406 error = apply_unveil(got_repo_get_path(repo), 1,
6407 got_worktree_get_root_path(worktree));
6408 if (error)
6409 goto done;
6411 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6412 if (error)
6413 goto done;
6415 if (!can_recurse) {
6416 char *ondisk_path;
6417 struct stat sb;
6418 TAILQ_FOREACH(pe, &paths, entry) {
6419 if (asprintf(&ondisk_path, "%s/%s",
6420 got_worktree_get_root_path(worktree),
6421 pe->path) == -1) {
6422 error = got_error_from_errno("asprintf");
6423 goto done;
6425 if (lstat(ondisk_path, &sb) == -1) {
6426 if (errno == ENOENT) {
6427 free(ondisk_path);
6428 continue;
6430 error = got_error_from_errno2("lstat",
6431 ondisk_path);
6432 free(ondisk_path);
6433 goto done;
6435 free(ondisk_path);
6436 if (S_ISDIR(sb.st_mode)) {
6437 error = got_error_msg(GOT_ERR_BAD_PATH,
6438 "removing directories requires -R option");
6439 goto done;
6444 error = got_worktree_schedule_delete(worktree, &paths,
6445 delete_local_mods, status_codes, print_remove_status, NULL,
6446 repo, keep_on_disk);
6447 done:
6448 if (repo)
6449 got_repo_close(repo);
6450 if (worktree)
6451 got_worktree_close(worktree);
6452 TAILQ_FOREACH(pe, &paths, entry)
6453 free((char *)pe->path);
6454 got_pathlist_free(&paths);
6455 free(cwd);
6456 return error;
6459 __dead static void
6460 usage_revert(void)
6462 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6463 "path ...\n", getprogname());
6464 exit(1);
6467 static const struct got_error *
6468 revert_progress(void *arg, unsigned char status, const char *path)
6470 if (status == GOT_STATUS_UNVERSIONED)
6471 return NULL;
6473 while (path[0] == '/')
6474 path++;
6475 printf("%c %s\n", status, path);
6476 return NULL;
6479 struct choose_patch_arg {
6480 FILE *patch_script_file;
6481 const char *action;
6484 static const struct got_error *
6485 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6486 int nchanges, const char *action)
6488 char *line = NULL;
6489 size_t linesize = 0;
6490 ssize_t linelen;
6492 switch (status) {
6493 case GOT_STATUS_ADD:
6494 printf("A %s\n%s this addition? [y/n] ", path, action);
6495 break;
6496 case GOT_STATUS_DELETE:
6497 printf("D %s\n%s this deletion? [y/n] ", path, action);
6498 break;
6499 case GOT_STATUS_MODIFY:
6500 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6501 return got_error_from_errno("fseek");
6502 printf(GOT_COMMIT_SEP_STR);
6503 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6504 printf("%s", line);
6505 if (ferror(patch_file))
6506 return got_error_from_errno("getline");
6507 printf(GOT_COMMIT_SEP_STR);
6508 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6509 path, n, nchanges, action);
6510 break;
6511 default:
6512 return got_error_path(path, GOT_ERR_FILE_STATUS);
6515 return NULL;
6518 static const struct got_error *
6519 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6520 FILE *patch_file, int n, int nchanges)
6522 const struct got_error *err = NULL;
6523 char *line = NULL;
6524 size_t linesize = 0;
6525 ssize_t linelen;
6526 int resp = ' ';
6527 struct choose_patch_arg *a = arg;
6529 *choice = GOT_PATCH_CHOICE_NONE;
6531 if (a->patch_script_file) {
6532 char *nl;
6533 err = show_change(status, path, patch_file, n, nchanges,
6534 a->action);
6535 if (err)
6536 return err;
6537 linelen = getline(&line, &linesize, a->patch_script_file);
6538 if (linelen == -1) {
6539 if (ferror(a->patch_script_file))
6540 return got_error_from_errno("getline");
6541 return NULL;
6543 nl = strchr(line, '\n');
6544 if (nl)
6545 *nl = '\0';
6546 if (strcmp(line, "y") == 0) {
6547 *choice = GOT_PATCH_CHOICE_YES;
6548 printf("y\n");
6549 } else if (strcmp(line, "n") == 0) {
6550 *choice = GOT_PATCH_CHOICE_NO;
6551 printf("n\n");
6552 } else if (strcmp(line, "q") == 0 &&
6553 status == GOT_STATUS_MODIFY) {
6554 *choice = GOT_PATCH_CHOICE_QUIT;
6555 printf("q\n");
6556 } else
6557 printf("invalid response '%s'\n", line);
6558 free(line);
6559 return NULL;
6562 while (resp != 'y' && resp != 'n' && resp != 'q') {
6563 err = show_change(status, path, patch_file, n, nchanges,
6564 a->action);
6565 if (err)
6566 return err;
6567 resp = getchar();
6568 if (resp == '\n')
6569 resp = getchar();
6570 if (status == GOT_STATUS_MODIFY) {
6571 if (resp != 'y' && resp != 'n' && resp != 'q') {
6572 printf("invalid response '%c'\n", resp);
6573 resp = ' ';
6575 } else if (resp != 'y' && resp != 'n') {
6576 printf("invalid response '%c'\n", resp);
6577 resp = ' ';
6581 if (resp == 'y')
6582 *choice = GOT_PATCH_CHOICE_YES;
6583 else if (resp == 'n')
6584 *choice = GOT_PATCH_CHOICE_NO;
6585 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6586 *choice = GOT_PATCH_CHOICE_QUIT;
6588 return NULL;
6592 static const struct got_error *
6593 cmd_revert(int argc, char *argv[])
6595 const struct got_error *error = NULL;
6596 struct got_worktree *worktree = NULL;
6597 struct got_repository *repo = NULL;
6598 char *cwd = NULL, *path = NULL;
6599 struct got_pathlist_head paths;
6600 struct got_pathlist_entry *pe;
6601 int ch, can_recurse = 0, pflag = 0;
6602 FILE *patch_script_file = NULL;
6603 const char *patch_script_path = NULL;
6604 struct choose_patch_arg cpa;
6606 TAILQ_INIT(&paths);
6608 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6609 switch (ch) {
6610 case 'p':
6611 pflag = 1;
6612 break;
6613 case 'F':
6614 patch_script_path = optarg;
6615 break;
6616 case 'R':
6617 can_recurse = 1;
6618 break;
6619 default:
6620 usage_revert();
6621 /* NOTREACHED */
6625 argc -= optind;
6626 argv += optind;
6628 #ifndef PROFILE
6629 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6630 "unveil", NULL) == -1)
6631 err(1, "pledge");
6632 #endif
6633 if (argc < 1)
6634 usage_revert();
6635 if (patch_script_path && !pflag)
6636 errx(1, "-F option can only be used together with -p option");
6638 cwd = getcwd(NULL, 0);
6639 if (cwd == NULL) {
6640 error = got_error_from_errno("getcwd");
6641 goto done;
6643 error = got_worktree_open(&worktree, cwd);
6644 if (error) {
6645 if (error->code == GOT_ERR_NOT_WORKTREE)
6646 error = wrap_not_worktree_error(error, "revert", cwd);
6647 goto done;
6650 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6651 NULL);
6652 if (error != NULL)
6653 goto done;
6655 if (patch_script_path) {
6656 patch_script_file = fopen(patch_script_path, "r");
6657 if (patch_script_file == NULL) {
6658 error = got_error_from_errno2("fopen",
6659 patch_script_path);
6660 goto done;
6663 error = apply_unveil(got_repo_get_path(repo), 1,
6664 got_worktree_get_root_path(worktree));
6665 if (error)
6666 goto done;
6668 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6669 if (error)
6670 goto done;
6672 if (!can_recurse) {
6673 char *ondisk_path;
6674 struct stat sb;
6675 TAILQ_FOREACH(pe, &paths, entry) {
6676 if (asprintf(&ondisk_path, "%s/%s",
6677 got_worktree_get_root_path(worktree),
6678 pe->path) == -1) {
6679 error = got_error_from_errno("asprintf");
6680 goto done;
6682 if (lstat(ondisk_path, &sb) == -1) {
6683 if (errno == ENOENT) {
6684 free(ondisk_path);
6685 continue;
6687 error = got_error_from_errno2("lstat",
6688 ondisk_path);
6689 free(ondisk_path);
6690 goto done;
6692 free(ondisk_path);
6693 if (S_ISDIR(sb.st_mode)) {
6694 error = got_error_msg(GOT_ERR_BAD_PATH,
6695 "reverting directories requires -R option");
6696 goto done;
6701 cpa.patch_script_file = patch_script_file;
6702 cpa.action = "revert";
6703 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6704 pflag ? choose_patch : NULL, &cpa, repo);
6705 done:
6706 if (patch_script_file && fclose(patch_script_file) == EOF &&
6707 error == NULL)
6708 error = got_error_from_errno2("fclose", patch_script_path);
6709 if (repo)
6710 got_repo_close(repo);
6711 if (worktree)
6712 got_worktree_close(worktree);
6713 free(path);
6714 free(cwd);
6715 return error;
6718 __dead static void
6719 usage_commit(void)
6721 fprintf(stderr, "usage: %s commit [-m msg] [-S] [path ...]\n",
6722 getprogname());
6723 exit(1);
6726 struct collect_commit_logmsg_arg {
6727 const char *cmdline_log;
6728 const char *editor;
6729 const char *worktree_path;
6730 const char *branch_name;
6731 const char *repo_path;
6732 char *logmsg_path;
6736 static const struct got_error *
6737 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6738 void *arg)
6740 char *initial_content = NULL;
6741 struct got_pathlist_entry *pe;
6742 const struct got_error *err = NULL;
6743 char *template = NULL;
6744 struct collect_commit_logmsg_arg *a = arg;
6745 int initial_content_len;
6746 int fd = -1;
6747 size_t len;
6749 /* if a message was specified on the command line, just use it */
6750 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6751 len = strlen(a->cmdline_log) + 1;
6752 *logmsg = malloc(len + 1);
6753 if (*logmsg == NULL)
6754 return got_error_from_errno("malloc");
6755 strlcpy(*logmsg, a->cmdline_log, len);
6756 return NULL;
6759 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6760 return got_error_from_errno("asprintf");
6762 initial_content_len = asprintf(&initial_content,
6763 "\n# changes to be committed on branch %s:\n",
6764 a->branch_name);
6765 if (initial_content_len == -1)
6766 return got_error_from_errno("asprintf");
6768 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6769 if (err)
6770 goto done;
6772 if (write(fd, initial_content, initial_content_len) == -1) {
6773 err = got_error_from_errno2("write", a->logmsg_path);
6774 goto done;
6777 TAILQ_FOREACH(pe, commitable_paths, entry) {
6778 struct got_commitable *ct = pe->data;
6779 dprintf(fd, "# %c %s\n",
6780 got_commitable_get_status(ct),
6781 got_commitable_get_path(ct));
6784 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
6785 initial_content_len);
6786 done:
6787 free(initial_content);
6788 free(template);
6790 if (fd != -1 && close(fd) == -1 && err == NULL)
6791 err = got_error_from_errno2("close", a->logmsg_path);
6793 /* Editor is done; we can now apply unveil(2) */
6794 if (err == NULL)
6795 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6796 if (err) {
6797 free(*logmsg);
6798 *logmsg = NULL;
6800 return err;
6803 static const struct got_error *
6804 cmd_commit(int argc, char *argv[])
6806 const struct got_error *error = NULL;
6807 struct got_worktree *worktree = NULL;
6808 struct got_repository *repo = NULL;
6809 char *cwd = NULL, *id_str = NULL;
6810 struct got_object_id *id = NULL;
6811 const char *logmsg = NULL;
6812 struct collect_commit_logmsg_arg cl_arg;
6813 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6814 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6815 int allow_bad_symlinks = 0;
6816 struct got_pathlist_head paths;
6818 TAILQ_INIT(&paths);
6819 cl_arg.logmsg_path = NULL;
6821 while ((ch = getopt(argc, argv, "m:S")) != -1) {
6822 switch (ch) {
6823 case 'm':
6824 logmsg = optarg;
6825 break;
6826 case 'S':
6827 allow_bad_symlinks = 1;
6828 break;
6829 default:
6830 usage_commit();
6831 /* NOTREACHED */
6835 argc -= optind;
6836 argv += optind;
6838 #ifndef PROFILE
6839 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6840 "unveil", NULL) == -1)
6841 err(1, "pledge");
6842 #endif
6843 cwd = getcwd(NULL, 0);
6844 if (cwd == NULL) {
6845 error = got_error_from_errno("getcwd");
6846 goto done;
6848 error = got_worktree_open(&worktree, cwd);
6849 if (error) {
6850 if (error->code == GOT_ERR_NOT_WORKTREE)
6851 error = wrap_not_worktree_error(error, "commit", cwd);
6852 goto done;
6855 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6856 if (error)
6857 goto done;
6858 if (rebase_in_progress) {
6859 error = got_error(GOT_ERR_REBASING);
6860 goto done;
6863 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6864 worktree);
6865 if (error)
6866 goto done;
6868 error = get_gitconfig_path(&gitconfig_path);
6869 if (error)
6870 goto done;
6871 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6872 gitconfig_path);
6873 if (error != NULL)
6874 goto done;
6876 error = get_author(&author, repo, worktree);
6877 if (error)
6878 return error;
6881 * unveil(2) traverses exec(2); if an editor is used we have
6882 * to apply unveil after the log message has been written.
6884 if (logmsg == NULL || strlen(logmsg) == 0)
6885 error = get_editor(&editor);
6886 else
6887 error = apply_unveil(got_repo_get_path(repo), 0,
6888 got_worktree_get_root_path(worktree));
6889 if (error)
6890 goto done;
6892 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6893 if (error)
6894 goto done;
6896 cl_arg.editor = editor;
6897 cl_arg.cmdline_log = logmsg;
6898 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6899 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6900 if (!histedit_in_progress) {
6901 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6902 error = got_error(GOT_ERR_COMMIT_BRANCH);
6903 goto done;
6905 cl_arg.branch_name += 11;
6907 cl_arg.repo_path = got_repo_get_path(repo);
6908 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6909 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
6910 print_status, NULL, repo);
6911 if (error) {
6912 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6913 cl_arg.logmsg_path != NULL)
6914 preserve_logmsg = 1;
6915 goto done;
6918 error = got_object_id_str(&id_str, id);
6919 if (error)
6920 goto done;
6921 printf("Created commit %s\n", id_str);
6922 done:
6923 if (preserve_logmsg) {
6924 fprintf(stderr, "%s: log message preserved in %s\n",
6925 getprogname(), cl_arg.logmsg_path);
6926 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6927 error == NULL)
6928 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6929 free(cl_arg.logmsg_path);
6930 if (repo)
6931 got_repo_close(repo);
6932 if (worktree)
6933 got_worktree_close(worktree);
6934 free(cwd);
6935 free(id_str);
6936 free(gitconfig_path);
6937 free(editor);
6938 free(author);
6939 return error;
6942 __dead static void
6943 usage_cherrypick(void)
6945 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6946 exit(1);
6949 static const struct got_error *
6950 cmd_cherrypick(int argc, char *argv[])
6952 const struct got_error *error = NULL;
6953 struct got_worktree *worktree = NULL;
6954 struct got_repository *repo = NULL;
6955 char *cwd = NULL, *commit_id_str = NULL;
6956 struct got_object_id *commit_id = NULL;
6957 struct got_commit_object *commit = NULL;
6958 struct got_object_qid *pid;
6959 struct got_reference *head_ref = NULL;
6960 int ch;
6961 struct got_update_progress_arg upa;
6963 while ((ch = getopt(argc, argv, "")) != -1) {
6964 switch (ch) {
6965 default:
6966 usage_cherrypick();
6967 /* NOTREACHED */
6971 argc -= optind;
6972 argv += optind;
6974 #ifndef PROFILE
6975 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6976 "unveil", NULL) == -1)
6977 err(1, "pledge");
6978 #endif
6979 if (argc != 1)
6980 usage_cherrypick();
6982 cwd = getcwd(NULL, 0);
6983 if (cwd == NULL) {
6984 error = got_error_from_errno("getcwd");
6985 goto done;
6987 error = got_worktree_open(&worktree, cwd);
6988 if (error) {
6989 if (error->code == GOT_ERR_NOT_WORKTREE)
6990 error = wrap_not_worktree_error(error, "cherrypick",
6991 cwd);
6992 goto done;
6995 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6996 NULL);
6997 if (error != NULL)
6998 goto done;
7000 error = apply_unveil(got_repo_get_path(repo), 0,
7001 got_worktree_get_root_path(worktree));
7002 if (error)
7003 goto done;
7005 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7006 GOT_OBJ_TYPE_COMMIT, repo);
7007 if (error != NULL) {
7008 struct got_reference *ref;
7009 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7010 goto done;
7011 error = got_ref_open(&ref, repo, argv[0], 0);
7012 if (error != NULL)
7013 goto done;
7014 error = got_ref_resolve(&commit_id, repo, ref);
7015 got_ref_close(ref);
7016 if (error != NULL)
7017 goto done;
7019 error = got_object_id_str(&commit_id_str, commit_id);
7020 if (error)
7021 goto done;
7023 error = got_ref_open(&head_ref, repo,
7024 got_worktree_get_head_ref_name(worktree), 0);
7025 if (error != NULL)
7026 goto done;
7028 error = check_same_branch(commit_id, head_ref, NULL, repo);
7029 if (error) {
7030 if (error->code != GOT_ERR_ANCESTRY)
7031 goto done;
7032 error = NULL;
7033 } else {
7034 error = got_error(GOT_ERR_SAME_BRANCH);
7035 goto done;
7038 error = got_object_open_as_commit(&commit, repo, commit_id);
7039 if (error)
7040 goto done;
7041 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7042 memset(&upa, 0, sizeof(upa));
7043 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
7044 commit_id, repo, update_progress, &upa, check_cancelled,
7045 NULL);
7046 if (error != NULL)
7047 goto done;
7049 if (upa.did_something)
7050 printf("Merged commit %s\n", commit_id_str);
7051 print_update_progress_stats(&upa);
7052 done:
7053 if (commit)
7054 got_object_commit_close(commit);
7055 free(commit_id_str);
7056 if (head_ref)
7057 got_ref_close(head_ref);
7058 if (worktree)
7059 got_worktree_close(worktree);
7060 if (repo)
7061 got_repo_close(repo);
7062 return error;
7065 __dead static void
7066 usage_backout(void)
7068 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
7069 exit(1);
7072 static const struct got_error *
7073 cmd_backout(int argc, char *argv[])
7075 const struct got_error *error = NULL;
7076 struct got_worktree *worktree = NULL;
7077 struct got_repository *repo = NULL;
7078 char *cwd = NULL, *commit_id_str = NULL;
7079 struct got_object_id *commit_id = NULL;
7080 struct got_commit_object *commit = NULL;
7081 struct got_object_qid *pid;
7082 struct got_reference *head_ref = NULL;
7083 int ch;
7084 struct got_update_progress_arg upa;
7086 while ((ch = getopt(argc, argv, "")) != -1) {
7087 switch (ch) {
7088 default:
7089 usage_backout();
7090 /* NOTREACHED */
7094 argc -= optind;
7095 argv += optind;
7097 #ifndef PROFILE
7098 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7099 "unveil", NULL) == -1)
7100 err(1, "pledge");
7101 #endif
7102 if (argc != 1)
7103 usage_backout();
7105 cwd = getcwd(NULL, 0);
7106 if (cwd == NULL) {
7107 error = got_error_from_errno("getcwd");
7108 goto done;
7110 error = got_worktree_open(&worktree, cwd);
7111 if (error) {
7112 if (error->code == GOT_ERR_NOT_WORKTREE)
7113 error = wrap_not_worktree_error(error, "backout", cwd);
7114 goto done;
7117 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7118 NULL);
7119 if (error != NULL)
7120 goto done;
7122 error = apply_unveil(got_repo_get_path(repo), 0,
7123 got_worktree_get_root_path(worktree));
7124 if (error)
7125 goto done;
7127 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7128 GOT_OBJ_TYPE_COMMIT, repo);
7129 if (error != NULL) {
7130 struct got_reference *ref;
7131 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7132 goto done;
7133 error = got_ref_open(&ref, repo, argv[0], 0);
7134 if (error != NULL)
7135 goto done;
7136 error = got_ref_resolve(&commit_id, repo, ref);
7137 got_ref_close(ref);
7138 if (error != NULL)
7139 goto done;
7141 error = got_object_id_str(&commit_id_str, commit_id);
7142 if (error)
7143 goto done;
7145 error = got_ref_open(&head_ref, repo,
7146 got_worktree_get_head_ref_name(worktree), 0);
7147 if (error != NULL)
7148 goto done;
7150 error = check_same_branch(commit_id, head_ref, NULL, repo);
7151 if (error)
7152 goto done;
7154 error = got_object_open_as_commit(&commit, repo, commit_id);
7155 if (error)
7156 goto done;
7157 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7158 if (pid == NULL) {
7159 error = got_error(GOT_ERR_ROOT_COMMIT);
7160 goto done;
7163 memset(&upa, 0, sizeof(upa));
7164 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
7165 update_progress, &upa, check_cancelled, NULL);
7166 if (error != NULL)
7167 goto done;
7169 if (upa.did_something)
7170 printf("Backed out commit %s\n", commit_id_str);
7171 print_update_progress_stats(&upa);
7172 done:
7173 if (commit)
7174 got_object_commit_close(commit);
7175 free(commit_id_str);
7176 if (head_ref)
7177 got_ref_close(head_ref);
7178 if (worktree)
7179 got_worktree_close(worktree);
7180 if (repo)
7181 got_repo_close(repo);
7182 return error;
7185 __dead static void
7186 usage_rebase(void)
7188 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
7189 getprogname());
7190 exit(1);
7193 void
7194 trim_logmsg(char *logmsg, int limit)
7196 char *nl;
7197 size_t len;
7199 len = strlen(logmsg);
7200 if (len > limit)
7201 len = limit;
7202 logmsg[len] = '\0';
7203 nl = strchr(logmsg, '\n');
7204 if (nl)
7205 *nl = '\0';
7208 static const struct got_error *
7209 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
7211 const struct got_error *err;
7212 char *logmsg0 = NULL;
7213 const char *s;
7215 err = got_object_commit_get_logmsg(&logmsg0, commit);
7216 if (err)
7217 return err;
7219 s = logmsg0;
7220 while (isspace((unsigned char)s[0]))
7221 s++;
7223 *logmsg = strdup(s);
7224 if (*logmsg == NULL) {
7225 err = got_error_from_errno("strdup");
7226 goto done;
7229 trim_logmsg(*logmsg, limit);
7230 done:
7231 free(logmsg0);
7232 return err;
7235 static const struct got_error *
7236 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
7238 const struct got_error *err;
7239 struct got_commit_object *commit = NULL;
7240 char *id_str = NULL, *logmsg = NULL;
7242 err = got_object_open_as_commit(&commit, repo, id);
7243 if (err)
7244 return err;
7246 err = got_object_id_str(&id_str, id);
7247 if (err)
7248 goto done;
7250 id_str[12] = '\0';
7252 err = get_short_logmsg(&logmsg, 42, commit);
7253 if (err)
7254 goto done;
7256 printf("%s -> merge conflict: %s\n", id_str, logmsg);
7257 done:
7258 free(id_str);
7259 got_object_commit_close(commit);
7260 free(logmsg);
7261 return err;
7264 static const struct got_error *
7265 show_rebase_progress(struct got_commit_object *commit,
7266 struct got_object_id *old_id, struct got_object_id *new_id)
7268 const struct got_error *err;
7269 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7271 err = got_object_id_str(&old_id_str, old_id);
7272 if (err)
7273 goto done;
7275 if (new_id) {
7276 err = got_object_id_str(&new_id_str, new_id);
7277 if (err)
7278 goto done;
7281 old_id_str[12] = '\0';
7282 if (new_id_str)
7283 new_id_str[12] = '\0';
7285 err = get_short_logmsg(&logmsg, 42, commit);
7286 if (err)
7287 goto done;
7289 printf("%s -> %s: %s\n", old_id_str,
7290 new_id_str ? new_id_str : "no-op change", logmsg);
7291 done:
7292 free(old_id_str);
7293 free(new_id_str);
7294 free(logmsg);
7295 return err;
7298 static const struct got_error *
7299 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
7300 struct got_reference *branch, struct got_reference *new_base_branch,
7301 struct got_reference *tmp_branch, struct got_repository *repo)
7303 printf("Switching work tree to %s\n", got_ref_get_name(branch));
7304 return got_worktree_rebase_complete(worktree, fileindex,
7305 new_base_branch, tmp_branch, branch, repo);
7308 static const struct got_error *
7309 rebase_commit(struct got_pathlist_head *merged_paths,
7310 struct got_worktree *worktree, struct got_fileindex *fileindex,
7311 struct got_reference *tmp_branch,
7312 struct got_object_id *commit_id, struct got_repository *repo)
7314 const struct got_error *error;
7315 struct got_commit_object *commit;
7316 struct got_object_id *new_commit_id;
7318 error = got_object_open_as_commit(&commit, repo, commit_id);
7319 if (error)
7320 return error;
7322 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
7323 worktree, fileindex, tmp_branch, commit, commit_id, repo);
7324 if (error) {
7325 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
7326 goto done;
7327 error = show_rebase_progress(commit, commit_id, NULL);
7328 } else {
7329 error = show_rebase_progress(commit, commit_id, new_commit_id);
7330 free(new_commit_id);
7332 done:
7333 got_object_commit_close(commit);
7334 return error;
7337 struct check_path_prefix_arg {
7338 const char *path_prefix;
7339 size_t len;
7340 int errcode;
7343 static const struct got_error *
7344 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
7345 struct got_blob_object *blob2, struct got_object_id *id1,
7346 struct got_object_id *id2, const char *path1, const char *path2,
7347 mode_t mode1, mode_t mode2, struct got_repository *repo)
7349 struct check_path_prefix_arg *a = arg;
7351 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
7352 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
7353 return got_error(a->errcode);
7355 return NULL;
7358 static const struct got_error *
7359 check_path_prefix(struct got_object_id *parent_id,
7360 struct got_object_id *commit_id, const char *path_prefix,
7361 int errcode, struct got_repository *repo)
7363 const struct got_error *err;
7364 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7365 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7366 struct check_path_prefix_arg cpp_arg;
7368 if (got_path_is_root_dir(path_prefix))
7369 return NULL;
7371 err = got_object_open_as_commit(&commit, repo, commit_id);
7372 if (err)
7373 goto done;
7375 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7376 if (err)
7377 goto done;
7379 err = got_object_open_as_tree(&tree1, repo,
7380 got_object_commit_get_tree_id(parent_commit));
7381 if (err)
7382 goto done;
7384 err = got_object_open_as_tree(&tree2, repo,
7385 got_object_commit_get_tree_id(commit));
7386 if (err)
7387 goto done;
7389 cpp_arg.path_prefix = path_prefix;
7390 while (cpp_arg.path_prefix[0] == '/')
7391 cpp_arg.path_prefix++;
7392 cpp_arg.len = strlen(cpp_arg.path_prefix);
7393 cpp_arg.errcode = errcode;
7394 err = got_diff_tree(tree1, tree2, "", "", repo,
7395 check_path_prefix_in_diff, &cpp_arg, 0);
7396 done:
7397 if (tree1)
7398 got_object_tree_close(tree1);
7399 if (tree2)
7400 got_object_tree_close(tree2);
7401 if (commit)
7402 got_object_commit_close(commit);
7403 if (parent_commit)
7404 got_object_commit_close(parent_commit);
7405 return err;
7408 static const struct got_error *
7409 collect_commits(struct got_object_id_queue *commits,
7410 struct got_object_id *initial_commit_id,
7411 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7412 const char *path_prefix, int path_prefix_errcode,
7413 struct got_repository *repo)
7415 const struct got_error *err = NULL;
7416 struct got_commit_graph *graph = NULL;
7417 struct got_object_id *parent_id = NULL;
7418 struct got_object_qid *qid;
7419 struct got_object_id *commit_id = initial_commit_id;
7421 err = got_commit_graph_open(&graph, "/", 1);
7422 if (err)
7423 return err;
7425 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7426 check_cancelled, NULL);
7427 if (err)
7428 goto done;
7429 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7430 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7431 check_cancelled, NULL);
7432 if (err) {
7433 if (err->code == GOT_ERR_ITER_COMPLETED) {
7434 err = got_error_msg(GOT_ERR_ANCESTRY,
7435 "ran out of commits to rebase before "
7436 "youngest common ancestor commit has "
7437 "been reached?!?");
7439 goto done;
7440 } else {
7441 err = check_path_prefix(parent_id, commit_id,
7442 path_prefix, path_prefix_errcode, repo);
7443 if (err)
7444 goto done;
7446 err = got_object_qid_alloc(&qid, commit_id);
7447 if (err)
7448 goto done;
7449 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
7450 commit_id = parent_id;
7453 done:
7454 got_commit_graph_close(graph);
7455 return err;
7458 static const struct got_error *
7459 cmd_rebase(int argc, char *argv[])
7461 const struct got_error *error = NULL;
7462 struct got_worktree *worktree = NULL;
7463 struct got_repository *repo = NULL;
7464 struct got_fileindex *fileindex = NULL;
7465 char *cwd = NULL;
7466 struct got_reference *branch = NULL;
7467 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
7468 struct got_object_id *commit_id = NULL, *parent_id = NULL;
7469 struct got_object_id *resume_commit_id = NULL;
7470 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
7471 struct got_commit_object *commit = NULL;
7472 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
7473 int histedit_in_progress = 0;
7474 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7475 struct got_object_id_queue commits;
7476 struct got_pathlist_head merged_paths;
7477 const struct got_object_id_queue *parent_ids;
7478 struct got_object_qid *qid, *pid;
7480 SIMPLEQ_INIT(&commits);
7481 TAILQ_INIT(&merged_paths);
7483 while ((ch = getopt(argc, argv, "ac")) != -1) {
7484 switch (ch) {
7485 case 'a':
7486 abort_rebase = 1;
7487 break;
7488 case 'c':
7489 continue_rebase = 1;
7490 break;
7491 default:
7492 usage_rebase();
7493 /* NOTREACHED */
7497 argc -= optind;
7498 argv += optind;
7500 #ifndef PROFILE
7501 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7502 "unveil", NULL) == -1)
7503 err(1, "pledge");
7504 #endif
7505 if (abort_rebase && continue_rebase)
7506 usage_rebase();
7507 else if (abort_rebase || continue_rebase) {
7508 if (argc != 0)
7509 usage_rebase();
7510 } else if (argc != 1)
7511 usage_rebase();
7513 cwd = getcwd(NULL, 0);
7514 if (cwd == NULL) {
7515 error = got_error_from_errno("getcwd");
7516 goto done;
7518 error = got_worktree_open(&worktree, cwd);
7519 if (error) {
7520 if (error->code == GOT_ERR_NOT_WORKTREE)
7521 error = wrap_not_worktree_error(error, "rebase", cwd);
7522 goto done;
7525 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7526 NULL);
7527 if (error != NULL)
7528 goto done;
7530 error = apply_unveil(got_repo_get_path(repo), 0,
7531 got_worktree_get_root_path(worktree));
7532 if (error)
7533 goto done;
7535 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7536 worktree);
7537 if (error)
7538 goto done;
7539 if (histedit_in_progress) {
7540 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7541 goto done;
7544 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7545 if (error)
7546 goto done;
7548 if (abort_rebase) {
7549 struct got_update_progress_arg upa;
7550 if (!rebase_in_progress) {
7551 error = got_error(GOT_ERR_NOT_REBASING);
7552 goto done;
7554 error = got_worktree_rebase_continue(&resume_commit_id,
7555 &new_base_branch, &tmp_branch, &branch, &fileindex,
7556 worktree, repo);
7557 if (error)
7558 goto done;
7559 printf("Switching work tree to %s\n",
7560 got_ref_get_symref_target(new_base_branch));
7561 memset(&upa, 0, sizeof(upa));
7562 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7563 new_base_branch, update_progress, &upa);
7564 if (error)
7565 goto done;
7566 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7567 print_update_progress_stats(&upa);
7568 goto done; /* nothing else to do */
7571 if (continue_rebase) {
7572 if (!rebase_in_progress) {
7573 error = got_error(GOT_ERR_NOT_REBASING);
7574 goto done;
7576 error = got_worktree_rebase_continue(&resume_commit_id,
7577 &new_base_branch, &tmp_branch, &branch, &fileindex,
7578 worktree, repo);
7579 if (error)
7580 goto done;
7582 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7583 resume_commit_id, repo);
7584 if (error)
7585 goto done;
7587 yca_id = got_object_id_dup(resume_commit_id);
7588 if (yca_id == NULL) {
7589 error = got_error_from_errno("got_object_id_dup");
7590 goto done;
7592 } else {
7593 error = got_ref_open(&branch, repo, argv[0], 0);
7594 if (error != NULL)
7595 goto done;
7598 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7599 if (error)
7600 goto done;
7602 if (!continue_rebase) {
7603 struct got_object_id *base_commit_id;
7605 base_commit_id = got_worktree_get_base_commit_id(worktree);
7606 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7607 base_commit_id, branch_head_commit_id, repo,
7608 check_cancelled, NULL);
7609 if (error)
7610 goto done;
7611 if (yca_id == NULL) {
7612 error = got_error_msg(GOT_ERR_ANCESTRY,
7613 "specified branch shares no common ancestry "
7614 "with work tree's branch");
7615 goto done;
7618 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7619 if (error) {
7620 if (error->code != GOT_ERR_ANCESTRY)
7621 goto done;
7622 error = NULL;
7623 } else {
7624 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7625 "specified branch resolves to a commit which "
7626 "is already contained in work tree's branch");
7627 goto done;
7629 error = got_worktree_rebase_prepare(&new_base_branch,
7630 &tmp_branch, &fileindex, worktree, branch, repo);
7631 if (error)
7632 goto done;
7635 commit_id = branch_head_commit_id;
7636 error = got_object_open_as_commit(&commit, repo, commit_id);
7637 if (error)
7638 goto done;
7640 parent_ids = got_object_commit_get_parent_ids(commit);
7641 pid = SIMPLEQ_FIRST(parent_ids);
7642 if (pid == NULL) {
7643 if (!continue_rebase) {
7644 struct got_update_progress_arg upa;
7645 memset(&upa, 0, sizeof(upa));
7646 error = got_worktree_rebase_abort(worktree, fileindex,
7647 repo, new_base_branch, update_progress, &upa);
7648 if (error)
7649 goto done;
7650 printf("Rebase of %s aborted\n",
7651 got_ref_get_name(branch));
7652 print_update_progress_stats(&upa);
7655 error = got_error(GOT_ERR_EMPTY_REBASE);
7656 goto done;
7658 error = collect_commits(&commits, commit_id, pid->id,
7659 yca_id, got_worktree_get_path_prefix(worktree),
7660 GOT_ERR_REBASE_PATH, repo);
7661 got_object_commit_close(commit);
7662 commit = NULL;
7663 if (error)
7664 goto done;
7666 if (SIMPLEQ_EMPTY(&commits)) {
7667 if (continue_rebase) {
7668 error = rebase_complete(worktree, fileindex,
7669 branch, new_base_branch, tmp_branch, repo);
7670 goto done;
7671 } else {
7672 /* Fast-forward the reference of the branch. */
7673 struct got_object_id *new_head_commit_id;
7674 char *id_str;
7675 error = got_ref_resolve(&new_head_commit_id, repo,
7676 new_base_branch);
7677 if (error)
7678 goto done;
7679 error = got_object_id_str(&id_str, new_head_commit_id);
7680 printf("Forwarding %s to commit %s\n",
7681 got_ref_get_name(branch), id_str);
7682 free(id_str);
7683 error = got_ref_change_ref(branch,
7684 new_head_commit_id);
7685 if (error)
7686 goto done;
7690 pid = NULL;
7691 SIMPLEQ_FOREACH(qid, &commits, entry) {
7692 struct got_update_progress_arg upa;
7694 commit_id = qid->id;
7695 parent_id = pid ? pid->id : yca_id;
7696 pid = qid;
7698 memset(&upa, 0, sizeof(upa));
7699 error = got_worktree_rebase_merge_files(&merged_paths,
7700 worktree, fileindex, parent_id, commit_id, repo,
7701 update_progress, &upa, check_cancelled, NULL);
7702 if (error)
7703 goto done;
7705 print_update_progress_stats(&upa);
7706 if (upa.conflicts > 0)
7707 rebase_status = GOT_STATUS_CONFLICT;
7709 if (rebase_status == GOT_STATUS_CONFLICT) {
7710 error = show_rebase_merge_conflict(qid->id, repo);
7711 if (error)
7712 goto done;
7713 got_worktree_rebase_pathlist_free(&merged_paths);
7714 break;
7717 error = rebase_commit(&merged_paths, worktree, fileindex,
7718 tmp_branch, commit_id, repo);
7719 got_worktree_rebase_pathlist_free(&merged_paths);
7720 if (error)
7721 goto done;
7724 if (rebase_status == GOT_STATUS_CONFLICT) {
7725 error = got_worktree_rebase_postpone(worktree, fileindex);
7726 if (error)
7727 goto done;
7728 error = got_error_msg(GOT_ERR_CONFLICTS,
7729 "conflicts must be resolved before rebasing can continue");
7730 } else
7731 error = rebase_complete(worktree, fileindex, branch,
7732 new_base_branch, tmp_branch, repo);
7733 done:
7734 got_object_id_queue_free(&commits);
7735 free(branch_head_commit_id);
7736 free(resume_commit_id);
7737 free(yca_id);
7738 if (commit)
7739 got_object_commit_close(commit);
7740 if (branch)
7741 got_ref_close(branch);
7742 if (new_base_branch)
7743 got_ref_close(new_base_branch);
7744 if (tmp_branch)
7745 got_ref_close(tmp_branch);
7746 if (worktree)
7747 got_worktree_close(worktree);
7748 if (repo)
7749 got_repo_close(repo);
7750 return error;
7753 __dead static void
7754 usage_histedit(void)
7756 fprintf(stderr, "usage: %s histedit [-a] [-c] [-f] [-F histedit-script] [-m]\n",
7757 getprogname());
7758 exit(1);
7761 #define GOT_HISTEDIT_PICK 'p'
7762 #define GOT_HISTEDIT_EDIT 'e'
7763 #define GOT_HISTEDIT_FOLD 'f'
7764 #define GOT_HISTEDIT_DROP 'd'
7765 #define GOT_HISTEDIT_MESG 'm'
7767 static struct got_histedit_cmd {
7768 unsigned char code;
7769 const char *name;
7770 const char *desc;
7771 } got_histedit_cmds[] = {
7772 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7773 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7774 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7775 "be used" },
7776 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7777 { GOT_HISTEDIT_MESG, "mesg",
7778 "single-line log message for commit above (open editor if empty)" },
7781 struct got_histedit_list_entry {
7782 TAILQ_ENTRY(got_histedit_list_entry) entry;
7783 struct got_object_id *commit_id;
7784 const struct got_histedit_cmd *cmd;
7785 char *logmsg;
7787 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7789 static const struct got_error *
7790 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7791 FILE *f, struct got_repository *repo)
7793 const struct got_error *err = NULL;
7794 char *logmsg = NULL, *id_str = NULL;
7795 struct got_commit_object *commit = NULL;
7796 int n;
7798 err = got_object_open_as_commit(&commit, repo, commit_id);
7799 if (err)
7800 goto done;
7802 err = get_short_logmsg(&logmsg, 34, commit);
7803 if (err)
7804 goto done;
7806 err = got_object_id_str(&id_str, commit_id);
7807 if (err)
7808 goto done;
7810 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7811 if (n < 0)
7812 err = got_ferror(f, GOT_ERR_IO);
7813 done:
7814 if (commit)
7815 got_object_commit_close(commit);
7816 free(id_str);
7817 free(logmsg);
7818 return err;
7821 static const struct got_error *
7822 histedit_write_commit_list(struct got_object_id_queue *commits,
7823 FILE *f, int edit_logmsg_only, int fold_only, struct got_repository *repo)
7825 const struct got_error *err = NULL;
7826 struct got_object_qid *qid;
7827 const char *histedit_cmd = NULL;
7829 if (SIMPLEQ_EMPTY(commits))
7830 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7832 SIMPLEQ_FOREACH(qid, commits, entry) {
7833 histedit_cmd = got_histedit_cmds[0].name;
7834 if (fold_only && SIMPLEQ_NEXT(qid, entry) != NULL)
7835 histedit_cmd = "fold";
7836 err = histedit_write_commit(qid->id, histedit_cmd, f, repo);
7837 if (err)
7838 break;
7839 if (edit_logmsg_only) {
7840 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7841 if (n < 0) {
7842 err = got_ferror(f, GOT_ERR_IO);
7843 break;
7848 return err;
7851 static const struct got_error *
7852 write_cmd_list(FILE *f, const char *branch_name,
7853 struct got_object_id_queue *commits)
7855 const struct got_error *err = NULL;
7856 int n, i;
7857 char *id_str;
7858 struct got_object_qid *qid;
7860 qid = SIMPLEQ_FIRST(commits);
7861 err = got_object_id_str(&id_str, qid->id);
7862 if (err)
7863 return err;
7865 n = fprintf(f,
7866 "# Editing the history of branch '%s' starting at\n"
7867 "# commit %s\n"
7868 "# Commits will be processed in order from top to "
7869 "bottom of this file.\n", branch_name, id_str);
7870 if (n < 0) {
7871 err = got_ferror(f, GOT_ERR_IO);
7872 goto done;
7875 n = fprintf(f, "# Available histedit commands:\n");
7876 if (n < 0) {
7877 err = got_ferror(f, GOT_ERR_IO);
7878 goto done;
7881 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7882 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7883 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7884 cmd->desc);
7885 if (n < 0) {
7886 err = got_ferror(f, GOT_ERR_IO);
7887 break;
7890 done:
7891 free(id_str);
7892 return err;
7895 static const struct got_error *
7896 histedit_syntax_error(int lineno)
7898 static char msg[42];
7899 int ret;
7901 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7902 lineno);
7903 if (ret == -1 || ret >= sizeof(msg))
7904 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7906 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7909 static const struct got_error *
7910 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7911 char *logmsg, struct got_repository *repo)
7913 const struct got_error *err;
7914 struct got_commit_object *folded_commit = NULL;
7915 char *id_str, *folded_logmsg = NULL;
7917 err = got_object_id_str(&id_str, hle->commit_id);
7918 if (err)
7919 return err;
7921 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7922 if (err)
7923 goto done;
7925 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7926 if (err)
7927 goto done;
7928 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7929 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7930 folded_logmsg) == -1) {
7931 err = got_error_from_errno("asprintf");
7933 done:
7934 if (folded_commit)
7935 got_object_commit_close(folded_commit);
7936 free(id_str);
7937 free(folded_logmsg);
7938 return err;
7941 static struct got_histedit_list_entry *
7942 get_folded_commits(struct got_histedit_list_entry *hle)
7944 struct got_histedit_list_entry *prev, *folded = NULL;
7946 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7947 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7948 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7949 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7950 folded = prev;
7951 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7954 return folded;
7957 static const struct got_error *
7958 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7959 struct got_repository *repo)
7961 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7962 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7963 const struct got_error *err = NULL;
7964 struct got_commit_object *commit = NULL;
7965 int logmsg_len;
7966 int fd;
7967 struct got_histedit_list_entry *folded = NULL;
7969 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7970 if (err)
7971 return err;
7973 folded = get_folded_commits(hle);
7974 if (folded) {
7975 while (folded != hle) {
7976 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7977 folded = TAILQ_NEXT(folded, entry);
7978 continue;
7980 err = append_folded_commit_msg(&new_msg, folded,
7981 logmsg, repo);
7982 if (err)
7983 goto done;
7984 free(logmsg);
7985 logmsg = new_msg;
7986 folded = TAILQ_NEXT(folded, entry);
7990 err = got_object_id_str(&id_str, hle->commit_id);
7991 if (err)
7992 goto done;
7993 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7994 if (err)
7995 goto done;
7996 logmsg_len = asprintf(&new_msg,
7997 "%s\n# original log message of commit %s: %s",
7998 logmsg ? logmsg : "", id_str, orig_logmsg);
7999 if (logmsg_len == -1) {
8000 err = got_error_from_errno("asprintf");
8001 goto done;
8003 free(logmsg);
8004 logmsg = new_msg;
8006 err = got_object_id_str(&id_str, hle->commit_id);
8007 if (err)
8008 goto done;
8010 err = got_opentemp_named_fd(&logmsg_path, &fd,
8011 GOT_TMPDIR_STR "/got-logmsg");
8012 if (err)
8013 goto done;
8015 write(fd, logmsg, logmsg_len);
8016 close(fd);
8018 err = get_editor(&editor);
8019 if (err)
8020 goto done;
8022 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
8023 logmsg_len);
8024 if (err) {
8025 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
8026 goto done;
8027 err = NULL;
8028 hle->logmsg = strdup(new_msg);
8029 if (hle->logmsg == NULL)
8030 err = got_error_from_errno("strdup");
8032 done:
8033 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
8034 err = got_error_from_errno2("unlink", logmsg_path);
8035 free(logmsg_path);
8036 free(logmsg);
8037 free(orig_logmsg);
8038 free(editor);
8039 if (commit)
8040 got_object_commit_close(commit);
8041 return err;
8044 static const struct got_error *
8045 histedit_parse_list(struct got_histedit_list *histedit_cmds,
8046 FILE *f, struct got_repository *repo)
8048 const struct got_error *err = NULL;
8049 char *line = NULL, *p, *end;
8050 size_t size;
8051 ssize_t len;
8052 int lineno = 0, i;
8053 const struct got_histedit_cmd *cmd;
8054 struct got_object_id *commit_id = NULL;
8055 struct got_histedit_list_entry *hle = NULL;
8057 for (;;) {
8058 len = getline(&line, &size, f);
8059 if (len == -1) {
8060 const struct got_error *getline_err;
8061 if (feof(f))
8062 break;
8063 getline_err = got_error_from_errno("getline");
8064 err = got_ferror(f, getline_err->code);
8065 break;
8067 lineno++;
8068 p = line;
8069 while (isspace((unsigned char)p[0]))
8070 p++;
8071 if (p[0] == '#' || p[0] == '\0') {
8072 free(line);
8073 line = NULL;
8074 continue;
8076 cmd = NULL;
8077 for (i = 0; i < nitems(got_histedit_cmds); i++) {
8078 cmd = &got_histedit_cmds[i];
8079 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
8080 isspace((unsigned char)p[strlen(cmd->name)])) {
8081 p += strlen(cmd->name);
8082 break;
8084 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
8085 p++;
8086 break;
8089 if (i == nitems(got_histedit_cmds)) {
8090 err = histedit_syntax_error(lineno);
8091 break;
8093 while (isspace((unsigned char)p[0]))
8094 p++;
8095 if (cmd->code == GOT_HISTEDIT_MESG) {
8096 if (hle == NULL || hle->logmsg != NULL) {
8097 err = got_error(GOT_ERR_HISTEDIT_CMD);
8098 break;
8100 if (p[0] == '\0') {
8101 err = histedit_edit_logmsg(hle, repo);
8102 if (err)
8103 break;
8104 } else {
8105 hle->logmsg = strdup(p);
8106 if (hle->logmsg == NULL) {
8107 err = got_error_from_errno("strdup");
8108 break;
8111 free(line);
8112 line = NULL;
8113 continue;
8114 } else {
8115 end = p;
8116 while (end[0] && !isspace((unsigned char)end[0]))
8117 end++;
8118 *end = '\0';
8120 err = got_object_resolve_id_str(&commit_id, repo, p);
8121 if (err) {
8122 /* override error code */
8123 err = histedit_syntax_error(lineno);
8124 break;
8127 hle = malloc(sizeof(*hle));
8128 if (hle == NULL) {
8129 err = got_error_from_errno("malloc");
8130 break;
8132 hle->cmd = cmd;
8133 hle->commit_id = commit_id;
8134 hle->logmsg = NULL;
8135 commit_id = NULL;
8136 free(line);
8137 line = NULL;
8138 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
8141 free(line);
8142 free(commit_id);
8143 return err;
8146 static const struct got_error *
8147 histedit_check_script(struct got_histedit_list *histedit_cmds,
8148 struct got_object_id_queue *commits, struct got_repository *repo)
8150 const struct got_error *err = NULL;
8151 struct got_object_qid *qid;
8152 struct got_histedit_list_entry *hle;
8153 static char msg[92];
8154 char *id_str;
8156 if (TAILQ_EMPTY(histedit_cmds))
8157 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
8158 "histedit script contains no commands");
8159 if (SIMPLEQ_EMPTY(commits))
8160 return got_error(GOT_ERR_EMPTY_HISTEDIT);
8162 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8163 struct got_histedit_list_entry *hle2;
8164 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
8165 if (hle == hle2)
8166 continue;
8167 if (got_object_id_cmp(hle->commit_id,
8168 hle2->commit_id) != 0)
8169 continue;
8170 err = got_object_id_str(&id_str, hle->commit_id);
8171 if (err)
8172 return err;
8173 snprintf(msg, sizeof(msg), "commit %s is listed "
8174 "more than once in histedit script", id_str);
8175 free(id_str);
8176 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8180 SIMPLEQ_FOREACH(qid, commits, entry) {
8181 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8182 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
8183 break;
8185 if (hle == NULL) {
8186 err = got_object_id_str(&id_str, qid->id);
8187 if (err)
8188 return err;
8189 snprintf(msg, sizeof(msg),
8190 "commit %s missing from histedit script", id_str);
8191 free(id_str);
8192 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8196 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
8197 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
8198 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
8199 "last commit in histedit script cannot be folded");
8201 return NULL;
8204 static const struct got_error *
8205 histedit_run_editor(struct got_histedit_list *histedit_cmds,
8206 const char *path, struct got_object_id_queue *commits,
8207 struct got_repository *repo)
8209 const struct got_error *err = NULL;
8210 char *editor;
8211 FILE *f = NULL;
8213 err = get_editor(&editor);
8214 if (err)
8215 return err;
8217 if (spawn_editor(editor, path) == -1) {
8218 err = got_error_from_errno("failed spawning editor");
8219 goto done;
8222 f = fopen(path, "r");
8223 if (f == NULL) {
8224 err = got_error_from_errno("fopen");
8225 goto done;
8227 err = histedit_parse_list(histedit_cmds, f, repo);
8228 if (err)
8229 goto done;
8231 err = histedit_check_script(histedit_cmds, commits, repo);
8232 done:
8233 if (f && fclose(f) != 0 && err == NULL)
8234 err = got_error_from_errno("fclose");
8235 free(editor);
8236 return err;
8239 static const struct got_error *
8240 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
8241 struct got_object_id_queue *, const char *, const char *,
8242 struct got_repository *);
8244 static const struct got_error *
8245 histedit_edit_script(struct got_histedit_list *histedit_cmds,
8246 struct got_object_id_queue *commits, const char *branch_name,
8247 int edit_logmsg_only, int fold_only, struct got_repository *repo)
8249 const struct got_error *err;
8250 FILE *f = NULL;
8251 char *path = NULL;
8253 err = got_opentemp_named(&path, &f, "got-histedit");
8254 if (err)
8255 return err;
8257 err = write_cmd_list(f, branch_name, commits);
8258 if (err)
8259 goto done;
8261 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
8262 fold_only, repo);
8263 if (err)
8264 goto done;
8266 if (edit_logmsg_only || fold_only) {
8267 rewind(f);
8268 err = histedit_parse_list(histedit_cmds, f, repo);
8269 } else {
8270 if (fclose(f) != 0) {
8271 err = got_error_from_errno("fclose");
8272 goto done;
8274 f = NULL;
8275 err = histedit_run_editor(histedit_cmds, path, commits, repo);
8276 if (err) {
8277 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8278 err->code != GOT_ERR_HISTEDIT_CMD)
8279 goto done;
8280 err = histedit_edit_list_retry(histedit_cmds, err,
8281 commits, path, branch_name, repo);
8284 done:
8285 if (f && fclose(f) != 0 && err == NULL)
8286 err = got_error_from_errno("fclose");
8287 if (path && unlink(path) != 0 && err == NULL)
8288 err = got_error_from_errno2("unlink", path);
8289 free(path);
8290 return err;
8293 static const struct got_error *
8294 histedit_save_list(struct got_histedit_list *histedit_cmds,
8295 struct got_worktree *worktree, struct got_repository *repo)
8297 const struct got_error *err = NULL;
8298 char *path = NULL;
8299 FILE *f = NULL;
8300 struct got_histedit_list_entry *hle;
8301 struct got_commit_object *commit = NULL;
8303 err = got_worktree_get_histedit_script_path(&path, worktree);
8304 if (err)
8305 return err;
8307 f = fopen(path, "w");
8308 if (f == NULL) {
8309 err = got_error_from_errno2("fopen", path);
8310 goto done;
8312 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8313 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
8314 repo);
8315 if (err)
8316 break;
8318 if (hle->logmsg) {
8319 int n = fprintf(f, "%c %s\n",
8320 GOT_HISTEDIT_MESG, hle->logmsg);
8321 if (n < 0) {
8322 err = got_ferror(f, GOT_ERR_IO);
8323 break;
8327 done:
8328 if (f && fclose(f) != 0 && err == NULL)
8329 err = got_error_from_errno("fclose");
8330 free(path);
8331 if (commit)
8332 got_object_commit_close(commit);
8333 return err;
8336 void
8337 histedit_free_list(struct got_histedit_list *histedit_cmds)
8339 struct got_histedit_list_entry *hle;
8341 while ((hle = TAILQ_FIRST(histedit_cmds))) {
8342 TAILQ_REMOVE(histedit_cmds, hle, entry);
8343 free(hle);
8347 static const struct got_error *
8348 histedit_load_list(struct got_histedit_list *histedit_cmds,
8349 const char *path, struct got_repository *repo)
8351 const struct got_error *err = NULL;
8352 FILE *f = NULL;
8354 f = fopen(path, "r");
8355 if (f == NULL) {
8356 err = got_error_from_errno2("fopen", path);
8357 goto done;
8360 err = histedit_parse_list(histedit_cmds, f, repo);
8361 done:
8362 if (f && fclose(f) != 0 && err == NULL)
8363 err = got_error_from_errno("fclose");
8364 return err;
8367 static const struct got_error *
8368 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
8369 const struct got_error *edit_err, struct got_object_id_queue *commits,
8370 const char *path, const char *branch_name, struct got_repository *repo)
8372 const struct got_error *err = NULL, *prev_err = edit_err;
8373 int resp = ' ';
8375 while (resp != 'c' && resp != 'r' && resp != 'a') {
8376 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
8377 "or (a)bort: ", getprogname(), prev_err->msg);
8378 resp = getchar();
8379 if (resp == '\n')
8380 resp = getchar();
8381 if (resp == 'c') {
8382 histedit_free_list(histedit_cmds);
8383 err = histedit_run_editor(histedit_cmds, path, commits,
8384 repo);
8385 if (err) {
8386 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8387 err->code != GOT_ERR_HISTEDIT_CMD)
8388 break;
8389 prev_err = err;
8390 resp = ' ';
8391 continue;
8393 break;
8394 } else if (resp == 'r') {
8395 histedit_free_list(histedit_cmds);
8396 err = histedit_edit_script(histedit_cmds,
8397 commits, branch_name, 0, 0, repo);
8398 if (err) {
8399 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8400 err->code != GOT_ERR_HISTEDIT_CMD)
8401 break;
8402 prev_err = err;
8403 resp = ' ';
8404 continue;
8406 break;
8407 } else if (resp == 'a') {
8408 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
8409 break;
8410 } else
8411 printf("invalid response '%c'\n", resp);
8414 return err;
8417 static const struct got_error *
8418 histedit_complete(struct got_worktree *worktree,
8419 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
8420 struct got_reference *branch, struct got_repository *repo)
8422 printf("Switching work tree to %s\n",
8423 got_ref_get_symref_target(branch));
8424 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
8425 branch, repo);
8428 static const struct got_error *
8429 show_histedit_progress(struct got_commit_object *commit,
8430 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
8432 const struct got_error *err;
8433 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8435 err = got_object_id_str(&old_id_str, hle->commit_id);
8436 if (err)
8437 goto done;
8439 if (new_id) {
8440 err = got_object_id_str(&new_id_str, new_id);
8441 if (err)
8442 goto done;
8445 old_id_str[12] = '\0';
8446 if (new_id_str)
8447 new_id_str[12] = '\0';
8449 if (hle->logmsg) {
8450 logmsg = strdup(hle->logmsg);
8451 if (logmsg == NULL) {
8452 err = got_error_from_errno("strdup");
8453 goto done;
8455 trim_logmsg(logmsg, 42);
8456 } else {
8457 err = get_short_logmsg(&logmsg, 42, commit);
8458 if (err)
8459 goto done;
8462 switch (hle->cmd->code) {
8463 case GOT_HISTEDIT_PICK:
8464 case GOT_HISTEDIT_EDIT:
8465 printf("%s -> %s: %s\n", old_id_str,
8466 new_id_str ? new_id_str : "no-op change", logmsg);
8467 break;
8468 case GOT_HISTEDIT_DROP:
8469 case GOT_HISTEDIT_FOLD:
8470 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
8471 logmsg);
8472 break;
8473 default:
8474 break;
8476 done:
8477 free(old_id_str);
8478 free(new_id_str);
8479 return err;
8482 static const struct got_error *
8483 histedit_commit(struct got_pathlist_head *merged_paths,
8484 struct got_worktree *worktree, struct got_fileindex *fileindex,
8485 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
8486 struct got_repository *repo)
8488 const struct got_error *err;
8489 struct got_commit_object *commit;
8490 struct got_object_id *new_commit_id;
8492 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
8493 && hle->logmsg == NULL) {
8494 err = histedit_edit_logmsg(hle, repo);
8495 if (err)
8496 return err;
8499 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8500 if (err)
8501 return err;
8503 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
8504 worktree, fileindex, tmp_branch, commit, hle->commit_id,
8505 hle->logmsg, repo);
8506 if (err) {
8507 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
8508 goto done;
8509 err = show_histedit_progress(commit, hle, NULL);
8510 } else {
8511 err = show_histedit_progress(commit, hle, new_commit_id);
8512 free(new_commit_id);
8514 done:
8515 got_object_commit_close(commit);
8516 return err;
8519 static const struct got_error *
8520 histedit_skip_commit(struct got_histedit_list_entry *hle,
8521 struct got_worktree *worktree, struct got_repository *repo)
8523 const struct got_error *error;
8524 struct got_commit_object *commit;
8526 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
8527 repo);
8528 if (error)
8529 return error;
8531 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
8532 if (error)
8533 return error;
8535 error = show_histedit_progress(commit, hle, NULL);
8536 got_object_commit_close(commit);
8537 return error;
8540 static const struct got_error *
8541 check_local_changes(void *arg, unsigned char status,
8542 unsigned char staged_status, const char *path,
8543 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8544 struct got_object_id *commit_id, int dirfd, const char *de_name)
8546 int *have_local_changes = arg;
8548 switch (status) {
8549 case GOT_STATUS_ADD:
8550 case GOT_STATUS_DELETE:
8551 case GOT_STATUS_MODIFY:
8552 case GOT_STATUS_CONFLICT:
8553 *have_local_changes = 1;
8554 return got_error(GOT_ERR_CANCELLED);
8555 default:
8556 break;
8559 switch (staged_status) {
8560 case GOT_STATUS_ADD:
8561 case GOT_STATUS_DELETE:
8562 case GOT_STATUS_MODIFY:
8563 *have_local_changes = 1;
8564 return got_error(GOT_ERR_CANCELLED);
8565 default:
8566 break;
8569 return NULL;
8572 static const struct got_error *
8573 cmd_histedit(int argc, char *argv[])
8575 const struct got_error *error = NULL;
8576 struct got_worktree *worktree = NULL;
8577 struct got_fileindex *fileindex = NULL;
8578 struct got_repository *repo = NULL;
8579 char *cwd = NULL;
8580 struct got_reference *branch = NULL;
8581 struct got_reference *tmp_branch = NULL;
8582 struct got_object_id *resume_commit_id = NULL;
8583 struct got_object_id *base_commit_id = NULL;
8584 struct got_object_id *head_commit_id = NULL;
8585 struct got_commit_object *commit = NULL;
8586 int ch, rebase_in_progress = 0;
8587 struct got_update_progress_arg upa;
8588 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8589 int edit_logmsg_only = 0, fold_only = 0;
8590 const char *edit_script_path = NULL;
8591 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8592 struct got_object_id_queue commits;
8593 struct got_pathlist_head merged_paths;
8594 const struct got_object_id_queue *parent_ids;
8595 struct got_object_qid *pid;
8596 struct got_histedit_list histedit_cmds;
8597 struct got_histedit_list_entry *hle;
8599 SIMPLEQ_INIT(&commits);
8600 TAILQ_INIT(&histedit_cmds);
8601 TAILQ_INIT(&merged_paths);
8602 memset(&upa, 0, sizeof(upa));
8604 while ((ch = getopt(argc, argv, "acfF:m")) != -1) {
8605 switch (ch) {
8606 case 'a':
8607 abort_edit = 1;
8608 break;
8609 case 'c':
8610 continue_edit = 1;
8611 break;
8612 case 'f':
8613 fold_only = 1;
8614 break;
8615 case 'F':
8616 edit_script_path = optarg;
8617 break;
8618 case 'm':
8619 edit_logmsg_only = 1;
8620 break;
8621 default:
8622 usage_histedit();
8623 /* NOTREACHED */
8627 argc -= optind;
8628 argv += optind;
8630 #ifndef PROFILE
8631 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8632 "unveil", NULL) == -1)
8633 err(1, "pledge");
8634 #endif
8635 if (abort_edit && continue_edit)
8636 option_conflict('a', 'c');
8637 if (edit_script_path && edit_logmsg_only)
8638 option_conflict('F', 'm');
8639 if (abort_edit && edit_logmsg_only)
8640 option_conflict('a', 'm');
8641 if (continue_edit && edit_logmsg_only)
8642 option_conflict('c', 'm');
8643 if (abort_edit && fold_only)
8644 option_conflict('a', 'f');
8645 if (continue_edit && fold_only)
8646 option_conflict('c', 'f');
8647 if (fold_only && edit_logmsg_only)
8648 option_conflict('f', 'm');
8649 if (edit_script_path && fold_only)
8650 option_conflict('F', 'f');
8651 if (argc != 0)
8652 usage_histedit();
8655 * This command cannot apply unveil(2) in all cases because the
8656 * user may choose to run an editor to edit the histedit script
8657 * and to edit individual commit log messages.
8658 * unveil(2) traverses exec(2); if an editor is used we have to
8659 * apply unveil after edit script and log messages have been written.
8660 * XXX TODO: Make use of unveil(2) where possible.
8663 cwd = getcwd(NULL, 0);
8664 if (cwd == NULL) {
8665 error = got_error_from_errno("getcwd");
8666 goto done;
8668 error = got_worktree_open(&worktree, cwd);
8669 if (error) {
8670 if (error->code == GOT_ERR_NOT_WORKTREE)
8671 error = wrap_not_worktree_error(error, "histedit", cwd);
8672 goto done;
8675 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8676 NULL);
8677 if (error != NULL)
8678 goto done;
8680 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8681 if (error)
8682 goto done;
8683 if (rebase_in_progress) {
8684 error = got_error(GOT_ERR_REBASING);
8685 goto done;
8688 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8689 if (error)
8690 goto done;
8692 if (edit_in_progress && edit_logmsg_only) {
8693 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8694 "histedit operation is in progress in this "
8695 "work tree and must be continued or aborted "
8696 "before the -m option can be used");
8697 goto done;
8699 if (edit_in_progress && fold_only) {
8700 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8701 "histedit operation is in progress in this "
8702 "work tree and must be continued or aborted "
8703 "before the -f option can be used");
8704 goto done;
8707 if (edit_in_progress && abort_edit) {
8708 error = got_worktree_histedit_continue(&resume_commit_id,
8709 &tmp_branch, &branch, &base_commit_id, &fileindex,
8710 worktree, repo);
8711 if (error)
8712 goto done;
8713 printf("Switching work tree to %s\n",
8714 got_ref_get_symref_target(branch));
8715 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8716 branch, base_commit_id, update_progress, &upa);
8717 if (error)
8718 goto done;
8719 printf("Histedit of %s aborted\n",
8720 got_ref_get_symref_target(branch));
8721 print_update_progress_stats(&upa);
8722 goto done; /* nothing else to do */
8723 } else if (abort_edit) {
8724 error = got_error(GOT_ERR_NOT_HISTEDIT);
8725 goto done;
8728 if (continue_edit) {
8729 char *path;
8731 if (!edit_in_progress) {
8732 error = got_error(GOT_ERR_NOT_HISTEDIT);
8733 goto done;
8736 error = got_worktree_get_histedit_script_path(&path, worktree);
8737 if (error)
8738 goto done;
8740 error = histedit_load_list(&histedit_cmds, path, repo);
8741 free(path);
8742 if (error)
8743 goto done;
8745 error = got_worktree_histedit_continue(&resume_commit_id,
8746 &tmp_branch, &branch, &base_commit_id, &fileindex,
8747 worktree, repo);
8748 if (error)
8749 goto done;
8751 error = got_ref_resolve(&head_commit_id, repo, branch);
8752 if (error)
8753 goto done;
8755 error = got_object_open_as_commit(&commit, repo,
8756 head_commit_id);
8757 if (error)
8758 goto done;
8759 parent_ids = got_object_commit_get_parent_ids(commit);
8760 pid = SIMPLEQ_FIRST(parent_ids);
8761 if (pid == NULL) {
8762 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8763 goto done;
8765 error = collect_commits(&commits, head_commit_id, pid->id,
8766 base_commit_id, got_worktree_get_path_prefix(worktree),
8767 GOT_ERR_HISTEDIT_PATH, repo);
8768 got_object_commit_close(commit);
8769 commit = NULL;
8770 if (error)
8771 goto done;
8772 } else {
8773 if (edit_in_progress) {
8774 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8775 goto done;
8778 error = got_ref_open(&branch, repo,
8779 got_worktree_get_head_ref_name(worktree), 0);
8780 if (error != NULL)
8781 goto done;
8783 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8784 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8785 "will not edit commit history of a branch outside "
8786 "the \"refs/heads/\" reference namespace");
8787 goto done;
8790 error = got_ref_resolve(&head_commit_id, repo, branch);
8791 got_ref_close(branch);
8792 branch = NULL;
8793 if (error)
8794 goto done;
8796 error = got_object_open_as_commit(&commit, repo,
8797 head_commit_id);
8798 if (error)
8799 goto done;
8800 parent_ids = got_object_commit_get_parent_ids(commit);
8801 pid = SIMPLEQ_FIRST(parent_ids);
8802 if (pid == NULL) {
8803 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8804 goto done;
8806 error = collect_commits(&commits, head_commit_id, pid->id,
8807 got_worktree_get_base_commit_id(worktree),
8808 got_worktree_get_path_prefix(worktree),
8809 GOT_ERR_HISTEDIT_PATH, repo);
8810 got_object_commit_close(commit);
8811 commit = NULL;
8812 if (error)
8813 goto done;
8815 if (SIMPLEQ_EMPTY(&commits)) {
8816 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8817 goto done;
8820 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8821 &base_commit_id, &fileindex, worktree, repo);
8822 if (error)
8823 goto done;
8825 if (edit_script_path) {
8826 error = histedit_load_list(&histedit_cmds,
8827 edit_script_path, repo);
8828 if (error) {
8829 got_worktree_histedit_abort(worktree, fileindex,
8830 repo, branch, base_commit_id,
8831 update_progress, &upa);
8832 print_update_progress_stats(&upa);
8833 goto done;
8835 } else {
8836 const char *branch_name;
8837 branch_name = got_ref_get_symref_target(branch);
8838 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8839 branch_name += 11;
8840 error = histedit_edit_script(&histedit_cmds, &commits,
8841 branch_name, edit_logmsg_only, fold_only, repo);
8842 if (error) {
8843 got_worktree_histedit_abort(worktree, fileindex,
8844 repo, branch, base_commit_id,
8845 update_progress, &upa);
8846 print_update_progress_stats(&upa);
8847 goto done;
8852 error = histedit_save_list(&histedit_cmds, worktree,
8853 repo);
8854 if (error) {
8855 got_worktree_histedit_abort(worktree, fileindex,
8856 repo, branch, base_commit_id,
8857 update_progress, &upa);
8858 print_update_progress_stats(&upa);
8859 goto done;
8864 error = histedit_check_script(&histedit_cmds, &commits, repo);
8865 if (error)
8866 goto done;
8868 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8869 if (resume_commit_id) {
8870 if (got_object_id_cmp(hle->commit_id,
8871 resume_commit_id) != 0)
8872 continue;
8874 resume_commit_id = NULL;
8875 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8876 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8877 error = histedit_skip_commit(hle, worktree,
8878 repo);
8879 if (error)
8880 goto done;
8881 } else {
8882 struct got_pathlist_head paths;
8883 int have_changes = 0;
8885 TAILQ_INIT(&paths);
8886 error = got_pathlist_append(&paths, "", NULL);
8887 if (error)
8888 goto done;
8889 error = got_worktree_status(worktree, &paths,
8890 repo, check_local_changes, &have_changes,
8891 check_cancelled, NULL);
8892 got_pathlist_free(&paths);
8893 if (error) {
8894 if (error->code != GOT_ERR_CANCELLED)
8895 goto done;
8896 if (sigint_received || sigpipe_received)
8897 goto done;
8899 if (have_changes) {
8900 error = histedit_commit(NULL, worktree,
8901 fileindex, tmp_branch, hle, repo);
8902 if (error)
8903 goto done;
8904 } else {
8905 error = got_object_open_as_commit(
8906 &commit, repo, hle->commit_id);
8907 if (error)
8908 goto done;
8909 error = show_histedit_progress(commit,
8910 hle, NULL);
8911 got_object_commit_close(commit);
8912 commit = NULL;
8913 if (error)
8914 goto done;
8917 continue;
8920 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8921 error = histedit_skip_commit(hle, worktree, repo);
8922 if (error)
8923 goto done;
8924 continue;
8927 error = got_object_open_as_commit(&commit, repo,
8928 hle->commit_id);
8929 if (error)
8930 goto done;
8931 parent_ids = got_object_commit_get_parent_ids(commit);
8932 pid = SIMPLEQ_FIRST(parent_ids);
8934 error = got_worktree_histedit_merge_files(&merged_paths,
8935 worktree, fileindex, pid->id, hle->commit_id, repo,
8936 update_progress, &upa, check_cancelled, NULL);
8937 if (error)
8938 goto done;
8939 got_object_commit_close(commit);
8940 commit = NULL;
8942 print_update_progress_stats(&upa);
8943 if (upa.conflicts > 0)
8944 rebase_status = GOT_STATUS_CONFLICT;
8946 if (rebase_status == GOT_STATUS_CONFLICT) {
8947 error = show_rebase_merge_conflict(hle->commit_id,
8948 repo);
8949 if (error)
8950 goto done;
8951 got_worktree_rebase_pathlist_free(&merged_paths);
8952 break;
8955 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8956 char *id_str;
8957 error = got_object_id_str(&id_str, hle->commit_id);
8958 if (error)
8959 goto done;
8960 printf("Stopping histedit for amending commit %s\n",
8961 id_str);
8962 free(id_str);
8963 got_worktree_rebase_pathlist_free(&merged_paths);
8964 error = got_worktree_histedit_postpone(worktree,
8965 fileindex);
8966 goto done;
8969 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8970 error = histedit_skip_commit(hle, worktree, repo);
8971 if (error)
8972 goto done;
8973 continue;
8976 error = histedit_commit(&merged_paths, worktree, fileindex,
8977 tmp_branch, hle, repo);
8978 got_worktree_rebase_pathlist_free(&merged_paths);
8979 if (error)
8980 goto done;
8983 if (rebase_status == GOT_STATUS_CONFLICT) {
8984 error = got_worktree_histedit_postpone(worktree, fileindex);
8985 if (error)
8986 goto done;
8987 error = got_error_msg(GOT_ERR_CONFLICTS,
8988 "conflicts must be resolved before histedit can continue");
8989 } else
8990 error = histedit_complete(worktree, fileindex, tmp_branch,
8991 branch, repo);
8992 done:
8993 got_object_id_queue_free(&commits);
8994 histedit_free_list(&histedit_cmds);
8995 free(head_commit_id);
8996 free(base_commit_id);
8997 free(resume_commit_id);
8998 if (commit)
8999 got_object_commit_close(commit);
9000 if (branch)
9001 got_ref_close(branch);
9002 if (tmp_branch)
9003 got_ref_close(tmp_branch);
9004 if (worktree)
9005 got_worktree_close(worktree);
9006 if (repo)
9007 got_repo_close(repo);
9008 return error;
9011 __dead static void
9012 usage_integrate(void)
9014 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
9015 exit(1);
9018 static const struct got_error *
9019 cmd_integrate(int argc, char *argv[])
9021 const struct got_error *error = NULL;
9022 struct got_repository *repo = NULL;
9023 struct got_worktree *worktree = NULL;
9024 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
9025 const char *branch_arg = NULL;
9026 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
9027 struct got_fileindex *fileindex = NULL;
9028 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
9029 int ch;
9030 struct got_update_progress_arg upa;
9032 while ((ch = getopt(argc, argv, "")) != -1) {
9033 switch (ch) {
9034 default:
9035 usage_integrate();
9036 /* NOTREACHED */
9040 argc -= optind;
9041 argv += optind;
9043 if (argc != 1)
9044 usage_integrate();
9045 branch_arg = argv[0];
9046 #ifndef PROFILE
9047 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9048 "unveil", NULL) == -1)
9049 err(1, "pledge");
9050 #endif
9051 cwd = getcwd(NULL, 0);
9052 if (cwd == NULL) {
9053 error = got_error_from_errno("getcwd");
9054 goto done;
9057 error = got_worktree_open(&worktree, cwd);
9058 if (error) {
9059 if (error->code == GOT_ERR_NOT_WORKTREE)
9060 error = wrap_not_worktree_error(error, "integrate",
9061 cwd);
9062 goto done;
9065 error = check_rebase_or_histedit_in_progress(worktree);
9066 if (error)
9067 goto done;
9069 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9070 NULL);
9071 if (error != NULL)
9072 goto done;
9074 error = apply_unveil(got_repo_get_path(repo), 0,
9075 got_worktree_get_root_path(worktree));
9076 if (error)
9077 goto done;
9079 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
9080 error = got_error_from_errno("asprintf");
9081 goto done;
9084 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
9085 &base_branch_ref, worktree, refname, repo);
9086 if (error)
9087 goto done;
9089 refname = strdup(got_ref_get_name(branch_ref));
9090 if (refname == NULL) {
9091 error = got_error_from_errno("strdup");
9092 got_worktree_integrate_abort(worktree, fileindex, repo,
9093 branch_ref, base_branch_ref);
9094 goto done;
9096 base_refname = strdup(got_ref_get_name(base_branch_ref));
9097 if (base_refname == NULL) {
9098 error = got_error_from_errno("strdup");
9099 got_worktree_integrate_abort(worktree, fileindex, repo,
9100 branch_ref, base_branch_ref);
9101 goto done;
9104 error = got_ref_resolve(&commit_id, repo, branch_ref);
9105 if (error)
9106 goto done;
9108 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
9109 if (error)
9110 goto done;
9112 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
9113 error = got_error_msg(GOT_ERR_SAME_BRANCH,
9114 "specified branch has already been integrated");
9115 got_worktree_integrate_abort(worktree, fileindex, repo,
9116 branch_ref, base_branch_ref);
9117 goto done;
9120 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
9121 if (error) {
9122 if (error->code == GOT_ERR_ANCESTRY)
9123 error = got_error(GOT_ERR_REBASE_REQUIRED);
9124 got_worktree_integrate_abort(worktree, fileindex, repo,
9125 branch_ref, base_branch_ref);
9126 goto done;
9129 memset(&upa, 0, sizeof(upa));
9130 error = got_worktree_integrate_continue(worktree, fileindex, repo,
9131 branch_ref, base_branch_ref, update_progress, &upa,
9132 check_cancelled, NULL);
9133 if (error)
9134 goto done;
9136 printf("Integrated %s into %s\n", refname, base_refname);
9137 print_update_progress_stats(&upa);
9138 done:
9139 if (repo)
9140 got_repo_close(repo);
9141 if (worktree)
9142 got_worktree_close(worktree);
9143 free(cwd);
9144 free(base_commit_id);
9145 free(commit_id);
9146 free(refname);
9147 free(base_refname);
9148 return error;
9151 __dead static void
9152 usage_stage(void)
9154 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
9155 "[-S] [file-path ...]\n",
9156 getprogname());
9157 exit(1);
9160 static const struct got_error *
9161 print_stage(void *arg, unsigned char status, unsigned char staged_status,
9162 const char *path, struct got_object_id *blob_id,
9163 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
9164 int dirfd, const char *de_name)
9166 const struct got_error *err = NULL;
9167 char *id_str = NULL;
9169 if (staged_status != GOT_STATUS_ADD &&
9170 staged_status != GOT_STATUS_MODIFY &&
9171 staged_status != GOT_STATUS_DELETE)
9172 return NULL;
9174 if (staged_status == GOT_STATUS_ADD ||
9175 staged_status == GOT_STATUS_MODIFY)
9176 err = got_object_id_str(&id_str, staged_blob_id);
9177 else
9178 err = got_object_id_str(&id_str, blob_id);
9179 if (err)
9180 return err;
9182 printf("%s %c %s\n", id_str, staged_status, path);
9183 free(id_str);
9184 return NULL;
9187 static const struct got_error *
9188 cmd_stage(int argc, char *argv[])
9190 const struct got_error *error = NULL;
9191 struct got_repository *repo = NULL;
9192 struct got_worktree *worktree = NULL;
9193 char *cwd = NULL;
9194 struct got_pathlist_head paths;
9195 struct got_pathlist_entry *pe;
9196 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
9197 FILE *patch_script_file = NULL;
9198 const char *patch_script_path = NULL;
9199 struct choose_patch_arg cpa;
9201 TAILQ_INIT(&paths);
9203 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
9204 switch (ch) {
9205 case 'l':
9206 list_stage = 1;
9207 break;
9208 case 'p':
9209 pflag = 1;
9210 break;
9211 case 'F':
9212 patch_script_path = optarg;
9213 break;
9214 case 'S':
9215 allow_bad_symlinks = 1;
9216 break;
9217 default:
9218 usage_stage();
9219 /* NOTREACHED */
9223 argc -= optind;
9224 argv += optind;
9226 #ifndef PROFILE
9227 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9228 "unveil", NULL) == -1)
9229 err(1, "pledge");
9230 #endif
9231 if (list_stage && (pflag || patch_script_path))
9232 errx(1, "-l option cannot be used with other options");
9233 if (patch_script_path && !pflag)
9234 errx(1, "-F option can only be used together with -p option");
9236 cwd = getcwd(NULL, 0);
9237 if (cwd == NULL) {
9238 error = got_error_from_errno("getcwd");
9239 goto done;
9242 error = got_worktree_open(&worktree, cwd);
9243 if (error) {
9244 if (error->code == GOT_ERR_NOT_WORKTREE)
9245 error = wrap_not_worktree_error(error, "stage", cwd);
9246 goto done;
9249 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9250 NULL);
9251 if (error != NULL)
9252 goto done;
9254 if (patch_script_path) {
9255 patch_script_file = fopen(patch_script_path, "r");
9256 if (patch_script_file == NULL) {
9257 error = got_error_from_errno2("fopen",
9258 patch_script_path);
9259 goto done;
9262 error = apply_unveil(got_repo_get_path(repo), 0,
9263 got_worktree_get_root_path(worktree));
9264 if (error)
9265 goto done;
9267 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9268 if (error)
9269 goto done;
9271 if (list_stage)
9272 error = got_worktree_status(worktree, &paths, repo,
9273 print_stage, NULL, check_cancelled, NULL);
9274 else {
9275 cpa.patch_script_file = patch_script_file;
9276 cpa.action = "stage";
9277 error = got_worktree_stage(worktree, &paths,
9278 pflag ? NULL : print_status, NULL,
9279 pflag ? choose_patch : NULL, &cpa,
9280 allow_bad_symlinks, repo);
9282 done:
9283 if (patch_script_file && fclose(patch_script_file) == EOF &&
9284 error == NULL)
9285 error = got_error_from_errno2("fclose", patch_script_path);
9286 if (repo)
9287 got_repo_close(repo);
9288 if (worktree)
9289 got_worktree_close(worktree);
9290 TAILQ_FOREACH(pe, &paths, entry)
9291 free((char *)pe->path);
9292 got_pathlist_free(&paths);
9293 free(cwd);
9294 return error;
9297 __dead static void
9298 usage_unstage(void)
9300 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
9301 "[file-path ...]\n",
9302 getprogname());
9303 exit(1);
9307 static const struct got_error *
9308 cmd_unstage(int argc, char *argv[])
9310 const struct got_error *error = NULL;
9311 struct got_repository *repo = NULL;
9312 struct got_worktree *worktree = NULL;
9313 char *cwd = NULL;
9314 struct got_pathlist_head paths;
9315 struct got_pathlist_entry *pe;
9316 int ch, pflag = 0;
9317 struct got_update_progress_arg upa;
9318 FILE *patch_script_file = NULL;
9319 const char *patch_script_path = NULL;
9320 struct choose_patch_arg cpa;
9322 TAILQ_INIT(&paths);
9324 while ((ch = getopt(argc, argv, "pF:")) != -1) {
9325 switch (ch) {
9326 case 'p':
9327 pflag = 1;
9328 break;
9329 case 'F':
9330 patch_script_path = optarg;
9331 break;
9332 default:
9333 usage_unstage();
9334 /* NOTREACHED */
9338 argc -= optind;
9339 argv += optind;
9341 #ifndef PROFILE
9342 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9343 "unveil", NULL) == -1)
9344 err(1, "pledge");
9345 #endif
9346 if (patch_script_path && !pflag)
9347 errx(1, "-F option can only be used together with -p option");
9349 cwd = getcwd(NULL, 0);
9350 if (cwd == NULL) {
9351 error = got_error_from_errno("getcwd");
9352 goto done;
9355 error = got_worktree_open(&worktree, cwd);
9356 if (error) {
9357 if (error->code == GOT_ERR_NOT_WORKTREE)
9358 error = wrap_not_worktree_error(error, "unstage", cwd);
9359 goto done;
9362 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9363 NULL);
9364 if (error != NULL)
9365 goto done;
9367 if (patch_script_path) {
9368 patch_script_file = fopen(patch_script_path, "r");
9369 if (patch_script_file == NULL) {
9370 error = got_error_from_errno2("fopen",
9371 patch_script_path);
9372 goto done;
9376 error = apply_unveil(got_repo_get_path(repo), 0,
9377 got_worktree_get_root_path(worktree));
9378 if (error)
9379 goto done;
9381 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9382 if (error)
9383 goto done;
9385 cpa.patch_script_file = patch_script_file;
9386 cpa.action = "unstage";
9387 memset(&upa, 0, sizeof(upa));
9388 error = got_worktree_unstage(worktree, &paths, update_progress,
9389 &upa, pflag ? choose_patch : NULL, &cpa, repo);
9390 if (!error)
9391 print_update_progress_stats(&upa);
9392 done:
9393 if (patch_script_file && fclose(patch_script_file) == EOF &&
9394 error == NULL)
9395 error = got_error_from_errno2("fclose", patch_script_path);
9396 if (repo)
9397 got_repo_close(repo);
9398 if (worktree)
9399 got_worktree_close(worktree);
9400 TAILQ_FOREACH(pe, &paths, entry)
9401 free((char *)pe->path);
9402 got_pathlist_free(&paths);
9403 free(cwd);
9404 return error;
9407 __dead static void
9408 usage_cat(void)
9410 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
9411 "arg1 [arg2 ...]\n", getprogname());
9412 exit(1);
9415 static const struct got_error *
9416 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9418 const struct got_error *err;
9419 struct got_blob_object *blob;
9421 err = got_object_open_as_blob(&blob, repo, id, 8192);
9422 if (err)
9423 return err;
9425 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
9426 got_object_blob_close(blob);
9427 return err;
9430 static const struct got_error *
9431 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9433 const struct got_error *err;
9434 struct got_tree_object *tree;
9435 int nentries, i;
9437 err = got_object_open_as_tree(&tree, repo, id);
9438 if (err)
9439 return err;
9441 nentries = got_object_tree_get_nentries(tree);
9442 for (i = 0; i < nentries; i++) {
9443 struct got_tree_entry *te;
9444 char *id_str;
9445 if (sigint_received || sigpipe_received)
9446 break;
9447 te = got_object_tree_get_entry(tree, i);
9448 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
9449 if (err)
9450 break;
9451 fprintf(outfile, "%s %.7o %s\n", id_str,
9452 got_tree_entry_get_mode(te),
9453 got_tree_entry_get_name(te));
9454 free(id_str);
9457 got_object_tree_close(tree);
9458 return err;
9461 static const struct got_error *
9462 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9464 const struct got_error *err;
9465 struct got_commit_object *commit;
9466 const struct got_object_id_queue *parent_ids;
9467 struct got_object_qid *pid;
9468 char *id_str = NULL;
9469 const char *logmsg = NULL;
9471 err = got_object_open_as_commit(&commit, repo, id);
9472 if (err)
9473 return err;
9475 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
9476 if (err)
9477 goto done;
9479 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
9480 parent_ids = got_object_commit_get_parent_ids(commit);
9481 fprintf(outfile, "numparents %d\n",
9482 got_object_commit_get_nparents(commit));
9483 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
9484 char *pid_str;
9485 err = got_object_id_str(&pid_str, pid->id);
9486 if (err)
9487 goto done;
9488 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
9489 free(pid_str);
9491 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
9492 got_object_commit_get_author(commit),
9493 (long long)got_object_commit_get_author_time(commit));
9495 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
9496 got_object_commit_get_author(commit),
9497 (long long)got_object_commit_get_committer_time(commit));
9499 logmsg = got_object_commit_get_logmsg_raw(commit);
9500 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
9501 fprintf(outfile, "%s", logmsg);
9502 done:
9503 free(id_str);
9504 got_object_commit_close(commit);
9505 return err;
9508 static const struct got_error *
9509 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9511 const struct got_error *err;
9512 struct got_tag_object *tag;
9513 char *id_str = NULL;
9514 const char *tagmsg = NULL;
9516 err = got_object_open_as_tag(&tag, repo, id);
9517 if (err)
9518 return err;
9520 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
9521 if (err)
9522 goto done;
9524 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
9526 switch (got_object_tag_get_object_type(tag)) {
9527 case GOT_OBJ_TYPE_BLOB:
9528 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9529 GOT_OBJ_LABEL_BLOB);
9530 break;
9531 case GOT_OBJ_TYPE_TREE:
9532 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9533 GOT_OBJ_LABEL_TREE);
9534 break;
9535 case GOT_OBJ_TYPE_COMMIT:
9536 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9537 GOT_OBJ_LABEL_COMMIT);
9538 break;
9539 case GOT_OBJ_TYPE_TAG:
9540 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9541 GOT_OBJ_LABEL_TAG);
9542 break;
9543 default:
9544 break;
9547 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
9548 got_object_tag_get_name(tag));
9550 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
9551 got_object_tag_get_tagger(tag),
9552 (long long)got_object_tag_get_tagger_time(tag));
9554 tagmsg = got_object_tag_get_message(tag);
9555 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
9556 fprintf(outfile, "%s", tagmsg);
9557 done:
9558 free(id_str);
9559 got_object_tag_close(tag);
9560 return err;
9563 static const struct got_error *
9564 cmd_cat(int argc, char *argv[])
9566 const struct got_error *error;
9567 struct got_repository *repo = NULL;
9568 struct got_worktree *worktree = NULL;
9569 char *cwd = NULL, *repo_path = NULL, *label = NULL;
9570 const char *commit_id_str = NULL;
9571 struct got_object_id *id = NULL, *commit_id = NULL;
9572 int ch, obj_type, i, force_path = 0;
9574 #ifndef PROFILE
9575 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9576 NULL) == -1)
9577 err(1, "pledge");
9578 #endif
9580 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
9581 switch (ch) {
9582 case 'c':
9583 commit_id_str = optarg;
9584 break;
9585 case 'r':
9586 repo_path = realpath(optarg, NULL);
9587 if (repo_path == NULL)
9588 return got_error_from_errno2("realpath",
9589 optarg);
9590 got_path_strip_trailing_slashes(repo_path);
9591 break;
9592 case 'P':
9593 force_path = 1;
9594 break;
9595 default:
9596 usage_cat();
9597 /* NOTREACHED */
9601 argc -= optind;
9602 argv += optind;
9604 cwd = getcwd(NULL, 0);
9605 if (cwd == NULL) {
9606 error = got_error_from_errno("getcwd");
9607 goto done;
9609 error = got_worktree_open(&worktree, cwd);
9610 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9611 goto done;
9612 if (worktree) {
9613 if (repo_path == NULL) {
9614 repo_path = strdup(
9615 got_worktree_get_repo_path(worktree));
9616 if (repo_path == NULL) {
9617 error = got_error_from_errno("strdup");
9618 goto done;
9623 if (repo_path == NULL) {
9624 repo_path = getcwd(NULL, 0);
9625 if (repo_path == NULL)
9626 return got_error_from_errno("getcwd");
9629 error = got_repo_open(&repo, repo_path, NULL);
9630 free(repo_path);
9631 if (error != NULL)
9632 goto done;
9634 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9635 if (error)
9636 goto done;
9638 if (commit_id_str == NULL)
9639 commit_id_str = GOT_REF_HEAD;
9640 error = got_repo_match_object_id(&commit_id, NULL,
9641 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
9642 if (error)
9643 goto done;
9645 for (i = 0; i < argc; i++) {
9646 if (force_path) {
9647 error = got_object_id_by_path(&id, repo, commit_id,
9648 argv[i]);
9649 if (error)
9650 break;
9651 } else {
9652 error = got_repo_match_object_id(&id, &label, argv[i],
9653 GOT_OBJ_TYPE_ANY, 0, repo);
9654 if (error) {
9655 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9656 error->code != GOT_ERR_NOT_REF)
9657 break;
9658 error = got_object_id_by_path(&id, repo,
9659 commit_id, argv[i]);
9660 if (error)
9661 break;
9665 error = got_object_get_type(&obj_type, repo, id);
9666 if (error)
9667 break;
9669 switch (obj_type) {
9670 case GOT_OBJ_TYPE_BLOB:
9671 error = cat_blob(id, repo, stdout);
9672 break;
9673 case GOT_OBJ_TYPE_TREE:
9674 error = cat_tree(id, repo, stdout);
9675 break;
9676 case GOT_OBJ_TYPE_COMMIT:
9677 error = cat_commit(id, repo, stdout);
9678 break;
9679 case GOT_OBJ_TYPE_TAG:
9680 error = cat_tag(id, repo, stdout);
9681 break;
9682 default:
9683 error = got_error(GOT_ERR_OBJ_TYPE);
9684 break;
9686 if (error)
9687 break;
9688 free(label);
9689 label = NULL;
9690 free(id);
9691 id = NULL;
9693 done:
9694 free(label);
9695 free(id);
9696 free(commit_id);
9697 if (worktree)
9698 got_worktree_close(worktree);
9699 if (repo) {
9700 const struct got_error *repo_error;
9701 repo_error = got_repo_close(repo);
9702 if (error == NULL)
9703 error = repo_error;
9705 return error;
9708 __dead static void
9709 usage_info(void)
9711 fprintf(stderr, "usage: %s info [path ...]\n",
9712 getprogname());
9713 exit(1);
9716 static const struct got_error *
9717 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
9718 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9719 struct got_object_id *commit_id)
9721 const struct got_error *err = NULL;
9722 char *id_str = NULL;
9723 char datebuf[128];
9724 struct tm mytm, *tm;
9725 struct got_pathlist_head *paths = arg;
9726 struct got_pathlist_entry *pe;
9729 * Clear error indication from any of the path arguments which
9730 * would cause this file index entry to be displayed.
9732 TAILQ_FOREACH(pe, paths, entry) {
9733 if (got_path_cmp(path, pe->path, strlen(path),
9734 pe->path_len) == 0 ||
9735 got_path_is_child(path, pe->path, pe->path_len))
9736 pe->data = NULL; /* no error */
9739 printf(GOT_COMMIT_SEP_STR);
9740 if (S_ISLNK(mode))
9741 printf("symlink: %s\n", path);
9742 else if (S_ISREG(mode)) {
9743 printf("file: %s\n", path);
9744 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
9745 } else if (S_ISDIR(mode))
9746 printf("directory: %s\n", path);
9747 else
9748 printf("something: %s\n", path);
9750 tm = localtime_r(&mtime, &mytm);
9751 if (tm == NULL)
9752 return NULL;
9753 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) >= sizeof(datebuf))
9754 return got_error(GOT_ERR_NO_SPACE);
9755 printf("timestamp: %s\n", datebuf);
9757 if (blob_id) {
9758 err = got_object_id_str(&id_str, blob_id);
9759 if (err)
9760 return err;
9761 printf("based on blob: %s\n", id_str);
9762 free(id_str);
9765 if (staged_blob_id) {
9766 err = got_object_id_str(&id_str, staged_blob_id);
9767 if (err)
9768 return err;
9769 printf("based on staged blob: %s\n", id_str);
9770 free(id_str);
9773 if (commit_id) {
9774 err = got_object_id_str(&id_str, commit_id);
9775 if (err)
9776 return err;
9777 printf("based on commit: %s\n", id_str);
9778 free(id_str);
9781 return NULL;
9784 static const struct got_error *
9785 cmd_info(int argc, char *argv[])
9787 const struct got_error *error = NULL;
9788 struct got_worktree *worktree = NULL;
9789 char *cwd = NULL, *id_str = NULL;
9790 struct got_pathlist_head paths;
9791 struct got_pathlist_entry *pe;
9792 char *uuidstr = NULL;
9793 int ch, show_files = 0;
9795 TAILQ_INIT(&paths);
9797 while ((ch = getopt(argc, argv, "")) != -1) {
9798 switch (ch) {
9799 default:
9800 usage_info();
9801 /* NOTREACHED */
9805 argc -= optind;
9806 argv += optind;
9808 #ifndef PROFILE
9809 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
9810 NULL) == -1)
9811 err(1, "pledge");
9812 #endif
9813 cwd = getcwd(NULL, 0);
9814 if (cwd == NULL) {
9815 error = got_error_from_errno("getcwd");
9816 goto done;
9819 error = got_worktree_open(&worktree, cwd);
9820 if (error) {
9821 if (error->code == GOT_ERR_NOT_WORKTREE)
9822 error = wrap_not_worktree_error(error, "status", cwd);
9823 goto done;
9826 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9827 if (error)
9828 goto done;
9830 if (argc >= 1) {
9831 error = get_worktree_paths_from_argv(&paths, argc, argv,
9832 worktree);
9833 if (error)
9834 goto done;
9835 show_files = 1;
9838 error = got_object_id_str(&id_str,
9839 got_worktree_get_base_commit_id(worktree));
9840 if (error)
9841 goto done;
9843 error = got_worktree_get_uuid(&uuidstr, worktree);
9844 if (error)
9845 goto done;
9847 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9848 printf("work tree base commit: %s\n", id_str);
9849 printf("work tree path prefix: %s\n",
9850 got_worktree_get_path_prefix(worktree));
9851 printf("work tree branch reference: %s\n",
9852 got_worktree_get_head_ref_name(worktree));
9853 printf("work tree UUID: %s\n", uuidstr);
9854 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
9856 if (show_files) {
9857 struct got_pathlist_entry *pe;
9858 TAILQ_FOREACH(pe, &paths, entry) {
9859 if (pe->path_len == 0)
9860 continue;
9862 * Assume this path will fail. This will be corrected
9863 * in print_path_info() in case the path does suceeed.
9865 pe->data = (void *)got_error_path(pe->path,
9866 GOT_ERR_BAD_PATH);
9868 error = got_worktree_path_info(worktree, &paths,
9869 print_path_info, &paths, check_cancelled, NULL);
9870 if (error)
9871 goto done;
9872 TAILQ_FOREACH(pe, &paths, entry) {
9873 if (pe->data != NULL) {
9874 error = pe->data; /* bad path */
9875 break;
9879 done:
9880 TAILQ_FOREACH(pe, &paths, entry)
9881 free((char *)pe->path);
9882 got_pathlist_free(&paths);
9883 free(cwd);
9884 free(id_str);
9885 free(uuidstr);
9886 return error;