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);
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(void)
176 int i;
178 fprintf(stderr, "commands:");
179 for (i = 0; i < nitems(got_commands); i++) {
180 struct got_cmd *cmd = &got_commands[i];
181 fprintf(stderr, " %s", cmd->cmd_name);
183 fputc('\n', stderr);
186 int
187 main(int argc, char *argv[])
189 struct got_cmd *cmd;
190 unsigned int i;
191 int ch;
192 int hflag = 0, Vflag = 0;
193 static struct option longopts[] = {
194 { "version", no_argument, NULL, 'V' },
195 { NULL, 0, NULL, 0 }
196 };
198 setlocale(LC_CTYPE, "");
200 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
201 switch (ch) {
202 case 'h':
203 hflag = 1;
204 break;
205 case 'V':
206 Vflag = 1;
207 break;
208 default:
209 usage(hflag);
210 /* NOTREACHED */
214 argc -= optind;
215 argv += optind;
216 optind = 0;
218 if (Vflag) {
219 got_version_print_str();
220 return 1;
223 if (argc <= 0)
224 usage(hflag);
226 signal(SIGINT, catch_sigint);
227 signal(SIGPIPE, catch_sigpipe);
229 for (i = 0; i < nitems(got_commands); i++) {
230 const struct got_error *error;
232 cmd = &got_commands[i];
234 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
235 strcmp(cmd->cmd_alias, argv[0]) != 0)
236 continue;
238 if (hflag)
239 got_commands[i].cmd_usage();
241 error = got_commands[i].cmd_main(argc, argv);
242 if (error && error->code != GOT_ERR_CANCELLED &&
243 error->code != GOT_ERR_PRIVSEP_EXIT &&
244 !(sigpipe_received &&
245 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
246 !(sigint_received &&
247 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
248 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
249 return 1;
252 return 0;
255 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
256 list_commands();
257 return 1;
260 __dead static void
261 usage(int hflag)
263 fprintf(stderr, "usage: %s [-h] [-V | --version] command [arg ...]\n",
264 getprogname());
265 if (hflag)
266 list_commands();
267 exit(1);
270 static const struct got_error *
271 get_editor(char **abspath)
273 const struct got_error *err = NULL;
274 const char *editor;
276 *abspath = NULL;
278 editor = getenv("VISUAL");
279 if (editor == NULL)
280 editor = getenv("EDITOR");
282 if (editor) {
283 err = got_path_find_prog(abspath, editor);
284 if (err)
285 return err;
288 if (*abspath == NULL) {
289 *abspath = strdup("/bin/ed");
290 if (*abspath == NULL)
291 return got_error_from_errno("strdup");
294 return NULL;
297 static const struct got_error *
298 apply_unveil(const char *repo_path, int repo_read_only,
299 const char *worktree_path)
301 const struct got_error *err;
303 #ifdef PROFILE
304 if (unveil("gmon.out", "rwc") != 0)
305 return got_error_from_errno2("unveil", "gmon.out");
306 #endif
307 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
308 return got_error_from_errno2("unveil", repo_path);
310 if (worktree_path && unveil(worktree_path, "rwc") != 0)
311 return got_error_from_errno2("unveil", worktree_path);
313 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
314 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
316 err = got_privsep_unveil_exec_helpers();
317 if (err != NULL)
318 return err;
320 if (unveil(NULL, NULL) != 0)
321 return got_error_from_errno("unveil");
323 return NULL;
326 __dead static void
327 usage_init(void)
329 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
330 exit(1);
333 static const struct got_error *
334 cmd_init(int argc, char *argv[])
336 const struct got_error *error = NULL;
337 char *repo_path = NULL;
338 int ch;
340 while ((ch = getopt(argc, argv, "")) != -1) {
341 switch (ch) {
342 default:
343 usage_init();
344 /* NOTREACHED */
348 argc -= optind;
349 argv += optind;
351 #ifndef PROFILE
352 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
353 err(1, "pledge");
354 #endif
355 if (argc != 1)
356 usage_init();
358 repo_path = strdup(argv[0]);
359 if (repo_path == NULL)
360 return got_error_from_errno("strdup");
362 got_path_strip_trailing_slashes(repo_path);
364 error = got_path_mkdir(repo_path);
365 if (error &&
366 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
367 goto done;
369 error = apply_unveil(repo_path, 0, NULL);
370 if (error)
371 goto done;
373 error = got_repo_init(repo_path);
374 done:
375 free(repo_path);
376 return error;
379 __dead static void
380 usage_import(void)
382 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
383 "[-r repository-path] [-I pattern] path\n", getprogname());
384 exit(1);
387 int
388 spawn_editor(const char *editor, const char *file)
390 pid_t pid;
391 sig_t sighup, sigint, sigquit;
392 int st = -1;
394 sighup = signal(SIGHUP, SIG_IGN);
395 sigint = signal(SIGINT, SIG_IGN);
396 sigquit = signal(SIGQUIT, SIG_IGN);
398 switch (pid = fork()) {
399 case -1:
400 goto doneediting;
401 case 0:
402 execl(editor, editor, file, (char *)NULL);
403 _exit(127);
406 while (waitpid(pid, &st, 0) == -1)
407 if (errno != EINTR)
408 break;
410 doneediting:
411 (void)signal(SIGHUP, sighup);
412 (void)signal(SIGINT, sigint);
413 (void)signal(SIGQUIT, sigquit);
415 if (!WIFEXITED(st)) {
416 errno = EINTR;
417 return -1;
420 return WEXITSTATUS(st);
423 static const struct got_error *
424 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
425 const char *initial_content, size_t initial_content_len)
427 const struct got_error *err = NULL;
428 char *line = NULL;
429 size_t linesize = 0;
430 ssize_t linelen;
431 struct stat st, st2;
432 FILE *fp = NULL;
433 size_t len, logmsg_len;
434 char *initial_content_stripped = NULL, *buf = NULL, *s;
436 *logmsg = NULL;
438 if (stat(logmsg_path, &st) == -1)
439 return got_error_from_errno2("stat", logmsg_path);
441 if (spawn_editor(editor, logmsg_path) == -1)
442 return got_error_from_errno("failed spawning editor");
444 if (stat(logmsg_path, &st2) == -1)
445 return got_error_from_errno("stat");
447 if (st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
448 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
449 "no changes made to commit message, aborting");
451 /*
452 * Set up a stripped version of the initial content without comments
453 * and blank lines. We need this in order to check if the message
454 * has in fact been edited.
455 */
456 initial_content_stripped = malloc(initial_content_len + 1);
457 if (initial_content_stripped == NULL)
458 return got_error_from_errno("malloc");
459 initial_content_stripped[0] = '\0';
461 buf = strdup(initial_content);
462 if (buf == NULL) {
463 err = got_error_from_errno("strdup");
464 goto done;
466 s = buf;
467 len = 0;
468 while ((line = strsep(&s, "\n")) != NULL) {
469 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
470 continue; /* remove comments and leading empty lines */
471 len = strlcat(initial_content_stripped, line,
472 initial_content_len + 1);
473 if (len >= initial_content_len + 1) {
474 err = got_error(GOT_ERR_NO_SPACE);
475 goto done;
478 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
479 initial_content_stripped[len - 1] = '\0';
480 len--;
483 logmsg_len = st2.st_size;
484 *logmsg = malloc(logmsg_len + 1);
485 if (*logmsg == NULL)
486 return got_error_from_errno("malloc");
487 (*logmsg)[0] = '\0';
489 fp = fopen(logmsg_path, "r");
490 if (fp == NULL) {
491 err = got_error_from_errno("fopen");
492 goto done;
495 len = 0;
496 while ((linelen = getline(&line, &linesize, fp)) != -1) {
497 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
498 continue; /* remove comments and leading empty lines */
499 len = strlcat(*logmsg, line, logmsg_len + 1);
500 if (len >= logmsg_len + 1) {
501 err = got_error(GOT_ERR_NO_SPACE);
502 goto done;
505 free(line);
506 if (ferror(fp)) {
507 err = got_ferror(fp, GOT_ERR_IO);
508 goto done;
510 while (len > 0 && (*logmsg)[len - 1] == '\n') {
511 (*logmsg)[len - 1] = '\0';
512 len--;
515 if (len == 0) {
516 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
517 "commit message cannot be empty, aborting");
518 goto done;
520 if (strcmp(*logmsg, initial_content_stripped) == 0)
521 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
522 "no changes made to commit message, aborting");
523 done:
524 free(initial_content_stripped);
525 free(buf);
526 if (fp && fclose(fp) == EOF && err == NULL)
527 err = got_error_from_errno("fclose");
528 if (err) {
529 free(*logmsg);
530 *logmsg = NULL;
532 return err;
535 static const struct got_error *
536 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
537 const char *path_dir, const char *branch_name)
539 char *initial_content = NULL;
540 const struct got_error *err = NULL;
541 int initial_content_len;
542 int fd = -1;
544 initial_content_len = asprintf(&initial_content,
545 "\n# %s to be imported to branch %s\n", path_dir,
546 branch_name);
547 if (initial_content_len == -1)
548 return got_error_from_errno("asprintf");
550 err = got_opentemp_named_fd(logmsg_path, &fd,
551 GOT_TMPDIR_STR "/got-importmsg");
552 if (err)
553 goto done;
555 if (write(fd, initial_content, initial_content_len) == -1) {
556 err = got_error_from_errno2("write", *logmsg_path);
557 goto done;
560 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
561 initial_content_len);
562 done:
563 if (fd != -1 && close(fd) == -1 && err == NULL)
564 err = got_error_from_errno2("close", *logmsg_path);
565 free(initial_content);
566 if (err) {
567 free(*logmsg_path);
568 *logmsg_path = NULL;
570 return err;
573 static const struct got_error *
574 import_progress(void *arg, const char *path)
576 printf("A %s\n", path);
577 return NULL;
580 static const struct got_error *
581 get_author(char **author, struct got_repository *repo,
582 struct got_worktree *worktree)
584 const struct got_error *err = NULL;
585 const char *got_author = NULL, *name, *email;
586 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
588 *author = NULL;
590 if (worktree)
591 worktree_conf = got_worktree_get_gotconfig(worktree);
592 repo_conf = got_repo_get_gotconfig(repo);
594 /*
595 * Priority of potential author information sources, from most
596 * significant to least significant:
597 * 1) work tree's .got/got.conf file
598 * 2) repository's got.conf file
599 * 3) repository's git config file
600 * 4) environment variables
601 * 5) global git config files (in user's home directory or /etc)
602 */
604 if (worktree_conf)
605 got_author = got_gotconfig_get_author(worktree_conf);
606 if (got_author == NULL)
607 got_author = got_gotconfig_get_author(repo_conf);
608 if (got_author == NULL) {
609 name = got_repo_get_gitconfig_author_name(repo);
610 email = got_repo_get_gitconfig_author_email(repo);
611 if (name && email) {
612 if (asprintf(author, "%s <%s>", name, email) == -1)
613 return got_error_from_errno("asprintf");
614 return NULL;
617 got_author = getenv("GOT_AUTHOR");
618 if (got_author == NULL) {
619 name = got_repo_get_global_gitconfig_author_name(repo);
620 email = got_repo_get_global_gitconfig_author_email(
621 repo);
622 if (name && email) {
623 if (asprintf(author, "%s <%s>", name, email)
624 == -1)
625 return got_error_from_errno("asprintf");
626 return NULL;
628 /* TODO: Look up user in password database? */
629 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
633 *author = strdup(got_author);
634 if (*author == NULL)
635 return got_error_from_errno("strdup");
637 /*
638 * Really dumb email address check; we're only doing this to
639 * avoid git's object parser breaking on commits we create.
640 */
641 while (*got_author && *got_author != '<')
642 got_author++;
643 if (*got_author != '<') {
644 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
645 goto done;
647 while (*got_author && *got_author != '@')
648 got_author++;
649 if (*got_author != '@') {
650 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
651 goto done;
653 while (*got_author && *got_author != '>')
654 got_author++;
655 if (*got_author != '>')
656 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
657 done:
658 if (err) {
659 free(*author);
660 *author = NULL;
662 return err;
665 static const struct got_error *
666 get_gitconfig_path(char **gitconfig_path)
668 const char *homedir = getenv("HOME");
670 *gitconfig_path = NULL;
671 if (homedir) {
672 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
673 return got_error_from_errno("asprintf");
676 return NULL;
679 static const struct got_error *
680 cmd_import(int argc, char *argv[])
682 const struct got_error *error = NULL;
683 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
684 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
685 const char *branch_name = "main";
686 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
687 struct got_repository *repo = NULL;
688 struct got_reference *branch_ref = NULL, *head_ref = NULL;
689 struct got_object_id *new_commit_id = NULL;
690 int ch;
691 struct got_pathlist_head ignores;
692 struct got_pathlist_entry *pe;
693 int preserve_logmsg = 0;
695 TAILQ_INIT(&ignores);
697 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
698 switch (ch) {
699 case 'b':
700 branch_name = optarg;
701 break;
702 case 'm':
703 logmsg = strdup(optarg);
704 if (logmsg == NULL) {
705 error = got_error_from_errno("strdup");
706 goto done;
708 break;
709 case 'r':
710 repo_path = realpath(optarg, NULL);
711 if (repo_path == NULL) {
712 error = got_error_from_errno2("realpath",
713 optarg);
714 goto done;
716 break;
717 case 'I':
718 if (optarg[0] == '\0')
719 break;
720 error = got_pathlist_insert(&pe, &ignores, optarg,
721 NULL);
722 if (error)
723 goto done;
724 break;
725 default:
726 usage_import();
727 /* NOTREACHED */
731 argc -= optind;
732 argv += optind;
734 #ifndef PROFILE
735 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
736 "unveil",
737 NULL) == -1)
738 err(1, "pledge");
739 #endif
740 if (argc != 1)
741 usage_import();
743 if (repo_path == NULL) {
744 repo_path = getcwd(NULL, 0);
745 if (repo_path == NULL)
746 return got_error_from_errno("getcwd");
748 got_path_strip_trailing_slashes(repo_path);
749 error = get_gitconfig_path(&gitconfig_path);
750 if (error)
751 goto done;
752 error = got_repo_open(&repo, repo_path, gitconfig_path);
753 if (error)
754 goto done;
756 error = get_author(&author, repo, NULL);
757 if (error)
758 return error;
760 /*
761 * Don't let the user create a branch name with a leading '-'.
762 * While technically a valid reference name, this case is usually
763 * an unintended typo.
764 */
765 if (branch_name[0] == '-')
766 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
768 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
769 error = got_error_from_errno("asprintf");
770 goto done;
773 error = got_ref_open(&branch_ref, repo, refname, 0);
774 if (error) {
775 if (error->code != GOT_ERR_NOT_REF)
776 goto done;
777 } else {
778 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
779 "import target branch already exists");
780 goto done;
783 path_dir = realpath(argv[0], NULL);
784 if (path_dir == NULL) {
785 error = got_error_from_errno2("realpath", argv[0]);
786 goto done;
788 got_path_strip_trailing_slashes(path_dir);
790 /*
791 * unveil(2) traverses exec(2); if an editor is used we have
792 * to apply unveil after the log message has been written.
793 */
794 if (logmsg == NULL || strlen(logmsg) == 0) {
795 error = get_editor(&editor);
796 if (error)
797 goto done;
798 free(logmsg);
799 error = collect_import_msg(&logmsg, &logmsg_path, editor,
800 path_dir, refname);
801 if (error) {
802 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
803 logmsg_path != NULL)
804 preserve_logmsg = 1;
805 goto done;
809 if (unveil(path_dir, "r") != 0) {
810 error = got_error_from_errno2("unveil", path_dir);
811 if (logmsg_path)
812 preserve_logmsg = 1;
813 goto done;
816 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
817 if (error) {
818 if (logmsg_path)
819 preserve_logmsg = 1;
820 goto done;
823 error = got_repo_import(&new_commit_id, path_dir, logmsg,
824 author, &ignores, repo, import_progress, NULL);
825 if (error) {
826 if (logmsg_path)
827 preserve_logmsg = 1;
828 goto done;
831 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
832 if (error) {
833 if (logmsg_path)
834 preserve_logmsg = 1;
835 goto done;
838 error = got_ref_write(branch_ref, repo);
839 if (error) {
840 if (logmsg_path)
841 preserve_logmsg = 1;
842 goto done;
845 error = got_object_id_str(&id_str, new_commit_id);
846 if (error) {
847 if (logmsg_path)
848 preserve_logmsg = 1;
849 goto done;
852 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
853 if (error) {
854 if (error->code != GOT_ERR_NOT_REF) {
855 if (logmsg_path)
856 preserve_logmsg = 1;
857 goto done;
860 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
861 branch_ref);
862 if (error) {
863 if (logmsg_path)
864 preserve_logmsg = 1;
865 goto done;
868 error = got_ref_write(head_ref, repo);
869 if (error) {
870 if (logmsg_path)
871 preserve_logmsg = 1;
872 goto done;
876 printf("Created branch %s with commit %s\n",
877 got_ref_get_name(branch_ref), id_str);
878 done:
879 if (preserve_logmsg) {
880 fprintf(stderr, "%s: log message preserved in %s\n",
881 getprogname(), logmsg_path);
882 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
883 error = got_error_from_errno2("unlink", logmsg_path);
884 free(logmsg);
885 free(logmsg_path);
886 free(repo_path);
887 free(editor);
888 free(refname);
889 free(new_commit_id);
890 free(id_str);
891 free(author);
892 free(gitconfig_path);
893 if (branch_ref)
894 got_ref_close(branch_ref);
895 if (head_ref)
896 got_ref_close(head_ref);
897 return error;
900 __dead static void
901 usage_clone(void)
903 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
904 "[-R reference] repository-url [directory]\n", getprogname());
905 exit(1);
908 struct got_fetch_progress_arg {
909 char last_scaled_size[FMT_SCALED_STRSIZE];
910 int last_p_indexed;
911 int last_p_resolved;
912 int verbosity;
914 struct got_repository *repo;
916 int create_configs;
917 int configs_created;
918 struct {
919 struct got_pathlist_head *symrefs;
920 struct got_pathlist_head *wanted_branches;
921 const char *proto;
922 const char *host;
923 const char *port;
924 const char *remote_repo_path;
925 const char *git_url;
926 int fetch_all_branches;
927 int mirror_references;
928 } config_info;
929 };
931 /* XXX forward declaration */
932 static const struct got_error *
933 create_config_files(const char *proto, const char *host, const char *port,
934 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
935 int mirror_references, struct got_pathlist_head *symrefs,
936 struct got_pathlist_head *wanted_branches, struct got_repository *repo);
938 static const struct got_error *
939 fetch_progress(void *arg, const char *message, off_t packfile_size,
940 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
942 const struct got_error *err = NULL;
943 struct got_fetch_progress_arg *a = arg;
944 char scaled_size[FMT_SCALED_STRSIZE];
945 int p_indexed, p_resolved;
946 int print_size = 0, print_indexed = 0, print_resolved = 0;
948 /*
949 * In order to allow a failed clone to be resumed with 'got fetch'
950 * we try to create configuration files as soon as possible.
951 * Once the server has sent information about its default branch
952 * we have all required information.
953 */
954 if (a->create_configs && !a->configs_created &&
955 !TAILQ_EMPTY(a->config_info.symrefs)) {
956 err = create_config_files(a->config_info.proto,
957 a->config_info.host, a->config_info.port,
958 a->config_info.remote_repo_path,
959 a->config_info.git_url,
960 a->config_info.fetch_all_branches,
961 a->config_info.mirror_references,
962 a->config_info.symrefs,
963 a->config_info.wanted_branches, a->repo);
964 if (err)
965 return err;
966 a->configs_created = 1;
969 if (a->verbosity < 0)
970 return NULL;
972 if (message && message[0] != '\0') {
973 printf("\rserver: %s", message);
974 fflush(stdout);
975 return NULL;
978 if (packfile_size > 0 || nobj_indexed > 0) {
979 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
980 (a->last_scaled_size[0] == '\0' ||
981 strcmp(scaled_size, a->last_scaled_size)) != 0) {
982 print_size = 1;
983 if (strlcpy(a->last_scaled_size, scaled_size,
984 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
985 return got_error(GOT_ERR_NO_SPACE);
987 if (nobj_indexed > 0) {
988 p_indexed = (nobj_indexed * 100) / nobj_total;
989 if (p_indexed != a->last_p_indexed) {
990 a->last_p_indexed = p_indexed;
991 print_indexed = 1;
992 print_size = 1;
995 if (nobj_resolved > 0) {
996 p_resolved = (nobj_resolved * 100) /
997 (nobj_total - nobj_loose);
998 if (p_resolved != a->last_p_resolved) {
999 a->last_p_resolved = p_resolved;
1000 print_resolved = 1;
1001 print_indexed = 1;
1002 print_size = 1;
1007 if (print_size || print_indexed || print_resolved)
1008 printf("\r");
1009 if (print_size)
1010 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
1011 if (print_indexed)
1012 printf("; indexing %d%%", p_indexed);
1013 if (print_resolved)
1014 printf("; resolving deltas %d%%", p_resolved);
1015 if (print_size || print_indexed || print_resolved)
1016 fflush(stdout);
1018 return NULL;
1021 static const struct got_error *
1022 create_symref(const char *refname, struct got_reference *target_ref,
1023 int verbosity, struct got_repository *repo)
1025 const struct got_error *err;
1026 struct got_reference *head_symref;
1028 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1029 if (err)
1030 return err;
1032 err = got_ref_write(head_symref, repo);
1033 if (err == NULL && verbosity > 0) {
1034 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1035 got_ref_get_name(target_ref));
1037 got_ref_close(head_symref);
1038 return err;
1041 static const struct got_error *
1042 list_remote_refs(struct got_pathlist_head *symrefs,
1043 struct got_pathlist_head *refs)
1045 const struct got_error *err;
1046 struct got_pathlist_entry *pe;
1048 TAILQ_FOREACH(pe, symrefs, entry) {
1049 const char *refname = pe->path;
1050 const char *targetref = pe->data;
1052 printf("%s: %s\n", refname, targetref);
1055 TAILQ_FOREACH(pe, refs, entry) {
1056 const char *refname = pe->path;
1057 struct got_object_id *id = pe->data;
1058 char *id_str;
1060 err = got_object_id_str(&id_str, id);
1061 if (err)
1062 return err;
1063 printf("%s: %s\n", refname, id_str);
1064 free(id_str);
1067 return NULL;
1070 static const struct got_error *
1071 create_ref(const char *refname, struct got_object_id *id,
1072 int verbosity, struct got_repository *repo)
1074 const struct got_error *err = NULL;
1075 struct got_reference *ref;
1076 char *id_str;
1078 err = got_object_id_str(&id_str, id);
1079 if (err)
1080 return err;
1082 err = got_ref_alloc(&ref, refname, id);
1083 if (err)
1084 goto done;
1086 err = got_ref_write(ref, repo);
1087 got_ref_close(ref);
1089 if (err == NULL && verbosity >= 0)
1090 printf("Created reference %s: %s\n", refname, id_str);
1091 done:
1092 free(id_str);
1093 return err;
1096 static int
1097 match_wanted_ref(const char *refname, const char *wanted_ref)
1099 if (strncmp(refname, "refs/", 5) != 0)
1100 return 0;
1101 refname += 5;
1104 * Prevent fetching of references that won't make any
1105 * sense outside of the remote repository's context.
1107 if (strncmp(refname, "got/", 4) == 0)
1108 return 0;
1109 if (strncmp(refname, "remotes/", 8) == 0)
1110 return 0;
1112 if (strncmp(wanted_ref, "refs/", 5) == 0)
1113 wanted_ref += 5;
1115 /* Allow prefix match. */
1116 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1117 return 1;
1119 /* Allow exact match. */
1120 return (strcmp(refname, wanted_ref) == 0);
1123 static int
1124 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1126 struct got_pathlist_entry *pe;
1128 TAILQ_FOREACH(pe, wanted_refs, entry) {
1129 if (match_wanted_ref(refname, pe->path))
1130 return 1;
1133 return 0;
1136 static const struct got_error *
1137 create_wanted_ref(const char *refname, struct got_object_id *id,
1138 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1140 const struct got_error *err;
1141 char *remote_refname;
1143 if (strncmp("refs/", refname, 5) == 0)
1144 refname += 5;
1146 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1147 remote_repo_name, refname) == -1)
1148 return got_error_from_errno("asprintf");
1150 err = create_ref(remote_refname, id, verbosity, repo);
1151 free(remote_refname);
1152 return err;
1155 static const struct got_error *
1156 create_gotconfig(const char *proto, const char *host, const char *port,
1157 const char *remote_repo_path, int fetch_all_branches, int mirror_references,
1158 struct got_repository *repo)
1160 const struct got_error *err = NULL;
1161 char *gotconfig_path = NULL;
1162 char *gotconfig = NULL;
1163 FILE *gotconfig_file = NULL;
1164 ssize_t n;
1166 /* Create got.conf(5). */
1167 gotconfig_path = got_repo_get_path_gotconfig(repo);
1168 if (gotconfig_path == NULL) {
1169 err = got_error_from_errno("got_repo_get_path_gotconfig");
1170 goto done;
1172 gotconfig_file = fopen(gotconfig_path, "a");
1173 if (gotconfig_file == NULL) {
1174 err = got_error_from_errno2("fopen", gotconfig_path);
1175 goto done;
1177 if (asprintf(&gotconfig,
1178 "remote \"%s\" {\n"
1179 "\tserver %s\n"
1180 "\tprotocol %s\n"
1181 "%s%s%s"
1182 "\trepository \"%s\"\n"
1183 "%s"
1184 "}\n",
1185 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1186 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1187 remote_repo_path,
1188 mirror_references ? "\tmirror-references yes\n" : "") == -1) {
1189 err = got_error_from_errno("asprintf");
1190 goto done;
1192 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1193 if (n != strlen(gotconfig)) {
1194 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1195 goto done;
1198 done:
1199 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1200 err = got_error_from_errno2("fclose", gotconfig_path);
1201 free(gotconfig_path);
1202 return err;
1205 static const struct got_error *
1206 create_gitconfig(const char *git_url, const char *default_branch,
1207 int fetch_all_branches, int mirror_references, struct got_repository *repo)
1209 const struct got_error *err = NULL;
1210 char *gitconfig_path = NULL;
1211 char *gitconfig = NULL;
1212 FILE *gitconfig_file = NULL;
1213 ssize_t n;
1215 /* Create a config file Git can understand. */
1216 gitconfig_path = got_repo_get_path_gitconfig(repo);
1217 if (gitconfig_path == NULL) {
1218 err = got_error_from_errno("got_repo_get_path_gitconfig");
1219 goto done;
1221 gitconfig_file = fopen(gitconfig_path, "a");
1222 if (gitconfig_file == NULL) {
1223 err = got_error_from_errno2("fopen", gitconfig_path);
1224 goto done;
1226 if (mirror_references) {
1227 if (asprintf(&gitconfig,
1228 "[remote \"%s\"]\n"
1229 "\turl = %s\n"
1230 "\tfetch = +refs/*:refs/*\n"
1231 "\tmirror = true\n",
1232 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1233 err = got_error_from_errno("asprintf");
1234 goto done;
1236 } else if (fetch_all_branches) {
1237 if (asprintf(&gitconfig,
1238 "[remote \"%s\"]\n"
1239 "\turl = %s\n"
1240 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1241 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1242 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1243 err = got_error_from_errno("asprintf");
1244 goto done;
1246 } else {
1247 const char *branchname;
1250 * If the server specified a default branch, use just that one.
1251 * Otherwise fall back to fetching all branches on next fetch.
1253 if (default_branch) {
1254 branchname = default_branch;
1255 if (strncmp(branchname, "refs/heads/", 11) == 0)
1256 branchname += 11;
1257 } else
1258 branchname = "*"; /* fall back to all branches */
1259 if (asprintf(&gitconfig,
1260 "[remote \"%s\"]\n"
1261 "\turl = %s\n"
1262 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1263 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1264 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1265 branchname) == -1) {
1266 err = got_error_from_errno("asprintf");
1267 goto done;
1270 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1271 if (n != strlen(gitconfig)) {
1272 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1273 goto done;
1275 done:
1276 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1277 err = got_error_from_errno2("fclose", gitconfig_path);
1278 free(gitconfig_path);
1279 return err;
1282 static const struct got_error *
1283 create_config_files(const char *proto, const char *host, const char *port,
1284 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1285 int mirror_references, struct got_pathlist_head *symrefs,
1286 struct got_pathlist_head *wanted_branches, struct got_repository *repo)
1288 const struct got_error *err = NULL;
1289 const char *default_branch = NULL;
1290 struct got_pathlist_entry *pe;
1293 * If we asked for a set of wanted branches then use the first
1294 * one of those.
1296 if (!TAILQ_EMPTY(wanted_branches)) {
1297 pe = TAILQ_FIRST(wanted_branches);
1298 default_branch = pe->path;
1299 } else {
1300 /* First HEAD ref listed by server is the default branch. */
1301 TAILQ_FOREACH(pe, symrefs, entry) {
1302 const char *refname = pe->path;
1303 const char *target = pe->data;
1305 if (strcmp(refname, GOT_REF_HEAD) != 0)
1306 continue;
1308 default_branch = target;
1309 break;
1313 /* Create got.conf(5). */
1314 err = create_gotconfig(proto, host, port, remote_repo_path,
1315 fetch_all_branches, mirror_references, repo);
1316 if (err)
1317 return err;
1319 /* Create a config file Git can understand. */
1320 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1321 mirror_references, repo);
1324 static const struct got_error *
1325 cmd_clone(int argc, char *argv[])
1327 const struct got_error *error = NULL;
1328 const char *uri, *dirname;
1329 char *proto, *host, *port, *repo_name, *server_path;
1330 char *default_destdir = NULL, *id_str = NULL;
1331 const char *repo_path;
1332 struct got_repository *repo = NULL;
1333 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1334 struct got_pathlist_entry *pe;
1335 struct got_object_id *pack_hash = NULL;
1336 int ch, fetchfd = -1, fetchstatus;
1337 pid_t fetchpid = -1;
1338 struct got_fetch_progress_arg fpa;
1339 char *git_url = NULL;
1340 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1341 int list_refs_only = 0;
1343 TAILQ_INIT(&refs);
1344 TAILQ_INIT(&symrefs);
1345 TAILQ_INIT(&wanted_branches);
1346 TAILQ_INIT(&wanted_refs);
1348 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1349 switch (ch) {
1350 case 'a':
1351 fetch_all_branches = 1;
1352 break;
1353 case 'b':
1354 error = got_pathlist_append(&wanted_branches,
1355 optarg, NULL);
1356 if (error)
1357 return error;
1358 break;
1359 case 'l':
1360 list_refs_only = 1;
1361 break;
1362 case 'm':
1363 mirror_references = 1;
1364 break;
1365 case 'v':
1366 if (verbosity < 0)
1367 verbosity = 0;
1368 else if (verbosity < 3)
1369 verbosity++;
1370 break;
1371 case 'q':
1372 verbosity = -1;
1373 break;
1374 case 'R':
1375 error = got_pathlist_append(&wanted_refs,
1376 optarg, NULL);
1377 if (error)
1378 return error;
1379 break;
1380 default:
1381 usage_clone();
1382 break;
1385 argc -= optind;
1386 argv += optind;
1388 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1389 errx(1, "-a and -b options are mutually exclusive");
1390 if (list_refs_only) {
1391 if (!TAILQ_EMPTY(&wanted_branches))
1392 errx(1, "-l and -b options are mutually exclusive");
1393 if (fetch_all_branches)
1394 errx(1, "-l and -a options are mutually exclusive");
1395 if (mirror_references)
1396 errx(1, "-l and -m options are mutually exclusive");
1397 if (verbosity == -1)
1398 errx(1, "-l and -q options are mutually exclusive");
1399 if (!TAILQ_EMPTY(&wanted_refs))
1400 errx(1, "-l and -R options are mutually exclusive");
1403 uri = argv[0];
1405 if (argc == 1)
1406 dirname = NULL;
1407 else if (argc == 2)
1408 dirname = argv[1];
1409 else
1410 usage_clone();
1412 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1413 &repo_name, uri);
1414 if (error)
1415 goto done;
1417 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1418 host, port ? ":" : "", port ? port : "",
1419 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1420 error = got_error_from_errno("asprintf");
1421 goto done;
1424 if (strcmp(proto, "git") == 0) {
1425 #ifndef PROFILE
1426 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1427 "sendfd dns inet unveil", NULL) == -1)
1428 err(1, "pledge");
1429 #endif
1430 } else if (strcmp(proto, "git+ssh") == 0 ||
1431 strcmp(proto, "ssh") == 0) {
1432 #ifndef PROFILE
1433 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1434 "sendfd unveil", NULL) == -1)
1435 err(1, "pledge");
1436 #endif
1437 } else if (strcmp(proto, "http") == 0 ||
1438 strcmp(proto, "git+http") == 0) {
1439 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1440 goto done;
1441 } else {
1442 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1443 goto done;
1445 if (dirname == NULL) {
1446 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1447 error = got_error_from_errno("asprintf");
1448 goto done;
1450 repo_path = default_destdir;
1451 } else
1452 repo_path = dirname;
1454 if (!list_refs_only) {
1455 error = got_path_mkdir(repo_path);
1456 if (error &&
1457 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1458 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1459 goto done;
1460 if (!got_path_dir_is_empty(repo_path)) {
1461 error = got_error_path(repo_path,
1462 GOT_ERR_DIR_NOT_EMPTY);
1463 goto done;
1467 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1468 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1469 error = got_error_from_errno2("unveil",
1470 GOT_FETCH_PATH_SSH);
1471 goto done;
1474 error = apply_unveil(repo ? got_repo_get_path(repo) : NULL, 0, NULL);
1475 if (error)
1476 goto done;
1478 if (verbosity >= 0)
1479 printf("Connecting to %s%s%s\n", host,
1480 port ? ":" : "", port ? port : "");
1482 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1483 server_path, verbosity);
1484 if (error)
1485 goto done;
1487 if (!list_refs_only) {
1488 error = got_repo_init(repo_path);
1489 if (error)
1490 goto done;
1491 error = got_repo_open(&repo, repo_path, NULL);
1492 if (error)
1493 goto done;
1496 fpa.last_scaled_size[0] = '\0';
1497 fpa.last_p_indexed = -1;
1498 fpa.last_p_resolved = -1;
1499 fpa.verbosity = verbosity;
1500 fpa.create_configs = 1;
1501 fpa.configs_created = 0;
1502 fpa.repo = repo;
1503 fpa.config_info.symrefs = &symrefs;
1504 fpa.config_info.wanted_branches = &wanted_branches;
1505 fpa.config_info.proto = proto;
1506 fpa.config_info.host = host;
1507 fpa.config_info.port = port;
1508 fpa.config_info.remote_repo_path = server_path;
1509 fpa.config_info.git_url = git_url;
1510 fpa.config_info.fetch_all_branches = fetch_all_branches;
1511 fpa.config_info.mirror_references = mirror_references;
1512 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1513 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1514 fetch_all_branches, &wanted_branches, &wanted_refs,
1515 list_refs_only, verbosity, fetchfd, repo,
1516 fetch_progress, &fpa);
1517 if (error)
1518 goto done;
1520 if (list_refs_only) {
1521 error = list_remote_refs(&symrefs, &refs);
1522 goto done;
1525 error = got_object_id_str(&id_str, pack_hash);
1526 if (error)
1527 goto done;
1528 if (verbosity >= 0)
1529 printf("\nFetched %s.pack\n", id_str);
1530 free(id_str);
1532 /* Set up references provided with the pack file. */
1533 TAILQ_FOREACH(pe, &refs, entry) {
1534 const char *refname = pe->path;
1535 struct got_object_id *id = pe->data;
1536 char *remote_refname;
1538 if (is_wanted_ref(&wanted_refs, refname) &&
1539 !mirror_references) {
1540 error = create_wanted_ref(refname, id,
1541 GOT_FETCH_DEFAULT_REMOTE_NAME,
1542 verbosity - 1, repo);
1543 if (error)
1544 goto done;
1545 continue;
1548 error = create_ref(refname, id, verbosity - 1, repo);
1549 if (error)
1550 goto done;
1552 if (mirror_references)
1553 continue;
1555 if (strncmp("refs/heads/", refname, 11) != 0)
1556 continue;
1558 if (asprintf(&remote_refname,
1559 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1560 refname + 11) == -1) {
1561 error = got_error_from_errno("asprintf");
1562 goto done;
1564 error = create_ref(remote_refname, id, verbosity - 1, repo);
1565 free(remote_refname);
1566 if (error)
1567 goto done;
1570 /* Set the HEAD reference if the server provided one. */
1571 TAILQ_FOREACH(pe, &symrefs, entry) {
1572 struct got_reference *target_ref;
1573 const char *refname = pe->path;
1574 const char *target = pe->data;
1575 char *remote_refname = NULL, *remote_target = NULL;
1577 if (strcmp(refname, GOT_REF_HEAD) != 0)
1578 continue;
1580 error = got_ref_open(&target_ref, repo, target, 0);
1581 if (error) {
1582 if (error->code == GOT_ERR_NOT_REF) {
1583 error = NULL;
1584 continue;
1586 goto done;
1589 error = create_symref(refname, target_ref, verbosity, repo);
1590 got_ref_close(target_ref);
1591 if (error)
1592 goto done;
1594 if (mirror_references)
1595 continue;
1597 if (strncmp("refs/heads/", target, 11) != 0)
1598 continue;
1600 if (asprintf(&remote_refname,
1601 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1602 refname) == -1) {
1603 error = got_error_from_errno("asprintf");
1604 goto done;
1606 if (asprintf(&remote_target,
1607 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1608 target + 11) == -1) {
1609 error = got_error_from_errno("asprintf");
1610 free(remote_refname);
1611 goto done;
1613 error = got_ref_open(&target_ref, repo, remote_target, 0);
1614 if (error) {
1615 free(remote_refname);
1616 free(remote_target);
1617 if (error->code == GOT_ERR_NOT_REF) {
1618 error = NULL;
1619 continue;
1621 goto done;
1623 error = create_symref(remote_refname, target_ref,
1624 verbosity - 1, repo);
1625 free(remote_refname);
1626 free(remote_target);
1627 got_ref_close(target_ref);
1628 if (error)
1629 goto done;
1631 if (pe == NULL) {
1633 * We failed to set the HEAD reference. If we asked for
1634 * a set of wanted branches use the first of one of those
1635 * which could be fetched instead.
1637 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1638 const char *target = pe->path;
1639 struct got_reference *target_ref;
1641 error = got_ref_open(&target_ref, repo, target, 0);
1642 if (error) {
1643 if (error->code == GOT_ERR_NOT_REF) {
1644 error = NULL;
1645 continue;
1647 goto done;
1650 error = create_symref(GOT_REF_HEAD, target_ref,
1651 verbosity, repo);
1652 got_ref_close(target_ref);
1653 if (error)
1654 goto done;
1655 break;
1659 if (verbosity >= 0)
1660 printf("Created %s repository '%s'\n",
1661 mirror_references ? "mirrored" : "cloned", repo_path);
1662 done:
1663 if (fetchpid > 0) {
1664 if (kill(fetchpid, SIGTERM) == -1)
1665 error = got_error_from_errno("kill");
1666 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1667 error = got_error_from_errno("waitpid");
1669 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1670 error = got_error_from_errno("close");
1671 if (repo)
1672 got_repo_close(repo);
1673 TAILQ_FOREACH(pe, &refs, entry) {
1674 free((void *)pe->path);
1675 free(pe->data);
1677 got_pathlist_free(&refs);
1678 TAILQ_FOREACH(pe, &symrefs, entry) {
1679 free((void *)pe->path);
1680 free(pe->data);
1682 got_pathlist_free(&symrefs);
1683 got_pathlist_free(&wanted_branches);
1684 got_pathlist_free(&wanted_refs);
1685 free(pack_hash);
1686 free(proto);
1687 free(host);
1688 free(port);
1689 free(server_path);
1690 free(repo_name);
1691 free(default_destdir);
1692 free(git_url);
1693 return error;
1696 static const struct got_error *
1697 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1698 int replace_tags, int verbosity, struct got_repository *repo)
1700 const struct got_error *err = NULL;
1701 char *new_id_str = NULL;
1702 struct got_object_id *old_id = NULL;
1704 err = got_object_id_str(&new_id_str, new_id);
1705 if (err)
1706 goto done;
1708 if (!replace_tags &&
1709 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1710 err = got_ref_resolve(&old_id, repo, ref);
1711 if (err)
1712 goto done;
1713 if (got_object_id_cmp(old_id, new_id) == 0)
1714 goto done;
1715 if (verbosity >= 0) {
1716 printf("Rejecting update of existing tag %s: %s\n",
1717 got_ref_get_name(ref), new_id_str);
1719 goto done;
1722 if (got_ref_is_symbolic(ref)) {
1723 if (verbosity >= 0) {
1724 printf("Replacing reference %s: %s\n",
1725 got_ref_get_name(ref),
1726 got_ref_get_symref_target(ref));
1728 err = got_ref_change_symref_to_ref(ref, new_id);
1729 if (err)
1730 goto done;
1731 err = got_ref_write(ref, repo);
1732 if (err)
1733 goto done;
1734 } else {
1735 err = got_ref_resolve(&old_id, repo, ref);
1736 if (err)
1737 goto done;
1738 if (got_object_id_cmp(old_id, new_id) == 0)
1739 goto done;
1741 err = got_ref_change_ref(ref, new_id);
1742 if (err)
1743 goto done;
1744 err = got_ref_write(ref, repo);
1745 if (err)
1746 goto done;
1749 if (verbosity >= 0)
1750 printf("Updated %s: %s\n", got_ref_get_name(ref),
1751 new_id_str);
1752 done:
1753 free(old_id);
1754 free(new_id_str);
1755 return err;
1758 static const struct got_error *
1759 update_symref(const char *refname, struct got_reference *target_ref,
1760 int verbosity, struct got_repository *repo)
1762 const struct got_error *err = NULL, *unlock_err;
1763 struct got_reference *symref;
1764 int symref_is_locked = 0;
1766 err = got_ref_open(&symref, repo, refname, 1);
1767 if (err) {
1768 if (err->code != GOT_ERR_NOT_REF)
1769 return err;
1770 err = got_ref_alloc_symref(&symref, refname, target_ref);
1771 if (err)
1772 goto done;
1774 err = got_ref_write(symref, repo);
1775 if (err)
1776 goto done;
1778 if (verbosity >= 0)
1779 printf("Created reference %s: %s\n",
1780 got_ref_get_name(symref),
1781 got_ref_get_symref_target(symref));
1782 } else {
1783 symref_is_locked = 1;
1785 if (strcmp(got_ref_get_symref_target(symref),
1786 got_ref_get_name(target_ref)) == 0)
1787 goto done;
1789 err = got_ref_change_symref(symref,
1790 got_ref_get_name(target_ref));
1791 if (err)
1792 goto done;
1794 err = got_ref_write(symref, repo);
1795 if (err)
1796 goto done;
1798 if (verbosity >= 0)
1799 printf("Updated %s: %s\n", got_ref_get_name(symref),
1800 got_ref_get_symref_target(symref));
1803 done:
1804 if (symref_is_locked) {
1805 unlock_err = got_ref_unlock(symref);
1806 if (unlock_err && err == NULL)
1807 err = unlock_err;
1809 got_ref_close(symref);
1810 return err;
1813 __dead static void
1814 usage_fetch(void)
1816 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1817 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1818 "[remote-repository-name]\n",
1819 getprogname());
1820 exit(1);
1823 static const struct got_error *
1824 delete_missing_ref(struct got_reference *ref,
1825 int verbosity, struct got_repository *repo)
1827 const struct got_error *err = NULL;
1828 struct got_object_id *id = NULL;
1829 char *id_str = NULL;
1831 if (got_ref_is_symbolic(ref)) {
1832 err = got_ref_delete(ref, repo);
1833 if (err)
1834 return err;
1835 if (verbosity >= 0) {
1836 printf("Deleted reference %s: %s\n",
1837 got_ref_get_name(ref),
1838 got_ref_get_symref_target(ref));
1840 } else {
1841 err = got_ref_resolve(&id, repo, ref);
1842 if (err)
1843 return err;
1844 err = got_object_id_str(&id_str, id);
1845 if (err)
1846 goto done;
1848 err = got_ref_delete(ref, repo);
1849 if (err)
1850 goto done;
1851 if (verbosity >= 0) {
1852 printf("Deleted reference %s: %s\n",
1853 got_ref_get_name(ref), id_str);
1856 done:
1857 free(id);
1858 free(id_str);
1859 return NULL;
1862 static const struct got_error *
1863 delete_missing_refs(struct got_pathlist_head *their_refs,
1864 struct got_pathlist_head *their_symrefs,
1865 const struct got_remote_repo *remote,
1866 int verbosity, struct got_repository *repo)
1868 const struct got_error *err = NULL, *unlock_err;
1869 struct got_reflist_head my_refs;
1870 struct got_reflist_entry *re;
1871 struct got_pathlist_entry *pe;
1872 char *remote_namespace = NULL;
1873 char *local_refname = NULL;
1875 SIMPLEQ_INIT(&my_refs);
1877 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
1878 == -1)
1879 return got_error_from_errno("asprintf");
1881 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1882 if (err)
1883 goto done;
1885 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1886 const char *refname = got_ref_get_name(re->ref);
1888 if (!remote->mirror_references) {
1889 if (strncmp(refname, remote_namespace,
1890 strlen(remote_namespace)) == 0) {
1891 if (strcmp(refname + strlen(remote_namespace),
1892 GOT_REF_HEAD) == 0)
1893 continue;
1894 if (asprintf(&local_refname, "refs/heads/%s",
1895 refname + strlen(remote_namespace)) == -1) {
1896 err = got_error_from_errno("asprintf");
1897 goto done;
1899 } else if (strncmp(refname, "refs/tags/", 10) != 0)
1900 continue;
1903 TAILQ_FOREACH(pe, their_refs, entry) {
1904 if (strcmp(local_refname, pe->path) == 0)
1905 break;
1907 if (pe != NULL)
1908 continue;
1910 TAILQ_FOREACH(pe, their_symrefs, entry) {
1911 if (strcmp(local_refname, pe->path) == 0)
1912 break;
1914 if (pe != NULL)
1915 continue;
1917 err = delete_missing_ref(re->ref, verbosity, repo);
1918 if (err)
1919 break;
1921 if (local_refname) {
1922 struct got_reference *ref;
1923 err = got_ref_open(&ref, repo, local_refname, 1);
1924 if (err) {
1925 if (err->code != GOT_ERR_NOT_REF)
1926 break;
1927 free(local_refname);
1928 local_refname = NULL;
1929 continue;
1931 err = delete_missing_ref(ref, verbosity, repo);
1932 if (err)
1933 break;
1934 unlock_err = got_ref_unlock(ref);
1935 got_ref_close(ref);
1936 if (unlock_err && err == NULL) {
1937 err = unlock_err;
1938 break;
1941 free(local_refname);
1942 local_refname = NULL;
1945 done:
1946 free(remote_namespace);
1947 free(local_refname);
1948 return err;
1951 static const struct got_error *
1952 update_wanted_ref(const char *refname, struct got_object_id *id,
1953 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1955 const struct got_error *err, *unlock_err;
1956 char *remote_refname;
1957 struct got_reference *ref;
1959 if (strncmp("refs/", refname, 5) == 0)
1960 refname += 5;
1962 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1963 remote_repo_name, refname) == -1)
1964 return got_error_from_errno("asprintf");
1966 err = got_ref_open(&ref, repo, remote_refname, 1);
1967 if (err) {
1968 if (err->code != GOT_ERR_NOT_REF)
1969 goto done;
1970 err = create_ref(remote_refname, id, verbosity, repo);
1971 } else {
1972 err = update_ref(ref, id, 0, verbosity, repo);
1973 unlock_err = got_ref_unlock(ref);
1974 if (unlock_err && err == NULL)
1975 err = unlock_err;
1976 got_ref_close(ref);
1978 done:
1979 free(remote_refname);
1980 return err;
1983 static const struct got_error *
1984 cmd_fetch(int argc, char *argv[])
1986 const struct got_error *error = NULL, *unlock_err;
1987 char *cwd = NULL, *repo_path = NULL;
1988 const char *remote_name;
1989 char *proto = NULL, *host = NULL, *port = NULL;
1990 char *repo_name = NULL, *server_path = NULL;
1991 const struct got_remote_repo *remotes, *remote = NULL;
1992 int nremotes;
1993 char *id_str = NULL;
1994 struct got_repository *repo = NULL;
1995 struct got_worktree *worktree = NULL;
1996 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
1997 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1998 struct got_pathlist_entry *pe;
1999 struct got_object_id *pack_hash = NULL;
2000 int i, ch, fetchfd = -1, fetchstatus;
2001 pid_t fetchpid = -1;
2002 struct got_fetch_progress_arg fpa;
2003 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2004 int delete_refs = 0, replace_tags = 0;
2006 TAILQ_INIT(&refs);
2007 TAILQ_INIT(&symrefs);
2008 TAILQ_INIT(&wanted_branches);
2009 TAILQ_INIT(&wanted_refs);
2011 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
2012 switch (ch) {
2013 case 'a':
2014 fetch_all_branches = 1;
2015 break;
2016 case 'b':
2017 error = got_pathlist_append(&wanted_branches,
2018 optarg, NULL);
2019 if (error)
2020 return error;
2021 break;
2022 case 'd':
2023 delete_refs = 1;
2024 break;
2025 case 'l':
2026 list_refs_only = 1;
2027 break;
2028 case 'r':
2029 repo_path = realpath(optarg, NULL);
2030 if (repo_path == NULL)
2031 return got_error_from_errno2("realpath",
2032 optarg);
2033 got_path_strip_trailing_slashes(repo_path);
2034 break;
2035 case 't':
2036 replace_tags = 1;
2037 break;
2038 case 'v':
2039 if (verbosity < 0)
2040 verbosity = 0;
2041 else if (verbosity < 3)
2042 verbosity++;
2043 break;
2044 case 'q':
2045 verbosity = -1;
2046 break;
2047 case 'R':
2048 error = got_pathlist_append(&wanted_refs,
2049 optarg, NULL);
2050 if (error)
2051 return error;
2052 break;
2053 default:
2054 usage_fetch();
2055 break;
2058 argc -= optind;
2059 argv += optind;
2061 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2062 errx(1, "-a and -b options are mutually exclusive");
2063 if (list_refs_only) {
2064 if (!TAILQ_EMPTY(&wanted_branches))
2065 errx(1, "-l and -b options are mutually exclusive");
2066 if (fetch_all_branches)
2067 errx(1, "-l and -a options are mutually exclusive");
2068 if (delete_refs)
2069 errx(1, "-l and -d options are mutually exclusive");
2070 if (verbosity == -1)
2071 errx(1, "-l and -q options are mutually exclusive");
2074 if (argc == 0)
2075 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2076 else if (argc == 1)
2077 remote_name = argv[0];
2078 else
2079 usage_fetch();
2081 cwd = getcwd(NULL, 0);
2082 if (cwd == NULL) {
2083 error = got_error_from_errno("getcwd");
2084 goto done;
2087 if (repo_path == NULL) {
2088 error = got_worktree_open(&worktree, cwd);
2089 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2090 goto done;
2091 else
2092 error = NULL;
2093 if (worktree) {
2094 repo_path =
2095 strdup(got_worktree_get_repo_path(worktree));
2096 if (repo_path == NULL)
2097 error = got_error_from_errno("strdup");
2098 if (error)
2099 goto done;
2100 } else {
2101 repo_path = strdup(cwd);
2102 if (repo_path == NULL) {
2103 error = got_error_from_errno("strdup");
2104 goto done;
2109 error = got_repo_open(&repo, repo_path, NULL);
2110 if (error)
2111 goto done;
2113 if (worktree) {
2114 worktree_conf = got_worktree_get_gotconfig(worktree);
2115 if (worktree_conf) {
2116 got_gotconfig_get_remotes(&nremotes, &remotes,
2117 worktree_conf);
2118 for (i = 0; i < nremotes; i++) {
2119 remote = &remotes[i];
2120 if (strcmp(remote->name, remote_name) == 0)
2121 break;
2125 if (remote == NULL) {
2126 repo_conf = got_repo_get_gotconfig(repo);
2127 if (repo_conf) {
2128 got_gotconfig_get_remotes(&nremotes, &remotes,
2129 repo_conf);
2130 for (i = 0; i < nremotes; i++) {
2131 remote = &remotes[i];
2132 if (strcmp(remote->name, remote_name) == 0)
2133 break;
2137 if (remote == NULL) {
2138 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2139 for (i = 0; i < nremotes; i++) {
2140 remote = &remotes[i];
2141 if (strcmp(remote->name, remote_name) == 0)
2142 break;
2145 if (remote == NULL) {
2146 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2147 goto done;
2150 if (TAILQ_EMPTY(&wanted_branches) && remote->nbranches > 0) {
2151 for (i = 0; i < remote->nbranches; i++) {
2152 got_pathlist_append(&wanted_branches,
2153 remote->branches[i], NULL);
2158 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
2159 &repo_name, remote->url);
2160 if (error)
2161 goto done;
2163 if (strcmp(proto, "git") == 0) {
2164 #ifndef PROFILE
2165 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2166 "sendfd dns inet unveil", NULL) == -1)
2167 err(1, "pledge");
2168 #endif
2169 } else if (strcmp(proto, "git+ssh") == 0 ||
2170 strcmp(proto, "ssh") == 0) {
2171 #ifndef PROFILE
2172 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2173 "sendfd unveil", NULL) == -1)
2174 err(1, "pledge");
2175 #endif
2176 } else if (strcmp(proto, "http") == 0 ||
2177 strcmp(proto, "git+http") == 0) {
2178 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2179 goto done;
2180 } else {
2181 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2182 goto done;
2185 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
2186 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
2187 error = got_error_from_errno2("unveil",
2188 GOT_FETCH_PATH_SSH);
2189 goto done;
2192 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2193 if (error)
2194 goto done;
2196 if (verbosity >= 0)
2197 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2198 port ? ":" : "", port ? port : "");
2200 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2201 server_path, verbosity);
2202 if (error)
2203 goto done;
2205 fpa.last_scaled_size[0] = '\0';
2206 fpa.last_p_indexed = -1;
2207 fpa.last_p_resolved = -1;
2208 fpa.verbosity = verbosity;
2209 fpa.repo = repo;
2210 fpa.create_configs = 0;
2211 fpa.configs_created = 0;
2212 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2213 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2214 remote->mirror_references, fetch_all_branches, &wanted_branches,
2215 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2216 fetch_progress, &fpa);
2217 if (error)
2218 goto done;
2220 if (list_refs_only) {
2221 error = list_remote_refs(&symrefs, &refs);
2222 goto done;
2225 if (pack_hash == NULL) {
2226 if (verbosity >= 0)
2227 printf("Already up-to-date\n");
2228 } else if (verbosity >= 0) {
2229 error = got_object_id_str(&id_str, pack_hash);
2230 if (error)
2231 goto done;
2232 printf("\nFetched %s.pack\n", id_str);
2233 free(id_str);
2234 id_str = NULL;
2237 /* Update references provided with the pack file. */
2238 TAILQ_FOREACH(pe, &refs, entry) {
2239 const char *refname = pe->path;
2240 struct got_object_id *id = pe->data;
2241 struct got_reference *ref;
2242 char *remote_refname;
2244 if (is_wanted_ref(&wanted_refs, refname) &&
2245 !remote->mirror_references) {
2246 error = update_wanted_ref(refname, id,
2247 remote->name, verbosity, repo);
2248 if (error)
2249 goto done;
2250 continue;
2253 if (remote->mirror_references ||
2254 strncmp("refs/tags/", refname, 10) == 0) {
2255 error = got_ref_open(&ref, repo, refname, 1);
2256 if (error) {
2257 if (error->code != GOT_ERR_NOT_REF)
2258 goto done;
2259 error = create_ref(refname, id, verbosity,
2260 repo);
2261 if (error)
2262 goto done;
2263 } else {
2264 error = update_ref(ref, id, replace_tags,
2265 verbosity, repo);
2266 unlock_err = got_ref_unlock(ref);
2267 if (unlock_err && error == NULL)
2268 error = unlock_err;
2269 got_ref_close(ref);
2270 if (error)
2271 goto done;
2273 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2274 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2275 remote_name, refname + 11) == -1) {
2276 error = got_error_from_errno("asprintf");
2277 goto done;
2280 error = got_ref_open(&ref, repo, remote_refname, 1);
2281 if (error) {
2282 if (error->code != GOT_ERR_NOT_REF)
2283 goto done;
2284 error = create_ref(remote_refname, id,
2285 verbosity, repo);
2286 if (error)
2287 goto done;
2288 } else {
2289 error = update_ref(ref, id, replace_tags,
2290 verbosity, repo);
2291 unlock_err = got_ref_unlock(ref);
2292 if (unlock_err && error == NULL)
2293 error = unlock_err;
2294 got_ref_close(ref);
2295 if (error)
2296 goto done;
2299 /* Also create a local branch if none exists yet. */
2300 error = got_ref_open(&ref, repo, refname, 1);
2301 if (error) {
2302 if (error->code != GOT_ERR_NOT_REF)
2303 goto done;
2304 error = create_ref(refname, id, verbosity,
2305 repo);
2306 if (error)
2307 goto done;
2308 } else {
2309 unlock_err = got_ref_unlock(ref);
2310 if (unlock_err && error == NULL)
2311 error = unlock_err;
2312 got_ref_close(ref);
2316 if (delete_refs) {
2317 error = delete_missing_refs(&refs, &symrefs, remote,
2318 verbosity, repo);
2319 if (error)
2320 goto done;
2323 if (!remote->mirror_references) {
2324 /* Update remote HEAD reference if the server provided one. */
2325 TAILQ_FOREACH(pe, &symrefs, entry) {
2326 struct got_reference *target_ref;
2327 const char *refname = pe->path;
2328 const char *target = pe->data;
2329 char *remote_refname = NULL, *remote_target = NULL;
2331 if (strcmp(refname, GOT_REF_HEAD) != 0)
2332 continue;
2334 if (strncmp("refs/heads/", target, 11) != 0)
2335 continue;
2337 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2338 remote->name, refname) == -1) {
2339 error = got_error_from_errno("asprintf");
2340 goto done;
2342 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2343 remote->name, target + 11) == -1) {
2344 error = got_error_from_errno("asprintf");
2345 free(remote_refname);
2346 goto done;
2349 error = got_ref_open(&target_ref, repo, remote_target,
2350 0);
2351 if (error) {
2352 free(remote_refname);
2353 free(remote_target);
2354 if (error->code == GOT_ERR_NOT_REF) {
2355 error = NULL;
2356 continue;
2358 goto done;
2360 error = update_symref(remote_refname, target_ref,
2361 verbosity, repo);
2362 free(remote_refname);
2363 free(remote_target);
2364 got_ref_close(target_ref);
2365 if (error)
2366 goto done;
2369 done:
2370 if (fetchpid > 0) {
2371 if (kill(fetchpid, SIGTERM) == -1)
2372 error = got_error_from_errno("kill");
2373 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2374 error = got_error_from_errno("waitpid");
2376 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2377 error = got_error_from_errno("close");
2378 if (repo)
2379 got_repo_close(repo);
2380 if (worktree)
2381 got_worktree_close(worktree);
2382 TAILQ_FOREACH(pe, &refs, entry) {
2383 free((void *)pe->path);
2384 free(pe->data);
2386 got_pathlist_free(&refs);
2387 TAILQ_FOREACH(pe, &symrefs, entry) {
2388 free((void *)pe->path);
2389 free(pe->data);
2391 got_pathlist_free(&symrefs);
2392 got_pathlist_free(&wanted_branches);
2393 got_pathlist_free(&wanted_refs);
2394 free(id_str);
2395 free(cwd);
2396 free(repo_path);
2397 free(pack_hash);
2398 free(proto);
2399 free(host);
2400 free(port);
2401 free(server_path);
2402 free(repo_name);
2403 return error;
2407 __dead static void
2408 usage_checkout(void)
2410 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2411 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2412 exit(1);
2415 static void
2416 show_worktree_base_ref_warning(void)
2418 fprintf(stderr, "%s: warning: could not create a reference "
2419 "to the work tree's base commit; the commit could be "
2420 "garbage-collected by Git; making the repository "
2421 "writable and running 'got update' will prevent this\n",
2422 getprogname());
2425 struct got_checkout_progress_arg {
2426 const char *worktree_path;
2427 int had_base_commit_ref_error;
2430 static const struct got_error *
2431 checkout_progress(void *arg, unsigned char status, const char *path)
2433 struct got_checkout_progress_arg *a = arg;
2435 /* Base commit bump happens silently. */
2436 if (status == GOT_STATUS_BUMP_BASE)
2437 return NULL;
2439 if (status == GOT_STATUS_BASE_REF_ERR) {
2440 a->had_base_commit_ref_error = 1;
2441 return NULL;
2444 while (path[0] == '/')
2445 path++;
2447 printf("%c %s/%s\n", status, a->worktree_path, path);
2448 return NULL;
2451 static const struct got_error *
2452 check_cancelled(void *arg)
2454 if (sigint_received || sigpipe_received)
2455 return got_error(GOT_ERR_CANCELLED);
2456 return NULL;
2459 static const struct got_error *
2460 check_linear_ancestry(struct got_object_id *commit_id,
2461 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2462 struct got_repository *repo)
2464 const struct got_error *err = NULL;
2465 struct got_object_id *yca_id;
2467 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2468 commit_id, base_commit_id, repo, check_cancelled, NULL);
2469 if (err)
2470 return err;
2472 if (yca_id == NULL)
2473 return got_error(GOT_ERR_ANCESTRY);
2476 * Require a straight line of history between the target commit
2477 * and the work tree's base commit.
2479 * Non-linear situations such as this require a rebase:
2481 * (commit) D F (base_commit)
2482 * \ /
2483 * C E
2484 * \ /
2485 * B (yca)
2486 * |
2487 * A
2489 * 'got update' only handles linear cases:
2490 * Update forwards in time: A (base/yca) - B - C - D (commit)
2491 * Update backwards in time: D (base) - C - B - A (commit/yca)
2493 if (allow_forwards_in_time_only) {
2494 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2495 return got_error(GOT_ERR_ANCESTRY);
2496 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2497 got_object_id_cmp(base_commit_id, yca_id) != 0)
2498 return got_error(GOT_ERR_ANCESTRY);
2500 free(yca_id);
2501 return NULL;
2504 static const struct got_error *
2505 check_same_branch(struct got_object_id *commit_id,
2506 struct got_reference *head_ref, struct got_object_id *yca_id,
2507 struct got_repository *repo)
2509 const struct got_error *err = NULL;
2510 struct got_commit_graph *graph = NULL;
2511 struct got_object_id *head_commit_id = NULL;
2512 int is_same_branch = 0;
2514 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2515 if (err)
2516 goto done;
2518 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2519 is_same_branch = 1;
2520 goto done;
2522 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2523 is_same_branch = 1;
2524 goto done;
2527 err = got_commit_graph_open(&graph, "/", 1);
2528 if (err)
2529 goto done;
2531 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2532 check_cancelled, NULL);
2533 if (err)
2534 goto done;
2536 for (;;) {
2537 struct got_object_id *id;
2538 err = got_commit_graph_iter_next(&id, graph, repo,
2539 check_cancelled, NULL);
2540 if (err) {
2541 if (err->code == GOT_ERR_ITER_COMPLETED)
2542 err = NULL;
2543 break;
2546 if (id) {
2547 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2548 break;
2549 if (got_object_id_cmp(id, commit_id) == 0) {
2550 is_same_branch = 1;
2551 break;
2555 done:
2556 if (graph)
2557 got_commit_graph_close(graph);
2558 free(head_commit_id);
2559 if (!err && !is_same_branch)
2560 err = got_error(GOT_ERR_ANCESTRY);
2561 return err;
2564 static const struct got_error *
2565 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2567 static char msg[512];
2568 const char *branch_name;
2570 if (got_ref_is_symbolic(ref))
2571 branch_name = got_ref_get_symref_target(ref);
2572 else
2573 branch_name = got_ref_get_name(ref);
2575 if (strncmp("refs/heads/", branch_name, 11) == 0)
2576 branch_name += 11;
2578 snprintf(msg, sizeof(msg),
2579 "target commit is not contained in branch '%s'; "
2580 "the branch to use must be specified with -b; "
2581 "if necessary a new branch can be created for "
2582 "this commit with 'got branch -c %s BRANCH_NAME'",
2583 branch_name, commit_id_str);
2585 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2588 static const struct got_error *
2589 cmd_checkout(int argc, char *argv[])
2591 const struct got_error *error = NULL;
2592 struct got_repository *repo = NULL;
2593 struct got_reference *head_ref = NULL;
2594 struct got_worktree *worktree = NULL;
2595 char *repo_path = NULL;
2596 char *worktree_path = NULL;
2597 const char *path_prefix = "";
2598 const char *branch_name = GOT_REF_HEAD;
2599 char *commit_id_str = NULL;
2600 char *cwd = NULL, *path = NULL;
2601 int ch, same_path_prefix, allow_nonempty = 0;
2602 struct got_pathlist_head paths;
2603 struct got_checkout_progress_arg cpa;
2605 TAILQ_INIT(&paths);
2607 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2608 switch (ch) {
2609 case 'b':
2610 branch_name = optarg;
2611 break;
2612 case 'c':
2613 commit_id_str = strdup(optarg);
2614 if (commit_id_str == NULL)
2615 return got_error_from_errno("strdup");
2616 break;
2617 case 'E':
2618 allow_nonempty = 1;
2619 break;
2620 case 'p':
2621 path_prefix = optarg;
2622 break;
2623 default:
2624 usage_checkout();
2625 /* NOTREACHED */
2629 argc -= optind;
2630 argv += optind;
2632 #ifndef PROFILE
2633 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2634 "unveil", NULL) == -1)
2635 err(1, "pledge");
2636 #endif
2637 if (argc == 1) {
2638 char *base, *dotgit;
2639 repo_path = realpath(argv[0], NULL);
2640 if (repo_path == NULL)
2641 return got_error_from_errno2("realpath", argv[0]);
2642 cwd = getcwd(NULL, 0);
2643 if (cwd == NULL) {
2644 error = got_error_from_errno("getcwd");
2645 goto done;
2647 if (path_prefix[0])
2648 path = strdup(path_prefix);
2649 else
2650 path = strdup(repo_path);
2651 if (path == NULL) {
2652 error = got_error_from_errno("strdup");
2653 goto done;
2655 base = basename(path);
2656 if (base == NULL) {
2657 error = got_error_from_errno2("basename", path);
2658 goto done;
2660 dotgit = strstr(base, ".git");
2661 if (dotgit)
2662 *dotgit = '\0';
2663 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2664 error = got_error_from_errno("asprintf");
2665 goto done;
2667 } else if (argc == 2) {
2668 repo_path = realpath(argv[0], NULL);
2669 if (repo_path == NULL) {
2670 error = got_error_from_errno2("realpath", argv[0]);
2671 goto done;
2673 worktree_path = realpath(argv[1], NULL);
2674 if (worktree_path == NULL) {
2675 if (errno != ENOENT) {
2676 error = got_error_from_errno2("realpath",
2677 argv[1]);
2678 goto done;
2680 worktree_path = strdup(argv[1]);
2681 if (worktree_path == NULL) {
2682 error = got_error_from_errno("strdup");
2683 goto done;
2686 } else
2687 usage_checkout();
2689 got_path_strip_trailing_slashes(repo_path);
2690 got_path_strip_trailing_slashes(worktree_path);
2692 error = got_repo_open(&repo, repo_path, NULL);
2693 if (error != NULL)
2694 goto done;
2696 /* Pre-create work tree path for unveil(2) */
2697 error = got_path_mkdir(worktree_path);
2698 if (error) {
2699 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2700 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2701 goto done;
2702 if (!allow_nonempty &&
2703 !got_path_dir_is_empty(worktree_path)) {
2704 error = got_error_path(worktree_path,
2705 GOT_ERR_DIR_NOT_EMPTY);
2706 goto done;
2710 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2711 if (error)
2712 goto done;
2714 error = got_ref_open(&head_ref, repo, branch_name, 0);
2715 if (error != NULL)
2716 goto done;
2718 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2719 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2720 goto done;
2722 error = got_worktree_open(&worktree, worktree_path);
2723 if (error != NULL)
2724 goto done;
2726 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2727 path_prefix);
2728 if (error != NULL)
2729 goto done;
2730 if (!same_path_prefix) {
2731 error = got_error(GOT_ERR_PATH_PREFIX);
2732 goto done;
2735 if (commit_id_str) {
2736 struct got_object_id *commit_id;
2737 error = got_repo_match_object_id(&commit_id, NULL,
2738 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2739 if (error)
2740 goto done;
2741 error = check_linear_ancestry(commit_id,
2742 got_worktree_get_base_commit_id(worktree), 0, repo);
2743 if (error != NULL) {
2744 free(commit_id);
2745 if (error->code == GOT_ERR_ANCESTRY) {
2746 error = checkout_ancestry_error(
2747 head_ref, commit_id_str);
2749 goto done;
2751 error = check_same_branch(commit_id, head_ref, NULL, repo);
2752 if (error) {
2753 if (error->code == GOT_ERR_ANCESTRY) {
2754 error = checkout_ancestry_error(
2755 head_ref, commit_id_str);
2757 goto done;
2759 error = got_worktree_set_base_commit_id(worktree, repo,
2760 commit_id);
2761 free(commit_id);
2762 if (error)
2763 goto done;
2766 error = got_pathlist_append(&paths, "", NULL);
2767 if (error)
2768 goto done;
2769 cpa.worktree_path = worktree_path;
2770 cpa.had_base_commit_ref_error = 0;
2771 error = got_worktree_checkout_files(worktree, &paths, repo,
2772 checkout_progress, &cpa, check_cancelled, NULL);
2773 if (error != NULL)
2774 goto done;
2776 printf("Now shut up and hack\n");
2777 if (cpa.had_base_commit_ref_error)
2778 show_worktree_base_ref_warning();
2779 done:
2780 got_pathlist_free(&paths);
2781 free(commit_id_str);
2782 free(repo_path);
2783 free(worktree_path);
2784 free(cwd);
2785 free(path);
2786 return error;
2789 struct got_update_progress_arg {
2790 int did_something;
2791 int conflicts;
2792 int obstructed;
2793 int not_updated;
2796 void
2797 print_update_progress_stats(struct got_update_progress_arg *upa)
2799 if (!upa->did_something)
2800 return;
2802 if (upa->conflicts > 0)
2803 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2804 if (upa->obstructed > 0)
2805 printf("File paths obstructed by a non-regular file: %d\n",
2806 upa->obstructed);
2807 if (upa->not_updated > 0)
2808 printf("Files not updated because of existing merge "
2809 "conflicts: %d\n", upa->not_updated);
2812 __dead static void
2813 usage_update(void)
2815 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2816 getprogname());
2817 exit(1);
2820 static const struct got_error *
2821 update_progress(void *arg, unsigned char status, const char *path)
2823 struct got_update_progress_arg *upa = arg;
2825 if (status == GOT_STATUS_EXISTS ||
2826 status == GOT_STATUS_BASE_REF_ERR)
2827 return NULL;
2829 upa->did_something = 1;
2831 /* Base commit bump happens silently. */
2832 if (status == GOT_STATUS_BUMP_BASE)
2833 return NULL;
2835 if (status == GOT_STATUS_CONFLICT)
2836 upa->conflicts++;
2837 if (status == GOT_STATUS_OBSTRUCTED)
2838 upa->obstructed++;
2839 if (status == GOT_STATUS_CANNOT_UPDATE)
2840 upa->not_updated++;
2842 while (path[0] == '/')
2843 path++;
2844 printf("%c %s\n", status, path);
2845 return NULL;
2848 static const struct got_error *
2849 switch_head_ref(struct got_reference *head_ref,
2850 struct got_object_id *commit_id, struct got_worktree *worktree,
2851 struct got_repository *repo)
2853 const struct got_error *err = NULL;
2854 char *base_id_str;
2855 int ref_has_moved = 0;
2857 /* Trivial case: switching between two different references. */
2858 if (strcmp(got_ref_get_name(head_ref),
2859 got_worktree_get_head_ref_name(worktree)) != 0) {
2860 printf("Switching work tree from %s to %s\n",
2861 got_worktree_get_head_ref_name(worktree),
2862 got_ref_get_name(head_ref));
2863 return got_worktree_set_head_ref(worktree, head_ref);
2866 err = check_linear_ancestry(commit_id,
2867 got_worktree_get_base_commit_id(worktree), 0, repo);
2868 if (err) {
2869 if (err->code != GOT_ERR_ANCESTRY)
2870 return err;
2871 ref_has_moved = 1;
2873 if (!ref_has_moved)
2874 return NULL;
2876 /* Switching to a rebased branch with the same reference name. */
2877 err = got_object_id_str(&base_id_str,
2878 got_worktree_get_base_commit_id(worktree));
2879 if (err)
2880 return err;
2881 printf("Reference %s now points at a different branch\n",
2882 got_worktree_get_head_ref_name(worktree));
2883 printf("Switching work tree from %s to %s\n", base_id_str,
2884 got_worktree_get_head_ref_name(worktree));
2885 return NULL;
2888 static const struct got_error *
2889 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2891 const struct got_error *err;
2892 int in_progress;
2894 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2895 if (err)
2896 return err;
2897 if (in_progress)
2898 return got_error(GOT_ERR_REBASING);
2900 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2901 if (err)
2902 return err;
2903 if (in_progress)
2904 return got_error(GOT_ERR_HISTEDIT_BUSY);
2906 return NULL;
2909 static const struct got_error *
2910 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2911 char *argv[], struct got_worktree *worktree)
2913 const struct got_error *err = NULL;
2914 char *path;
2915 int i;
2917 if (argc == 0) {
2918 path = strdup("");
2919 if (path == NULL)
2920 return got_error_from_errno("strdup");
2921 return got_pathlist_append(paths, path, NULL);
2924 for (i = 0; i < argc; i++) {
2925 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2926 if (err)
2927 break;
2928 err = got_pathlist_append(paths, path, NULL);
2929 if (err) {
2930 free(path);
2931 break;
2935 return err;
2938 static const struct got_error *
2939 wrap_not_worktree_error(const struct got_error *orig_err,
2940 const char *cmdname, const char *path)
2942 const struct got_error *err;
2943 struct got_repository *repo;
2944 static char msg[512];
2946 err = got_repo_open(&repo, path, NULL);
2947 if (err)
2948 return orig_err;
2950 snprintf(msg, sizeof(msg),
2951 "'got %s' needs a work tree in addition to a git repository\n"
2952 "Work trees can be checked out from this Git repository with "
2953 "'got checkout'.\n"
2954 "The got(1) manual page contains more information.", cmdname);
2955 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2956 got_repo_close(repo);
2957 return err;
2960 static const struct got_error *
2961 cmd_update(int argc, char *argv[])
2963 const struct got_error *error = NULL;
2964 struct got_repository *repo = NULL;
2965 struct got_worktree *worktree = NULL;
2966 char *worktree_path = NULL;
2967 struct got_object_id *commit_id = NULL;
2968 char *commit_id_str = NULL;
2969 const char *branch_name = NULL;
2970 struct got_reference *head_ref = NULL;
2971 struct got_pathlist_head paths;
2972 struct got_pathlist_entry *pe;
2973 int ch;
2974 struct got_update_progress_arg upa;
2976 TAILQ_INIT(&paths);
2978 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2979 switch (ch) {
2980 case 'b':
2981 branch_name = optarg;
2982 break;
2983 case 'c':
2984 commit_id_str = strdup(optarg);
2985 if (commit_id_str == NULL)
2986 return got_error_from_errno("strdup");
2987 break;
2988 default:
2989 usage_update();
2990 /* NOTREACHED */
2994 argc -= optind;
2995 argv += optind;
2997 #ifndef PROFILE
2998 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2999 "unveil", NULL) == -1)
3000 err(1, "pledge");
3001 #endif
3002 worktree_path = getcwd(NULL, 0);
3003 if (worktree_path == NULL) {
3004 error = got_error_from_errno("getcwd");
3005 goto done;
3007 error = got_worktree_open(&worktree, worktree_path);
3008 if (error) {
3009 if (error->code == GOT_ERR_NOT_WORKTREE)
3010 error = wrap_not_worktree_error(error, "update",
3011 worktree_path);
3012 goto done;
3015 error = check_rebase_or_histedit_in_progress(worktree);
3016 if (error)
3017 goto done;
3019 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3020 NULL);
3021 if (error != NULL)
3022 goto done;
3024 error = apply_unveil(got_repo_get_path(repo), 0,
3025 got_worktree_get_root_path(worktree));
3026 if (error)
3027 goto done;
3029 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3030 if (error)
3031 goto done;
3033 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3034 got_worktree_get_head_ref_name(worktree), 0);
3035 if (error != NULL)
3036 goto done;
3037 if (commit_id_str == NULL) {
3038 error = got_ref_resolve(&commit_id, repo, head_ref);
3039 if (error != NULL)
3040 goto done;
3041 error = got_object_id_str(&commit_id_str, commit_id);
3042 if (error != NULL)
3043 goto done;
3044 } else {
3045 error = got_repo_match_object_id(&commit_id, NULL,
3046 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
3047 free(commit_id_str);
3048 commit_id_str = NULL;
3049 if (error)
3050 goto done;
3051 error = got_object_id_str(&commit_id_str, commit_id);
3052 if (error)
3053 goto done;
3056 if (branch_name) {
3057 struct got_object_id *head_commit_id;
3058 TAILQ_FOREACH(pe, &paths, entry) {
3059 if (pe->path_len == 0)
3060 continue;
3061 error = got_error_msg(GOT_ERR_BAD_PATH,
3062 "switching between branches requires that "
3063 "the entire work tree gets updated");
3064 goto done;
3066 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3067 if (error)
3068 goto done;
3069 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3070 repo);
3071 free(head_commit_id);
3072 if (error != NULL)
3073 goto done;
3074 error = check_same_branch(commit_id, head_ref, NULL, repo);
3075 if (error)
3076 goto done;
3077 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3078 if (error)
3079 goto done;
3080 } else {
3081 error = check_linear_ancestry(commit_id,
3082 got_worktree_get_base_commit_id(worktree), 0, repo);
3083 if (error != NULL) {
3084 if (error->code == GOT_ERR_ANCESTRY)
3085 error = got_error(GOT_ERR_BRANCH_MOVED);
3086 goto done;
3088 error = check_same_branch(commit_id, head_ref, NULL, repo);
3089 if (error)
3090 goto done;
3093 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3094 commit_id) != 0) {
3095 error = got_worktree_set_base_commit_id(worktree, repo,
3096 commit_id);
3097 if (error)
3098 goto done;
3101 memset(&upa, 0, sizeof(upa));
3102 error = got_worktree_checkout_files(worktree, &paths, repo,
3103 update_progress, &upa, check_cancelled, NULL);
3104 if (error != NULL)
3105 goto done;
3107 if (upa.did_something)
3108 printf("Updated to commit %s\n", commit_id_str);
3109 else
3110 printf("Already up-to-date\n");
3111 print_update_progress_stats(&upa);
3112 done:
3113 free(worktree_path);
3114 TAILQ_FOREACH(pe, &paths, entry)
3115 free((char *)pe->path);
3116 got_pathlist_free(&paths);
3117 free(commit_id);
3118 free(commit_id_str);
3119 return error;
3122 static const struct got_error *
3123 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3124 const char *path, int diff_context, int ignore_whitespace,
3125 struct got_repository *repo)
3127 const struct got_error *err = NULL;
3128 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3130 if (blob_id1) {
3131 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3132 if (err)
3133 goto done;
3136 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3137 if (err)
3138 goto done;
3140 while (path[0] == '/')
3141 path++;
3142 err = got_diff_blob(blob1, blob2, path, path, diff_context,
3143 ignore_whitespace, stdout);
3144 done:
3145 if (blob1)
3146 got_object_blob_close(blob1);
3147 got_object_blob_close(blob2);
3148 return err;
3151 static const struct got_error *
3152 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3153 const char *path, int diff_context, int ignore_whitespace,
3154 struct got_repository *repo)
3156 const struct got_error *err = NULL;
3157 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3158 struct got_diff_blob_output_unidiff_arg arg;
3160 if (tree_id1) {
3161 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3162 if (err)
3163 goto done;
3166 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3167 if (err)
3168 goto done;
3170 arg.diff_context = diff_context;
3171 arg.ignore_whitespace = ignore_whitespace;
3172 arg.outfile = stdout;
3173 while (path[0] == '/')
3174 path++;
3175 err = got_diff_tree(tree1, tree2, path, path, repo,
3176 got_diff_blob_output_unidiff, &arg, 1);
3177 done:
3178 if (tree1)
3179 got_object_tree_close(tree1);
3180 if (tree2)
3181 got_object_tree_close(tree2);
3182 return err;
3185 static const struct got_error *
3186 get_changed_paths(struct got_pathlist_head *paths,
3187 struct got_commit_object *commit, struct got_repository *repo)
3189 const struct got_error *err = NULL;
3190 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3191 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3192 struct got_object_qid *qid;
3194 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3195 if (qid != NULL) {
3196 struct got_commit_object *pcommit;
3197 err = got_object_open_as_commit(&pcommit, repo,
3198 qid->id);
3199 if (err)
3200 return err;
3202 tree_id1 = got_object_commit_get_tree_id(pcommit);
3203 got_object_commit_close(pcommit);
3207 if (tree_id1) {
3208 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3209 if (err)
3210 goto done;
3213 tree_id2 = got_object_commit_get_tree_id(commit);
3214 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3215 if (err)
3216 goto done;
3218 err = got_diff_tree(tree1, tree2, "", "", repo,
3219 got_diff_tree_collect_changed_paths, paths, 0);
3220 done:
3221 if (tree1)
3222 got_object_tree_close(tree1);
3223 if (tree2)
3224 got_object_tree_close(tree2);
3225 return err;
3228 static const struct got_error *
3229 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3230 const char *path, int diff_context, struct got_repository *repo)
3232 const struct got_error *err = NULL;
3233 struct got_commit_object *pcommit = NULL;
3234 char *id_str1 = NULL, *id_str2 = NULL;
3235 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3236 struct got_object_qid *qid;
3238 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3239 if (qid != NULL) {
3240 err = got_object_open_as_commit(&pcommit, repo,
3241 qid->id);
3242 if (err)
3243 return err;
3246 if (path && path[0] != '\0') {
3247 int obj_type;
3248 err = got_object_id_by_path(&obj_id2, repo, id, path);
3249 if (err)
3250 goto done;
3251 err = got_object_id_str(&id_str2, obj_id2);
3252 if (err) {
3253 free(obj_id2);
3254 goto done;
3256 if (pcommit) {
3257 err = got_object_id_by_path(&obj_id1, repo,
3258 qid->id, path);
3259 if (err) {
3260 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3261 free(obj_id2);
3262 goto done;
3264 } else {
3265 err = got_object_id_str(&id_str1, obj_id1);
3266 if (err) {
3267 free(obj_id2);
3268 goto done;
3272 err = got_object_get_type(&obj_type, repo, obj_id2);
3273 if (err) {
3274 free(obj_id2);
3275 goto done;
3277 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3278 switch (obj_type) {
3279 case GOT_OBJ_TYPE_BLOB:
3280 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3281 0, repo);
3282 break;
3283 case GOT_OBJ_TYPE_TREE:
3284 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3285 0, repo);
3286 break;
3287 default:
3288 err = got_error(GOT_ERR_OBJ_TYPE);
3289 break;
3291 free(obj_id1);
3292 free(obj_id2);
3293 } else {
3294 obj_id2 = got_object_commit_get_tree_id(commit);
3295 err = got_object_id_str(&id_str2, obj_id2);
3296 if (err)
3297 goto done;
3298 obj_id1 = got_object_commit_get_tree_id(pcommit);
3299 err = got_object_id_str(&id_str1, obj_id1);
3300 if (err)
3301 goto done;
3302 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3303 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
3305 done:
3306 free(id_str1);
3307 free(id_str2);
3308 if (pcommit)
3309 got_object_commit_close(pcommit);
3310 return err;
3313 static char *
3314 get_datestr(time_t *time, char *datebuf)
3316 struct tm mytm, *tm;
3317 char *p, *s;
3319 tm = gmtime_r(time, &mytm);
3320 if (tm == NULL)
3321 return NULL;
3322 s = asctime_r(tm, datebuf);
3323 if (s == NULL)
3324 return NULL;
3325 p = strchr(s, '\n');
3326 if (p)
3327 *p = '\0';
3328 return s;
3331 static const struct got_error *
3332 match_logmsg(int *have_match, struct got_object_id *id,
3333 struct got_commit_object *commit, regex_t *regex)
3335 const struct got_error *err = NULL;
3336 regmatch_t regmatch;
3337 char *id_str = NULL, *logmsg = NULL;
3339 *have_match = 0;
3341 err = got_object_id_str(&id_str, id);
3342 if (err)
3343 return err;
3345 err = got_object_commit_get_logmsg(&logmsg, commit);
3346 if (err)
3347 goto done;
3349 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3350 *have_match = 1;
3351 done:
3352 free(id_str);
3353 free(logmsg);
3354 return err;
3357 static void
3358 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3359 regex_t *regex)
3361 regmatch_t regmatch;
3362 struct got_pathlist_entry *pe;
3364 *have_match = 0;
3366 TAILQ_FOREACH(pe, changed_paths, entry) {
3367 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3368 *have_match = 1;
3369 break;
3374 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3376 static const struct got_error *
3377 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3378 struct got_repository *repo, const char *path,
3379 struct got_pathlist_head *changed_paths, int show_patch,
3380 int diff_context, struct got_reflist_head *refs)
3382 const struct got_error *err = NULL;
3383 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3384 char datebuf[26];
3385 time_t committer_time;
3386 const char *author, *committer;
3387 char *refs_str = NULL;
3388 struct got_reflist_entry *re;
3390 SIMPLEQ_FOREACH(re, refs, entry) {
3391 char *s;
3392 const char *name;
3393 struct got_tag_object *tag = NULL;
3394 struct got_object_id *ref_id;
3395 int cmp;
3397 name = got_ref_get_name(re->ref);
3398 if (strcmp(name, GOT_REF_HEAD) == 0)
3399 continue;
3400 if (strncmp(name, "refs/", 5) == 0)
3401 name += 5;
3402 if (strncmp(name, "got/", 4) == 0)
3403 continue;
3404 if (strncmp(name, "heads/", 6) == 0)
3405 name += 6;
3406 if (strncmp(name, "remotes/", 8) == 0) {
3407 name += 8;
3408 s = strstr(name, "/" GOT_REF_HEAD);
3409 if (s != NULL && s[strlen(s)] == '\0')
3410 continue;
3412 err = got_ref_resolve(&ref_id, repo, re->ref);
3413 if (err)
3414 return err;
3415 if (strncmp(name, "tags/", 5) == 0) {
3416 err = got_object_open_as_tag(&tag, repo, ref_id);
3417 if (err) {
3418 if (err->code != GOT_ERR_OBJ_TYPE) {
3419 free(ref_id);
3420 return err;
3422 /* Ref points at something other than a tag. */
3423 err = NULL;
3424 tag = NULL;
3427 cmp = got_object_id_cmp(tag ?
3428 got_object_tag_get_object_id(tag) : ref_id, id);
3429 free(ref_id);
3430 if (tag)
3431 got_object_tag_close(tag);
3432 if (cmp != 0)
3433 continue;
3434 s = refs_str;
3435 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3436 name) == -1) {
3437 err = got_error_from_errno("asprintf");
3438 free(s);
3439 return err;
3441 free(s);
3443 err = got_object_id_str(&id_str, id);
3444 if (err)
3445 return err;
3447 printf(GOT_COMMIT_SEP_STR);
3448 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3449 refs_str ? refs_str : "", refs_str ? ")" : "");
3450 free(id_str);
3451 id_str = NULL;
3452 free(refs_str);
3453 refs_str = NULL;
3454 printf("from: %s\n", got_object_commit_get_author(commit));
3455 committer_time = got_object_commit_get_committer_time(commit);
3456 datestr = get_datestr(&committer_time, datebuf);
3457 if (datestr)
3458 printf("date: %s UTC\n", datestr);
3459 author = got_object_commit_get_author(commit);
3460 committer = got_object_commit_get_committer(commit);
3461 if (strcmp(author, committer) != 0)
3462 printf("via: %s\n", committer);
3463 if (got_object_commit_get_nparents(commit) > 1) {
3464 const struct got_object_id_queue *parent_ids;
3465 struct got_object_qid *qid;
3466 int n = 1;
3467 parent_ids = got_object_commit_get_parent_ids(commit);
3468 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3469 err = got_object_id_str(&id_str, qid->id);
3470 if (err)
3471 return err;
3472 printf("parent %d: %s\n", n++, id_str);
3473 free(id_str);
3477 err = got_object_commit_get_logmsg(&logmsg0, commit);
3478 if (err)
3479 return err;
3481 logmsg = logmsg0;
3482 do {
3483 line = strsep(&logmsg, "\n");
3484 if (line)
3485 printf(" %s\n", line);
3486 } while (line);
3487 free(logmsg0);
3489 if (changed_paths) {
3490 struct got_pathlist_entry *pe;
3491 TAILQ_FOREACH(pe, changed_paths, entry) {
3492 struct got_diff_changed_path *cp = pe->data;
3493 printf(" %c %s\n", cp->status, pe->path);
3495 printf("\n");
3497 if (show_patch) {
3498 err = print_patch(commit, id, path, diff_context, repo);
3499 if (err == 0)
3500 printf("\n");
3503 if (fflush(stdout) != 0 && err == NULL)
3504 err = got_error_from_errno("fflush");
3505 return err;
3508 static const struct got_error *
3509 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3510 struct got_repository *repo, const char *path, int show_changed_paths,
3511 int show_patch, const char *search_pattern, int diff_context, int limit,
3512 int log_branches, int reverse_display_order, struct got_reflist_head *refs)
3514 const struct got_error *err;
3515 struct got_commit_graph *graph;
3516 regex_t regex;
3517 int have_match;
3518 struct got_object_id_queue reversed_commits;
3519 struct got_object_qid *qid;
3520 struct got_commit_object *commit;
3521 struct got_pathlist_head changed_paths;
3522 struct got_pathlist_entry *pe;
3524 SIMPLEQ_INIT(&reversed_commits);
3525 TAILQ_INIT(&changed_paths);
3527 if (search_pattern && regcomp(&regex, search_pattern,
3528 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3529 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3531 err = got_commit_graph_open(&graph, path, !log_branches);
3532 if (err)
3533 return err;
3534 err = got_commit_graph_iter_start(graph, root_id, repo,
3535 check_cancelled, NULL);
3536 if (err)
3537 goto done;
3538 for (;;) {
3539 struct got_object_id *id;
3541 if (sigint_received || sigpipe_received)
3542 break;
3544 err = got_commit_graph_iter_next(&id, graph, repo,
3545 check_cancelled, NULL);
3546 if (err) {
3547 if (err->code == GOT_ERR_ITER_COMPLETED)
3548 err = NULL;
3549 break;
3551 if (id == NULL)
3552 break;
3554 err = got_object_open_as_commit(&commit, repo, id);
3555 if (err)
3556 break;
3558 if (show_changed_paths && !reverse_display_order) {
3559 err = get_changed_paths(&changed_paths, commit, repo);
3560 if (err)
3561 break;
3564 if (search_pattern) {
3565 err = match_logmsg(&have_match, id, commit, &regex);
3566 if (err) {
3567 got_object_commit_close(commit);
3568 break;
3570 if (have_match == 0 && show_changed_paths)
3571 match_changed_paths(&have_match,
3572 &changed_paths, &regex);
3573 if (have_match == 0) {
3574 got_object_commit_close(commit);
3575 TAILQ_FOREACH(pe, &changed_paths, entry) {
3576 free((char *)pe->path);
3577 free(pe->data);
3579 got_pathlist_free(&changed_paths);
3580 continue;
3584 if (reverse_display_order) {
3585 err = got_object_qid_alloc(&qid, id);
3586 if (err)
3587 break;
3588 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3589 got_object_commit_close(commit);
3590 } else {
3591 err = print_commit(commit, id, repo, path,
3592 show_changed_paths ? &changed_paths : NULL,
3593 show_patch, diff_context, refs);
3594 got_object_commit_close(commit);
3595 if (err)
3596 break;
3598 if ((limit && --limit == 0) ||
3599 (end_id && got_object_id_cmp(id, end_id) == 0))
3600 break;
3602 TAILQ_FOREACH(pe, &changed_paths, entry) {
3603 free((char *)pe->path);
3604 free(pe->data);
3606 got_pathlist_free(&changed_paths);
3608 if (reverse_display_order) {
3609 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3610 err = got_object_open_as_commit(&commit, repo, qid->id);
3611 if (err)
3612 break;
3613 if (show_changed_paths) {
3614 err = get_changed_paths(&changed_paths,
3615 commit, repo);
3616 if (err)
3617 break;
3619 err = print_commit(commit, qid->id, repo, path,
3620 show_changed_paths ? &changed_paths : NULL,
3621 show_patch, diff_context, refs);
3622 got_object_commit_close(commit);
3623 if (err)
3624 break;
3625 TAILQ_FOREACH(pe, &changed_paths, entry) {
3626 free((char *)pe->path);
3627 free(pe->data);
3629 got_pathlist_free(&changed_paths);
3632 done:
3633 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3634 qid = SIMPLEQ_FIRST(&reversed_commits);
3635 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3636 got_object_qid_free(qid);
3638 TAILQ_FOREACH(pe, &changed_paths, entry) {
3639 free((char *)pe->path);
3640 free(pe->data);
3642 got_pathlist_free(&changed_paths);
3643 if (search_pattern)
3644 regfree(&regex);
3645 got_commit_graph_close(graph);
3646 return err;
3649 __dead static void
3650 usage_log(void)
3652 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3653 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3654 "[-R] [path]\n", getprogname());
3655 exit(1);
3658 static int
3659 get_default_log_limit(void)
3661 const char *got_default_log_limit;
3662 long long n;
3663 const char *errstr;
3665 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3666 if (got_default_log_limit == NULL)
3667 return 0;
3668 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3669 if (errstr != NULL)
3670 return 0;
3671 return n;
3674 static const struct got_error *
3675 resolve_commit_arg(struct got_object_id **id, const char *commit_arg,
3676 struct got_repository *repo)
3678 const struct got_error *err = NULL;
3679 struct got_reference *ref;
3681 *id = NULL;
3683 err = got_ref_open(&ref, repo, commit_arg, 0);
3684 if (err == NULL) {
3685 int obj_type;
3686 err = got_ref_resolve(id, repo, ref);
3687 got_ref_close(ref);
3688 if (err)
3689 return err;
3690 err = got_object_get_type(&obj_type, repo, *id);
3691 if (err)
3692 return err;
3693 if (obj_type == GOT_OBJ_TYPE_TAG) {
3694 struct got_tag_object *tag;
3695 err = got_object_open_as_tag(&tag, repo, *id);
3696 if (err)
3697 return err;
3698 if (got_object_tag_get_object_type(tag) !=
3699 GOT_OBJ_TYPE_COMMIT) {
3700 got_object_tag_close(tag);
3701 return got_error(GOT_ERR_OBJ_TYPE);
3703 free(*id);
3704 *id = got_object_id_dup(
3705 got_object_tag_get_object_id(tag));
3706 if (*id == NULL)
3707 err = got_error_from_errno(
3708 "got_object_id_dup");
3709 got_object_tag_close(tag);
3710 if (err)
3711 return err;
3712 } else if (obj_type != GOT_OBJ_TYPE_COMMIT)
3713 return got_error(GOT_ERR_OBJ_TYPE);
3714 } else {
3715 err = got_repo_match_object_id_prefix(id, commit_arg,
3716 GOT_OBJ_TYPE_COMMIT, repo);
3719 return err;
3722 static const struct got_error *
3723 cmd_log(int argc, char *argv[])
3725 const struct got_error *error;
3726 struct got_repository *repo = NULL;
3727 struct got_worktree *worktree = NULL;
3728 struct got_object_id *start_id = NULL, *end_id = NULL;
3729 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3730 const char *start_commit = NULL, *end_commit = NULL;
3731 const char *search_pattern = NULL;
3732 int diff_context = -1, ch;
3733 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3734 int reverse_display_order = 0;
3735 const char *errstr;
3736 struct got_reflist_head refs;
3738 SIMPLEQ_INIT(&refs);
3740 #ifndef PROFILE
3741 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3742 NULL)
3743 == -1)
3744 err(1, "pledge");
3745 #endif
3747 limit = get_default_log_limit();
3749 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3750 switch (ch) {
3751 case 'p':
3752 show_patch = 1;
3753 break;
3754 case 'P':
3755 show_changed_paths = 1;
3756 break;
3757 case 'c':
3758 start_commit = optarg;
3759 break;
3760 case 'C':
3761 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3762 &errstr);
3763 if (errstr != NULL)
3764 err(1, "-C option %s", errstr);
3765 break;
3766 case 'l':
3767 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3768 if (errstr != NULL)
3769 err(1, "-l option %s", errstr);
3770 break;
3771 case 'b':
3772 log_branches = 1;
3773 break;
3774 case 'r':
3775 repo_path = realpath(optarg, NULL);
3776 if (repo_path == NULL)
3777 return got_error_from_errno2("realpath",
3778 optarg);
3779 got_path_strip_trailing_slashes(repo_path);
3780 break;
3781 case 'R':
3782 reverse_display_order = 1;
3783 break;
3784 case 's':
3785 search_pattern = optarg;
3786 break;
3787 case 'x':
3788 end_commit = optarg;
3789 break;
3790 default:
3791 usage_log();
3792 /* NOTREACHED */
3796 argc -= optind;
3797 argv += optind;
3799 if (diff_context == -1)
3800 diff_context = 3;
3801 else if (!show_patch)
3802 errx(1, "-C requires -p");
3804 cwd = getcwd(NULL, 0);
3805 if (cwd == NULL) {
3806 error = got_error_from_errno("getcwd");
3807 goto done;
3810 if (repo_path == NULL) {
3811 error = got_worktree_open(&worktree, cwd);
3812 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3813 goto done;
3814 error = NULL;
3817 if (argc == 0) {
3818 path = strdup("");
3819 if (path == NULL) {
3820 error = got_error_from_errno("strdup");
3821 goto done;
3823 } else if (argc == 1) {
3824 if (worktree) {
3825 error = got_worktree_resolve_path(&path, worktree,
3826 argv[0]);
3827 if (error)
3828 goto done;
3829 } else {
3830 path = strdup(argv[0]);
3831 if (path == NULL) {
3832 error = got_error_from_errno("strdup");
3833 goto done;
3836 } else
3837 usage_log();
3839 if (repo_path == NULL) {
3840 repo_path = worktree ?
3841 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3843 if (repo_path == NULL) {
3844 error = got_error_from_errno("strdup");
3845 goto done;
3848 error = got_repo_open(&repo, repo_path, NULL);
3849 if (error != NULL)
3850 goto done;
3852 error = apply_unveil(got_repo_get_path(repo), 1,
3853 worktree ? got_worktree_get_root_path(worktree) : NULL);
3854 if (error)
3855 goto done;
3857 if (start_commit == NULL) {
3858 struct got_reference *head_ref;
3859 struct got_commit_object *commit = NULL;
3860 error = got_ref_open(&head_ref, repo,
3861 worktree ? got_worktree_get_head_ref_name(worktree)
3862 : GOT_REF_HEAD, 0);
3863 if (error != NULL)
3864 goto done;
3865 error = got_ref_resolve(&start_id, repo, head_ref);
3866 got_ref_close(head_ref);
3867 if (error != NULL)
3868 goto done;
3869 error = got_object_open_as_commit(&commit, repo,
3870 start_id);
3871 if (error != NULL)
3872 goto done;
3873 got_object_commit_close(commit);
3874 } else {
3875 error = resolve_commit_arg(&start_id, start_commit, repo);
3876 if (error != NULL)
3877 goto done;
3879 if (end_commit != NULL) {
3880 error = resolve_commit_arg(&end_id, end_commit, repo);
3881 if (error != NULL)
3882 goto done;
3885 if (worktree) {
3886 const char *prefix = got_worktree_get_path_prefix(worktree);
3887 char *p;
3888 if (asprintf(&p, "%s%s%s", prefix,
3889 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3890 error = got_error_from_errno("asprintf");
3891 goto done;
3893 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3894 free(p);
3895 } else
3896 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3897 if (error != NULL)
3898 goto done;
3899 if (in_repo_path) {
3900 free(path);
3901 path = in_repo_path;
3904 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3905 if (error)
3906 goto done;
3908 error = print_commits(start_id, end_id, repo, path, show_changed_paths,
3909 show_patch, search_pattern, diff_context, limit, log_branches,
3910 reverse_display_order, &refs);
3911 done:
3912 free(path);
3913 free(repo_path);
3914 free(cwd);
3915 if (worktree)
3916 got_worktree_close(worktree);
3917 if (repo) {
3918 const struct got_error *repo_error;
3919 repo_error = got_repo_close(repo);
3920 if (error == NULL)
3921 error = repo_error;
3923 got_ref_list_free(&refs);
3924 return error;
3927 __dead static void
3928 usage_diff(void)
3930 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3931 "[-w] [object1 object2 | path]\n", getprogname());
3932 exit(1);
3935 struct print_diff_arg {
3936 struct got_repository *repo;
3937 struct got_worktree *worktree;
3938 int diff_context;
3939 const char *id_str;
3940 int header_shown;
3941 int diff_staged;
3942 int ignore_whitespace;
3946 * Create a file which contains the target path of a symlink so we can feed
3947 * it as content to the diff engine.
3949 static const struct got_error *
3950 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
3951 const char *abspath)
3953 const struct got_error *err = NULL;
3954 char target_path[PATH_MAX];
3955 ssize_t target_len, outlen;
3957 *fd = -1;
3959 if (dirfd != -1) {
3960 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
3961 if (target_len == -1)
3962 return got_error_from_errno2("readlinkat", abspath);
3963 } else {
3964 target_len = readlink(abspath, target_path, PATH_MAX);
3965 if (target_len == -1)
3966 return got_error_from_errno2("readlink", abspath);
3969 *fd = got_opentempfd();
3970 if (*fd == -1)
3971 return got_error_from_errno("got_opentempfd");
3973 outlen = write(*fd, target_path, target_len);
3974 if (outlen == -1) {
3975 err = got_error_from_errno("got_opentempfd");
3976 goto done;
3979 if (lseek(*fd, 0, SEEK_SET) == -1) {
3980 err = got_error_from_errno2("lseek", abspath);
3981 goto done;
3983 done:
3984 if (err) {
3985 close(*fd);
3986 *fd = -1;
3988 return err;
3991 static const struct got_error *
3992 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3993 const char *path, struct got_object_id *blob_id,
3994 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3995 int dirfd, const char *de_name)
3997 struct print_diff_arg *a = arg;
3998 const struct got_error *err = NULL;
3999 struct got_blob_object *blob1 = NULL;
4000 int fd = -1;
4001 FILE *f2 = NULL;
4002 char *abspath = NULL, *label1 = NULL;
4003 struct stat sb;
4005 if (a->diff_staged) {
4006 if (staged_status != GOT_STATUS_MODIFY &&
4007 staged_status != GOT_STATUS_ADD &&
4008 staged_status != GOT_STATUS_DELETE)
4009 return NULL;
4010 } else {
4011 if (staged_status == GOT_STATUS_DELETE)
4012 return NULL;
4013 if (status == GOT_STATUS_NONEXISTENT)
4014 return got_error_set_errno(ENOENT, path);
4015 if (status != GOT_STATUS_MODIFY &&
4016 status != GOT_STATUS_ADD &&
4017 status != GOT_STATUS_DELETE &&
4018 status != GOT_STATUS_CONFLICT)
4019 return NULL;
4022 if (!a->header_shown) {
4023 printf("diff %s %s%s\n", a->id_str,
4024 got_worktree_get_root_path(a->worktree),
4025 a->diff_staged ? " (staged changes)" : "");
4026 a->header_shown = 1;
4029 if (a->diff_staged) {
4030 const char *label1 = NULL, *label2 = NULL;
4031 switch (staged_status) {
4032 case GOT_STATUS_MODIFY:
4033 label1 = path;
4034 label2 = path;
4035 break;
4036 case GOT_STATUS_ADD:
4037 label2 = path;
4038 break;
4039 case GOT_STATUS_DELETE:
4040 label1 = path;
4041 break;
4042 default:
4043 return got_error(GOT_ERR_FILE_STATUS);
4045 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
4046 label1, label2, a->diff_context, a->ignore_whitespace,
4047 a->repo, stdout);
4050 if (staged_status == GOT_STATUS_ADD ||
4051 staged_status == GOT_STATUS_MODIFY) {
4052 char *id_str;
4053 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4054 8192);
4055 if (err)
4056 goto done;
4057 err = got_object_id_str(&id_str, staged_blob_id);
4058 if (err)
4059 goto done;
4060 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4061 err = got_error_from_errno("asprintf");
4062 free(id_str);
4063 goto done;
4065 free(id_str);
4066 } else if (status != GOT_STATUS_ADD) {
4067 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4068 if (err)
4069 goto done;
4072 if (status != GOT_STATUS_DELETE) {
4073 if (asprintf(&abspath, "%s/%s",
4074 got_worktree_get_root_path(a->worktree), path) == -1) {
4075 err = got_error_from_errno("asprintf");
4076 goto done;
4079 if (dirfd != -1) {
4080 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
4081 if (fd == -1) {
4082 if (errno != ELOOP) {
4083 err = got_error_from_errno2("openat",
4084 abspath);
4085 goto done;
4087 err = get_symlink_target_file(&fd, dirfd,
4088 de_name, abspath);
4089 if (err)
4090 goto done;
4092 } else {
4093 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
4094 if (fd == -1) {
4095 if (errno != ELOOP) {
4096 err = got_error_from_errno2("open",
4097 abspath);
4098 goto done;
4100 err = get_symlink_target_file(&fd, dirfd,
4101 de_name, abspath);
4102 if (err)
4103 goto done;
4106 if (fstat(fd, &sb) == -1) {
4107 err = got_error_from_errno2("fstat", abspath);
4108 goto done;
4110 f2 = fdopen(fd, "r");
4111 if (f2 == NULL) {
4112 err = got_error_from_errno2("fdopen", abspath);
4113 goto done;
4115 fd = -1;
4116 } else
4117 sb.st_size = 0;
4119 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4120 a->diff_context, a->ignore_whitespace, stdout);
4121 done:
4122 if (blob1)
4123 got_object_blob_close(blob1);
4124 if (f2 && fclose(f2) == EOF && err == NULL)
4125 err = got_error_from_errno("fclose");
4126 if (fd != -1 && close(fd) == -1 && err == NULL)
4127 err = got_error_from_errno("close");
4128 free(abspath);
4129 return err;
4132 static const struct got_error *
4133 cmd_diff(int argc, char *argv[])
4135 const struct got_error *error;
4136 struct got_repository *repo = NULL;
4137 struct got_worktree *worktree = NULL;
4138 char *cwd = NULL, *repo_path = NULL;
4139 struct got_object_id *id1 = NULL, *id2 = NULL;
4140 const char *id_str1 = NULL, *id_str2 = NULL;
4141 char *label1 = NULL, *label2 = NULL;
4142 int type1, type2;
4143 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
4144 const char *errstr;
4145 char *path = NULL;
4147 #ifndef PROFILE
4148 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4149 NULL) == -1)
4150 err(1, "pledge");
4151 #endif
4153 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
4154 switch (ch) {
4155 case 'C':
4156 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4157 &errstr);
4158 if (errstr != NULL)
4159 err(1, "-C option %s", errstr);
4160 break;
4161 case 'r':
4162 repo_path = realpath(optarg, NULL);
4163 if (repo_path == NULL)
4164 return got_error_from_errno2("realpath",
4165 optarg);
4166 got_path_strip_trailing_slashes(repo_path);
4167 break;
4168 case 's':
4169 diff_staged = 1;
4170 break;
4171 case 'w':
4172 ignore_whitespace = 1;
4173 break;
4174 default:
4175 usage_diff();
4176 /* NOTREACHED */
4180 argc -= optind;
4181 argv += optind;
4183 cwd = getcwd(NULL, 0);
4184 if (cwd == NULL) {
4185 error = got_error_from_errno("getcwd");
4186 goto done;
4188 if (argc <= 1) {
4189 if (repo_path)
4190 errx(1,
4191 "-r option can't be used when diffing a work tree");
4192 error = got_worktree_open(&worktree, cwd);
4193 if (error) {
4194 if (error->code == GOT_ERR_NOT_WORKTREE)
4195 error = wrap_not_worktree_error(error, "diff",
4196 cwd);
4197 goto done;
4199 repo_path = strdup(got_worktree_get_repo_path(worktree));
4200 if (repo_path == NULL) {
4201 error = got_error_from_errno("strdup");
4202 goto done;
4204 if (argc == 1) {
4205 error = got_worktree_resolve_path(&path, worktree,
4206 argv[0]);
4207 if (error)
4208 goto done;
4209 } else {
4210 path = strdup("");
4211 if (path == NULL) {
4212 error = got_error_from_errno("strdup");
4213 goto done;
4216 } else if (argc == 2) {
4217 if (diff_staged)
4218 errx(1, "-s option can't be used when diffing "
4219 "objects in repository");
4220 id_str1 = argv[0];
4221 id_str2 = argv[1];
4222 if (repo_path == NULL) {
4223 error = got_worktree_open(&worktree, cwd);
4224 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4225 goto done;
4226 if (worktree) {
4227 repo_path = strdup(
4228 got_worktree_get_repo_path(worktree));
4229 if (repo_path == NULL) {
4230 error = got_error_from_errno("strdup");
4231 goto done;
4233 } else {
4234 repo_path = strdup(cwd);
4235 if (repo_path == NULL) {
4236 error = got_error_from_errno("strdup");
4237 goto done;
4241 } else
4242 usage_diff();
4244 error = got_repo_open(&repo, repo_path, NULL);
4245 free(repo_path);
4246 if (error != NULL)
4247 goto done;
4249 error = apply_unveil(got_repo_get_path(repo), 1,
4250 worktree ? got_worktree_get_root_path(worktree) : NULL);
4251 if (error)
4252 goto done;
4254 if (argc <= 1) {
4255 struct print_diff_arg arg;
4256 struct got_pathlist_head paths;
4257 char *id_str;
4259 TAILQ_INIT(&paths);
4261 error = got_object_id_str(&id_str,
4262 got_worktree_get_base_commit_id(worktree));
4263 if (error)
4264 goto done;
4265 arg.repo = repo;
4266 arg.worktree = worktree;
4267 arg.diff_context = diff_context;
4268 arg.id_str = id_str;
4269 arg.header_shown = 0;
4270 arg.diff_staged = diff_staged;
4271 arg.ignore_whitespace = ignore_whitespace;
4273 error = got_pathlist_append(&paths, path, NULL);
4274 if (error)
4275 goto done;
4277 error = got_worktree_status(worktree, &paths, repo, print_diff,
4278 &arg, check_cancelled, NULL);
4279 free(id_str);
4280 got_pathlist_free(&paths);
4281 goto done;
4284 error = got_repo_match_object_id(&id1, &label1, id_str1,
4285 GOT_OBJ_TYPE_ANY, 1, repo);
4286 if (error)
4287 goto done;
4289 error = got_repo_match_object_id(&id2, &label2, id_str2,
4290 GOT_OBJ_TYPE_ANY, 1, repo);
4291 if (error)
4292 goto done;
4294 error = got_object_get_type(&type1, repo, id1);
4295 if (error)
4296 goto done;
4298 error = got_object_get_type(&type2, repo, id2);
4299 if (error)
4300 goto done;
4302 if (type1 != type2) {
4303 error = got_error(GOT_ERR_OBJ_TYPE);
4304 goto done;
4307 switch (type1) {
4308 case GOT_OBJ_TYPE_BLOB:
4309 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
4310 diff_context, ignore_whitespace, repo, stdout);
4311 break;
4312 case GOT_OBJ_TYPE_TREE:
4313 error = got_diff_objects_as_trees(id1, id2, "", "",
4314 diff_context, ignore_whitespace, repo, stdout);
4315 break;
4316 case GOT_OBJ_TYPE_COMMIT:
4317 printf("diff %s %s\n", label1, label2);
4318 error = got_diff_objects_as_commits(id1, id2, diff_context,
4319 ignore_whitespace, repo, stdout);
4320 break;
4321 default:
4322 error = got_error(GOT_ERR_OBJ_TYPE);
4324 done:
4325 free(label1);
4326 free(label2);
4327 free(id1);
4328 free(id2);
4329 free(path);
4330 if (worktree)
4331 got_worktree_close(worktree);
4332 if (repo) {
4333 const struct got_error *repo_error;
4334 repo_error = got_repo_close(repo);
4335 if (error == NULL)
4336 error = repo_error;
4338 return error;
4341 __dead static void
4342 usage_blame(void)
4344 fprintf(stderr,
4345 "usage: %s blame [-c commit] [-r repository-path] path\n",
4346 getprogname());
4347 exit(1);
4350 struct blame_line {
4351 int annotated;
4352 char *id_str;
4353 char *committer;
4354 char datebuf[11]; /* YYYY-MM-DD + NUL */
4357 struct blame_cb_args {
4358 struct blame_line *lines;
4359 int nlines;
4360 int nlines_prec;
4361 int lineno_cur;
4362 off_t *line_offsets;
4363 FILE *f;
4364 struct got_repository *repo;
4367 static const struct got_error *
4368 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4370 const struct got_error *err = NULL;
4371 struct blame_cb_args *a = arg;
4372 struct blame_line *bline;
4373 char *line = NULL;
4374 size_t linesize = 0;
4375 struct got_commit_object *commit = NULL;
4376 off_t offset;
4377 struct tm tm;
4378 time_t committer_time;
4380 if (nlines != a->nlines ||
4381 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4382 return got_error(GOT_ERR_RANGE);
4384 if (sigint_received)
4385 return got_error(GOT_ERR_ITER_COMPLETED);
4387 if (lineno == -1)
4388 return NULL; /* no change in this commit */
4390 /* Annotate this line. */
4391 bline = &a->lines[lineno - 1];
4392 if (bline->annotated)
4393 return NULL;
4394 err = got_object_id_str(&bline->id_str, id);
4395 if (err)
4396 return err;
4398 err = got_object_open_as_commit(&commit, a->repo, id);
4399 if (err)
4400 goto done;
4402 bline->committer = strdup(got_object_commit_get_committer(commit));
4403 if (bline->committer == NULL) {
4404 err = got_error_from_errno("strdup");
4405 goto done;
4408 committer_time = got_object_commit_get_committer_time(commit);
4409 if (localtime_r(&committer_time, &tm) == NULL)
4410 return got_error_from_errno("localtime_r");
4411 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4412 &tm) >= sizeof(bline->datebuf)) {
4413 err = got_error(GOT_ERR_NO_SPACE);
4414 goto done;
4416 bline->annotated = 1;
4418 /* Print lines annotated so far. */
4419 bline = &a->lines[a->lineno_cur - 1];
4420 if (!bline->annotated)
4421 goto done;
4423 offset = a->line_offsets[a->lineno_cur - 1];
4424 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4425 err = got_error_from_errno("fseeko");
4426 goto done;
4429 while (bline->annotated) {
4430 char *smallerthan, *at, *nl, *committer;
4431 size_t len;
4433 if (getline(&line, &linesize, a->f) == -1) {
4434 if (ferror(a->f))
4435 err = got_error_from_errno("getline");
4436 break;
4439 committer = bline->committer;
4440 smallerthan = strchr(committer, '<');
4441 if (smallerthan && smallerthan[1] != '\0')
4442 committer = smallerthan + 1;
4443 at = strchr(committer, '@');
4444 if (at)
4445 *at = '\0';
4446 len = strlen(committer);
4447 if (len >= 9)
4448 committer[8] = '\0';
4450 nl = strchr(line, '\n');
4451 if (nl)
4452 *nl = '\0';
4453 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4454 bline->id_str, bline->datebuf, committer, line);
4456 a->lineno_cur++;
4457 bline = &a->lines[a->lineno_cur - 1];
4459 done:
4460 if (commit)
4461 got_object_commit_close(commit);
4462 free(line);
4463 return err;
4466 static const struct got_error *
4467 cmd_blame(int argc, char *argv[])
4469 const struct got_error *error;
4470 struct got_repository *repo = NULL;
4471 struct got_worktree *worktree = NULL;
4472 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4473 char *link_target = NULL;
4474 struct got_object_id *obj_id = NULL;
4475 struct got_object_id *commit_id = NULL;
4476 struct got_blob_object *blob = NULL;
4477 char *commit_id_str = NULL;
4478 struct blame_cb_args bca;
4479 int ch, obj_type, i;
4480 size_t filesize;
4482 memset(&bca, 0, sizeof(bca));
4484 #ifndef PROFILE
4485 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4486 NULL) == -1)
4487 err(1, "pledge");
4488 #endif
4490 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4491 switch (ch) {
4492 case 'c':
4493 commit_id_str = optarg;
4494 break;
4495 case 'r':
4496 repo_path = realpath(optarg, NULL);
4497 if (repo_path == NULL)
4498 return got_error_from_errno2("realpath",
4499 optarg);
4500 got_path_strip_trailing_slashes(repo_path);
4501 break;
4502 default:
4503 usage_blame();
4504 /* NOTREACHED */
4508 argc -= optind;
4509 argv += optind;
4511 if (argc == 1)
4512 path = argv[0];
4513 else
4514 usage_blame();
4516 cwd = getcwd(NULL, 0);
4517 if (cwd == NULL) {
4518 error = got_error_from_errno("getcwd");
4519 goto done;
4521 if (repo_path == NULL) {
4522 error = got_worktree_open(&worktree, cwd);
4523 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4524 goto done;
4525 else
4526 error = NULL;
4527 if (worktree) {
4528 repo_path =
4529 strdup(got_worktree_get_repo_path(worktree));
4530 if (repo_path == NULL) {
4531 error = got_error_from_errno("strdup");
4532 if (error)
4533 goto done;
4535 } else {
4536 repo_path = strdup(cwd);
4537 if (repo_path == NULL) {
4538 error = got_error_from_errno("strdup");
4539 goto done;
4544 error = got_repo_open(&repo, repo_path, NULL);
4545 if (error != NULL)
4546 goto done;
4548 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4549 if (error)
4550 goto done;
4552 if (worktree) {
4553 const char *prefix = got_worktree_get_path_prefix(worktree);
4554 char *p, *worktree_subdir = cwd +
4555 strlen(got_worktree_get_root_path(worktree));
4556 if (asprintf(&p, "%s%s%s%s%s",
4557 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
4558 worktree_subdir, worktree_subdir[0] ? "/" : "",
4559 path) == -1) {
4560 error = got_error_from_errno("asprintf");
4561 goto done;
4563 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4564 free(p);
4565 } else {
4566 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4568 if (error)
4569 goto done;
4571 if (commit_id_str == NULL) {
4572 struct got_reference *head_ref;
4573 error = got_ref_open(&head_ref, repo, worktree ?
4574 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4575 if (error != NULL)
4576 goto done;
4577 error = got_ref_resolve(&commit_id, repo, head_ref);
4578 got_ref_close(head_ref);
4579 if (error != NULL)
4580 goto done;
4581 } else {
4582 error = got_repo_match_object_id(&commit_id, NULL,
4583 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4584 if (error)
4585 goto done;
4588 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4589 commit_id, repo);
4590 if (error)
4591 goto done;
4593 error = got_object_id_by_path(&obj_id, repo, commit_id,
4594 link_target ? link_target : in_repo_path);
4595 if (error)
4596 goto done;
4598 error = got_object_get_type(&obj_type, repo, obj_id);
4599 if (error)
4600 goto done;
4602 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4603 error = got_error_path(link_target ? link_target : in_repo_path,
4604 GOT_ERR_OBJ_TYPE);
4605 goto done;
4608 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4609 if (error)
4610 goto done;
4611 bca.f = got_opentemp();
4612 if (bca.f == NULL) {
4613 error = got_error_from_errno("got_opentemp");
4614 goto done;
4616 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4617 &bca.line_offsets, bca.f, blob);
4618 if (error || bca.nlines == 0)
4619 goto done;
4621 /* Don't include \n at EOF in the blame line count. */
4622 if (bca.line_offsets[bca.nlines - 1] == filesize)
4623 bca.nlines--;
4625 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4626 if (bca.lines == NULL) {
4627 error = got_error_from_errno("calloc");
4628 goto done;
4630 bca.lineno_cur = 1;
4631 bca.nlines_prec = 0;
4632 i = bca.nlines;
4633 while (i > 0) {
4634 i /= 10;
4635 bca.nlines_prec++;
4637 bca.repo = repo;
4639 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4640 repo, blame_cb, &bca, check_cancelled, NULL);
4641 done:
4642 free(in_repo_path);
4643 free(link_target);
4644 free(repo_path);
4645 free(cwd);
4646 free(commit_id);
4647 free(obj_id);
4648 if (blob)
4649 got_object_blob_close(blob);
4650 if (worktree)
4651 got_worktree_close(worktree);
4652 if (repo) {
4653 const struct got_error *repo_error;
4654 repo_error = got_repo_close(repo);
4655 if (error == NULL)
4656 error = repo_error;
4658 if (bca.lines) {
4659 for (i = 0; i < bca.nlines; i++) {
4660 struct blame_line *bline = &bca.lines[i];
4661 free(bline->id_str);
4662 free(bline->committer);
4664 free(bca.lines);
4666 free(bca.line_offsets);
4667 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4668 error = got_error_from_errno("fclose");
4669 return error;
4672 __dead static void
4673 usage_tree(void)
4675 fprintf(stderr,
4676 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4677 getprogname());
4678 exit(1);
4681 static const struct got_error *
4682 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4683 const char *root_path, struct got_repository *repo)
4685 const struct got_error *err = NULL;
4686 int is_root_path = (strcmp(path, root_path) == 0);
4687 const char *modestr = "";
4688 mode_t mode = got_tree_entry_get_mode(te);
4689 char *link_target = NULL;
4691 path += strlen(root_path);
4692 while (path[0] == '/')
4693 path++;
4695 if (got_object_tree_entry_is_submodule(te))
4696 modestr = "$";
4697 else if (S_ISLNK(mode)) {
4698 int i;
4700 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4701 if (err)
4702 return err;
4703 for (i = 0; i < strlen(link_target); i++) {
4704 if (!isprint((unsigned char)link_target[i]))
4705 link_target[i] = '?';
4708 modestr = "@";
4710 else if (S_ISDIR(mode))
4711 modestr = "/";
4712 else if (mode & S_IXUSR)
4713 modestr = "*";
4715 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4716 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4717 link_target ? " -> ": "", link_target ? link_target : "");
4719 free(link_target);
4720 return NULL;
4723 static const struct got_error *
4724 print_tree(const char *path, struct got_object_id *commit_id,
4725 int show_ids, int recurse, const char *root_path,
4726 struct got_repository *repo)
4728 const struct got_error *err = NULL;
4729 struct got_object_id *tree_id = NULL;
4730 struct got_tree_object *tree = NULL;
4731 int nentries, i;
4733 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4734 if (err)
4735 goto done;
4737 err = got_object_open_as_tree(&tree, repo, tree_id);
4738 if (err)
4739 goto done;
4740 nentries = got_object_tree_get_nentries(tree);
4741 for (i = 0; i < nentries; i++) {
4742 struct got_tree_entry *te;
4743 char *id = NULL;
4745 if (sigint_received || sigpipe_received)
4746 break;
4748 te = got_object_tree_get_entry(tree, i);
4749 if (show_ids) {
4750 char *id_str;
4751 err = got_object_id_str(&id_str,
4752 got_tree_entry_get_id(te));
4753 if (err)
4754 goto done;
4755 if (asprintf(&id, "%s ", id_str) == -1) {
4756 err = got_error_from_errno("asprintf");
4757 free(id_str);
4758 goto done;
4760 free(id_str);
4762 err = print_entry(te, id, path, root_path, repo);
4763 free(id);
4764 if (err)
4765 goto done;
4767 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4768 char *child_path;
4769 if (asprintf(&child_path, "%s%s%s", path,
4770 path[0] == '/' && path[1] == '\0' ? "" : "/",
4771 got_tree_entry_get_name(te)) == -1) {
4772 err = got_error_from_errno("asprintf");
4773 goto done;
4775 err = print_tree(child_path, commit_id, show_ids, 1,
4776 root_path, repo);
4777 free(child_path);
4778 if (err)
4779 goto done;
4782 done:
4783 if (tree)
4784 got_object_tree_close(tree);
4785 free(tree_id);
4786 return err;
4789 static const struct got_error *
4790 cmd_tree(int argc, char *argv[])
4792 const struct got_error *error;
4793 struct got_repository *repo = NULL;
4794 struct got_worktree *worktree = NULL;
4795 const char *path, *refname = NULL;
4796 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4797 struct got_object_id *commit_id = NULL;
4798 char *commit_id_str = NULL;
4799 int show_ids = 0, recurse = 0;
4800 int ch;
4802 #ifndef PROFILE
4803 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4804 NULL) == -1)
4805 err(1, "pledge");
4806 #endif
4808 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4809 switch (ch) {
4810 case 'c':
4811 commit_id_str = optarg;
4812 break;
4813 case 'r':
4814 repo_path = realpath(optarg, NULL);
4815 if (repo_path == NULL)
4816 return got_error_from_errno2("realpath",
4817 optarg);
4818 got_path_strip_trailing_slashes(repo_path);
4819 break;
4820 case 'i':
4821 show_ids = 1;
4822 break;
4823 case 'R':
4824 recurse = 1;
4825 break;
4826 default:
4827 usage_tree();
4828 /* NOTREACHED */
4832 argc -= optind;
4833 argv += optind;
4835 if (argc == 1)
4836 path = argv[0];
4837 else if (argc > 1)
4838 usage_tree();
4839 else
4840 path = NULL;
4842 cwd = getcwd(NULL, 0);
4843 if (cwd == NULL) {
4844 error = got_error_from_errno("getcwd");
4845 goto done;
4847 if (repo_path == NULL) {
4848 error = got_worktree_open(&worktree, cwd);
4849 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4850 goto done;
4851 else
4852 error = NULL;
4853 if (worktree) {
4854 repo_path =
4855 strdup(got_worktree_get_repo_path(worktree));
4856 if (repo_path == NULL)
4857 error = got_error_from_errno("strdup");
4858 if (error)
4859 goto done;
4860 } else {
4861 repo_path = strdup(cwd);
4862 if (repo_path == NULL) {
4863 error = got_error_from_errno("strdup");
4864 goto done;
4869 error = got_repo_open(&repo, repo_path, NULL);
4870 if (error != NULL)
4871 goto done;
4873 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4874 if (error)
4875 goto done;
4877 if (path == NULL) {
4878 if (worktree) {
4879 char *p, *worktree_subdir = cwd +
4880 strlen(got_worktree_get_root_path(worktree));
4881 if (asprintf(&p, "%s/%s",
4882 got_worktree_get_path_prefix(worktree),
4883 worktree_subdir) == -1) {
4884 error = got_error_from_errno("asprintf");
4885 goto done;
4887 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4888 free(p);
4889 if (error)
4890 goto done;
4891 } else
4892 path = "/";
4894 if (in_repo_path == NULL) {
4895 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4896 if (error != NULL)
4897 goto done;
4900 if (commit_id_str == NULL) {
4901 struct got_reference *head_ref;
4902 if (worktree)
4903 refname = got_worktree_get_head_ref_name(worktree);
4904 else
4905 refname = GOT_REF_HEAD;
4906 error = got_ref_open(&head_ref, repo, refname, 0);
4907 if (error != NULL)
4908 goto done;
4909 error = got_ref_resolve(&commit_id, repo, head_ref);
4910 got_ref_close(head_ref);
4911 if (error != NULL)
4912 goto done;
4913 } else {
4914 error = got_repo_match_object_id(&commit_id, NULL,
4915 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4916 if (error)
4917 goto done;
4920 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4921 in_repo_path, repo);
4922 done:
4923 free(in_repo_path);
4924 free(repo_path);
4925 free(cwd);
4926 free(commit_id);
4927 if (worktree)
4928 got_worktree_close(worktree);
4929 if (repo) {
4930 const struct got_error *repo_error;
4931 repo_error = got_repo_close(repo);
4932 if (error == NULL)
4933 error = repo_error;
4935 return error;
4938 __dead static void
4939 usage_status(void)
4941 fprintf(stderr, "usage: %s status [-s status-codes ] [path ...]\n",
4942 getprogname());
4943 exit(1);
4946 static const struct got_error *
4947 print_status(void *arg, unsigned char status, unsigned char staged_status,
4948 const char *path, struct got_object_id *blob_id,
4949 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4950 int dirfd, const char *de_name)
4952 if (status == staged_status && (status == GOT_STATUS_DELETE))
4953 status = GOT_STATUS_NO_CHANGE;
4954 if (arg) {
4955 char *status_codes = arg;
4956 size_t ncodes = strlen(status_codes);
4957 int i;
4958 for (i = 0; i < ncodes ; i++) {
4959 if (status == status_codes[i] ||
4960 staged_status == status_codes[i])
4961 break;
4963 if (i == ncodes)
4964 return NULL;
4966 printf("%c%c %s\n", status, staged_status, path);
4967 return NULL;
4970 static const struct got_error *
4971 cmd_status(int argc, char *argv[])
4973 const struct got_error *error = NULL;
4974 struct got_repository *repo = NULL;
4975 struct got_worktree *worktree = NULL;
4976 char *cwd = NULL, *status_codes = NULL;;
4977 struct got_pathlist_head paths;
4978 struct got_pathlist_entry *pe;
4979 int ch, i;
4981 TAILQ_INIT(&paths);
4983 while ((ch = getopt(argc, argv, "s:")) != -1) {
4984 switch (ch) {
4985 case 's':
4986 for (i = 0; i < strlen(optarg); i++) {
4987 switch (optarg[i]) {
4988 case GOT_STATUS_MODIFY:
4989 case GOT_STATUS_ADD:
4990 case GOT_STATUS_DELETE:
4991 case GOT_STATUS_CONFLICT:
4992 case GOT_STATUS_MISSING:
4993 case GOT_STATUS_OBSTRUCTED:
4994 case GOT_STATUS_UNVERSIONED:
4995 case GOT_STATUS_MODE_CHANGE:
4996 case GOT_STATUS_NONEXISTENT:
4997 break;
4998 default:
4999 errx(1, "invalid status code '%c'",
5000 optarg[i]);
5003 status_codes = optarg;
5004 break;
5005 default:
5006 usage_status();
5007 /* NOTREACHED */
5011 argc -= optind;
5012 argv += optind;
5014 #ifndef PROFILE
5015 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5016 NULL) == -1)
5017 err(1, "pledge");
5018 #endif
5019 cwd = getcwd(NULL, 0);
5020 if (cwd == NULL) {
5021 error = got_error_from_errno("getcwd");
5022 goto done;
5025 error = got_worktree_open(&worktree, cwd);
5026 if (error) {
5027 if (error->code == GOT_ERR_NOT_WORKTREE)
5028 error = wrap_not_worktree_error(error, "status", cwd);
5029 goto done;
5032 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5033 NULL);
5034 if (error != NULL)
5035 goto done;
5037 error = apply_unveil(got_repo_get_path(repo), 1,
5038 got_worktree_get_root_path(worktree));
5039 if (error)
5040 goto done;
5042 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5043 if (error)
5044 goto done;
5046 error = got_worktree_status(worktree, &paths, repo, print_status,
5047 status_codes, check_cancelled, NULL);
5048 done:
5049 TAILQ_FOREACH(pe, &paths, entry)
5050 free((char *)pe->path);
5051 got_pathlist_free(&paths);
5052 free(cwd);
5053 return error;
5056 __dead static void
5057 usage_ref(void)
5059 fprintf(stderr,
5060 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
5061 "[-d] [name]\n",
5062 getprogname());
5063 exit(1);
5066 static const struct got_error *
5067 list_refs(struct got_repository *repo, const char *refname)
5069 static const struct got_error *err = NULL;
5070 struct got_reflist_head refs;
5071 struct got_reflist_entry *re;
5073 SIMPLEQ_INIT(&refs);
5074 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
5075 if (err)
5076 return err;
5078 SIMPLEQ_FOREACH(re, &refs, entry) {
5079 char *refstr;
5080 refstr = got_ref_to_str(re->ref);
5081 if (refstr == NULL)
5082 return got_error_from_errno("got_ref_to_str");
5083 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5084 free(refstr);
5087 got_ref_list_free(&refs);
5088 return NULL;
5091 static const struct got_error *
5092 delete_ref(struct got_repository *repo, const char *refname)
5094 const struct got_error *err = NULL;
5095 struct got_reference *ref;
5097 err = got_ref_open(&ref, repo, refname, 0);
5098 if (err)
5099 return err;
5101 err = got_ref_delete(ref, repo);
5102 got_ref_close(ref);
5103 return err;
5106 static const struct got_error *
5107 add_ref(struct got_repository *repo, const char *refname, const char *target)
5109 const struct got_error *err = NULL;
5110 struct got_object_id *id;
5111 struct got_reference *ref = NULL;
5114 * Don't let the user create a reference name with a leading '-'.
5115 * While technically a valid reference name, this case is usually
5116 * an unintended typo.
5118 if (refname[0] == '-')
5119 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5121 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5122 repo);
5123 if (err) {
5124 struct got_reference *target_ref;
5126 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5127 return err;
5128 err = got_ref_open(&target_ref, repo, target, 0);
5129 if (err)
5130 return err;
5131 err = got_ref_resolve(&id, repo, target_ref);
5132 got_ref_close(target_ref);
5133 if (err)
5134 return err;
5137 err = got_ref_alloc(&ref, refname, id);
5138 if (err)
5139 goto done;
5141 err = got_ref_write(ref, repo);
5142 done:
5143 if (ref)
5144 got_ref_close(ref);
5145 free(id);
5146 return err;
5149 static const struct got_error *
5150 add_symref(struct got_repository *repo, const char *refname, const char *target)
5152 const struct got_error *err = NULL;
5153 struct got_reference *ref = NULL;
5154 struct got_reference *target_ref = NULL;
5157 * Don't let the user create a reference name with a leading '-'.
5158 * While technically a valid reference name, this case is usually
5159 * an unintended typo.
5161 if (refname[0] == '-')
5162 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5164 err = got_ref_open(&target_ref, repo, target, 0);
5165 if (err)
5166 return err;
5168 err = got_ref_alloc_symref(&ref, refname, target_ref);
5169 if (err)
5170 goto done;
5172 err = got_ref_write(ref, repo);
5173 done:
5174 if (target_ref)
5175 got_ref_close(target_ref);
5176 if (ref)
5177 got_ref_close(ref);
5178 return err;
5181 static const struct got_error *
5182 cmd_ref(int argc, char *argv[])
5184 const struct got_error *error = NULL;
5185 struct got_repository *repo = NULL;
5186 struct got_worktree *worktree = NULL;
5187 char *cwd = NULL, *repo_path = NULL;
5188 int ch, do_list = 0, do_delete = 0;
5189 const char *obj_arg = NULL, *symref_target= NULL;
5190 char *refname = NULL;
5192 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5193 switch (ch) {
5194 case 'c':
5195 obj_arg = optarg;
5196 break;
5197 case 'd':
5198 do_delete = 1;
5199 break;
5200 case 'r':
5201 repo_path = realpath(optarg, NULL);
5202 if (repo_path == NULL)
5203 return got_error_from_errno2("realpath",
5204 optarg);
5205 got_path_strip_trailing_slashes(repo_path);
5206 break;
5207 case 'l':
5208 do_list = 1;
5209 break;
5210 case 's':
5211 symref_target = optarg;
5212 break;
5213 default:
5214 usage_ref();
5215 /* NOTREACHED */
5219 if (obj_arg && do_list)
5220 errx(1, "-c and -l options are mutually exclusive");
5221 if (obj_arg && do_delete)
5222 errx(1, "-c and -d options are mutually exclusive");
5223 if (obj_arg && symref_target)
5224 errx(1, "-c and -s options are mutually exclusive");
5225 if (symref_target && do_delete)
5226 errx(1, "-s and -d options are mutually exclusive");
5227 if (symref_target && do_list)
5228 errx(1, "-s and -l options are mutually exclusive");
5229 if (do_delete && do_list)
5230 errx(1, "-d and -l options are mutually exclusive");
5232 argc -= optind;
5233 argv += optind;
5235 if (do_list) {
5236 if (argc != 0 && argc != 1)
5237 usage_ref();
5238 if (argc == 1) {
5239 refname = strdup(argv[0]);
5240 if (refname == NULL) {
5241 error = got_error_from_errno("strdup");
5242 goto done;
5245 } else {
5246 if (argc != 1)
5247 usage_ref();
5248 refname = strdup(argv[0]);
5249 if (refname == NULL) {
5250 error = got_error_from_errno("strdup");
5251 goto done;
5255 if (refname)
5256 got_path_strip_trailing_slashes(refname);
5258 #ifndef PROFILE
5259 if (do_list) {
5260 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5261 NULL) == -1)
5262 err(1, "pledge");
5263 } else {
5264 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5265 "sendfd unveil", NULL) == -1)
5266 err(1, "pledge");
5268 #endif
5269 cwd = getcwd(NULL, 0);
5270 if (cwd == NULL) {
5271 error = got_error_from_errno("getcwd");
5272 goto done;
5275 if (repo_path == NULL) {
5276 error = got_worktree_open(&worktree, cwd);
5277 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5278 goto done;
5279 else
5280 error = NULL;
5281 if (worktree) {
5282 repo_path =
5283 strdup(got_worktree_get_repo_path(worktree));
5284 if (repo_path == NULL)
5285 error = got_error_from_errno("strdup");
5286 if (error)
5287 goto done;
5288 } else {
5289 repo_path = strdup(cwd);
5290 if (repo_path == NULL) {
5291 error = got_error_from_errno("strdup");
5292 goto done;
5297 error = got_repo_open(&repo, repo_path, NULL);
5298 if (error != NULL)
5299 goto done;
5301 error = apply_unveil(got_repo_get_path(repo), do_list,
5302 worktree ? got_worktree_get_root_path(worktree) : NULL);
5303 if (error)
5304 goto done;
5306 if (do_list)
5307 error = list_refs(repo, refname);
5308 else if (do_delete)
5309 error = delete_ref(repo, refname);
5310 else if (symref_target)
5311 error = add_symref(repo, refname, symref_target);
5312 else {
5313 if (obj_arg == NULL)
5314 usage_ref();
5315 error = add_ref(repo, refname, obj_arg);
5317 done:
5318 free(refname);
5319 if (repo)
5320 got_repo_close(repo);
5321 if (worktree)
5322 got_worktree_close(worktree);
5323 free(cwd);
5324 free(repo_path);
5325 return error;
5328 __dead static void
5329 usage_branch(void)
5331 fprintf(stderr,
5332 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5333 "[name]\n", getprogname());
5334 exit(1);
5337 static const struct got_error *
5338 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5339 struct got_reference *ref)
5341 const struct got_error *err = NULL;
5342 const char *refname, *marker = " ";
5343 char *refstr;
5345 refname = got_ref_get_name(ref);
5346 if (worktree && strcmp(refname,
5347 got_worktree_get_head_ref_name(worktree)) == 0) {
5348 struct got_object_id *id = NULL;
5350 err = got_ref_resolve(&id, repo, ref);
5351 if (err)
5352 return err;
5353 if (got_object_id_cmp(id,
5354 got_worktree_get_base_commit_id(worktree)) == 0)
5355 marker = "* ";
5356 else
5357 marker = "~ ";
5358 free(id);
5361 if (strncmp(refname, "refs/heads/", 11) == 0)
5362 refname += 11;
5363 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5364 refname += 18;
5366 refstr = got_ref_to_str(ref);
5367 if (refstr == NULL)
5368 return got_error_from_errno("got_ref_to_str");
5370 printf("%s%s: %s\n", marker, refname, refstr);
5371 free(refstr);
5372 return NULL;
5375 static const struct got_error *
5376 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5378 const char *refname;
5380 if (worktree == NULL)
5381 return got_error(GOT_ERR_NOT_WORKTREE);
5383 refname = got_worktree_get_head_ref_name(worktree);
5385 if (strncmp(refname, "refs/heads/", 11) == 0)
5386 refname += 11;
5387 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5388 refname += 18;
5390 printf("%s\n", refname);
5392 return NULL;
5395 static const struct got_error *
5396 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5398 static const struct got_error *err = NULL;
5399 struct got_reflist_head refs;
5400 struct got_reflist_entry *re;
5401 struct got_reference *temp_ref = NULL;
5402 int rebase_in_progress, histedit_in_progress;
5404 SIMPLEQ_INIT(&refs);
5406 if (worktree) {
5407 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5408 worktree);
5409 if (err)
5410 return err;
5412 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5413 worktree);
5414 if (err)
5415 return err;
5417 if (rebase_in_progress || histedit_in_progress) {
5418 err = got_ref_open(&temp_ref, repo,
5419 got_worktree_get_head_ref_name(worktree), 0);
5420 if (err)
5421 return err;
5422 list_branch(repo, worktree, temp_ref);
5423 got_ref_close(temp_ref);
5427 err = got_ref_list(&refs, repo, "refs/heads",
5428 got_ref_cmp_by_name, NULL);
5429 if (err)
5430 return err;
5432 SIMPLEQ_FOREACH(re, &refs, entry)
5433 list_branch(repo, worktree, re->ref);
5435 got_ref_list_free(&refs);
5436 return NULL;
5439 static const struct got_error *
5440 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5441 const char *branch_name)
5443 const struct got_error *err = NULL;
5444 struct got_reference *ref = NULL;
5445 char *refname;
5447 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5448 return got_error_from_errno("asprintf");
5450 err = got_ref_open(&ref, repo, refname, 0);
5451 if (err)
5452 goto done;
5454 if (worktree &&
5455 strcmp(got_worktree_get_head_ref_name(worktree),
5456 got_ref_get_name(ref)) == 0) {
5457 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5458 "will not delete this work tree's current branch");
5459 goto done;
5462 err = got_ref_delete(ref, repo);
5463 done:
5464 if (ref)
5465 got_ref_close(ref);
5466 free(refname);
5467 return err;
5470 static const struct got_error *
5471 add_branch(struct got_repository *repo, const char *branch_name,
5472 struct got_object_id *base_commit_id)
5474 const struct got_error *err = NULL;
5475 struct got_reference *ref = NULL;
5476 char *base_refname = NULL, *refname = NULL;
5479 * Don't let the user create a branch name with a leading '-'.
5480 * While technically a valid reference name, this case is usually
5481 * an unintended typo.
5483 if (branch_name[0] == '-')
5484 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5486 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5487 err = got_error_from_errno("asprintf");
5488 goto done;
5491 err = got_ref_open(&ref, repo, refname, 0);
5492 if (err == NULL) {
5493 err = got_error(GOT_ERR_BRANCH_EXISTS);
5494 goto done;
5495 } else if (err->code != GOT_ERR_NOT_REF)
5496 goto done;
5498 err = got_ref_alloc(&ref, refname, base_commit_id);
5499 if (err)
5500 goto done;
5502 err = got_ref_write(ref, repo);
5503 done:
5504 if (ref)
5505 got_ref_close(ref);
5506 free(base_refname);
5507 free(refname);
5508 return err;
5511 static const struct got_error *
5512 cmd_branch(int argc, char *argv[])
5514 const struct got_error *error = NULL;
5515 struct got_repository *repo = NULL;
5516 struct got_worktree *worktree = NULL;
5517 char *cwd = NULL, *repo_path = NULL;
5518 int ch, do_list = 0, do_show = 0, do_update = 1;
5519 const char *delref = NULL, *commit_id_arg = NULL;
5520 struct got_reference *ref = NULL;
5521 struct got_pathlist_head paths;
5522 struct got_pathlist_entry *pe;
5523 struct got_object_id *commit_id = NULL;
5524 char *commit_id_str = NULL;
5526 TAILQ_INIT(&paths);
5528 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5529 switch (ch) {
5530 case 'c':
5531 commit_id_arg = optarg;
5532 break;
5533 case 'd':
5534 delref = optarg;
5535 break;
5536 case 'r':
5537 repo_path = realpath(optarg, NULL);
5538 if (repo_path == NULL)
5539 return got_error_from_errno2("realpath",
5540 optarg);
5541 got_path_strip_trailing_slashes(repo_path);
5542 break;
5543 case 'l':
5544 do_list = 1;
5545 break;
5546 case 'n':
5547 do_update = 0;
5548 break;
5549 default:
5550 usage_branch();
5551 /* NOTREACHED */
5555 if (do_list && delref)
5556 errx(1, "-l and -d options are mutually exclusive");
5558 argc -= optind;
5559 argv += optind;
5561 if (!do_list && !delref && argc == 0)
5562 do_show = 1;
5564 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5565 errx(1, "-c option can only be used when creating a branch");
5567 if (do_list || delref) {
5568 if (argc > 0)
5569 usage_branch();
5570 } else if (!do_show && argc != 1)
5571 usage_branch();
5573 #ifndef PROFILE
5574 if (do_list || do_show) {
5575 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5576 NULL) == -1)
5577 err(1, "pledge");
5578 } else {
5579 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5580 "sendfd unveil", NULL) == -1)
5581 err(1, "pledge");
5583 #endif
5584 cwd = getcwd(NULL, 0);
5585 if (cwd == NULL) {
5586 error = got_error_from_errno("getcwd");
5587 goto done;
5590 if (repo_path == NULL) {
5591 error = got_worktree_open(&worktree, cwd);
5592 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5593 goto done;
5594 else
5595 error = NULL;
5596 if (worktree) {
5597 repo_path =
5598 strdup(got_worktree_get_repo_path(worktree));
5599 if (repo_path == NULL)
5600 error = got_error_from_errno("strdup");
5601 if (error)
5602 goto done;
5603 } else {
5604 repo_path = strdup(cwd);
5605 if (repo_path == NULL) {
5606 error = got_error_from_errno("strdup");
5607 goto done;
5612 error = got_repo_open(&repo, repo_path, NULL);
5613 if (error != NULL)
5614 goto done;
5616 error = apply_unveil(got_repo_get_path(repo), do_list,
5617 worktree ? got_worktree_get_root_path(worktree) : NULL);
5618 if (error)
5619 goto done;
5621 if (do_show)
5622 error = show_current_branch(repo, worktree);
5623 else if (do_list)
5624 error = list_branches(repo, worktree);
5625 else if (delref)
5626 error = delete_branch(repo, worktree, delref);
5627 else {
5628 if (commit_id_arg == NULL)
5629 commit_id_arg = worktree ?
5630 got_worktree_get_head_ref_name(worktree) :
5631 GOT_REF_HEAD;
5632 error = got_repo_match_object_id(&commit_id, NULL,
5633 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5634 if (error)
5635 goto done;
5636 error = add_branch(repo, argv[0], commit_id);
5637 if (error)
5638 goto done;
5639 if (worktree && do_update) {
5640 struct got_update_progress_arg upa;
5641 char *branch_refname = NULL;
5643 error = got_object_id_str(&commit_id_str, commit_id);
5644 if (error)
5645 goto done;
5646 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5647 worktree);
5648 if (error)
5649 goto done;
5650 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5651 == -1) {
5652 error = got_error_from_errno("asprintf");
5653 goto done;
5655 error = got_ref_open(&ref, repo, branch_refname, 0);
5656 free(branch_refname);
5657 if (error)
5658 goto done;
5659 error = switch_head_ref(ref, commit_id, worktree,
5660 repo);
5661 if (error)
5662 goto done;
5663 error = got_worktree_set_base_commit_id(worktree, repo,
5664 commit_id);
5665 if (error)
5666 goto done;
5667 memset(&upa, 0, sizeof(upa));
5668 error = got_worktree_checkout_files(worktree, &paths,
5669 repo, update_progress, &upa, check_cancelled,
5670 NULL);
5671 if (error)
5672 goto done;
5673 if (upa.did_something)
5674 printf("Updated to commit %s\n", commit_id_str);
5675 print_update_progress_stats(&upa);
5678 done:
5679 if (ref)
5680 got_ref_close(ref);
5681 if (repo)
5682 got_repo_close(repo);
5683 if (worktree)
5684 got_worktree_close(worktree);
5685 free(cwd);
5686 free(repo_path);
5687 free(commit_id);
5688 free(commit_id_str);
5689 TAILQ_FOREACH(pe, &paths, entry)
5690 free((char *)pe->path);
5691 got_pathlist_free(&paths);
5692 return error;
5696 __dead static void
5697 usage_tag(void)
5699 fprintf(stderr,
5700 "usage: %s tag [-c commit] [-r repository] [-l] "
5701 "[-m message] name\n", getprogname());
5702 exit(1);
5705 #if 0
5706 static const struct got_error *
5707 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5709 const struct got_error *err = NULL;
5710 struct got_reflist_entry *re, *se, *new;
5711 struct got_object_id *re_id, *se_id;
5712 struct got_tag_object *re_tag, *se_tag;
5713 time_t re_time, se_time;
5715 SIMPLEQ_FOREACH(re, tags, entry) {
5716 se = SIMPLEQ_FIRST(sorted);
5717 if (se == NULL) {
5718 err = got_reflist_entry_dup(&new, re);
5719 if (err)
5720 return err;
5721 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5722 continue;
5723 } else {
5724 err = got_ref_resolve(&re_id, repo, re->ref);
5725 if (err)
5726 break;
5727 err = got_object_open_as_tag(&re_tag, repo, re_id);
5728 free(re_id);
5729 if (err)
5730 break;
5731 re_time = got_object_tag_get_tagger_time(re_tag);
5732 got_object_tag_close(re_tag);
5735 while (se) {
5736 err = got_ref_resolve(&se_id, repo, re->ref);
5737 if (err)
5738 break;
5739 err = got_object_open_as_tag(&se_tag, repo, se_id);
5740 free(se_id);
5741 if (err)
5742 break;
5743 se_time = got_object_tag_get_tagger_time(se_tag);
5744 got_object_tag_close(se_tag);
5746 if (se_time > re_time) {
5747 err = got_reflist_entry_dup(&new, re);
5748 if (err)
5749 return err;
5750 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5751 break;
5753 se = SIMPLEQ_NEXT(se, entry);
5754 continue;
5757 done:
5758 return err;
5760 #endif
5762 static const struct got_error *
5763 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5765 static const struct got_error *err = NULL;
5766 struct got_reflist_head refs;
5767 struct got_reflist_entry *re;
5769 SIMPLEQ_INIT(&refs);
5771 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5772 if (err)
5773 return err;
5775 SIMPLEQ_FOREACH(re, &refs, entry) {
5776 const char *refname;
5777 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5778 char datebuf[26];
5779 const char *tagger;
5780 time_t tagger_time;
5781 struct got_object_id *id;
5782 struct got_tag_object *tag;
5783 struct got_commit_object *commit = NULL;
5785 refname = got_ref_get_name(re->ref);
5786 if (strncmp(refname, "refs/tags/", 10) != 0)
5787 continue;
5788 refname += 10;
5789 refstr = got_ref_to_str(re->ref);
5790 if (refstr == NULL) {
5791 err = got_error_from_errno("got_ref_to_str");
5792 break;
5794 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5795 free(refstr);
5797 err = got_ref_resolve(&id, repo, re->ref);
5798 if (err)
5799 break;
5800 err = got_object_open_as_tag(&tag, repo, id);
5801 if (err) {
5802 if (err->code != GOT_ERR_OBJ_TYPE) {
5803 free(id);
5804 break;
5806 /* "lightweight" tag */
5807 err = got_object_open_as_commit(&commit, repo, id);
5808 if (err) {
5809 free(id);
5810 break;
5812 tagger = got_object_commit_get_committer(commit);
5813 tagger_time =
5814 got_object_commit_get_committer_time(commit);
5815 err = got_object_id_str(&id_str, id);
5816 free(id);
5817 if (err)
5818 break;
5819 } else {
5820 free(id);
5821 tagger = got_object_tag_get_tagger(tag);
5822 tagger_time = got_object_tag_get_tagger_time(tag);
5823 err = got_object_id_str(&id_str,
5824 got_object_tag_get_object_id(tag));
5825 if (err)
5826 break;
5828 printf("from: %s\n", tagger);
5829 datestr = get_datestr(&tagger_time, datebuf);
5830 if (datestr)
5831 printf("date: %s UTC\n", datestr);
5832 if (commit)
5833 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5834 else {
5835 switch (got_object_tag_get_object_type(tag)) {
5836 case GOT_OBJ_TYPE_BLOB:
5837 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5838 id_str);
5839 break;
5840 case GOT_OBJ_TYPE_TREE:
5841 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5842 id_str);
5843 break;
5844 case GOT_OBJ_TYPE_COMMIT:
5845 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5846 id_str);
5847 break;
5848 case GOT_OBJ_TYPE_TAG:
5849 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5850 id_str);
5851 break;
5852 default:
5853 break;
5856 free(id_str);
5857 if (commit) {
5858 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5859 if (err)
5860 break;
5861 got_object_commit_close(commit);
5862 } else {
5863 tagmsg0 = strdup(got_object_tag_get_message(tag));
5864 got_object_tag_close(tag);
5865 if (tagmsg0 == NULL) {
5866 err = got_error_from_errno("strdup");
5867 break;
5871 tagmsg = tagmsg0;
5872 do {
5873 line = strsep(&tagmsg, "\n");
5874 if (line)
5875 printf(" %s\n", line);
5876 } while (line);
5877 free(tagmsg0);
5880 got_ref_list_free(&refs);
5881 return NULL;
5884 static const struct got_error *
5885 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5886 const char *tag_name, const char *repo_path)
5888 const struct got_error *err = NULL;
5889 char *template = NULL, *initial_content = NULL;
5890 char *editor = NULL;
5891 int initial_content_len;
5892 int fd = -1;
5894 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5895 err = got_error_from_errno("asprintf");
5896 goto done;
5899 initial_content_len = asprintf(&initial_content,
5900 "\n# tagging commit %s as %s\n",
5901 commit_id_str, tag_name);
5902 if (initial_content_len == -1) {
5903 err = got_error_from_errno("asprintf");
5904 goto done;
5907 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5908 if (err)
5909 goto done;
5911 if (write(fd, initial_content, initial_content_len) == -1) {
5912 err = got_error_from_errno2("write", *tagmsg_path);
5913 goto done;
5916 err = get_editor(&editor);
5917 if (err)
5918 goto done;
5919 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
5920 initial_content_len);
5921 done:
5922 free(initial_content);
5923 free(template);
5924 free(editor);
5926 if (fd != -1 && close(fd) == -1 && err == NULL)
5927 err = got_error_from_errno2("close", *tagmsg_path);
5929 /* Editor is done; we can now apply unveil(2) */
5930 if (err == NULL)
5931 err = apply_unveil(repo_path, 0, NULL);
5932 if (err) {
5933 free(*tagmsg);
5934 *tagmsg = NULL;
5936 return err;
5939 static const struct got_error *
5940 add_tag(struct got_repository *repo, struct got_worktree *worktree,
5941 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
5943 const struct got_error *err = NULL;
5944 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5945 char *label = NULL, *commit_id_str = NULL;
5946 struct got_reference *ref = NULL;
5947 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5948 char *tagmsg_path = NULL, *tag_id_str = NULL;
5949 int preserve_tagmsg = 0;
5952 * Don't let the user create a tag name with a leading '-'.
5953 * While technically a valid reference name, this case is usually
5954 * an unintended typo.
5956 if (tag_name[0] == '-')
5957 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5959 err = get_author(&tagger, repo, worktree);
5960 if (err)
5961 return err;
5963 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5964 GOT_OBJ_TYPE_COMMIT, 1, repo);
5965 if (err)
5966 goto done;
5968 err = got_object_id_str(&commit_id_str, commit_id);
5969 if (err)
5970 goto done;
5972 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5973 refname = strdup(tag_name);
5974 if (refname == NULL) {
5975 err = got_error_from_errno("strdup");
5976 goto done;
5978 tag_name += 10;
5979 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5980 err = got_error_from_errno("asprintf");
5981 goto done;
5984 err = got_ref_open(&ref, repo, refname, 0);
5985 if (err == NULL) {
5986 err = got_error(GOT_ERR_TAG_EXISTS);
5987 goto done;
5988 } else if (err->code != GOT_ERR_NOT_REF)
5989 goto done;
5991 if (tagmsg_arg == NULL) {
5992 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5993 tag_name, got_repo_get_path(repo));
5994 if (err) {
5995 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5996 tagmsg_path != NULL)
5997 preserve_tagmsg = 1;
5998 goto done;
6002 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6003 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6004 if (err) {
6005 if (tagmsg_path)
6006 preserve_tagmsg = 1;
6007 goto done;
6010 err = got_ref_alloc(&ref, refname, tag_id);
6011 if (err) {
6012 if (tagmsg_path)
6013 preserve_tagmsg = 1;
6014 goto done;
6017 err = got_ref_write(ref, repo);
6018 if (err) {
6019 if (tagmsg_path)
6020 preserve_tagmsg = 1;
6021 goto done;
6024 err = got_object_id_str(&tag_id_str, tag_id);
6025 if (err) {
6026 if (tagmsg_path)
6027 preserve_tagmsg = 1;
6028 goto done;
6030 printf("Created tag %s\n", tag_id_str);
6031 done:
6032 if (preserve_tagmsg) {
6033 fprintf(stderr, "%s: tag message preserved in %s\n",
6034 getprogname(), tagmsg_path);
6035 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6036 err = got_error_from_errno2("unlink", tagmsg_path);
6037 free(tag_id_str);
6038 if (ref)
6039 got_ref_close(ref);
6040 free(commit_id);
6041 free(commit_id_str);
6042 free(refname);
6043 free(tagmsg);
6044 free(tagmsg_path);
6045 free(tagger);
6046 return err;
6049 static const struct got_error *
6050 cmd_tag(int argc, char *argv[])
6052 const struct got_error *error = NULL;
6053 struct got_repository *repo = NULL;
6054 struct got_worktree *worktree = NULL;
6055 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6056 char *gitconfig_path = NULL;
6057 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6058 int ch, do_list = 0;
6060 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6061 switch (ch) {
6062 case 'c':
6063 commit_id_arg = optarg;
6064 break;
6065 case 'm':
6066 tagmsg = optarg;
6067 break;
6068 case 'r':
6069 repo_path = realpath(optarg, NULL);
6070 if (repo_path == NULL)
6071 return got_error_from_errno2("realpath",
6072 optarg);
6073 got_path_strip_trailing_slashes(repo_path);
6074 break;
6075 case 'l':
6076 do_list = 1;
6077 break;
6078 default:
6079 usage_tag();
6080 /* NOTREACHED */
6084 argc -= optind;
6085 argv += optind;
6087 if (do_list) {
6088 if (commit_id_arg != NULL)
6089 errx(1,
6090 "-c option can only be used when creating a tag");
6091 if (tagmsg)
6092 errx(1, "-l and -m options are mutually exclusive");
6093 if (argc > 0)
6094 usage_tag();
6095 } else if (argc != 1)
6096 usage_tag();
6098 tag_name = argv[0];
6100 #ifndef PROFILE
6101 if (do_list) {
6102 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6103 NULL) == -1)
6104 err(1, "pledge");
6105 } else {
6106 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6107 "sendfd unveil", NULL) == -1)
6108 err(1, "pledge");
6110 #endif
6111 cwd = getcwd(NULL, 0);
6112 if (cwd == NULL) {
6113 error = got_error_from_errno("getcwd");
6114 goto done;
6117 if (repo_path == NULL) {
6118 error = got_worktree_open(&worktree, cwd);
6119 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6120 goto done;
6121 else
6122 error = NULL;
6123 if (worktree) {
6124 repo_path =
6125 strdup(got_worktree_get_repo_path(worktree));
6126 if (repo_path == NULL)
6127 error = got_error_from_errno("strdup");
6128 if (error)
6129 goto done;
6130 } else {
6131 repo_path = strdup(cwd);
6132 if (repo_path == NULL) {
6133 error = got_error_from_errno("strdup");
6134 goto done;
6139 if (do_list) {
6140 error = got_repo_open(&repo, repo_path, NULL);
6141 if (error != NULL)
6142 goto done;
6143 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6144 if (error)
6145 goto done;
6146 error = list_tags(repo, worktree);
6147 } else {
6148 error = get_gitconfig_path(&gitconfig_path);
6149 if (error)
6150 goto done;
6151 error = got_repo_open(&repo, repo_path, gitconfig_path);
6152 if (error != NULL)
6153 goto done;
6155 if (tagmsg) {
6156 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6157 if (error)
6158 goto done;
6161 if (commit_id_arg == NULL) {
6162 struct got_reference *head_ref;
6163 struct got_object_id *commit_id;
6164 error = got_ref_open(&head_ref, repo,
6165 worktree ? got_worktree_get_head_ref_name(worktree)
6166 : GOT_REF_HEAD, 0);
6167 if (error)
6168 goto done;
6169 error = got_ref_resolve(&commit_id, repo, head_ref);
6170 got_ref_close(head_ref);
6171 if (error)
6172 goto done;
6173 error = got_object_id_str(&commit_id_str, commit_id);
6174 free(commit_id);
6175 if (error)
6176 goto done;
6179 error = add_tag(repo, worktree, tag_name,
6180 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6182 done:
6183 if (repo)
6184 got_repo_close(repo);
6185 if (worktree)
6186 got_worktree_close(worktree);
6187 free(cwd);
6188 free(repo_path);
6189 free(gitconfig_path);
6190 free(commit_id_str);
6191 return error;
6194 __dead static void
6195 usage_add(void)
6197 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6198 getprogname());
6199 exit(1);
6202 static const struct got_error *
6203 add_progress(void *arg, unsigned char status, const char *path)
6205 while (path[0] == '/')
6206 path++;
6207 printf("%c %s\n", status, path);
6208 return NULL;
6211 static const struct got_error *
6212 cmd_add(int argc, char *argv[])
6214 const struct got_error *error = NULL;
6215 struct got_repository *repo = NULL;
6216 struct got_worktree *worktree = NULL;
6217 char *cwd = NULL;
6218 struct got_pathlist_head paths;
6219 struct got_pathlist_entry *pe;
6220 int ch, can_recurse = 0, no_ignores = 0;
6222 TAILQ_INIT(&paths);
6224 while ((ch = getopt(argc, argv, "IR")) != -1) {
6225 switch (ch) {
6226 case 'I':
6227 no_ignores = 1;
6228 break;
6229 case 'R':
6230 can_recurse = 1;
6231 break;
6232 default:
6233 usage_add();
6234 /* NOTREACHED */
6238 argc -= optind;
6239 argv += optind;
6241 #ifndef PROFILE
6242 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6243 NULL) == -1)
6244 err(1, "pledge");
6245 #endif
6246 if (argc < 1)
6247 usage_add();
6249 cwd = getcwd(NULL, 0);
6250 if (cwd == NULL) {
6251 error = got_error_from_errno("getcwd");
6252 goto done;
6255 error = got_worktree_open(&worktree, cwd);
6256 if (error) {
6257 if (error->code == GOT_ERR_NOT_WORKTREE)
6258 error = wrap_not_worktree_error(error, "add", cwd);
6259 goto done;
6262 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6263 NULL);
6264 if (error != NULL)
6265 goto done;
6267 error = apply_unveil(got_repo_get_path(repo), 1,
6268 got_worktree_get_root_path(worktree));
6269 if (error)
6270 goto done;
6272 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6273 if (error)
6274 goto done;
6276 if (!can_recurse && no_ignores) {
6277 error = got_error_msg(GOT_ERR_BAD_PATH,
6278 "disregarding ignores requires -R option");
6279 goto done;
6283 if (!can_recurse) {
6284 char *ondisk_path;
6285 struct stat sb;
6286 TAILQ_FOREACH(pe, &paths, entry) {
6287 if (asprintf(&ondisk_path, "%s/%s",
6288 got_worktree_get_root_path(worktree),
6289 pe->path) == -1) {
6290 error = got_error_from_errno("asprintf");
6291 goto done;
6293 if (lstat(ondisk_path, &sb) == -1) {
6294 if (errno == ENOENT) {
6295 free(ondisk_path);
6296 continue;
6298 error = got_error_from_errno2("lstat",
6299 ondisk_path);
6300 free(ondisk_path);
6301 goto done;
6303 free(ondisk_path);
6304 if (S_ISDIR(sb.st_mode)) {
6305 error = got_error_msg(GOT_ERR_BAD_PATH,
6306 "adding directories requires -R option");
6307 goto done;
6312 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6313 NULL, repo, no_ignores);
6314 done:
6315 if (repo)
6316 got_repo_close(repo);
6317 if (worktree)
6318 got_worktree_close(worktree);
6319 TAILQ_FOREACH(pe, &paths, entry)
6320 free((char *)pe->path);
6321 got_pathlist_free(&paths);
6322 free(cwd);
6323 return error;
6326 __dead static void
6327 usage_remove(void)
6329 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6330 "path ...\n", getprogname());
6331 exit(1);
6334 static const struct got_error *
6335 print_remove_status(void *arg, unsigned char status,
6336 unsigned char staged_status, const char *path)
6338 while (path[0] == '/')
6339 path++;
6340 if (status == GOT_STATUS_NONEXISTENT)
6341 return NULL;
6342 if (status == staged_status && (status == GOT_STATUS_DELETE))
6343 status = GOT_STATUS_NO_CHANGE;
6344 printf("%c%c %s\n", status, staged_status, path);
6345 return NULL;
6348 static const struct got_error *
6349 cmd_remove(int argc, char *argv[])
6351 const struct got_error *error = NULL;
6352 struct got_worktree *worktree = NULL;
6353 struct got_repository *repo = NULL;
6354 const char *status_codes = NULL;
6355 char *cwd = NULL;
6356 struct got_pathlist_head paths;
6357 struct got_pathlist_entry *pe;
6358 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6360 TAILQ_INIT(&paths);
6362 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6363 switch (ch) {
6364 case 'f':
6365 delete_local_mods = 1;
6366 break;
6367 case 'k':
6368 keep_on_disk = 1;
6369 break;
6370 case 'R':
6371 can_recurse = 1;
6372 break;
6373 case 's':
6374 for (i = 0; i < strlen(optarg); i++) {
6375 switch (optarg[i]) {
6376 case GOT_STATUS_MODIFY:
6377 delete_local_mods = 1;
6378 break;
6379 case GOT_STATUS_MISSING:
6380 break;
6381 default:
6382 errx(1, "invalid status code '%c'",
6383 optarg[i]);
6386 status_codes = optarg;
6387 break;
6388 default:
6389 usage_remove();
6390 /* NOTREACHED */
6394 argc -= optind;
6395 argv += optind;
6397 #ifndef PROFILE
6398 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6399 NULL) == -1)
6400 err(1, "pledge");
6401 #endif
6402 if (argc < 1)
6403 usage_remove();
6405 cwd = getcwd(NULL, 0);
6406 if (cwd == NULL) {
6407 error = got_error_from_errno("getcwd");
6408 goto done;
6410 error = got_worktree_open(&worktree, cwd);
6411 if (error) {
6412 if (error->code == GOT_ERR_NOT_WORKTREE)
6413 error = wrap_not_worktree_error(error, "remove", cwd);
6414 goto done;
6417 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6418 NULL);
6419 if (error)
6420 goto done;
6422 error = apply_unveil(got_repo_get_path(repo), 1,
6423 got_worktree_get_root_path(worktree));
6424 if (error)
6425 goto done;
6427 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6428 if (error)
6429 goto done;
6431 if (!can_recurse) {
6432 char *ondisk_path;
6433 struct stat sb;
6434 TAILQ_FOREACH(pe, &paths, entry) {
6435 if (asprintf(&ondisk_path, "%s/%s",
6436 got_worktree_get_root_path(worktree),
6437 pe->path) == -1) {
6438 error = got_error_from_errno("asprintf");
6439 goto done;
6441 if (lstat(ondisk_path, &sb) == -1) {
6442 if (errno == ENOENT) {
6443 free(ondisk_path);
6444 continue;
6446 error = got_error_from_errno2("lstat",
6447 ondisk_path);
6448 free(ondisk_path);
6449 goto done;
6451 free(ondisk_path);
6452 if (S_ISDIR(sb.st_mode)) {
6453 error = got_error_msg(GOT_ERR_BAD_PATH,
6454 "removing directories requires -R option");
6455 goto done;
6460 error = got_worktree_schedule_delete(worktree, &paths,
6461 delete_local_mods, status_codes, print_remove_status, NULL,
6462 repo, keep_on_disk);
6463 done:
6464 if (repo)
6465 got_repo_close(repo);
6466 if (worktree)
6467 got_worktree_close(worktree);
6468 TAILQ_FOREACH(pe, &paths, entry)
6469 free((char *)pe->path);
6470 got_pathlist_free(&paths);
6471 free(cwd);
6472 return error;
6475 __dead static void
6476 usage_revert(void)
6478 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6479 "path ...\n", getprogname());
6480 exit(1);
6483 static const struct got_error *
6484 revert_progress(void *arg, unsigned char status, const char *path)
6486 if (status == GOT_STATUS_UNVERSIONED)
6487 return NULL;
6489 while (path[0] == '/')
6490 path++;
6491 printf("%c %s\n", status, path);
6492 return NULL;
6495 struct choose_patch_arg {
6496 FILE *patch_script_file;
6497 const char *action;
6500 static const struct got_error *
6501 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6502 int nchanges, const char *action)
6504 char *line = NULL;
6505 size_t linesize = 0;
6506 ssize_t linelen;
6508 switch (status) {
6509 case GOT_STATUS_ADD:
6510 printf("A %s\n%s this addition? [y/n] ", path, action);
6511 break;
6512 case GOT_STATUS_DELETE:
6513 printf("D %s\n%s this deletion? [y/n] ", path, action);
6514 break;
6515 case GOT_STATUS_MODIFY:
6516 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6517 return got_error_from_errno("fseek");
6518 printf(GOT_COMMIT_SEP_STR);
6519 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6520 printf("%s", line);
6521 if (ferror(patch_file))
6522 return got_error_from_errno("getline");
6523 printf(GOT_COMMIT_SEP_STR);
6524 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6525 path, n, nchanges, action);
6526 break;
6527 default:
6528 return got_error_path(path, GOT_ERR_FILE_STATUS);
6531 return NULL;
6534 static const struct got_error *
6535 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6536 FILE *patch_file, int n, int nchanges)
6538 const struct got_error *err = NULL;
6539 char *line = NULL;
6540 size_t linesize = 0;
6541 ssize_t linelen;
6542 int resp = ' ';
6543 struct choose_patch_arg *a = arg;
6545 *choice = GOT_PATCH_CHOICE_NONE;
6547 if (a->patch_script_file) {
6548 char *nl;
6549 err = show_change(status, path, patch_file, n, nchanges,
6550 a->action);
6551 if (err)
6552 return err;
6553 linelen = getline(&line, &linesize, a->patch_script_file);
6554 if (linelen == -1) {
6555 if (ferror(a->patch_script_file))
6556 return got_error_from_errno("getline");
6557 return NULL;
6559 nl = strchr(line, '\n');
6560 if (nl)
6561 *nl = '\0';
6562 if (strcmp(line, "y") == 0) {
6563 *choice = GOT_PATCH_CHOICE_YES;
6564 printf("y\n");
6565 } else if (strcmp(line, "n") == 0) {
6566 *choice = GOT_PATCH_CHOICE_NO;
6567 printf("n\n");
6568 } else if (strcmp(line, "q") == 0 &&
6569 status == GOT_STATUS_MODIFY) {
6570 *choice = GOT_PATCH_CHOICE_QUIT;
6571 printf("q\n");
6572 } else
6573 printf("invalid response '%s'\n", line);
6574 free(line);
6575 return NULL;
6578 while (resp != 'y' && resp != 'n' && resp != 'q') {
6579 err = show_change(status, path, patch_file, n, nchanges,
6580 a->action);
6581 if (err)
6582 return err;
6583 resp = getchar();
6584 if (resp == '\n')
6585 resp = getchar();
6586 if (status == GOT_STATUS_MODIFY) {
6587 if (resp != 'y' && resp != 'n' && resp != 'q') {
6588 printf("invalid response '%c'\n", resp);
6589 resp = ' ';
6591 } else if (resp != 'y' && resp != 'n') {
6592 printf("invalid response '%c'\n", resp);
6593 resp = ' ';
6597 if (resp == 'y')
6598 *choice = GOT_PATCH_CHOICE_YES;
6599 else if (resp == 'n')
6600 *choice = GOT_PATCH_CHOICE_NO;
6601 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6602 *choice = GOT_PATCH_CHOICE_QUIT;
6604 return NULL;
6608 static const struct got_error *
6609 cmd_revert(int argc, char *argv[])
6611 const struct got_error *error = NULL;
6612 struct got_worktree *worktree = NULL;
6613 struct got_repository *repo = NULL;
6614 char *cwd = NULL, *path = NULL;
6615 struct got_pathlist_head paths;
6616 struct got_pathlist_entry *pe;
6617 int ch, can_recurse = 0, pflag = 0;
6618 FILE *patch_script_file = NULL;
6619 const char *patch_script_path = NULL;
6620 struct choose_patch_arg cpa;
6622 TAILQ_INIT(&paths);
6624 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6625 switch (ch) {
6626 case 'p':
6627 pflag = 1;
6628 break;
6629 case 'F':
6630 patch_script_path = optarg;
6631 break;
6632 case 'R':
6633 can_recurse = 1;
6634 break;
6635 default:
6636 usage_revert();
6637 /* NOTREACHED */
6641 argc -= optind;
6642 argv += optind;
6644 #ifndef PROFILE
6645 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6646 "unveil", NULL) == -1)
6647 err(1, "pledge");
6648 #endif
6649 if (argc < 1)
6650 usage_revert();
6651 if (patch_script_path && !pflag)
6652 errx(1, "-F option can only be used together with -p option");
6654 cwd = getcwd(NULL, 0);
6655 if (cwd == NULL) {
6656 error = got_error_from_errno("getcwd");
6657 goto done;
6659 error = got_worktree_open(&worktree, cwd);
6660 if (error) {
6661 if (error->code == GOT_ERR_NOT_WORKTREE)
6662 error = wrap_not_worktree_error(error, "revert", cwd);
6663 goto done;
6666 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6667 NULL);
6668 if (error != NULL)
6669 goto done;
6671 if (patch_script_path) {
6672 patch_script_file = fopen(patch_script_path, "r");
6673 if (patch_script_file == NULL) {
6674 error = got_error_from_errno2("fopen",
6675 patch_script_path);
6676 goto done;
6679 error = apply_unveil(got_repo_get_path(repo), 1,
6680 got_worktree_get_root_path(worktree));
6681 if (error)
6682 goto done;
6684 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6685 if (error)
6686 goto done;
6688 if (!can_recurse) {
6689 char *ondisk_path;
6690 struct stat sb;
6691 TAILQ_FOREACH(pe, &paths, entry) {
6692 if (asprintf(&ondisk_path, "%s/%s",
6693 got_worktree_get_root_path(worktree),
6694 pe->path) == -1) {
6695 error = got_error_from_errno("asprintf");
6696 goto done;
6698 if (lstat(ondisk_path, &sb) == -1) {
6699 if (errno == ENOENT) {
6700 free(ondisk_path);
6701 continue;
6703 error = got_error_from_errno2("lstat",
6704 ondisk_path);
6705 free(ondisk_path);
6706 goto done;
6708 free(ondisk_path);
6709 if (S_ISDIR(sb.st_mode)) {
6710 error = got_error_msg(GOT_ERR_BAD_PATH,
6711 "reverting directories requires -R option");
6712 goto done;
6717 cpa.patch_script_file = patch_script_file;
6718 cpa.action = "revert";
6719 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6720 pflag ? choose_patch : NULL, &cpa, repo);
6721 done:
6722 if (patch_script_file && fclose(patch_script_file) == EOF &&
6723 error == NULL)
6724 error = got_error_from_errno2("fclose", patch_script_path);
6725 if (repo)
6726 got_repo_close(repo);
6727 if (worktree)
6728 got_worktree_close(worktree);
6729 free(path);
6730 free(cwd);
6731 return error;
6734 __dead static void
6735 usage_commit(void)
6737 fprintf(stderr, "usage: %s commit [-m msg] [-S] [path ...]\n",
6738 getprogname());
6739 exit(1);
6742 struct collect_commit_logmsg_arg {
6743 const char *cmdline_log;
6744 const char *editor;
6745 const char *worktree_path;
6746 const char *branch_name;
6747 const char *repo_path;
6748 char *logmsg_path;
6752 static const struct got_error *
6753 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6754 void *arg)
6756 char *initial_content = NULL;
6757 struct got_pathlist_entry *pe;
6758 const struct got_error *err = NULL;
6759 char *template = NULL;
6760 struct collect_commit_logmsg_arg *a = arg;
6761 int initial_content_len;
6762 int fd = -1;
6763 size_t len;
6765 /* if a message was specified on the command line, just use it */
6766 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6767 len = strlen(a->cmdline_log) + 1;
6768 *logmsg = malloc(len + 1);
6769 if (*logmsg == NULL)
6770 return got_error_from_errno("malloc");
6771 strlcpy(*logmsg, a->cmdline_log, len);
6772 return NULL;
6775 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6776 return got_error_from_errno("asprintf");
6778 initial_content_len = asprintf(&initial_content,
6779 "\n# changes to be committed on branch %s:\n",
6780 a->branch_name);
6781 if (initial_content_len == -1)
6782 return got_error_from_errno("asprintf");
6784 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6785 if (err)
6786 goto done;
6788 if (write(fd, initial_content, initial_content_len) == -1) {
6789 err = got_error_from_errno2("write", a->logmsg_path);
6790 goto done;
6793 TAILQ_FOREACH(pe, commitable_paths, entry) {
6794 struct got_commitable *ct = pe->data;
6795 dprintf(fd, "# %c %s\n",
6796 got_commitable_get_status(ct),
6797 got_commitable_get_path(ct));
6800 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
6801 initial_content_len);
6802 done:
6803 free(initial_content);
6804 free(template);
6806 if (fd != -1 && close(fd) == -1 && err == NULL)
6807 err = got_error_from_errno2("close", a->logmsg_path);
6809 /* Editor is done; we can now apply unveil(2) */
6810 if (err == NULL)
6811 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6812 if (err) {
6813 free(*logmsg);
6814 *logmsg = NULL;
6816 return err;
6819 static const struct got_error *
6820 cmd_commit(int argc, char *argv[])
6822 const struct got_error *error = NULL;
6823 struct got_worktree *worktree = NULL;
6824 struct got_repository *repo = NULL;
6825 char *cwd = NULL, *id_str = NULL;
6826 struct got_object_id *id = NULL;
6827 const char *logmsg = NULL;
6828 struct collect_commit_logmsg_arg cl_arg;
6829 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6830 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6831 int allow_bad_symlinks = 0;
6832 struct got_pathlist_head paths;
6834 TAILQ_INIT(&paths);
6835 cl_arg.logmsg_path = NULL;
6837 while ((ch = getopt(argc, argv, "m:S")) != -1) {
6838 switch (ch) {
6839 case 'm':
6840 logmsg = optarg;
6841 break;
6842 case 'S':
6843 allow_bad_symlinks = 1;
6844 break;
6845 default:
6846 usage_commit();
6847 /* NOTREACHED */
6851 argc -= optind;
6852 argv += optind;
6854 #ifndef PROFILE
6855 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6856 "unveil", NULL) == -1)
6857 err(1, "pledge");
6858 #endif
6859 cwd = getcwd(NULL, 0);
6860 if (cwd == NULL) {
6861 error = got_error_from_errno("getcwd");
6862 goto done;
6864 error = got_worktree_open(&worktree, cwd);
6865 if (error) {
6866 if (error->code == GOT_ERR_NOT_WORKTREE)
6867 error = wrap_not_worktree_error(error, "commit", cwd);
6868 goto done;
6871 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6872 if (error)
6873 goto done;
6874 if (rebase_in_progress) {
6875 error = got_error(GOT_ERR_REBASING);
6876 goto done;
6879 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6880 worktree);
6881 if (error)
6882 goto done;
6884 error = get_gitconfig_path(&gitconfig_path);
6885 if (error)
6886 goto done;
6887 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6888 gitconfig_path);
6889 if (error != NULL)
6890 goto done;
6892 error = get_author(&author, repo, worktree);
6893 if (error)
6894 return error;
6897 * unveil(2) traverses exec(2); if an editor is used we have
6898 * to apply unveil after the log message has been written.
6900 if (logmsg == NULL || strlen(logmsg) == 0)
6901 error = get_editor(&editor);
6902 else
6903 error = apply_unveil(got_repo_get_path(repo), 0,
6904 got_worktree_get_root_path(worktree));
6905 if (error)
6906 goto done;
6908 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6909 if (error)
6910 goto done;
6912 cl_arg.editor = editor;
6913 cl_arg.cmdline_log = logmsg;
6914 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6915 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6916 if (!histedit_in_progress) {
6917 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6918 error = got_error(GOT_ERR_COMMIT_BRANCH);
6919 goto done;
6921 cl_arg.branch_name += 11;
6923 cl_arg.repo_path = got_repo_get_path(repo);
6924 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6925 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
6926 print_status, NULL, repo);
6927 if (error) {
6928 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6929 cl_arg.logmsg_path != NULL)
6930 preserve_logmsg = 1;
6931 goto done;
6934 error = got_object_id_str(&id_str, id);
6935 if (error)
6936 goto done;
6937 printf("Created commit %s\n", id_str);
6938 done:
6939 if (preserve_logmsg) {
6940 fprintf(stderr, "%s: log message preserved in %s\n",
6941 getprogname(), cl_arg.logmsg_path);
6942 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6943 error == NULL)
6944 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6945 free(cl_arg.logmsg_path);
6946 if (repo)
6947 got_repo_close(repo);
6948 if (worktree)
6949 got_worktree_close(worktree);
6950 free(cwd);
6951 free(id_str);
6952 free(gitconfig_path);
6953 free(editor);
6954 free(author);
6955 return error;
6958 __dead static void
6959 usage_cherrypick(void)
6961 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6962 exit(1);
6965 static const struct got_error *
6966 cmd_cherrypick(int argc, char *argv[])
6968 const struct got_error *error = NULL;
6969 struct got_worktree *worktree = NULL;
6970 struct got_repository *repo = NULL;
6971 char *cwd = NULL, *commit_id_str = NULL;
6972 struct got_object_id *commit_id = NULL;
6973 struct got_commit_object *commit = NULL;
6974 struct got_object_qid *pid;
6975 struct got_reference *head_ref = NULL;
6976 int ch;
6977 struct got_update_progress_arg upa;
6979 while ((ch = getopt(argc, argv, "")) != -1) {
6980 switch (ch) {
6981 default:
6982 usage_cherrypick();
6983 /* NOTREACHED */
6987 argc -= optind;
6988 argv += optind;
6990 #ifndef PROFILE
6991 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6992 "unveil", NULL) == -1)
6993 err(1, "pledge");
6994 #endif
6995 if (argc != 1)
6996 usage_cherrypick();
6998 cwd = getcwd(NULL, 0);
6999 if (cwd == NULL) {
7000 error = got_error_from_errno("getcwd");
7001 goto done;
7003 error = got_worktree_open(&worktree, cwd);
7004 if (error) {
7005 if (error->code == GOT_ERR_NOT_WORKTREE)
7006 error = wrap_not_worktree_error(error, "cherrypick",
7007 cwd);
7008 goto done;
7011 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7012 NULL);
7013 if (error != NULL)
7014 goto done;
7016 error = apply_unveil(got_repo_get_path(repo), 0,
7017 got_worktree_get_root_path(worktree));
7018 if (error)
7019 goto done;
7021 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7022 GOT_OBJ_TYPE_COMMIT, repo);
7023 if (error != NULL) {
7024 struct got_reference *ref;
7025 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7026 goto done;
7027 error = got_ref_open(&ref, repo, argv[0], 0);
7028 if (error != NULL)
7029 goto done;
7030 error = got_ref_resolve(&commit_id, repo, ref);
7031 got_ref_close(ref);
7032 if (error != NULL)
7033 goto done;
7035 error = got_object_id_str(&commit_id_str, commit_id);
7036 if (error)
7037 goto done;
7039 error = got_ref_open(&head_ref, repo,
7040 got_worktree_get_head_ref_name(worktree), 0);
7041 if (error != NULL)
7042 goto done;
7044 error = check_same_branch(commit_id, head_ref, NULL, repo);
7045 if (error) {
7046 if (error->code != GOT_ERR_ANCESTRY)
7047 goto done;
7048 error = NULL;
7049 } else {
7050 error = got_error(GOT_ERR_SAME_BRANCH);
7051 goto done;
7054 error = got_object_open_as_commit(&commit, repo, commit_id);
7055 if (error)
7056 goto done;
7057 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7058 memset(&upa, 0, sizeof(upa));
7059 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
7060 commit_id, repo, update_progress, &upa, check_cancelled,
7061 NULL);
7062 if (error != NULL)
7063 goto done;
7065 if (upa.did_something)
7066 printf("Merged commit %s\n", commit_id_str);
7067 print_update_progress_stats(&upa);
7068 done:
7069 if (commit)
7070 got_object_commit_close(commit);
7071 free(commit_id_str);
7072 if (head_ref)
7073 got_ref_close(head_ref);
7074 if (worktree)
7075 got_worktree_close(worktree);
7076 if (repo)
7077 got_repo_close(repo);
7078 return error;
7081 __dead static void
7082 usage_backout(void)
7084 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
7085 exit(1);
7088 static const struct got_error *
7089 cmd_backout(int argc, char *argv[])
7091 const struct got_error *error = NULL;
7092 struct got_worktree *worktree = NULL;
7093 struct got_repository *repo = NULL;
7094 char *cwd = NULL, *commit_id_str = NULL;
7095 struct got_object_id *commit_id = NULL;
7096 struct got_commit_object *commit = NULL;
7097 struct got_object_qid *pid;
7098 struct got_reference *head_ref = NULL;
7099 int ch;
7100 struct got_update_progress_arg upa;
7102 while ((ch = getopt(argc, argv, "")) != -1) {
7103 switch (ch) {
7104 default:
7105 usage_backout();
7106 /* NOTREACHED */
7110 argc -= optind;
7111 argv += optind;
7113 #ifndef PROFILE
7114 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7115 "unveil", NULL) == -1)
7116 err(1, "pledge");
7117 #endif
7118 if (argc != 1)
7119 usage_backout();
7121 cwd = getcwd(NULL, 0);
7122 if (cwd == NULL) {
7123 error = got_error_from_errno("getcwd");
7124 goto done;
7126 error = got_worktree_open(&worktree, cwd);
7127 if (error) {
7128 if (error->code == GOT_ERR_NOT_WORKTREE)
7129 error = wrap_not_worktree_error(error, "backout", cwd);
7130 goto done;
7133 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7134 NULL);
7135 if (error != NULL)
7136 goto done;
7138 error = apply_unveil(got_repo_get_path(repo), 0,
7139 got_worktree_get_root_path(worktree));
7140 if (error)
7141 goto done;
7143 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7144 GOT_OBJ_TYPE_COMMIT, repo);
7145 if (error != NULL) {
7146 struct got_reference *ref;
7147 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7148 goto done;
7149 error = got_ref_open(&ref, repo, argv[0], 0);
7150 if (error != NULL)
7151 goto done;
7152 error = got_ref_resolve(&commit_id, repo, ref);
7153 got_ref_close(ref);
7154 if (error != NULL)
7155 goto done;
7157 error = got_object_id_str(&commit_id_str, commit_id);
7158 if (error)
7159 goto done;
7161 error = got_ref_open(&head_ref, repo,
7162 got_worktree_get_head_ref_name(worktree), 0);
7163 if (error != NULL)
7164 goto done;
7166 error = check_same_branch(commit_id, head_ref, NULL, repo);
7167 if (error)
7168 goto done;
7170 error = got_object_open_as_commit(&commit, repo, commit_id);
7171 if (error)
7172 goto done;
7173 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7174 if (pid == NULL) {
7175 error = got_error(GOT_ERR_ROOT_COMMIT);
7176 goto done;
7179 memset(&upa, 0, sizeof(upa));
7180 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
7181 update_progress, &upa, check_cancelled, NULL);
7182 if (error != NULL)
7183 goto done;
7185 if (upa.did_something)
7186 printf("Backed out commit %s\n", commit_id_str);
7187 print_update_progress_stats(&upa);
7188 done:
7189 if (commit)
7190 got_object_commit_close(commit);
7191 free(commit_id_str);
7192 if (head_ref)
7193 got_ref_close(head_ref);
7194 if (worktree)
7195 got_worktree_close(worktree);
7196 if (repo)
7197 got_repo_close(repo);
7198 return error;
7201 __dead static void
7202 usage_rebase(void)
7204 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
7205 getprogname());
7206 exit(1);
7209 void
7210 trim_logmsg(char *logmsg, int limit)
7212 char *nl;
7213 size_t len;
7215 len = strlen(logmsg);
7216 if (len > limit)
7217 len = limit;
7218 logmsg[len] = '\0';
7219 nl = strchr(logmsg, '\n');
7220 if (nl)
7221 *nl = '\0';
7224 static const struct got_error *
7225 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
7227 const struct got_error *err;
7228 char *logmsg0 = NULL;
7229 const char *s;
7231 err = got_object_commit_get_logmsg(&logmsg0, commit);
7232 if (err)
7233 return err;
7235 s = logmsg0;
7236 while (isspace((unsigned char)s[0]))
7237 s++;
7239 *logmsg = strdup(s);
7240 if (*logmsg == NULL) {
7241 err = got_error_from_errno("strdup");
7242 goto done;
7245 trim_logmsg(*logmsg, limit);
7246 done:
7247 free(logmsg0);
7248 return err;
7251 static const struct got_error *
7252 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
7254 const struct got_error *err;
7255 struct got_commit_object *commit = NULL;
7256 char *id_str = NULL, *logmsg = NULL;
7258 err = got_object_open_as_commit(&commit, repo, id);
7259 if (err)
7260 return err;
7262 err = got_object_id_str(&id_str, id);
7263 if (err)
7264 goto done;
7266 id_str[12] = '\0';
7268 err = get_short_logmsg(&logmsg, 42, commit);
7269 if (err)
7270 goto done;
7272 printf("%s -> merge conflict: %s\n", id_str, logmsg);
7273 done:
7274 free(id_str);
7275 got_object_commit_close(commit);
7276 free(logmsg);
7277 return err;
7280 static const struct got_error *
7281 show_rebase_progress(struct got_commit_object *commit,
7282 struct got_object_id *old_id, struct got_object_id *new_id)
7284 const struct got_error *err;
7285 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7287 err = got_object_id_str(&old_id_str, old_id);
7288 if (err)
7289 goto done;
7291 if (new_id) {
7292 err = got_object_id_str(&new_id_str, new_id);
7293 if (err)
7294 goto done;
7297 old_id_str[12] = '\0';
7298 if (new_id_str)
7299 new_id_str[12] = '\0';
7301 err = get_short_logmsg(&logmsg, 42, commit);
7302 if (err)
7303 goto done;
7305 printf("%s -> %s: %s\n", old_id_str,
7306 new_id_str ? new_id_str : "no-op change", logmsg);
7307 done:
7308 free(old_id_str);
7309 free(new_id_str);
7310 free(logmsg);
7311 return err;
7314 static const struct got_error *
7315 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
7316 struct got_reference *branch, struct got_reference *new_base_branch,
7317 struct got_reference *tmp_branch, struct got_repository *repo)
7319 printf("Switching work tree to %s\n", got_ref_get_name(branch));
7320 return got_worktree_rebase_complete(worktree, fileindex,
7321 new_base_branch, tmp_branch, branch, repo);
7324 static const struct got_error *
7325 rebase_commit(struct got_pathlist_head *merged_paths,
7326 struct got_worktree *worktree, struct got_fileindex *fileindex,
7327 struct got_reference *tmp_branch,
7328 struct got_object_id *commit_id, struct got_repository *repo)
7330 const struct got_error *error;
7331 struct got_commit_object *commit;
7332 struct got_object_id *new_commit_id;
7334 error = got_object_open_as_commit(&commit, repo, commit_id);
7335 if (error)
7336 return error;
7338 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
7339 worktree, fileindex, tmp_branch, commit, commit_id, repo);
7340 if (error) {
7341 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
7342 goto done;
7343 error = show_rebase_progress(commit, commit_id, NULL);
7344 } else {
7345 error = show_rebase_progress(commit, commit_id, new_commit_id);
7346 free(new_commit_id);
7348 done:
7349 got_object_commit_close(commit);
7350 return error;
7353 struct check_path_prefix_arg {
7354 const char *path_prefix;
7355 size_t len;
7356 int errcode;
7359 static const struct got_error *
7360 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
7361 struct got_blob_object *blob2, struct got_object_id *id1,
7362 struct got_object_id *id2, const char *path1, const char *path2,
7363 mode_t mode1, mode_t mode2, struct got_repository *repo)
7365 struct check_path_prefix_arg *a = arg;
7367 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
7368 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
7369 return got_error(a->errcode);
7371 return NULL;
7374 static const struct got_error *
7375 check_path_prefix(struct got_object_id *parent_id,
7376 struct got_object_id *commit_id, const char *path_prefix,
7377 int errcode, struct got_repository *repo)
7379 const struct got_error *err;
7380 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7381 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7382 struct check_path_prefix_arg cpp_arg;
7384 if (got_path_is_root_dir(path_prefix))
7385 return NULL;
7387 err = got_object_open_as_commit(&commit, repo, commit_id);
7388 if (err)
7389 goto done;
7391 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7392 if (err)
7393 goto done;
7395 err = got_object_open_as_tree(&tree1, repo,
7396 got_object_commit_get_tree_id(parent_commit));
7397 if (err)
7398 goto done;
7400 err = got_object_open_as_tree(&tree2, repo,
7401 got_object_commit_get_tree_id(commit));
7402 if (err)
7403 goto done;
7405 cpp_arg.path_prefix = path_prefix;
7406 while (cpp_arg.path_prefix[0] == '/')
7407 cpp_arg.path_prefix++;
7408 cpp_arg.len = strlen(cpp_arg.path_prefix);
7409 cpp_arg.errcode = errcode;
7410 err = got_diff_tree(tree1, tree2, "", "", repo,
7411 check_path_prefix_in_diff, &cpp_arg, 0);
7412 done:
7413 if (tree1)
7414 got_object_tree_close(tree1);
7415 if (tree2)
7416 got_object_tree_close(tree2);
7417 if (commit)
7418 got_object_commit_close(commit);
7419 if (parent_commit)
7420 got_object_commit_close(parent_commit);
7421 return err;
7424 static const struct got_error *
7425 collect_commits(struct got_object_id_queue *commits,
7426 struct got_object_id *initial_commit_id,
7427 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7428 const char *path_prefix, int path_prefix_errcode,
7429 struct got_repository *repo)
7431 const struct got_error *err = NULL;
7432 struct got_commit_graph *graph = NULL;
7433 struct got_object_id *parent_id = NULL;
7434 struct got_object_qid *qid;
7435 struct got_object_id *commit_id = initial_commit_id;
7437 err = got_commit_graph_open(&graph, "/", 1);
7438 if (err)
7439 return err;
7441 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7442 check_cancelled, NULL);
7443 if (err)
7444 goto done;
7445 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7446 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7447 check_cancelled, NULL);
7448 if (err) {
7449 if (err->code == GOT_ERR_ITER_COMPLETED) {
7450 err = got_error_msg(GOT_ERR_ANCESTRY,
7451 "ran out of commits to rebase before "
7452 "youngest common ancestor commit has "
7453 "been reached?!?");
7455 goto done;
7456 } else {
7457 err = check_path_prefix(parent_id, commit_id,
7458 path_prefix, path_prefix_errcode, repo);
7459 if (err)
7460 goto done;
7462 err = got_object_qid_alloc(&qid, commit_id);
7463 if (err)
7464 goto done;
7465 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
7466 commit_id = parent_id;
7469 done:
7470 got_commit_graph_close(graph);
7471 return err;
7474 static const struct got_error *
7475 cmd_rebase(int argc, char *argv[])
7477 const struct got_error *error = NULL;
7478 struct got_worktree *worktree = NULL;
7479 struct got_repository *repo = NULL;
7480 struct got_fileindex *fileindex = NULL;
7481 char *cwd = NULL;
7482 struct got_reference *branch = NULL;
7483 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
7484 struct got_object_id *commit_id = NULL, *parent_id = NULL;
7485 struct got_object_id *resume_commit_id = NULL;
7486 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
7487 struct got_commit_object *commit = NULL;
7488 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
7489 int histedit_in_progress = 0;
7490 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7491 struct got_object_id_queue commits;
7492 struct got_pathlist_head merged_paths;
7493 const struct got_object_id_queue *parent_ids;
7494 struct got_object_qid *qid, *pid;
7496 SIMPLEQ_INIT(&commits);
7497 TAILQ_INIT(&merged_paths);
7499 while ((ch = getopt(argc, argv, "ac")) != -1) {
7500 switch (ch) {
7501 case 'a':
7502 abort_rebase = 1;
7503 break;
7504 case 'c':
7505 continue_rebase = 1;
7506 break;
7507 default:
7508 usage_rebase();
7509 /* NOTREACHED */
7513 argc -= optind;
7514 argv += optind;
7516 #ifndef PROFILE
7517 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7518 "unveil", NULL) == -1)
7519 err(1, "pledge");
7520 #endif
7521 if (abort_rebase && continue_rebase)
7522 usage_rebase();
7523 else if (abort_rebase || continue_rebase) {
7524 if (argc != 0)
7525 usage_rebase();
7526 } else if (argc != 1)
7527 usage_rebase();
7529 cwd = getcwd(NULL, 0);
7530 if (cwd == NULL) {
7531 error = got_error_from_errno("getcwd");
7532 goto done;
7534 error = got_worktree_open(&worktree, cwd);
7535 if (error) {
7536 if (error->code == GOT_ERR_NOT_WORKTREE)
7537 error = wrap_not_worktree_error(error, "rebase", cwd);
7538 goto done;
7541 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7542 NULL);
7543 if (error != NULL)
7544 goto done;
7546 error = apply_unveil(got_repo_get_path(repo), 0,
7547 got_worktree_get_root_path(worktree));
7548 if (error)
7549 goto done;
7551 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7552 worktree);
7553 if (error)
7554 goto done;
7555 if (histedit_in_progress) {
7556 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7557 goto done;
7560 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7561 if (error)
7562 goto done;
7564 if (abort_rebase) {
7565 struct got_update_progress_arg upa;
7566 if (!rebase_in_progress) {
7567 error = got_error(GOT_ERR_NOT_REBASING);
7568 goto done;
7570 error = got_worktree_rebase_continue(&resume_commit_id,
7571 &new_base_branch, &tmp_branch, &branch, &fileindex,
7572 worktree, repo);
7573 if (error)
7574 goto done;
7575 printf("Switching work tree to %s\n",
7576 got_ref_get_symref_target(new_base_branch));
7577 memset(&upa, 0, sizeof(upa));
7578 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7579 new_base_branch, update_progress, &upa);
7580 if (error)
7581 goto done;
7582 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7583 print_update_progress_stats(&upa);
7584 goto done; /* nothing else to do */
7587 if (continue_rebase) {
7588 if (!rebase_in_progress) {
7589 error = got_error(GOT_ERR_NOT_REBASING);
7590 goto done;
7592 error = got_worktree_rebase_continue(&resume_commit_id,
7593 &new_base_branch, &tmp_branch, &branch, &fileindex,
7594 worktree, repo);
7595 if (error)
7596 goto done;
7598 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7599 resume_commit_id, repo);
7600 if (error)
7601 goto done;
7603 yca_id = got_object_id_dup(resume_commit_id);
7604 if (yca_id == NULL) {
7605 error = got_error_from_errno("got_object_id_dup");
7606 goto done;
7608 } else {
7609 error = got_ref_open(&branch, repo, argv[0], 0);
7610 if (error != NULL)
7611 goto done;
7614 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7615 if (error)
7616 goto done;
7618 if (!continue_rebase) {
7619 struct got_object_id *base_commit_id;
7621 base_commit_id = got_worktree_get_base_commit_id(worktree);
7622 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7623 base_commit_id, branch_head_commit_id, repo,
7624 check_cancelled, NULL);
7625 if (error)
7626 goto done;
7627 if (yca_id == NULL) {
7628 error = got_error_msg(GOT_ERR_ANCESTRY,
7629 "specified branch shares no common ancestry "
7630 "with work tree's branch");
7631 goto done;
7634 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7635 if (error) {
7636 if (error->code != GOT_ERR_ANCESTRY)
7637 goto done;
7638 error = NULL;
7639 } else {
7640 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7641 "specified branch resolves to a commit which "
7642 "is already contained in work tree's branch");
7643 goto done;
7645 error = got_worktree_rebase_prepare(&new_base_branch,
7646 &tmp_branch, &fileindex, worktree, branch, repo);
7647 if (error)
7648 goto done;
7651 commit_id = branch_head_commit_id;
7652 error = got_object_open_as_commit(&commit, repo, commit_id);
7653 if (error)
7654 goto done;
7656 parent_ids = got_object_commit_get_parent_ids(commit);
7657 pid = SIMPLEQ_FIRST(parent_ids);
7658 if (pid == NULL) {
7659 if (!continue_rebase) {
7660 struct got_update_progress_arg upa;
7661 memset(&upa, 0, sizeof(upa));
7662 error = got_worktree_rebase_abort(worktree, fileindex,
7663 repo, new_base_branch, update_progress, &upa);
7664 if (error)
7665 goto done;
7666 printf("Rebase of %s aborted\n",
7667 got_ref_get_name(branch));
7668 print_update_progress_stats(&upa);
7671 error = got_error(GOT_ERR_EMPTY_REBASE);
7672 goto done;
7674 error = collect_commits(&commits, commit_id, pid->id,
7675 yca_id, got_worktree_get_path_prefix(worktree),
7676 GOT_ERR_REBASE_PATH, repo);
7677 got_object_commit_close(commit);
7678 commit = NULL;
7679 if (error)
7680 goto done;
7682 if (SIMPLEQ_EMPTY(&commits)) {
7683 if (continue_rebase) {
7684 error = rebase_complete(worktree, fileindex,
7685 branch, new_base_branch, tmp_branch, repo);
7686 goto done;
7687 } else {
7688 /* Fast-forward the reference of the branch. */
7689 struct got_object_id *new_head_commit_id;
7690 char *id_str;
7691 error = got_ref_resolve(&new_head_commit_id, repo,
7692 new_base_branch);
7693 if (error)
7694 goto done;
7695 error = got_object_id_str(&id_str, new_head_commit_id);
7696 printf("Forwarding %s to commit %s\n",
7697 got_ref_get_name(branch), id_str);
7698 free(id_str);
7699 error = got_ref_change_ref(branch,
7700 new_head_commit_id);
7701 if (error)
7702 goto done;
7706 pid = NULL;
7707 SIMPLEQ_FOREACH(qid, &commits, entry) {
7708 struct got_update_progress_arg upa;
7710 commit_id = qid->id;
7711 parent_id = pid ? pid->id : yca_id;
7712 pid = qid;
7714 memset(&upa, 0, sizeof(upa));
7715 error = got_worktree_rebase_merge_files(&merged_paths,
7716 worktree, fileindex, parent_id, commit_id, repo,
7717 update_progress, &upa, check_cancelled, NULL);
7718 if (error)
7719 goto done;
7721 print_update_progress_stats(&upa);
7722 if (upa.conflicts > 0)
7723 rebase_status = GOT_STATUS_CONFLICT;
7725 if (rebase_status == GOT_STATUS_CONFLICT) {
7726 error = show_rebase_merge_conflict(qid->id, repo);
7727 if (error)
7728 goto done;
7729 got_worktree_rebase_pathlist_free(&merged_paths);
7730 break;
7733 error = rebase_commit(&merged_paths, worktree, fileindex,
7734 tmp_branch, commit_id, repo);
7735 got_worktree_rebase_pathlist_free(&merged_paths);
7736 if (error)
7737 goto done;
7740 if (rebase_status == GOT_STATUS_CONFLICT) {
7741 error = got_worktree_rebase_postpone(worktree, fileindex);
7742 if (error)
7743 goto done;
7744 error = got_error_msg(GOT_ERR_CONFLICTS,
7745 "conflicts must be resolved before rebasing can continue");
7746 } else
7747 error = rebase_complete(worktree, fileindex, branch,
7748 new_base_branch, tmp_branch, repo);
7749 done:
7750 got_object_id_queue_free(&commits);
7751 free(branch_head_commit_id);
7752 free(resume_commit_id);
7753 free(yca_id);
7754 if (commit)
7755 got_object_commit_close(commit);
7756 if (branch)
7757 got_ref_close(branch);
7758 if (new_base_branch)
7759 got_ref_close(new_base_branch);
7760 if (tmp_branch)
7761 got_ref_close(tmp_branch);
7762 if (worktree)
7763 got_worktree_close(worktree);
7764 if (repo)
7765 got_repo_close(repo);
7766 return error;
7769 __dead static void
7770 usage_histedit(void)
7772 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
7773 getprogname());
7774 exit(1);
7777 #define GOT_HISTEDIT_PICK 'p'
7778 #define GOT_HISTEDIT_EDIT 'e'
7779 #define GOT_HISTEDIT_FOLD 'f'
7780 #define GOT_HISTEDIT_DROP 'd'
7781 #define GOT_HISTEDIT_MESG 'm'
7783 static struct got_histedit_cmd {
7784 unsigned char code;
7785 const char *name;
7786 const char *desc;
7787 } got_histedit_cmds[] = {
7788 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7789 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7790 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7791 "be used" },
7792 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7793 { GOT_HISTEDIT_MESG, "mesg",
7794 "single-line log message for commit above (open editor if empty)" },
7797 struct got_histedit_list_entry {
7798 TAILQ_ENTRY(got_histedit_list_entry) entry;
7799 struct got_object_id *commit_id;
7800 const struct got_histedit_cmd *cmd;
7801 char *logmsg;
7803 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7805 static const struct got_error *
7806 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7807 FILE *f, struct got_repository *repo)
7809 const struct got_error *err = NULL;
7810 char *logmsg = NULL, *id_str = NULL;
7811 struct got_commit_object *commit = NULL;
7812 int n;
7814 err = got_object_open_as_commit(&commit, repo, commit_id);
7815 if (err)
7816 goto done;
7818 err = get_short_logmsg(&logmsg, 34, commit);
7819 if (err)
7820 goto done;
7822 err = got_object_id_str(&id_str, commit_id);
7823 if (err)
7824 goto done;
7826 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7827 if (n < 0)
7828 err = got_ferror(f, GOT_ERR_IO);
7829 done:
7830 if (commit)
7831 got_object_commit_close(commit);
7832 free(id_str);
7833 free(logmsg);
7834 return err;
7837 static const struct got_error *
7838 histedit_write_commit_list(struct got_object_id_queue *commits,
7839 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7841 const struct got_error *err = NULL;
7842 struct got_object_qid *qid;
7844 if (SIMPLEQ_EMPTY(commits))
7845 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7847 SIMPLEQ_FOREACH(qid, commits, entry) {
7848 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7849 f, repo);
7850 if (err)
7851 break;
7852 if (edit_logmsg_only) {
7853 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7854 if (n < 0) {
7855 err = got_ferror(f, GOT_ERR_IO);
7856 break;
7861 return err;
7864 static const struct got_error *
7865 write_cmd_list(FILE *f, const char *branch_name,
7866 struct got_object_id_queue *commits)
7868 const struct got_error *err = NULL;
7869 int n, i;
7870 char *id_str;
7871 struct got_object_qid *qid;
7873 qid = SIMPLEQ_FIRST(commits);
7874 err = got_object_id_str(&id_str, qid->id);
7875 if (err)
7876 return err;
7878 n = fprintf(f,
7879 "# Editing the history of branch '%s' starting at\n"
7880 "# commit %s\n"
7881 "# Commits will be processed in order from top to "
7882 "bottom of this file.\n", branch_name, id_str);
7883 if (n < 0) {
7884 err = got_ferror(f, GOT_ERR_IO);
7885 goto done;
7888 n = fprintf(f, "# Available histedit commands:\n");
7889 if (n < 0) {
7890 err = got_ferror(f, GOT_ERR_IO);
7891 goto done;
7894 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7895 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7896 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7897 cmd->desc);
7898 if (n < 0) {
7899 err = got_ferror(f, GOT_ERR_IO);
7900 break;
7903 done:
7904 free(id_str);
7905 return err;
7908 static const struct got_error *
7909 histedit_syntax_error(int lineno)
7911 static char msg[42];
7912 int ret;
7914 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7915 lineno);
7916 if (ret == -1 || ret >= sizeof(msg))
7917 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7919 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7922 static const struct got_error *
7923 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7924 char *logmsg, struct got_repository *repo)
7926 const struct got_error *err;
7927 struct got_commit_object *folded_commit = NULL;
7928 char *id_str, *folded_logmsg = NULL;
7930 err = got_object_id_str(&id_str, hle->commit_id);
7931 if (err)
7932 return err;
7934 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7935 if (err)
7936 goto done;
7938 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7939 if (err)
7940 goto done;
7941 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7942 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7943 folded_logmsg) == -1) {
7944 err = got_error_from_errno("asprintf");
7946 done:
7947 if (folded_commit)
7948 got_object_commit_close(folded_commit);
7949 free(id_str);
7950 free(folded_logmsg);
7951 return err;
7954 static struct got_histedit_list_entry *
7955 get_folded_commits(struct got_histedit_list_entry *hle)
7957 struct got_histedit_list_entry *prev, *folded = NULL;
7959 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7960 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7961 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7962 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7963 folded = prev;
7964 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7967 return folded;
7970 static const struct got_error *
7971 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7972 struct got_repository *repo)
7974 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7975 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7976 const struct got_error *err = NULL;
7977 struct got_commit_object *commit = NULL;
7978 int logmsg_len;
7979 int fd;
7980 struct got_histedit_list_entry *folded = NULL;
7982 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7983 if (err)
7984 return err;
7986 folded = get_folded_commits(hle);
7987 if (folded) {
7988 while (folded != hle) {
7989 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7990 folded = TAILQ_NEXT(folded, entry);
7991 continue;
7993 err = append_folded_commit_msg(&new_msg, folded,
7994 logmsg, repo);
7995 if (err)
7996 goto done;
7997 free(logmsg);
7998 logmsg = new_msg;
7999 folded = TAILQ_NEXT(folded, entry);
8003 err = got_object_id_str(&id_str, hle->commit_id);
8004 if (err)
8005 goto done;
8006 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
8007 if (err)
8008 goto done;
8009 logmsg_len = asprintf(&new_msg,
8010 "%s\n# original log message of commit %s: %s",
8011 logmsg ? logmsg : "", id_str, orig_logmsg);
8012 if (logmsg_len == -1) {
8013 err = got_error_from_errno("asprintf");
8014 goto done;
8016 free(logmsg);
8017 logmsg = new_msg;
8019 err = got_object_id_str(&id_str, hle->commit_id);
8020 if (err)
8021 goto done;
8023 err = got_opentemp_named_fd(&logmsg_path, &fd,
8024 GOT_TMPDIR_STR "/got-logmsg");
8025 if (err)
8026 goto done;
8028 write(fd, logmsg, logmsg_len);
8029 close(fd);
8031 err = get_editor(&editor);
8032 if (err)
8033 goto done;
8035 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
8036 logmsg_len);
8037 if (err) {
8038 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
8039 goto done;
8040 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
8042 done:
8043 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
8044 err = got_error_from_errno2("unlink", logmsg_path);
8045 free(logmsg_path);
8046 free(logmsg);
8047 free(orig_logmsg);
8048 free(editor);
8049 if (commit)
8050 got_object_commit_close(commit);
8051 return err;
8054 static const struct got_error *
8055 histedit_parse_list(struct got_histedit_list *histedit_cmds,
8056 FILE *f, struct got_repository *repo)
8058 const struct got_error *err = NULL;
8059 char *line = NULL, *p, *end;
8060 size_t size;
8061 ssize_t len;
8062 int lineno = 0, i;
8063 const struct got_histedit_cmd *cmd;
8064 struct got_object_id *commit_id = NULL;
8065 struct got_histedit_list_entry *hle = NULL;
8067 for (;;) {
8068 len = getline(&line, &size, f);
8069 if (len == -1) {
8070 const struct got_error *getline_err;
8071 if (feof(f))
8072 break;
8073 getline_err = got_error_from_errno("getline");
8074 err = got_ferror(f, getline_err->code);
8075 break;
8077 lineno++;
8078 p = line;
8079 while (isspace((unsigned char)p[0]))
8080 p++;
8081 if (p[0] == '#' || p[0] == '\0') {
8082 free(line);
8083 line = NULL;
8084 continue;
8086 cmd = NULL;
8087 for (i = 0; i < nitems(got_histedit_cmds); i++) {
8088 cmd = &got_histedit_cmds[i];
8089 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
8090 isspace((unsigned char)p[strlen(cmd->name)])) {
8091 p += strlen(cmd->name);
8092 break;
8094 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
8095 p++;
8096 break;
8099 if (i == nitems(got_histedit_cmds)) {
8100 err = histedit_syntax_error(lineno);
8101 break;
8103 while (isspace((unsigned char)p[0]))
8104 p++;
8105 if (cmd->code == GOT_HISTEDIT_MESG) {
8106 if (hle == NULL || hle->logmsg != NULL) {
8107 err = got_error(GOT_ERR_HISTEDIT_CMD);
8108 break;
8110 if (p[0] == '\0') {
8111 err = histedit_edit_logmsg(hle, repo);
8112 if (err)
8113 break;
8114 } else {
8115 hle->logmsg = strdup(p);
8116 if (hle->logmsg == NULL) {
8117 err = got_error_from_errno("strdup");
8118 break;
8121 free(line);
8122 line = NULL;
8123 continue;
8124 } else {
8125 end = p;
8126 while (end[0] && !isspace((unsigned char)end[0]))
8127 end++;
8128 *end = '\0';
8130 err = got_object_resolve_id_str(&commit_id, repo, p);
8131 if (err) {
8132 /* override error code */
8133 err = histedit_syntax_error(lineno);
8134 break;
8137 hle = malloc(sizeof(*hle));
8138 if (hle == NULL) {
8139 err = got_error_from_errno("malloc");
8140 break;
8142 hle->cmd = cmd;
8143 hle->commit_id = commit_id;
8144 hle->logmsg = NULL;
8145 commit_id = NULL;
8146 free(line);
8147 line = NULL;
8148 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
8151 free(line);
8152 free(commit_id);
8153 return err;
8156 static const struct got_error *
8157 histedit_check_script(struct got_histedit_list *histedit_cmds,
8158 struct got_object_id_queue *commits, struct got_repository *repo)
8160 const struct got_error *err = NULL;
8161 struct got_object_qid *qid;
8162 struct got_histedit_list_entry *hle;
8163 static char msg[92];
8164 char *id_str;
8166 if (TAILQ_EMPTY(histedit_cmds))
8167 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
8168 "histedit script contains no commands");
8169 if (SIMPLEQ_EMPTY(commits))
8170 return got_error(GOT_ERR_EMPTY_HISTEDIT);
8172 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8173 struct got_histedit_list_entry *hle2;
8174 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
8175 if (hle == hle2)
8176 continue;
8177 if (got_object_id_cmp(hle->commit_id,
8178 hle2->commit_id) != 0)
8179 continue;
8180 err = got_object_id_str(&id_str, hle->commit_id);
8181 if (err)
8182 return err;
8183 snprintf(msg, sizeof(msg), "commit %s is listed "
8184 "more than once in histedit script", id_str);
8185 free(id_str);
8186 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8190 SIMPLEQ_FOREACH(qid, commits, entry) {
8191 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8192 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
8193 break;
8195 if (hle == NULL) {
8196 err = got_object_id_str(&id_str, qid->id);
8197 if (err)
8198 return err;
8199 snprintf(msg, sizeof(msg),
8200 "commit %s missing from histedit script", id_str);
8201 free(id_str);
8202 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8206 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
8207 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
8208 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
8209 "last commit in histedit script cannot be folded");
8211 return NULL;
8214 static const struct got_error *
8215 histedit_run_editor(struct got_histedit_list *histedit_cmds,
8216 const char *path, struct got_object_id_queue *commits,
8217 struct got_repository *repo)
8219 const struct got_error *err = NULL;
8220 char *editor;
8221 FILE *f = NULL;
8223 err = get_editor(&editor);
8224 if (err)
8225 return err;
8227 if (spawn_editor(editor, path) == -1) {
8228 err = got_error_from_errno("failed spawning editor");
8229 goto done;
8232 f = fopen(path, "r");
8233 if (f == NULL) {
8234 err = got_error_from_errno("fopen");
8235 goto done;
8237 err = histedit_parse_list(histedit_cmds, f, repo);
8238 if (err)
8239 goto done;
8241 err = histedit_check_script(histedit_cmds, commits, repo);
8242 done:
8243 if (f && fclose(f) != 0 && err == NULL)
8244 err = got_error_from_errno("fclose");
8245 free(editor);
8246 return err;
8249 static const struct got_error *
8250 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
8251 struct got_object_id_queue *, const char *, const char *,
8252 struct got_repository *);
8254 static const struct got_error *
8255 histedit_edit_script(struct got_histedit_list *histedit_cmds,
8256 struct got_object_id_queue *commits, const char *branch_name,
8257 int edit_logmsg_only, struct got_repository *repo)
8259 const struct got_error *err;
8260 FILE *f = NULL;
8261 char *path = NULL;
8263 err = got_opentemp_named(&path, &f, "got-histedit");
8264 if (err)
8265 return err;
8267 err = write_cmd_list(f, branch_name, commits);
8268 if (err)
8269 goto done;
8271 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
8272 if (err)
8273 goto done;
8275 if (edit_logmsg_only) {
8276 rewind(f);
8277 err = histedit_parse_list(histedit_cmds, f, repo);
8278 } else {
8279 if (fclose(f) != 0) {
8280 err = got_error_from_errno("fclose");
8281 goto done;
8283 f = NULL;
8284 err = histedit_run_editor(histedit_cmds, path, commits, repo);
8285 if (err) {
8286 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8287 err->code != GOT_ERR_HISTEDIT_CMD)
8288 goto done;
8289 err = histedit_edit_list_retry(histedit_cmds, err,
8290 commits, path, branch_name, repo);
8293 done:
8294 if (f && fclose(f) != 0 && err == NULL)
8295 err = got_error_from_errno("fclose");
8296 if (path && unlink(path) != 0 && err == NULL)
8297 err = got_error_from_errno2("unlink", path);
8298 free(path);
8299 return err;
8302 static const struct got_error *
8303 histedit_save_list(struct got_histedit_list *histedit_cmds,
8304 struct got_worktree *worktree, struct got_repository *repo)
8306 const struct got_error *err = NULL;
8307 char *path = NULL;
8308 FILE *f = NULL;
8309 struct got_histedit_list_entry *hle;
8310 struct got_commit_object *commit = NULL;
8312 err = got_worktree_get_histedit_script_path(&path, worktree);
8313 if (err)
8314 return err;
8316 f = fopen(path, "w");
8317 if (f == NULL) {
8318 err = got_error_from_errno2("fopen", path);
8319 goto done;
8321 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8322 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
8323 repo);
8324 if (err)
8325 break;
8327 if (hle->logmsg) {
8328 int n = fprintf(f, "%c %s\n",
8329 GOT_HISTEDIT_MESG, hle->logmsg);
8330 if (n < 0) {
8331 err = got_ferror(f, GOT_ERR_IO);
8332 break;
8336 done:
8337 if (f && fclose(f) != 0 && err == NULL)
8338 err = got_error_from_errno("fclose");
8339 free(path);
8340 if (commit)
8341 got_object_commit_close(commit);
8342 return err;
8345 void
8346 histedit_free_list(struct got_histedit_list *histedit_cmds)
8348 struct got_histedit_list_entry *hle;
8350 while ((hle = TAILQ_FIRST(histedit_cmds))) {
8351 TAILQ_REMOVE(histedit_cmds, hle, entry);
8352 free(hle);
8356 static const struct got_error *
8357 histedit_load_list(struct got_histedit_list *histedit_cmds,
8358 const char *path, struct got_repository *repo)
8360 const struct got_error *err = NULL;
8361 FILE *f = NULL;
8363 f = fopen(path, "r");
8364 if (f == NULL) {
8365 err = got_error_from_errno2("fopen", path);
8366 goto done;
8369 err = histedit_parse_list(histedit_cmds, f, repo);
8370 done:
8371 if (f && fclose(f) != 0 && err == NULL)
8372 err = got_error_from_errno("fclose");
8373 return err;
8376 static const struct got_error *
8377 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
8378 const struct got_error *edit_err, struct got_object_id_queue *commits,
8379 const char *path, const char *branch_name, struct got_repository *repo)
8381 const struct got_error *err = NULL, *prev_err = edit_err;
8382 int resp = ' ';
8384 while (resp != 'c' && resp != 'r' && resp != 'a') {
8385 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
8386 "or (a)bort: ", getprogname(), prev_err->msg);
8387 resp = getchar();
8388 if (resp == '\n')
8389 resp = getchar();
8390 if (resp == 'c') {
8391 histedit_free_list(histedit_cmds);
8392 err = histedit_run_editor(histedit_cmds, path, commits,
8393 repo);
8394 if (err) {
8395 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8396 err->code != GOT_ERR_HISTEDIT_CMD)
8397 break;
8398 prev_err = err;
8399 resp = ' ';
8400 continue;
8402 break;
8403 } else if (resp == 'r') {
8404 histedit_free_list(histedit_cmds);
8405 err = histedit_edit_script(histedit_cmds,
8406 commits, branch_name, 0, repo);
8407 if (err) {
8408 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8409 err->code != GOT_ERR_HISTEDIT_CMD)
8410 break;
8411 prev_err = err;
8412 resp = ' ';
8413 continue;
8415 break;
8416 } else if (resp == 'a') {
8417 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
8418 break;
8419 } else
8420 printf("invalid response '%c'\n", resp);
8423 return err;
8426 static const struct got_error *
8427 histedit_complete(struct got_worktree *worktree,
8428 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
8429 struct got_reference *branch, struct got_repository *repo)
8431 printf("Switching work tree to %s\n",
8432 got_ref_get_symref_target(branch));
8433 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
8434 branch, repo);
8437 static const struct got_error *
8438 show_histedit_progress(struct got_commit_object *commit,
8439 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
8441 const struct got_error *err;
8442 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8444 err = got_object_id_str(&old_id_str, hle->commit_id);
8445 if (err)
8446 goto done;
8448 if (new_id) {
8449 err = got_object_id_str(&new_id_str, new_id);
8450 if (err)
8451 goto done;
8454 old_id_str[12] = '\0';
8455 if (new_id_str)
8456 new_id_str[12] = '\0';
8458 if (hle->logmsg) {
8459 logmsg = strdup(hle->logmsg);
8460 if (logmsg == NULL) {
8461 err = got_error_from_errno("strdup");
8462 goto done;
8464 trim_logmsg(logmsg, 42);
8465 } else {
8466 err = get_short_logmsg(&logmsg, 42, commit);
8467 if (err)
8468 goto done;
8471 switch (hle->cmd->code) {
8472 case GOT_HISTEDIT_PICK:
8473 case GOT_HISTEDIT_EDIT:
8474 printf("%s -> %s: %s\n", old_id_str,
8475 new_id_str ? new_id_str : "no-op change", logmsg);
8476 break;
8477 case GOT_HISTEDIT_DROP:
8478 case GOT_HISTEDIT_FOLD:
8479 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
8480 logmsg);
8481 break;
8482 default:
8483 break;
8485 done:
8486 free(old_id_str);
8487 free(new_id_str);
8488 return err;
8491 static const struct got_error *
8492 histedit_commit(struct got_pathlist_head *merged_paths,
8493 struct got_worktree *worktree, struct got_fileindex *fileindex,
8494 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
8495 struct got_repository *repo)
8497 const struct got_error *err;
8498 struct got_commit_object *commit;
8499 struct got_object_id *new_commit_id;
8501 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
8502 && hle->logmsg == NULL) {
8503 err = histedit_edit_logmsg(hle, repo);
8504 if (err)
8505 return err;
8508 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8509 if (err)
8510 return err;
8512 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
8513 worktree, fileindex, tmp_branch, commit, hle->commit_id,
8514 hle->logmsg, repo);
8515 if (err) {
8516 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
8517 goto done;
8518 err = show_histedit_progress(commit, hle, NULL);
8519 } else {
8520 err = show_histedit_progress(commit, hle, new_commit_id);
8521 free(new_commit_id);
8523 done:
8524 got_object_commit_close(commit);
8525 return err;
8528 static const struct got_error *
8529 histedit_skip_commit(struct got_histedit_list_entry *hle,
8530 struct got_worktree *worktree, struct got_repository *repo)
8532 const struct got_error *error;
8533 struct got_commit_object *commit;
8535 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
8536 repo);
8537 if (error)
8538 return error;
8540 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
8541 if (error)
8542 return error;
8544 error = show_histedit_progress(commit, hle, NULL);
8545 got_object_commit_close(commit);
8546 return error;
8549 static const struct got_error *
8550 check_local_changes(void *arg, unsigned char status,
8551 unsigned char staged_status, const char *path,
8552 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8553 struct got_object_id *commit_id, int dirfd, const char *de_name)
8555 int *have_local_changes = arg;
8557 switch (status) {
8558 case GOT_STATUS_ADD:
8559 case GOT_STATUS_DELETE:
8560 case GOT_STATUS_MODIFY:
8561 case GOT_STATUS_CONFLICT:
8562 *have_local_changes = 1;
8563 return got_error(GOT_ERR_CANCELLED);
8564 default:
8565 break;
8568 switch (staged_status) {
8569 case GOT_STATUS_ADD:
8570 case GOT_STATUS_DELETE:
8571 case GOT_STATUS_MODIFY:
8572 *have_local_changes = 1;
8573 return got_error(GOT_ERR_CANCELLED);
8574 default:
8575 break;
8578 return NULL;
8581 static const struct got_error *
8582 cmd_histedit(int argc, char *argv[])
8584 const struct got_error *error = NULL;
8585 struct got_worktree *worktree = NULL;
8586 struct got_fileindex *fileindex = NULL;
8587 struct got_repository *repo = NULL;
8588 char *cwd = NULL;
8589 struct got_reference *branch = NULL;
8590 struct got_reference *tmp_branch = NULL;
8591 struct got_object_id *resume_commit_id = NULL;
8592 struct got_object_id *base_commit_id = NULL;
8593 struct got_object_id *head_commit_id = NULL;
8594 struct got_commit_object *commit = NULL;
8595 int ch, rebase_in_progress = 0;
8596 struct got_update_progress_arg upa;
8597 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8598 int edit_logmsg_only = 0;
8599 const char *edit_script_path = NULL;
8600 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8601 struct got_object_id_queue commits;
8602 struct got_pathlist_head merged_paths;
8603 const struct got_object_id_queue *parent_ids;
8604 struct got_object_qid *pid;
8605 struct got_histedit_list histedit_cmds;
8606 struct got_histedit_list_entry *hle;
8608 SIMPLEQ_INIT(&commits);
8609 TAILQ_INIT(&histedit_cmds);
8610 TAILQ_INIT(&merged_paths);
8611 memset(&upa, 0, sizeof(upa));
8613 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
8614 switch (ch) {
8615 case 'a':
8616 abort_edit = 1;
8617 break;
8618 case 'c':
8619 continue_edit = 1;
8620 break;
8621 case 'F':
8622 edit_script_path = optarg;
8623 break;
8624 case 'm':
8625 edit_logmsg_only = 1;
8626 break;
8627 default:
8628 usage_histedit();
8629 /* NOTREACHED */
8633 argc -= optind;
8634 argv += optind;
8636 #ifndef PROFILE
8637 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8638 "unveil", NULL) == -1)
8639 err(1, "pledge");
8640 #endif
8641 if (abort_edit && continue_edit)
8642 errx(1, "histedit's -a and -c options are mutually exclusive");
8643 if (edit_script_path && edit_logmsg_only)
8644 errx(1, "histedit's -F and -m options are mutually exclusive");
8645 if (abort_edit && edit_logmsg_only)
8646 errx(1, "histedit's -a and -m options are mutually exclusive");
8647 if (continue_edit && edit_logmsg_only)
8648 errx(1, "histedit's -c and -m options are mutually exclusive");
8649 if (argc != 0)
8650 usage_histedit();
8653 * This command cannot apply unveil(2) in all cases because the
8654 * user may choose to run an editor to edit the histedit script
8655 * and to edit individual commit log messages.
8656 * unveil(2) traverses exec(2); if an editor is used we have to
8657 * apply unveil after edit script and log messages have been written.
8658 * XXX TODO: Make use of unveil(2) where possible.
8661 cwd = getcwd(NULL, 0);
8662 if (cwd == NULL) {
8663 error = got_error_from_errno("getcwd");
8664 goto done;
8666 error = got_worktree_open(&worktree, cwd);
8667 if (error) {
8668 if (error->code == GOT_ERR_NOT_WORKTREE)
8669 error = wrap_not_worktree_error(error, "histedit", cwd);
8670 goto done;
8673 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8674 NULL);
8675 if (error != NULL)
8676 goto done;
8678 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8679 if (error)
8680 goto done;
8681 if (rebase_in_progress) {
8682 error = got_error(GOT_ERR_REBASING);
8683 goto done;
8686 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8687 if (error)
8688 goto done;
8690 if (edit_in_progress && edit_logmsg_only) {
8691 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8692 "histedit operation is in progress in this "
8693 "work tree and must be continued or aborted "
8694 "before the -m option can be used");
8695 goto done;
8698 if (edit_in_progress && abort_edit) {
8699 error = got_worktree_histedit_continue(&resume_commit_id,
8700 &tmp_branch, &branch, &base_commit_id, &fileindex,
8701 worktree, repo);
8702 if (error)
8703 goto done;
8704 printf("Switching work tree to %s\n",
8705 got_ref_get_symref_target(branch));
8706 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8707 branch, base_commit_id, update_progress, &upa);
8708 if (error)
8709 goto done;
8710 printf("Histedit of %s aborted\n",
8711 got_ref_get_symref_target(branch));
8712 print_update_progress_stats(&upa);
8713 goto done; /* nothing else to do */
8714 } else if (abort_edit) {
8715 error = got_error(GOT_ERR_NOT_HISTEDIT);
8716 goto done;
8719 if (continue_edit) {
8720 char *path;
8722 if (!edit_in_progress) {
8723 error = got_error(GOT_ERR_NOT_HISTEDIT);
8724 goto done;
8727 error = got_worktree_get_histedit_script_path(&path, worktree);
8728 if (error)
8729 goto done;
8731 error = histedit_load_list(&histedit_cmds, path, repo);
8732 free(path);
8733 if (error)
8734 goto done;
8736 error = got_worktree_histedit_continue(&resume_commit_id,
8737 &tmp_branch, &branch, &base_commit_id, &fileindex,
8738 worktree, repo);
8739 if (error)
8740 goto done;
8742 error = got_ref_resolve(&head_commit_id, repo, branch);
8743 if (error)
8744 goto done;
8746 error = got_object_open_as_commit(&commit, repo,
8747 head_commit_id);
8748 if (error)
8749 goto done;
8750 parent_ids = got_object_commit_get_parent_ids(commit);
8751 pid = SIMPLEQ_FIRST(parent_ids);
8752 if (pid == NULL) {
8753 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8754 goto done;
8756 error = collect_commits(&commits, head_commit_id, pid->id,
8757 base_commit_id, got_worktree_get_path_prefix(worktree),
8758 GOT_ERR_HISTEDIT_PATH, repo);
8759 got_object_commit_close(commit);
8760 commit = NULL;
8761 if (error)
8762 goto done;
8763 } else {
8764 if (edit_in_progress) {
8765 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8766 goto done;
8769 error = got_ref_open(&branch, repo,
8770 got_worktree_get_head_ref_name(worktree), 0);
8771 if (error != NULL)
8772 goto done;
8774 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8775 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8776 "will not edit commit history of a branch outside "
8777 "the \"refs/heads/\" reference namespace");
8778 goto done;
8781 error = got_ref_resolve(&head_commit_id, repo, branch);
8782 got_ref_close(branch);
8783 branch = NULL;
8784 if (error)
8785 goto done;
8787 error = got_object_open_as_commit(&commit, repo,
8788 head_commit_id);
8789 if (error)
8790 goto done;
8791 parent_ids = got_object_commit_get_parent_ids(commit);
8792 pid = SIMPLEQ_FIRST(parent_ids);
8793 if (pid == NULL) {
8794 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8795 goto done;
8797 error = collect_commits(&commits, head_commit_id, pid->id,
8798 got_worktree_get_base_commit_id(worktree),
8799 got_worktree_get_path_prefix(worktree),
8800 GOT_ERR_HISTEDIT_PATH, repo);
8801 got_object_commit_close(commit);
8802 commit = NULL;
8803 if (error)
8804 goto done;
8806 if (SIMPLEQ_EMPTY(&commits)) {
8807 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8808 goto done;
8811 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8812 &base_commit_id, &fileindex, worktree, repo);
8813 if (error)
8814 goto done;
8816 if (edit_script_path) {
8817 error = histedit_load_list(&histedit_cmds,
8818 edit_script_path, repo);
8819 if (error) {
8820 got_worktree_histedit_abort(worktree, fileindex,
8821 repo, branch, base_commit_id,
8822 update_progress, &upa);
8823 print_update_progress_stats(&upa);
8824 goto done;
8826 } else {
8827 const char *branch_name;
8828 branch_name = got_ref_get_symref_target(branch);
8829 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8830 branch_name += 11;
8831 error = histedit_edit_script(&histedit_cmds, &commits,
8832 branch_name, edit_logmsg_only, repo);
8833 if (error) {
8834 got_worktree_histedit_abort(worktree, fileindex,
8835 repo, branch, base_commit_id,
8836 update_progress, &upa);
8837 print_update_progress_stats(&upa);
8838 goto done;
8843 error = histedit_save_list(&histedit_cmds, worktree,
8844 repo);
8845 if (error) {
8846 got_worktree_histedit_abort(worktree, fileindex,
8847 repo, branch, base_commit_id,
8848 update_progress, &upa);
8849 print_update_progress_stats(&upa);
8850 goto done;
8855 error = histedit_check_script(&histedit_cmds, &commits, repo);
8856 if (error)
8857 goto done;
8859 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8860 if (resume_commit_id) {
8861 if (got_object_id_cmp(hle->commit_id,
8862 resume_commit_id) != 0)
8863 continue;
8865 resume_commit_id = NULL;
8866 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8867 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8868 error = histedit_skip_commit(hle, worktree,
8869 repo);
8870 if (error)
8871 goto done;
8872 } else {
8873 struct got_pathlist_head paths;
8874 int have_changes = 0;
8876 TAILQ_INIT(&paths);
8877 error = got_pathlist_append(&paths, "", NULL);
8878 if (error)
8879 goto done;
8880 error = got_worktree_status(worktree, &paths,
8881 repo, check_local_changes, &have_changes,
8882 check_cancelled, NULL);
8883 got_pathlist_free(&paths);
8884 if (error) {
8885 if (error->code != GOT_ERR_CANCELLED)
8886 goto done;
8887 if (sigint_received || sigpipe_received)
8888 goto done;
8890 if (have_changes) {
8891 error = histedit_commit(NULL, worktree,
8892 fileindex, tmp_branch, hle, repo);
8893 if (error)
8894 goto done;
8895 } else {
8896 error = got_object_open_as_commit(
8897 &commit, repo, hle->commit_id);
8898 if (error)
8899 goto done;
8900 error = show_histedit_progress(commit,
8901 hle, NULL);
8902 got_object_commit_close(commit);
8903 commit = NULL;
8904 if (error)
8905 goto done;
8908 continue;
8911 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8912 error = histedit_skip_commit(hle, worktree, repo);
8913 if (error)
8914 goto done;
8915 continue;
8918 error = got_object_open_as_commit(&commit, repo,
8919 hle->commit_id);
8920 if (error)
8921 goto done;
8922 parent_ids = got_object_commit_get_parent_ids(commit);
8923 pid = SIMPLEQ_FIRST(parent_ids);
8925 error = got_worktree_histedit_merge_files(&merged_paths,
8926 worktree, fileindex, pid->id, hle->commit_id, repo,
8927 update_progress, &upa, check_cancelled, NULL);
8928 if (error)
8929 goto done;
8930 got_object_commit_close(commit);
8931 commit = NULL;
8933 print_update_progress_stats(&upa);
8934 if (upa.conflicts > 0)
8935 rebase_status = GOT_STATUS_CONFLICT;
8937 if (rebase_status == GOT_STATUS_CONFLICT) {
8938 error = show_rebase_merge_conflict(hle->commit_id,
8939 repo);
8940 if (error)
8941 goto done;
8942 got_worktree_rebase_pathlist_free(&merged_paths);
8943 break;
8946 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8947 char *id_str;
8948 error = got_object_id_str(&id_str, hle->commit_id);
8949 if (error)
8950 goto done;
8951 printf("Stopping histedit for amending commit %s\n",
8952 id_str);
8953 free(id_str);
8954 got_worktree_rebase_pathlist_free(&merged_paths);
8955 error = got_worktree_histedit_postpone(worktree,
8956 fileindex);
8957 goto done;
8960 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8961 error = histedit_skip_commit(hle, worktree, repo);
8962 if (error)
8963 goto done;
8964 continue;
8967 error = histedit_commit(&merged_paths, worktree, fileindex,
8968 tmp_branch, hle, repo);
8969 got_worktree_rebase_pathlist_free(&merged_paths);
8970 if (error)
8971 goto done;
8974 if (rebase_status == GOT_STATUS_CONFLICT) {
8975 error = got_worktree_histedit_postpone(worktree, fileindex);
8976 if (error)
8977 goto done;
8978 error = got_error_msg(GOT_ERR_CONFLICTS,
8979 "conflicts must be resolved before histedit can continue");
8980 } else
8981 error = histedit_complete(worktree, fileindex, tmp_branch,
8982 branch, repo);
8983 done:
8984 got_object_id_queue_free(&commits);
8985 histedit_free_list(&histedit_cmds);
8986 free(head_commit_id);
8987 free(base_commit_id);
8988 free(resume_commit_id);
8989 if (commit)
8990 got_object_commit_close(commit);
8991 if (branch)
8992 got_ref_close(branch);
8993 if (tmp_branch)
8994 got_ref_close(tmp_branch);
8995 if (worktree)
8996 got_worktree_close(worktree);
8997 if (repo)
8998 got_repo_close(repo);
8999 return error;
9002 __dead static void
9003 usage_integrate(void)
9005 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
9006 exit(1);
9009 static const struct got_error *
9010 cmd_integrate(int argc, char *argv[])
9012 const struct got_error *error = NULL;
9013 struct got_repository *repo = NULL;
9014 struct got_worktree *worktree = NULL;
9015 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
9016 const char *branch_arg = NULL;
9017 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
9018 struct got_fileindex *fileindex = NULL;
9019 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
9020 int ch;
9021 struct got_update_progress_arg upa;
9023 while ((ch = getopt(argc, argv, "")) != -1) {
9024 switch (ch) {
9025 default:
9026 usage_integrate();
9027 /* NOTREACHED */
9031 argc -= optind;
9032 argv += optind;
9034 if (argc != 1)
9035 usage_integrate();
9036 branch_arg = argv[0];
9037 #ifndef PROFILE
9038 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9039 "unveil", NULL) == -1)
9040 err(1, "pledge");
9041 #endif
9042 cwd = getcwd(NULL, 0);
9043 if (cwd == NULL) {
9044 error = got_error_from_errno("getcwd");
9045 goto done;
9048 error = got_worktree_open(&worktree, cwd);
9049 if (error) {
9050 if (error->code == GOT_ERR_NOT_WORKTREE)
9051 error = wrap_not_worktree_error(error, "integrate",
9052 cwd);
9053 goto done;
9056 error = check_rebase_or_histedit_in_progress(worktree);
9057 if (error)
9058 goto done;
9060 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9061 NULL);
9062 if (error != NULL)
9063 goto done;
9065 error = apply_unveil(got_repo_get_path(repo), 0,
9066 got_worktree_get_root_path(worktree));
9067 if (error)
9068 goto done;
9070 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
9071 error = got_error_from_errno("asprintf");
9072 goto done;
9075 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
9076 &base_branch_ref, worktree, refname, repo);
9077 if (error)
9078 goto done;
9080 refname = strdup(got_ref_get_name(branch_ref));
9081 if (refname == NULL) {
9082 error = got_error_from_errno("strdup");
9083 got_worktree_integrate_abort(worktree, fileindex, repo,
9084 branch_ref, base_branch_ref);
9085 goto done;
9087 base_refname = strdup(got_ref_get_name(base_branch_ref));
9088 if (base_refname == NULL) {
9089 error = got_error_from_errno("strdup");
9090 got_worktree_integrate_abort(worktree, fileindex, repo,
9091 branch_ref, base_branch_ref);
9092 goto done;
9095 error = got_ref_resolve(&commit_id, repo, branch_ref);
9096 if (error)
9097 goto done;
9099 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
9100 if (error)
9101 goto done;
9103 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
9104 error = got_error_msg(GOT_ERR_SAME_BRANCH,
9105 "specified branch has already been integrated");
9106 got_worktree_integrate_abort(worktree, fileindex, repo,
9107 branch_ref, base_branch_ref);
9108 goto done;
9111 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
9112 if (error) {
9113 if (error->code == GOT_ERR_ANCESTRY)
9114 error = got_error(GOT_ERR_REBASE_REQUIRED);
9115 got_worktree_integrate_abort(worktree, fileindex, repo,
9116 branch_ref, base_branch_ref);
9117 goto done;
9120 memset(&upa, 0, sizeof(upa));
9121 error = got_worktree_integrate_continue(worktree, fileindex, repo,
9122 branch_ref, base_branch_ref, update_progress, &upa,
9123 check_cancelled, NULL);
9124 if (error)
9125 goto done;
9127 printf("Integrated %s into %s\n", refname, base_refname);
9128 print_update_progress_stats(&upa);
9129 done:
9130 if (repo)
9131 got_repo_close(repo);
9132 if (worktree)
9133 got_worktree_close(worktree);
9134 free(cwd);
9135 free(base_commit_id);
9136 free(commit_id);
9137 free(refname);
9138 free(base_refname);
9139 return error;
9142 __dead static void
9143 usage_stage(void)
9145 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
9146 "[-S] [file-path ...]\n",
9147 getprogname());
9148 exit(1);
9151 static const struct got_error *
9152 print_stage(void *arg, unsigned char status, unsigned char staged_status,
9153 const char *path, struct got_object_id *blob_id,
9154 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
9155 int dirfd, const char *de_name)
9157 const struct got_error *err = NULL;
9158 char *id_str = NULL;
9160 if (staged_status != GOT_STATUS_ADD &&
9161 staged_status != GOT_STATUS_MODIFY &&
9162 staged_status != GOT_STATUS_DELETE)
9163 return NULL;
9165 if (staged_status == GOT_STATUS_ADD ||
9166 staged_status == GOT_STATUS_MODIFY)
9167 err = got_object_id_str(&id_str, staged_blob_id);
9168 else
9169 err = got_object_id_str(&id_str, blob_id);
9170 if (err)
9171 return err;
9173 printf("%s %c %s\n", id_str, staged_status, path);
9174 free(id_str);
9175 return NULL;
9178 static const struct got_error *
9179 cmd_stage(int argc, char *argv[])
9181 const struct got_error *error = NULL;
9182 struct got_repository *repo = NULL;
9183 struct got_worktree *worktree = NULL;
9184 char *cwd = NULL;
9185 struct got_pathlist_head paths;
9186 struct got_pathlist_entry *pe;
9187 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
9188 FILE *patch_script_file = NULL;
9189 const char *patch_script_path = NULL;
9190 struct choose_patch_arg cpa;
9192 TAILQ_INIT(&paths);
9194 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
9195 switch (ch) {
9196 case 'l':
9197 list_stage = 1;
9198 break;
9199 case 'p':
9200 pflag = 1;
9201 break;
9202 case 'F':
9203 patch_script_path = optarg;
9204 break;
9205 case 'S':
9206 allow_bad_symlinks = 1;
9207 break;
9208 default:
9209 usage_stage();
9210 /* NOTREACHED */
9214 argc -= optind;
9215 argv += optind;
9217 #ifndef PROFILE
9218 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9219 "unveil", NULL) == -1)
9220 err(1, "pledge");
9221 #endif
9222 if (list_stage && (pflag || patch_script_path))
9223 errx(1, "-l option cannot be used with other options");
9224 if (patch_script_path && !pflag)
9225 errx(1, "-F option can only be used together with -p option");
9227 cwd = getcwd(NULL, 0);
9228 if (cwd == NULL) {
9229 error = got_error_from_errno("getcwd");
9230 goto done;
9233 error = got_worktree_open(&worktree, cwd);
9234 if (error) {
9235 if (error->code == GOT_ERR_NOT_WORKTREE)
9236 error = wrap_not_worktree_error(error, "stage", cwd);
9237 goto done;
9240 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9241 NULL);
9242 if (error != NULL)
9243 goto done;
9245 if (patch_script_path) {
9246 patch_script_file = fopen(patch_script_path, "r");
9247 if (patch_script_file == NULL) {
9248 error = got_error_from_errno2("fopen",
9249 patch_script_path);
9250 goto done;
9253 error = apply_unveil(got_repo_get_path(repo), 0,
9254 got_worktree_get_root_path(worktree));
9255 if (error)
9256 goto done;
9258 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9259 if (error)
9260 goto done;
9262 if (list_stage)
9263 error = got_worktree_status(worktree, &paths, repo,
9264 print_stage, NULL, check_cancelled, NULL);
9265 else {
9266 cpa.patch_script_file = patch_script_file;
9267 cpa.action = "stage";
9268 error = got_worktree_stage(worktree, &paths,
9269 pflag ? NULL : print_status, NULL,
9270 pflag ? choose_patch : NULL, &cpa,
9271 allow_bad_symlinks, repo);
9273 done:
9274 if (patch_script_file && fclose(patch_script_file) == EOF &&
9275 error == NULL)
9276 error = got_error_from_errno2("fclose", patch_script_path);
9277 if (repo)
9278 got_repo_close(repo);
9279 if (worktree)
9280 got_worktree_close(worktree);
9281 TAILQ_FOREACH(pe, &paths, entry)
9282 free((char *)pe->path);
9283 got_pathlist_free(&paths);
9284 free(cwd);
9285 return error;
9288 __dead static void
9289 usage_unstage(void)
9291 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
9292 "[file-path ...]\n",
9293 getprogname());
9294 exit(1);
9298 static const struct got_error *
9299 cmd_unstage(int argc, char *argv[])
9301 const struct got_error *error = NULL;
9302 struct got_repository *repo = NULL;
9303 struct got_worktree *worktree = NULL;
9304 char *cwd = NULL;
9305 struct got_pathlist_head paths;
9306 struct got_pathlist_entry *pe;
9307 int ch, pflag = 0;
9308 struct got_update_progress_arg upa;
9309 FILE *patch_script_file = NULL;
9310 const char *patch_script_path = NULL;
9311 struct choose_patch_arg cpa;
9313 TAILQ_INIT(&paths);
9315 while ((ch = getopt(argc, argv, "pF:")) != -1) {
9316 switch (ch) {
9317 case 'p':
9318 pflag = 1;
9319 break;
9320 case 'F':
9321 patch_script_path = optarg;
9322 break;
9323 default:
9324 usage_unstage();
9325 /* NOTREACHED */
9329 argc -= optind;
9330 argv += optind;
9332 #ifndef PROFILE
9333 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9334 "unveil", NULL) == -1)
9335 err(1, "pledge");
9336 #endif
9337 if (patch_script_path && !pflag)
9338 errx(1, "-F option can only be used together with -p option");
9340 cwd = getcwd(NULL, 0);
9341 if (cwd == NULL) {
9342 error = got_error_from_errno("getcwd");
9343 goto done;
9346 error = got_worktree_open(&worktree, cwd);
9347 if (error) {
9348 if (error->code == GOT_ERR_NOT_WORKTREE)
9349 error = wrap_not_worktree_error(error, "unstage", cwd);
9350 goto done;
9353 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9354 NULL);
9355 if (error != NULL)
9356 goto done;
9358 if (patch_script_path) {
9359 patch_script_file = fopen(patch_script_path, "r");
9360 if (patch_script_file == NULL) {
9361 error = got_error_from_errno2("fopen",
9362 patch_script_path);
9363 goto done;
9367 error = apply_unveil(got_repo_get_path(repo), 0,
9368 got_worktree_get_root_path(worktree));
9369 if (error)
9370 goto done;
9372 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9373 if (error)
9374 goto done;
9376 cpa.patch_script_file = patch_script_file;
9377 cpa.action = "unstage";
9378 memset(&upa, 0, sizeof(upa));
9379 error = got_worktree_unstage(worktree, &paths, update_progress,
9380 &upa, pflag ? choose_patch : NULL, &cpa, repo);
9381 if (!error)
9382 print_update_progress_stats(&upa);
9383 done:
9384 if (patch_script_file && fclose(patch_script_file) == EOF &&
9385 error == NULL)
9386 error = got_error_from_errno2("fclose", patch_script_path);
9387 if (repo)
9388 got_repo_close(repo);
9389 if (worktree)
9390 got_worktree_close(worktree);
9391 TAILQ_FOREACH(pe, &paths, entry)
9392 free((char *)pe->path);
9393 got_pathlist_free(&paths);
9394 free(cwd);
9395 return error;
9398 __dead static void
9399 usage_cat(void)
9401 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
9402 "arg1 [arg2 ...]\n", getprogname());
9403 exit(1);
9406 static const struct got_error *
9407 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9409 const struct got_error *err;
9410 struct got_blob_object *blob;
9412 err = got_object_open_as_blob(&blob, repo, id, 8192);
9413 if (err)
9414 return err;
9416 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
9417 got_object_blob_close(blob);
9418 return err;
9421 static const struct got_error *
9422 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9424 const struct got_error *err;
9425 struct got_tree_object *tree;
9426 int nentries, i;
9428 err = got_object_open_as_tree(&tree, repo, id);
9429 if (err)
9430 return err;
9432 nentries = got_object_tree_get_nentries(tree);
9433 for (i = 0; i < nentries; i++) {
9434 struct got_tree_entry *te;
9435 char *id_str;
9436 if (sigint_received || sigpipe_received)
9437 break;
9438 te = got_object_tree_get_entry(tree, i);
9439 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
9440 if (err)
9441 break;
9442 fprintf(outfile, "%s %.7o %s\n", id_str,
9443 got_tree_entry_get_mode(te),
9444 got_tree_entry_get_name(te));
9445 free(id_str);
9448 got_object_tree_close(tree);
9449 return err;
9452 static const struct got_error *
9453 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9455 const struct got_error *err;
9456 struct got_commit_object *commit;
9457 const struct got_object_id_queue *parent_ids;
9458 struct got_object_qid *pid;
9459 char *id_str = NULL;
9460 const char *logmsg = NULL;
9462 err = got_object_open_as_commit(&commit, repo, id);
9463 if (err)
9464 return err;
9466 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
9467 if (err)
9468 goto done;
9470 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
9471 parent_ids = got_object_commit_get_parent_ids(commit);
9472 fprintf(outfile, "numparents %d\n",
9473 got_object_commit_get_nparents(commit));
9474 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
9475 char *pid_str;
9476 err = got_object_id_str(&pid_str, pid->id);
9477 if (err)
9478 goto done;
9479 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
9480 free(pid_str);
9482 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
9483 got_object_commit_get_author(commit),
9484 got_object_commit_get_author_time(commit));
9486 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
9487 got_object_commit_get_author(commit),
9488 got_object_commit_get_committer_time(commit));
9490 logmsg = got_object_commit_get_logmsg_raw(commit);
9491 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
9492 fprintf(outfile, "%s", logmsg);
9493 done:
9494 free(id_str);
9495 got_object_commit_close(commit);
9496 return err;
9499 static const struct got_error *
9500 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9502 const struct got_error *err;
9503 struct got_tag_object *tag;
9504 char *id_str = NULL;
9505 const char *tagmsg = NULL;
9507 err = got_object_open_as_tag(&tag, repo, id);
9508 if (err)
9509 return err;
9511 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
9512 if (err)
9513 goto done;
9515 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
9517 switch (got_object_tag_get_object_type(tag)) {
9518 case GOT_OBJ_TYPE_BLOB:
9519 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9520 GOT_OBJ_LABEL_BLOB);
9521 break;
9522 case GOT_OBJ_TYPE_TREE:
9523 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9524 GOT_OBJ_LABEL_TREE);
9525 break;
9526 case GOT_OBJ_TYPE_COMMIT:
9527 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9528 GOT_OBJ_LABEL_COMMIT);
9529 break;
9530 case GOT_OBJ_TYPE_TAG:
9531 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9532 GOT_OBJ_LABEL_TAG);
9533 break;
9534 default:
9535 break;
9538 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
9539 got_object_tag_get_name(tag));
9541 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
9542 got_object_tag_get_tagger(tag),
9543 got_object_tag_get_tagger_time(tag));
9545 tagmsg = got_object_tag_get_message(tag);
9546 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
9547 fprintf(outfile, "%s", tagmsg);
9548 done:
9549 free(id_str);
9550 got_object_tag_close(tag);
9551 return err;
9554 static const struct got_error *
9555 cmd_cat(int argc, char *argv[])
9557 const struct got_error *error;
9558 struct got_repository *repo = NULL;
9559 struct got_worktree *worktree = NULL;
9560 char *cwd = NULL, *repo_path = NULL, *label = NULL;
9561 const char *commit_id_str = NULL;
9562 struct got_object_id *id = NULL, *commit_id = NULL;
9563 int ch, obj_type, i, force_path = 0;
9565 #ifndef PROFILE
9566 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9567 NULL) == -1)
9568 err(1, "pledge");
9569 #endif
9571 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
9572 switch (ch) {
9573 case 'c':
9574 commit_id_str = optarg;
9575 break;
9576 case 'r':
9577 repo_path = realpath(optarg, NULL);
9578 if (repo_path == NULL)
9579 return got_error_from_errno2("realpath",
9580 optarg);
9581 got_path_strip_trailing_slashes(repo_path);
9582 break;
9583 case 'P':
9584 force_path = 1;
9585 break;
9586 default:
9587 usage_cat();
9588 /* NOTREACHED */
9592 argc -= optind;
9593 argv += optind;
9595 cwd = getcwd(NULL, 0);
9596 if (cwd == NULL) {
9597 error = got_error_from_errno("getcwd");
9598 goto done;
9600 error = got_worktree_open(&worktree, cwd);
9601 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9602 goto done;
9603 if (worktree) {
9604 if (repo_path == NULL) {
9605 repo_path = strdup(
9606 got_worktree_get_repo_path(worktree));
9607 if (repo_path == NULL) {
9608 error = got_error_from_errno("strdup");
9609 goto done;
9614 if (repo_path == NULL) {
9615 repo_path = getcwd(NULL, 0);
9616 if (repo_path == NULL)
9617 return got_error_from_errno("getcwd");
9620 error = got_repo_open(&repo, repo_path, NULL);
9621 free(repo_path);
9622 if (error != NULL)
9623 goto done;
9625 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9626 if (error)
9627 goto done;
9629 if (commit_id_str == NULL)
9630 commit_id_str = GOT_REF_HEAD;
9631 error = got_repo_match_object_id(&commit_id, NULL,
9632 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
9633 if (error)
9634 goto done;
9636 for (i = 0; i < argc; i++) {
9637 if (force_path) {
9638 error = got_object_id_by_path(&id, repo, commit_id,
9639 argv[i]);
9640 if (error)
9641 break;
9642 } else {
9643 error = got_repo_match_object_id(&id, &label, argv[i],
9644 GOT_OBJ_TYPE_ANY, 0, repo);
9645 if (error) {
9646 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9647 error->code != GOT_ERR_NOT_REF)
9648 break;
9649 error = got_object_id_by_path(&id, repo,
9650 commit_id, argv[i]);
9651 if (error)
9652 break;
9656 error = got_object_get_type(&obj_type, repo, id);
9657 if (error)
9658 break;
9660 switch (obj_type) {
9661 case GOT_OBJ_TYPE_BLOB:
9662 error = cat_blob(id, repo, stdout);
9663 break;
9664 case GOT_OBJ_TYPE_TREE:
9665 error = cat_tree(id, repo, stdout);
9666 break;
9667 case GOT_OBJ_TYPE_COMMIT:
9668 error = cat_commit(id, repo, stdout);
9669 break;
9670 case GOT_OBJ_TYPE_TAG:
9671 error = cat_tag(id, repo, stdout);
9672 break;
9673 default:
9674 error = got_error(GOT_ERR_OBJ_TYPE);
9675 break;
9677 if (error)
9678 break;
9679 free(label);
9680 label = NULL;
9681 free(id);
9682 id = NULL;
9684 done:
9685 free(label);
9686 free(id);
9687 free(commit_id);
9688 if (worktree)
9689 got_worktree_close(worktree);
9690 if (repo) {
9691 const struct got_error *repo_error;
9692 repo_error = got_repo_close(repo);
9693 if (error == NULL)
9694 error = repo_error;
9696 return error;
9699 __dead static void
9700 usage_info(void)
9702 fprintf(stderr, "usage: %s info [path ...]\n",
9703 getprogname());
9704 exit(1);
9707 static const struct got_error *
9708 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
9709 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9710 struct got_object_id *commit_id)
9712 const struct got_error *err = NULL;
9713 char *id_str = NULL;
9714 char datebuf[128];
9715 struct tm mytm, *tm;
9716 struct got_pathlist_head *paths = arg;
9717 struct got_pathlist_entry *pe;
9720 * Clear error indication from any of the path arguments which
9721 * would cause this file index entry to be displayed.
9723 TAILQ_FOREACH(pe, paths, entry) {
9724 if (got_path_cmp(path, pe->path, strlen(path),
9725 pe->path_len) == 0 ||
9726 got_path_is_child(path, pe->path, pe->path_len))
9727 pe->data = NULL; /* no error */
9730 printf(GOT_COMMIT_SEP_STR);
9731 if (S_ISLNK(mode))
9732 printf("symlink: %s\n", path);
9733 else if (S_ISREG(mode)) {
9734 printf("file: %s\n", path);
9735 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
9736 } else if (S_ISDIR(mode))
9737 printf("directory: %s\n", path);
9738 else
9739 printf("something: %s\n", path);
9741 tm = localtime_r(&mtime, &mytm);
9742 if (tm == NULL)
9743 return NULL;
9744 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) >= sizeof(datebuf))
9745 return got_error(GOT_ERR_NO_SPACE);
9746 printf("timestamp: %s\n", datebuf);
9748 if (blob_id) {
9749 err = got_object_id_str(&id_str, blob_id);
9750 if (err)
9751 return err;
9752 printf("based on blob: %s\n", id_str);
9753 free(id_str);
9756 if (staged_blob_id) {
9757 err = got_object_id_str(&id_str, staged_blob_id);
9758 if (err)
9759 return err;
9760 printf("based on staged blob: %s\n", id_str);
9761 free(id_str);
9764 if (commit_id) {
9765 err = got_object_id_str(&id_str, commit_id);
9766 if (err)
9767 return err;
9768 printf("based on commit: %s\n", id_str);
9769 free(id_str);
9772 return NULL;
9775 static const struct got_error *
9776 cmd_info(int argc, char *argv[])
9778 const struct got_error *error = NULL;
9779 struct got_worktree *worktree = NULL;
9780 char *cwd = NULL, *id_str = NULL;
9781 struct got_pathlist_head paths;
9782 struct got_pathlist_entry *pe;
9783 char *uuidstr = NULL;
9784 int ch, show_files = 0;
9786 TAILQ_INIT(&paths);
9788 while ((ch = getopt(argc, argv, "")) != -1) {
9789 switch (ch) {
9790 default:
9791 usage_info();
9792 /* NOTREACHED */
9796 argc -= optind;
9797 argv += optind;
9799 #ifndef PROFILE
9800 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
9801 NULL) == -1)
9802 err(1, "pledge");
9803 #endif
9804 cwd = getcwd(NULL, 0);
9805 if (cwd == NULL) {
9806 error = got_error_from_errno("getcwd");
9807 goto done;
9810 error = got_worktree_open(&worktree, cwd);
9811 if (error) {
9812 if (error->code == GOT_ERR_NOT_WORKTREE)
9813 error = wrap_not_worktree_error(error, "status", cwd);
9814 goto done;
9817 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9818 if (error)
9819 goto done;
9821 if (argc >= 1) {
9822 error = get_worktree_paths_from_argv(&paths, argc, argv,
9823 worktree);
9824 if (error)
9825 goto done;
9826 show_files = 1;
9829 error = got_object_id_str(&id_str,
9830 got_worktree_get_base_commit_id(worktree));
9831 if (error)
9832 goto done;
9834 error = got_worktree_get_uuid(&uuidstr, worktree);
9835 if (error)
9836 goto done;
9838 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9839 printf("work tree base commit: %s\n", id_str);
9840 printf("work tree path prefix: %s\n",
9841 got_worktree_get_path_prefix(worktree));
9842 printf("work tree branch reference: %s\n",
9843 got_worktree_get_head_ref_name(worktree));
9844 printf("work tree UUID: %s\n", uuidstr);
9845 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
9847 if (show_files) {
9848 struct got_pathlist_entry *pe;
9849 TAILQ_FOREACH(pe, &paths, entry) {
9850 if (pe->path_len == 0)
9851 continue;
9853 * Assume this path will fail. This will be corrected
9854 * in print_path_info() in case the path does suceeed.
9856 pe->data = (void *)got_error_path(pe->path,
9857 GOT_ERR_BAD_PATH);
9859 error = got_worktree_path_info(worktree, &paths,
9860 print_path_info, &paths, check_cancelled, NULL);
9861 if (error)
9862 goto done;
9863 TAILQ_FOREACH(pe, &paths, entry) {
9864 if (pe->data != NULL) {
9865 error = pe->data; /* bad path */
9866 break;
9870 done:
9871 TAILQ_FOREACH(pe, &paths, entry)
9872 free((char *)pe->path);
9873 got_pathlist_free(&paths);
9874 free(cwd);
9875 free(id_str);
9876 free(uuidstr);
9877 return error;