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 = 1;
217 optreset = 1;
219 if (Vflag) {
220 got_version_print_str();
221 return 1;
224 if (argc <= 0)
225 usage(hflag);
227 signal(SIGINT, catch_sigint);
228 signal(SIGPIPE, catch_sigpipe);
230 for (i = 0; i < nitems(got_commands); i++) {
231 const struct got_error *error;
233 cmd = &got_commands[i];
235 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
236 strcmp(cmd->cmd_alias, argv[0]) != 0)
237 continue;
239 if (hflag)
240 got_commands[i].cmd_usage();
242 error = got_commands[i].cmd_main(argc, argv);
243 if (error && error->code != GOT_ERR_CANCELLED &&
244 error->code != GOT_ERR_PRIVSEP_EXIT &&
245 !(sigpipe_received &&
246 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
247 !(sigint_received &&
248 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
249 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
250 return 1;
253 return 0;
256 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
257 list_commands();
258 return 1;
261 __dead static void
262 usage(int hflag)
264 fprintf(stderr, "usage: %s [-h] [-V | --version] command [arg ...]\n",
265 getprogname());
266 if (hflag)
267 list_commands();
268 exit(1);
271 static const struct got_error *
272 get_editor(char **abspath)
274 const struct got_error *err = NULL;
275 const char *editor;
277 *abspath = NULL;
279 editor = getenv("VISUAL");
280 if (editor == NULL)
281 editor = getenv("EDITOR");
283 if (editor) {
284 err = got_path_find_prog(abspath, editor);
285 if (err)
286 return err;
289 if (*abspath == NULL) {
290 *abspath = strdup("/bin/ed");
291 if (*abspath == NULL)
292 return got_error_from_errno("strdup");
295 return NULL;
298 static const struct got_error *
299 apply_unveil(const char *repo_path, int repo_read_only,
300 const char *worktree_path)
302 const struct got_error *err;
304 #ifdef PROFILE
305 if (unveil("gmon.out", "rwc") != 0)
306 return got_error_from_errno2("unveil", "gmon.out");
307 #endif
308 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
309 return got_error_from_errno2("unveil", repo_path);
311 if (worktree_path && unveil(worktree_path, "rwc") != 0)
312 return got_error_from_errno2("unveil", worktree_path);
314 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
315 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
317 err = got_privsep_unveil_exec_helpers();
318 if (err != NULL)
319 return err;
321 if (unveil(NULL, NULL) != 0)
322 return got_error_from_errno("unveil");
324 return NULL;
327 __dead static void
328 usage_init(void)
330 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
331 exit(1);
334 static const struct got_error *
335 cmd_init(int argc, char *argv[])
337 const struct got_error *error = NULL;
338 char *repo_path = NULL;
339 int ch;
341 while ((ch = getopt(argc, argv, "")) != -1) {
342 switch (ch) {
343 default:
344 usage_init();
345 /* NOTREACHED */
349 argc -= optind;
350 argv += optind;
352 #ifndef PROFILE
353 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
354 err(1, "pledge");
355 #endif
356 if (argc != 1)
357 usage_init();
359 repo_path = strdup(argv[0]);
360 if (repo_path == NULL)
361 return got_error_from_errno("strdup");
363 got_path_strip_trailing_slashes(repo_path);
365 error = got_path_mkdir(repo_path);
366 if (error &&
367 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
368 goto done;
370 error = apply_unveil(repo_path, 0, NULL);
371 if (error)
372 goto done;
374 error = got_repo_init(repo_path);
375 done:
376 free(repo_path);
377 return error;
380 __dead static void
381 usage_import(void)
383 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
384 "[-r repository-path] [-I pattern] path\n", getprogname());
385 exit(1);
388 int
389 spawn_editor(const char *editor, const char *file)
391 pid_t pid;
392 sig_t sighup, sigint, sigquit;
393 int st = -1;
395 sighup = signal(SIGHUP, SIG_IGN);
396 sigint = signal(SIGINT, SIG_IGN);
397 sigquit = signal(SIGQUIT, SIG_IGN);
399 switch (pid = fork()) {
400 case -1:
401 goto doneediting;
402 case 0:
403 execl(editor, editor, file, (char *)NULL);
404 _exit(127);
407 while (waitpid(pid, &st, 0) == -1)
408 if (errno != EINTR)
409 break;
411 doneediting:
412 (void)signal(SIGHUP, sighup);
413 (void)signal(SIGINT, sigint);
414 (void)signal(SIGQUIT, sigquit);
416 if (!WIFEXITED(st)) {
417 errno = EINTR;
418 return -1;
421 return WEXITSTATUS(st);
424 static const struct got_error *
425 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
426 const char *initial_content, size_t initial_content_len)
428 const struct got_error *err = NULL;
429 char *line = NULL;
430 size_t linesize = 0;
431 ssize_t linelen;
432 struct stat st, st2;
433 FILE *fp = NULL;
434 size_t len, logmsg_len;
435 char *initial_content_stripped = NULL, *buf = NULL, *s;
437 *logmsg = NULL;
439 if (stat(logmsg_path, &st) == -1)
440 return got_error_from_errno2("stat", logmsg_path);
442 if (spawn_editor(editor, logmsg_path) == -1)
443 return got_error_from_errno("failed spawning editor");
445 if (stat(logmsg_path, &st2) == -1)
446 return got_error_from_errno("stat");
448 if (st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
449 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
450 "no changes made to commit message, aborting");
452 /*
453 * Set up a stripped version of the initial content without comments
454 * and blank lines. We need this in order to check if the message
455 * has in fact been edited.
456 */
457 initial_content_stripped = malloc(initial_content_len + 1);
458 if (initial_content_stripped == NULL)
459 return got_error_from_errno("malloc");
460 initial_content_stripped[0] = '\0';
462 buf = strdup(initial_content);
463 if (buf == NULL) {
464 err = got_error_from_errno("strdup");
465 goto done;
467 s = buf;
468 len = 0;
469 while ((line = strsep(&s, "\n")) != NULL) {
470 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
471 continue; /* remove comments and leading empty lines */
472 len = strlcat(initial_content_stripped, line,
473 initial_content_len + 1);
474 if (len >= initial_content_len + 1) {
475 err = got_error(GOT_ERR_NO_SPACE);
476 goto done;
479 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
480 initial_content_stripped[len - 1] = '\0';
481 len--;
484 logmsg_len = st2.st_size;
485 *logmsg = malloc(logmsg_len + 1);
486 if (*logmsg == NULL)
487 return got_error_from_errno("malloc");
488 (*logmsg)[0] = '\0';
490 fp = fopen(logmsg_path, "r");
491 if (fp == NULL) {
492 err = got_error_from_errno("fopen");
493 goto done;
496 len = 0;
497 while ((linelen = getline(&line, &linesize, fp)) != -1) {
498 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
499 continue; /* remove comments and leading empty lines */
500 len = strlcat(*logmsg, line, logmsg_len + 1);
501 if (len >= logmsg_len + 1) {
502 err = got_error(GOT_ERR_NO_SPACE);
503 goto done;
506 free(line);
507 if (ferror(fp)) {
508 err = got_ferror(fp, GOT_ERR_IO);
509 goto done;
511 while (len > 0 && (*logmsg)[len - 1] == '\n') {
512 (*logmsg)[len - 1] = '\0';
513 len--;
516 if (len == 0) {
517 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
518 "commit message cannot be empty, aborting");
519 goto done;
521 if (strcmp(*logmsg, initial_content_stripped) == 0)
522 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
523 "no changes made to commit message, aborting");
524 done:
525 free(initial_content_stripped);
526 free(buf);
527 if (fp && fclose(fp) == EOF && err == NULL)
528 err = got_error_from_errno("fclose");
529 if (err) {
530 free(*logmsg);
531 *logmsg = NULL;
533 return err;
536 static const struct got_error *
537 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
538 const char *path_dir, const char *branch_name)
540 char *initial_content = NULL;
541 const struct got_error *err = NULL;
542 int initial_content_len;
543 int fd = -1;
545 initial_content_len = asprintf(&initial_content,
546 "\n# %s to be imported to branch %s\n", path_dir,
547 branch_name);
548 if (initial_content_len == -1)
549 return got_error_from_errno("asprintf");
551 err = got_opentemp_named_fd(logmsg_path, &fd,
552 GOT_TMPDIR_STR "/got-importmsg");
553 if (err)
554 goto done;
556 if (write(fd, initial_content, initial_content_len) == -1) {
557 err = got_error_from_errno2("write", *logmsg_path);
558 goto done;
561 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
562 initial_content_len);
563 done:
564 if (fd != -1 && close(fd) == -1 && err == NULL)
565 err = got_error_from_errno2("close", *logmsg_path);
566 free(initial_content);
567 if (err) {
568 free(*logmsg_path);
569 *logmsg_path = NULL;
571 return err;
574 static const struct got_error *
575 import_progress(void *arg, const char *path)
577 printf("A %s\n", path);
578 return NULL;
581 static const struct got_error *
582 get_author(char **author, struct got_repository *repo,
583 struct got_worktree *worktree)
585 const struct got_error *err = NULL;
586 const char *got_author = NULL, *name, *email;
587 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
589 *author = NULL;
591 if (worktree)
592 worktree_conf = got_worktree_get_gotconfig(worktree);
593 repo_conf = got_repo_get_gotconfig(repo);
595 /*
596 * Priority of potential author information sources, from most
597 * significant to least significant:
598 * 1) work tree's .got/got.conf file
599 * 2) repository's got.conf file
600 * 3) repository's git config file
601 * 4) environment variables
602 * 5) global git config files (in user's home directory or /etc)
603 */
605 if (worktree_conf)
606 got_author = got_gotconfig_get_author(worktree_conf);
607 if (got_author == NULL)
608 got_author = got_gotconfig_get_author(repo_conf);
609 if (got_author == NULL) {
610 name = got_repo_get_gitconfig_author_name(repo);
611 email = got_repo_get_gitconfig_author_email(repo);
612 if (name && email) {
613 if (asprintf(author, "%s <%s>", name, email) == -1)
614 return got_error_from_errno("asprintf");
615 return NULL;
618 got_author = getenv("GOT_AUTHOR");
619 if (got_author == NULL) {
620 name = got_repo_get_global_gitconfig_author_name(repo);
621 email = got_repo_get_global_gitconfig_author_email(
622 repo);
623 if (name && email) {
624 if (asprintf(author, "%s <%s>", name, email)
625 == -1)
626 return got_error_from_errno("asprintf");
627 return NULL;
629 /* TODO: Look up user in password database? */
630 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
634 *author = strdup(got_author);
635 if (*author == NULL)
636 return got_error_from_errno("strdup");
638 /*
639 * Really dumb email address check; we're only doing this to
640 * avoid git's object parser breaking on commits we create.
641 */
642 while (*got_author && *got_author != '<')
643 got_author++;
644 if (*got_author != '<') {
645 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
646 goto done;
648 while (*got_author && *got_author != '@')
649 got_author++;
650 if (*got_author != '@') {
651 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
652 goto done;
654 while (*got_author && *got_author != '>')
655 got_author++;
656 if (*got_author != '>')
657 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
658 done:
659 if (err) {
660 free(*author);
661 *author = NULL;
663 return err;
666 static const struct got_error *
667 get_gitconfig_path(char **gitconfig_path)
669 const char *homedir = getenv("HOME");
671 *gitconfig_path = NULL;
672 if (homedir) {
673 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
674 return got_error_from_errno("asprintf");
677 return NULL;
680 static const struct got_error *
681 cmd_import(int argc, char *argv[])
683 const struct got_error *error = NULL;
684 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
685 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
686 const char *branch_name = "main";
687 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
688 struct got_repository *repo = NULL;
689 struct got_reference *branch_ref = NULL, *head_ref = NULL;
690 struct got_object_id *new_commit_id = NULL;
691 int ch;
692 struct got_pathlist_head ignores;
693 struct got_pathlist_entry *pe;
694 int preserve_logmsg = 0;
696 TAILQ_INIT(&ignores);
698 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
699 switch (ch) {
700 case 'b':
701 branch_name = optarg;
702 break;
703 case 'm':
704 logmsg = strdup(optarg);
705 if (logmsg == NULL) {
706 error = got_error_from_errno("strdup");
707 goto done;
709 break;
710 case 'r':
711 repo_path = realpath(optarg, NULL);
712 if (repo_path == NULL) {
713 error = got_error_from_errno2("realpath",
714 optarg);
715 goto done;
717 break;
718 case 'I':
719 if (optarg[0] == '\0')
720 break;
721 error = got_pathlist_insert(&pe, &ignores, optarg,
722 NULL);
723 if (error)
724 goto done;
725 break;
726 default:
727 usage_import();
728 /* NOTREACHED */
732 argc -= optind;
733 argv += optind;
735 #ifndef PROFILE
736 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
737 "unveil",
738 NULL) == -1)
739 err(1, "pledge");
740 #endif
741 if (argc != 1)
742 usage_import();
744 if (repo_path == NULL) {
745 repo_path = getcwd(NULL, 0);
746 if (repo_path == NULL)
747 return got_error_from_errno("getcwd");
749 got_path_strip_trailing_slashes(repo_path);
750 error = get_gitconfig_path(&gitconfig_path);
751 if (error)
752 goto done;
753 error = got_repo_open(&repo, repo_path, gitconfig_path);
754 if (error)
755 goto done;
757 error = get_author(&author, repo, NULL);
758 if (error)
759 return error;
761 /*
762 * Don't let the user create a branch name with a leading '-'.
763 * While technically a valid reference name, this case is usually
764 * an unintended typo.
765 */
766 if (branch_name[0] == '-')
767 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
769 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
770 error = got_error_from_errno("asprintf");
771 goto done;
774 error = got_ref_open(&branch_ref, repo, refname, 0);
775 if (error) {
776 if (error->code != GOT_ERR_NOT_REF)
777 goto done;
778 } else {
779 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
780 "import target branch already exists");
781 goto done;
784 path_dir = realpath(argv[0], NULL);
785 if (path_dir == NULL) {
786 error = got_error_from_errno2("realpath", argv[0]);
787 goto done;
789 got_path_strip_trailing_slashes(path_dir);
791 /*
792 * unveil(2) traverses exec(2); if an editor is used we have
793 * to apply unveil after the log message has been written.
794 */
795 if (logmsg == NULL || strlen(logmsg) == 0) {
796 error = get_editor(&editor);
797 if (error)
798 goto done;
799 free(logmsg);
800 error = collect_import_msg(&logmsg, &logmsg_path, editor,
801 path_dir, refname);
802 if (error) {
803 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
804 logmsg_path != NULL)
805 preserve_logmsg = 1;
806 goto done;
810 if (unveil(path_dir, "r") != 0) {
811 error = got_error_from_errno2("unveil", path_dir);
812 if (logmsg_path)
813 preserve_logmsg = 1;
814 goto done;
817 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
818 if (error) {
819 if (logmsg_path)
820 preserve_logmsg = 1;
821 goto done;
824 error = got_repo_import(&new_commit_id, path_dir, logmsg,
825 author, &ignores, repo, import_progress, NULL);
826 if (error) {
827 if (logmsg_path)
828 preserve_logmsg = 1;
829 goto done;
832 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
833 if (error) {
834 if (logmsg_path)
835 preserve_logmsg = 1;
836 goto done;
839 error = got_ref_write(branch_ref, repo);
840 if (error) {
841 if (logmsg_path)
842 preserve_logmsg = 1;
843 goto done;
846 error = got_object_id_str(&id_str, new_commit_id);
847 if (error) {
848 if (logmsg_path)
849 preserve_logmsg = 1;
850 goto done;
853 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
854 if (error) {
855 if (error->code != GOT_ERR_NOT_REF) {
856 if (logmsg_path)
857 preserve_logmsg = 1;
858 goto done;
861 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
862 branch_ref);
863 if (error) {
864 if (logmsg_path)
865 preserve_logmsg = 1;
866 goto done;
869 error = got_ref_write(head_ref, repo);
870 if (error) {
871 if (logmsg_path)
872 preserve_logmsg = 1;
873 goto done;
877 printf("Created branch %s with commit %s\n",
878 got_ref_get_name(branch_ref), id_str);
879 done:
880 if (preserve_logmsg) {
881 fprintf(stderr, "%s: log message preserved in %s\n",
882 getprogname(), logmsg_path);
883 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
884 error = got_error_from_errno2("unlink", logmsg_path);
885 free(logmsg);
886 free(logmsg_path);
887 free(repo_path);
888 free(editor);
889 free(refname);
890 free(new_commit_id);
891 free(id_str);
892 free(author);
893 free(gitconfig_path);
894 if (branch_ref)
895 got_ref_close(branch_ref);
896 if (head_ref)
897 got_ref_close(head_ref);
898 return error;
901 __dead static void
902 usage_clone(void)
904 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
905 "[-R reference] repository-url [directory]\n", getprogname());
906 exit(1);
909 struct got_fetch_progress_arg {
910 char last_scaled_size[FMT_SCALED_STRSIZE];
911 int last_p_indexed;
912 int last_p_resolved;
913 int verbosity;
915 struct got_repository *repo;
917 int create_configs;
918 int configs_created;
919 struct {
920 struct got_pathlist_head *symrefs;
921 struct got_pathlist_head *wanted_branches;
922 const char *proto;
923 const char *host;
924 const char *port;
925 const char *remote_repo_path;
926 const char *git_url;
927 int fetch_all_branches;
928 int mirror_references;
929 } config_info;
930 };
932 /* XXX forward declaration */
933 static const struct got_error *
934 create_config_files(const char *proto, const char *host, const char *port,
935 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
936 int mirror_references, struct got_pathlist_head *symrefs,
937 struct got_pathlist_head *wanted_branches, struct got_repository *repo);
939 static const struct got_error *
940 fetch_progress(void *arg, const char *message, off_t packfile_size,
941 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
943 const struct got_error *err = NULL;
944 struct got_fetch_progress_arg *a = arg;
945 char scaled_size[FMT_SCALED_STRSIZE];
946 int p_indexed, p_resolved;
947 int print_size = 0, print_indexed = 0, print_resolved = 0;
949 /*
950 * In order to allow a failed clone to be resumed with 'got fetch'
951 * we try to create configuration files as soon as possible.
952 * Once the server has sent information about its default branch
953 * we have all required information.
954 */
955 if (a->create_configs && !a->configs_created &&
956 !TAILQ_EMPTY(a->config_info.symrefs)) {
957 err = create_config_files(a->config_info.proto,
958 a->config_info.host, a->config_info.port,
959 a->config_info.remote_repo_path,
960 a->config_info.git_url,
961 a->config_info.fetch_all_branches,
962 a->config_info.mirror_references,
963 a->config_info.symrefs,
964 a->config_info.wanted_branches, a->repo);
965 if (err)
966 return err;
967 a->configs_created = 1;
970 if (a->verbosity < 0)
971 return NULL;
973 if (message && message[0] != '\0') {
974 printf("\rserver: %s", message);
975 fflush(stdout);
976 return NULL;
979 if (packfile_size > 0 || nobj_indexed > 0) {
980 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
981 (a->last_scaled_size[0] == '\0' ||
982 strcmp(scaled_size, a->last_scaled_size)) != 0) {
983 print_size = 1;
984 if (strlcpy(a->last_scaled_size, scaled_size,
985 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
986 return got_error(GOT_ERR_NO_SPACE);
988 if (nobj_indexed > 0) {
989 p_indexed = (nobj_indexed * 100) / nobj_total;
990 if (p_indexed != a->last_p_indexed) {
991 a->last_p_indexed = p_indexed;
992 print_indexed = 1;
993 print_size = 1;
996 if (nobj_resolved > 0) {
997 p_resolved = (nobj_resolved * 100) /
998 (nobj_total - nobj_loose);
999 if (p_resolved != a->last_p_resolved) {
1000 a->last_p_resolved = p_resolved;
1001 print_resolved = 1;
1002 print_indexed = 1;
1003 print_size = 1;
1008 if (print_size || print_indexed || print_resolved)
1009 printf("\r");
1010 if (print_size)
1011 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
1012 if (print_indexed)
1013 printf("; indexing %d%%", p_indexed);
1014 if (print_resolved)
1015 printf("; resolving deltas %d%%", p_resolved);
1016 if (print_size || print_indexed || print_resolved)
1017 fflush(stdout);
1019 return NULL;
1022 static const struct got_error *
1023 create_symref(const char *refname, struct got_reference *target_ref,
1024 int verbosity, struct got_repository *repo)
1026 const struct got_error *err;
1027 struct got_reference *head_symref;
1029 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1030 if (err)
1031 return err;
1033 err = got_ref_write(head_symref, repo);
1034 if (err == NULL && verbosity > 0) {
1035 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1036 got_ref_get_name(target_ref));
1038 got_ref_close(head_symref);
1039 return err;
1042 static const struct got_error *
1043 list_remote_refs(struct got_pathlist_head *symrefs,
1044 struct got_pathlist_head *refs)
1046 const struct got_error *err;
1047 struct got_pathlist_entry *pe;
1049 TAILQ_FOREACH(pe, symrefs, entry) {
1050 const char *refname = pe->path;
1051 const char *targetref = pe->data;
1053 printf("%s: %s\n", refname, targetref);
1056 TAILQ_FOREACH(pe, refs, entry) {
1057 const char *refname = pe->path;
1058 struct got_object_id *id = pe->data;
1059 char *id_str;
1061 err = got_object_id_str(&id_str, id);
1062 if (err)
1063 return err;
1064 printf("%s: %s\n", refname, id_str);
1065 free(id_str);
1068 return NULL;
1071 static const struct got_error *
1072 create_ref(const char *refname, struct got_object_id *id,
1073 int verbosity, struct got_repository *repo)
1075 const struct got_error *err = NULL;
1076 struct got_reference *ref;
1077 char *id_str;
1079 err = got_object_id_str(&id_str, id);
1080 if (err)
1081 return err;
1083 err = got_ref_alloc(&ref, refname, id);
1084 if (err)
1085 goto done;
1087 err = got_ref_write(ref, repo);
1088 got_ref_close(ref);
1090 if (err == NULL && verbosity >= 0)
1091 printf("Created reference %s: %s\n", refname, id_str);
1092 done:
1093 free(id_str);
1094 return err;
1097 static int
1098 match_wanted_ref(const char *refname, const char *wanted_ref)
1100 if (strncmp(refname, "refs/", 5) != 0)
1101 return 0;
1102 refname += 5;
1105 * Prevent fetching of references that won't make any
1106 * sense outside of the remote repository's context.
1108 if (strncmp(refname, "got/", 4) == 0)
1109 return 0;
1110 if (strncmp(refname, "remotes/", 8) == 0)
1111 return 0;
1113 if (strncmp(wanted_ref, "refs/", 5) == 0)
1114 wanted_ref += 5;
1116 /* Allow prefix match. */
1117 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1118 return 1;
1120 /* Allow exact match. */
1121 return (strcmp(refname, wanted_ref) == 0);
1124 static int
1125 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1127 struct got_pathlist_entry *pe;
1129 TAILQ_FOREACH(pe, wanted_refs, entry) {
1130 if (match_wanted_ref(refname, pe->path))
1131 return 1;
1134 return 0;
1137 static const struct got_error *
1138 create_wanted_ref(const char *refname, struct got_object_id *id,
1139 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1141 const struct got_error *err;
1142 char *remote_refname;
1144 if (strncmp("refs/", refname, 5) == 0)
1145 refname += 5;
1147 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1148 remote_repo_name, refname) == -1)
1149 return got_error_from_errno("asprintf");
1151 err = create_ref(remote_refname, id, verbosity, repo);
1152 free(remote_refname);
1153 return err;
1156 static const struct got_error *
1157 create_gotconfig(const char *proto, const char *host, const char *port,
1158 const char *remote_repo_path, int fetch_all_branches, int mirror_references,
1159 struct got_repository *repo)
1161 const struct got_error *err = NULL;
1162 char *gotconfig_path = NULL;
1163 char *gotconfig = NULL;
1164 FILE *gotconfig_file = NULL;
1165 ssize_t n;
1167 /* Create got.conf(5). */
1168 gotconfig_path = got_repo_get_path_gotconfig(repo);
1169 if (gotconfig_path == NULL) {
1170 err = got_error_from_errno("got_repo_get_path_gotconfig");
1171 goto done;
1173 gotconfig_file = fopen(gotconfig_path, "a");
1174 if (gotconfig_file == NULL) {
1175 err = got_error_from_errno2("fopen", gotconfig_path);
1176 goto done;
1178 if (asprintf(&gotconfig,
1179 "remote \"%s\" {\n"
1180 "\tserver %s\n"
1181 "\tprotocol %s\n"
1182 "%s%s%s"
1183 "\trepository \"%s\"\n"
1184 "%s"
1185 "}\n",
1186 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1187 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1188 remote_repo_path,
1189 mirror_references ? "\tmirror-references yes\n" : "") == -1) {
1190 err = got_error_from_errno("asprintf");
1191 goto done;
1193 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1194 if (n != strlen(gotconfig)) {
1195 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1196 goto done;
1199 done:
1200 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1201 err = got_error_from_errno2("fclose", gotconfig_path);
1202 free(gotconfig_path);
1203 return err;
1206 static const struct got_error *
1207 create_gitconfig(const char *git_url, const char *default_branch,
1208 int fetch_all_branches, int mirror_references, struct got_repository *repo)
1210 const struct got_error *err = NULL;
1211 char *gitconfig_path = NULL;
1212 char *gitconfig = NULL;
1213 FILE *gitconfig_file = NULL;
1214 ssize_t n;
1216 /* Create a config file Git can understand. */
1217 gitconfig_path = got_repo_get_path_gitconfig(repo);
1218 if (gitconfig_path == NULL) {
1219 err = got_error_from_errno("got_repo_get_path_gitconfig");
1220 goto done;
1222 gitconfig_file = fopen(gitconfig_path, "a");
1223 if (gitconfig_file == NULL) {
1224 err = got_error_from_errno2("fopen", gitconfig_path);
1225 goto done;
1227 if (mirror_references) {
1228 if (asprintf(&gitconfig,
1229 "[remote \"%s\"]\n"
1230 "\turl = %s\n"
1231 "\tfetch = +refs/*:refs/*\n"
1232 "\tmirror = true\n",
1233 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1234 err = got_error_from_errno("asprintf");
1235 goto done;
1237 } else if (fetch_all_branches) {
1238 if (asprintf(&gitconfig,
1239 "[remote \"%s\"]\n"
1240 "\turl = %s\n"
1241 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1242 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1243 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1244 err = got_error_from_errno("asprintf");
1245 goto done;
1247 } else {
1248 const char *branchname;
1251 * If the server specified a default branch, use just that one.
1252 * Otherwise fall back to fetching all branches on next fetch.
1254 if (default_branch) {
1255 branchname = default_branch;
1256 if (strncmp(branchname, "refs/heads/", 11) == 0)
1257 branchname += 11;
1258 } else
1259 branchname = "*"; /* fall back to all branches */
1260 if (asprintf(&gitconfig,
1261 "[remote \"%s\"]\n"
1262 "\turl = %s\n"
1263 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1264 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1265 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1266 branchname) == -1) {
1267 err = got_error_from_errno("asprintf");
1268 goto done;
1271 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1272 if (n != strlen(gitconfig)) {
1273 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1274 goto done;
1276 done:
1277 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1278 err = got_error_from_errno2("fclose", gitconfig_path);
1279 free(gitconfig_path);
1280 return err;
1283 static const struct got_error *
1284 create_config_files(const char *proto, const char *host, const char *port,
1285 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1286 int mirror_references, struct got_pathlist_head *symrefs,
1287 struct got_pathlist_head *wanted_branches, struct got_repository *repo)
1289 const struct got_error *err = NULL;
1290 const char *default_branch = NULL;
1291 struct got_pathlist_entry *pe;
1294 * If we asked for a set of wanted branches then use the first
1295 * one of those.
1297 if (!TAILQ_EMPTY(wanted_branches)) {
1298 pe = TAILQ_FIRST(wanted_branches);
1299 default_branch = pe->path;
1300 } else {
1301 /* First HEAD ref listed by server is the default branch. */
1302 TAILQ_FOREACH(pe, symrefs, entry) {
1303 const char *refname = pe->path;
1304 const char *target = pe->data;
1306 if (strcmp(refname, GOT_REF_HEAD) != 0)
1307 continue;
1309 default_branch = target;
1310 break;
1314 /* Create got.conf(5). */
1315 err = create_gotconfig(proto, host, port, remote_repo_path,
1316 fetch_all_branches, mirror_references, repo);
1317 if (err)
1318 return err;
1320 /* Create a config file Git can understand. */
1321 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1322 mirror_references, repo);
1325 static const struct got_error *
1326 cmd_clone(int argc, char *argv[])
1328 const struct got_error *error = NULL;
1329 const char *uri, *dirname;
1330 char *proto, *host, *port, *repo_name, *server_path;
1331 char *default_destdir = NULL, *id_str = NULL;
1332 const char *repo_path;
1333 struct got_repository *repo = NULL;
1334 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1335 struct got_pathlist_entry *pe;
1336 struct got_object_id *pack_hash = NULL;
1337 int ch, fetchfd = -1, fetchstatus;
1338 pid_t fetchpid = -1;
1339 struct got_fetch_progress_arg fpa;
1340 char *git_url = NULL;
1341 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1342 int list_refs_only = 0;
1344 TAILQ_INIT(&refs);
1345 TAILQ_INIT(&symrefs);
1346 TAILQ_INIT(&wanted_branches);
1347 TAILQ_INIT(&wanted_refs);
1349 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1350 switch (ch) {
1351 case 'a':
1352 fetch_all_branches = 1;
1353 break;
1354 case 'b':
1355 error = got_pathlist_append(&wanted_branches,
1356 optarg, NULL);
1357 if (error)
1358 return error;
1359 break;
1360 case 'l':
1361 list_refs_only = 1;
1362 break;
1363 case 'm':
1364 mirror_references = 1;
1365 break;
1366 case 'v':
1367 if (verbosity < 0)
1368 verbosity = 0;
1369 else if (verbosity < 3)
1370 verbosity++;
1371 break;
1372 case 'q':
1373 verbosity = -1;
1374 break;
1375 case 'R':
1376 error = got_pathlist_append(&wanted_refs,
1377 optarg, NULL);
1378 if (error)
1379 return error;
1380 break;
1381 default:
1382 usage_clone();
1383 break;
1386 argc -= optind;
1387 argv += optind;
1389 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1390 errx(1, "-a and -b options are mutually exclusive");
1391 if (list_refs_only) {
1392 if (!TAILQ_EMPTY(&wanted_branches))
1393 errx(1, "-l and -b options are mutually exclusive");
1394 if (fetch_all_branches)
1395 errx(1, "-l and -a options are mutually exclusive");
1396 if (mirror_references)
1397 errx(1, "-l and -m options are mutually exclusive");
1398 if (verbosity == -1)
1399 errx(1, "-l and -q options are mutually exclusive");
1400 if (!TAILQ_EMPTY(&wanted_refs))
1401 errx(1, "-l and -R options are mutually exclusive");
1404 uri = argv[0];
1406 if (argc == 1)
1407 dirname = NULL;
1408 else if (argc == 2)
1409 dirname = argv[1];
1410 else
1411 usage_clone();
1413 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1414 &repo_name, uri);
1415 if (error)
1416 goto done;
1418 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1419 host, port ? ":" : "", port ? port : "",
1420 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1421 error = got_error_from_errno("asprintf");
1422 goto done;
1425 if (strcmp(proto, "git") == 0) {
1426 #ifndef PROFILE
1427 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1428 "sendfd dns inet unveil", NULL) == -1)
1429 err(1, "pledge");
1430 #endif
1431 } else if (strcmp(proto, "git+ssh") == 0 ||
1432 strcmp(proto, "ssh") == 0) {
1433 #ifndef PROFILE
1434 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1435 "sendfd unveil", NULL) == -1)
1436 err(1, "pledge");
1437 #endif
1438 } else if (strcmp(proto, "http") == 0 ||
1439 strcmp(proto, "git+http") == 0) {
1440 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1441 goto done;
1442 } else {
1443 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1444 goto done;
1446 if (dirname == NULL) {
1447 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1448 error = got_error_from_errno("asprintf");
1449 goto done;
1451 repo_path = default_destdir;
1452 } else
1453 repo_path = dirname;
1455 if (!list_refs_only) {
1456 error = got_path_mkdir(repo_path);
1457 if (error &&
1458 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1459 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1460 goto done;
1461 if (!got_path_dir_is_empty(repo_path)) {
1462 error = got_error_path(repo_path,
1463 GOT_ERR_DIR_NOT_EMPTY);
1464 goto done;
1468 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1469 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1470 error = got_error_from_errno2("unveil",
1471 GOT_FETCH_PATH_SSH);
1472 goto done;
1475 error = apply_unveil(repo_path, 0, NULL);
1476 if (error)
1477 goto done;
1479 if (verbosity >= 0)
1480 printf("Connecting to %s%s%s\n", host,
1481 port ? ":" : "", port ? port : "");
1483 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1484 server_path, verbosity);
1485 if (error)
1486 goto done;
1488 if (!list_refs_only) {
1489 error = got_repo_init(repo_path);
1490 if (error)
1491 goto done;
1492 error = got_repo_open(&repo, repo_path, NULL);
1493 if (error)
1494 goto done;
1497 fpa.last_scaled_size[0] = '\0';
1498 fpa.last_p_indexed = -1;
1499 fpa.last_p_resolved = -1;
1500 fpa.verbosity = verbosity;
1501 fpa.create_configs = 1;
1502 fpa.configs_created = 0;
1503 fpa.repo = repo;
1504 fpa.config_info.symrefs = &symrefs;
1505 fpa.config_info.wanted_branches = &wanted_branches;
1506 fpa.config_info.proto = proto;
1507 fpa.config_info.host = host;
1508 fpa.config_info.port = port;
1509 fpa.config_info.remote_repo_path = server_path;
1510 fpa.config_info.git_url = git_url;
1511 fpa.config_info.fetch_all_branches = fetch_all_branches;
1512 fpa.config_info.mirror_references = mirror_references;
1513 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1514 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1515 fetch_all_branches, &wanted_branches, &wanted_refs,
1516 list_refs_only, verbosity, fetchfd, repo,
1517 fetch_progress, &fpa);
1518 if (error)
1519 goto done;
1521 if (list_refs_only) {
1522 error = list_remote_refs(&symrefs, &refs);
1523 goto done;
1526 error = got_object_id_str(&id_str, pack_hash);
1527 if (error)
1528 goto done;
1529 if (verbosity >= 0)
1530 printf("\nFetched %s.pack\n", id_str);
1531 free(id_str);
1533 /* Set up references provided with the pack file. */
1534 TAILQ_FOREACH(pe, &refs, entry) {
1535 const char *refname = pe->path;
1536 struct got_object_id *id = pe->data;
1537 char *remote_refname;
1539 if (is_wanted_ref(&wanted_refs, refname) &&
1540 !mirror_references) {
1541 error = create_wanted_ref(refname, id,
1542 GOT_FETCH_DEFAULT_REMOTE_NAME,
1543 verbosity - 1, repo);
1544 if (error)
1545 goto done;
1546 continue;
1549 error = create_ref(refname, id, verbosity - 1, repo);
1550 if (error)
1551 goto done;
1553 if (mirror_references)
1554 continue;
1556 if (strncmp("refs/heads/", refname, 11) != 0)
1557 continue;
1559 if (asprintf(&remote_refname,
1560 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1561 refname + 11) == -1) {
1562 error = got_error_from_errno("asprintf");
1563 goto done;
1565 error = create_ref(remote_refname, id, verbosity - 1, repo);
1566 free(remote_refname);
1567 if (error)
1568 goto done;
1571 /* Set the HEAD reference if the server provided one. */
1572 TAILQ_FOREACH(pe, &symrefs, entry) {
1573 struct got_reference *target_ref;
1574 const char *refname = pe->path;
1575 const char *target = pe->data;
1576 char *remote_refname = NULL, *remote_target = NULL;
1578 if (strcmp(refname, GOT_REF_HEAD) != 0)
1579 continue;
1581 error = got_ref_open(&target_ref, repo, target, 0);
1582 if (error) {
1583 if (error->code == GOT_ERR_NOT_REF) {
1584 error = NULL;
1585 continue;
1587 goto done;
1590 error = create_symref(refname, target_ref, verbosity, repo);
1591 got_ref_close(target_ref);
1592 if (error)
1593 goto done;
1595 if (mirror_references)
1596 continue;
1598 if (strncmp("refs/heads/", target, 11) != 0)
1599 continue;
1601 if (asprintf(&remote_refname,
1602 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1603 refname) == -1) {
1604 error = got_error_from_errno("asprintf");
1605 goto done;
1607 if (asprintf(&remote_target,
1608 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1609 target + 11) == -1) {
1610 error = got_error_from_errno("asprintf");
1611 free(remote_refname);
1612 goto done;
1614 error = got_ref_open(&target_ref, repo, remote_target, 0);
1615 if (error) {
1616 free(remote_refname);
1617 free(remote_target);
1618 if (error->code == GOT_ERR_NOT_REF) {
1619 error = NULL;
1620 continue;
1622 goto done;
1624 error = create_symref(remote_refname, target_ref,
1625 verbosity - 1, repo);
1626 free(remote_refname);
1627 free(remote_target);
1628 got_ref_close(target_ref);
1629 if (error)
1630 goto done;
1632 if (pe == NULL) {
1634 * We failed to set the HEAD reference. If we asked for
1635 * a set of wanted branches use the first of one of those
1636 * which could be fetched instead.
1638 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1639 const char *target = pe->path;
1640 struct got_reference *target_ref;
1642 error = got_ref_open(&target_ref, repo, target, 0);
1643 if (error) {
1644 if (error->code == GOT_ERR_NOT_REF) {
1645 error = NULL;
1646 continue;
1648 goto done;
1651 error = create_symref(GOT_REF_HEAD, target_ref,
1652 verbosity, repo);
1653 got_ref_close(target_ref);
1654 if (error)
1655 goto done;
1656 break;
1660 if (verbosity >= 0)
1661 printf("Created %s repository '%s'\n",
1662 mirror_references ? "mirrored" : "cloned", repo_path);
1663 done:
1664 if (fetchpid > 0) {
1665 if (kill(fetchpid, SIGTERM) == -1)
1666 error = got_error_from_errno("kill");
1667 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1668 error = got_error_from_errno("waitpid");
1670 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1671 error = got_error_from_errno("close");
1672 if (repo)
1673 got_repo_close(repo);
1674 TAILQ_FOREACH(pe, &refs, entry) {
1675 free((void *)pe->path);
1676 free(pe->data);
1678 got_pathlist_free(&refs);
1679 TAILQ_FOREACH(pe, &symrefs, entry) {
1680 free((void *)pe->path);
1681 free(pe->data);
1683 got_pathlist_free(&symrefs);
1684 got_pathlist_free(&wanted_branches);
1685 got_pathlist_free(&wanted_refs);
1686 free(pack_hash);
1687 free(proto);
1688 free(host);
1689 free(port);
1690 free(server_path);
1691 free(repo_name);
1692 free(default_destdir);
1693 free(git_url);
1694 return error;
1697 static const struct got_error *
1698 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1699 int replace_tags, int verbosity, struct got_repository *repo)
1701 const struct got_error *err = NULL;
1702 char *new_id_str = NULL;
1703 struct got_object_id *old_id = NULL;
1705 err = got_object_id_str(&new_id_str, new_id);
1706 if (err)
1707 goto done;
1709 if (!replace_tags &&
1710 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1711 err = got_ref_resolve(&old_id, repo, ref);
1712 if (err)
1713 goto done;
1714 if (got_object_id_cmp(old_id, new_id) == 0)
1715 goto done;
1716 if (verbosity >= 0) {
1717 printf("Rejecting update of existing tag %s: %s\n",
1718 got_ref_get_name(ref), new_id_str);
1720 goto done;
1723 if (got_ref_is_symbolic(ref)) {
1724 if (verbosity >= 0) {
1725 printf("Replacing reference %s: %s\n",
1726 got_ref_get_name(ref),
1727 got_ref_get_symref_target(ref));
1729 err = got_ref_change_symref_to_ref(ref, new_id);
1730 if (err)
1731 goto done;
1732 err = got_ref_write(ref, repo);
1733 if (err)
1734 goto done;
1735 } else {
1736 err = got_ref_resolve(&old_id, repo, ref);
1737 if (err)
1738 goto done;
1739 if (got_object_id_cmp(old_id, new_id) == 0)
1740 goto done;
1742 err = got_ref_change_ref(ref, new_id);
1743 if (err)
1744 goto done;
1745 err = got_ref_write(ref, repo);
1746 if (err)
1747 goto done;
1750 if (verbosity >= 0)
1751 printf("Updated %s: %s\n", got_ref_get_name(ref),
1752 new_id_str);
1753 done:
1754 free(old_id);
1755 free(new_id_str);
1756 return err;
1759 static const struct got_error *
1760 update_symref(const char *refname, struct got_reference *target_ref,
1761 int verbosity, struct got_repository *repo)
1763 const struct got_error *err = NULL, *unlock_err;
1764 struct got_reference *symref;
1765 int symref_is_locked = 0;
1767 err = got_ref_open(&symref, repo, refname, 1);
1768 if (err) {
1769 if (err->code != GOT_ERR_NOT_REF)
1770 return err;
1771 err = got_ref_alloc_symref(&symref, refname, target_ref);
1772 if (err)
1773 goto done;
1775 err = got_ref_write(symref, repo);
1776 if (err)
1777 goto done;
1779 if (verbosity >= 0)
1780 printf("Created reference %s: %s\n",
1781 got_ref_get_name(symref),
1782 got_ref_get_symref_target(symref));
1783 } else {
1784 symref_is_locked = 1;
1786 if (strcmp(got_ref_get_symref_target(symref),
1787 got_ref_get_name(target_ref)) == 0)
1788 goto done;
1790 err = got_ref_change_symref(symref,
1791 got_ref_get_name(target_ref));
1792 if (err)
1793 goto done;
1795 err = got_ref_write(symref, repo);
1796 if (err)
1797 goto done;
1799 if (verbosity >= 0)
1800 printf("Updated %s: %s\n", got_ref_get_name(symref),
1801 got_ref_get_symref_target(symref));
1804 done:
1805 if (symref_is_locked) {
1806 unlock_err = got_ref_unlock(symref);
1807 if (unlock_err && err == NULL)
1808 err = unlock_err;
1810 got_ref_close(symref);
1811 return err;
1814 __dead static void
1815 usage_fetch(void)
1817 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1818 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1819 "[remote-repository-name]\n",
1820 getprogname());
1821 exit(1);
1824 static const struct got_error *
1825 delete_missing_ref(struct got_reference *ref,
1826 int verbosity, struct got_repository *repo)
1828 const struct got_error *err = NULL;
1829 struct got_object_id *id = NULL;
1830 char *id_str = NULL;
1832 if (got_ref_is_symbolic(ref)) {
1833 err = got_ref_delete(ref, repo);
1834 if (err)
1835 return err;
1836 if (verbosity >= 0) {
1837 printf("Deleted reference %s: %s\n",
1838 got_ref_get_name(ref),
1839 got_ref_get_symref_target(ref));
1841 } else {
1842 err = got_ref_resolve(&id, repo, ref);
1843 if (err)
1844 return err;
1845 err = got_object_id_str(&id_str, id);
1846 if (err)
1847 goto done;
1849 err = got_ref_delete(ref, repo);
1850 if (err)
1851 goto done;
1852 if (verbosity >= 0) {
1853 printf("Deleted reference %s: %s\n",
1854 got_ref_get_name(ref), id_str);
1857 done:
1858 free(id);
1859 free(id_str);
1860 return NULL;
1863 static const struct got_error *
1864 delete_missing_refs(struct got_pathlist_head *their_refs,
1865 struct got_pathlist_head *their_symrefs,
1866 const struct got_remote_repo *remote,
1867 int verbosity, struct got_repository *repo)
1869 const struct got_error *err = NULL, *unlock_err;
1870 struct got_reflist_head my_refs;
1871 struct got_reflist_entry *re;
1872 struct got_pathlist_entry *pe;
1873 char *remote_namespace = NULL;
1874 char *local_refname = NULL;
1876 SIMPLEQ_INIT(&my_refs);
1878 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
1879 == -1)
1880 return got_error_from_errno("asprintf");
1882 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1883 if (err)
1884 goto done;
1886 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1887 const char *refname = got_ref_get_name(re->ref);
1889 if (!remote->mirror_references) {
1890 if (strncmp(refname, remote_namespace,
1891 strlen(remote_namespace)) == 0) {
1892 if (strcmp(refname + strlen(remote_namespace),
1893 GOT_REF_HEAD) == 0)
1894 continue;
1895 if (asprintf(&local_refname, "refs/heads/%s",
1896 refname + strlen(remote_namespace)) == -1) {
1897 err = got_error_from_errno("asprintf");
1898 goto done;
1900 } else if (strncmp(refname, "refs/tags/", 10) != 0)
1901 continue;
1904 TAILQ_FOREACH(pe, their_refs, entry) {
1905 if (strcmp(local_refname, pe->path) == 0)
1906 break;
1908 if (pe != NULL)
1909 continue;
1911 TAILQ_FOREACH(pe, their_symrefs, entry) {
1912 if (strcmp(local_refname, pe->path) == 0)
1913 break;
1915 if (pe != NULL)
1916 continue;
1918 err = delete_missing_ref(re->ref, verbosity, repo);
1919 if (err)
1920 break;
1922 if (local_refname) {
1923 struct got_reference *ref;
1924 err = got_ref_open(&ref, repo, local_refname, 1);
1925 if (err) {
1926 if (err->code != GOT_ERR_NOT_REF)
1927 break;
1928 free(local_refname);
1929 local_refname = NULL;
1930 continue;
1932 err = delete_missing_ref(ref, verbosity, repo);
1933 if (err)
1934 break;
1935 unlock_err = got_ref_unlock(ref);
1936 got_ref_close(ref);
1937 if (unlock_err && err == NULL) {
1938 err = unlock_err;
1939 break;
1942 free(local_refname);
1943 local_refname = NULL;
1946 done:
1947 free(remote_namespace);
1948 free(local_refname);
1949 return err;
1952 static const struct got_error *
1953 update_wanted_ref(const char *refname, struct got_object_id *id,
1954 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1956 const struct got_error *err, *unlock_err;
1957 char *remote_refname;
1958 struct got_reference *ref;
1960 if (strncmp("refs/", refname, 5) == 0)
1961 refname += 5;
1963 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1964 remote_repo_name, refname) == -1)
1965 return got_error_from_errno("asprintf");
1967 err = got_ref_open(&ref, repo, remote_refname, 1);
1968 if (err) {
1969 if (err->code != GOT_ERR_NOT_REF)
1970 goto done;
1971 err = create_ref(remote_refname, id, verbosity, repo);
1972 } else {
1973 err = update_ref(ref, id, 0, verbosity, repo);
1974 unlock_err = got_ref_unlock(ref);
1975 if (unlock_err && err == NULL)
1976 err = unlock_err;
1977 got_ref_close(ref);
1979 done:
1980 free(remote_refname);
1981 return err;
1984 static const struct got_error *
1985 cmd_fetch(int argc, char *argv[])
1987 const struct got_error *error = NULL, *unlock_err;
1988 char *cwd = NULL, *repo_path = NULL;
1989 const char *remote_name;
1990 char *proto = NULL, *host = NULL, *port = NULL;
1991 char *repo_name = NULL, *server_path = NULL;
1992 const struct got_remote_repo *remotes, *remote = NULL;
1993 int nremotes;
1994 char *id_str = NULL;
1995 struct got_repository *repo = NULL;
1996 struct got_worktree *worktree = NULL;
1997 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
1998 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1999 struct got_pathlist_entry *pe;
2000 struct got_object_id *pack_hash = NULL;
2001 int i, ch, fetchfd = -1, fetchstatus;
2002 pid_t fetchpid = -1;
2003 struct got_fetch_progress_arg fpa;
2004 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2005 int delete_refs = 0, replace_tags = 0;
2007 TAILQ_INIT(&refs);
2008 TAILQ_INIT(&symrefs);
2009 TAILQ_INIT(&wanted_branches);
2010 TAILQ_INIT(&wanted_refs);
2012 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
2013 switch (ch) {
2014 case 'a':
2015 fetch_all_branches = 1;
2016 break;
2017 case 'b':
2018 error = got_pathlist_append(&wanted_branches,
2019 optarg, NULL);
2020 if (error)
2021 return error;
2022 break;
2023 case 'd':
2024 delete_refs = 1;
2025 break;
2026 case 'l':
2027 list_refs_only = 1;
2028 break;
2029 case 'r':
2030 repo_path = realpath(optarg, NULL);
2031 if (repo_path == NULL)
2032 return got_error_from_errno2("realpath",
2033 optarg);
2034 got_path_strip_trailing_slashes(repo_path);
2035 break;
2036 case 't':
2037 replace_tags = 1;
2038 break;
2039 case 'v':
2040 if (verbosity < 0)
2041 verbosity = 0;
2042 else if (verbosity < 3)
2043 verbosity++;
2044 break;
2045 case 'q':
2046 verbosity = -1;
2047 break;
2048 case 'R':
2049 error = got_pathlist_append(&wanted_refs,
2050 optarg, NULL);
2051 if (error)
2052 return error;
2053 break;
2054 default:
2055 usage_fetch();
2056 break;
2059 argc -= optind;
2060 argv += optind;
2062 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2063 errx(1, "-a and -b options are mutually exclusive");
2064 if (list_refs_only) {
2065 if (!TAILQ_EMPTY(&wanted_branches))
2066 errx(1, "-l and -b options are mutually exclusive");
2067 if (fetch_all_branches)
2068 errx(1, "-l and -a options are mutually exclusive");
2069 if (delete_refs)
2070 errx(1, "-l and -d options are mutually exclusive");
2071 if (verbosity == -1)
2072 errx(1, "-l and -q options are mutually exclusive");
2075 if (argc == 0)
2076 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2077 else if (argc == 1)
2078 remote_name = argv[0];
2079 else
2080 usage_fetch();
2082 cwd = getcwd(NULL, 0);
2083 if (cwd == NULL) {
2084 error = got_error_from_errno("getcwd");
2085 goto done;
2088 if (repo_path == NULL) {
2089 error = got_worktree_open(&worktree, cwd);
2090 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2091 goto done;
2092 else
2093 error = NULL;
2094 if (worktree) {
2095 repo_path =
2096 strdup(got_worktree_get_repo_path(worktree));
2097 if (repo_path == NULL)
2098 error = got_error_from_errno("strdup");
2099 if (error)
2100 goto done;
2101 } else {
2102 repo_path = strdup(cwd);
2103 if (repo_path == NULL) {
2104 error = got_error_from_errno("strdup");
2105 goto done;
2110 error = got_repo_open(&repo, repo_path, NULL);
2111 if (error)
2112 goto done;
2114 if (worktree) {
2115 worktree_conf = got_worktree_get_gotconfig(worktree);
2116 if (worktree_conf) {
2117 got_gotconfig_get_remotes(&nremotes, &remotes,
2118 worktree_conf);
2119 for (i = 0; i < nremotes; i++) {
2120 remote = &remotes[i];
2121 if (strcmp(remote->name, remote_name) == 0)
2122 break;
2126 if (remote == NULL) {
2127 repo_conf = got_repo_get_gotconfig(repo);
2128 if (repo_conf) {
2129 got_gotconfig_get_remotes(&nremotes, &remotes,
2130 repo_conf);
2131 for (i = 0; i < nremotes; i++) {
2132 remote = &remotes[i];
2133 if (strcmp(remote->name, remote_name) == 0)
2134 break;
2138 if (remote == NULL) {
2139 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2140 for (i = 0; i < nremotes; i++) {
2141 remote = &remotes[i];
2142 if (strcmp(remote->name, remote_name) == 0)
2143 break;
2146 if (remote == NULL) {
2147 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2148 goto done;
2151 if (TAILQ_EMPTY(&wanted_branches) && remote->nbranches > 0) {
2152 for (i = 0; i < remote->nbranches; i++) {
2153 got_pathlist_append(&wanted_branches,
2154 remote->branches[i], NULL);
2159 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
2160 &repo_name, remote->url);
2161 if (error)
2162 goto done;
2164 if (strcmp(proto, "git") == 0) {
2165 #ifndef PROFILE
2166 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2167 "sendfd dns inet unveil", NULL) == -1)
2168 err(1, "pledge");
2169 #endif
2170 } else if (strcmp(proto, "git+ssh") == 0 ||
2171 strcmp(proto, "ssh") == 0) {
2172 #ifndef PROFILE
2173 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2174 "sendfd unveil", NULL) == -1)
2175 err(1, "pledge");
2176 #endif
2177 } else if (strcmp(proto, "http") == 0 ||
2178 strcmp(proto, "git+http") == 0) {
2179 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2180 goto done;
2181 } else {
2182 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2183 goto done;
2186 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
2187 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
2188 error = got_error_from_errno2("unveil",
2189 GOT_FETCH_PATH_SSH);
2190 goto done;
2193 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2194 if (error)
2195 goto done;
2197 if (verbosity >= 0)
2198 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2199 port ? ":" : "", port ? port : "");
2201 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2202 server_path, verbosity);
2203 if (error)
2204 goto done;
2206 fpa.last_scaled_size[0] = '\0';
2207 fpa.last_p_indexed = -1;
2208 fpa.last_p_resolved = -1;
2209 fpa.verbosity = verbosity;
2210 fpa.repo = repo;
2211 fpa.create_configs = 0;
2212 fpa.configs_created = 0;
2213 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2214 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2215 remote->mirror_references, fetch_all_branches, &wanted_branches,
2216 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2217 fetch_progress, &fpa);
2218 if (error)
2219 goto done;
2221 if (list_refs_only) {
2222 error = list_remote_refs(&symrefs, &refs);
2223 goto done;
2226 if (pack_hash == NULL) {
2227 if (verbosity >= 0)
2228 printf("Already up-to-date\n");
2229 } else if (verbosity >= 0) {
2230 error = got_object_id_str(&id_str, pack_hash);
2231 if (error)
2232 goto done;
2233 printf("\nFetched %s.pack\n", id_str);
2234 free(id_str);
2235 id_str = NULL;
2238 /* Update references provided with the pack file. */
2239 TAILQ_FOREACH(pe, &refs, entry) {
2240 const char *refname = pe->path;
2241 struct got_object_id *id = pe->data;
2242 struct got_reference *ref;
2243 char *remote_refname;
2245 if (is_wanted_ref(&wanted_refs, refname) &&
2246 !remote->mirror_references) {
2247 error = update_wanted_ref(refname, id,
2248 remote->name, verbosity, repo);
2249 if (error)
2250 goto done;
2251 continue;
2254 if (remote->mirror_references ||
2255 strncmp("refs/tags/", refname, 10) == 0) {
2256 error = got_ref_open(&ref, repo, refname, 1);
2257 if (error) {
2258 if (error->code != GOT_ERR_NOT_REF)
2259 goto done;
2260 error = create_ref(refname, id, verbosity,
2261 repo);
2262 if (error)
2263 goto done;
2264 } else {
2265 error = update_ref(ref, id, replace_tags,
2266 verbosity, repo);
2267 unlock_err = got_ref_unlock(ref);
2268 if (unlock_err && error == NULL)
2269 error = unlock_err;
2270 got_ref_close(ref);
2271 if (error)
2272 goto done;
2274 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2275 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2276 remote_name, refname + 11) == -1) {
2277 error = got_error_from_errno("asprintf");
2278 goto done;
2281 error = got_ref_open(&ref, repo, remote_refname, 1);
2282 if (error) {
2283 if (error->code != GOT_ERR_NOT_REF)
2284 goto done;
2285 error = create_ref(remote_refname, id,
2286 verbosity, repo);
2287 if (error)
2288 goto done;
2289 } else {
2290 error = update_ref(ref, id, replace_tags,
2291 verbosity, repo);
2292 unlock_err = got_ref_unlock(ref);
2293 if (unlock_err && error == NULL)
2294 error = unlock_err;
2295 got_ref_close(ref);
2296 if (error)
2297 goto done;
2300 /* Also create a local branch if none exists yet. */
2301 error = got_ref_open(&ref, repo, refname, 1);
2302 if (error) {
2303 if (error->code != GOT_ERR_NOT_REF)
2304 goto done;
2305 error = create_ref(refname, id, verbosity,
2306 repo);
2307 if (error)
2308 goto done;
2309 } else {
2310 unlock_err = got_ref_unlock(ref);
2311 if (unlock_err && error == NULL)
2312 error = unlock_err;
2313 got_ref_close(ref);
2317 if (delete_refs) {
2318 error = delete_missing_refs(&refs, &symrefs, remote,
2319 verbosity, repo);
2320 if (error)
2321 goto done;
2324 if (!remote->mirror_references) {
2325 /* Update remote HEAD reference if the server provided one. */
2326 TAILQ_FOREACH(pe, &symrefs, entry) {
2327 struct got_reference *target_ref;
2328 const char *refname = pe->path;
2329 const char *target = pe->data;
2330 char *remote_refname = NULL, *remote_target = NULL;
2332 if (strcmp(refname, GOT_REF_HEAD) != 0)
2333 continue;
2335 if (strncmp("refs/heads/", target, 11) != 0)
2336 continue;
2338 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2339 remote->name, refname) == -1) {
2340 error = got_error_from_errno("asprintf");
2341 goto done;
2343 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2344 remote->name, target + 11) == -1) {
2345 error = got_error_from_errno("asprintf");
2346 free(remote_refname);
2347 goto done;
2350 error = got_ref_open(&target_ref, repo, remote_target,
2351 0);
2352 if (error) {
2353 free(remote_refname);
2354 free(remote_target);
2355 if (error->code == GOT_ERR_NOT_REF) {
2356 error = NULL;
2357 continue;
2359 goto done;
2361 error = update_symref(remote_refname, target_ref,
2362 verbosity, repo);
2363 free(remote_refname);
2364 free(remote_target);
2365 got_ref_close(target_ref);
2366 if (error)
2367 goto done;
2370 done:
2371 if (fetchpid > 0) {
2372 if (kill(fetchpid, SIGTERM) == -1)
2373 error = got_error_from_errno("kill");
2374 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2375 error = got_error_from_errno("waitpid");
2377 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2378 error = got_error_from_errno("close");
2379 if (repo)
2380 got_repo_close(repo);
2381 if (worktree)
2382 got_worktree_close(worktree);
2383 TAILQ_FOREACH(pe, &refs, entry) {
2384 free((void *)pe->path);
2385 free(pe->data);
2387 got_pathlist_free(&refs);
2388 TAILQ_FOREACH(pe, &symrefs, entry) {
2389 free((void *)pe->path);
2390 free(pe->data);
2392 got_pathlist_free(&symrefs);
2393 got_pathlist_free(&wanted_branches);
2394 got_pathlist_free(&wanted_refs);
2395 free(id_str);
2396 free(cwd);
2397 free(repo_path);
2398 free(pack_hash);
2399 free(proto);
2400 free(host);
2401 free(port);
2402 free(server_path);
2403 free(repo_name);
2404 return error;
2408 __dead static void
2409 usage_checkout(void)
2411 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2412 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2413 exit(1);
2416 static void
2417 show_worktree_base_ref_warning(void)
2419 fprintf(stderr, "%s: warning: could not create a reference "
2420 "to the work tree's base commit; the commit could be "
2421 "garbage-collected by Git; making the repository "
2422 "writable and running 'got update' will prevent this\n",
2423 getprogname());
2426 struct got_checkout_progress_arg {
2427 const char *worktree_path;
2428 int had_base_commit_ref_error;
2431 static const struct got_error *
2432 checkout_progress(void *arg, unsigned char status, const char *path)
2434 struct got_checkout_progress_arg *a = arg;
2436 /* Base commit bump happens silently. */
2437 if (status == GOT_STATUS_BUMP_BASE)
2438 return NULL;
2440 if (status == GOT_STATUS_BASE_REF_ERR) {
2441 a->had_base_commit_ref_error = 1;
2442 return NULL;
2445 while (path[0] == '/')
2446 path++;
2448 printf("%c %s/%s\n", status, a->worktree_path, path);
2449 return NULL;
2452 static const struct got_error *
2453 check_cancelled(void *arg)
2455 if (sigint_received || sigpipe_received)
2456 return got_error(GOT_ERR_CANCELLED);
2457 return NULL;
2460 static const struct got_error *
2461 check_linear_ancestry(struct got_object_id *commit_id,
2462 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2463 struct got_repository *repo)
2465 const struct got_error *err = NULL;
2466 struct got_object_id *yca_id;
2468 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2469 commit_id, base_commit_id, repo, check_cancelled, NULL);
2470 if (err)
2471 return err;
2473 if (yca_id == NULL)
2474 return got_error(GOT_ERR_ANCESTRY);
2477 * Require a straight line of history between the target commit
2478 * and the work tree's base commit.
2480 * Non-linear situations such as this require a rebase:
2482 * (commit) D F (base_commit)
2483 * \ /
2484 * C E
2485 * \ /
2486 * B (yca)
2487 * |
2488 * A
2490 * 'got update' only handles linear cases:
2491 * Update forwards in time: A (base/yca) - B - C - D (commit)
2492 * Update backwards in time: D (base) - C - B - A (commit/yca)
2494 if (allow_forwards_in_time_only) {
2495 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2496 return got_error(GOT_ERR_ANCESTRY);
2497 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2498 got_object_id_cmp(base_commit_id, yca_id) != 0)
2499 return got_error(GOT_ERR_ANCESTRY);
2501 free(yca_id);
2502 return NULL;
2505 static const struct got_error *
2506 check_same_branch(struct got_object_id *commit_id,
2507 struct got_reference *head_ref, struct got_object_id *yca_id,
2508 struct got_repository *repo)
2510 const struct got_error *err = NULL;
2511 struct got_commit_graph *graph = NULL;
2512 struct got_object_id *head_commit_id = NULL;
2513 int is_same_branch = 0;
2515 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2516 if (err)
2517 goto done;
2519 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2520 is_same_branch = 1;
2521 goto done;
2523 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2524 is_same_branch = 1;
2525 goto done;
2528 err = got_commit_graph_open(&graph, "/", 1);
2529 if (err)
2530 goto done;
2532 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2533 check_cancelled, NULL);
2534 if (err)
2535 goto done;
2537 for (;;) {
2538 struct got_object_id *id;
2539 err = got_commit_graph_iter_next(&id, graph, repo,
2540 check_cancelled, NULL);
2541 if (err) {
2542 if (err->code == GOT_ERR_ITER_COMPLETED)
2543 err = NULL;
2544 break;
2547 if (id) {
2548 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2549 break;
2550 if (got_object_id_cmp(id, commit_id) == 0) {
2551 is_same_branch = 1;
2552 break;
2556 done:
2557 if (graph)
2558 got_commit_graph_close(graph);
2559 free(head_commit_id);
2560 if (!err && !is_same_branch)
2561 err = got_error(GOT_ERR_ANCESTRY);
2562 return err;
2565 static const struct got_error *
2566 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2568 static char msg[512];
2569 const char *branch_name;
2571 if (got_ref_is_symbolic(ref))
2572 branch_name = got_ref_get_symref_target(ref);
2573 else
2574 branch_name = got_ref_get_name(ref);
2576 if (strncmp("refs/heads/", branch_name, 11) == 0)
2577 branch_name += 11;
2579 snprintf(msg, sizeof(msg),
2580 "target commit is not contained in branch '%s'; "
2581 "the branch to use must be specified with -b; "
2582 "if necessary a new branch can be created for "
2583 "this commit with 'got branch -c %s BRANCH_NAME'",
2584 branch_name, commit_id_str);
2586 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2589 static const struct got_error *
2590 cmd_checkout(int argc, char *argv[])
2592 const struct got_error *error = NULL;
2593 struct got_repository *repo = NULL;
2594 struct got_reference *head_ref = NULL;
2595 struct got_worktree *worktree = NULL;
2596 char *repo_path = NULL;
2597 char *worktree_path = NULL;
2598 const char *path_prefix = "";
2599 const char *branch_name = GOT_REF_HEAD;
2600 char *commit_id_str = NULL;
2601 char *cwd = NULL, *path = NULL;
2602 int ch, same_path_prefix, allow_nonempty = 0;
2603 struct got_pathlist_head paths;
2604 struct got_checkout_progress_arg cpa;
2606 TAILQ_INIT(&paths);
2608 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2609 switch (ch) {
2610 case 'b':
2611 branch_name = optarg;
2612 break;
2613 case 'c':
2614 commit_id_str = strdup(optarg);
2615 if (commit_id_str == NULL)
2616 return got_error_from_errno("strdup");
2617 break;
2618 case 'E':
2619 allow_nonempty = 1;
2620 break;
2621 case 'p':
2622 path_prefix = optarg;
2623 break;
2624 default:
2625 usage_checkout();
2626 /* NOTREACHED */
2630 argc -= optind;
2631 argv += optind;
2633 #ifndef PROFILE
2634 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2635 "unveil", NULL) == -1)
2636 err(1, "pledge");
2637 #endif
2638 if (argc == 1) {
2639 char *base, *dotgit;
2640 repo_path = realpath(argv[0], NULL);
2641 if (repo_path == NULL)
2642 return got_error_from_errno2("realpath", argv[0]);
2643 cwd = getcwd(NULL, 0);
2644 if (cwd == NULL) {
2645 error = got_error_from_errno("getcwd");
2646 goto done;
2648 if (path_prefix[0])
2649 path = strdup(path_prefix);
2650 else
2651 path = strdup(repo_path);
2652 if (path == NULL) {
2653 error = got_error_from_errno("strdup");
2654 goto done;
2656 base = basename(path);
2657 if (base == NULL) {
2658 error = got_error_from_errno2("basename", path);
2659 goto done;
2661 dotgit = strstr(base, ".git");
2662 if (dotgit)
2663 *dotgit = '\0';
2664 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2665 error = got_error_from_errno("asprintf");
2666 goto done;
2668 } else if (argc == 2) {
2669 repo_path = realpath(argv[0], NULL);
2670 if (repo_path == NULL) {
2671 error = got_error_from_errno2("realpath", argv[0]);
2672 goto done;
2674 worktree_path = realpath(argv[1], NULL);
2675 if (worktree_path == NULL) {
2676 if (errno != ENOENT) {
2677 error = got_error_from_errno2("realpath",
2678 argv[1]);
2679 goto done;
2681 worktree_path = strdup(argv[1]);
2682 if (worktree_path == NULL) {
2683 error = got_error_from_errno("strdup");
2684 goto done;
2687 } else
2688 usage_checkout();
2690 got_path_strip_trailing_slashes(repo_path);
2691 got_path_strip_trailing_slashes(worktree_path);
2693 error = got_repo_open(&repo, repo_path, NULL);
2694 if (error != NULL)
2695 goto done;
2697 /* Pre-create work tree path for unveil(2) */
2698 error = got_path_mkdir(worktree_path);
2699 if (error) {
2700 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2701 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2702 goto done;
2703 if (!allow_nonempty &&
2704 !got_path_dir_is_empty(worktree_path)) {
2705 error = got_error_path(worktree_path,
2706 GOT_ERR_DIR_NOT_EMPTY);
2707 goto done;
2711 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2712 if (error)
2713 goto done;
2715 error = got_ref_open(&head_ref, repo, branch_name, 0);
2716 if (error != NULL)
2717 goto done;
2719 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2720 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2721 goto done;
2723 error = got_worktree_open(&worktree, worktree_path);
2724 if (error != NULL)
2725 goto done;
2727 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2728 path_prefix);
2729 if (error != NULL)
2730 goto done;
2731 if (!same_path_prefix) {
2732 error = got_error(GOT_ERR_PATH_PREFIX);
2733 goto done;
2736 if (commit_id_str) {
2737 struct got_object_id *commit_id;
2738 error = got_repo_match_object_id(&commit_id, NULL,
2739 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2740 if (error)
2741 goto done;
2742 error = check_linear_ancestry(commit_id,
2743 got_worktree_get_base_commit_id(worktree), 0, repo);
2744 if (error != NULL) {
2745 free(commit_id);
2746 if (error->code == GOT_ERR_ANCESTRY) {
2747 error = checkout_ancestry_error(
2748 head_ref, commit_id_str);
2750 goto done;
2752 error = check_same_branch(commit_id, head_ref, NULL, repo);
2753 if (error) {
2754 if (error->code == GOT_ERR_ANCESTRY) {
2755 error = checkout_ancestry_error(
2756 head_ref, commit_id_str);
2758 goto done;
2760 error = got_worktree_set_base_commit_id(worktree, repo,
2761 commit_id);
2762 free(commit_id);
2763 if (error)
2764 goto done;
2767 error = got_pathlist_append(&paths, "", NULL);
2768 if (error)
2769 goto done;
2770 cpa.worktree_path = worktree_path;
2771 cpa.had_base_commit_ref_error = 0;
2772 error = got_worktree_checkout_files(worktree, &paths, repo,
2773 checkout_progress, &cpa, check_cancelled, NULL);
2774 if (error != NULL)
2775 goto done;
2777 printf("Now shut up and hack\n");
2778 if (cpa.had_base_commit_ref_error)
2779 show_worktree_base_ref_warning();
2780 done:
2781 got_pathlist_free(&paths);
2782 free(commit_id_str);
2783 free(repo_path);
2784 free(worktree_path);
2785 free(cwd);
2786 free(path);
2787 return error;
2790 struct got_update_progress_arg {
2791 int did_something;
2792 int conflicts;
2793 int obstructed;
2794 int not_updated;
2797 void
2798 print_update_progress_stats(struct got_update_progress_arg *upa)
2800 if (!upa->did_something)
2801 return;
2803 if (upa->conflicts > 0)
2804 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2805 if (upa->obstructed > 0)
2806 printf("File paths obstructed by a non-regular file: %d\n",
2807 upa->obstructed);
2808 if (upa->not_updated > 0)
2809 printf("Files not updated because of existing merge "
2810 "conflicts: %d\n", upa->not_updated);
2813 __dead static void
2814 usage_update(void)
2816 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2817 getprogname());
2818 exit(1);
2821 static const struct got_error *
2822 update_progress(void *arg, unsigned char status, const char *path)
2824 struct got_update_progress_arg *upa = arg;
2826 if (status == GOT_STATUS_EXISTS ||
2827 status == GOT_STATUS_BASE_REF_ERR)
2828 return NULL;
2830 upa->did_something = 1;
2832 /* Base commit bump happens silently. */
2833 if (status == GOT_STATUS_BUMP_BASE)
2834 return NULL;
2836 if (status == GOT_STATUS_CONFLICT)
2837 upa->conflicts++;
2838 if (status == GOT_STATUS_OBSTRUCTED)
2839 upa->obstructed++;
2840 if (status == GOT_STATUS_CANNOT_UPDATE)
2841 upa->not_updated++;
2843 while (path[0] == '/')
2844 path++;
2845 printf("%c %s\n", status, path);
2846 return NULL;
2849 static const struct got_error *
2850 switch_head_ref(struct got_reference *head_ref,
2851 struct got_object_id *commit_id, struct got_worktree *worktree,
2852 struct got_repository *repo)
2854 const struct got_error *err = NULL;
2855 char *base_id_str;
2856 int ref_has_moved = 0;
2858 /* Trivial case: switching between two different references. */
2859 if (strcmp(got_ref_get_name(head_ref),
2860 got_worktree_get_head_ref_name(worktree)) != 0) {
2861 printf("Switching work tree from %s to %s\n",
2862 got_worktree_get_head_ref_name(worktree),
2863 got_ref_get_name(head_ref));
2864 return got_worktree_set_head_ref(worktree, head_ref);
2867 err = check_linear_ancestry(commit_id,
2868 got_worktree_get_base_commit_id(worktree), 0, repo);
2869 if (err) {
2870 if (err->code != GOT_ERR_ANCESTRY)
2871 return err;
2872 ref_has_moved = 1;
2874 if (!ref_has_moved)
2875 return NULL;
2877 /* Switching to a rebased branch with the same reference name. */
2878 err = got_object_id_str(&base_id_str,
2879 got_worktree_get_base_commit_id(worktree));
2880 if (err)
2881 return err;
2882 printf("Reference %s now points at a different branch\n",
2883 got_worktree_get_head_ref_name(worktree));
2884 printf("Switching work tree from %s to %s\n", base_id_str,
2885 got_worktree_get_head_ref_name(worktree));
2886 return NULL;
2889 static const struct got_error *
2890 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2892 const struct got_error *err;
2893 int in_progress;
2895 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2896 if (err)
2897 return err;
2898 if (in_progress)
2899 return got_error(GOT_ERR_REBASING);
2901 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2902 if (err)
2903 return err;
2904 if (in_progress)
2905 return got_error(GOT_ERR_HISTEDIT_BUSY);
2907 return NULL;
2910 static const struct got_error *
2911 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2912 char *argv[], struct got_worktree *worktree)
2914 const struct got_error *err = NULL;
2915 char *path;
2916 int i;
2918 if (argc == 0) {
2919 path = strdup("");
2920 if (path == NULL)
2921 return got_error_from_errno("strdup");
2922 return got_pathlist_append(paths, path, NULL);
2925 for (i = 0; i < argc; i++) {
2926 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2927 if (err)
2928 break;
2929 err = got_pathlist_append(paths, path, NULL);
2930 if (err) {
2931 free(path);
2932 break;
2936 return err;
2939 static const struct got_error *
2940 wrap_not_worktree_error(const struct got_error *orig_err,
2941 const char *cmdname, const char *path)
2943 const struct got_error *err;
2944 struct got_repository *repo;
2945 static char msg[512];
2947 err = got_repo_open(&repo, path, NULL);
2948 if (err)
2949 return orig_err;
2951 snprintf(msg, sizeof(msg),
2952 "'got %s' needs a work tree in addition to a git repository\n"
2953 "Work trees can be checked out from this Git repository with "
2954 "'got checkout'.\n"
2955 "The got(1) manual page contains more information.", cmdname);
2956 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2957 got_repo_close(repo);
2958 return err;
2961 static const struct got_error *
2962 cmd_update(int argc, char *argv[])
2964 const struct got_error *error = NULL;
2965 struct got_repository *repo = NULL;
2966 struct got_worktree *worktree = NULL;
2967 char *worktree_path = NULL;
2968 struct got_object_id *commit_id = NULL;
2969 char *commit_id_str = NULL;
2970 const char *branch_name = NULL;
2971 struct got_reference *head_ref = NULL;
2972 struct got_pathlist_head paths;
2973 struct got_pathlist_entry *pe;
2974 int ch;
2975 struct got_update_progress_arg upa;
2977 TAILQ_INIT(&paths);
2979 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2980 switch (ch) {
2981 case 'b':
2982 branch_name = optarg;
2983 break;
2984 case 'c':
2985 commit_id_str = strdup(optarg);
2986 if (commit_id_str == NULL)
2987 return got_error_from_errno("strdup");
2988 break;
2989 default:
2990 usage_update();
2991 /* NOTREACHED */
2995 argc -= optind;
2996 argv += optind;
2998 #ifndef PROFILE
2999 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3000 "unveil", NULL) == -1)
3001 err(1, "pledge");
3002 #endif
3003 worktree_path = getcwd(NULL, 0);
3004 if (worktree_path == NULL) {
3005 error = got_error_from_errno("getcwd");
3006 goto done;
3008 error = got_worktree_open(&worktree, worktree_path);
3009 if (error) {
3010 if (error->code == GOT_ERR_NOT_WORKTREE)
3011 error = wrap_not_worktree_error(error, "update",
3012 worktree_path);
3013 goto done;
3016 error = check_rebase_or_histedit_in_progress(worktree);
3017 if (error)
3018 goto done;
3020 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3021 NULL);
3022 if (error != NULL)
3023 goto done;
3025 error = apply_unveil(got_repo_get_path(repo), 0,
3026 got_worktree_get_root_path(worktree));
3027 if (error)
3028 goto done;
3030 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3031 if (error)
3032 goto done;
3034 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3035 got_worktree_get_head_ref_name(worktree), 0);
3036 if (error != NULL)
3037 goto done;
3038 if (commit_id_str == NULL) {
3039 error = got_ref_resolve(&commit_id, repo, head_ref);
3040 if (error != NULL)
3041 goto done;
3042 error = got_object_id_str(&commit_id_str, commit_id);
3043 if (error != NULL)
3044 goto done;
3045 } else {
3046 error = got_repo_match_object_id(&commit_id, NULL,
3047 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
3048 free(commit_id_str);
3049 commit_id_str = NULL;
3050 if (error)
3051 goto done;
3052 error = got_object_id_str(&commit_id_str, commit_id);
3053 if (error)
3054 goto done;
3057 if (branch_name) {
3058 struct got_object_id *head_commit_id;
3059 TAILQ_FOREACH(pe, &paths, entry) {
3060 if (pe->path_len == 0)
3061 continue;
3062 error = got_error_msg(GOT_ERR_BAD_PATH,
3063 "switching between branches requires that "
3064 "the entire work tree gets updated");
3065 goto done;
3067 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3068 if (error)
3069 goto done;
3070 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3071 repo);
3072 free(head_commit_id);
3073 if (error != NULL)
3074 goto done;
3075 error = check_same_branch(commit_id, head_ref, NULL, repo);
3076 if (error)
3077 goto done;
3078 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3079 if (error)
3080 goto done;
3081 } else {
3082 error = check_linear_ancestry(commit_id,
3083 got_worktree_get_base_commit_id(worktree), 0, repo);
3084 if (error != NULL) {
3085 if (error->code == GOT_ERR_ANCESTRY)
3086 error = got_error(GOT_ERR_BRANCH_MOVED);
3087 goto done;
3089 error = check_same_branch(commit_id, head_ref, NULL, repo);
3090 if (error)
3091 goto done;
3094 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3095 commit_id) != 0) {
3096 error = got_worktree_set_base_commit_id(worktree, repo,
3097 commit_id);
3098 if (error)
3099 goto done;
3102 memset(&upa, 0, sizeof(upa));
3103 error = got_worktree_checkout_files(worktree, &paths, repo,
3104 update_progress, &upa, check_cancelled, NULL);
3105 if (error != NULL)
3106 goto done;
3108 if (upa.did_something)
3109 printf("Updated to commit %s\n", commit_id_str);
3110 else
3111 printf("Already up-to-date\n");
3112 print_update_progress_stats(&upa);
3113 done:
3114 free(worktree_path);
3115 TAILQ_FOREACH(pe, &paths, entry)
3116 free((char *)pe->path);
3117 got_pathlist_free(&paths);
3118 free(commit_id);
3119 free(commit_id_str);
3120 return error;
3123 static const struct got_error *
3124 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3125 const char *path, int diff_context, int ignore_whitespace,
3126 struct got_repository *repo)
3128 const struct got_error *err = NULL;
3129 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3131 if (blob_id1) {
3132 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3133 if (err)
3134 goto done;
3137 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3138 if (err)
3139 goto done;
3141 while (path[0] == '/')
3142 path++;
3143 err = got_diff_blob(blob1, blob2, path, path, diff_context,
3144 ignore_whitespace, stdout);
3145 done:
3146 if (blob1)
3147 got_object_blob_close(blob1);
3148 got_object_blob_close(blob2);
3149 return err;
3152 static const struct got_error *
3153 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3154 const char *path, int diff_context, int ignore_whitespace,
3155 struct got_repository *repo)
3157 const struct got_error *err = NULL;
3158 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3159 struct got_diff_blob_output_unidiff_arg arg;
3161 if (tree_id1) {
3162 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3163 if (err)
3164 goto done;
3167 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3168 if (err)
3169 goto done;
3171 arg.diff_context = diff_context;
3172 arg.ignore_whitespace = ignore_whitespace;
3173 arg.outfile = stdout;
3174 while (path[0] == '/')
3175 path++;
3176 err = got_diff_tree(tree1, tree2, path, path, repo,
3177 got_diff_blob_output_unidiff, &arg, 1);
3178 done:
3179 if (tree1)
3180 got_object_tree_close(tree1);
3181 if (tree2)
3182 got_object_tree_close(tree2);
3183 return err;
3186 static const struct got_error *
3187 get_changed_paths(struct got_pathlist_head *paths,
3188 struct got_commit_object *commit, struct got_repository *repo)
3190 const struct got_error *err = NULL;
3191 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3192 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3193 struct got_object_qid *qid;
3195 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3196 if (qid != NULL) {
3197 struct got_commit_object *pcommit;
3198 err = got_object_open_as_commit(&pcommit, repo,
3199 qid->id);
3200 if (err)
3201 return err;
3203 tree_id1 = got_object_commit_get_tree_id(pcommit);
3204 got_object_commit_close(pcommit);
3208 if (tree_id1) {
3209 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3210 if (err)
3211 goto done;
3214 tree_id2 = got_object_commit_get_tree_id(commit);
3215 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3216 if (err)
3217 goto done;
3219 err = got_diff_tree(tree1, tree2, "", "", repo,
3220 got_diff_tree_collect_changed_paths, paths, 0);
3221 done:
3222 if (tree1)
3223 got_object_tree_close(tree1);
3224 if (tree2)
3225 got_object_tree_close(tree2);
3226 return err;
3229 static const struct got_error *
3230 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3231 const char *path, int diff_context, struct got_repository *repo)
3233 const struct got_error *err = NULL;
3234 struct got_commit_object *pcommit = NULL;
3235 char *id_str1 = NULL, *id_str2 = NULL;
3236 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3237 struct got_object_qid *qid;
3239 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3240 if (qid != NULL) {
3241 err = got_object_open_as_commit(&pcommit, repo,
3242 qid->id);
3243 if (err)
3244 return err;
3247 if (path && path[0] != '\0') {
3248 int obj_type;
3249 err = got_object_id_by_path(&obj_id2, repo, id, path);
3250 if (err)
3251 goto done;
3252 err = got_object_id_str(&id_str2, obj_id2);
3253 if (err) {
3254 free(obj_id2);
3255 goto done;
3257 if (pcommit) {
3258 err = got_object_id_by_path(&obj_id1, repo,
3259 qid->id, path);
3260 if (err) {
3261 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3262 free(obj_id2);
3263 goto done;
3265 } else {
3266 err = got_object_id_str(&id_str1, obj_id1);
3267 if (err) {
3268 free(obj_id2);
3269 goto done;
3273 err = got_object_get_type(&obj_type, repo, obj_id2);
3274 if (err) {
3275 free(obj_id2);
3276 goto done;
3278 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3279 switch (obj_type) {
3280 case GOT_OBJ_TYPE_BLOB:
3281 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3282 0, repo);
3283 break;
3284 case GOT_OBJ_TYPE_TREE:
3285 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3286 0, repo);
3287 break;
3288 default:
3289 err = got_error(GOT_ERR_OBJ_TYPE);
3290 break;
3292 free(obj_id1);
3293 free(obj_id2);
3294 } else {
3295 obj_id2 = got_object_commit_get_tree_id(commit);
3296 err = got_object_id_str(&id_str2, obj_id2);
3297 if (err)
3298 goto done;
3299 obj_id1 = got_object_commit_get_tree_id(pcommit);
3300 err = got_object_id_str(&id_str1, obj_id1);
3301 if (err)
3302 goto done;
3303 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3304 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
3306 done:
3307 free(id_str1);
3308 free(id_str2);
3309 if (pcommit)
3310 got_object_commit_close(pcommit);
3311 return err;
3314 static char *
3315 get_datestr(time_t *time, char *datebuf)
3317 struct tm mytm, *tm;
3318 char *p, *s;
3320 tm = gmtime_r(time, &mytm);
3321 if (tm == NULL)
3322 return NULL;
3323 s = asctime_r(tm, datebuf);
3324 if (s == NULL)
3325 return NULL;
3326 p = strchr(s, '\n');
3327 if (p)
3328 *p = '\0';
3329 return s;
3332 static const struct got_error *
3333 match_logmsg(int *have_match, struct got_object_id *id,
3334 struct got_commit_object *commit, regex_t *regex)
3336 const struct got_error *err = NULL;
3337 regmatch_t regmatch;
3338 char *id_str = NULL, *logmsg = NULL;
3340 *have_match = 0;
3342 err = got_object_id_str(&id_str, id);
3343 if (err)
3344 return err;
3346 err = got_object_commit_get_logmsg(&logmsg, commit);
3347 if (err)
3348 goto done;
3350 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3351 *have_match = 1;
3352 done:
3353 free(id_str);
3354 free(logmsg);
3355 return err;
3358 static void
3359 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3360 regex_t *regex)
3362 regmatch_t regmatch;
3363 struct got_pathlist_entry *pe;
3365 *have_match = 0;
3367 TAILQ_FOREACH(pe, changed_paths, entry) {
3368 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3369 *have_match = 1;
3370 break;
3375 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3377 static const struct got_error *
3378 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3379 struct got_repository *repo, const char *path,
3380 struct got_pathlist_head *changed_paths, int show_patch,
3381 int diff_context, struct got_reflist_head *refs)
3383 const struct got_error *err = NULL;
3384 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3385 char datebuf[26];
3386 time_t committer_time;
3387 const char *author, *committer;
3388 char *refs_str = NULL;
3389 struct got_reflist_entry *re;
3391 SIMPLEQ_FOREACH(re, refs, entry) {
3392 char *s;
3393 const char *name;
3394 struct got_tag_object *tag = NULL;
3395 struct got_object_id *ref_id;
3396 int cmp;
3398 name = got_ref_get_name(re->ref);
3399 if (strcmp(name, GOT_REF_HEAD) == 0)
3400 continue;
3401 if (strncmp(name, "refs/", 5) == 0)
3402 name += 5;
3403 if (strncmp(name, "got/", 4) == 0)
3404 continue;
3405 if (strncmp(name, "heads/", 6) == 0)
3406 name += 6;
3407 if (strncmp(name, "remotes/", 8) == 0) {
3408 name += 8;
3409 s = strstr(name, "/" GOT_REF_HEAD);
3410 if (s != NULL && s[strlen(s)] == '\0')
3411 continue;
3413 err = got_ref_resolve(&ref_id, repo, re->ref);
3414 if (err)
3415 return err;
3416 if (strncmp(name, "tags/", 5) == 0) {
3417 err = got_object_open_as_tag(&tag, repo, ref_id);
3418 if (err) {
3419 if (err->code != GOT_ERR_OBJ_TYPE) {
3420 free(ref_id);
3421 return err;
3423 /* Ref points at something other than a tag. */
3424 err = NULL;
3425 tag = NULL;
3428 cmp = got_object_id_cmp(tag ?
3429 got_object_tag_get_object_id(tag) : ref_id, id);
3430 free(ref_id);
3431 if (tag)
3432 got_object_tag_close(tag);
3433 if (cmp != 0)
3434 continue;
3435 s = refs_str;
3436 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3437 name) == -1) {
3438 err = got_error_from_errno("asprintf");
3439 free(s);
3440 return err;
3442 free(s);
3444 err = got_object_id_str(&id_str, id);
3445 if (err)
3446 return err;
3448 printf(GOT_COMMIT_SEP_STR);
3449 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3450 refs_str ? refs_str : "", refs_str ? ")" : "");
3451 free(id_str);
3452 id_str = NULL;
3453 free(refs_str);
3454 refs_str = NULL;
3455 printf("from: %s\n", got_object_commit_get_author(commit));
3456 committer_time = got_object_commit_get_committer_time(commit);
3457 datestr = get_datestr(&committer_time, datebuf);
3458 if (datestr)
3459 printf("date: %s UTC\n", datestr);
3460 author = got_object_commit_get_author(commit);
3461 committer = got_object_commit_get_committer(commit);
3462 if (strcmp(author, committer) != 0)
3463 printf("via: %s\n", committer);
3464 if (got_object_commit_get_nparents(commit) > 1) {
3465 const struct got_object_id_queue *parent_ids;
3466 struct got_object_qid *qid;
3467 int n = 1;
3468 parent_ids = got_object_commit_get_parent_ids(commit);
3469 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3470 err = got_object_id_str(&id_str, qid->id);
3471 if (err)
3472 return err;
3473 printf("parent %d: %s\n", n++, id_str);
3474 free(id_str);
3478 err = got_object_commit_get_logmsg(&logmsg0, commit);
3479 if (err)
3480 return err;
3482 logmsg = logmsg0;
3483 do {
3484 line = strsep(&logmsg, "\n");
3485 if (line)
3486 printf(" %s\n", line);
3487 } while (line);
3488 free(logmsg0);
3490 if (changed_paths) {
3491 struct got_pathlist_entry *pe;
3492 TAILQ_FOREACH(pe, changed_paths, entry) {
3493 struct got_diff_changed_path *cp = pe->data;
3494 printf(" %c %s\n", cp->status, pe->path);
3496 printf("\n");
3498 if (show_patch) {
3499 err = print_patch(commit, id, path, diff_context, repo);
3500 if (err == 0)
3501 printf("\n");
3504 if (fflush(stdout) != 0 && err == NULL)
3505 err = got_error_from_errno("fflush");
3506 return err;
3509 static const struct got_error *
3510 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3511 struct got_repository *repo, const char *path, int show_changed_paths,
3512 int show_patch, const char *search_pattern, int diff_context, int limit,
3513 int log_branches, int reverse_display_order, struct got_reflist_head *refs)
3515 const struct got_error *err;
3516 struct got_commit_graph *graph;
3517 regex_t regex;
3518 int have_match;
3519 struct got_object_id_queue reversed_commits;
3520 struct got_object_qid *qid;
3521 struct got_commit_object *commit;
3522 struct got_pathlist_head changed_paths;
3523 struct got_pathlist_entry *pe;
3525 SIMPLEQ_INIT(&reversed_commits);
3526 TAILQ_INIT(&changed_paths);
3528 if (search_pattern && regcomp(&regex, search_pattern,
3529 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3530 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3532 err = got_commit_graph_open(&graph, path, !log_branches);
3533 if (err)
3534 return err;
3535 err = got_commit_graph_iter_start(graph, root_id, repo,
3536 check_cancelled, NULL);
3537 if (err)
3538 goto done;
3539 for (;;) {
3540 struct got_object_id *id;
3542 if (sigint_received || sigpipe_received)
3543 break;
3545 err = got_commit_graph_iter_next(&id, graph, repo,
3546 check_cancelled, NULL);
3547 if (err) {
3548 if (err->code == GOT_ERR_ITER_COMPLETED)
3549 err = NULL;
3550 break;
3552 if (id == NULL)
3553 break;
3555 err = got_object_open_as_commit(&commit, repo, id);
3556 if (err)
3557 break;
3559 if (show_changed_paths && !reverse_display_order) {
3560 err = get_changed_paths(&changed_paths, commit, repo);
3561 if (err)
3562 break;
3565 if (search_pattern) {
3566 err = match_logmsg(&have_match, id, commit, &regex);
3567 if (err) {
3568 got_object_commit_close(commit);
3569 break;
3571 if (have_match == 0 && show_changed_paths)
3572 match_changed_paths(&have_match,
3573 &changed_paths, &regex);
3574 if (have_match == 0) {
3575 got_object_commit_close(commit);
3576 TAILQ_FOREACH(pe, &changed_paths, entry) {
3577 free((char *)pe->path);
3578 free(pe->data);
3580 got_pathlist_free(&changed_paths);
3581 continue;
3585 if (reverse_display_order) {
3586 err = got_object_qid_alloc(&qid, id);
3587 if (err)
3588 break;
3589 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3590 got_object_commit_close(commit);
3591 } else {
3592 err = print_commit(commit, id, repo, path,
3593 show_changed_paths ? &changed_paths : NULL,
3594 show_patch, diff_context, refs);
3595 got_object_commit_close(commit);
3596 if (err)
3597 break;
3599 if ((limit && --limit == 0) ||
3600 (end_id && got_object_id_cmp(id, end_id) == 0))
3601 break;
3603 TAILQ_FOREACH(pe, &changed_paths, entry) {
3604 free((char *)pe->path);
3605 free(pe->data);
3607 got_pathlist_free(&changed_paths);
3609 if (reverse_display_order) {
3610 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3611 err = got_object_open_as_commit(&commit, repo, qid->id);
3612 if (err)
3613 break;
3614 if (show_changed_paths) {
3615 err = get_changed_paths(&changed_paths,
3616 commit, repo);
3617 if (err)
3618 break;
3620 err = print_commit(commit, qid->id, repo, path,
3621 show_changed_paths ? &changed_paths : NULL,
3622 show_patch, diff_context, refs);
3623 got_object_commit_close(commit);
3624 if (err)
3625 break;
3626 TAILQ_FOREACH(pe, &changed_paths, entry) {
3627 free((char *)pe->path);
3628 free(pe->data);
3630 got_pathlist_free(&changed_paths);
3633 done:
3634 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3635 qid = SIMPLEQ_FIRST(&reversed_commits);
3636 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3637 got_object_qid_free(qid);
3639 TAILQ_FOREACH(pe, &changed_paths, entry) {
3640 free((char *)pe->path);
3641 free(pe->data);
3643 got_pathlist_free(&changed_paths);
3644 if (search_pattern)
3645 regfree(&regex);
3646 got_commit_graph_close(graph);
3647 return err;
3650 __dead static void
3651 usage_log(void)
3653 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3654 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3655 "[-R] [path]\n", getprogname());
3656 exit(1);
3659 static int
3660 get_default_log_limit(void)
3662 const char *got_default_log_limit;
3663 long long n;
3664 const char *errstr;
3666 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3667 if (got_default_log_limit == NULL)
3668 return 0;
3669 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3670 if (errstr != NULL)
3671 return 0;
3672 return n;
3675 static const struct got_error *
3676 resolve_commit_arg(struct got_object_id **id, const char *commit_arg,
3677 struct got_repository *repo)
3679 const struct got_error *err = NULL;
3680 struct got_reference *ref;
3682 *id = NULL;
3684 err = got_ref_open(&ref, repo, commit_arg, 0);
3685 if (err == NULL) {
3686 int obj_type;
3687 err = got_ref_resolve(id, repo, ref);
3688 got_ref_close(ref);
3689 if (err)
3690 return err;
3691 err = got_object_get_type(&obj_type, repo, *id);
3692 if (err)
3693 return err;
3694 if (obj_type == GOT_OBJ_TYPE_TAG) {
3695 struct got_tag_object *tag;
3696 err = got_object_open_as_tag(&tag, repo, *id);
3697 if (err)
3698 return err;
3699 if (got_object_tag_get_object_type(tag) !=
3700 GOT_OBJ_TYPE_COMMIT) {
3701 got_object_tag_close(tag);
3702 return got_error(GOT_ERR_OBJ_TYPE);
3704 free(*id);
3705 *id = got_object_id_dup(
3706 got_object_tag_get_object_id(tag));
3707 if (*id == NULL)
3708 err = got_error_from_errno(
3709 "got_object_id_dup");
3710 got_object_tag_close(tag);
3711 if (err)
3712 return err;
3713 } else if (obj_type != GOT_OBJ_TYPE_COMMIT)
3714 return got_error(GOT_ERR_OBJ_TYPE);
3715 } else {
3716 err = got_repo_match_object_id_prefix(id, commit_arg,
3717 GOT_OBJ_TYPE_COMMIT, repo);
3720 return err;
3723 static const struct got_error *
3724 cmd_log(int argc, char *argv[])
3726 const struct got_error *error;
3727 struct got_repository *repo = NULL;
3728 struct got_worktree *worktree = NULL;
3729 struct got_object_id *start_id = NULL, *end_id = NULL;
3730 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3731 const char *start_commit = NULL, *end_commit = NULL;
3732 const char *search_pattern = NULL;
3733 int diff_context = -1, ch;
3734 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3735 int reverse_display_order = 0;
3736 const char *errstr;
3737 struct got_reflist_head refs;
3739 SIMPLEQ_INIT(&refs);
3741 #ifndef PROFILE
3742 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3743 NULL)
3744 == -1)
3745 err(1, "pledge");
3746 #endif
3748 limit = get_default_log_limit();
3750 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3751 switch (ch) {
3752 case 'p':
3753 show_patch = 1;
3754 break;
3755 case 'P':
3756 show_changed_paths = 1;
3757 break;
3758 case 'c':
3759 start_commit = optarg;
3760 break;
3761 case 'C':
3762 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3763 &errstr);
3764 if (errstr != NULL)
3765 err(1, "-C option %s", errstr);
3766 break;
3767 case 'l':
3768 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3769 if (errstr != NULL)
3770 err(1, "-l option %s", errstr);
3771 break;
3772 case 'b':
3773 log_branches = 1;
3774 break;
3775 case 'r':
3776 repo_path = realpath(optarg, NULL);
3777 if (repo_path == NULL)
3778 return got_error_from_errno2("realpath",
3779 optarg);
3780 got_path_strip_trailing_slashes(repo_path);
3781 break;
3782 case 'R':
3783 reverse_display_order = 1;
3784 break;
3785 case 's':
3786 search_pattern = optarg;
3787 break;
3788 case 'x':
3789 end_commit = optarg;
3790 break;
3791 default:
3792 usage_log();
3793 /* NOTREACHED */
3797 argc -= optind;
3798 argv += optind;
3800 if (diff_context == -1)
3801 diff_context = 3;
3802 else if (!show_patch)
3803 errx(1, "-C requires -p");
3805 cwd = getcwd(NULL, 0);
3806 if (cwd == NULL) {
3807 error = got_error_from_errno("getcwd");
3808 goto done;
3811 if (repo_path == NULL) {
3812 error = got_worktree_open(&worktree, cwd);
3813 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3814 goto done;
3815 error = NULL;
3818 if (argc == 0) {
3819 path = strdup("");
3820 if (path == NULL) {
3821 error = got_error_from_errno("strdup");
3822 goto done;
3824 } else if (argc == 1) {
3825 if (worktree) {
3826 error = got_worktree_resolve_path(&path, worktree,
3827 argv[0]);
3828 if (error)
3829 goto done;
3830 } else {
3831 path = strdup(argv[0]);
3832 if (path == NULL) {
3833 error = got_error_from_errno("strdup");
3834 goto done;
3837 } else
3838 usage_log();
3840 if (repo_path == NULL) {
3841 repo_path = worktree ?
3842 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3844 if (repo_path == NULL) {
3845 error = got_error_from_errno("strdup");
3846 goto done;
3849 error = got_repo_open(&repo, repo_path, NULL);
3850 if (error != NULL)
3851 goto done;
3853 error = apply_unveil(got_repo_get_path(repo), 1,
3854 worktree ? got_worktree_get_root_path(worktree) : NULL);
3855 if (error)
3856 goto done;
3858 if (start_commit == NULL) {
3859 struct got_reference *head_ref;
3860 struct got_commit_object *commit = NULL;
3861 error = got_ref_open(&head_ref, repo,
3862 worktree ? got_worktree_get_head_ref_name(worktree)
3863 : GOT_REF_HEAD, 0);
3864 if (error != NULL)
3865 goto done;
3866 error = got_ref_resolve(&start_id, repo, head_ref);
3867 got_ref_close(head_ref);
3868 if (error != NULL)
3869 goto done;
3870 error = got_object_open_as_commit(&commit, repo,
3871 start_id);
3872 if (error != NULL)
3873 goto done;
3874 got_object_commit_close(commit);
3875 } else {
3876 error = resolve_commit_arg(&start_id, start_commit, repo);
3877 if (error != NULL)
3878 goto done;
3880 if (end_commit != NULL) {
3881 error = resolve_commit_arg(&end_id, end_commit, repo);
3882 if (error != NULL)
3883 goto done;
3886 if (worktree) {
3887 const char *prefix = got_worktree_get_path_prefix(worktree);
3888 char *p;
3889 if (asprintf(&p, "%s%s%s", prefix,
3890 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3891 error = got_error_from_errno("asprintf");
3892 goto done;
3894 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3895 free(p);
3896 } else
3897 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3898 if (error != NULL)
3899 goto done;
3900 if (in_repo_path) {
3901 free(path);
3902 path = in_repo_path;
3905 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3906 if (error)
3907 goto done;
3909 error = print_commits(start_id, end_id, repo, path, show_changed_paths,
3910 show_patch, search_pattern, diff_context, limit, log_branches,
3911 reverse_display_order, &refs);
3912 done:
3913 free(path);
3914 free(repo_path);
3915 free(cwd);
3916 if (worktree)
3917 got_worktree_close(worktree);
3918 if (repo) {
3919 const struct got_error *repo_error;
3920 repo_error = got_repo_close(repo);
3921 if (error == NULL)
3922 error = repo_error;
3924 got_ref_list_free(&refs);
3925 return error;
3928 __dead static void
3929 usage_diff(void)
3931 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3932 "[-w] [object1 object2 | path]\n", getprogname());
3933 exit(1);
3936 struct print_diff_arg {
3937 struct got_repository *repo;
3938 struct got_worktree *worktree;
3939 int diff_context;
3940 const char *id_str;
3941 int header_shown;
3942 int diff_staged;
3943 int ignore_whitespace;
3947 * Create a file which contains the target path of a symlink so we can feed
3948 * it as content to the diff engine.
3950 static const struct got_error *
3951 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
3952 const char *abspath)
3954 const struct got_error *err = NULL;
3955 char target_path[PATH_MAX];
3956 ssize_t target_len, outlen;
3958 *fd = -1;
3960 if (dirfd != -1) {
3961 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
3962 if (target_len == -1)
3963 return got_error_from_errno2("readlinkat", abspath);
3964 } else {
3965 target_len = readlink(abspath, target_path, PATH_MAX);
3966 if (target_len == -1)
3967 return got_error_from_errno2("readlink", abspath);
3970 *fd = got_opentempfd();
3971 if (*fd == -1)
3972 return got_error_from_errno("got_opentempfd");
3974 outlen = write(*fd, target_path, target_len);
3975 if (outlen == -1) {
3976 err = got_error_from_errno("got_opentempfd");
3977 goto done;
3980 if (lseek(*fd, 0, SEEK_SET) == -1) {
3981 err = got_error_from_errno2("lseek", abspath);
3982 goto done;
3984 done:
3985 if (err) {
3986 close(*fd);
3987 *fd = -1;
3989 return err;
3992 static const struct got_error *
3993 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3994 const char *path, struct got_object_id *blob_id,
3995 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3996 int dirfd, const char *de_name)
3998 struct print_diff_arg *a = arg;
3999 const struct got_error *err = NULL;
4000 struct got_blob_object *blob1 = NULL;
4001 int fd = -1;
4002 FILE *f2 = NULL;
4003 char *abspath = NULL, *label1 = NULL;
4004 struct stat sb;
4006 if (a->diff_staged) {
4007 if (staged_status != GOT_STATUS_MODIFY &&
4008 staged_status != GOT_STATUS_ADD &&
4009 staged_status != GOT_STATUS_DELETE)
4010 return NULL;
4011 } else {
4012 if (staged_status == GOT_STATUS_DELETE)
4013 return NULL;
4014 if (status == GOT_STATUS_NONEXISTENT)
4015 return got_error_set_errno(ENOENT, path);
4016 if (status != GOT_STATUS_MODIFY &&
4017 status != GOT_STATUS_ADD &&
4018 status != GOT_STATUS_DELETE &&
4019 status != GOT_STATUS_CONFLICT)
4020 return NULL;
4023 if (!a->header_shown) {
4024 printf("diff %s %s%s\n", a->id_str,
4025 got_worktree_get_root_path(a->worktree),
4026 a->diff_staged ? " (staged changes)" : "");
4027 a->header_shown = 1;
4030 if (a->diff_staged) {
4031 const char *label1 = NULL, *label2 = NULL;
4032 switch (staged_status) {
4033 case GOT_STATUS_MODIFY:
4034 label1 = path;
4035 label2 = path;
4036 break;
4037 case GOT_STATUS_ADD:
4038 label2 = path;
4039 break;
4040 case GOT_STATUS_DELETE:
4041 label1 = path;
4042 break;
4043 default:
4044 return got_error(GOT_ERR_FILE_STATUS);
4046 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
4047 label1, label2, a->diff_context, a->ignore_whitespace,
4048 a->repo, stdout);
4051 if (staged_status == GOT_STATUS_ADD ||
4052 staged_status == GOT_STATUS_MODIFY) {
4053 char *id_str;
4054 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4055 8192);
4056 if (err)
4057 goto done;
4058 err = got_object_id_str(&id_str, staged_blob_id);
4059 if (err)
4060 goto done;
4061 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4062 err = got_error_from_errno("asprintf");
4063 free(id_str);
4064 goto done;
4066 free(id_str);
4067 } else if (status != GOT_STATUS_ADD) {
4068 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4069 if (err)
4070 goto done;
4073 if (status != GOT_STATUS_DELETE) {
4074 if (asprintf(&abspath, "%s/%s",
4075 got_worktree_get_root_path(a->worktree), path) == -1) {
4076 err = got_error_from_errno("asprintf");
4077 goto done;
4080 if (dirfd != -1) {
4081 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
4082 if (fd == -1) {
4083 if (errno != ELOOP) {
4084 err = got_error_from_errno2("openat",
4085 abspath);
4086 goto done;
4088 err = get_symlink_target_file(&fd, dirfd,
4089 de_name, abspath);
4090 if (err)
4091 goto done;
4093 } else {
4094 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
4095 if (fd == -1) {
4096 if (errno != ELOOP) {
4097 err = got_error_from_errno2("open",
4098 abspath);
4099 goto done;
4101 err = get_symlink_target_file(&fd, dirfd,
4102 de_name, abspath);
4103 if (err)
4104 goto done;
4107 if (fstat(fd, &sb) == -1) {
4108 err = got_error_from_errno2("fstat", abspath);
4109 goto done;
4111 f2 = fdopen(fd, "r");
4112 if (f2 == NULL) {
4113 err = got_error_from_errno2("fdopen", abspath);
4114 goto done;
4116 fd = -1;
4117 } else
4118 sb.st_size = 0;
4120 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4121 a->diff_context, a->ignore_whitespace, stdout);
4122 done:
4123 if (blob1)
4124 got_object_blob_close(blob1);
4125 if (f2 && fclose(f2) == EOF && err == NULL)
4126 err = got_error_from_errno("fclose");
4127 if (fd != -1 && close(fd) == -1 && err == NULL)
4128 err = got_error_from_errno("close");
4129 free(abspath);
4130 return err;
4133 static const struct got_error *
4134 cmd_diff(int argc, char *argv[])
4136 const struct got_error *error;
4137 struct got_repository *repo = NULL;
4138 struct got_worktree *worktree = NULL;
4139 char *cwd = NULL, *repo_path = NULL;
4140 struct got_object_id *id1 = NULL, *id2 = NULL;
4141 const char *id_str1 = NULL, *id_str2 = NULL;
4142 char *label1 = NULL, *label2 = NULL;
4143 int type1, type2;
4144 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
4145 const char *errstr;
4146 char *path = NULL;
4148 #ifndef PROFILE
4149 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4150 NULL) == -1)
4151 err(1, "pledge");
4152 #endif
4154 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
4155 switch (ch) {
4156 case 'C':
4157 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4158 &errstr);
4159 if (errstr != NULL)
4160 err(1, "-C option %s", errstr);
4161 break;
4162 case 'r':
4163 repo_path = realpath(optarg, NULL);
4164 if (repo_path == NULL)
4165 return got_error_from_errno2("realpath",
4166 optarg);
4167 got_path_strip_trailing_slashes(repo_path);
4168 break;
4169 case 's':
4170 diff_staged = 1;
4171 break;
4172 case 'w':
4173 ignore_whitespace = 1;
4174 break;
4175 default:
4176 usage_diff();
4177 /* NOTREACHED */
4181 argc -= optind;
4182 argv += optind;
4184 cwd = getcwd(NULL, 0);
4185 if (cwd == NULL) {
4186 error = got_error_from_errno("getcwd");
4187 goto done;
4189 if (argc <= 1) {
4190 if (repo_path)
4191 errx(1,
4192 "-r option can't be used when diffing a work tree");
4193 error = got_worktree_open(&worktree, cwd);
4194 if (error) {
4195 if (error->code == GOT_ERR_NOT_WORKTREE)
4196 error = wrap_not_worktree_error(error, "diff",
4197 cwd);
4198 goto done;
4200 repo_path = strdup(got_worktree_get_repo_path(worktree));
4201 if (repo_path == NULL) {
4202 error = got_error_from_errno("strdup");
4203 goto done;
4205 if (argc == 1) {
4206 error = got_worktree_resolve_path(&path, worktree,
4207 argv[0]);
4208 if (error)
4209 goto done;
4210 } else {
4211 path = strdup("");
4212 if (path == NULL) {
4213 error = got_error_from_errno("strdup");
4214 goto done;
4217 } else if (argc == 2) {
4218 if (diff_staged)
4219 errx(1, "-s option can't be used when diffing "
4220 "objects in repository");
4221 id_str1 = argv[0];
4222 id_str2 = argv[1];
4223 if (repo_path == NULL) {
4224 error = got_worktree_open(&worktree, cwd);
4225 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4226 goto done;
4227 if (worktree) {
4228 repo_path = strdup(
4229 got_worktree_get_repo_path(worktree));
4230 if (repo_path == NULL) {
4231 error = got_error_from_errno("strdup");
4232 goto done;
4234 } else {
4235 repo_path = strdup(cwd);
4236 if (repo_path == NULL) {
4237 error = got_error_from_errno("strdup");
4238 goto done;
4242 } else
4243 usage_diff();
4245 error = got_repo_open(&repo, repo_path, NULL);
4246 free(repo_path);
4247 if (error != NULL)
4248 goto done;
4250 error = apply_unveil(got_repo_get_path(repo), 1,
4251 worktree ? got_worktree_get_root_path(worktree) : NULL);
4252 if (error)
4253 goto done;
4255 if (argc <= 1) {
4256 struct print_diff_arg arg;
4257 struct got_pathlist_head paths;
4258 char *id_str;
4260 TAILQ_INIT(&paths);
4262 error = got_object_id_str(&id_str,
4263 got_worktree_get_base_commit_id(worktree));
4264 if (error)
4265 goto done;
4266 arg.repo = repo;
4267 arg.worktree = worktree;
4268 arg.diff_context = diff_context;
4269 arg.id_str = id_str;
4270 arg.header_shown = 0;
4271 arg.diff_staged = diff_staged;
4272 arg.ignore_whitespace = ignore_whitespace;
4274 error = got_pathlist_append(&paths, path, NULL);
4275 if (error)
4276 goto done;
4278 error = got_worktree_status(worktree, &paths, repo, print_diff,
4279 &arg, check_cancelled, NULL);
4280 free(id_str);
4281 got_pathlist_free(&paths);
4282 goto done;
4285 error = got_repo_match_object_id(&id1, &label1, id_str1,
4286 GOT_OBJ_TYPE_ANY, 1, repo);
4287 if (error)
4288 goto done;
4290 error = got_repo_match_object_id(&id2, &label2, id_str2,
4291 GOT_OBJ_TYPE_ANY, 1, repo);
4292 if (error)
4293 goto done;
4295 error = got_object_get_type(&type1, repo, id1);
4296 if (error)
4297 goto done;
4299 error = got_object_get_type(&type2, repo, id2);
4300 if (error)
4301 goto done;
4303 if (type1 != type2) {
4304 error = got_error(GOT_ERR_OBJ_TYPE);
4305 goto done;
4308 switch (type1) {
4309 case GOT_OBJ_TYPE_BLOB:
4310 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
4311 diff_context, ignore_whitespace, repo, stdout);
4312 break;
4313 case GOT_OBJ_TYPE_TREE:
4314 error = got_diff_objects_as_trees(id1, id2, "", "",
4315 diff_context, ignore_whitespace, repo, stdout);
4316 break;
4317 case GOT_OBJ_TYPE_COMMIT:
4318 printf("diff %s %s\n", label1, label2);
4319 error = got_diff_objects_as_commits(id1, id2, diff_context,
4320 ignore_whitespace, repo, stdout);
4321 break;
4322 default:
4323 error = got_error(GOT_ERR_OBJ_TYPE);
4325 done:
4326 free(label1);
4327 free(label2);
4328 free(id1);
4329 free(id2);
4330 free(path);
4331 if (worktree)
4332 got_worktree_close(worktree);
4333 if (repo) {
4334 const struct got_error *repo_error;
4335 repo_error = got_repo_close(repo);
4336 if (error == NULL)
4337 error = repo_error;
4339 return error;
4342 __dead static void
4343 usage_blame(void)
4345 fprintf(stderr,
4346 "usage: %s blame [-c commit] [-r repository-path] path\n",
4347 getprogname());
4348 exit(1);
4351 struct blame_line {
4352 int annotated;
4353 char *id_str;
4354 char *committer;
4355 char datebuf[11]; /* YYYY-MM-DD + NUL */
4358 struct blame_cb_args {
4359 struct blame_line *lines;
4360 int nlines;
4361 int nlines_prec;
4362 int lineno_cur;
4363 off_t *line_offsets;
4364 FILE *f;
4365 struct got_repository *repo;
4368 static const struct got_error *
4369 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4371 const struct got_error *err = NULL;
4372 struct blame_cb_args *a = arg;
4373 struct blame_line *bline;
4374 char *line = NULL;
4375 size_t linesize = 0;
4376 struct got_commit_object *commit = NULL;
4377 off_t offset;
4378 struct tm tm;
4379 time_t committer_time;
4381 if (nlines != a->nlines ||
4382 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4383 return got_error(GOT_ERR_RANGE);
4385 if (sigint_received)
4386 return got_error(GOT_ERR_ITER_COMPLETED);
4388 if (lineno == -1)
4389 return NULL; /* no change in this commit */
4391 /* Annotate this line. */
4392 bline = &a->lines[lineno - 1];
4393 if (bline->annotated)
4394 return NULL;
4395 err = got_object_id_str(&bline->id_str, id);
4396 if (err)
4397 return err;
4399 err = got_object_open_as_commit(&commit, a->repo, id);
4400 if (err)
4401 goto done;
4403 bline->committer = strdup(got_object_commit_get_committer(commit));
4404 if (bline->committer == NULL) {
4405 err = got_error_from_errno("strdup");
4406 goto done;
4409 committer_time = got_object_commit_get_committer_time(commit);
4410 if (localtime_r(&committer_time, &tm) == NULL)
4411 return got_error_from_errno("localtime_r");
4412 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4413 &tm) >= sizeof(bline->datebuf)) {
4414 err = got_error(GOT_ERR_NO_SPACE);
4415 goto done;
4417 bline->annotated = 1;
4419 /* Print lines annotated so far. */
4420 bline = &a->lines[a->lineno_cur - 1];
4421 if (!bline->annotated)
4422 goto done;
4424 offset = a->line_offsets[a->lineno_cur - 1];
4425 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4426 err = got_error_from_errno("fseeko");
4427 goto done;
4430 while (bline->annotated) {
4431 char *smallerthan, *at, *nl, *committer;
4432 size_t len;
4434 if (getline(&line, &linesize, a->f) == -1) {
4435 if (ferror(a->f))
4436 err = got_error_from_errno("getline");
4437 break;
4440 committer = bline->committer;
4441 smallerthan = strchr(committer, '<');
4442 if (smallerthan && smallerthan[1] != '\0')
4443 committer = smallerthan + 1;
4444 at = strchr(committer, '@');
4445 if (at)
4446 *at = '\0';
4447 len = strlen(committer);
4448 if (len >= 9)
4449 committer[8] = '\0';
4451 nl = strchr(line, '\n');
4452 if (nl)
4453 *nl = '\0';
4454 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4455 bline->id_str, bline->datebuf, committer, line);
4457 a->lineno_cur++;
4458 bline = &a->lines[a->lineno_cur - 1];
4460 done:
4461 if (commit)
4462 got_object_commit_close(commit);
4463 free(line);
4464 return err;
4467 static const struct got_error *
4468 cmd_blame(int argc, char *argv[])
4470 const struct got_error *error;
4471 struct got_repository *repo = NULL;
4472 struct got_worktree *worktree = NULL;
4473 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4474 char *link_target = NULL;
4475 struct got_object_id *obj_id = NULL;
4476 struct got_object_id *commit_id = NULL;
4477 struct got_blob_object *blob = NULL;
4478 char *commit_id_str = NULL;
4479 struct blame_cb_args bca;
4480 int ch, obj_type, i;
4481 size_t filesize;
4483 memset(&bca, 0, sizeof(bca));
4485 #ifndef PROFILE
4486 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4487 NULL) == -1)
4488 err(1, "pledge");
4489 #endif
4491 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4492 switch (ch) {
4493 case 'c':
4494 commit_id_str = optarg;
4495 break;
4496 case 'r':
4497 repo_path = realpath(optarg, NULL);
4498 if (repo_path == NULL)
4499 return got_error_from_errno2("realpath",
4500 optarg);
4501 got_path_strip_trailing_slashes(repo_path);
4502 break;
4503 default:
4504 usage_blame();
4505 /* NOTREACHED */
4509 argc -= optind;
4510 argv += optind;
4512 if (argc == 1)
4513 path = argv[0];
4514 else
4515 usage_blame();
4517 cwd = getcwd(NULL, 0);
4518 if (cwd == NULL) {
4519 error = got_error_from_errno("getcwd");
4520 goto done;
4522 if (repo_path == NULL) {
4523 error = got_worktree_open(&worktree, cwd);
4524 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4525 goto done;
4526 else
4527 error = NULL;
4528 if (worktree) {
4529 repo_path =
4530 strdup(got_worktree_get_repo_path(worktree));
4531 if (repo_path == NULL) {
4532 error = got_error_from_errno("strdup");
4533 if (error)
4534 goto done;
4536 } else {
4537 repo_path = strdup(cwd);
4538 if (repo_path == NULL) {
4539 error = got_error_from_errno("strdup");
4540 goto done;
4545 error = got_repo_open(&repo, repo_path, NULL);
4546 if (error != NULL)
4547 goto done;
4549 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4550 if (error)
4551 goto done;
4553 if (worktree) {
4554 const char *prefix = got_worktree_get_path_prefix(worktree);
4555 char *p, *worktree_subdir = cwd +
4556 strlen(got_worktree_get_root_path(worktree));
4557 if (asprintf(&p, "%s%s%s%s%s",
4558 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
4559 worktree_subdir, worktree_subdir[0] ? "/" : "",
4560 path) == -1) {
4561 error = got_error_from_errno("asprintf");
4562 goto done;
4564 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4565 free(p);
4566 } else {
4567 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4569 if (error)
4570 goto done;
4572 if (commit_id_str == NULL) {
4573 struct got_reference *head_ref;
4574 error = got_ref_open(&head_ref, repo, worktree ?
4575 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4576 if (error != NULL)
4577 goto done;
4578 error = got_ref_resolve(&commit_id, repo, head_ref);
4579 got_ref_close(head_ref);
4580 if (error != NULL)
4581 goto done;
4582 } else {
4583 error = got_repo_match_object_id(&commit_id, NULL,
4584 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4585 if (error)
4586 goto done;
4589 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4590 commit_id, repo);
4591 if (error)
4592 goto done;
4594 error = got_object_id_by_path(&obj_id, repo, commit_id,
4595 link_target ? link_target : in_repo_path);
4596 if (error)
4597 goto done;
4599 error = got_object_get_type(&obj_type, repo, obj_id);
4600 if (error)
4601 goto done;
4603 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4604 error = got_error_path(link_target ? link_target : in_repo_path,
4605 GOT_ERR_OBJ_TYPE);
4606 goto done;
4609 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4610 if (error)
4611 goto done;
4612 bca.f = got_opentemp();
4613 if (bca.f == NULL) {
4614 error = got_error_from_errno("got_opentemp");
4615 goto done;
4617 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4618 &bca.line_offsets, bca.f, blob);
4619 if (error || bca.nlines == 0)
4620 goto done;
4622 /* Don't include \n at EOF in the blame line count. */
4623 if (bca.line_offsets[bca.nlines - 1] == filesize)
4624 bca.nlines--;
4626 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4627 if (bca.lines == NULL) {
4628 error = got_error_from_errno("calloc");
4629 goto done;
4631 bca.lineno_cur = 1;
4632 bca.nlines_prec = 0;
4633 i = bca.nlines;
4634 while (i > 0) {
4635 i /= 10;
4636 bca.nlines_prec++;
4638 bca.repo = repo;
4640 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4641 repo, blame_cb, &bca, check_cancelled, NULL);
4642 done:
4643 free(in_repo_path);
4644 free(link_target);
4645 free(repo_path);
4646 free(cwd);
4647 free(commit_id);
4648 free(obj_id);
4649 if (blob)
4650 got_object_blob_close(blob);
4651 if (worktree)
4652 got_worktree_close(worktree);
4653 if (repo) {
4654 const struct got_error *repo_error;
4655 repo_error = got_repo_close(repo);
4656 if (error == NULL)
4657 error = repo_error;
4659 if (bca.lines) {
4660 for (i = 0; i < bca.nlines; i++) {
4661 struct blame_line *bline = &bca.lines[i];
4662 free(bline->id_str);
4663 free(bline->committer);
4665 free(bca.lines);
4667 free(bca.line_offsets);
4668 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4669 error = got_error_from_errno("fclose");
4670 return error;
4673 __dead static void
4674 usage_tree(void)
4676 fprintf(stderr,
4677 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4678 getprogname());
4679 exit(1);
4682 static const struct got_error *
4683 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4684 const char *root_path, struct got_repository *repo)
4686 const struct got_error *err = NULL;
4687 int is_root_path = (strcmp(path, root_path) == 0);
4688 const char *modestr = "";
4689 mode_t mode = got_tree_entry_get_mode(te);
4690 char *link_target = NULL;
4692 path += strlen(root_path);
4693 while (path[0] == '/')
4694 path++;
4696 if (got_object_tree_entry_is_submodule(te))
4697 modestr = "$";
4698 else if (S_ISLNK(mode)) {
4699 int i;
4701 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4702 if (err)
4703 return err;
4704 for (i = 0; i < strlen(link_target); i++) {
4705 if (!isprint((unsigned char)link_target[i]))
4706 link_target[i] = '?';
4709 modestr = "@";
4711 else if (S_ISDIR(mode))
4712 modestr = "/";
4713 else if (mode & S_IXUSR)
4714 modestr = "*";
4716 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4717 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4718 link_target ? " -> ": "", link_target ? link_target : "");
4720 free(link_target);
4721 return NULL;
4724 static const struct got_error *
4725 print_tree(const char *path, struct got_object_id *commit_id,
4726 int show_ids, int recurse, const char *root_path,
4727 struct got_repository *repo)
4729 const struct got_error *err = NULL;
4730 struct got_object_id *tree_id = NULL;
4731 struct got_tree_object *tree = NULL;
4732 int nentries, i;
4734 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4735 if (err)
4736 goto done;
4738 err = got_object_open_as_tree(&tree, repo, tree_id);
4739 if (err)
4740 goto done;
4741 nentries = got_object_tree_get_nentries(tree);
4742 for (i = 0; i < nentries; i++) {
4743 struct got_tree_entry *te;
4744 char *id = NULL;
4746 if (sigint_received || sigpipe_received)
4747 break;
4749 te = got_object_tree_get_entry(tree, i);
4750 if (show_ids) {
4751 char *id_str;
4752 err = got_object_id_str(&id_str,
4753 got_tree_entry_get_id(te));
4754 if (err)
4755 goto done;
4756 if (asprintf(&id, "%s ", id_str) == -1) {
4757 err = got_error_from_errno("asprintf");
4758 free(id_str);
4759 goto done;
4761 free(id_str);
4763 err = print_entry(te, id, path, root_path, repo);
4764 free(id);
4765 if (err)
4766 goto done;
4768 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4769 char *child_path;
4770 if (asprintf(&child_path, "%s%s%s", path,
4771 path[0] == '/' && path[1] == '\0' ? "" : "/",
4772 got_tree_entry_get_name(te)) == -1) {
4773 err = got_error_from_errno("asprintf");
4774 goto done;
4776 err = print_tree(child_path, commit_id, show_ids, 1,
4777 root_path, repo);
4778 free(child_path);
4779 if (err)
4780 goto done;
4783 done:
4784 if (tree)
4785 got_object_tree_close(tree);
4786 free(tree_id);
4787 return err;
4790 static const struct got_error *
4791 cmd_tree(int argc, char *argv[])
4793 const struct got_error *error;
4794 struct got_repository *repo = NULL;
4795 struct got_worktree *worktree = NULL;
4796 const char *path, *refname = NULL;
4797 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4798 struct got_object_id *commit_id = NULL;
4799 char *commit_id_str = NULL;
4800 int show_ids = 0, recurse = 0;
4801 int ch;
4803 #ifndef PROFILE
4804 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4805 NULL) == -1)
4806 err(1, "pledge");
4807 #endif
4809 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4810 switch (ch) {
4811 case 'c':
4812 commit_id_str = optarg;
4813 break;
4814 case 'r':
4815 repo_path = realpath(optarg, NULL);
4816 if (repo_path == NULL)
4817 return got_error_from_errno2("realpath",
4818 optarg);
4819 got_path_strip_trailing_slashes(repo_path);
4820 break;
4821 case 'i':
4822 show_ids = 1;
4823 break;
4824 case 'R':
4825 recurse = 1;
4826 break;
4827 default:
4828 usage_tree();
4829 /* NOTREACHED */
4833 argc -= optind;
4834 argv += optind;
4836 if (argc == 1)
4837 path = argv[0];
4838 else if (argc > 1)
4839 usage_tree();
4840 else
4841 path = NULL;
4843 cwd = getcwd(NULL, 0);
4844 if (cwd == NULL) {
4845 error = got_error_from_errno("getcwd");
4846 goto done;
4848 if (repo_path == NULL) {
4849 error = got_worktree_open(&worktree, cwd);
4850 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4851 goto done;
4852 else
4853 error = NULL;
4854 if (worktree) {
4855 repo_path =
4856 strdup(got_worktree_get_repo_path(worktree));
4857 if (repo_path == NULL)
4858 error = got_error_from_errno("strdup");
4859 if (error)
4860 goto done;
4861 } else {
4862 repo_path = strdup(cwd);
4863 if (repo_path == NULL) {
4864 error = got_error_from_errno("strdup");
4865 goto done;
4870 error = got_repo_open(&repo, repo_path, NULL);
4871 if (error != NULL)
4872 goto done;
4874 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4875 if (error)
4876 goto done;
4878 if (path == NULL) {
4879 if (worktree) {
4880 char *p, *worktree_subdir = cwd +
4881 strlen(got_worktree_get_root_path(worktree));
4882 if (asprintf(&p, "%s/%s",
4883 got_worktree_get_path_prefix(worktree),
4884 worktree_subdir) == -1) {
4885 error = got_error_from_errno("asprintf");
4886 goto done;
4888 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4889 free(p);
4890 if (error)
4891 goto done;
4892 } else
4893 path = "/";
4895 if (in_repo_path == NULL) {
4896 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4897 if (error != NULL)
4898 goto done;
4901 if (commit_id_str == NULL) {
4902 struct got_reference *head_ref;
4903 if (worktree)
4904 refname = got_worktree_get_head_ref_name(worktree);
4905 else
4906 refname = GOT_REF_HEAD;
4907 error = got_ref_open(&head_ref, repo, refname, 0);
4908 if (error != NULL)
4909 goto done;
4910 error = got_ref_resolve(&commit_id, repo, head_ref);
4911 got_ref_close(head_ref);
4912 if (error != NULL)
4913 goto done;
4914 } else {
4915 error = got_repo_match_object_id(&commit_id, NULL,
4916 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4917 if (error)
4918 goto done;
4921 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4922 in_repo_path, repo);
4923 done:
4924 free(in_repo_path);
4925 free(repo_path);
4926 free(cwd);
4927 free(commit_id);
4928 if (worktree)
4929 got_worktree_close(worktree);
4930 if (repo) {
4931 const struct got_error *repo_error;
4932 repo_error = got_repo_close(repo);
4933 if (error == NULL)
4934 error = repo_error;
4936 return error;
4939 __dead static void
4940 usage_status(void)
4942 fprintf(stderr, "usage: %s status [-s status-codes ] [path ...]\n",
4943 getprogname());
4944 exit(1);
4947 static const struct got_error *
4948 print_status(void *arg, unsigned char status, unsigned char staged_status,
4949 const char *path, struct got_object_id *blob_id,
4950 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4951 int dirfd, const char *de_name)
4953 if (status == staged_status && (status == GOT_STATUS_DELETE))
4954 status = GOT_STATUS_NO_CHANGE;
4955 if (arg) {
4956 char *status_codes = arg;
4957 size_t ncodes = strlen(status_codes);
4958 int i;
4959 for (i = 0; i < ncodes ; i++) {
4960 if (status == status_codes[i] ||
4961 staged_status == status_codes[i])
4962 break;
4964 if (i == ncodes)
4965 return NULL;
4967 printf("%c%c %s\n", status, staged_status, path);
4968 return NULL;
4971 static const struct got_error *
4972 cmd_status(int argc, char *argv[])
4974 const struct got_error *error = NULL;
4975 struct got_repository *repo = NULL;
4976 struct got_worktree *worktree = NULL;
4977 char *cwd = NULL, *status_codes = NULL;;
4978 struct got_pathlist_head paths;
4979 struct got_pathlist_entry *pe;
4980 int ch, i;
4982 TAILQ_INIT(&paths);
4984 while ((ch = getopt(argc, argv, "s:")) != -1) {
4985 switch (ch) {
4986 case 's':
4987 for (i = 0; i < strlen(optarg); i++) {
4988 switch (optarg[i]) {
4989 case GOT_STATUS_MODIFY:
4990 case GOT_STATUS_ADD:
4991 case GOT_STATUS_DELETE:
4992 case GOT_STATUS_CONFLICT:
4993 case GOT_STATUS_MISSING:
4994 case GOT_STATUS_OBSTRUCTED:
4995 case GOT_STATUS_UNVERSIONED:
4996 case GOT_STATUS_MODE_CHANGE:
4997 case GOT_STATUS_NONEXISTENT:
4998 break;
4999 default:
5000 errx(1, "invalid status code '%c'",
5001 optarg[i]);
5004 status_codes = optarg;
5005 break;
5006 default:
5007 usage_status();
5008 /* NOTREACHED */
5012 argc -= optind;
5013 argv += optind;
5015 #ifndef PROFILE
5016 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5017 NULL) == -1)
5018 err(1, "pledge");
5019 #endif
5020 cwd = getcwd(NULL, 0);
5021 if (cwd == NULL) {
5022 error = got_error_from_errno("getcwd");
5023 goto done;
5026 error = got_worktree_open(&worktree, cwd);
5027 if (error) {
5028 if (error->code == GOT_ERR_NOT_WORKTREE)
5029 error = wrap_not_worktree_error(error, "status", cwd);
5030 goto done;
5033 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5034 NULL);
5035 if (error != NULL)
5036 goto done;
5038 error = apply_unveil(got_repo_get_path(repo), 1,
5039 got_worktree_get_root_path(worktree));
5040 if (error)
5041 goto done;
5043 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5044 if (error)
5045 goto done;
5047 error = got_worktree_status(worktree, &paths, repo, print_status,
5048 status_codes, check_cancelled, NULL);
5049 done:
5050 TAILQ_FOREACH(pe, &paths, entry)
5051 free((char *)pe->path);
5052 got_pathlist_free(&paths);
5053 free(cwd);
5054 return error;
5057 __dead static void
5058 usage_ref(void)
5060 fprintf(stderr,
5061 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
5062 "[-d] [name]\n",
5063 getprogname());
5064 exit(1);
5067 static const struct got_error *
5068 list_refs(struct got_repository *repo, const char *refname)
5070 static const struct got_error *err = NULL;
5071 struct got_reflist_head refs;
5072 struct got_reflist_entry *re;
5074 SIMPLEQ_INIT(&refs);
5075 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
5076 if (err)
5077 return err;
5079 SIMPLEQ_FOREACH(re, &refs, entry) {
5080 char *refstr;
5081 refstr = got_ref_to_str(re->ref);
5082 if (refstr == NULL)
5083 return got_error_from_errno("got_ref_to_str");
5084 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5085 free(refstr);
5088 got_ref_list_free(&refs);
5089 return NULL;
5092 static const struct got_error *
5093 delete_ref(struct got_repository *repo, const char *refname)
5095 const struct got_error *err = NULL;
5096 struct got_reference *ref;
5098 err = got_ref_open(&ref, repo, refname, 0);
5099 if (err)
5100 return err;
5102 err = got_ref_delete(ref, repo);
5103 got_ref_close(ref);
5104 return err;
5107 static const struct got_error *
5108 add_ref(struct got_repository *repo, const char *refname, const char *target)
5110 const struct got_error *err = NULL;
5111 struct got_object_id *id;
5112 struct got_reference *ref = NULL;
5115 * Don't let the user create a reference name with a leading '-'.
5116 * While technically a valid reference name, this case is usually
5117 * an unintended typo.
5119 if (refname[0] == '-')
5120 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5122 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5123 repo);
5124 if (err) {
5125 struct got_reference *target_ref;
5127 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5128 return err;
5129 err = got_ref_open(&target_ref, repo, target, 0);
5130 if (err)
5131 return err;
5132 err = got_ref_resolve(&id, repo, target_ref);
5133 got_ref_close(target_ref);
5134 if (err)
5135 return err;
5138 err = got_ref_alloc(&ref, refname, id);
5139 if (err)
5140 goto done;
5142 err = got_ref_write(ref, repo);
5143 done:
5144 if (ref)
5145 got_ref_close(ref);
5146 free(id);
5147 return err;
5150 static const struct got_error *
5151 add_symref(struct got_repository *repo, const char *refname, const char *target)
5153 const struct got_error *err = NULL;
5154 struct got_reference *ref = NULL;
5155 struct got_reference *target_ref = NULL;
5158 * Don't let the user create a reference name with a leading '-'.
5159 * While technically a valid reference name, this case is usually
5160 * an unintended typo.
5162 if (refname[0] == '-')
5163 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5165 err = got_ref_open(&target_ref, repo, target, 0);
5166 if (err)
5167 return err;
5169 err = got_ref_alloc_symref(&ref, refname, target_ref);
5170 if (err)
5171 goto done;
5173 err = got_ref_write(ref, repo);
5174 done:
5175 if (target_ref)
5176 got_ref_close(target_ref);
5177 if (ref)
5178 got_ref_close(ref);
5179 return err;
5182 static const struct got_error *
5183 cmd_ref(int argc, char *argv[])
5185 const struct got_error *error = NULL;
5186 struct got_repository *repo = NULL;
5187 struct got_worktree *worktree = NULL;
5188 char *cwd = NULL, *repo_path = NULL;
5189 int ch, do_list = 0, do_delete = 0;
5190 const char *obj_arg = NULL, *symref_target= NULL;
5191 char *refname = NULL;
5193 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5194 switch (ch) {
5195 case 'c':
5196 obj_arg = optarg;
5197 break;
5198 case 'd':
5199 do_delete = 1;
5200 break;
5201 case 'r':
5202 repo_path = realpath(optarg, NULL);
5203 if (repo_path == NULL)
5204 return got_error_from_errno2("realpath",
5205 optarg);
5206 got_path_strip_trailing_slashes(repo_path);
5207 break;
5208 case 'l':
5209 do_list = 1;
5210 break;
5211 case 's':
5212 symref_target = optarg;
5213 break;
5214 default:
5215 usage_ref();
5216 /* NOTREACHED */
5220 if (obj_arg && do_list)
5221 errx(1, "-c and -l options are mutually exclusive");
5222 if (obj_arg && do_delete)
5223 errx(1, "-c and -d options are mutually exclusive");
5224 if (obj_arg && symref_target)
5225 errx(1, "-c and -s options are mutually exclusive");
5226 if (symref_target && do_delete)
5227 errx(1, "-s and -d options are mutually exclusive");
5228 if (symref_target && do_list)
5229 errx(1, "-s and -l options are mutually exclusive");
5230 if (do_delete && do_list)
5231 errx(1, "-d and -l options are mutually exclusive");
5233 argc -= optind;
5234 argv += optind;
5236 if (do_list) {
5237 if (argc != 0 && argc != 1)
5238 usage_ref();
5239 if (argc == 1) {
5240 refname = strdup(argv[0]);
5241 if (refname == NULL) {
5242 error = got_error_from_errno("strdup");
5243 goto done;
5246 } else {
5247 if (argc != 1)
5248 usage_ref();
5249 refname = strdup(argv[0]);
5250 if (refname == NULL) {
5251 error = got_error_from_errno("strdup");
5252 goto done;
5256 if (refname)
5257 got_path_strip_trailing_slashes(refname);
5259 #ifndef PROFILE
5260 if (do_list) {
5261 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5262 NULL) == -1)
5263 err(1, "pledge");
5264 } else {
5265 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5266 "sendfd unveil", NULL) == -1)
5267 err(1, "pledge");
5269 #endif
5270 cwd = getcwd(NULL, 0);
5271 if (cwd == NULL) {
5272 error = got_error_from_errno("getcwd");
5273 goto done;
5276 if (repo_path == NULL) {
5277 error = got_worktree_open(&worktree, cwd);
5278 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5279 goto done;
5280 else
5281 error = NULL;
5282 if (worktree) {
5283 repo_path =
5284 strdup(got_worktree_get_repo_path(worktree));
5285 if (repo_path == NULL)
5286 error = got_error_from_errno("strdup");
5287 if (error)
5288 goto done;
5289 } else {
5290 repo_path = strdup(cwd);
5291 if (repo_path == NULL) {
5292 error = got_error_from_errno("strdup");
5293 goto done;
5298 error = got_repo_open(&repo, repo_path, NULL);
5299 if (error != NULL)
5300 goto done;
5302 error = apply_unveil(got_repo_get_path(repo), do_list,
5303 worktree ? got_worktree_get_root_path(worktree) : NULL);
5304 if (error)
5305 goto done;
5307 if (do_list)
5308 error = list_refs(repo, refname);
5309 else if (do_delete)
5310 error = delete_ref(repo, refname);
5311 else if (symref_target)
5312 error = add_symref(repo, refname, symref_target);
5313 else {
5314 if (obj_arg == NULL)
5315 usage_ref();
5316 error = add_ref(repo, refname, obj_arg);
5318 done:
5319 free(refname);
5320 if (repo)
5321 got_repo_close(repo);
5322 if (worktree)
5323 got_worktree_close(worktree);
5324 free(cwd);
5325 free(repo_path);
5326 return error;
5329 __dead static void
5330 usage_branch(void)
5332 fprintf(stderr,
5333 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5334 "[name]\n", getprogname());
5335 exit(1);
5338 static const struct got_error *
5339 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5340 struct got_reference *ref)
5342 const struct got_error *err = NULL;
5343 const char *refname, *marker = " ";
5344 char *refstr;
5346 refname = got_ref_get_name(ref);
5347 if (worktree && strcmp(refname,
5348 got_worktree_get_head_ref_name(worktree)) == 0) {
5349 struct got_object_id *id = NULL;
5351 err = got_ref_resolve(&id, repo, ref);
5352 if (err)
5353 return err;
5354 if (got_object_id_cmp(id,
5355 got_worktree_get_base_commit_id(worktree)) == 0)
5356 marker = "* ";
5357 else
5358 marker = "~ ";
5359 free(id);
5362 if (strncmp(refname, "refs/heads/", 11) == 0)
5363 refname += 11;
5364 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5365 refname += 18;
5367 refstr = got_ref_to_str(ref);
5368 if (refstr == NULL)
5369 return got_error_from_errno("got_ref_to_str");
5371 printf("%s%s: %s\n", marker, refname, refstr);
5372 free(refstr);
5373 return NULL;
5376 static const struct got_error *
5377 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5379 const char *refname;
5381 if (worktree == NULL)
5382 return got_error(GOT_ERR_NOT_WORKTREE);
5384 refname = got_worktree_get_head_ref_name(worktree);
5386 if (strncmp(refname, "refs/heads/", 11) == 0)
5387 refname += 11;
5388 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5389 refname += 18;
5391 printf("%s\n", refname);
5393 return NULL;
5396 static const struct got_error *
5397 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5399 static const struct got_error *err = NULL;
5400 struct got_reflist_head refs;
5401 struct got_reflist_entry *re;
5402 struct got_reference *temp_ref = NULL;
5403 int rebase_in_progress, histedit_in_progress;
5405 SIMPLEQ_INIT(&refs);
5407 if (worktree) {
5408 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5409 worktree);
5410 if (err)
5411 return err;
5413 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5414 worktree);
5415 if (err)
5416 return err;
5418 if (rebase_in_progress || histedit_in_progress) {
5419 err = got_ref_open(&temp_ref, repo,
5420 got_worktree_get_head_ref_name(worktree), 0);
5421 if (err)
5422 return err;
5423 list_branch(repo, worktree, temp_ref);
5424 got_ref_close(temp_ref);
5428 err = got_ref_list(&refs, repo, "refs/heads",
5429 got_ref_cmp_by_name, NULL);
5430 if (err)
5431 return err;
5433 SIMPLEQ_FOREACH(re, &refs, entry)
5434 list_branch(repo, worktree, re->ref);
5436 got_ref_list_free(&refs);
5437 return NULL;
5440 static const struct got_error *
5441 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5442 const char *branch_name)
5444 const struct got_error *err = NULL;
5445 struct got_reference *ref = NULL;
5446 char *refname;
5448 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5449 return got_error_from_errno("asprintf");
5451 err = got_ref_open(&ref, repo, refname, 0);
5452 if (err)
5453 goto done;
5455 if (worktree &&
5456 strcmp(got_worktree_get_head_ref_name(worktree),
5457 got_ref_get_name(ref)) == 0) {
5458 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5459 "will not delete this work tree's current branch");
5460 goto done;
5463 err = got_ref_delete(ref, repo);
5464 done:
5465 if (ref)
5466 got_ref_close(ref);
5467 free(refname);
5468 return err;
5471 static const struct got_error *
5472 add_branch(struct got_repository *repo, const char *branch_name,
5473 struct got_object_id *base_commit_id)
5475 const struct got_error *err = NULL;
5476 struct got_reference *ref = NULL;
5477 char *base_refname = NULL, *refname = NULL;
5480 * Don't let the user create a branch name with a leading '-'.
5481 * While technically a valid reference name, this case is usually
5482 * an unintended typo.
5484 if (branch_name[0] == '-')
5485 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5487 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5488 err = got_error_from_errno("asprintf");
5489 goto done;
5492 err = got_ref_open(&ref, repo, refname, 0);
5493 if (err == NULL) {
5494 err = got_error(GOT_ERR_BRANCH_EXISTS);
5495 goto done;
5496 } else if (err->code != GOT_ERR_NOT_REF)
5497 goto done;
5499 err = got_ref_alloc(&ref, refname, base_commit_id);
5500 if (err)
5501 goto done;
5503 err = got_ref_write(ref, repo);
5504 done:
5505 if (ref)
5506 got_ref_close(ref);
5507 free(base_refname);
5508 free(refname);
5509 return err;
5512 static const struct got_error *
5513 cmd_branch(int argc, char *argv[])
5515 const struct got_error *error = NULL;
5516 struct got_repository *repo = NULL;
5517 struct got_worktree *worktree = NULL;
5518 char *cwd = NULL, *repo_path = NULL;
5519 int ch, do_list = 0, do_show = 0, do_update = 1;
5520 const char *delref = NULL, *commit_id_arg = NULL;
5521 struct got_reference *ref = NULL;
5522 struct got_pathlist_head paths;
5523 struct got_pathlist_entry *pe;
5524 struct got_object_id *commit_id = NULL;
5525 char *commit_id_str = NULL;
5527 TAILQ_INIT(&paths);
5529 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5530 switch (ch) {
5531 case 'c':
5532 commit_id_arg = optarg;
5533 break;
5534 case 'd':
5535 delref = optarg;
5536 break;
5537 case 'r':
5538 repo_path = realpath(optarg, NULL);
5539 if (repo_path == NULL)
5540 return got_error_from_errno2("realpath",
5541 optarg);
5542 got_path_strip_trailing_slashes(repo_path);
5543 break;
5544 case 'l':
5545 do_list = 1;
5546 break;
5547 case 'n':
5548 do_update = 0;
5549 break;
5550 default:
5551 usage_branch();
5552 /* NOTREACHED */
5556 if (do_list && delref)
5557 errx(1, "-l and -d options are mutually exclusive");
5559 argc -= optind;
5560 argv += optind;
5562 if (!do_list && !delref && argc == 0)
5563 do_show = 1;
5565 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5566 errx(1, "-c option can only be used when creating a branch");
5568 if (do_list || delref) {
5569 if (argc > 0)
5570 usage_branch();
5571 } else if (!do_show && argc != 1)
5572 usage_branch();
5574 #ifndef PROFILE
5575 if (do_list || do_show) {
5576 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5577 NULL) == -1)
5578 err(1, "pledge");
5579 } else {
5580 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5581 "sendfd unveil", NULL) == -1)
5582 err(1, "pledge");
5584 #endif
5585 cwd = getcwd(NULL, 0);
5586 if (cwd == NULL) {
5587 error = got_error_from_errno("getcwd");
5588 goto done;
5591 if (repo_path == NULL) {
5592 error = got_worktree_open(&worktree, cwd);
5593 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5594 goto done;
5595 else
5596 error = NULL;
5597 if (worktree) {
5598 repo_path =
5599 strdup(got_worktree_get_repo_path(worktree));
5600 if (repo_path == NULL)
5601 error = got_error_from_errno("strdup");
5602 if (error)
5603 goto done;
5604 } else {
5605 repo_path = strdup(cwd);
5606 if (repo_path == NULL) {
5607 error = got_error_from_errno("strdup");
5608 goto done;
5613 error = got_repo_open(&repo, repo_path, NULL);
5614 if (error != NULL)
5615 goto done;
5617 error = apply_unveil(got_repo_get_path(repo), do_list,
5618 worktree ? got_worktree_get_root_path(worktree) : NULL);
5619 if (error)
5620 goto done;
5622 if (do_show)
5623 error = show_current_branch(repo, worktree);
5624 else if (do_list)
5625 error = list_branches(repo, worktree);
5626 else if (delref)
5627 error = delete_branch(repo, worktree, delref);
5628 else {
5629 if (commit_id_arg == NULL)
5630 commit_id_arg = worktree ?
5631 got_worktree_get_head_ref_name(worktree) :
5632 GOT_REF_HEAD;
5633 error = got_repo_match_object_id(&commit_id, NULL,
5634 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5635 if (error)
5636 goto done;
5637 error = add_branch(repo, argv[0], commit_id);
5638 if (error)
5639 goto done;
5640 if (worktree && do_update) {
5641 struct got_update_progress_arg upa;
5642 char *branch_refname = NULL;
5644 error = got_object_id_str(&commit_id_str, commit_id);
5645 if (error)
5646 goto done;
5647 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5648 worktree);
5649 if (error)
5650 goto done;
5651 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5652 == -1) {
5653 error = got_error_from_errno("asprintf");
5654 goto done;
5656 error = got_ref_open(&ref, repo, branch_refname, 0);
5657 free(branch_refname);
5658 if (error)
5659 goto done;
5660 error = switch_head_ref(ref, commit_id, worktree,
5661 repo);
5662 if (error)
5663 goto done;
5664 error = got_worktree_set_base_commit_id(worktree, repo,
5665 commit_id);
5666 if (error)
5667 goto done;
5668 memset(&upa, 0, sizeof(upa));
5669 error = got_worktree_checkout_files(worktree, &paths,
5670 repo, update_progress, &upa, check_cancelled,
5671 NULL);
5672 if (error)
5673 goto done;
5674 if (upa.did_something)
5675 printf("Updated to commit %s\n", commit_id_str);
5676 print_update_progress_stats(&upa);
5679 done:
5680 if (ref)
5681 got_ref_close(ref);
5682 if (repo)
5683 got_repo_close(repo);
5684 if (worktree)
5685 got_worktree_close(worktree);
5686 free(cwd);
5687 free(repo_path);
5688 free(commit_id);
5689 free(commit_id_str);
5690 TAILQ_FOREACH(pe, &paths, entry)
5691 free((char *)pe->path);
5692 got_pathlist_free(&paths);
5693 return error;
5697 __dead static void
5698 usage_tag(void)
5700 fprintf(stderr,
5701 "usage: %s tag [-c commit] [-r repository] [-l] "
5702 "[-m message] name\n", getprogname());
5703 exit(1);
5706 #if 0
5707 static const struct got_error *
5708 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5710 const struct got_error *err = NULL;
5711 struct got_reflist_entry *re, *se, *new;
5712 struct got_object_id *re_id, *se_id;
5713 struct got_tag_object *re_tag, *se_tag;
5714 time_t re_time, se_time;
5716 SIMPLEQ_FOREACH(re, tags, entry) {
5717 se = SIMPLEQ_FIRST(sorted);
5718 if (se == NULL) {
5719 err = got_reflist_entry_dup(&new, re);
5720 if (err)
5721 return err;
5722 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5723 continue;
5724 } else {
5725 err = got_ref_resolve(&re_id, repo, re->ref);
5726 if (err)
5727 break;
5728 err = got_object_open_as_tag(&re_tag, repo, re_id);
5729 free(re_id);
5730 if (err)
5731 break;
5732 re_time = got_object_tag_get_tagger_time(re_tag);
5733 got_object_tag_close(re_tag);
5736 while (se) {
5737 err = got_ref_resolve(&se_id, repo, re->ref);
5738 if (err)
5739 break;
5740 err = got_object_open_as_tag(&se_tag, repo, se_id);
5741 free(se_id);
5742 if (err)
5743 break;
5744 se_time = got_object_tag_get_tagger_time(se_tag);
5745 got_object_tag_close(se_tag);
5747 if (se_time > re_time) {
5748 err = got_reflist_entry_dup(&new, re);
5749 if (err)
5750 return err;
5751 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5752 break;
5754 se = SIMPLEQ_NEXT(se, entry);
5755 continue;
5758 done:
5759 return err;
5761 #endif
5763 static const struct got_error *
5764 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5766 static const struct got_error *err = NULL;
5767 struct got_reflist_head refs;
5768 struct got_reflist_entry *re;
5770 SIMPLEQ_INIT(&refs);
5772 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5773 if (err)
5774 return err;
5776 SIMPLEQ_FOREACH(re, &refs, entry) {
5777 const char *refname;
5778 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5779 char datebuf[26];
5780 const char *tagger;
5781 time_t tagger_time;
5782 struct got_object_id *id;
5783 struct got_tag_object *tag;
5784 struct got_commit_object *commit = NULL;
5786 refname = got_ref_get_name(re->ref);
5787 if (strncmp(refname, "refs/tags/", 10) != 0)
5788 continue;
5789 refname += 10;
5790 refstr = got_ref_to_str(re->ref);
5791 if (refstr == NULL) {
5792 err = got_error_from_errno("got_ref_to_str");
5793 break;
5795 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5796 free(refstr);
5798 err = got_ref_resolve(&id, repo, re->ref);
5799 if (err)
5800 break;
5801 err = got_object_open_as_tag(&tag, repo, id);
5802 if (err) {
5803 if (err->code != GOT_ERR_OBJ_TYPE) {
5804 free(id);
5805 break;
5807 /* "lightweight" tag */
5808 err = got_object_open_as_commit(&commit, repo, id);
5809 if (err) {
5810 free(id);
5811 break;
5813 tagger = got_object_commit_get_committer(commit);
5814 tagger_time =
5815 got_object_commit_get_committer_time(commit);
5816 err = got_object_id_str(&id_str, id);
5817 free(id);
5818 if (err)
5819 break;
5820 } else {
5821 free(id);
5822 tagger = got_object_tag_get_tagger(tag);
5823 tagger_time = got_object_tag_get_tagger_time(tag);
5824 err = got_object_id_str(&id_str,
5825 got_object_tag_get_object_id(tag));
5826 if (err)
5827 break;
5829 printf("from: %s\n", tagger);
5830 datestr = get_datestr(&tagger_time, datebuf);
5831 if (datestr)
5832 printf("date: %s UTC\n", datestr);
5833 if (commit)
5834 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5835 else {
5836 switch (got_object_tag_get_object_type(tag)) {
5837 case GOT_OBJ_TYPE_BLOB:
5838 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5839 id_str);
5840 break;
5841 case GOT_OBJ_TYPE_TREE:
5842 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5843 id_str);
5844 break;
5845 case GOT_OBJ_TYPE_COMMIT:
5846 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5847 id_str);
5848 break;
5849 case GOT_OBJ_TYPE_TAG:
5850 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5851 id_str);
5852 break;
5853 default:
5854 break;
5857 free(id_str);
5858 if (commit) {
5859 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5860 if (err)
5861 break;
5862 got_object_commit_close(commit);
5863 } else {
5864 tagmsg0 = strdup(got_object_tag_get_message(tag));
5865 got_object_tag_close(tag);
5866 if (tagmsg0 == NULL) {
5867 err = got_error_from_errno("strdup");
5868 break;
5872 tagmsg = tagmsg0;
5873 do {
5874 line = strsep(&tagmsg, "\n");
5875 if (line)
5876 printf(" %s\n", line);
5877 } while (line);
5878 free(tagmsg0);
5881 got_ref_list_free(&refs);
5882 return NULL;
5885 static const struct got_error *
5886 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5887 const char *tag_name, const char *repo_path)
5889 const struct got_error *err = NULL;
5890 char *template = NULL, *initial_content = NULL;
5891 char *editor = NULL;
5892 int initial_content_len;
5893 int fd = -1;
5895 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5896 err = got_error_from_errno("asprintf");
5897 goto done;
5900 initial_content_len = asprintf(&initial_content,
5901 "\n# tagging commit %s as %s\n",
5902 commit_id_str, tag_name);
5903 if (initial_content_len == -1) {
5904 err = got_error_from_errno("asprintf");
5905 goto done;
5908 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5909 if (err)
5910 goto done;
5912 if (write(fd, initial_content, initial_content_len) == -1) {
5913 err = got_error_from_errno2("write", *tagmsg_path);
5914 goto done;
5917 err = get_editor(&editor);
5918 if (err)
5919 goto done;
5920 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
5921 initial_content_len);
5922 done:
5923 free(initial_content);
5924 free(template);
5925 free(editor);
5927 if (fd != -1 && close(fd) == -1 && err == NULL)
5928 err = got_error_from_errno2("close", *tagmsg_path);
5930 /* Editor is done; we can now apply unveil(2) */
5931 if (err == NULL)
5932 err = apply_unveil(repo_path, 0, NULL);
5933 if (err) {
5934 free(*tagmsg);
5935 *tagmsg = NULL;
5937 return err;
5940 static const struct got_error *
5941 add_tag(struct got_repository *repo, struct got_worktree *worktree,
5942 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
5944 const struct got_error *err = NULL;
5945 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5946 char *label = NULL, *commit_id_str = NULL;
5947 struct got_reference *ref = NULL;
5948 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5949 char *tagmsg_path = NULL, *tag_id_str = NULL;
5950 int preserve_tagmsg = 0;
5953 * Don't let the user create a tag name with a leading '-'.
5954 * While technically a valid reference name, this case is usually
5955 * an unintended typo.
5957 if (tag_name[0] == '-')
5958 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5960 err = get_author(&tagger, repo, worktree);
5961 if (err)
5962 return err;
5964 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5965 GOT_OBJ_TYPE_COMMIT, 1, repo);
5966 if (err)
5967 goto done;
5969 err = got_object_id_str(&commit_id_str, commit_id);
5970 if (err)
5971 goto done;
5973 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5974 refname = strdup(tag_name);
5975 if (refname == NULL) {
5976 err = got_error_from_errno("strdup");
5977 goto done;
5979 tag_name += 10;
5980 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5981 err = got_error_from_errno("asprintf");
5982 goto done;
5985 err = got_ref_open(&ref, repo, refname, 0);
5986 if (err == NULL) {
5987 err = got_error(GOT_ERR_TAG_EXISTS);
5988 goto done;
5989 } else if (err->code != GOT_ERR_NOT_REF)
5990 goto done;
5992 if (tagmsg_arg == NULL) {
5993 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5994 tag_name, got_repo_get_path(repo));
5995 if (err) {
5996 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5997 tagmsg_path != NULL)
5998 preserve_tagmsg = 1;
5999 goto done;
6003 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6004 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6005 if (err) {
6006 if (tagmsg_path)
6007 preserve_tagmsg = 1;
6008 goto done;
6011 err = got_ref_alloc(&ref, refname, tag_id);
6012 if (err) {
6013 if (tagmsg_path)
6014 preserve_tagmsg = 1;
6015 goto done;
6018 err = got_ref_write(ref, repo);
6019 if (err) {
6020 if (tagmsg_path)
6021 preserve_tagmsg = 1;
6022 goto done;
6025 err = got_object_id_str(&tag_id_str, tag_id);
6026 if (err) {
6027 if (tagmsg_path)
6028 preserve_tagmsg = 1;
6029 goto done;
6031 printf("Created tag %s\n", tag_id_str);
6032 done:
6033 if (preserve_tagmsg) {
6034 fprintf(stderr, "%s: tag message preserved in %s\n",
6035 getprogname(), tagmsg_path);
6036 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6037 err = got_error_from_errno2("unlink", tagmsg_path);
6038 free(tag_id_str);
6039 if (ref)
6040 got_ref_close(ref);
6041 free(commit_id);
6042 free(commit_id_str);
6043 free(refname);
6044 free(tagmsg);
6045 free(tagmsg_path);
6046 free(tagger);
6047 return err;
6050 static const struct got_error *
6051 cmd_tag(int argc, char *argv[])
6053 const struct got_error *error = NULL;
6054 struct got_repository *repo = NULL;
6055 struct got_worktree *worktree = NULL;
6056 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6057 char *gitconfig_path = NULL;
6058 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6059 int ch, do_list = 0;
6061 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6062 switch (ch) {
6063 case 'c':
6064 commit_id_arg = optarg;
6065 break;
6066 case 'm':
6067 tagmsg = optarg;
6068 break;
6069 case 'r':
6070 repo_path = realpath(optarg, NULL);
6071 if (repo_path == NULL)
6072 return got_error_from_errno2("realpath",
6073 optarg);
6074 got_path_strip_trailing_slashes(repo_path);
6075 break;
6076 case 'l':
6077 do_list = 1;
6078 break;
6079 default:
6080 usage_tag();
6081 /* NOTREACHED */
6085 argc -= optind;
6086 argv += optind;
6088 if (do_list) {
6089 if (commit_id_arg != NULL)
6090 errx(1,
6091 "-c option can only be used when creating a tag");
6092 if (tagmsg)
6093 errx(1, "-l and -m options are mutually exclusive");
6094 if (argc > 0)
6095 usage_tag();
6096 } else if (argc != 1)
6097 usage_tag();
6099 tag_name = argv[0];
6101 #ifndef PROFILE
6102 if (do_list) {
6103 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6104 NULL) == -1)
6105 err(1, "pledge");
6106 } else {
6107 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6108 "sendfd unveil", NULL) == -1)
6109 err(1, "pledge");
6111 #endif
6112 cwd = getcwd(NULL, 0);
6113 if (cwd == NULL) {
6114 error = got_error_from_errno("getcwd");
6115 goto done;
6118 if (repo_path == NULL) {
6119 error = got_worktree_open(&worktree, cwd);
6120 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6121 goto done;
6122 else
6123 error = NULL;
6124 if (worktree) {
6125 repo_path =
6126 strdup(got_worktree_get_repo_path(worktree));
6127 if (repo_path == NULL)
6128 error = got_error_from_errno("strdup");
6129 if (error)
6130 goto done;
6131 } else {
6132 repo_path = strdup(cwd);
6133 if (repo_path == NULL) {
6134 error = got_error_from_errno("strdup");
6135 goto done;
6140 if (do_list) {
6141 error = got_repo_open(&repo, repo_path, NULL);
6142 if (error != NULL)
6143 goto done;
6144 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6145 if (error)
6146 goto done;
6147 error = list_tags(repo, worktree);
6148 } else {
6149 error = get_gitconfig_path(&gitconfig_path);
6150 if (error)
6151 goto done;
6152 error = got_repo_open(&repo, repo_path, gitconfig_path);
6153 if (error != NULL)
6154 goto done;
6156 if (tagmsg) {
6157 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6158 if (error)
6159 goto done;
6162 if (commit_id_arg == NULL) {
6163 struct got_reference *head_ref;
6164 struct got_object_id *commit_id;
6165 error = got_ref_open(&head_ref, repo,
6166 worktree ? got_worktree_get_head_ref_name(worktree)
6167 : GOT_REF_HEAD, 0);
6168 if (error)
6169 goto done;
6170 error = got_ref_resolve(&commit_id, repo, head_ref);
6171 got_ref_close(head_ref);
6172 if (error)
6173 goto done;
6174 error = got_object_id_str(&commit_id_str, commit_id);
6175 free(commit_id);
6176 if (error)
6177 goto done;
6180 error = add_tag(repo, worktree, tag_name,
6181 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6183 done:
6184 if (repo)
6185 got_repo_close(repo);
6186 if (worktree)
6187 got_worktree_close(worktree);
6188 free(cwd);
6189 free(repo_path);
6190 free(gitconfig_path);
6191 free(commit_id_str);
6192 return error;
6195 __dead static void
6196 usage_add(void)
6198 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6199 getprogname());
6200 exit(1);
6203 static const struct got_error *
6204 add_progress(void *arg, unsigned char status, const char *path)
6206 while (path[0] == '/')
6207 path++;
6208 printf("%c %s\n", status, path);
6209 return NULL;
6212 static const struct got_error *
6213 cmd_add(int argc, char *argv[])
6215 const struct got_error *error = NULL;
6216 struct got_repository *repo = NULL;
6217 struct got_worktree *worktree = NULL;
6218 char *cwd = NULL;
6219 struct got_pathlist_head paths;
6220 struct got_pathlist_entry *pe;
6221 int ch, can_recurse = 0, no_ignores = 0;
6223 TAILQ_INIT(&paths);
6225 while ((ch = getopt(argc, argv, "IR")) != -1) {
6226 switch (ch) {
6227 case 'I':
6228 no_ignores = 1;
6229 break;
6230 case 'R':
6231 can_recurse = 1;
6232 break;
6233 default:
6234 usage_add();
6235 /* NOTREACHED */
6239 argc -= optind;
6240 argv += optind;
6242 #ifndef PROFILE
6243 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6244 NULL) == -1)
6245 err(1, "pledge");
6246 #endif
6247 if (argc < 1)
6248 usage_add();
6250 cwd = getcwd(NULL, 0);
6251 if (cwd == NULL) {
6252 error = got_error_from_errno("getcwd");
6253 goto done;
6256 error = got_worktree_open(&worktree, cwd);
6257 if (error) {
6258 if (error->code == GOT_ERR_NOT_WORKTREE)
6259 error = wrap_not_worktree_error(error, "add", cwd);
6260 goto done;
6263 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6264 NULL);
6265 if (error != NULL)
6266 goto done;
6268 error = apply_unveil(got_repo_get_path(repo), 1,
6269 got_worktree_get_root_path(worktree));
6270 if (error)
6271 goto done;
6273 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6274 if (error)
6275 goto done;
6277 if (!can_recurse && no_ignores) {
6278 error = got_error_msg(GOT_ERR_BAD_PATH,
6279 "disregarding ignores requires -R option");
6280 goto done;
6284 if (!can_recurse) {
6285 char *ondisk_path;
6286 struct stat sb;
6287 TAILQ_FOREACH(pe, &paths, entry) {
6288 if (asprintf(&ondisk_path, "%s/%s",
6289 got_worktree_get_root_path(worktree),
6290 pe->path) == -1) {
6291 error = got_error_from_errno("asprintf");
6292 goto done;
6294 if (lstat(ondisk_path, &sb) == -1) {
6295 if (errno == ENOENT) {
6296 free(ondisk_path);
6297 continue;
6299 error = got_error_from_errno2("lstat",
6300 ondisk_path);
6301 free(ondisk_path);
6302 goto done;
6304 free(ondisk_path);
6305 if (S_ISDIR(sb.st_mode)) {
6306 error = got_error_msg(GOT_ERR_BAD_PATH,
6307 "adding directories requires -R option");
6308 goto done;
6313 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6314 NULL, repo, no_ignores);
6315 done:
6316 if (repo)
6317 got_repo_close(repo);
6318 if (worktree)
6319 got_worktree_close(worktree);
6320 TAILQ_FOREACH(pe, &paths, entry)
6321 free((char *)pe->path);
6322 got_pathlist_free(&paths);
6323 free(cwd);
6324 return error;
6327 __dead static void
6328 usage_remove(void)
6330 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6331 "path ...\n", getprogname());
6332 exit(1);
6335 static const struct got_error *
6336 print_remove_status(void *arg, unsigned char status,
6337 unsigned char staged_status, const char *path)
6339 while (path[0] == '/')
6340 path++;
6341 if (status == GOT_STATUS_NONEXISTENT)
6342 return NULL;
6343 if (status == staged_status && (status == GOT_STATUS_DELETE))
6344 status = GOT_STATUS_NO_CHANGE;
6345 printf("%c%c %s\n", status, staged_status, path);
6346 return NULL;
6349 static const struct got_error *
6350 cmd_remove(int argc, char *argv[])
6352 const struct got_error *error = NULL;
6353 struct got_worktree *worktree = NULL;
6354 struct got_repository *repo = NULL;
6355 const char *status_codes = NULL;
6356 char *cwd = NULL;
6357 struct got_pathlist_head paths;
6358 struct got_pathlist_entry *pe;
6359 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6361 TAILQ_INIT(&paths);
6363 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6364 switch (ch) {
6365 case 'f':
6366 delete_local_mods = 1;
6367 break;
6368 case 'k':
6369 keep_on_disk = 1;
6370 break;
6371 case 'R':
6372 can_recurse = 1;
6373 break;
6374 case 's':
6375 for (i = 0; i < strlen(optarg); i++) {
6376 switch (optarg[i]) {
6377 case GOT_STATUS_MODIFY:
6378 delete_local_mods = 1;
6379 break;
6380 case GOT_STATUS_MISSING:
6381 break;
6382 default:
6383 errx(1, "invalid status code '%c'",
6384 optarg[i]);
6387 status_codes = optarg;
6388 break;
6389 default:
6390 usage_remove();
6391 /* NOTREACHED */
6395 argc -= optind;
6396 argv += optind;
6398 #ifndef PROFILE
6399 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6400 NULL) == -1)
6401 err(1, "pledge");
6402 #endif
6403 if (argc < 1)
6404 usage_remove();
6406 cwd = getcwd(NULL, 0);
6407 if (cwd == NULL) {
6408 error = got_error_from_errno("getcwd");
6409 goto done;
6411 error = got_worktree_open(&worktree, cwd);
6412 if (error) {
6413 if (error->code == GOT_ERR_NOT_WORKTREE)
6414 error = wrap_not_worktree_error(error, "remove", cwd);
6415 goto done;
6418 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6419 NULL);
6420 if (error)
6421 goto done;
6423 error = apply_unveil(got_repo_get_path(repo), 1,
6424 got_worktree_get_root_path(worktree));
6425 if (error)
6426 goto done;
6428 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6429 if (error)
6430 goto done;
6432 if (!can_recurse) {
6433 char *ondisk_path;
6434 struct stat sb;
6435 TAILQ_FOREACH(pe, &paths, entry) {
6436 if (asprintf(&ondisk_path, "%s/%s",
6437 got_worktree_get_root_path(worktree),
6438 pe->path) == -1) {
6439 error = got_error_from_errno("asprintf");
6440 goto done;
6442 if (lstat(ondisk_path, &sb) == -1) {
6443 if (errno == ENOENT) {
6444 free(ondisk_path);
6445 continue;
6447 error = got_error_from_errno2("lstat",
6448 ondisk_path);
6449 free(ondisk_path);
6450 goto done;
6452 free(ondisk_path);
6453 if (S_ISDIR(sb.st_mode)) {
6454 error = got_error_msg(GOT_ERR_BAD_PATH,
6455 "removing directories requires -R option");
6456 goto done;
6461 error = got_worktree_schedule_delete(worktree, &paths,
6462 delete_local_mods, status_codes, print_remove_status, NULL,
6463 repo, keep_on_disk);
6464 done:
6465 if (repo)
6466 got_repo_close(repo);
6467 if (worktree)
6468 got_worktree_close(worktree);
6469 TAILQ_FOREACH(pe, &paths, entry)
6470 free((char *)pe->path);
6471 got_pathlist_free(&paths);
6472 free(cwd);
6473 return error;
6476 __dead static void
6477 usage_revert(void)
6479 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6480 "path ...\n", getprogname());
6481 exit(1);
6484 static const struct got_error *
6485 revert_progress(void *arg, unsigned char status, const char *path)
6487 if (status == GOT_STATUS_UNVERSIONED)
6488 return NULL;
6490 while (path[0] == '/')
6491 path++;
6492 printf("%c %s\n", status, path);
6493 return NULL;
6496 struct choose_patch_arg {
6497 FILE *patch_script_file;
6498 const char *action;
6501 static const struct got_error *
6502 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6503 int nchanges, const char *action)
6505 char *line = NULL;
6506 size_t linesize = 0;
6507 ssize_t linelen;
6509 switch (status) {
6510 case GOT_STATUS_ADD:
6511 printf("A %s\n%s this addition? [y/n] ", path, action);
6512 break;
6513 case GOT_STATUS_DELETE:
6514 printf("D %s\n%s this deletion? [y/n] ", path, action);
6515 break;
6516 case GOT_STATUS_MODIFY:
6517 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6518 return got_error_from_errno("fseek");
6519 printf(GOT_COMMIT_SEP_STR);
6520 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6521 printf("%s", line);
6522 if (ferror(patch_file))
6523 return got_error_from_errno("getline");
6524 printf(GOT_COMMIT_SEP_STR);
6525 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6526 path, n, nchanges, action);
6527 break;
6528 default:
6529 return got_error_path(path, GOT_ERR_FILE_STATUS);
6532 return NULL;
6535 static const struct got_error *
6536 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6537 FILE *patch_file, int n, int nchanges)
6539 const struct got_error *err = NULL;
6540 char *line = NULL;
6541 size_t linesize = 0;
6542 ssize_t linelen;
6543 int resp = ' ';
6544 struct choose_patch_arg *a = arg;
6546 *choice = GOT_PATCH_CHOICE_NONE;
6548 if (a->patch_script_file) {
6549 char *nl;
6550 err = show_change(status, path, patch_file, n, nchanges,
6551 a->action);
6552 if (err)
6553 return err;
6554 linelen = getline(&line, &linesize, a->patch_script_file);
6555 if (linelen == -1) {
6556 if (ferror(a->patch_script_file))
6557 return got_error_from_errno("getline");
6558 return NULL;
6560 nl = strchr(line, '\n');
6561 if (nl)
6562 *nl = '\0';
6563 if (strcmp(line, "y") == 0) {
6564 *choice = GOT_PATCH_CHOICE_YES;
6565 printf("y\n");
6566 } else if (strcmp(line, "n") == 0) {
6567 *choice = GOT_PATCH_CHOICE_NO;
6568 printf("n\n");
6569 } else if (strcmp(line, "q") == 0 &&
6570 status == GOT_STATUS_MODIFY) {
6571 *choice = GOT_PATCH_CHOICE_QUIT;
6572 printf("q\n");
6573 } else
6574 printf("invalid response '%s'\n", line);
6575 free(line);
6576 return NULL;
6579 while (resp != 'y' && resp != 'n' && resp != 'q') {
6580 err = show_change(status, path, patch_file, n, nchanges,
6581 a->action);
6582 if (err)
6583 return err;
6584 resp = getchar();
6585 if (resp == '\n')
6586 resp = getchar();
6587 if (status == GOT_STATUS_MODIFY) {
6588 if (resp != 'y' && resp != 'n' && resp != 'q') {
6589 printf("invalid response '%c'\n", resp);
6590 resp = ' ';
6592 } else if (resp != 'y' && resp != 'n') {
6593 printf("invalid response '%c'\n", resp);
6594 resp = ' ';
6598 if (resp == 'y')
6599 *choice = GOT_PATCH_CHOICE_YES;
6600 else if (resp == 'n')
6601 *choice = GOT_PATCH_CHOICE_NO;
6602 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6603 *choice = GOT_PATCH_CHOICE_QUIT;
6605 return NULL;
6609 static const struct got_error *
6610 cmd_revert(int argc, char *argv[])
6612 const struct got_error *error = NULL;
6613 struct got_worktree *worktree = NULL;
6614 struct got_repository *repo = NULL;
6615 char *cwd = NULL, *path = NULL;
6616 struct got_pathlist_head paths;
6617 struct got_pathlist_entry *pe;
6618 int ch, can_recurse = 0, pflag = 0;
6619 FILE *patch_script_file = NULL;
6620 const char *patch_script_path = NULL;
6621 struct choose_patch_arg cpa;
6623 TAILQ_INIT(&paths);
6625 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6626 switch (ch) {
6627 case 'p':
6628 pflag = 1;
6629 break;
6630 case 'F':
6631 patch_script_path = optarg;
6632 break;
6633 case 'R':
6634 can_recurse = 1;
6635 break;
6636 default:
6637 usage_revert();
6638 /* NOTREACHED */
6642 argc -= optind;
6643 argv += optind;
6645 #ifndef PROFILE
6646 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6647 "unveil", NULL) == -1)
6648 err(1, "pledge");
6649 #endif
6650 if (argc < 1)
6651 usage_revert();
6652 if (patch_script_path && !pflag)
6653 errx(1, "-F option can only be used together with -p option");
6655 cwd = getcwd(NULL, 0);
6656 if (cwd == NULL) {
6657 error = got_error_from_errno("getcwd");
6658 goto done;
6660 error = got_worktree_open(&worktree, cwd);
6661 if (error) {
6662 if (error->code == GOT_ERR_NOT_WORKTREE)
6663 error = wrap_not_worktree_error(error, "revert", cwd);
6664 goto done;
6667 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6668 NULL);
6669 if (error != NULL)
6670 goto done;
6672 if (patch_script_path) {
6673 patch_script_file = fopen(patch_script_path, "r");
6674 if (patch_script_file == NULL) {
6675 error = got_error_from_errno2("fopen",
6676 patch_script_path);
6677 goto done;
6680 error = apply_unveil(got_repo_get_path(repo), 1,
6681 got_worktree_get_root_path(worktree));
6682 if (error)
6683 goto done;
6685 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6686 if (error)
6687 goto done;
6689 if (!can_recurse) {
6690 char *ondisk_path;
6691 struct stat sb;
6692 TAILQ_FOREACH(pe, &paths, entry) {
6693 if (asprintf(&ondisk_path, "%s/%s",
6694 got_worktree_get_root_path(worktree),
6695 pe->path) == -1) {
6696 error = got_error_from_errno("asprintf");
6697 goto done;
6699 if (lstat(ondisk_path, &sb) == -1) {
6700 if (errno == ENOENT) {
6701 free(ondisk_path);
6702 continue;
6704 error = got_error_from_errno2("lstat",
6705 ondisk_path);
6706 free(ondisk_path);
6707 goto done;
6709 free(ondisk_path);
6710 if (S_ISDIR(sb.st_mode)) {
6711 error = got_error_msg(GOT_ERR_BAD_PATH,
6712 "reverting directories requires -R option");
6713 goto done;
6718 cpa.patch_script_file = patch_script_file;
6719 cpa.action = "revert";
6720 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6721 pflag ? choose_patch : NULL, &cpa, repo);
6722 done:
6723 if (patch_script_file && fclose(patch_script_file) == EOF &&
6724 error == NULL)
6725 error = got_error_from_errno2("fclose", patch_script_path);
6726 if (repo)
6727 got_repo_close(repo);
6728 if (worktree)
6729 got_worktree_close(worktree);
6730 free(path);
6731 free(cwd);
6732 return error;
6735 __dead static void
6736 usage_commit(void)
6738 fprintf(stderr, "usage: %s commit [-m msg] [-S] [path ...]\n",
6739 getprogname());
6740 exit(1);
6743 struct collect_commit_logmsg_arg {
6744 const char *cmdline_log;
6745 const char *editor;
6746 const char *worktree_path;
6747 const char *branch_name;
6748 const char *repo_path;
6749 char *logmsg_path;
6753 static const struct got_error *
6754 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6755 void *arg)
6757 char *initial_content = NULL;
6758 struct got_pathlist_entry *pe;
6759 const struct got_error *err = NULL;
6760 char *template = NULL;
6761 struct collect_commit_logmsg_arg *a = arg;
6762 int initial_content_len;
6763 int fd = -1;
6764 size_t len;
6766 /* if a message was specified on the command line, just use it */
6767 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6768 len = strlen(a->cmdline_log) + 1;
6769 *logmsg = malloc(len + 1);
6770 if (*logmsg == NULL)
6771 return got_error_from_errno("malloc");
6772 strlcpy(*logmsg, a->cmdline_log, len);
6773 return NULL;
6776 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6777 return got_error_from_errno("asprintf");
6779 initial_content_len = asprintf(&initial_content,
6780 "\n# changes to be committed on branch %s:\n",
6781 a->branch_name);
6782 if (initial_content_len == -1)
6783 return got_error_from_errno("asprintf");
6785 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6786 if (err)
6787 goto done;
6789 if (write(fd, initial_content, initial_content_len) == -1) {
6790 err = got_error_from_errno2("write", a->logmsg_path);
6791 goto done;
6794 TAILQ_FOREACH(pe, commitable_paths, entry) {
6795 struct got_commitable *ct = pe->data;
6796 dprintf(fd, "# %c %s\n",
6797 got_commitable_get_status(ct),
6798 got_commitable_get_path(ct));
6801 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
6802 initial_content_len);
6803 done:
6804 free(initial_content);
6805 free(template);
6807 if (fd != -1 && close(fd) == -1 && err == NULL)
6808 err = got_error_from_errno2("close", a->logmsg_path);
6810 /* Editor is done; we can now apply unveil(2) */
6811 if (err == NULL)
6812 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6813 if (err) {
6814 free(*logmsg);
6815 *logmsg = NULL;
6817 return err;
6820 static const struct got_error *
6821 cmd_commit(int argc, char *argv[])
6823 const struct got_error *error = NULL;
6824 struct got_worktree *worktree = NULL;
6825 struct got_repository *repo = NULL;
6826 char *cwd = NULL, *id_str = NULL;
6827 struct got_object_id *id = NULL;
6828 const char *logmsg = NULL;
6829 struct collect_commit_logmsg_arg cl_arg;
6830 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6831 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6832 int allow_bad_symlinks = 0;
6833 struct got_pathlist_head paths;
6835 TAILQ_INIT(&paths);
6836 cl_arg.logmsg_path = NULL;
6838 while ((ch = getopt(argc, argv, "m:S")) != -1) {
6839 switch (ch) {
6840 case 'm':
6841 logmsg = optarg;
6842 break;
6843 case 'S':
6844 allow_bad_symlinks = 1;
6845 break;
6846 default:
6847 usage_commit();
6848 /* NOTREACHED */
6852 argc -= optind;
6853 argv += optind;
6855 #ifndef PROFILE
6856 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6857 "unveil", NULL) == -1)
6858 err(1, "pledge");
6859 #endif
6860 cwd = getcwd(NULL, 0);
6861 if (cwd == NULL) {
6862 error = got_error_from_errno("getcwd");
6863 goto done;
6865 error = got_worktree_open(&worktree, cwd);
6866 if (error) {
6867 if (error->code == GOT_ERR_NOT_WORKTREE)
6868 error = wrap_not_worktree_error(error, "commit", cwd);
6869 goto done;
6872 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6873 if (error)
6874 goto done;
6875 if (rebase_in_progress) {
6876 error = got_error(GOT_ERR_REBASING);
6877 goto done;
6880 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6881 worktree);
6882 if (error)
6883 goto done;
6885 error = get_gitconfig_path(&gitconfig_path);
6886 if (error)
6887 goto done;
6888 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6889 gitconfig_path);
6890 if (error != NULL)
6891 goto done;
6893 error = get_author(&author, repo, worktree);
6894 if (error)
6895 return error;
6898 * unveil(2) traverses exec(2); if an editor is used we have
6899 * to apply unveil after the log message has been written.
6901 if (logmsg == NULL || strlen(logmsg) == 0)
6902 error = get_editor(&editor);
6903 else
6904 error = apply_unveil(got_repo_get_path(repo), 0,
6905 got_worktree_get_root_path(worktree));
6906 if (error)
6907 goto done;
6909 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6910 if (error)
6911 goto done;
6913 cl_arg.editor = editor;
6914 cl_arg.cmdline_log = logmsg;
6915 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6916 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6917 if (!histedit_in_progress) {
6918 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6919 error = got_error(GOT_ERR_COMMIT_BRANCH);
6920 goto done;
6922 cl_arg.branch_name += 11;
6924 cl_arg.repo_path = got_repo_get_path(repo);
6925 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6926 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
6927 print_status, NULL, repo);
6928 if (error) {
6929 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6930 cl_arg.logmsg_path != NULL)
6931 preserve_logmsg = 1;
6932 goto done;
6935 error = got_object_id_str(&id_str, id);
6936 if (error)
6937 goto done;
6938 printf("Created commit %s\n", id_str);
6939 done:
6940 if (preserve_logmsg) {
6941 fprintf(stderr, "%s: log message preserved in %s\n",
6942 getprogname(), cl_arg.logmsg_path);
6943 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6944 error == NULL)
6945 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6946 free(cl_arg.logmsg_path);
6947 if (repo)
6948 got_repo_close(repo);
6949 if (worktree)
6950 got_worktree_close(worktree);
6951 free(cwd);
6952 free(id_str);
6953 free(gitconfig_path);
6954 free(editor);
6955 free(author);
6956 return error;
6959 __dead static void
6960 usage_cherrypick(void)
6962 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6963 exit(1);
6966 static const struct got_error *
6967 cmd_cherrypick(int argc, char *argv[])
6969 const struct got_error *error = NULL;
6970 struct got_worktree *worktree = NULL;
6971 struct got_repository *repo = NULL;
6972 char *cwd = NULL, *commit_id_str = NULL;
6973 struct got_object_id *commit_id = NULL;
6974 struct got_commit_object *commit = NULL;
6975 struct got_object_qid *pid;
6976 struct got_reference *head_ref = NULL;
6977 int ch;
6978 struct got_update_progress_arg upa;
6980 while ((ch = getopt(argc, argv, "")) != -1) {
6981 switch (ch) {
6982 default:
6983 usage_cherrypick();
6984 /* NOTREACHED */
6988 argc -= optind;
6989 argv += optind;
6991 #ifndef PROFILE
6992 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6993 "unveil", NULL) == -1)
6994 err(1, "pledge");
6995 #endif
6996 if (argc != 1)
6997 usage_cherrypick();
6999 cwd = getcwd(NULL, 0);
7000 if (cwd == NULL) {
7001 error = got_error_from_errno("getcwd");
7002 goto done;
7004 error = got_worktree_open(&worktree, cwd);
7005 if (error) {
7006 if (error->code == GOT_ERR_NOT_WORKTREE)
7007 error = wrap_not_worktree_error(error, "cherrypick",
7008 cwd);
7009 goto done;
7012 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7013 NULL);
7014 if (error != NULL)
7015 goto done;
7017 error = apply_unveil(got_repo_get_path(repo), 0,
7018 got_worktree_get_root_path(worktree));
7019 if (error)
7020 goto done;
7022 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7023 GOT_OBJ_TYPE_COMMIT, repo);
7024 if (error != NULL) {
7025 struct got_reference *ref;
7026 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7027 goto done;
7028 error = got_ref_open(&ref, repo, argv[0], 0);
7029 if (error != NULL)
7030 goto done;
7031 error = got_ref_resolve(&commit_id, repo, ref);
7032 got_ref_close(ref);
7033 if (error != NULL)
7034 goto done;
7036 error = got_object_id_str(&commit_id_str, commit_id);
7037 if (error)
7038 goto done;
7040 error = got_ref_open(&head_ref, repo,
7041 got_worktree_get_head_ref_name(worktree), 0);
7042 if (error != NULL)
7043 goto done;
7045 error = check_same_branch(commit_id, head_ref, NULL, repo);
7046 if (error) {
7047 if (error->code != GOT_ERR_ANCESTRY)
7048 goto done;
7049 error = NULL;
7050 } else {
7051 error = got_error(GOT_ERR_SAME_BRANCH);
7052 goto done;
7055 error = got_object_open_as_commit(&commit, repo, commit_id);
7056 if (error)
7057 goto done;
7058 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7059 memset(&upa, 0, sizeof(upa));
7060 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
7061 commit_id, repo, update_progress, &upa, check_cancelled,
7062 NULL);
7063 if (error != NULL)
7064 goto done;
7066 if (upa.did_something)
7067 printf("Merged commit %s\n", commit_id_str);
7068 print_update_progress_stats(&upa);
7069 done:
7070 if (commit)
7071 got_object_commit_close(commit);
7072 free(commit_id_str);
7073 if (head_ref)
7074 got_ref_close(head_ref);
7075 if (worktree)
7076 got_worktree_close(worktree);
7077 if (repo)
7078 got_repo_close(repo);
7079 return error;
7082 __dead static void
7083 usage_backout(void)
7085 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
7086 exit(1);
7089 static const struct got_error *
7090 cmd_backout(int argc, char *argv[])
7092 const struct got_error *error = NULL;
7093 struct got_worktree *worktree = NULL;
7094 struct got_repository *repo = NULL;
7095 char *cwd = NULL, *commit_id_str = NULL;
7096 struct got_object_id *commit_id = NULL;
7097 struct got_commit_object *commit = NULL;
7098 struct got_object_qid *pid;
7099 struct got_reference *head_ref = NULL;
7100 int ch;
7101 struct got_update_progress_arg upa;
7103 while ((ch = getopt(argc, argv, "")) != -1) {
7104 switch (ch) {
7105 default:
7106 usage_backout();
7107 /* NOTREACHED */
7111 argc -= optind;
7112 argv += optind;
7114 #ifndef PROFILE
7115 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7116 "unveil", NULL) == -1)
7117 err(1, "pledge");
7118 #endif
7119 if (argc != 1)
7120 usage_backout();
7122 cwd = getcwd(NULL, 0);
7123 if (cwd == NULL) {
7124 error = got_error_from_errno("getcwd");
7125 goto done;
7127 error = got_worktree_open(&worktree, cwd);
7128 if (error) {
7129 if (error->code == GOT_ERR_NOT_WORKTREE)
7130 error = wrap_not_worktree_error(error, "backout", cwd);
7131 goto done;
7134 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7135 NULL);
7136 if (error != NULL)
7137 goto done;
7139 error = apply_unveil(got_repo_get_path(repo), 0,
7140 got_worktree_get_root_path(worktree));
7141 if (error)
7142 goto done;
7144 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7145 GOT_OBJ_TYPE_COMMIT, repo);
7146 if (error != NULL) {
7147 struct got_reference *ref;
7148 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7149 goto done;
7150 error = got_ref_open(&ref, repo, argv[0], 0);
7151 if (error != NULL)
7152 goto done;
7153 error = got_ref_resolve(&commit_id, repo, ref);
7154 got_ref_close(ref);
7155 if (error != NULL)
7156 goto done;
7158 error = got_object_id_str(&commit_id_str, commit_id);
7159 if (error)
7160 goto done;
7162 error = got_ref_open(&head_ref, repo,
7163 got_worktree_get_head_ref_name(worktree), 0);
7164 if (error != NULL)
7165 goto done;
7167 error = check_same_branch(commit_id, head_ref, NULL, repo);
7168 if (error)
7169 goto done;
7171 error = got_object_open_as_commit(&commit, repo, commit_id);
7172 if (error)
7173 goto done;
7174 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7175 if (pid == NULL) {
7176 error = got_error(GOT_ERR_ROOT_COMMIT);
7177 goto done;
7180 memset(&upa, 0, sizeof(upa));
7181 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
7182 update_progress, &upa, check_cancelled, NULL);
7183 if (error != NULL)
7184 goto done;
7186 if (upa.did_something)
7187 printf("Backed out commit %s\n", commit_id_str);
7188 print_update_progress_stats(&upa);
7189 done:
7190 if (commit)
7191 got_object_commit_close(commit);
7192 free(commit_id_str);
7193 if (head_ref)
7194 got_ref_close(head_ref);
7195 if (worktree)
7196 got_worktree_close(worktree);
7197 if (repo)
7198 got_repo_close(repo);
7199 return error;
7202 __dead static void
7203 usage_rebase(void)
7205 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
7206 getprogname());
7207 exit(1);
7210 void
7211 trim_logmsg(char *logmsg, int limit)
7213 char *nl;
7214 size_t len;
7216 len = strlen(logmsg);
7217 if (len > limit)
7218 len = limit;
7219 logmsg[len] = '\0';
7220 nl = strchr(logmsg, '\n');
7221 if (nl)
7222 *nl = '\0';
7225 static const struct got_error *
7226 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
7228 const struct got_error *err;
7229 char *logmsg0 = NULL;
7230 const char *s;
7232 err = got_object_commit_get_logmsg(&logmsg0, commit);
7233 if (err)
7234 return err;
7236 s = logmsg0;
7237 while (isspace((unsigned char)s[0]))
7238 s++;
7240 *logmsg = strdup(s);
7241 if (*logmsg == NULL) {
7242 err = got_error_from_errno("strdup");
7243 goto done;
7246 trim_logmsg(*logmsg, limit);
7247 done:
7248 free(logmsg0);
7249 return err;
7252 static const struct got_error *
7253 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
7255 const struct got_error *err;
7256 struct got_commit_object *commit = NULL;
7257 char *id_str = NULL, *logmsg = NULL;
7259 err = got_object_open_as_commit(&commit, repo, id);
7260 if (err)
7261 return err;
7263 err = got_object_id_str(&id_str, id);
7264 if (err)
7265 goto done;
7267 id_str[12] = '\0';
7269 err = get_short_logmsg(&logmsg, 42, commit);
7270 if (err)
7271 goto done;
7273 printf("%s -> merge conflict: %s\n", id_str, logmsg);
7274 done:
7275 free(id_str);
7276 got_object_commit_close(commit);
7277 free(logmsg);
7278 return err;
7281 static const struct got_error *
7282 show_rebase_progress(struct got_commit_object *commit,
7283 struct got_object_id *old_id, struct got_object_id *new_id)
7285 const struct got_error *err;
7286 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7288 err = got_object_id_str(&old_id_str, old_id);
7289 if (err)
7290 goto done;
7292 if (new_id) {
7293 err = got_object_id_str(&new_id_str, new_id);
7294 if (err)
7295 goto done;
7298 old_id_str[12] = '\0';
7299 if (new_id_str)
7300 new_id_str[12] = '\0';
7302 err = get_short_logmsg(&logmsg, 42, commit);
7303 if (err)
7304 goto done;
7306 printf("%s -> %s: %s\n", old_id_str,
7307 new_id_str ? new_id_str : "no-op change", logmsg);
7308 done:
7309 free(old_id_str);
7310 free(new_id_str);
7311 free(logmsg);
7312 return err;
7315 static const struct got_error *
7316 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
7317 struct got_reference *branch, struct got_reference *new_base_branch,
7318 struct got_reference *tmp_branch, struct got_repository *repo)
7320 printf("Switching work tree to %s\n", got_ref_get_name(branch));
7321 return got_worktree_rebase_complete(worktree, fileindex,
7322 new_base_branch, tmp_branch, branch, repo);
7325 static const struct got_error *
7326 rebase_commit(struct got_pathlist_head *merged_paths,
7327 struct got_worktree *worktree, struct got_fileindex *fileindex,
7328 struct got_reference *tmp_branch,
7329 struct got_object_id *commit_id, struct got_repository *repo)
7331 const struct got_error *error;
7332 struct got_commit_object *commit;
7333 struct got_object_id *new_commit_id;
7335 error = got_object_open_as_commit(&commit, repo, commit_id);
7336 if (error)
7337 return error;
7339 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
7340 worktree, fileindex, tmp_branch, commit, commit_id, repo);
7341 if (error) {
7342 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
7343 goto done;
7344 error = show_rebase_progress(commit, commit_id, NULL);
7345 } else {
7346 error = show_rebase_progress(commit, commit_id, new_commit_id);
7347 free(new_commit_id);
7349 done:
7350 got_object_commit_close(commit);
7351 return error;
7354 struct check_path_prefix_arg {
7355 const char *path_prefix;
7356 size_t len;
7357 int errcode;
7360 static const struct got_error *
7361 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
7362 struct got_blob_object *blob2, struct got_object_id *id1,
7363 struct got_object_id *id2, const char *path1, const char *path2,
7364 mode_t mode1, mode_t mode2, struct got_repository *repo)
7366 struct check_path_prefix_arg *a = arg;
7368 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
7369 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
7370 return got_error(a->errcode);
7372 return NULL;
7375 static const struct got_error *
7376 check_path_prefix(struct got_object_id *parent_id,
7377 struct got_object_id *commit_id, const char *path_prefix,
7378 int errcode, struct got_repository *repo)
7380 const struct got_error *err;
7381 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7382 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7383 struct check_path_prefix_arg cpp_arg;
7385 if (got_path_is_root_dir(path_prefix))
7386 return NULL;
7388 err = got_object_open_as_commit(&commit, repo, commit_id);
7389 if (err)
7390 goto done;
7392 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7393 if (err)
7394 goto done;
7396 err = got_object_open_as_tree(&tree1, repo,
7397 got_object_commit_get_tree_id(parent_commit));
7398 if (err)
7399 goto done;
7401 err = got_object_open_as_tree(&tree2, repo,
7402 got_object_commit_get_tree_id(commit));
7403 if (err)
7404 goto done;
7406 cpp_arg.path_prefix = path_prefix;
7407 while (cpp_arg.path_prefix[0] == '/')
7408 cpp_arg.path_prefix++;
7409 cpp_arg.len = strlen(cpp_arg.path_prefix);
7410 cpp_arg.errcode = errcode;
7411 err = got_diff_tree(tree1, tree2, "", "", repo,
7412 check_path_prefix_in_diff, &cpp_arg, 0);
7413 done:
7414 if (tree1)
7415 got_object_tree_close(tree1);
7416 if (tree2)
7417 got_object_tree_close(tree2);
7418 if (commit)
7419 got_object_commit_close(commit);
7420 if (parent_commit)
7421 got_object_commit_close(parent_commit);
7422 return err;
7425 static const struct got_error *
7426 collect_commits(struct got_object_id_queue *commits,
7427 struct got_object_id *initial_commit_id,
7428 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7429 const char *path_prefix, int path_prefix_errcode,
7430 struct got_repository *repo)
7432 const struct got_error *err = NULL;
7433 struct got_commit_graph *graph = NULL;
7434 struct got_object_id *parent_id = NULL;
7435 struct got_object_qid *qid;
7436 struct got_object_id *commit_id = initial_commit_id;
7438 err = got_commit_graph_open(&graph, "/", 1);
7439 if (err)
7440 return err;
7442 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7443 check_cancelled, NULL);
7444 if (err)
7445 goto done;
7446 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7447 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7448 check_cancelled, NULL);
7449 if (err) {
7450 if (err->code == GOT_ERR_ITER_COMPLETED) {
7451 err = got_error_msg(GOT_ERR_ANCESTRY,
7452 "ran out of commits to rebase before "
7453 "youngest common ancestor commit has "
7454 "been reached?!?");
7456 goto done;
7457 } else {
7458 err = check_path_prefix(parent_id, commit_id,
7459 path_prefix, path_prefix_errcode, repo);
7460 if (err)
7461 goto done;
7463 err = got_object_qid_alloc(&qid, commit_id);
7464 if (err)
7465 goto done;
7466 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
7467 commit_id = parent_id;
7470 done:
7471 got_commit_graph_close(graph);
7472 return err;
7475 static const struct got_error *
7476 cmd_rebase(int argc, char *argv[])
7478 const struct got_error *error = NULL;
7479 struct got_worktree *worktree = NULL;
7480 struct got_repository *repo = NULL;
7481 struct got_fileindex *fileindex = NULL;
7482 char *cwd = NULL;
7483 struct got_reference *branch = NULL;
7484 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
7485 struct got_object_id *commit_id = NULL, *parent_id = NULL;
7486 struct got_object_id *resume_commit_id = NULL;
7487 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
7488 struct got_commit_object *commit = NULL;
7489 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
7490 int histedit_in_progress = 0;
7491 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7492 struct got_object_id_queue commits;
7493 struct got_pathlist_head merged_paths;
7494 const struct got_object_id_queue *parent_ids;
7495 struct got_object_qid *qid, *pid;
7497 SIMPLEQ_INIT(&commits);
7498 TAILQ_INIT(&merged_paths);
7500 while ((ch = getopt(argc, argv, "ac")) != -1) {
7501 switch (ch) {
7502 case 'a':
7503 abort_rebase = 1;
7504 break;
7505 case 'c':
7506 continue_rebase = 1;
7507 break;
7508 default:
7509 usage_rebase();
7510 /* NOTREACHED */
7514 argc -= optind;
7515 argv += optind;
7517 #ifndef PROFILE
7518 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7519 "unveil", NULL) == -1)
7520 err(1, "pledge");
7521 #endif
7522 if (abort_rebase && continue_rebase)
7523 usage_rebase();
7524 else if (abort_rebase || continue_rebase) {
7525 if (argc != 0)
7526 usage_rebase();
7527 } else if (argc != 1)
7528 usage_rebase();
7530 cwd = getcwd(NULL, 0);
7531 if (cwd == NULL) {
7532 error = got_error_from_errno("getcwd");
7533 goto done;
7535 error = got_worktree_open(&worktree, cwd);
7536 if (error) {
7537 if (error->code == GOT_ERR_NOT_WORKTREE)
7538 error = wrap_not_worktree_error(error, "rebase", cwd);
7539 goto done;
7542 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7543 NULL);
7544 if (error != NULL)
7545 goto done;
7547 error = apply_unveil(got_repo_get_path(repo), 0,
7548 got_worktree_get_root_path(worktree));
7549 if (error)
7550 goto done;
7552 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7553 worktree);
7554 if (error)
7555 goto done;
7556 if (histedit_in_progress) {
7557 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7558 goto done;
7561 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7562 if (error)
7563 goto done;
7565 if (abort_rebase) {
7566 struct got_update_progress_arg upa;
7567 if (!rebase_in_progress) {
7568 error = got_error(GOT_ERR_NOT_REBASING);
7569 goto done;
7571 error = got_worktree_rebase_continue(&resume_commit_id,
7572 &new_base_branch, &tmp_branch, &branch, &fileindex,
7573 worktree, repo);
7574 if (error)
7575 goto done;
7576 printf("Switching work tree to %s\n",
7577 got_ref_get_symref_target(new_base_branch));
7578 memset(&upa, 0, sizeof(upa));
7579 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7580 new_base_branch, update_progress, &upa);
7581 if (error)
7582 goto done;
7583 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7584 print_update_progress_stats(&upa);
7585 goto done; /* nothing else to do */
7588 if (continue_rebase) {
7589 if (!rebase_in_progress) {
7590 error = got_error(GOT_ERR_NOT_REBASING);
7591 goto done;
7593 error = got_worktree_rebase_continue(&resume_commit_id,
7594 &new_base_branch, &tmp_branch, &branch, &fileindex,
7595 worktree, repo);
7596 if (error)
7597 goto done;
7599 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7600 resume_commit_id, repo);
7601 if (error)
7602 goto done;
7604 yca_id = got_object_id_dup(resume_commit_id);
7605 if (yca_id == NULL) {
7606 error = got_error_from_errno("got_object_id_dup");
7607 goto done;
7609 } else {
7610 error = got_ref_open(&branch, repo, argv[0], 0);
7611 if (error != NULL)
7612 goto done;
7615 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7616 if (error)
7617 goto done;
7619 if (!continue_rebase) {
7620 struct got_object_id *base_commit_id;
7622 base_commit_id = got_worktree_get_base_commit_id(worktree);
7623 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7624 base_commit_id, branch_head_commit_id, repo,
7625 check_cancelled, NULL);
7626 if (error)
7627 goto done;
7628 if (yca_id == NULL) {
7629 error = got_error_msg(GOT_ERR_ANCESTRY,
7630 "specified branch shares no common ancestry "
7631 "with work tree's branch");
7632 goto done;
7635 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7636 if (error) {
7637 if (error->code != GOT_ERR_ANCESTRY)
7638 goto done;
7639 error = NULL;
7640 } else {
7641 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7642 "specified branch resolves to a commit which "
7643 "is already contained in work tree's branch");
7644 goto done;
7646 error = got_worktree_rebase_prepare(&new_base_branch,
7647 &tmp_branch, &fileindex, worktree, branch, repo);
7648 if (error)
7649 goto done;
7652 commit_id = branch_head_commit_id;
7653 error = got_object_open_as_commit(&commit, repo, commit_id);
7654 if (error)
7655 goto done;
7657 parent_ids = got_object_commit_get_parent_ids(commit);
7658 pid = SIMPLEQ_FIRST(parent_ids);
7659 if (pid == NULL) {
7660 if (!continue_rebase) {
7661 struct got_update_progress_arg upa;
7662 memset(&upa, 0, sizeof(upa));
7663 error = got_worktree_rebase_abort(worktree, fileindex,
7664 repo, new_base_branch, update_progress, &upa);
7665 if (error)
7666 goto done;
7667 printf("Rebase of %s aborted\n",
7668 got_ref_get_name(branch));
7669 print_update_progress_stats(&upa);
7672 error = got_error(GOT_ERR_EMPTY_REBASE);
7673 goto done;
7675 error = collect_commits(&commits, commit_id, pid->id,
7676 yca_id, got_worktree_get_path_prefix(worktree),
7677 GOT_ERR_REBASE_PATH, repo);
7678 got_object_commit_close(commit);
7679 commit = NULL;
7680 if (error)
7681 goto done;
7683 if (SIMPLEQ_EMPTY(&commits)) {
7684 if (continue_rebase) {
7685 error = rebase_complete(worktree, fileindex,
7686 branch, new_base_branch, tmp_branch, repo);
7687 goto done;
7688 } else {
7689 /* Fast-forward the reference of the branch. */
7690 struct got_object_id *new_head_commit_id;
7691 char *id_str;
7692 error = got_ref_resolve(&new_head_commit_id, repo,
7693 new_base_branch);
7694 if (error)
7695 goto done;
7696 error = got_object_id_str(&id_str, new_head_commit_id);
7697 printf("Forwarding %s to commit %s\n",
7698 got_ref_get_name(branch), id_str);
7699 free(id_str);
7700 error = got_ref_change_ref(branch,
7701 new_head_commit_id);
7702 if (error)
7703 goto done;
7707 pid = NULL;
7708 SIMPLEQ_FOREACH(qid, &commits, entry) {
7709 struct got_update_progress_arg upa;
7711 commit_id = qid->id;
7712 parent_id = pid ? pid->id : yca_id;
7713 pid = qid;
7715 memset(&upa, 0, sizeof(upa));
7716 error = got_worktree_rebase_merge_files(&merged_paths,
7717 worktree, fileindex, parent_id, commit_id, repo,
7718 update_progress, &upa, check_cancelled, NULL);
7719 if (error)
7720 goto done;
7722 print_update_progress_stats(&upa);
7723 if (upa.conflicts > 0)
7724 rebase_status = GOT_STATUS_CONFLICT;
7726 if (rebase_status == GOT_STATUS_CONFLICT) {
7727 error = show_rebase_merge_conflict(qid->id, repo);
7728 if (error)
7729 goto done;
7730 got_worktree_rebase_pathlist_free(&merged_paths);
7731 break;
7734 error = rebase_commit(&merged_paths, worktree, fileindex,
7735 tmp_branch, commit_id, repo);
7736 got_worktree_rebase_pathlist_free(&merged_paths);
7737 if (error)
7738 goto done;
7741 if (rebase_status == GOT_STATUS_CONFLICT) {
7742 error = got_worktree_rebase_postpone(worktree, fileindex);
7743 if (error)
7744 goto done;
7745 error = got_error_msg(GOT_ERR_CONFLICTS,
7746 "conflicts must be resolved before rebasing can continue");
7747 } else
7748 error = rebase_complete(worktree, fileindex, branch,
7749 new_base_branch, tmp_branch, repo);
7750 done:
7751 got_object_id_queue_free(&commits);
7752 free(branch_head_commit_id);
7753 free(resume_commit_id);
7754 free(yca_id);
7755 if (commit)
7756 got_object_commit_close(commit);
7757 if (branch)
7758 got_ref_close(branch);
7759 if (new_base_branch)
7760 got_ref_close(new_base_branch);
7761 if (tmp_branch)
7762 got_ref_close(tmp_branch);
7763 if (worktree)
7764 got_worktree_close(worktree);
7765 if (repo)
7766 got_repo_close(repo);
7767 return error;
7770 __dead static void
7771 usage_histedit(void)
7773 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
7774 getprogname());
7775 exit(1);
7778 #define GOT_HISTEDIT_PICK 'p'
7779 #define GOT_HISTEDIT_EDIT 'e'
7780 #define GOT_HISTEDIT_FOLD 'f'
7781 #define GOT_HISTEDIT_DROP 'd'
7782 #define GOT_HISTEDIT_MESG 'm'
7784 static struct got_histedit_cmd {
7785 unsigned char code;
7786 const char *name;
7787 const char *desc;
7788 } got_histedit_cmds[] = {
7789 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7790 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7791 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7792 "be used" },
7793 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7794 { GOT_HISTEDIT_MESG, "mesg",
7795 "single-line log message for commit above (open editor if empty)" },
7798 struct got_histedit_list_entry {
7799 TAILQ_ENTRY(got_histedit_list_entry) entry;
7800 struct got_object_id *commit_id;
7801 const struct got_histedit_cmd *cmd;
7802 char *logmsg;
7804 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7806 static const struct got_error *
7807 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7808 FILE *f, struct got_repository *repo)
7810 const struct got_error *err = NULL;
7811 char *logmsg = NULL, *id_str = NULL;
7812 struct got_commit_object *commit = NULL;
7813 int n;
7815 err = got_object_open_as_commit(&commit, repo, commit_id);
7816 if (err)
7817 goto done;
7819 err = get_short_logmsg(&logmsg, 34, commit);
7820 if (err)
7821 goto done;
7823 err = got_object_id_str(&id_str, commit_id);
7824 if (err)
7825 goto done;
7827 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7828 if (n < 0)
7829 err = got_ferror(f, GOT_ERR_IO);
7830 done:
7831 if (commit)
7832 got_object_commit_close(commit);
7833 free(id_str);
7834 free(logmsg);
7835 return err;
7838 static const struct got_error *
7839 histedit_write_commit_list(struct got_object_id_queue *commits,
7840 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7842 const struct got_error *err = NULL;
7843 struct got_object_qid *qid;
7845 if (SIMPLEQ_EMPTY(commits))
7846 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7848 SIMPLEQ_FOREACH(qid, commits, entry) {
7849 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7850 f, repo);
7851 if (err)
7852 break;
7853 if (edit_logmsg_only) {
7854 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7855 if (n < 0) {
7856 err = got_ferror(f, GOT_ERR_IO);
7857 break;
7862 return err;
7865 static const struct got_error *
7866 write_cmd_list(FILE *f, const char *branch_name,
7867 struct got_object_id_queue *commits)
7869 const struct got_error *err = NULL;
7870 int n, i;
7871 char *id_str;
7872 struct got_object_qid *qid;
7874 qid = SIMPLEQ_FIRST(commits);
7875 err = got_object_id_str(&id_str, qid->id);
7876 if (err)
7877 return err;
7879 n = fprintf(f,
7880 "# Editing the history of branch '%s' starting at\n"
7881 "# commit %s\n"
7882 "# Commits will be processed in order from top to "
7883 "bottom of this file.\n", branch_name, id_str);
7884 if (n < 0) {
7885 err = got_ferror(f, GOT_ERR_IO);
7886 goto done;
7889 n = fprintf(f, "# Available histedit commands:\n");
7890 if (n < 0) {
7891 err = got_ferror(f, GOT_ERR_IO);
7892 goto done;
7895 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7896 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7897 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7898 cmd->desc);
7899 if (n < 0) {
7900 err = got_ferror(f, GOT_ERR_IO);
7901 break;
7904 done:
7905 free(id_str);
7906 return err;
7909 static const struct got_error *
7910 histedit_syntax_error(int lineno)
7912 static char msg[42];
7913 int ret;
7915 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7916 lineno);
7917 if (ret == -1 || ret >= sizeof(msg))
7918 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7920 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7923 static const struct got_error *
7924 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7925 char *logmsg, struct got_repository *repo)
7927 const struct got_error *err;
7928 struct got_commit_object *folded_commit = NULL;
7929 char *id_str, *folded_logmsg = NULL;
7931 err = got_object_id_str(&id_str, hle->commit_id);
7932 if (err)
7933 return err;
7935 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7936 if (err)
7937 goto done;
7939 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7940 if (err)
7941 goto done;
7942 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7943 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7944 folded_logmsg) == -1) {
7945 err = got_error_from_errno("asprintf");
7947 done:
7948 if (folded_commit)
7949 got_object_commit_close(folded_commit);
7950 free(id_str);
7951 free(folded_logmsg);
7952 return err;
7955 static struct got_histedit_list_entry *
7956 get_folded_commits(struct got_histedit_list_entry *hle)
7958 struct got_histedit_list_entry *prev, *folded = NULL;
7960 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7961 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7962 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7963 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7964 folded = prev;
7965 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7968 return folded;
7971 static const struct got_error *
7972 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7973 struct got_repository *repo)
7975 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7976 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7977 const struct got_error *err = NULL;
7978 struct got_commit_object *commit = NULL;
7979 int logmsg_len;
7980 int fd;
7981 struct got_histedit_list_entry *folded = NULL;
7983 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7984 if (err)
7985 return err;
7987 folded = get_folded_commits(hle);
7988 if (folded) {
7989 while (folded != hle) {
7990 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7991 folded = TAILQ_NEXT(folded, entry);
7992 continue;
7994 err = append_folded_commit_msg(&new_msg, folded,
7995 logmsg, repo);
7996 if (err)
7997 goto done;
7998 free(logmsg);
7999 logmsg = new_msg;
8000 folded = TAILQ_NEXT(folded, entry);
8004 err = got_object_id_str(&id_str, hle->commit_id);
8005 if (err)
8006 goto done;
8007 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
8008 if (err)
8009 goto done;
8010 logmsg_len = asprintf(&new_msg,
8011 "%s\n# original log message of commit %s: %s",
8012 logmsg ? logmsg : "", id_str, orig_logmsg);
8013 if (logmsg_len == -1) {
8014 err = got_error_from_errno("asprintf");
8015 goto done;
8017 free(logmsg);
8018 logmsg = new_msg;
8020 err = got_object_id_str(&id_str, hle->commit_id);
8021 if (err)
8022 goto done;
8024 err = got_opentemp_named_fd(&logmsg_path, &fd,
8025 GOT_TMPDIR_STR "/got-logmsg");
8026 if (err)
8027 goto done;
8029 write(fd, logmsg, logmsg_len);
8030 close(fd);
8032 err = get_editor(&editor);
8033 if (err)
8034 goto done;
8036 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
8037 logmsg_len);
8038 if (err) {
8039 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
8040 goto done;
8041 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
8043 done:
8044 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
8045 err = got_error_from_errno2("unlink", logmsg_path);
8046 free(logmsg_path);
8047 free(logmsg);
8048 free(orig_logmsg);
8049 free(editor);
8050 if (commit)
8051 got_object_commit_close(commit);
8052 return err;
8055 static const struct got_error *
8056 histedit_parse_list(struct got_histedit_list *histedit_cmds,
8057 FILE *f, struct got_repository *repo)
8059 const struct got_error *err = NULL;
8060 char *line = NULL, *p, *end;
8061 size_t size;
8062 ssize_t len;
8063 int lineno = 0, i;
8064 const struct got_histedit_cmd *cmd;
8065 struct got_object_id *commit_id = NULL;
8066 struct got_histedit_list_entry *hle = NULL;
8068 for (;;) {
8069 len = getline(&line, &size, f);
8070 if (len == -1) {
8071 const struct got_error *getline_err;
8072 if (feof(f))
8073 break;
8074 getline_err = got_error_from_errno("getline");
8075 err = got_ferror(f, getline_err->code);
8076 break;
8078 lineno++;
8079 p = line;
8080 while (isspace((unsigned char)p[0]))
8081 p++;
8082 if (p[0] == '#' || p[0] == '\0') {
8083 free(line);
8084 line = NULL;
8085 continue;
8087 cmd = NULL;
8088 for (i = 0; i < nitems(got_histedit_cmds); i++) {
8089 cmd = &got_histedit_cmds[i];
8090 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
8091 isspace((unsigned char)p[strlen(cmd->name)])) {
8092 p += strlen(cmd->name);
8093 break;
8095 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
8096 p++;
8097 break;
8100 if (i == nitems(got_histedit_cmds)) {
8101 err = histedit_syntax_error(lineno);
8102 break;
8104 while (isspace((unsigned char)p[0]))
8105 p++;
8106 if (cmd->code == GOT_HISTEDIT_MESG) {
8107 if (hle == NULL || hle->logmsg != NULL) {
8108 err = got_error(GOT_ERR_HISTEDIT_CMD);
8109 break;
8111 if (p[0] == '\0') {
8112 err = histedit_edit_logmsg(hle, repo);
8113 if (err)
8114 break;
8115 } else {
8116 hle->logmsg = strdup(p);
8117 if (hle->logmsg == NULL) {
8118 err = got_error_from_errno("strdup");
8119 break;
8122 free(line);
8123 line = NULL;
8124 continue;
8125 } else {
8126 end = p;
8127 while (end[0] && !isspace((unsigned char)end[0]))
8128 end++;
8129 *end = '\0';
8131 err = got_object_resolve_id_str(&commit_id, repo, p);
8132 if (err) {
8133 /* override error code */
8134 err = histedit_syntax_error(lineno);
8135 break;
8138 hle = malloc(sizeof(*hle));
8139 if (hle == NULL) {
8140 err = got_error_from_errno("malloc");
8141 break;
8143 hle->cmd = cmd;
8144 hle->commit_id = commit_id;
8145 hle->logmsg = NULL;
8146 commit_id = NULL;
8147 free(line);
8148 line = NULL;
8149 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
8152 free(line);
8153 free(commit_id);
8154 return err;
8157 static const struct got_error *
8158 histedit_check_script(struct got_histedit_list *histedit_cmds,
8159 struct got_object_id_queue *commits, struct got_repository *repo)
8161 const struct got_error *err = NULL;
8162 struct got_object_qid *qid;
8163 struct got_histedit_list_entry *hle;
8164 static char msg[92];
8165 char *id_str;
8167 if (TAILQ_EMPTY(histedit_cmds))
8168 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
8169 "histedit script contains no commands");
8170 if (SIMPLEQ_EMPTY(commits))
8171 return got_error(GOT_ERR_EMPTY_HISTEDIT);
8173 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8174 struct got_histedit_list_entry *hle2;
8175 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
8176 if (hle == hle2)
8177 continue;
8178 if (got_object_id_cmp(hle->commit_id,
8179 hle2->commit_id) != 0)
8180 continue;
8181 err = got_object_id_str(&id_str, hle->commit_id);
8182 if (err)
8183 return err;
8184 snprintf(msg, sizeof(msg), "commit %s is listed "
8185 "more than once in histedit script", id_str);
8186 free(id_str);
8187 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8191 SIMPLEQ_FOREACH(qid, commits, entry) {
8192 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8193 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
8194 break;
8196 if (hle == NULL) {
8197 err = got_object_id_str(&id_str, qid->id);
8198 if (err)
8199 return err;
8200 snprintf(msg, sizeof(msg),
8201 "commit %s missing from histedit script", id_str);
8202 free(id_str);
8203 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8207 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
8208 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
8209 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
8210 "last commit in histedit script cannot be folded");
8212 return NULL;
8215 static const struct got_error *
8216 histedit_run_editor(struct got_histedit_list *histedit_cmds,
8217 const char *path, struct got_object_id_queue *commits,
8218 struct got_repository *repo)
8220 const struct got_error *err = NULL;
8221 char *editor;
8222 FILE *f = NULL;
8224 err = get_editor(&editor);
8225 if (err)
8226 return err;
8228 if (spawn_editor(editor, path) == -1) {
8229 err = got_error_from_errno("failed spawning editor");
8230 goto done;
8233 f = fopen(path, "r");
8234 if (f == NULL) {
8235 err = got_error_from_errno("fopen");
8236 goto done;
8238 err = histedit_parse_list(histedit_cmds, f, repo);
8239 if (err)
8240 goto done;
8242 err = histedit_check_script(histedit_cmds, commits, repo);
8243 done:
8244 if (f && fclose(f) != 0 && err == NULL)
8245 err = got_error_from_errno("fclose");
8246 free(editor);
8247 return err;
8250 static const struct got_error *
8251 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
8252 struct got_object_id_queue *, const char *, const char *,
8253 struct got_repository *);
8255 static const struct got_error *
8256 histedit_edit_script(struct got_histedit_list *histedit_cmds,
8257 struct got_object_id_queue *commits, const char *branch_name,
8258 int edit_logmsg_only, struct got_repository *repo)
8260 const struct got_error *err;
8261 FILE *f = NULL;
8262 char *path = NULL;
8264 err = got_opentemp_named(&path, &f, "got-histedit");
8265 if (err)
8266 return err;
8268 err = write_cmd_list(f, branch_name, commits);
8269 if (err)
8270 goto done;
8272 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
8273 if (err)
8274 goto done;
8276 if (edit_logmsg_only) {
8277 rewind(f);
8278 err = histedit_parse_list(histedit_cmds, f, repo);
8279 } else {
8280 if (fclose(f) != 0) {
8281 err = got_error_from_errno("fclose");
8282 goto done;
8284 f = NULL;
8285 err = histedit_run_editor(histedit_cmds, path, commits, repo);
8286 if (err) {
8287 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8288 err->code != GOT_ERR_HISTEDIT_CMD)
8289 goto done;
8290 err = histedit_edit_list_retry(histedit_cmds, err,
8291 commits, path, branch_name, repo);
8294 done:
8295 if (f && fclose(f) != 0 && err == NULL)
8296 err = got_error_from_errno("fclose");
8297 if (path && unlink(path) != 0 && err == NULL)
8298 err = got_error_from_errno2("unlink", path);
8299 free(path);
8300 return err;
8303 static const struct got_error *
8304 histedit_save_list(struct got_histedit_list *histedit_cmds,
8305 struct got_worktree *worktree, struct got_repository *repo)
8307 const struct got_error *err = NULL;
8308 char *path = NULL;
8309 FILE *f = NULL;
8310 struct got_histedit_list_entry *hle;
8311 struct got_commit_object *commit = NULL;
8313 err = got_worktree_get_histedit_script_path(&path, worktree);
8314 if (err)
8315 return err;
8317 f = fopen(path, "w");
8318 if (f == NULL) {
8319 err = got_error_from_errno2("fopen", path);
8320 goto done;
8322 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8323 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
8324 repo);
8325 if (err)
8326 break;
8328 if (hle->logmsg) {
8329 int n = fprintf(f, "%c %s\n",
8330 GOT_HISTEDIT_MESG, hle->logmsg);
8331 if (n < 0) {
8332 err = got_ferror(f, GOT_ERR_IO);
8333 break;
8337 done:
8338 if (f && fclose(f) != 0 && err == NULL)
8339 err = got_error_from_errno("fclose");
8340 free(path);
8341 if (commit)
8342 got_object_commit_close(commit);
8343 return err;
8346 void
8347 histedit_free_list(struct got_histedit_list *histedit_cmds)
8349 struct got_histedit_list_entry *hle;
8351 while ((hle = TAILQ_FIRST(histedit_cmds))) {
8352 TAILQ_REMOVE(histedit_cmds, hle, entry);
8353 free(hle);
8357 static const struct got_error *
8358 histedit_load_list(struct got_histedit_list *histedit_cmds,
8359 const char *path, struct got_repository *repo)
8361 const struct got_error *err = NULL;
8362 FILE *f = NULL;
8364 f = fopen(path, "r");
8365 if (f == NULL) {
8366 err = got_error_from_errno2("fopen", path);
8367 goto done;
8370 err = histedit_parse_list(histedit_cmds, f, repo);
8371 done:
8372 if (f && fclose(f) != 0 && err == NULL)
8373 err = got_error_from_errno("fclose");
8374 return err;
8377 static const struct got_error *
8378 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
8379 const struct got_error *edit_err, struct got_object_id_queue *commits,
8380 const char *path, const char *branch_name, struct got_repository *repo)
8382 const struct got_error *err = NULL, *prev_err = edit_err;
8383 int resp = ' ';
8385 while (resp != 'c' && resp != 'r' && resp != 'a') {
8386 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
8387 "or (a)bort: ", getprogname(), prev_err->msg);
8388 resp = getchar();
8389 if (resp == '\n')
8390 resp = getchar();
8391 if (resp == 'c') {
8392 histedit_free_list(histedit_cmds);
8393 err = histedit_run_editor(histedit_cmds, path, commits,
8394 repo);
8395 if (err) {
8396 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8397 err->code != GOT_ERR_HISTEDIT_CMD)
8398 break;
8399 prev_err = err;
8400 resp = ' ';
8401 continue;
8403 break;
8404 } else if (resp == 'r') {
8405 histedit_free_list(histedit_cmds);
8406 err = histedit_edit_script(histedit_cmds,
8407 commits, branch_name, 0, repo);
8408 if (err) {
8409 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8410 err->code != GOT_ERR_HISTEDIT_CMD)
8411 break;
8412 prev_err = err;
8413 resp = ' ';
8414 continue;
8416 break;
8417 } else if (resp == 'a') {
8418 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
8419 break;
8420 } else
8421 printf("invalid response '%c'\n", resp);
8424 return err;
8427 static const struct got_error *
8428 histedit_complete(struct got_worktree *worktree,
8429 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
8430 struct got_reference *branch, struct got_repository *repo)
8432 printf("Switching work tree to %s\n",
8433 got_ref_get_symref_target(branch));
8434 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
8435 branch, repo);
8438 static const struct got_error *
8439 show_histedit_progress(struct got_commit_object *commit,
8440 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
8442 const struct got_error *err;
8443 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8445 err = got_object_id_str(&old_id_str, hle->commit_id);
8446 if (err)
8447 goto done;
8449 if (new_id) {
8450 err = got_object_id_str(&new_id_str, new_id);
8451 if (err)
8452 goto done;
8455 old_id_str[12] = '\0';
8456 if (new_id_str)
8457 new_id_str[12] = '\0';
8459 if (hle->logmsg) {
8460 logmsg = strdup(hle->logmsg);
8461 if (logmsg == NULL) {
8462 err = got_error_from_errno("strdup");
8463 goto done;
8465 trim_logmsg(logmsg, 42);
8466 } else {
8467 err = get_short_logmsg(&logmsg, 42, commit);
8468 if (err)
8469 goto done;
8472 switch (hle->cmd->code) {
8473 case GOT_HISTEDIT_PICK:
8474 case GOT_HISTEDIT_EDIT:
8475 printf("%s -> %s: %s\n", old_id_str,
8476 new_id_str ? new_id_str : "no-op change", logmsg);
8477 break;
8478 case GOT_HISTEDIT_DROP:
8479 case GOT_HISTEDIT_FOLD:
8480 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
8481 logmsg);
8482 break;
8483 default:
8484 break;
8486 done:
8487 free(old_id_str);
8488 free(new_id_str);
8489 return err;
8492 static const struct got_error *
8493 histedit_commit(struct got_pathlist_head *merged_paths,
8494 struct got_worktree *worktree, struct got_fileindex *fileindex,
8495 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
8496 struct got_repository *repo)
8498 const struct got_error *err;
8499 struct got_commit_object *commit;
8500 struct got_object_id *new_commit_id;
8502 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
8503 && hle->logmsg == NULL) {
8504 err = histedit_edit_logmsg(hle, repo);
8505 if (err)
8506 return err;
8509 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8510 if (err)
8511 return err;
8513 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
8514 worktree, fileindex, tmp_branch, commit, hle->commit_id,
8515 hle->logmsg, repo);
8516 if (err) {
8517 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
8518 goto done;
8519 err = show_histedit_progress(commit, hle, NULL);
8520 } else {
8521 err = show_histedit_progress(commit, hle, new_commit_id);
8522 free(new_commit_id);
8524 done:
8525 got_object_commit_close(commit);
8526 return err;
8529 static const struct got_error *
8530 histedit_skip_commit(struct got_histedit_list_entry *hle,
8531 struct got_worktree *worktree, struct got_repository *repo)
8533 const struct got_error *error;
8534 struct got_commit_object *commit;
8536 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
8537 repo);
8538 if (error)
8539 return error;
8541 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
8542 if (error)
8543 return error;
8545 error = show_histedit_progress(commit, hle, NULL);
8546 got_object_commit_close(commit);
8547 return error;
8550 static const struct got_error *
8551 check_local_changes(void *arg, unsigned char status,
8552 unsigned char staged_status, const char *path,
8553 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8554 struct got_object_id *commit_id, int dirfd, const char *de_name)
8556 int *have_local_changes = arg;
8558 switch (status) {
8559 case GOT_STATUS_ADD:
8560 case GOT_STATUS_DELETE:
8561 case GOT_STATUS_MODIFY:
8562 case GOT_STATUS_CONFLICT:
8563 *have_local_changes = 1;
8564 return got_error(GOT_ERR_CANCELLED);
8565 default:
8566 break;
8569 switch (staged_status) {
8570 case GOT_STATUS_ADD:
8571 case GOT_STATUS_DELETE:
8572 case GOT_STATUS_MODIFY:
8573 *have_local_changes = 1;
8574 return got_error(GOT_ERR_CANCELLED);
8575 default:
8576 break;
8579 return NULL;
8582 static const struct got_error *
8583 cmd_histedit(int argc, char *argv[])
8585 const struct got_error *error = NULL;
8586 struct got_worktree *worktree = NULL;
8587 struct got_fileindex *fileindex = NULL;
8588 struct got_repository *repo = NULL;
8589 char *cwd = NULL;
8590 struct got_reference *branch = NULL;
8591 struct got_reference *tmp_branch = NULL;
8592 struct got_object_id *resume_commit_id = NULL;
8593 struct got_object_id *base_commit_id = NULL;
8594 struct got_object_id *head_commit_id = NULL;
8595 struct got_commit_object *commit = NULL;
8596 int ch, rebase_in_progress = 0;
8597 struct got_update_progress_arg upa;
8598 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8599 int edit_logmsg_only = 0;
8600 const char *edit_script_path = NULL;
8601 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8602 struct got_object_id_queue commits;
8603 struct got_pathlist_head merged_paths;
8604 const struct got_object_id_queue *parent_ids;
8605 struct got_object_qid *pid;
8606 struct got_histedit_list histedit_cmds;
8607 struct got_histedit_list_entry *hle;
8609 SIMPLEQ_INIT(&commits);
8610 TAILQ_INIT(&histedit_cmds);
8611 TAILQ_INIT(&merged_paths);
8612 memset(&upa, 0, sizeof(upa));
8614 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
8615 switch (ch) {
8616 case 'a':
8617 abort_edit = 1;
8618 break;
8619 case 'c':
8620 continue_edit = 1;
8621 break;
8622 case 'F':
8623 edit_script_path = optarg;
8624 break;
8625 case 'm':
8626 edit_logmsg_only = 1;
8627 break;
8628 default:
8629 usage_histedit();
8630 /* NOTREACHED */
8634 argc -= optind;
8635 argv += optind;
8637 #ifndef PROFILE
8638 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8639 "unveil", NULL) == -1)
8640 err(1, "pledge");
8641 #endif
8642 if (abort_edit && continue_edit)
8643 errx(1, "histedit's -a and -c options are mutually exclusive");
8644 if (edit_script_path && edit_logmsg_only)
8645 errx(1, "histedit's -F and -m options are mutually exclusive");
8646 if (abort_edit && edit_logmsg_only)
8647 errx(1, "histedit's -a and -m options are mutually exclusive");
8648 if (continue_edit && edit_logmsg_only)
8649 errx(1, "histedit's -c and -m options are mutually exclusive");
8650 if (argc != 0)
8651 usage_histedit();
8654 * This command cannot apply unveil(2) in all cases because the
8655 * user may choose to run an editor to edit the histedit script
8656 * and to edit individual commit log messages.
8657 * unveil(2) traverses exec(2); if an editor is used we have to
8658 * apply unveil after edit script and log messages have been written.
8659 * XXX TODO: Make use of unveil(2) where possible.
8662 cwd = getcwd(NULL, 0);
8663 if (cwd == NULL) {
8664 error = got_error_from_errno("getcwd");
8665 goto done;
8667 error = got_worktree_open(&worktree, cwd);
8668 if (error) {
8669 if (error->code == GOT_ERR_NOT_WORKTREE)
8670 error = wrap_not_worktree_error(error, "histedit", cwd);
8671 goto done;
8674 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8675 NULL);
8676 if (error != NULL)
8677 goto done;
8679 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8680 if (error)
8681 goto done;
8682 if (rebase_in_progress) {
8683 error = got_error(GOT_ERR_REBASING);
8684 goto done;
8687 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8688 if (error)
8689 goto done;
8691 if (edit_in_progress && edit_logmsg_only) {
8692 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8693 "histedit operation is in progress in this "
8694 "work tree and must be continued or aborted "
8695 "before the -m option can be used");
8696 goto done;
8699 if (edit_in_progress && abort_edit) {
8700 error = got_worktree_histedit_continue(&resume_commit_id,
8701 &tmp_branch, &branch, &base_commit_id, &fileindex,
8702 worktree, repo);
8703 if (error)
8704 goto done;
8705 printf("Switching work tree to %s\n",
8706 got_ref_get_symref_target(branch));
8707 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8708 branch, base_commit_id, update_progress, &upa);
8709 if (error)
8710 goto done;
8711 printf("Histedit of %s aborted\n",
8712 got_ref_get_symref_target(branch));
8713 print_update_progress_stats(&upa);
8714 goto done; /* nothing else to do */
8715 } else if (abort_edit) {
8716 error = got_error(GOT_ERR_NOT_HISTEDIT);
8717 goto done;
8720 if (continue_edit) {
8721 char *path;
8723 if (!edit_in_progress) {
8724 error = got_error(GOT_ERR_NOT_HISTEDIT);
8725 goto done;
8728 error = got_worktree_get_histedit_script_path(&path, worktree);
8729 if (error)
8730 goto done;
8732 error = histedit_load_list(&histedit_cmds, path, repo);
8733 free(path);
8734 if (error)
8735 goto done;
8737 error = got_worktree_histedit_continue(&resume_commit_id,
8738 &tmp_branch, &branch, &base_commit_id, &fileindex,
8739 worktree, repo);
8740 if (error)
8741 goto done;
8743 error = got_ref_resolve(&head_commit_id, repo, branch);
8744 if (error)
8745 goto done;
8747 error = got_object_open_as_commit(&commit, repo,
8748 head_commit_id);
8749 if (error)
8750 goto done;
8751 parent_ids = got_object_commit_get_parent_ids(commit);
8752 pid = SIMPLEQ_FIRST(parent_ids);
8753 if (pid == NULL) {
8754 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8755 goto done;
8757 error = collect_commits(&commits, head_commit_id, pid->id,
8758 base_commit_id, got_worktree_get_path_prefix(worktree),
8759 GOT_ERR_HISTEDIT_PATH, repo);
8760 got_object_commit_close(commit);
8761 commit = NULL;
8762 if (error)
8763 goto done;
8764 } else {
8765 if (edit_in_progress) {
8766 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8767 goto done;
8770 error = got_ref_open(&branch, repo,
8771 got_worktree_get_head_ref_name(worktree), 0);
8772 if (error != NULL)
8773 goto done;
8775 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8776 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8777 "will not edit commit history of a branch outside "
8778 "the \"refs/heads/\" reference namespace");
8779 goto done;
8782 error = got_ref_resolve(&head_commit_id, repo, branch);
8783 got_ref_close(branch);
8784 branch = NULL;
8785 if (error)
8786 goto done;
8788 error = got_object_open_as_commit(&commit, repo,
8789 head_commit_id);
8790 if (error)
8791 goto done;
8792 parent_ids = got_object_commit_get_parent_ids(commit);
8793 pid = SIMPLEQ_FIRST(parent_ids);
8794 if (pid == NULL) {
8795 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8796 goto done;
8798 error = collect_commits(&commits, head_commit_id, pid->id,
8799 got_worktree_get_base_commit_id(worktree),
8800 got_worktree_get_path_prefix(worktree),
8801 GOT_ERR_HISTEDIT_PATH, repo);
8802 got_object_commit_close(commit);
8803 commit = NULL;
8804 if (error)
8805 goto done;
8807 if (SIMPLEQ_EMPTY(&commits)) {
8808 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8809 goto done;
8812 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8813 &base_commit_id, &fileindex, worktree, repo);
8814 if (error)
8815 goto done;
8817 if (edit_script_path) {
8818 error = histedit_load_list(&histedit_cmds,
8819 edit_script_path, repo);
8820 if (error) {
8821 got_worktree_histedit_abort(worktree, fileindex,
8822 repo, branch, base_commit_id,
8823 update_progress, &upa);
8824 print_update_progress_stats(&upa);
8825 goto done;
8827 } else {
8828 const char *branch_name;
8829 branch_name = got_ref_get_symref_target(branch);
8830 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8831 branch_name += 11;
8832 error = histedit_edit_script(&histedit_cmds, &commits,
8833 branch_name, edit_logmsg_only, repo);
8834 if (error) {
8835 got_worktree_histedit_abort(worktree, fileindex,
8836 repo, branch, base_commit_id,
8837 update_progress, &upa);
8838 print_update_progress_stats(&upa);
8839 goto done;
8844 error = histedit_save_list(&histedit_cmds, worktree,
8845 repo);
8846 if (error) {
8847 got_worktree_histedit_abort(worktree, fileindex,
8848 repo, branch, base_commit_id,
8849 update_progress, &upa);
8850 print_update_progress_stats(&upa);
8851 goto done;
8856 error = histedit_check_script(&histedit_cmds, &commits, repo);
8857 if (error)
8858 goto done;
8860 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8861 if (resume_commit_id) {
8862 if (got_object_id_cmp(hle->commit_id,
8863 resume_commit_id) != 0)
8864 continue;
8866 resume_commit_id = NULL;
8867 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8868 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8869 error = histedit_skip_commit(hle, worktree,
8870 repo);
8871 if (error)
8872 goto done;
8873 } else {
8874 struct got_pathlist_head paths;
8875 int have_changes = 0;
8877 TAILQ_INIT(&paths);
8878 error = got_pathlist_append(&paths, "", NULL);
8879 if (error)
8880 goto done;
8881 error = got_worktree_status(worktree, &paths,
8882 repo, check_local_changes, &have_changes,
8883 check_cancelled, NULL);
8884 got_pathlist_free(&paths);
8885 if (error) {
8886 if (error->code != GOT_ERR_CANCELLED)
8887 goto done;
8888 if (sigint_received || sigpipe_received)
8889 goto done;
8891 if (have_changes) {
8892 error = histedit_commit(NULL, worktree,
8893 fileindex, tmp_branch, hle, repo);
8894 if (error)
8895 goto done;
8896 } else {
8897 error = got_object_open_as_commit(
8898 &commit, repo, hle->commit_id);
8899 if (error)
8900 goto done;
8901 error = show_histedit_progress(commit,
8902 hle, NULL);
8903 got_object_commit_close(commit);
8904 commit = NULL;
8905 if (error)
8906 goto done;
8909 continue;
8912 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8913 error = histedit_skip_commit(hle, worktree, repo);
8914 if (error)
8915 goto done;
8916 continue;
8919 error = got_object_open_as_commit(&commit, repo,
8920 hle->commit_id);
8921 if (error)
8922 goto done;
8923 parent_ids = got_object_commit_get_parent_ids(commit);
8924 pid = SIMPLEQ_FIRST(parent_ids);
8926 error = got_worktree_histedit_merge_files(&merged_paths,
8927 worktree, fileindex, pid->id, hle->commit_id, repo,
8928 update_progress, &upa, check_cancelled, NULL);
8929 if (error)
8930 goto done;
8931 got_object_commit_close(commit);
8932 commit = NULL;
8934 print_update_progress_stats(&upa);
8935 if (upa.conflicts > 0)
8936 rebase_status = GOT_STATUS_CONFLICT;
8938 if (rebase_status == GOT_STATUS_CONFLICT) {
8939 error = show_rebase_merge_conflict(hle->commit_id,
8940 repo);
8941 if (error)
8942 goto done;
8943 got_worktree_rebase_pathlist_free(&merged_paths);
8944 break;
8947 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8948 char *id_str;
8949 error = got_object_id_str(&id_str, hle->commit_id);
8950 if (error)
8951 goto done;
8952 printf("Stopping histedit for amending commit %s\n",
8953 id_str);
8954 free(id_str);
8955 got_worktree_rebase_pathlist_free(&merged_paths);
8956 error = got_worktree_histedit_postpone(worktree,
8957 fileindex);
8958 goto done;
8961 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8962 error = histedit_skip_commit(hle, worktree, repo);
8963 if (error)
8964 goto done;
8965 continue;
8968 error = histedit_commit(&merged_paths, worktree, fileindex,
8969 tmp_branch, hle, repo);
8970 got_worktree_rebase_pathlist_free(&merged_paths);
8971 if (error)
8972 goto done;
8975 if (rebase_status == GOT_STATUS_CONFLICT) {
8976 error = got_worktree_histedit_postpone(worktree, fileindex);
8977 if (error)
8978 goto done;
8979 error = got_error_msg(GOT_ERR_CONFLICTS,
8980 "conflicts must be resolved before histedit can continue");
8981 } else
8982 error = histedit_complete(worktree, fileindex, tmp_branch,
8983 branch, repo);
8984 done:
8985 got_object_id_queue_free(&commits);
8986 histedit_free_list(&histedit_cmds);
8987 free(head_commit_id);
8988 free(base_commit_id);
8989 free(resume_commit_id);
8990 if (commit)
8991 got_object_commit_close(commit);
8992 if (branch)
8993 got_ref_close(branch);
8994 if (tmp_branch)
8995 got_ref_close(tmp_branch);
8996 if (worktree)
8997 got_worktree_close(worktree);
8998 if (repo)
8999 got_repo_close(repo);
9000 return error;
9003 __dead static void
9004 usage_integrate(void)
9006 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
9007 exit(1);
9010 static const struct got_error *
9011 cmd_integrate(int argc, char *argv[])
9013 const struct got_error *error = NULL;
9014 struct got_repository *repo = NULL;
9015 struct got_worktree *worktree = NULL;
9016 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
9017 const char *branch_arg = NULL;
9018 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
9019 struct got_fileindex *fileindex = NULL;
9020 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
9021 int ch;
9022 struct got_update_progress_arg upa;
9024 while ((ch = getopt(argc, argv, "")) != -1) {
9025 switch (ch) {
9026 default:
9027 usage_integrate();
9028 /* NOTREACHED */
9032 argc -= optind;
9033 argv += optind;
9035 if (argc != 1)
9036 usage_integrate();
9037 branch_arg = argv[0];
9038 #ifndef PROFILE
9039 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9040 "unveil", NULL) == -1)
9041 err(1, "pledge");
9042 #endif
9043 cwd = getcwd(NULL, 0);
9044 if (cwd == NULL) {
9045 error = got_error_from_errno("getcwd");
9046 goto done;
9049 error = got_worktree_open(&worktree, cwd);
9050 if (error) {
9051 if (error->code == GOT_ERR_NOT_WORKTREE)
9052 error = wrap_not_worktree_error(error, "integrate",
9053 cwd);
9054 goto done;
9057 error = check_rebase_or_histedit_in_progress(worktree);
9058 if (error)
9059 goto done;
9061 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9062 NULL);
9063 if (error != NULL)
9064 goto done;
9066 error = apply_unveil(got_repo_get_path(repo), 0,
9067 got_worktree_get_root_path(worktree));
9068 if (error)
9069 goto done;
9071 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
9072 error = got_error_from_errno("asprintf");
9073 goto done;
9076 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
9077 &base_branch_ref, worktree, refname, repo);
9078 if (error)
9079 goto done;
9081 refname = strdup(got_ref_get_name(branch_ref));
9082 if (refname == NULL) {
9083 error = got_error_from_errno("strdup");
9084 got_worktree_integrate_abort(worktree, fileindex, repo,
9085 branch_ref, base_branch_ref);
9086 goto done;
9088 base_refname = strdup(got_ref_get_name(base_branch_ref));
9089 if (base_refname == NULL) {
9090 error = got_error_from_errno("strdup");
9091 got_worktree_integrate_abort(worktree, fileindex, repo,
9092 branch_ref, base_branch_ref);
9093 goto done;
9096 error = got_ref_resolve(&commit_id, repo, branch_ref);
9097 if (error)
9098 goto done;
9100 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
9101 if (error)
9102 goto done;
9104 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
9105 error = got_error_msg(GOT_ERR_SAME_BRANCH,
9106 "specified branch has already been integrated");
9107 got_worktree_integrate_abort(worktree, fileindex, repo,
9108 branch_ref, base_branch_ref);
9109 goto done;
9112 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
9113 if (error) {
9114 if (error->code == GOT_ERR_ANCESTRY)
9115 error = got_error(GOT_ERR_REBASE_REQUIRED);
9116 got_worktree_integrate_abort(worktree, fileindex, repo,
9117 branch_ref, base_branch_ref);
9118 goto done;
9121 memset(&upa, 0, sizeof(upa));
9122 error = got_worktree_integrate_continue(worktree, fileindex, repo,
9123 branch_ref, base_branch_ref, update_progress, &upa,
9124 check_cancelled, NULL);
9125 if (error)
9126 goto done;
9128 printf("Integrated %s into %s\n", refname, base_refname);
9129 print_update_progress_stats(&upa);
9130 done:
9131 if (repo)
9132 got_repo_close(repo);
9133 if (worktree)
9134 got_worktree_close(worktree);
9135 free(cwd);
9136 free(base_commit_id);
9137 free(commit_id);
9138 free(refname);
9139 free(base_refname);
9140 return error;
9143 __dead static void
9144 usage_stage(void)
9146 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
9147 "[-S] [file-path ...]\n",
9148 getprogname());
9149 exit(1);
9152 static const struct got_error *
9153 print_stage(void *arg, unsigned char status, unsigned char staged_status,
9154 const char *path, struct got_object_id *blob_id,
9155 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
9156 int dirfd, const char *de_name)
9158 const struct got_error *err = NULL;
9159 char *id_str = NULL;
9161 if (staged_status != GOT_STATUS_ADD &&
9162 staged_status != GOT_STATUS_MODIFY &&
9163 staged_status != GOT_STATUS_DELETE)
9164 return NULL;
9166 if (staged_status == GOT_STATUS_ADD ||
9167 staged_status == GOT_STATUS_MODIFY)
9168 err = got_object_id_str(&id_str, staged_blob_id);
9169 else
9170 err = got_object_id_str(&id_str, blob_id);
9171 if (err)
9172 return err;
9174 printf("%s %c %s\n", id_str, staged_status, path);
9175 free(id_str);
9176 return NULL;
9179 static const struct got_error *
9180 cmd_stage(int argc, char *argv[])
9182 const struct got_error *error = NULL;
9183 struct got_repository *repo = NULL;
9184 struct got_worktree *worktree = NULL;
9185 char *cwd = NULL;
9186 struct got_pathlist_head paths;
9187 struct got_pathlist_entry *pe;
9188 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
9189 FILE *patch_script_file = NULL;
9190 const char *patch_script_path = NULL;
9191 struct choose_patch_arg cpa;
9193 TAILQ_INIT(&paths);
9195 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
9196 switch (ch) {
9197 case 'l':
9198 list_stage = 1;
9199 break;
9200 case 'p':
9201 pflag = 1;
9202 break;
9203 case 'F':
9204 patch_script_path = optarg;
9205 break;
9206 case 'S':
9207 allow_bad_symlinks = 1;
9208 break;
9209 default:
9210 usage_stage();
9211 /* NOTREACHED */
9215 argc -= optind;
9216 argv += optind;
9218 #ifndef PROFILE
9219 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9220 "unveil", NULL) == -1)
9221 err(1, "pledge");
9222 #endif
9223 if (list_stage && (pflag || patch_script_path))
9224 errx(1, "-l option cannot be used with other options");
9225 if (patch_script_path && !pflag)
9226 errx(1, "-F option can only be used together with -p option");
9228 cwd = getcwd(NULL, 0);
9229 if (cwd == NULL) {
9230 error = got_error_from_errno("getcwd");
9231 goto done;
9234 error = got_worktree_open(&worktree, cwd);
9235 if (error) {
9236 if (error->code == GOT_ERR_NOT_WORKTREE)
9237 error = wrap_not_worktree_error(error, "stage", cwd);
9238 goto done;
9241 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9242 NULL);
9243 if (error != NULL)
9244 goto done;
9246 if (patch_script_path) {
9247 patch_script_file = fopen(patch_script_path, "r");
9248 if (patch_script_file == NULL) {
9249 error = got_error_from_errno2("fopen",
9250 patch_script_path);
9251 goto done;
9254 error = apply_unveil(got_repo_get_path(repo), 0,
9255 got_worktree_get_root_path(worktree));
9256 if (error)
9257 goto done;
9259 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9260 if (error)
9261 goto done;
9263 if (list_stage)
9264 error = got_worktree_status(worktree, &paths, repo,
9265 print_stage, NULL, check_cancelled, NULL);
9266 else {
9267 cpa.patch_script_file = patch_script_file;
9268 cpa.action = "stage";
9269 error = got_worktree_stage(worktree, &paths,
9270 pflag ? NULL : print_status, NULL,
9271 pflag ? choose_patch : NULL, &cpa,
9272 allow_bad_symlinks, repo);
9274 done:
9275 if (patch_script_file && fclose(patch_script_file) == EOF &&
9276 error == NULL)
9277 error = got_error_from_errno2("fclose", patch_script_path);
9278 if (repo)
9279 got_repo_close(repo);
9280 if (worktree)
9281 got_worktree_close(worktree);
9282 TAILQ_FOREACH(pe, &paths, entry)
9283 free((char *)pe->path);
9284 got_pathlist_free(&paths);
9285 free(cwd);
9286 return error;
9289 __dead static void
9290 usage_unstage(void)
9292 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
9293 "[file-path ...]\n",
9294 getprogname());
9295 exit(1);
9299 static const struct got_error *
9300 cmd_unstage(int argc, char *argv[])
9302 const struct got_error *error = NULL;
9303 struct got_repository *repo = NULL;
9304 struct got_worktree *worktree = NULL;
9305 char *cwd = NULL;
9306 struct got_pathlist_head paths;
9307 struct got_pathlist_entry *pe;
9308 int ch, pflag = 0;
9309 struct got_update_progress_arg upa;
9310 FILE *patch_script_file = NULL;
9311 const char *patch_script_path = NULL;
9312 struct choose_patch_arg cpa;
9314 TAILQ_INIT(&paths);
9316 while ((ch = getopt(argc, argv, "pF:")) != -1) {
9317 switch (ch) {
9318 case 'p':
9319 pflag = 1;
9320 break;
9321 case 'F':
9322 patch_script_path = optarg;
9323 break;
9324 default:
9325 usage_unstage();
9326 /* NOTREACHED */
9330 argc -= optind;
9331 argv += optind;
9333 #ifndef PROFILE
9334 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9335 "unveil", NULL) == -1)
9336 err(1, "pledge");
9337 #endif
9338 if (patch_script_path && !pflag)
9339 errx(1, "-F option can only be used together with -p option");
9341 cwd = getcwd(NULL, 0);
9342 if (cwd == NULL) {
9343 error = got_error_from_errno("getcwd");
9344 goto done;
9347 error = got_worktree_open(&worktree, cwd);
9348 if (error) {
9349 if (error->code == GOT_ERR_NOT_WORKTREE)
9350 error = wrap_not_worktree_error(error, "unstage", cwd);
9351 goto done;
9354 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9355 NULL);
9356 if (error != NULL)
9357 goto done;
9359 if (patch_script_path) {
9360 patch_script_file = fopen(patch_script_path, "r");
9361 if (patch_script_file == NULL) {
9362 error = got_error_from_errno2("fopen",
9363 patch_script_path);
9364 goto done;
9368 error = apply_unveil(got_repo_get_path(repo), 0,
9369 got_worktree_get_root_path(worktree));
9370 if (error)
9371 goto done;
9373 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9374 if (error)
9375 goto done;
9377 cpa.patch_script_file = patch_script_file;
9378 cpa.action = "unstage";
9379 memset(&upa, 0, sizeof(upa));
9380 error = got_worktree_unstage(worktree, &paths, update_progress,
9381 &upa, pflag ? choose_patch : NULL, &cpa, repo);
9382 if (!error)
9383 print_update_progress_stats(&upa);
9384 done:
9385 if (patch_script_file && fclose(patch_script_file) == EOF &&
9386 error == NULL)
9387 error = got_error_from_errno2("fclose", patch_script_path);
9388 if (repo)
9389 got_repo_close(repo);
9390 if (worktree)
9391 got_worktree_close(worktree);
9392 TAILQ_FOREACH(pe, &paths, entry)
9393 free((char *)pe->path);
9394 got_pathlist_free(&paths);
9395 free(cwd);
9396 return error;
9399 __dead static void
9400 usage_cat(void)
9402 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
9403 "arg1 [arg2 ...]\n", getprogname());
9404 exit(1);
9407 static const struct got_error *
9408 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9410 const struct got_error *err;
9411 struct got_blob_object *blob;
9413 err = got_object_open_as_blob(&blob, repo, id, 8192);
9414 if (err)
9415 return err;
9417 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
9418 got_object_blob_close(blob);
9419 return err;
9422 static const struct got_error *
9423 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9425 const struct got_error *err;
9426 struct got_tree_object *tree;
9427 int nentries, i;
9429 err = got_object_open_as_tree(&tree, repo, id);
9430 if (err)
9431 return err;
9433 nentries = got_object_tree_get_nentries(tree);
9434 for (i = 0; i < nentries; i++) {
9435 struct got_tree_entry *te;
9436 char *id_str;
9437 if (sigint_received || sigpipe_received)
9438 break;
9439 te = got_object_tree_get_entry(tree, i);
9440 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
9441 if (err)
9442 break;
9443 fprintf(outfile, "%s %.7o %s\n", id_str,
9444 got_tree_entry_get_mode(te),
9445 got_tree_entry_get_name(te));
9446 free(id_str);
9449 got_object_tree_close(tree);
9450 return err;
9453 static const struct got_error *
9454 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9456 const struct got_error *err;
9457 struct got_commit_object *commit;
9458 const struct got_object_id_queue *parent_ids;
9459 struct got_object_qid *pid;
9460 char *id_str = NULL;
9461 const char *logmsg = NULL;
9463 err = got_object_open_as_commit(&commit, repo, id);
9464 if (err)
9465 return err;
9467 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
9468 if (err)
9469 goto done;
9471 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
9472 parent_ids = got_object_commit_get_parent_ids(commit);
9473 fprintf(outfile, "numparents %d\n",
9474 got_object_commit_get_nparents(commit));
9475 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
9476 char *pid_str;
9477 err = got_object_id_str(&pid_str, pid->id);
9478 if (err)
9479 goto done;
9480 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
9481 free(pid_str);
9483 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
9484 got_object_commit_get_author(commit),
9485 (long long)got_object_commit_get_author_time(commit));
9487 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
9488 got_object_commit_get_author(commit),
9489 (long long)got_object_commit_get_committer_time(commit));
9491 logmsg = got_object_commit_get_logmsg_raw(commit);
9492 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
9493 fprintf(outfile, "%s", logmsg);
9494 done:
9495 free(id_str);
9496 got_object_commit_close(commit);
9497 return err;
9500 static const struct got_error *
9501 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9503 const struct got_error *err;
9504 struct got_tag_object *tag;
9505 char *id_str = NULL;
9506 const char *tagmsg = NULL;
9508 err = got_object_open_as_tag(&tag, repo, id);
9509 if (err)
9510 return err;
9512 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
9513 if (err)
9514 goto done;
9516 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
9518 switch (got_object_tag_get_object_type(tag)) {
9519 case GOT_OBJ_TYPE_BLOB:
9520 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9521 GOT_OBJ_LABEL_BLOB);
9522 break;
9523 case GOT_OBJ_TYPE_TREE:
9524 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9525 GOT_OBJ_LABEL_TREE);
9526 break;
9527 case GOT_OBJ_TYPE_COMMIT:
9528 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9529 GOT_OBJ_LABEL_COMMIT);
9530 break;
9531 case GOT_OBJ_TYPE_TAG:
9532 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9533 GOT_OBJ_LABEL_TAG);
9534 break;
9535 default:
9536 break;
9539 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
9540 got_object_tag_get_name(tag));
9542 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
9543 got_object_tag_get_tagger(tag),
9544 (long long)got_object_tag_get_tagger_time(tag));
9546 tagmsg = got_object_tag_get_message(tag);
9547 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
9548 fprintf(outfile, "%s", tagmsg);
9549 done:
9550 free(id_str);
9551 got_object_tag_close(tag);
9552 return err;
9555 static const struct got_error *
9556 cmd_cat(int argc, char *argv[])
9558 const struct got_error *error;
9559 struct got_repository *repo = NULL;
9560 struct got_worktree *worktree = NULL;
9561 char *cwd = NULL, *repo_path = NULL, *label = NULL;
9562 const char *commit_id_str = NULL;
9563 struct got_object_id *id = NULL, *commit_id = NULL;
9564 int ch, obj_type, i, force_path = 0;
9566 #ifndef PROFILE
9567 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9568 NULL) == -1)
9569 err(1, "pledge");
9570 #endif
9572 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
9573 switch (ch) {
9574 case 'c':
9575 commit_id_str = optarg;
9576 break;
9577 case 'r':
9578 repo_path = realpath(optarg, NULL);
9579 if (repo_path == NULL)
9580 return got_error_from_errno2("realpath",
9581 optarg);
9582 got_path_strip_trailing_slashes(repo_path);
9583 break;
9584 case 'P':
9585 force_path = 1;
9586 break;
9587 default:
9588 usage_cat();
9589 /* NOTREACHED */
9593 argc -= optind;
9594 argv += optind;
9596 cwd = getcwd(NULL, 0);
9597 if (cwd == NULL) {
9598 error = got_error_from_errno("getcwd");
9599 goto done;
9601 error = got_worktree_open(&worktree, cwd);
9602 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9603 goto done;
9604 if (worktree) {
9605 if (repo_path == NULL) {
9606 repo_path = strdup(
9607 got_worktree_get_repo_path(worktree));
9608 if (repo_path == NULL) {
9609 error = got_error_from_errno("strdup");
9610 goto done;
9615 if (repo_path == NULL) {
9616 repo_path = getcwd(NULL, 0);
9617 if (repo_path == NULL)
9618 return got_error_from_errno("getcwd");
9621 error = got_repo_open(&repo, repo_path, NULL);
9622 free(repo_path);
9623 if (error != NULL)
9624 goto done;
9626 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9627 if (error)
9628 goto done;
9630 if (commit_id_str == NULL)
9631 commit_id_str = GOT_REF_HEAD;
9632 error = got_repo_match_object_id(&commit_id, NULL,
9633 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
9634 if (error)
9635 goto done;
9637 for (i = 0; i < argc; i++) {
9638 if (force_path) {
9639 error = got_object_id_by_path(&id, repo, commit_id,
9640 argv[i]);
9641 if (error)
9642 break;
9643 } else {
9644 error = got_repo_match_object_id(&id, &label, argv[i],
9645 GOT_OBJ_TYPE_ANY, 0, repo);
9646 if (error) {
9647 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9648 error->code != GOT_ERR_NOT_REF)
9649 break;
9650 error = got_object_id_by_path(&id, repo,
9651 commit_id, argv[i]);
9652 if (error)
9653 break;
9657 error = got_object_get_type(&obj_type, repo, id);
9658 if (error)
9659 break;
9661 switch (obj_type) {
9662 case GOT_OBJ_TYPE_BLOB:
9663 error = cat_blob(id, repo, stdout);
9664 break;
9665 case GOT_OBJ_TYPE_TREE:
9666 error = cat_tree(id, repo, stdout);
9667 break;
9668 case GOT_OBJ_TYPE_COMMIT:
9669 error = cat_commit(id, repo, stdout);
9670 break;
9671 case GOT_OBJ_TYPE_TAG:
9672 error = cat_tag(id, repo, stdout);
9673 break;
9674 default:
9675 error = got_error(GOT_ERR_OBJ_TYPE);
9676 break;
9678 if (error)
9679 break;
9680 free(label);
9681 label = NULL;
9682 free(id);
9683 id = NULL;
9685 done:
9686 free(label);
9687 free(id);
9688 free(commit_id);
9689 if (worktree)
9690 got_worktree_close(worktree);
9691 if (repo) {
9692 const struct got_error *repo_error;
9693 repo_error = got_repo_close(repo);
9694 if (error == NULL)
9695 error = repo_error;
9697 return error;
9700 __dead static void
9701 usage_info(void)
9703 fprintf(stderr, "usage: %s info [path ...]\n",
9704 getprogname());
9705 exit(1);
9708 static const struct got_error *
9709 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
9710 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9711 struct got_object_id *commit_id)
9713 const struct got_error *err = NULL;
9714 char *id_str = NULL;
9715 char datebuf[128];
9716 struct tm mytm, *tm;
9717 struct got_pathlist_head *paths = arg;
9718 struct got_pathlist_entry *pe;
9721 * Clear error indication from any of the path arguments which
9722 * would cause this file index entry to be displayed.
9724 TAILQ_FOREACH(pe, paths, entry) {
9725 if (got_path_cmp(path, pe->path, strlen(path),
9726 pe->path_len) == 0 ||
9727 got_path_is_child(path, pe->path, pe->path_len))
9728 pe->data = NULL; /* no error */
9731 printf(GOT_COMMIT_SEP_STR);
9732 if (S_ISLNK(mode))
9733 printf("symlink: %s\n", path);
9734 else if (S_ISREG(mode)) {
9735 printf("file: %s\n", path);
9736 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
9737 } else if (S_ISDIR(mode))
9738 printf("directory: %s\n", path);
9739 else
9740 printf("something: %s\n", path);
9742 tm = localtime_r(&mtime, &mytm);
9743 if (tm == NULL)
9744 return NULL;
9745 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) >= sizeof(datebuf))
9746 return got_error(GOT_ERR_NO_SPACE);
9747 printf("timestamp: %s\n", datebuf);
9749 if (blob_id) {
9750 err = got_object_id_str(&id_str, blob_id);
9751 if (err)
9752 return err;
9753 printf("based on blob: %s\n", id_str);
9754 free(id_str);
9757 if (staged_blob_id) {
9758 err = got_object_id_str(&id_str, staged_blob_id);
9759 if (err)
9760 return err;
9761 printf("based on staged blob: %s\n", id_str);
9762 free(id_str);
9765 if (commit_id) {
9766 err = got_object_id_str(&id_str, commit_id);
9767 if (err)
9768 return err;
9769 printf("based on commit: %s\n", id_str);
9770 free(id_str);
9773 return NULL;
9776 static const struct got_error *
9777 cmd_info(int argc, char *argv[])
9779 const struct got_error *error = NULL;
9780 struct got_worktree *worktree = NULL;
9781 char *cwd = NULL, *id_str = NULL;
9782 struct got_pathlist_head paths;
9783 struct got_pathlist_entry *pe;
9784 char *uuidstr = NULL;
9785 int ch, show_files = 0;
9787 TAILQ_INIT(&paths);
9789 while ((ch = getopt(argc, argv, "")) != -1) {
9790 switch (ch) {
9791 default:
9792 usage_info();
9793 /* NOTREACHED */
9797 argc -= optind;
9798 argv += optind;
9800 #ifndef PROFILE
9801 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
9802 NULL) == -1)
9803 err(1, "pledge");
9804 #endif
9805 cwd = getcwd(NULL, 0);
9806 if (cwd == NULL) {
9807 error = got_error_from_errno("getcwd");
9808 goto done;
9811 error = got_worktree_open(&worktree, cwd);
9812 if (error) {
9813 if (error->code == GOT_ERR_NOT_WORKTREE)
9814 error = wrap_not_worktree_error(error, "status", cwd);
9815 goto done;
9818 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9819 if (error)
9820 goto done;
9822 if (argc >= 1) {
9823 error = get_worktree_paths_from_argv(&paths, argc, argv,
9824 worktree);
9825 if (error)
9826 goto done;
9827 show_files = 1;
9830 error = got_object_id_str(&id_str,
9831 got_worktree_get_base_commit_id(worktree));
9832 if (error)
9833 goto done;
9835 error = got_worktree_get_uuid(&uuidstr, worktree);
9836 if (error)
9837 goto done;
9839 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9840 printf("work tree base commit: %s\n", id_str);
9841 printf("work tree path prefix: %s\n",
9842 got_worktree_get_path_prefix(worktree));
9843 printf("work tree branch reference: %s\n",
9844 got_worktree_get_head_ref_name(worktree));
9845 printf("work tree UUID: %s\n", uuidstr);
9846 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
9848 if (show_files) {
9849 struct got_pathlist_entry *pe;
9850 TAILQ_FOREACH(pe, &paths, entry) {
9851 if (pe->path_len == 0)
9852 continue;
9854 * Assume this path will fail. This will be corrected
9855 * in print_path_info() in case the path does suceeed.
9857 pe->data = (void *)got_error_path(pe->path,
9858 GOT_ERR_BAD_PATH);
9860 error = got_worktree_path_info(worktree, &paths,
9861 print_path_info, &paths, check_cancelled, NULL);
9862 if (error)
9863 goto done;
9864 TAILQ_FOREACH(pe, &paths, entry) {
9865 if (pe->data != NULL) {
9866 error = pe->data; /* bad path */
9867 break;
9871 done:
9872 TAILQ_FOREACH(pe, &paths, entry)
9873 free((char *)pe->path);
9874 got_pathlist_free(&paths);
9875 free(cwd);
9876 free(id_str);
9877 free(uuidstr);
9878 return error;