Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/param.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
41 #include <util.h>
43 #include "got_version.h"
44 #include "got_error.h"
45 #include "got_object.h"
46 #include "got_reference.h"
47 #include "got_repository.h"
48 #include "got_path.h"
49 #include "got_cancel.h"
50 #include "got_worktree.h"
51 #include "got_diff.h"
52 #include "got_commit_graph.h"
53 #include "got_fetch.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_opentemp.h"
57 #include "got_gotconfig.h"
59 #ifndef nitems
60 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
61 #endif
63 static volatile sig_atomic_t sigint_received;
64 static volatile sig_atomic_t sigpipe_received;
66 static void
67 catch_sigint(int signo)
68 {
69 sigint_received = 1;
70 }
72 static void
73 catch_sigpipe(int signo)
74 {
75 sigpipe_received = 1;
76 }
79 struct got_cmd {
80 const char *cmd_name;
81 const struct got_error *(*cmd_main)(int, char *[]);
82 void (*cmd_usage)(void);
83 const char *cmd_alias;
84 };
86 __dead static void usage(int);
87 __dead static void usage_init(void);
88 __dead static void usage_import(void);
89 __dead static void usage_clone(void);
90 __dead static void usage_fetch(void);
91 __dead static void usage_checkout(void);
92 __dead static void usage_update(void);
93 __dead static void usage_log(void);
94 __dead static void usage_diff(void);
95 __dead static void usage_blame(void);
96 __dead static void usage_tree(void);
97 __dead static void usage_status(void);
98 __dead static void usage_ref(void);
99 __dead static void usage_branch(void);
100 __dead static void usage_tag(void);
101 __dead static void usage_add(void);
102 __dead static void usage_remove(void);
103 __dead static void usage_revert(void);
104 __dead static void usage_commit(void);
105 __dead static void usage_cherrypick(void);
106 __dead static void usage_backout(void);
107 __dead static void usage_rebase(void);
108 __dead static void usage_histedit(void);
109 __dead static void usage_integrate(void);
110 __dead static void usage_stage(void);
111 __dead static void usage_unstage(void);
112 __dead static void usage_cat(void);
113 __dead static void usage_info(void);
115 static const struct got_error* cmd_init(int, char *[]);
116 static const struct got_error* cmd_import(int, char *[]);
117 static const struct got_error* cmd_clone(int, char *[]);
118 static const struct got_error* cmd_fetch(int, char *[]);
119 static const struct got_error* cmd_checkout(int, char *[]);
120 static const struct got_error* cmd_update(int, char *[]);
121 static const struct got_error* cmd_log(int, char *[]);
122 static const struct got_error* cmd_diff(int, char *[]);
123 static const struct got_error* cmd_blame(int, char *[]);
124 static const struct got_error* cmd_tree(int, char *[]);
125 static const struct got_error* cmd_status(int, char *[]);
126 static const struct got_error* cmd_ref(int, char *[]);
127 static const struct got_error* cmd_branch(int, char *[]);
128 static const struct got_error* cmd_tag(int, char *[]);
129 static const struct got_error* cmd_add(int, char *[]);
130 static const struct got_error* cmd_remove(int, char *[]);
131 static const struct got_error* cmd_revert(int, char *[]);
132 static const struct got_error* cmd_commit(int, char *[]);
133 static const struct got_error* cmd_cherrypick(int, char *[]);
134 static const struct got_error* cmd_backout(int, char *[]);
135 static const struct got_error* cmd_rebase(int, char *[]);
136 static const struct got_error* cmd_histedit(int, char *[]);
137 static const struct got_error* cmd_integrate(int, char *[]);
138 static const struct got_error* cmd_stage(int, char *[]);
139 static const struct got_error* cmd_unstage(int, char *[]);
140 static const struct got_error* cmd_cat(int, char *[]);
141 static const struct got_error* cmd_info(int, char *[]);
143 static struct got_cmd got_commands[] = {
144 { "init", cmd_init, usage_init, "" },
145 { "import", cmd_import, usage_import, "im" },
146 { "clone", cmd_clone, usage_clone, "cl" },
147 { "fetch", cmd_fetch, usage_fetch, "fe" },
148 { "checkout", cmd_checkout, usage_checkout, "co" },
149 { "update", cmd_update, usage_update, "up" },
150 { "log", cmd_log, usage_log, "" },
151 { "diff", cmd_diff, usage_diff, "di" },
152 { "blame", cmd_blame, usage_blame, "bl" },
153 { "tree", cmd_tree, usage_tree, "tr" },
154 { "status", cmd_status, usage_status, "st" },
155 { "ref", cmd_ref, usage_ref, "" },
156 { "branch", cmd_branch, usage_branch, "br" },
157 { "tag", cmd_tag, usage_tag, "" },
158 { "add", cmd_add, usage_add, "" },
159 { "remove", cmd_remove, usage_remove, "rm" },
160 { "revert", cmd_revert, usage_revert, "rv" },
161 { "commit", cmd_commit, usage_commit, "ci" },
162 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
163 { "backout", cmd_backout, usage_backout, "bo" },
164 { "rebase", cmd_rebase, usage_rebase, "rb" },
165 { "histedit", cmd_histedit, usage_histedit, "he" },
166 { "integrate", cmd_integrate, usage_integrate,"ig" },
167 { "stage", cmd_stage, usage_stage, "sg" },
168 { "unstage", cmd_unstage, usage_unstage, "ug" },
169 { "cat", cmd_cat, usage_cat, "" },
170 { "info", cmd_info, usage_info, "" },
171 };
173 static void
174 list_commands(void)
176 int i;
178 fprintf(stderr, "commands:");
179 for (i = 0; i < nitems(got_commands); i++) {
180 struct got_cmd *cmd = &got_commands[i];
181 fprintf(stderr, " %s", cmd->cmd_name);
183 fputc('\n', stderr);
186 int
187 main(int argc, char *argv[])
189 struct got_cmd *cmd;
190 unsigned int i;
191 int ch;
192 int hflag = 0, Vflag = 0;
193 static struct option longopts[] = {
194 { "version", no_argument, NULL, 'V' },
195 { NULL, 0, NULL, 0}
196 };
198 setlocale(LC_CTYPE, "");
200 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
201 switch (ch) {
202 case 'h':
203 hflag = 1;
204 break;
205 case 'V':
206 Vflag = 1;
207 break;
208 default:
209 usage(hflag);
210 /* NOTREACHED */
214 argc -= optind;
215 argv += optind;
216 optind = 0;
218 if (Vflag) {
219 got_version_print_str();
220 return 1;
223 if (argc <= 0)
224 usage(hflag);
226 signal(SIGINT, catch_sigint);
227 signal(SIGPIPE, catch_sigpipe);
229 for (i = 0; i < nitems(got_commands); i++) {
230 const struct got_error *error;
232 cmd = &got_commands[i];
234 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
235 strcmp(cmd->cmd_alias, argv[0]) != 0)
236 continue;
238 if (hflag)
239 got_commands[i].cmd_usage();
241 error = got_commands[i].cmd_main(argc, argv);
242 if (error && error->code != GOT_ERR_CANCELLED &&
243 error->code != GOT_ERR_PRIVSEP_EXIT &&
244 !(sigpipe_received &&
245 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
246 !(sigint_received &&
247 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
248 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
249 return 1;
252 return 0;
255 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
256 list_commands();
257 return 1;
260 __dead static void
261 usage(int hflag)
263 fprintf(stderr, "usage: %s [-h] [-V | --version] command [arg ...]\n",
264 getprogname());
265 if (hflag)
266 list_commands();
267 exit(1);
270 static const struct got_error *
271 get_editor(char **abspath)
273 const struct got_error *err = NULL;
274 const char *editor;
276 *abspath = NULL;
278 editor = getenv("VISUAL");
279 if (editor == NULL)
280 editor = getenv("EDITOR");
282 if (editor) {
283 err = got_path_find_prog(abspath, editor);
284 if (err)
285 return err;
288 if (*abspath == NULL) {
289 *abspath = strdup("/bin/ed");
290 if (*abspath == NULL)
291 return got_error_from_errno("strdup");
294 return NULL;
297 static const struct got_error *
298 apply_unveil(const char *repo_path, int repo_read_only,
299 const char *worktree_path)
301 const struct got_error *err;
303 #ifdef PROFILE
304 if (unveil("gmon.out", "rwc") != 0)
305 return got_error_from_errno2("unveil", "gmon.out");
306 #endif
307 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
308 return got_error_from_errno2("unveil", repo_path);
310 if (worktree_path && unveil(worktree_path, "rwc") != 0)
311 return got_error_from_errno2("unveil", worktree_path);
313 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
314 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
316 err = got_privsep_unveil_exec_helpers();
317 if (err != NULL)
318 return err;
320 if (unveil(NULL, NULL) != 0)
321 return got_error_from_errno("unveil");
323 return NULL;
326 __dead static void
327 usage_init(void)
329 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
330 exit(1);
333 static const struct got_error *
334 cmd_init(int argc, char *argv[])
336 const struct got_error *error = NULL;
337 char *repo_path = NULL;
338 int ch;
340 while ((ch = getopt(argc, argv, "")) != -1) {
341 switch (ch) {
342 default:
343 usage_init();
344 /* NOTREACHED */
348 argc -= optind;
349 argv += optind;
351 #ifndef PROFILE
352 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
353 err(1, "pledge");
354 #endif
355 if (argc != 1)
356 usage_init();
358 repo_path = strdup(argv[0]);
359 if (repo_path == NULL)
360 return got_error_from_errno("strdup");
362 got_path_strip_trailing_slashes(repo_path);
364 error = got_path_mkdir(repo_path);
365 if (error &&
366 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
367 goto done;
369 error = apply_unveil(repo_path, 0, NULL);
370 if (error)
371 goto done;
373 error = got_repo_init(repo_path);
374 done:
375 free(repo_path);
376 return error;
379 __dead static void
380 usage_import(void)
382 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
383 "[-r repository-path] [-I pattern] path\n", getprogname());
384 exit(1);
387 int
388 spawn_editor(const char *editor, const char *file)
390 pid_t pid;
391 sig_t sighup, sigint, sigquit;
392 int st = -1;
394 sighup = signal(SIGHUP, SIG_IGN);
395 sigint = signal(SIGINT, SIG_IGN);
396 sigquit = signal(SIGQUIT, SIG_IGN);
398 switch (pid = fork()) {
399 case -1:
400 goto doneediting;
401 case 0:
402 execl(editor, editor, file, (char *)NULL);
403 _exit(127);
406 while (waitpid(pid, &st, 0) == -1)
407 if (errno != EINTR)
408 break;
410 doneediting:
411 (void)signal(SIGHUP, sighup);
412 (void)signal(SIGINT, sigint);
413 (void)signal(SIGQUIT, sigquit);
415 if (!WIFEXITED(st)) {
416 errno = EINTR;
417 return -1;
420 return WEXITSTATUS(st);
423 static const struct got_error *
424 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
425 const char *initial_content)
427 const struct got_error *err = NULL;
428 char buf[1024];
429 struct stat st, st2;
430 FILE *fp;
431 int content_changed = 0;
432 size_t len;
434 *logmsg = NULL;
436 if (stat(logmsg_path, &st) == -1)
437 return got_error_from_errno2("stat", logmsg_path);
439 if (spawn_editor(editor, logmsg_path) == -1)
440 return got_error_from_errno("failed spawning editor");
442 if (stat(logmsg_path, &st2) == -1)
443 return got_error_from_errno("stat");
445 if (st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
446 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
447 "no changes made to commit message, aborting");
449 *logmsg = malloc(st2.st_size + 1);
450 if (*logmsg == NULL)
451 return got_error_from_errno("malloc");
452 (*logmsg)[0] = '\0';
453 len = 0;
455 fp = fopen(logmsg_path, "r");
456 if (fp == NULL) {
457 err = got_error_from_errno("fopen");
458 goto done;
460 while (fgets(buf, sizeof(buf), fp) != NULL) {
461 if (!content_changed && strcmp(buf, initial_content) != 0)
462 content_changed = 1;
463 if (buf[0] == '#' || (len == 0 && buf[0] == '\n'))
464 continue; /* remove comments and leading empty lines */
465 len = strlcat(*logmsg, buf, st2.st_size);
467 fclose(fp);
469 while (len > 0 && (*logmsg)[len - 1] == '\n') {
470 (*logmsg)[len - 1] = '\0';
471 len--;
474 if (len == 0 || !content_changed)
475 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
476 "commit message cannot be empty, aborting");
477 done:
478 if (err) {
479 free(*logmsg);
480 *logmsg = NULL;
482 return err;
485 static const struct got_error *
486 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
487 const char *path_dir, const char *branch_name)
489 char *initial_content = NULL;
490 const struct got_error *err = NULL;
491 int initial_content_len;
492 int fd = -1;
494 initial_content_len = asprintf(&initial_content,
495 "\n# %s to be imported to branch %s\n", path_dir,
496 branch_name);
497 if (initial_content_len == -1)
498 return got_error_from_errno("asprintf");
500 err = got_opentemp_named_fd(logmsg_path, &fd,
501 GOT_TMPDIR_STR "/got-importmsg");
502 if (err)
503 goto done;
505 if (write(fd, initial_content, initial_content_len) == -1) {
506 err = got_error_from_errno2("write", *logmsg_path);
507 goto done;
510 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content);
511 done:
512 if (fd != -1 && close(fd) == -1 && err == NULL)
513 err = got_error_from_errno2("close", *logmsg_path);
514 free(initial_content);
515 if (err) {
516 free(*logmsg_path);
517 *logmsg_path = NULL;
519 return err;
522 static const struct got_error *
523 import_progress(void *arg, const char *path)
525 printf("A %s\n", path);
526 return NULL;
529 static const struct got_error *
530 get_author(char **author, struct got_repository *repo,
531 struct got_worktree *worktree)
533 const struct got_error *err = NULL;
534 const char *got_author = NULL, *name, *email;
535 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
537 *author = NULL;
539 if (worktree)
540 worktree_conf = got_worktree_get_gotconfig(worktree);
541 repo_conf = got_repo_get_gotconfig(repo);
543 /*
544 * Priority of potential author information sources, from most
545 * significant to least significant:
546 * 1) work tree's .got/got.conf file
547 * 2) repository's got.conf file
548 * 3) repository's git config file
549 * 4) environment variables
550 * 5) global git config files (in user's home directory or /etc)
551 */
553 if (worktree_conf)
554 got_author = got_gotconfig_get_author(worktree_conf);
555 if (got_author == NULL)
556 got_author = got_gotconfig_get_author(repo_conf);
557 if (got_author == NULL) {
558 name = got_repo_get_gitconfig_author_name(repo);
559 email = got_repo_get_gitconfig_author_email(repo);
560 if (name && email) {
561 if (asprintf(author, "%s <%s>", name, email) == -1)
562 return got_error_from_errno("asprintf");
563 return NULL;
566 got_author = getenv("GOT_AUTHOR");
567 if (got_author == NULL) {
568 name = got_repo_get_global_gitconfig_author_name(repo);
569 email = got_repo_get_global_gitconfig_author_email(
570 repo);
571 if (name && email) {
572 if (asprintf(author, "%s <%s>", name, email)
573 == -1)
574 return got_error_from_errno("asprintf");
575 return NULL;
577 /* TODO: Look up user in password database? */
578 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
582 *author = strdup(got_author);
583 if (*author == NULL)
584 return got_error_from_errno("strdup");
586 /*
587 * Really dumb email address check; we're only doing this to
588 * avoid git's object parser breaking on commits we create.
589 */
590 while (*got_author && *got_author != '<')
591 got_author++;
592 if (*got_author != '<') {
593 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
594 goto done;
596 while (*got_author && *got_author != '@')
597 got_author++;
598 if (*got_author != '@') {
599 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
600 goto done;
602 while (*got_author && *got_author != '>')
603 got_author++;
604 if (*got_author != '>')
605 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
606 done:
607 if (err) {
608 free(*author);
609 *author = NULL;
611 return err;
614 static const struct got_error *
615 get_gitconfig_path(char **gitconfig_path)
617 const char *homedir = getenv("HOME");
619 *gitconfig_path = NULL;
620 if (homedir) {
621 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
622 return got_error_from_errno("asprintf");
625 return NULL;
628 static const struct got_error *
629 cmd_import(int argc, char *argv[])
631 const struct got_error *error = NULL;
632 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
633 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
634 const char *branch_name = "main";
635 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
636 struct got_repository *repo = NULL;
637 struct got_reference *branch_ref = NULL, *head_ref = NULL;
638 struct got_object_id *new_commit_id = NULL;
639 int ch;
640 struct got_pathlist_head ignores;
641 struct got_pathlist_entry *pe;
642 int preserve_logmsg = 0;
644 TAILQ_INIT(&ignores);
646 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
647 switch (ch) {
648 case 'b':
649 branch_name = optarg;
650 break;
651 case 'm':
652 logmsg = strdup(optarg);
653 if (logmsg == NULL) {
654 error = got_error_from_errno("strdup");
655 goto done;
657 break;
658 case 'r':
659 repo_path = realpath(optarg, NULL);
660 if (repo_path == NULL) {
661 error = got_error_from_errno2("realpath",
662 optarg);
663 goto done;
665 break;
666 case 'I':
667 if (optarg[0] == '\0')
668 break;
669 error = got_pathlist_insert(&pe, &ignores, optarg,
670 NULL);
671 if (error)
672 goto done;
673 break;
674 default:
675 usage_import();
676 /* NOTREACHED */
680 argc -= optind;
681 argv += optind;
683 #ifndef PROFILE
684 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
685 "unveil",
686 NULL) == -1)
687 err(1, "pledge");
688 #endif
689 if (argc != 1)
690 usage_import();
692 if (repo_path == NULL) {
693 repo_path = getcwd(NULL, 0);
694 if (repo_path == NULL)
695 return got_error_from_errno("getcwd");
697 got_path_strip_trailing_slashes(repo_path);
698 error = get_gitconfig_path(&gitconfig_path);
699 if (error)
700 goto done;
701 error = got_repo_open(&repo, repo_path, gitconfig_path);
702 if (error)
703 goto done;
705 error = get_author(&author, repo, NULL);
706 if (error)
707 return error;
709 /*
710 * Don't let the user create a branch name with a leading '-'.
711 * While technically a valid reference name, this case is usually
712 * an unintended typo.
713 */
714 if (branch_name[0] == '-')
715 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
717 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
718 error = got_error_from_errno("asprintf");
719 goto done;
722 error = got_ref_open(&branch_ref, repo, refname, 0);
723 if (error) {
724 if (error->code != GOT_ERR_NOT_REF)
725 goto done;
726 } else {
727 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
728 "import target branch already exists");
729 goto done;
732 path_dir = realpath(argv[0], NULL);
733 if (path_dir == NULL) {
734 error = got_error_from_errno2("realpath", argv[0]);
735 goto done;
737 got_path_strip_trailing_slashes(path_dir);
739 /*
740 * unveil(2) traverses exec(2); if an editor is used we have
741 * to apply unveil after the log message has been written.
742 */
743 if (logmsg == NULL || strlen(logmsg) == 0) {
744 error = get_editor(&editor);
745 if (error)
746 goto done;
747 free(logmsg);
748 error = collect_import_msg(&logmsg, &logmsg_path, editor,
749 path_dir, refname);
750 if (error) {
751 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
752 logmsg_path != NULL)
753 preserve_logmsg = 1;
754 goto done;
758 if (unveil(path_dir, "r") != 0) {
759 error = got_error_from_errno2("unveil", path_dir);
760 if (logmsg_path)
761 preserve_logmsg = 1;
762 goto done;
765 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
766 if (error) {
767 if (logmsg_path)
768 preserve_logmsg = 1;
769 goto done;
772 error = got_repo_import(&new_commit_id, path_dir, logmsg,
773 author, &ignores, repo, import_progress, NULL);
774 if (error) {
775 if (logmsg_path)
776 preserve_logmsg = 1;
777 goto done;
780 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
781 if (error) {
782 if (logmsg_path)
783 preserve_logmsg = 1;
784 goto done;
787 error = got_ref_write(branch_ref, repo);
788 if (error) {
789 if (logmsg_path)
790 preserve_logmsg = 1;
791 goto done;
794 error = got_object_id_str(&id_str, new_commit_id);
795 if (error) {
796 if (logmsg_path)
797 preserve_logmsg = 1;
798 goto done;
801 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
802 if (error) {
803 if (error->code != GOT_ERR_NOT_REF) {
804 if (logmsg_path)
805 preserve_logmsg = 1;
806 goto done;
809 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
810 branch_ref);
811 if (error) {
812 if (logmsg_path)
813 preserve_logmsg = 1;
814 goto done;
817 error = got_ref_write(head_ref, repo);
818 if (error) {
819 if (logmsg_path)
820 preserve_logmsg = 1;
821 goto done;
825 printf("Created branch %s with commit %s\n",
826 got_ref_get_name(branch_ref), id_str);
827 done:
828 if (preserve_logmsg) {
829 fprintf(stderr, "%s: log message preserved in %s\n",
830 getprogname(), logmsg_path);
831 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
832 error = got_error_from_errno2("unlink", logmsg_path);
833 free(logmsg);
834 free(logmsg_path);
835 free(repo_path);
836 free(editor);
837 free(refname);
838 free(new_commit_id);
839 free(id_str);
840 free(author);
841 free(gitconfig_path);
842 if (branch_ref)
843 got_ref_close(branch_ref);
844 if (head_ref)
845 got_ref_close(head_ref);
846 return error;
849 __dead static void
850 usage_clone(void)
852 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
853 "[-R reference] repository-url [directory]\n", getprogname());
854 exit(1);
857 struct got_fetch_progress_arg {
858 char last_scaled_size[FMT_SCALED_STRSIZE];
859 int last_p_indexed;
860 int last_p_resolved;
861 int verbosity;
863 struct got_repository *repo;
865 int create_configs;
866 int configs_created;
867 struct {
868 struct got_pathlist_head *symrefs;
869 struct got_pathlist_head *wanted_branches;
870 const char *proto;
871 const char *host;
872 const char *port;
873 const char *remote_repo_path;
874 const char *git_url;
875 int fetch_all_branches;
876 int mirror_references;
877 } config_info;
878 };
880 /* XXX forward declaration */
881 static const struct got_error *
882 create_config_files(const char *proto, const char *host, const char *port,
883 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
884 int mirror_references, struct got_pathlist_head *symrefs,
885 struct got_pathlist_head *wanted_branches, struct got_repository *repo);
887 static const struct got_error *
888 fetch_progress(void *arg, const char *message, off_t packfile_size,
889 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
891 const struct got_error *err = NULL;
892 struct got_fetch_progress_arg *a = arg;
893 char scaled_size[FMT_SCALED_STRSIZE];
894 int p_indexed, p_resolved;
895 int print_size = 0, print_indexed = 0, print_resolved = 0;
897 /*
898 * In order to allow a failed clone to be resumed with 'got fetch'
899 * we try to create configuration files as soon as possible.
900 * Once the server has sent information about its default branch
901 * we have all required information.
902 */
903 if (a->create_configs && !a->configs_created &&
904 !TAILQ_EMPTY(a->config_info.symrefs)) {
905 err = create_config_files(a->config_info.proto,
906 a->config_info.host, a->config_info.port,
907 a->config_info.remote_repo_path,
908 a->config_info.git_url,
909 a->config_info.fetch_all_branches,
910 a->config_info.mirror_references,
911 a->config_info.symrefs,
912 a->config_info.wanted_branches, a->repo);
913 if (err)
914 return err;
915 a->configs_created = 1;
918 if (a->verbosity < 0)
919 return NULL;
921 if (message && message[0] != '\0') {
922 printf("\rserver: %s", message);
923 fflush(stdout);
924 return NULL;
927 if (packfile_size > 0 || nobj_indexed > 0) {
928 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
929 (a->last_scaled_size[0] == '\0' ||
930 strcmp(scaled_size, a->last_scaled_size)) != 0) {
931 print_size = 1;
932 if (strlcpy(a->last_scaled_size, scaled_size,
933 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
934 return got_error(GOT_ERR_NO_SPACE);
936 if (nobj_indexed > 0) {
937 p_indexed = (nobj_indexed * 100) / nobj_total;
938 if (p_indexed != a->last_p_indexed) {
939 a->last_p_indexed = p_indexed;
940 print_indexed = 1;
941 print_size = 1;
944 if (nobj_resolved > 0) {
945 p_resolved = (nobj_resolved * 100) /
946 (nobj_total - nobj_loose);
947 if (p_resolved != a->last_p_resolved) {
948 a->last_p_resolved = p_resolved;
949 print_resolved = 1;
950 print_indexed = 1;
951 print_size = 1;
956 if (print_size || print_indexed || print_resolved)
957 printf("\r");
958 if (print_size)
959 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
960 if (print_indexed)
961 printf("; indexing %d%%", p_indexed);
962 if (print_resolved)
963 printf("; resolving deltas %d%%", p_resolved);
964 if (print_size || print_indexed || print_resolved)
965 fflush(stdout);
967 return NULL;
970 static const struct got_error *
971 create_symref(const char *refname, struct got_reference *target_ref,
972 int verbosity, struct got_repository *repo)
974 const struct got_error *err;
975 struct got_reference *head_symref;
977 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
978 if (err)
979 return err;
981 err = got_ref_write(head_symref, repo);
982 if (err == NULL && verbosity > 0) {
983 printf("Created reference %s: %s\n", GOT_REF_HEAD,
984 got_ref_get_name(target_ref));
986 got_ref_close(head_symref);
987 return err;
990 static const struct got_error *
991 list_remote_refs(struct got_pathlist_head *symrefs,
992 struct got_pathlist_head *refs)
994 const struct got_error *err;
995 struct got_pathlist_entry *pe;
997 TAILQ_FOREACH(pe, symrefs, entry) {
998 const char *refname = pe->path;
999 const char *targetref = pe->data;
1001 printf("%s: %s\n", refname, targetref);
1004 TAILQ_FOREACH(pe, refs, entry) {
1005 const char *refname = pe->path;
1006 struct got_object_id *id = pe->data;
1007 char *id_str;
1009 err = got_object_id_str(&id_str, id);
1010 if (err)
1011 return err;
1012 printf("%s: %s\n", refname, id_str);
1013 free(id_str);
1016 return NULL;
1019 static const struct got_error *
1020 create_ref(const char *refname, struct got_object_id *id,
1021 int verbosity, struct got_repository *repo)
1023 const struct got_error *err = NULL;
1024 struct got_reference *ref;
1025 char *id_str;
1027 err = got_object_id_str(&id_str, id);
1028 if (err)
1029 return err;
1031 err = got_ref_alloc(&ref, refname, id);
1032 if (err)
1033 goto done;
1035 err = got_ref_write(ref, repo);
1036 got_ref_close(ref);
1038 if (err == NULL && verbosity >= 0)
1039 printf("Created reference %s: %s\n", refname, id_str);
1040 done:
1041 free(id_str);
1042 return err;
1045 static int
1046 match_wanted_ref(const char *refname, const char *wanted_ref)
1048 if (strncmp(refname, "refs/", 5) != 0)
1049 return 0;
1050 refname += 5;
1053 * Prevent fetching of references that won't make any
1054 * sense outside of the remote repository's context.
1056 if (strncmp(refname, "got/", 4) == 0)
1057 return 0;
1058 if (strncmp(refname, "remotes/", 8) == 0)
1059 return 0;
1061 if (strncmp(wanted_ref, "refs/", 5) == 0)
1062 wanted_ref += 5;
1064 /* Allow prefix match. */
1065 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1066 return 1;
1068 /* Allow exact match. */
1069 return (strcmp(refname, wanted_ref) == 0);
1072 static int
1073 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1075 struct got_pathlist_entry *pe;
1077 TAILQ_FOREACH(pe, wanted_refs, entry) {
1078 if (match_wanted_ref(refname, pe->path))
1079 return 1;
1082 return 0;
1085 static const struct got_error *
1086 create_wanted_ref(const char *refname, struct got_object_id *id,
1087 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1089 const struct got_error *err;
1090 char *remote_refname;
1092 if (strncmp("refs/", refname, 5) == 0)
1093 refname += 5;
1095 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1096 remote_repo_name, refname) == -1)
1097 return got_error_from_errno("asprintf");
1099 err = create_ref(remote_refname, id, verbosity, repo);
1100 free(remote_refname);
1101 return err;
1104 static const struct got_error *
1105 create_gotconfig(const char *proto, const char *host, const char *port,
1106 const char *remote_repo_path, int fetch_all_branches, int mirror_references,
1107 struct got_repository *repo)
1109 const struct got_error *err = NULL;
1110 char *gotconfig_path = NULL;
1111 char *gotconfig = NULL;
1112 FILE *gotconfig_file = NULL;
1113 ssize_t n;
1115 /* Create got.conf(5). */
1116 gotconfig_path = got_repo_get_path_gotconfig(repo);
1117 if (gotconfig_path == NULL) {
1118 err = got_error_from_errno("got_repo_get_path_gotconfig");
1119 goto done;
1121 gotconfig_file = fopen(gotconfig_path, "a");
1122 if (gotconfig_file == NULL) {
1123 err = got_error_from_errno2("fopen", gotconfig_path);
1124 goto done;
1126 if (asprintf(&gotconfig,
1127 "remote \"%s\" {\n"
1128 "\tserver %s\n"
1129 "\tprotocol %s\n"
1130 "%s%s%s"
1131 "\trepository \"%s\"\n"
1132 "%s"
1133 "}\n",
1134 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1135 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1136 remote_repo_path,
1137 mirror_references ? "\tmirror-references yes\n" : "") == -1) {
1138 err = got_error_from_errno("asprintf");
1139 goto done;
1141 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1142 if (n != strlen(gotconfig)) {
1143 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1144 goto done;
1147 done:
1148 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1149 err = got_error_from_errno2("fclose", gotconfig_path);
1150 free(gotconfig_path);
1151 return err;
1154 static const struct got_error *
1155 create_gitconfig(const char *git_url, const char *default_branch,
1156 int fetch_all_branches, int mirror_references, struct got_repository *repo)
1158 const struct got_error *err = NULL;
1159 char *gitconfig_path = NULL;
1160 char *gitconfig = NULL;
1161 FILE *gitconfig_file = NULL;
1162 ssize_t n;
1164 /* Create a config file Git can understand. */
1165 gitconfig_path = got_repo_get_path_gitconfig(repo);
1166 if (gitconfig_path == NULL) {
1167 err = got_error_from_errno("got_repo_get_path_gitconfig");
1168 goto done;
1170 gitconfig_file = fopen(gitconfig_path, "a");
1171 if (gitconfig_file == NULL) {
1172 err = got_error_from_errno2("fopen", gitconfig_path);
1173 goto done;
1175 if (mirror_references) {
1176 if (asprintf(&gitconfig,
1177 "[remote \"%s\"]\n"
1178 "\turl = %s\n"
1179 "\tfetch = +refs/*:refs/*\n"
1180 "\tmirror = true\n",
1181 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1182 err = got_error_from_errno("asprintf");
1183 goto done;
1185 } else if (fetch_all_branches) {
1186 if (asprintf(&gitconfig,
1187 "[remote \"%s\"]\n"
1188 "\turl = %s\n"
1189 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1190 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1191 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1192 err = got_error_from_errno("asprintf");
1193 goto done;
1195 } else {
1196 const char *branchname;
1199 * If the server specified a default branch, use just that one.
1200 * Otherwise fall back to fetching all branches on next fetch.
1202 if (default_branch) {
1203 branchname = default_branch;
1204 if (strncmp(branchname, "refs/heads/", 11) == 0)
1205 branchname += 11;
1206 } else
1207 branchname = "*"; /* fall back to all branches */
1208 if (asprintf(&gitconfig,
1209 "[remote \"%s\"]\n"
1210 "\turl = %s\n"
1211 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1212 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1213 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1214 branchname) == -1) {
1215 err = got_error_from_errno("asprintf");
1216 goto done;
1219 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1220 if (n != strlen(gitconfig)) {
1221 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1222 goto done;
1224 done:
1225 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1226 err = got_error_from_errno2("fclose", gitconfig_path);
1227 free(gitconfig_path);
1228 return err;
1231 static const struct got_error *
1232 create_config_files(const char *proto, const char *host, const char *port,
1233 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1234 int mirror_references, struct got_pathlist_head *symrefs,
1235 struct got_pathlist_head *wanted_branches, struct got_repository *repo)
1237 const struct got_error *err = NULL;
1238 const char *default_branch = NULL;
1239 struct got_pathlist_entry *pe;
1242 * If we asked for a set of wanted branches then use the first
1243 * one of those.
1245 if (!TAILQ_EMPTY(wanted_branches)) {
1246 pe = TAILQ_FIRST(wanted_branches);
1247 default_branch = pe->path;
1248 } else {
1249 /* First HEAD ref listed by server is the default branch. */
1250 TAILQ_FOREACH(pe, symrefs, entry) {
1251 const char *refname = pe->path;
1252 const char *target = pe->data;
1254 if (strcmp(refname, GOT_REF_HEAD) != 0)
1255 continue;
1257 default_branch = target;
1258 break;
1262 /* Create got.conf(5). */
1263 err = create_gotconfig(proto, host, port, remote_repo_path,
1264 fetch_all_branches, mirror_references, repo);
1265 if (err)
1266 return err;
1268 /* Create a config file Git can understand. */
1269 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1270 mirror_references, repo);
1273 static const struct got_error *
1274 cmd_clone(int argc, char *argv[])
1276 const struct got_error *error = NULL;
1277 const char *uri, *dirname;
1278 char *proto, *host, *port, *repo_name, *server_path;
1279 char *default_destdir = NULL, *id_str = NULL;
1280 const char *repo_path;
1281 struct got_repository *repo = NULL;
1282 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1283 struct got_pathlist_entry *pe;
1284 struct got_object_id *pack_hash = NULL;
1285 int ch, fetchfd = -1, fetchstatus;
1286 pid_t fetchpid = -1;
1287 struct got_fetch_progress_arg fpa;
1288 char *git_url = NULL;
1289 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1290 int list_refs_only = 0;
1292 TAILQ_INIT(&refs);
1293 TAILQ_INIT(&symrefs);
1294 TAILQ_INIT(&wanted_branches);
1295 TAILQ_INIT(&wanted_refs);
1297 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1298 switch (ch) {
1299 case 'a':
1300 fetch_all_branches = 1;
1301 break;
1302 case 'b':
1303 error = got_pathlist_append(&wanted_branches,
1304 optarg, NULL);
1305 if (error)
1306 return error;
1307 break;
1308 case 'l':
1309 list_refs_only = 1;
1310 break;
1311 case 'm':
1312 mirror_references = 1;
1313 break;
1314 case 'v':
1315 if (verbosity < 0)
1316 verbosity = 0;
1317 else if (verbosity < 3)
1318 verbosity++;
1319 break;
1320 case 'q':
1321 verbosity = -1;
1322 break;
1323 case 'R':
1324 error = got_pathlist_append(&wanted_refs,
1325 optarg, NULL);
1326 if (error)
1327 return error;
1328 break;
1329 default:
1330 usage_clone();
1331 break;
1334 argc -= optind;
1335 argv += optind;
1337 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1338 errx(1, "-a and -b options are mutually exclusive");
1339 if (list_refs_only) {
1340 if (!TAILQ_EMPTY(&wanted_branches))
1341 errx(1, "-l and -b options are mutually exclusive");
1342 if (fetch_all_branches)
1343 errx(1, "-l and -a options are mutually exclusive");
1344 if (mirror_references)
1345 errx(1, "-l and -m options are mutually exclusive");
1346 if (verbosity == -1)
1347 errx(1, "-l and -q options are mutually exclusive");
1348 if (!TAILQ_EMPTY(&wanted_refs))
1349 errx(1, "-l and -R options are mutually exclusive");
1352 uri = argv[0];
1354 if (argc == 1)
1355 dirname = NULL;
1356 else if (argc == 2)
1357 dirname = argv[1];
1358 else
1359 usage_clone();
1361 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1362 &repo_name, uri);
1363 if (error)
1364 goto done;
1366 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1367 host, port ? ":" : "", port ? port : "",
1368 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1369 error = got_error_from_errno("asprintf");
1370 goto done;
1373 if (strcmp(proto, "git") == 0) {
1374 #ifndef PROFILE
1375 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1376 "sendfd dns inet unveil", NULL) == -1)
1377 err(1, "pledge");
1378 #endif
1379 } else if (strcmp(proto, "git+ssh") == 0 ||
1380 strcmp(proto, "ssh") == 0) {
1381 #ifndef PROFILE
1382 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1383 "sendfd unveil", NULL) == -1)
1384 err(1, "pledge");
1385 #endif
1386 } else if (strcmp(proto, "http") == 0 ||
1387 strcmp(proto, "git+http") == 0) {
1388 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1389 goto done;
1390 } else {
1391 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1392 goto done;
1394 if (dirname == NULL) {
1395 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1396 error = got_error_from_errno("asprintf");
1397 goto done;
1399 repo_path = default_destdir;
1400 } else
1401 repo_path = dirname;
1403 if (!list_refs_only) {
1404 error = got_path_mkdir(repo_path);
1405 if (error &&
1406 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1407 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1408 goto done;
1409 if (!got_path_dir_is_empty(repo_path)) {
1410 error = got_error_path(repo_path,
1411 GOT_ERR_DIR_NOT_EMPTY);
1412 goto done;
1416 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1417 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1418 error = got_error_from_errno2("unveil",
1419 GOT_FETCH_PATH_SSH);
1420 goto done;
1423 error = apply_unveil(repo ? got_repo_get_path(repo) : NULL, 0, NULL);
1424 if (error)
1425 goto done;
1427 if (verbosity >= 0)
1428 printf("Connecting to %s%s%s\n", host,
1429 port ? ":" : "", port ? port : "");
1431 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1432 server_path, verbosity);
1433 if (error)
1434 goto done;
1436 if (!list_refs_only) {
1437 error = got_repo_init(repo_path);
1438 if (error)
1439 goto done;
1440 error = got_repo_open(&repo, repo_path, NULL);
1441 if (error)
1442 goto done;
1445 fpa.last_scaled_size[0] = '\0';
1446 fpa.last_p_indexed = -1;
1447 fpa.last_p_resolved = -1;
1448 fpa.verbosity = verbosity;
1449 fpa.create_configs = 1;
1450 fpa.configs_created = 0;
1451 fpa.repo = repo;
1452 fpa.config_info.symrefs = &symrefs;
1453 fpa.config_info.wanted_branches = &wanted_branches;
1454 fpa.config_info.proto = proto;
1455 fpa.config_info.host = host;
1456 fpa.config_info.port = port;
1457 fpa.config_info.remote_repo_path = server_path;
1458 fpa.config_info.git_url = git_url;
1459 fpa.config_info.fetch_all_branches = fetch_all_branches;
1460 fpa.config_info.mirror_references = mirror_references;
1461 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1462 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1463 fetch_all_branches, &wanted_branches, &wanted_refs,
1464 list_refs_only, verbosity, fetchfd, repo,
1465 fetch_progress, &fpa);
1466 if (error)
1467 goto done;
1469 if (list_refs_only) {
1470 error = list_remote_refs(&symrefs, &refs);
1471 goto done;
1474 error = got_object_id_str(&id_str, pack_hash);
1475 if (error)
1476 goto done;
1477 if (verbosity >= 0)
1478 printf("\nFetched %s.pack\n", id_str);
1479 free(id_str);
1481 /* Set up references provided with the pack file. */
1482 TAILQ_FOREACH(pe, &refs, entry) {
1483 const char *refname = pe->path;
1484 struct got_object_id *id = pe->data;
1485 char *remote_refname;
1487 if (is_wanted_ref(&wanted_refs, refname) &&
1488 !mirror_references) {
1489 error = create_wanted_ref(refname, id,
1490 GOT_FETCH_DEFAULT_REMOTE_NAME,
1491 verbosity - 1, repo);
1492 if (error)
1493 goto done;
1494 continue;
1497 error = create_ref(refname, id, verbosity - 1, repo);
1498 if (error)
1499 goto done;
1501 if (mirror_references)
1502 continue;
1504 if (strncmp("refs/heads/", refname, 11) != 0)
1505 continue;
1507 if (asprintf(&remote_refname,
1508 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1509 refname + 11) == -1) {
1510 error = got_error_from_errno("asprintf");
1511 goto done;
1513 error = create_ref(remote_refname, id, verbosity - 1, repo);
1514 free(remote_refname);
1515 if (error)
1516 goto done;
1519 /* Set the HEAD reference if the server provided one. */
1520 TAILQ_FOREACH(pe, &symrefs, entry) {
1521 struct got_reference *target_ref;
1522 const char *refname = pe->path;
1523 const char *target = pe->data;
1524 char *remote_refname = NULL, *remote_target = NULL;
1526 if (strcmp(refname, GOT_REF_HEAD) != 0)
1527 continue;
1529 error = got_ref_open(&target_ref, repo, target, 0);
1530 if (error) {
1531 if (error->code == GOT_ERR_NOT_REF) {
1532 error = NULL;
1533 continue;
1535 goto done;
1538 error = create_symref(refname, target_ref, verbosity, repo);
1539 got_ref_close(target_ref);
1540 if (error)
1541 goto done;
1543 if (mirror_references)
1544 continue;
1546 if (strncmp("refs/heads/", target, 11) != 0)
1547 continue;
1549 if (asprintf(&remote_refname,
1550 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1551 refname) == -1) {
1552 error = got_error_from_errno("asprintf");
1553 goto done;
1555 if (asprintf(&remote_target,
1556 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1557 target + 11) == -1) {
1558 error = got_error_from_errno("asprintf");
1559 free(remote_refname);
1560 goto done;
1562 error = got_ref_open(&target_ref, repo, remote_target, 0);
1563 if (error) {
1564 free(remote_refname);
1565 free(remote_target);
1566 if (error->code == GOT_ERR_NOT_REF) {
1567 error = NULL;
1568 continue;
1570 goto done;
1572 error = create_symref(remote_refname, target_ref,
1573 verbosity - 1, repo);
1574 free(remote_refname);
1575 free(remote_target);
1576 got_ref_close(target_ref);
1577 if (error)
1578 goto done;
1580 if (pe == NULL) {
1582 * We failed to set the HEAD reference. If we asked for
1583 * a set of wanted branches use the first of one of those
1584 * which could be fetched instead.
1586 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1587 const char *target = pe->path;
1588 struct got_reference *target_ref;
1590 error = got_ref_open(&target_ref, repo, target, 0);
1591 if (error) {
1592 if (error->code == GOT_ERR_NOT_REF) {
1593 error = NULL;
1594 continue;
1596 goto done;
1599 error = create_symref(GOT_REF_HEAD, target_ref,
1600 verbosity, repo);
1601 got_ref_close(target_ref);
1602 if (error)
1603 goto done;
1604 break;
1608 if (verbosity >= 0)
1609 printf("Created %s repository '%s'\n",
1610 mirror_references ? "mirrored" : "cloned", repo_path);
1611 done:
1612 if (fetchpid > 0) {
1613 if (kill(fetchpid, SIGTERM) == -1)
1614 error = got_error_from_errno("kill");
1615 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1616 error = got_error_from_errno("waitpid");
1618 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1619 error = got_error_from_errno("close");
1620 if (repo)
1621 got_repo_close(repo);
1622 TAILQ_FOREACH(pe, &refs, entry) {
1623 free((void *)pe->path);
1624 free(pe->data);
1626 got_pathlist_free(&refs);
1627 TAILQ_FOREACH(pe, &symrefs, entry) {
1628 free((void *)pe->path);
1629 free(pe->data);
1631 got_pathlist_free(&symrefs);
1632 got_pathlist_free(&wanted_branches);
1633 got_pathlist_free(&wanted_refs);
1634 free(pack_hash);
1635 free(proto);
1636 free(host);
1637 free(port);
1638 free(server_path);
1639 free(repo_name);
1640 free(default_destdir);
1641 free(git_url);
1642 return error;
1645 static const struct got_error *
1646 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1647 int replace_tags, int verbosity, struct got_repository *repo)
1649 const struct got_error *err = NULL;
1650 char *new_id_str = NULL;
1651 struct got_object_id *old_id = NULL;
1653 err = got_object_id_str(&new_id_str, new_id);
1654 if (err)
1655 goto done;
1657 if (!replace_tags &&
1658 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1659 err = got_ref_resolve(&old_id, repo, ref);
1660 if (err)
1661 goto done;
1662 if (got_object_id_cmp(old_id, new_id) == 0)
1663 goto done;
1664 if (verbosity >= 0) {
1665 printf("Rejecting update of existing tag %s: %s\n",
1666 got_ref_get_name(ref), new_id_str);
1668 goto done;
1671 if (got_ref_is_symbolic(ref)) {
1672 if (verbosity >= 0) {
1673 printf("Replacing reference %s: %s\n",
1674 got_ref_get_name(ref),
1675 got_ref_get_symref_target(ref));
1677 err = got_ref_change_symref_to_ref(ref, new_id);
1678 if (err)
1679 goto done;
1680 err = got_ref_write(ref, repo);
1681 if (err)
1682 goto done;
1683 } else {
1684 err = got_ref_resolve(&old_id, repo, ref);
1685 if (err)
1686 goto done;
1687 if (got_object_id_cmp(old_id, new_id) == 0)
1688 goto done;
1690 err = got_ref_change_ref(ref, new_id);
1691 if (err)
1692 goto done;
1693 err = got_ref_write(ref, repo);
1694 if (err)
1695 goto done;
1698 if (verbosity >= 0)
1699 printf("Updated %s: %s\n", got_ref_get_name(ref),
1700 new_id_str);
1701 done:
1702 free(old_id);
1703 free(new_id_str);
1704 return err;
1707 static const struct got_error *
1708 update_symref(const char *refname, struct got_reference *target_ref,
1709 int verbosity, struct got_repository *repo)
1711 const struct got_error *err = NULL, *unlock_err;
1712 struct got_reference *symref;
1713 int symref_is_locked = 0;
1715 err = got_ref_open(&symref, repo, refname, 1);
1716 if (err) {
1717 if (err->code != GOT_ERR_NOT_REF)
1718 return err;
1719 err = got_ref_alloc_symref(&symref, refname, target_ref);
1720 if (err)
1721 goto done;
1723 err = got_ref_write(symref, repo);
1724 if (err)
1725 goto done;
1727 if (verbosity >= 0)
1728 printf("Created reference %s: %s\n",
1729 got_ref_get_name(symref),
1730 got_ref_get_symref_target(symref));
1731 } else {
1732 symref_is_locked = 1;
1734 if (strcmp(got_ref_get_symref_target(symref),
1735 got_ref_get_name(target_ref)) == 0)
1736 goto done;
1738 err = got_ref_change_symref(symref,
1739 got_ref_get_name(target_ref));
1740 if (err)
1741 goto done;
1743 err = got_ref_write(symref, repo);
1744 if (err)
1745 goto done;
1747 if (verbosity >= 0)
1748 printf("Updated %s: %s\n", got_ref_get_name(symref),
1749 got_ref_get_symref_target(symref));
1752 done:
1753 if (symref_is_locked) {
1754 unlock_err = got_ref_unlock(symref);
1755 if (unlock_err && err == NULL)
1756 err = unlock_err;
1758 got_ref_close(symref);
1759 return err;
1762 __dead static void
1763 usage_fetch(void)
1765 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1766 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1767 "[remote-repository-name]\n",
1768 getprogname());
1769 exit(1);
1772 static const struct got_error *
1773 delete_missing_ref(struct got_reference *ref,
1774 int verbosity, struct got_repository *repo)
1776 const struct got_error *err = NULL;
1777 struct got_object_id *id = NULL;
1778 char *id_str = NULL;
1780 if (got_ref_is_symbolic(ref)) {
1781 err = got_ref_delete(ref, repo);
1782 if (err)
1783 return err;
1784 if (verbosity >= 0) {
1785 printf("Deleted reference %s: %s\n",
1786 got_ref_get_name(ref),
1787 got_ref_get_symref_target(ref));
1789 } else {
1790 err = got_ref_resolve(&id, repo, ref);
1791 if (err)
1792 return err;
1793 err = got_object_id_str(&id_str, id);
1794 if (err)
1795 goto done;
1797 err = got_ref_delete(ref, repo);
1798 if (err)
1799 goto done;
1800 if (verbosity >= 0) {
1801 printf("Deleted reference %s: %s\n",
1802 got_ref_get_name(ref), id_str);
1805 done:
1806 free(id);
1807 free(id_str);
1808 return NULL;
1811 static const struct got_error *
1812 delete_missing_refs(struct got_pathlist_head *their_refs,
1813 struct got_pathlist_head *their_symrefs,
1814 const struct got_remote_repo *remote,
1815 int verbosity, struct got_repository *repo)
1817 const struct got_error *err = NULL, *unlock_err;
1818 struct got_reflist_head my_refs;
1819 struct got_reflist_entry *re;
1820 struct got_pathlist_entry *pe;
1821 char *remote_namespace = NULL;
1822 char *local_refname = NULL;
1824 SIMPLEQ_INIT(&my_refs);
1826 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
1827 == -1)
1828 return got_error_from_errno("asprintf");
1830 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1831 if (err)
1832 goto done;
1834 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1835 const char *refname = got_ref_get_name(re->ref);
1837 if (!remote->mirror_references) {
1838 if (strncmp(refname, remote_namespace,
1839 strlen(remote_namespace)) == 0) {
1840 if (strcmp(refname + strlen(remote_namespace),
1841 GOT_REF_HEAD) == 0)
1842 continue;
1843 if (asprintf(&local_refname, "refs/heads/%s",
1844 refname + strlen(remote_namespace)) == -1) {
1845 err = got_error_from_errno("asprintf");
1846 goto done;
1848 } else if (strncmp(refname, "refs/tags/", 10) != 0)
1849 continue;
1852 TAILQ_FOREACH(pe, their_refs, entry) {
1853 if (strcmp(local_refname, pe->path) == 0)
1854 break;
1856 if (pe != NULL)
1857 continue;
1859 TAILQ_FOREACH(pe, their_symrefs, entry) {
1860 if (strcmp(local_refname, pe->path) == 0)
1861 break;
1863 if (pe != NULL)
1864 continue;
1866 err = delete_missing_ref(re->ref, verbosity, repo);
1867 if (err)
1868 break;
1870 if (local_refname) {
1871 struct got_reference *ref;
1872 err = got_ref_open(&ref, repo, local_refname, 1);
1873 if (err) {
1874 if (err->code != GOT_ERR_NOT_REF)
1875 break;
1876 free(local_refname);
1877 local_refname = NULL;
1878 continue;
1880 err = delete_missing_ref(ref, verbosity, repo);
1881 if (err)
1882 break;
1883 unlock_err = got_ref_unlock(ref);
1884 got_ref_close(ref);
1885 if (unlock_err && err == NULL) {
1886 err = unlock_err;
1887 break;
1890 free(local_refname);
1891 local_refname = NULL;
1894 done:
1895 free(remote_namespace);
1896 free(local_refname);
1897 return err;
1900 static const struct got_error *
1901 update_wanted_ref(const char *refname, struct got_object_id *id,
1902 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1904 const struct got_error *err, *unlock_err;
1905 char *remote_refname;
1906 struct got_reference *ref;
1908 if (strncmp("refs/", refname, 5) == 0)
1909 refname += 5;
1911 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1912 remote_repo_name, refname) == -1)
1913 return got_error_from_errno("asprintf");
1915 err = got_ref_open(&ref, repo, remote_refname, 1);
1916 if (err) {
1917 if (err->code != GOT_ERR_NOT_REF)
1918 goto done;
1919 err = create_ref(remote_refname, id, verbosity, repo);
1920 } else {
1921 err = update_ref(ref, id, 0, verbosity, repo);
1922 unlock_err = got_ref_unlock(ref);
1923 if (unlock_err && err == NULL)
1924 err = unlock_err;
1925 got_ref_close(ref);
1927 done:
1928 free(remote_refname);
1929 return err;
1932 static const struct got_error *
1933 cmd_fetch(int argc, char *argv[])
1935 const struct got_error *error = NULL, *unlock_err;
1936 char *cwd = NULL, *repo_path = NULL;
1937 const char *remote_name;
1938 char *proto = NULL, *host = NULL, *port = NULL;
1939 char *repo_name = NULL, *server_path = NULL;
1940 const struct got_remote_repo *remotes, *remote = NULL;
1941 int nremotes;
1942 char *id_str = NULL;
1943 struct got_repository *repo = NULL;
1944 struct got_worktree *worktree = NULL;
1945 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
1946 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1947 struct got_pathlist_entry *pe;
1948 struct got_object_id *pack_hash = NULL;
1949 int i, ch, fetchfd = -1, fetchstatus;
1950 pid_t fetchpid = -1;
1951 struct got_fetch_progress_arg fpa;
1952 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
1953 int delete_refs = 0, replace_tags = 0;
1955 TAILQ_INIT(&refs);
1956 TAILQ_INIT(&symrefs);
1957 TAILQ_INIT(&wanted_branches);
1958 TAILQ_INIT(&wanted_refs);
1960 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
1961 switch (ch) {
1962 case 'a':
1963 fetch_all_branches = 1;
1964 break;
1965 case 'b':
1966 error = got_pathlist_append(&wanted_branches,
1967 optarg, NULL);
1968 if (error)
1969 return error;
1970 break;
1971 case 'd':
1972 delete_refs = 1;
1973 break;
1974 case 'l':
1975 list_refs_only = 1;
1976 break;
1977 case 'r':
1978 repo_path = realpath(optarg, NULL);
1979 if (repo_path == NULL)
1980 return got_error_from_errno2("realpath",
1981 optarg);
1982 got_path_strip_trailing_slashes(repo_path);
1983 break;
1984 case 't':
1985 replace_tags = 1;
1986 break;
1987 case 'v':
1988 if (verbosity < 0)
1989 verbosity = 0;
1990 else if (verbosity < 3)
1991 verbosity++;
1992 break;
1993 case 'q':
1994 verbosity = -1;
1995 break;
1996 case 'R':
1997 error = got_pathlist_append(&wanted_refs,
1998 optarg, NULL);
1999 if (error)
2000 return error;
2001 break;
2002 default:
2003 usage_fetch();
2004 break;
2007 argc -= optind;
2008 argv += optind;
2010 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2011 errx(1, "-a and -b options are mutually exclusive");
2012 if (list_refs_only) {
2013 if (!TAILQ_EMPTY(&wanted_branches))
2014 errx(1, "-l and -b options are mutually exclusive");
2015 if (fetch_all_branches)
2016 errx(1, "-l and -a options are mutually exclusive");
2017 if (delete_refs)
2018 errx(1, "-l and -d options are mutually exclusive");
2019 if (verbosity == -1)
2020 errx(1, "-l and -q options are mutually exclusive");
2023 if (argc == 0)
2024 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2025 else if (argc == 1)
2026 remote_name = argv[0];
2027 else
2028 usage_fetch();
2030 cwd = getcwd(NULL, 0);
2031 if (cwd == NULL) {
2032 error = got_error_from_errno("getcwd");
2033 goto done;
2036 if (repo_path == NULL) {
2037 error = got_worktree_open(&worktree, cwd);
2038 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2039 goto done;
2040 else
2041 error = NULL;
2042 if (worktree) {
2043 repo_path =
2044 strdup(got_worktree_get_repo_path(worktree));
2045 if (repo_path == NULL)
2046 error = got_error_from_errno("strdup");
2047 if (error)
2048 goto done;
2049 } else {
2050 repo_path = strdup(cwd);
2051 if (repo_path == NULL) {
2052 error = got_error_from_errno("strdup");
2053 goto done;
2058 error = got_repo_open(&repo, repo_path, NULL);
2059 if (error)
2060 goto done;
2062 if (worktree) {
2063 worktree_conf = got_worktree_get_gotconfig(worktree);
2064 if (worktree_conf) {
2065 got_gotconfig_get_remotes(&nremotes, &remotes,
2066 worktree_conf);
2067 for (i = 0; i < nremotes; i++) {
2068 remote = &remotes[i];
2069 if (strcmp(remote->name, remote_name) == 0)
2070 break;
2074 if (remote == NULL) {
2075 repo_conf = got_repo_get_gotconfig(repo);
2076 if (repo_conf) {
2077 got_gotconfig_get_remotes(&nremotes, &remotes,
2078 repo_conf);
2079 for (i = 0; i < nremotes; i++) {
2080 remote = &remotes[i];
2081 if (strcmp(remote->name, remote_name) == 0)
2082 break;
2086 if (remote == NULL) {
2087 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2088 for (i = 0; i < nremotes; i++) {
2089 remote = &remotes[i];
2090 if (strcmp(remote->name, remote_name) == 0)
2091 break;
2094 if (remote == NULL) {
2095 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2096 goto done;
2099 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
2100 &repo_name, remote->url);
2101 if (error)
2102 goto done;
2104 if (strcmp(proto, "git") == 0) {
2105 #ifndef PROFILE
2106 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2107 "sendfd dns inet unveil", NULL) == -1)
2108 err(1, "pledge");
2109 #endif
2110 } else if (strcmp(proto, "git+ssh") == 0 ||
2111 strcmp(proto, "ssh") == 0) {
2112 #ifndef PROFILE
2113 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2114 "sendfd unveil", NULL) == -1)
2115 err(1, "pledge");
2116 #endif
2117 } else if (strcmp(proto, "http") == 0 ||
2118 strcmp(proto, "git+http") == 0) {
2119 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2120 goto done;
2121 } else {
2122 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2123 goto done;
2126 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
2127 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
2128 error = got_error_from_errno2("unveil",
2129 GOT_FETCH_PATH_SSH);
2130 goto done;
2133 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2134 if (error)
2135 goto done;
2137 if (verbosity >= 0)
2138 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2139 port ? ":" : "", port ? port : "");
2141 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2142 server_path, verbosity);
2143 if (error)
2144 goto done;
2146 fpa.last_scaled_size[0] = '\0';
2147 fpa.last_p_indexed = -1;
2148 fpa.last_p_resolved = -1;
2149 fpa.verbosity = verbosity;
2150 fpa.repo = repo;
2151 fpa.create_configs = 0;
2152 fpa.configs_created = 0;
2153 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2154 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2155 remote->mirror_references, fetch_all_branches, &wanted_branches,
2156 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2157 fetch_progress, &fpa);
2158 if (error)
2159 goto done;
2161 if (list_refs_only) {
2162 error = list_remote_refs(&symrefs, &refs);
2163 goto done;
2166 if (pack_hash == NULL) {
2167 if (verbosity >= 0)
2168 printf("Already up-to-date\n");
2169 } else if (verbosity >= 0) {
2170 error = got_object_id_str(&id_str, pack_hash);
2171 if (error)
2172 goto done;
2173 printf("\nFetched %s.pack\n", id_str);
2174 free(id_str);
2175 id_str = NULL;
2178 /* Update references provided with the pack file. */
2179 TAILQ_FOREACH(pe, &refs, entry) {
2180 const char *refname = pe->path;
2181 struct got_object_id *id = pe->data;
2182 struct got_reference *ref;
2183 char *remote_refname;
2185 if (is_wanted_ref(&wanted_refs, refname) &&
2186 !remote->mirror_references) {
2187 error = update_wanted_ref(refname, id,
2188 remote->name, verbosity, repo);
2189 if (error)
2190 goto done;
2191 continue;
2194 if (remote->mirror_references ||
2195 strncmp("refs/tags/", refname, 10) == 0) {
2196 error = got_ref_open(&ref, repo, refname, 1);
2197 if (error) {
2198 if (error->code != GOT_ERR_NOT_REF)
2199 goto done;
2200 error = create_ref(refname, id, verbosity,
2201 repo);
2202 if (error)
2203 goto done;
2204 } else {
2205 error = update_ref(ref, id, replace_tags,
2206 verbosity, repo);
2207 unlock_err = got_ref_unlock(ref);
2208 if (unlock_err && error == NULL)
2209 error = unlock_err;
2210 got_ref_close(ref);
2211 if (error)
2212 goto done;
2214 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2215 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2216 remote_name, refname + 11) == -1) {
2217 error = got_error_from_errno("asprintf");
2218 goto done;
2221 error = got_ref_open(&ref, repo, remote_refname, 1);
2222 if (error) {
2223 if (error->code != GOT_ERR_NOT_REF)
2224 goto done;
2225 error = create_ref(remote_refname, id,
2226 verbosity, repo);
2227 if (error)
2228 goto done;
2229 } else {
2230 error = update_ref(ref, id, replace_tags,
2231 verbosity, repo);
2232 unlock_err = got_ref_unlock(ref);
2233 if (unlock_err && error == NULL)
2234 error = unlock_err;
2235 got_ref_close(ref);
2236 if (error)
2237 goto done;
2240 /* Also create a local branch if none exists yet. */
2241 error = got_ref_open(&ref, repo, refname, 1);
2242 if (error) {
2243 if (error->code != GOT_ERR_NOT_REF)
2244 goto done;
2245 error = create_ref(refname, id, verbosity,
2246 repo);
2247 if (error)
2248 goto done;
2249 } else {
2250 unlock_err = got_ref_unlock(ref);
2251 if (unlock_err && error == NULL)
2252 error = unlock_err;
2253 got_ref_close(ref);
2257 if (delete_refs) {
2258 error = delete_missing_refs(&refs, &symrefs, remote,
2259 verbosity, repo);
2260 if (error)
2261 goto done;
2264 if (!remote->mirror_references) {
2265 /* Update remote HEAD reference if the server provided one. */
2266 TAILQ_FOREACH(pe, &symrefs, entry) {
2267 struct got_reference *target_ref;
2268 const char *refname = pe->path;
2269 const char *target = pe->data;
2270 char *remote_refname = NULL, *remote_target = NULL;
2272 if (strcmp(refname, GOT_REF_HEAD) != 0)
2273 continue;
2275 if (strncmp("refs/heads/", target, 11) != 0)
2276 continue;
2278 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2279 remote->name, refname) == -1) {
2280 error = got_error_from_errno("asprintf");
2281 goto done;
2283 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2284 remote->name, target + 11) == -1) {
2285 error = got_error_from_errno("asprintf");
2286 free(remote_refname);
2287 goto done;
2290 error = got_ref_open(&target_ref, repo, remote_target,
2291 0);
2292 if (error) {
2293 free(remote_refname);
2294 free(remote_target);
2295 if (error->code == GOT_ERR_NOT_REF) {
2296 error = NULL;
2297 continue;
2299 goto done;
2301 error = update_symref(remote_refname, target_ref,
2302 verbosity, repo);
2303 free(remote_refname);
2304 free(remote_target);
2305 got_ref_close(target_ref);
2306 if (error)
2307 goto done;
2310 done:
2311 if (fetchpid > 0) {
2312 if (kill(fetchpid, SIGTERM) == -1)
2313 error = got_error_from_errno("kill");
2314 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2315 error = got_error_from_errno("waitpid");
2317 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2318 error = got_error_from_errno("close");
2319 if (repo)
2320 got_repo_close(repo);
2321 if (worktree)
2322 got_worktree_close(worktree);
2323 TAILQ_FOREACH(pe, &refs, entry) {
2324 free((void *)pe->path);
2325 free(pe->data);
2327 got_pathlist_free(&refs);
2328 TAILQ_FOREACH(pe, &symrefs, entry) {
2329 free((void *)pe->path);
2330 free(pe->data);
2332 got_pathlist_free(&symrefs);
2333 got_pathlist_free(&wanted_branches);
2334 got_pathlist_free(&wanted_refs);
2335 free(id_str);
2336 free(cwd);
2337 free(repo_path);
2338 free(pack_hash);
2339 free(proto);
2340 free(host);
2341 free(port);
2342 free(server_path);
2343 free(repo_name);
2344 return error;
2348 __dead static void
2349 usage_checkout(void)
2351 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2352 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2353 exit(1);
2356 static void
2357 show_worktree_base_ref_warning(void)
2359 fprintf(stderr, "%s: warning: could not create a reference "
2360 "to the work tree's base commit; the commit could be "
2361 "garbage-collected by Git; making the repository "
2362 "writable and running 'got update' will prevent this\n",
2363 getprogname());
2366 struct got_checkout_progress_arg {
2367 const char *worktree_path;
2368 int had_base_commit_ref_error;
2371 static const struct got_error *
2372 checkout_progress(void *arg, unsigned char status, const char *path)
2374 struct got_checkout_progress_arg *a = arg;
2376 /* Base commit bump happens silently. */
2377 if (status == GOT_STATUS_BUMP_BASE)
2378 return NULL;
2380 if (status == GOT_STATUS_BASE_REF_ERR) {
2381 a->had_base_commit_ref_error = 1;
2382 return NULL;
2385 while (path[0] == '/')
2386 path++;
2388 printf("%c %s/%s\n", status, a->worktree_path, path);
2389 return NULL;
2392 static const struct got_error *
2393 check_cancelled(void *arg)
2395 if (sigint_received || sigpipe_received)
2396 return got_error(GOT_ERR_CANCELLED);
2397 return NULL;
2400 static const struct got_error *
2401 check_linear_ancestry(struct got_object_id *commit_id,
2402 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2403 struct got_repository *repo)
2405 const struct got_error *err = NULL;
2406 struct got_object_id *yca_id;
2408 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2409 commit_id, base_commit_id, repo, check_cancelled, NULL);
2410 if (err)
2411 return err;
2413 if (yca_id == NULL)
2414 return got_error(GOT_ERR_ANCESTRY);
2417 * Require a straight line of history between the target commit
2418 * and the work tree's base commit.
2420 * Non-linear situations such as this require a rebase:
2422 * (commit) D F (base_commit)
2423 * \ /
2424 * C E
2425 * \ /
2426 * B (yca)
2427 * |
2428 * A
2430 * 'got update' only handles linear cases:
2431 * Update forwards in time: A (base/yca) - B - C - D (commit)
2432 * Update backwards in time: D (base) - C - B - A (commit/yca)
2434 if (allow_forwards_in_time_only) {
2435 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2436 return got_error(GOT_ERR_ANCESTRY);
2437 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2438 got_object_id_cmp(base_commit_id, yca_id) != 0)
2439 return got_error(GOT_ERR_ANCESTRY);
2441 free(yca_id);
2442 return NULL;
2445 static const struct got_error *
2446 check_same_branch(struct got_object_id *commit_id,
2447 struct got_reference *head_ref, struct got_object_id *yca_id,
2448 struct got_repository *repo)
2450 const struct got_error *err = NULL;
2451 struct got_commit_graph *graph = NULL;
2452 struct got_object_id *head_commit_id = NULL;
2453 int is_same_branch = 0;
2455 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2456 if (err)
2457 goto done;
2459 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2460 is_same_branch = 1;
2461 goto done;
2463 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2464 is_same_branch = 1;
2465 goto done;
2468 err = got_commit_graph_open(&graph, "/", 1);
2469 if (err)
2470 goto done;
2472 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2473 check_cancelled, NULL);
2474 if (err)
2475 goto done;
2477 for (;;) {
2478 struct got_object_id *id;
2479 err = got_commit_graph_iter_next(&id, graph, repo,
2480 check_cancelled, NULL);
2481 if (err) {
2482 if (err->code == GOT_ERR_ITER_COMPLETED)
2483 err = NULL;
2484 break;
2487 if (id) {
2488 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2489 break;
2490 if (got_object_id_cmp(id, commit_id) == 0) {
2491 is_same_branch = 1;
2492 break;
2496 done:
2497 if (graph)
2498 got_commit_graph_close(graph);
2499 free(head_commit_id);
2500 if (!err && !is_same_branch)
2501 err = got_error(GOT_ERR_ANCESTRY);
2502 return err;
2505 static const struct got_error *
2506 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2508 static char msg[512];
2509 const char *branch_name;
2511 if (got_ref_is_symbolic(ref))
2512 branch_name = got_ref_get_symref_target(ref);
2513 else
2514 branch_name = got_ref_get_name(ref);
2516 if (strncmp("refs/heads/", branch_name, 11) == 0)
2517 branch_name += 11;
2519 snprintf(msg, sizeof(msg),
2520 "target commit is not contained in branch '%s'; "
2521 "the branch to use must be specified with -b; "
2522 "if necessary a new branch can be created for "
2523 "this commit with 'got branch -c %s BRANCH_NAME'",
2524 branch_name, commit_id_str);
2526 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2529 static const struct got_error *
2530 cmd_checkout(int argc, char *argv[])
2532 const struct got_error *error = NULL;
2533 struct got_repository *repo = NULL;
2534 struct got_reference *head_ref = NULL;
2535 struct got_worktree *worktree = NULL;
2536 char *repo_path = NULL;
2537 char *worktree_path = NULL;
2538 const char *path_prefix = "";
2539 const char *branch_name = GOT_REF_HEAD;
2540 char *commit_id_str = NULL;
2541 char *cwd = NULL, *path = NULL;
2542 int ch, same_path_prefix, allow_nonempty = 0;
2543 struct got_pathlist_head paths;
2544 struct got_checkout_progress_arg cpa;
2546 TAILQ_INIT(&paths);
2548 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2549 switch (ch) {
2550 case 'b':
2551 branch_name = optarg;
2552 break;
2553 case 'c':
2554 commit_id_str = strdup(optarg);
2555 if (commit_id_str == NULL)
2556 return got_error_from_errno("strdup");
2557 break;
2558 case 'E':
2559 allow_nonempty = 1;
2560 break;
2561 case 'p':
2562 path_prefix = optarg;
2563 break;
2564 default:
2565 usage_checkout();
2566 /* NOTREACHED */
2570 argc -= optind;
2571 argv += optind;
2573 #ifndef PROFILE
2574 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2575 "unveil", NULL) == -1)
2576 err(1, "pledge");
2577 #endif
2578 if (argc == 1) {
2579 char *base, *dotgit;
2580 repo_path = realpath(argv[0], NULL);
2581 if (repo_path == NULL)
2582 return got_error_from_errno2("realpath", argv[0]);
2583 cwd = getcwd(NULL, 0);
2584 if (cwd == NULL) {
2585 error = got_error_from_errno("getcwd");
2586 goto done;
2588 if (path_prefix[0])
2589 path = strdup(path_prefix);
2590 else
2591 path = strdup(repo_path);
2592 if (path == NULL) {
2593 error = got_error_from_errno("strdup");
2594 goto done;
2596 base = basename(path);
2597 if (base == NULL) {
2598 error = got_error_from_errno2("basename", path);
2599 goto done;
2601 dotgit = strstr(base, ".git");
2602 if (dotgit)
2603 *dotgit = '\0';
2604 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2605 error = got_error_from_errno("asprintf");
2606 goto done;
2608 } else if (argc == 2) {
2609 repo_path = realpath(argv[0], NULL);
2610 if (repo_path == NULL) {
2611 error = got_error_from_errno2("realpath", argv[0]);
2612 goto done;
2614 worktree_path = realpath(argv[1], NULL);
2615 if (worktree_path == NULL) {
2616 if (errno != ENOENT) {
2617 error = got_error_from_errno2("realpath",
2618 argv[1]);
2619 goto done;
2621 worktree_path = strdup(argv[1]);
2622 if (worktree_path == NULL) {
2623 error = got_error_from_errno("strdup");
2624 goto done;
2627 } else
2628 usage_checkout();
2630 got_path_strip_trailing_slashes(repo_path);
2631 got_path_strip_trailing_slashes(worktree_path);
2633 error = got_repo_open(&repo, repo_path, NULL);
2634 if (error != NULL)
2635 goto done;
2637 /* Pre-create work tree path for unveil(2) */
2638 error = got_path_mkdir(worktree_path);
2639 if (error) {
2640 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2641 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2642 goto done;
2643 if (!allow_nonempty &&
2644 !got_path_dir_is_empty(worktree_path)) {
2645 error = got_error_path(worktree_path,
2646 GOT_ERR_DIR_NOT_EMPTY);
2647 goto done;
2651 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2652 if (error)
2653 goto done;
2655 error = got_ref_open(&head_ref, repo, branch_name, 0);
2656 if (error != NULL)
2657 goto done;
2659 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2660 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2661 goto done;
2663 error = got_worktree_open(&worktree, worktree_path);
2664 if (error != NULL)
2665 goto done;
2667 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2668 path_prefix);
2669 if (error != NULL)
2670 goto done;
2671 if (!same_path_prefix) {
2672 error = got_error(GOT_ERR_PATH_PREFIX);
2673 goto done;
2676 if (commit_id_str) {
2677 struct got_object_id *commit_id;
2678 error = got_repo_match_object_id(&commit_id, NULL,
2679 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2680 if (error)
2681 goto done;
2682 error = check_linear_ancestry(commit_id,
2683 got_worktree_get_base_commit_id(worktree), 0, repo);
2684 if (error != NULL) {
2685 free(commit_id);
2686 if (error->code == GOT_ERR_ANCESTRY) {
2687 error = checkout_ancestry_error(
2688 head_ref, commit_id_str);
2690 goto done;
2692 error = check_same_branch(commit_id, head_ref, NULL, repo);
2693 if (error) {
2694 if (error->code == GOT_ERR_ANCESTRY) {
2695 error = checkout_ancestry_error(
2696 head_ref, commit_id_str);
2698 goto done;
2700 error = got_worktree_set_base_commit_id(worktree, repo,
2701 commit_id);
2702 free(commit_id);
2703 if (error)
2704 goto done;
2707 error = got_pathlist_append(&paths, "", NULL);
2708 if (error)
2709 goto done;
2710 cpa.worktree_path = worktree_path;
2711 cpa.had_base_commit_ref_error = 0;
2712 error = got_worktree_checkout_files(worktree, &paths, repo,
2713 checkout_progress, &cpa, check_cancelled, NULL);
2714 if (error != NULL)
2715 goto done;
2717 printf("Now shut up and hack\n");
2718 if (cpa.had_base_commit_ref_error)
2719 show_worktree_base_ref_warning();
2720 done:
2721 got_pathlist_free(&paths);
2722 free(commit_id_str);
2723 free(repo_path);
2724 free(worktree_path);
2725 free(cwd);
2726 free(path);
2727 return error;
2730 struct got_update_progress_arg {
2731 int did_something;
2732 int conflicts;
2733 int obstructed;
2734 int not_updated;
2737 void
2738 print_update_progress_stats(struct got_update_progress_arg *upa)
2740 if (!upa->did_something)
2741 return;
2743 if (upa->conflicts > 0)
2744 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2745 if (upa->obstructed > 0)
2746 printf("File paths obstructed by a non-regular file: %d\n",
2747 upa->obstructed);
2748 if (upa->not_updated > 0)
2749 printf("Files not updated because of existing merge "
2750 "conflicts: %d\n", upa->not_updated);
2753 __dead static void
2754 usage_update(void)
2756 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2757 getprogname());
2758 exit(1);
2761 static const struct got_error *
2762 update_progress(void *arg, unsigned char status, const char *path)
2764 struct got_update_progress_arg *upa = arg;
2766 if (status == GOT_STATUS_EXISTS ||
2767 status == GOT_STATUS_BASE_REF_ERR)
2768 return NULL;
2770 upa->did_something = 1;
2772 /* Base commit bump happens silently. */
2773 if (status == GOT_STATUS_BUMP_BASE)
2774 return NULL;
2776 if (status == GOT_STATUS_CONFLICT)
2777 upa->conflicts++;
2778 if (status == GOT_STATUS_OBSTRUCTED)
2779 upa->obstructed++;
2780 if (status == GOT_STATUS_CANNOT_UPDATE)
2781 upa->not_updated++;
2783 while (path[0] == '/')
2784 path++;
2785 printf("%c %s\n", status, path);
2786 return NULL;
2789 static const struct got_error *
2790 switch_head_ref(struct got_reference *head_ref,
2791 struct got_object_id *commit_id, struct got_worktree *worktree,
2792 struct got_repository *repo)
2794 const struct got_error *err = NULL;
2795 char *base_id_str;
2796 int ref_has_moved = 0;
2798 /* Trivial case: switching between two different references. */
2799 if (strcmp(got_ref_get_name(head_ref),
2800 got_worktree_get_head_ref_name(worktree)) != 0) {
2801 printf("Switching work tree from %s to %s\n",
2802 got_worktree_get_head_ref_name(worktree),
2803 got_ref_get_name(head_ref));
2804 return got_worktree_set_head_ref(worktree, head_ref);
2807 err = check_linear_ancestry(commit_id,
2808 got_worktree_get_base_commit_id(worktree), 0, repo);
2809 if (err) {
2810 if (err->code != GOT_ERR_ANCESTRY)
2811 return err;
2812 ref_has_moved = 1;
2814 if (!ref_has_moved)
2815 return NULL;
2817 /* Switching to a rebased branch with the same reference name. */
2818 err = got_object_id_str(&base_id_str,
2819 got_worktree_get_base_commit_id(worktree));
2820 if (err)
2821 return err;
2822 printf("Reference %s now points at a different branch\n",
2823 got_worktree_get_head_ref_name(worktree));
2824 printf("Switching work tree from %s to %s\n", base_id_str,
2825 got_worktree_get_head_ref_name(worktree));
2826 return NULL;
2829 static const struct got_error *
2830 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2832 const struct got_error *err;
2833 int in_progress;
2835 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2836 if (err)
2837 return err;
2838 if (in_progress)
2839 return got_error(GOT_ERR_REBASING);
2841 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2842 if (err)
2843 return err;
2844 if (in_progress)
2845 return got_error(GOT_ERR_HISTEDIT_BUSY);
2847 return NULL;
2850 static const struct got_error *
2851 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2852 char *argv[], struct got_worktree *worktree)
2854 const struct got_error *err = NULL;
2855 char *path;
2856 int i;
2858 if (argc == 0) {
2859 path = strdup("");
2860 if (path == NULL)
2861 return got_error_from_errno("strdup");
2862 return got_pathlist_append(paths, path, NULL);
2865 for (i = 0; i < argc; i++) {
2866 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2867 if (err)
2868 break;
2869 err = got_pathlist_append(paths, path, NULL);
2870 if (err) {
2871 free(path);
2872 break;
2876 return err;
2879 static const struct got_error *
2880 wrap_not_worktree_error(const struct got_error *orig_err,
2881 const char *cmdname, const char *path)
2883 const struct got_error *err;
2884 struct got_repository *repo;
2885 static char msg[512];
2887 err = got_repo_open(&repo, path, NULL);
2888 if (err)
2889 return orig_err;
2891 snprintf(msg, sizeof(msg),
2892 "'got %s' needs a work tree in addition to a git repository\n"
2893 "Work trees can be checked out from this Git repository with "
2894 "'got checkout'.\n"
2895 "The got(1) manual page contains more information.", cmdname);
2896 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2897 got_repo_close(repo);
2898 return err;
2901 static const struct got_error *
2902 cmd_update(int argc, char *argv[])
2904 const struct got_error *error = NULL;
2905 struct got_repository *repo = NULL;
2906 struct got_worktree *worktree = NULL;
2907 char *worktree_path = NULL;
2908 struct got_object_id *commit_id = NULL;
2909 char *commit_id_str = NULL;
2910 const char *branch_name = NULL;
2911 struct got_reference *head_ref = NULL;
2912 struct got_pathlist_head paths;
2913 struct got_pathlist_entry *pe;
2914 int ch;
2915 struct got_update_progress_arg upa;
2917 TAILQ_INIT(&paths);
2919 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2920 switch (ch) {
2921 case 'b':
2922 branch_name = optarg;
2923 break;
2924 case 'c':
2925 commit_id_str = strdup(optarg);
2926 if (commit_id_str == NULL)
2927 return got_error_from_errno("strdup");
2928 break;
2929 default:
2930 usage_update();
2931 /* NOTREACHED */
2935 argc -= optind;
2936 argv += optind;
2938 #ifndef PROFILE
2939 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2940 "unveil", NULL) == -1)
2941 err(1, "pledge");
2942 #endif
2943 worktree_path = getcwd(NULL, 0);
2944 if (worktree_path == NULL) {
2945 error = got_error_from_errno("getcwd");
2946 goto done;
2948 error = got_worktree_open(&worktree, worktree_path);
2949 if (error) {
2950 if (error->code == GOT_ERR_NOT_WORKTREE)
2951 error = wrap_not_worktree_error(error, "update",
2952 worktree_path);
2953 goto done;
2956 error = check_rebase_or_histedit_in_progress(worktree);
2957 if (error)
2958 goto done;
2960 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
2961 NULL);
2962 if (error != NULL)
2963 goto done;
2965 error = apply_unveil(got_repo_get_path(repo), 0,
2966 got_worktree_get_root_path(worktree));
2967 if (error)
2968 goto done;
2970 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2971 if (error)
2972 goto done;
2974 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
2975 got_worktree_get_head_ref_name(worktree), 0);
2976 if (error != NULL)
2977 goto done;
2978 if (commit_id_str == NULL) {
2979 error = got_ref_resolve(&commit_id, repo, head_ref);
2980 if (error != NULL)
2981 goto done;
2982 error = got_object_id_str(&commit_id_str, commit_id);
2983 if (error != NULL)
2984 goto done;
2985 } else {
2986 error = got_repo_match_object_id(&commit_id, NULL,
2987 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2988 free(commit_id_str);
2989 commit_id_str = NULL;
2990 if (error)
2991 goto done;
2992 error = got_object_id_str(&commit_id_str, commit_id);
2993 if (error)
2994 goto done;
2997 if (branch_name) {
2998 struct got_object_id *head_commit_id;
2999 TAILQ_FOREACH(pe, &paths, entry) {
3000 if (pe->path_len == 0)
3001 continue;
3002 error = got_error_msg(GOT_ERR_BAD_PATH,
3003 "switching between branches requires that "
3004 "the entire work tree gets updated");
3005 goto done;
3007 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3008 if (error)
3009 goto done;
3010 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3011 repo);
3012 free(head_commit_id);
3013 if (error != NULL)
3014 goto done;
3015 error = check_same_branch(commit_id, head_ref, NULL, repo);
3016 if (error)
3017 goto done;
3018 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3019 if (error)
3020 goto done;
3021 } else {
3022 error = check_linear_ancestry(commit_id,
3023 got_worktree_get_base_commit_id(worktree), 0, repo);
3024 if (error != NULL) {
3025 if (error->code == GOT_ERR_ANCESTRY)
3026 error = got_error(GOT_ERR_BRANCH_MOVED);
3027 goto done;
3029 error = check_same_branch(commit_id, head_ref, NULL, repo);
3030 if (error)
3031 goto done;
3034 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3035 commit_id) != 0) {
3036 error = got_worktree_set_base_commit_id(worktree, repo,
3037 commit_id);
3038 if (error)
3039 goto done;
3042 memset(&upa, 0, sizeof(upa));
3043 error = got_worktree_checkout_files(worktree, &paths, repo,
3044 update_progress, &upa, check_cancelled, NULL);
3045 if (error != NULL)
3046 goto done;
3048 if (upa.did_something)
3049 printf("Updated to commit %s\n", commit_id_str);
3050 else
3051 printf("Already up-to-date\n");
3052 print_update_progress_stats(&upa);
3053 done:
3054 free(worktree_path);
3055 TAILQ_FOREACH(pe, &paths, entry)
3056 free((char *)pe->path);
3057 got_pathlist_free(&paths);
3058 free(commit_id);
3059 free(commit_id_str);
3060 return error;
3063 static const struct got_error *
3064 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3065 const char *path, int diff_context, int ignore_whitespace,
3066 struct got_repository *repo)
3068 const struct got_error *err = NULL;
3069 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3071 if (blob_id1) {
3072 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3073 if (err)
3074 goto done;
3077 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3078 if (err)
3079 goto done;
3081 while (path[0] == '/')
3082 path++;
3083 err = got_diff_blob(blob1, blob2, path, path, diff_context,
3084 ignore_whitespace, stdout);
3085 done:
3086 if (blob1)
3087 got_object_blob_close(blob1);
3088 got_object_blob_close(blob2);
3089 return err;
3092 static const struct got_error *
3093 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3094 const char *path, int diff_context, int ignore_whitespace,
3095 struct got_repository *repo)
3097 const struct got_error *err = NULL;
3098 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3099 struct got_diff_blob_output_unidiff_arg arg;
3101 if (tree_id1) {
3102 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3103 if (err)
3104 goto done;
3107 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3108 if (err)
3109 goto done;
3111 arg.diff_context = diff_context;
3112 arg.ignore_whitespace = ignore_whitespace;
3113 arg.outfile = stdout;
3114 while (path[0] == '/')
3115 path++;
3116 err = got_diff_tree(tree1, tree2, path, path, repo,
3117 got_diff_blob_output_unidiff, &arg, 1);
3118 done:
3119 if (tree1)
3120 got_object_tree_close(tree1);
3121 if (tree2)
3122 got_object_tree_close(tree2);
3123 return err;
3126 static const struct got_error *
3127 get_changed_paths(struct got_pathlist_head *paths,
3128 struct got_commit_object *commit, struct got_repository *repo)
3130 const struct got_error *err = NULL;
3131 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3132 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3133 struct got_object_qid *qid;
3135 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3136 if (qid != NULL) {
3137 struct got_commit_object *pcommit;
3138 err = got_object_open_as_commit(&pcommit, repo,
3139 qid->id);
3140 if (err)
3141 return err;
3143 tree_id1 = got_object_commit_get_tree_id(pcommit);
3144 got_object_commit_close(pcommit);
3148 if (tree_id1) {
3149 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3150 if (err)
3151 goto done;
3154 tree_id2 = got_object_commit_get_tree_id(commit);
3155 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3156 if (err)
3157 goto done;
3159 err = got_diff_tree(tree1, tree2, "", "", repo,
3160 got_diff_tree_collect_changed_paths, paths, 0);
3161 done:
3162 if (tree1)
3163 got_object_tree_close(tree1);
3164 if (tree2)
3165 got_object_tree_close(tree2);
3166 return err;
3169 static const struct got_error *
3170 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3171 const char *path, int diff_context, struct got_repository *repo)
3173 const struct got_error *err = NULL;
3174 struct got_commit_object *pcommit = NULL;
3175 char *id_str1 = NULL, *id_str2 = NULL;
3176 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3177 struct got_object_qid *qid;
3179 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3180 if (qid != NULL) {
3181 err = got_object_open_as_commit(&pcommit, repo,
3182 qid->id);
3183 if (err)
3184 return err;
3187 if (path && path[0] != '\0') {
3188 int obj_type;
3189 err = got_object_id_by_path(&obj_id2, repo, id, path);
3190 if (err)
3191 goto done;
3192 err = got_object_id_str(&id_str2, obj_id2);
3193 if (err) {
3194 free(obj_id2);
3195 goto done;
3197 if (pcommit) {
3198 err = got_object_id_by_path(&obj_id1, repo,
3199 qid->id, path);
3200 if (err) {
3201 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3202 free(obj_id2);
3203 goto done;
3205 } else {
3206 err = got_object_id_str(&id_str1, obj_id1);
3207 if (err) {
3208 free(obj_id2);
3209 goto done;
3213 err = got_object_get_type(&obj_type, repo, obj_id2);
3214 if (err) {
3215 free(obj_id2);
3216 goto done;
3218 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3219 switch (obj_type) {
3220 case GOT_OBJ_TYPE_BLOB:
3221 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3222 0, repo);
3223 break;
3224 case GOT_OBJ_TYPE_TREE:
3225 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3226 0, repo);
3227 break;
3228 default:
3229 err = got_error(GOT_ERR_OBJ_TYPE);
3230 break;
3232 free(obj_id1);
3233 free(obj_id2);
3234 } else {
3235 obj_id2 = got_object_commit_get_tree_id(commit);
3236 err = got_object_id_str(&id_str2, obj_id2);
3237 if (err)
3238 goto done;
3239 obj_id1 = got_object_commit_get_tree_id(pcommit);
3240 err = got_object_id_str(&id_str1, obj_id1);
3241 if (err)
3242 goto done;
3243 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3244 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
3246 done:
3247 free(id_str1);
3248 free(id_str2);
3249 if (pcommit)
3250 got_object_commit_close(pcommit);
3251 return err;
3254 static char *
3255 get_datestr(time_t *time, char *datebuf)
3257 struct tm mytm, *tm;
3258 char *p, *s;
3260 tm = gmtime_r(time, &mytm);
3261 if (tm == NULL)
3262 return NULL;
3263 s = asctime_r(tm, datebuf);
3264 if (s == NULL)
3265 return NULL;
3266 p = strchr(s, '\n');
3267 if (p)
3268 *p = '\0';
3269 return s;
3272 static const struct got_error *
3273 match_logmsg(int *have_match, struct got_object_id *id,
3274 struct got_commit_object *commit, regex_t *regex)
3276 const struct got_error *err = NULL;
3277 regmatch_t regmatch;
3278 char *id_str = NULL, *logmsg = NULL;
3280 *have_match = 0;
3282 err = got_object_id_str(&id_str, id);
3283 if (err)
3284 return err;
3286 err = got_object_commit_get_logmsg(&logmsg, commit);
3287 if (err)
3288 goto done;
3290 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3291 *have_match = 1;
3292 done:
3293 free(id_str);
3294 free(logmsg);
3295 return err;
3298 static void
3299 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3300 regex_t *regex)
3302 regmatch_t regmatch;
3303 struct got_pathlist_entry *pe;
3305 *have_match = 0;
3307 TAILQ_FOREACH(pe, changed_paths, entry) {
3308 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3309 *have_match = 1;
3310 break;
3315 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3317 static const struct got_error *
3318 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3319 struct got_repository *repo, const char *path,
3320 struct got_pathlist_head *changed_paths, int show_patch,
3321 int diff_context, struct got_reflist_head *refs)
3323 const struct got_error *err = NULL;
3324 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3325 char datebuf[26];
3326 time_t committer_time;
3327 const char *author, *committer;
3328 char *refs_str = NULL;
3329 struct got_reflist_entry *re;
3331 SIMPLEQ_FOREACH(re, refs, entry) {
3332 char *s;
3333 const char *name;
3334 struct got_tag_object *tag = NULL;
3335 struct got_object_id *ref_id;
3336 int cmp;
3338 name = got_ref_get_name(re->ref);
3339 if (strcmp(name, GOT_REF_HEAD) == 0)
3340 continue;
3341 if (strncmp(name, "refs/", 5) == 0)
3342 name += 5;
3343 if (strncmp(name, "got/", 4) == 0)
3344 continue;
3345 if (strncmp(name, "heads/", 6) == 0)
3346 name += 6;
3347 if (strncmp(name, "remotes/", 8) == 0) {
3348 name += 8;
3349 s = strstr(name, "/" GOT_REF_HEAD);
3350 if (s != NULL && s[strlen(s)] == '\0')
3351 continue;
3353 err = got_ref_resolve(&ref_id, repo, re->ref);
3354 if (err)
3355 return err;
3356 if (strncmp(name, "tags/", 5) == 0) {
3357 err = got_object_open_as_tag(&tag, repo, ref_id);
3358 if (err) {
3359 if (err->code != GOT_ERR_OBJ_TYPE) {
3360 free(ref_id);
3361 return err;
3363 /* Ref points at something other than a tag. */
3364 err = NULL;
3365 tag = NULL;
3368 cmp = got_object_id_cmp(tag ?
3369 got_object_tag_get_object_id(tag) : ref_id, id);
3370 free(ref_id);
3371 if (tag)
3372 got_object_tag_close(tag);
3373 if (cmp != 0)
3374 continue;
3375 s = refs_str;
3376 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3377 name) == -1) {
3378 err = got_error_from_errno("asprintf");
3379 free(s);
3380 return err;
3382 free(s);
3384 err = got_object_id_str(&id_str, id);
3385 if (err)
3386 return err;
3388 printf(GOT_COMMIT_SEP_STR);
3389 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3390 refs_str ? refs_str : "", refs_str ? ")" : "");
3391 free(id_str);
3392 id_str = NULL;
3393 free(refs_str);
3394 refs_str = NULL;
3395 printf("from: %s\n", got_object_commit_get_author(commit));
3396 committer_time = got_object_commit_get_committer_time(commit);
3397 datestr = get_datestr(&committer_time, datebuf);
3398 if (datestr)
3399 printf("date: %s UTC\n", datestr);
3400 author = got_object_commit_get_author(commit);
3401 committer = got_object_commit_get_committer(commit);
3402 if (strcmp(author, committer) != 0)
3403 printf("via: %s\n", committer);
3404 if (got_object_commit_get_nparents(commit) > 1) {
3405 const struct got_object_id_queue *parent_ids;
3406 struct got_object_qid *qid;
3407 int n = 1;
3408 parent_ids = got_object_commit_get_parent_ids(commit);
3409 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3410 err = got_object_id_str(&id_str, qid->id);
3411 if (err)
3412 return err;
3413 printf("parent %d: %s\n", n++, id_str);
3414 free(id_str);
3418 err = got_object_commit_get_logmsg(&logmsg0, commit);
3419 if (err)
3420 return err;
3422 logmsg = logmsg0;
3423 do {
3424 line = strsep(&logmsg, "\n");
3425 if (line)
3426 printf(" %s\n", line);
3427 } while (line);
3428 free(logmsg0);
3430 if (changed_paths) {
3431 struct got_pathlist_entry *pe;
3432 TAILQ_FOREACH(pe, changed_paths, entry) {
3433 struct got_diff_changed_path *cp = pe->data;
3434 printf(" %c %s\n", cp->status, pe->path);
3436 printf("\n");
3438 if (show_patch) {
3439 err = print_patch(commit, id, path, diff_context, repo);
3440 if (err == 0)
3441 printf("\n");
3444 if (fflush(stdout) != 0 && err == NULL)
3445 err = got_error_from_errno("fflush");
3446 return err;
3449 static const struct got_error *
3450 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3451 struct got_repository *repo, const char *path, int show_changed_paths,
3452 int show_patch, const char *search_pattern, int diff_context, int limit,
3453 int log_branches, int reverse_display_order, struct got_reflist_head *refs)
3455 const struct got_error *err;
3456 struct got_commit_graph *graph;
3457 regex_t regex;
3458 int have_match;
3459 struct got_object_id_queue reversed_commits;
3460 struct got_object_qid *qid;
3461 struct got_commit_object *commit;
3462 struct got_pathlist_head changed_paths;
3463 struct got_pathlist_entry *pe;
3465 SIMPLEQ_INIT(&reversed_commits);
3466 TAILQ_INIT(&changed_paths);
3468 if (search_pattern && regcomp(&regex, search_pattern,
3469 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3470 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3472 err = got_commit_graph_open(&graph, path, !log_branches);
3473 if (err)
3474 return err;
3475 err = got_commit_graph_iter_start(graph, root_id, repo,
3476 check_cancelled, NULL);
3477 if (err)
3478 goto done;
3479 for (;;) {
3480 struct got_object_id *id;
3482 if (sigint_received || sigpipe_received)
3483 break;
3485 err = got_commit_graph_iter_next(&id, graph, repo,
3486 check_cancelled, NULL);
3487 if (err) {
3488 if (err->code == GOT_ERR_ITER_COMPLETED)
3489 err = NULL;
3490 break;
3492 if (id == NULL)
3493 break;
3495 err = got_object_open_as_commit(&commit, repo, id);
3496 if (err)
3497 break;
3499 if (show_changed_paths && !reverse_display_order) {
3500 err = get_changed_paths(&changed_paths, commit, repo);
3501 if (err)
3502 break;
3505 if (search_pattern) {
3506 err = match_logmsg(&have_match, id, commit, &regex);
3507 if (err) {
3508 got_object_commit_close(commit);
3509 break;
3511 if (have_match == 0 && show_changed_paths)
3512 match_changed_paths(&have_match,
3513 &changed_paths, &regex);
3514 if (have_match == 0) {
3515 got_object_commit_close(commit);
3516 TAILQ_FOREACH(pe, &changed_paths, entry) {
3517 free((char *)pe->path);
3518 free(pe->data);
3520 got_pathlist_free(&changed_paths);
3521 continue;
3525 if (reverse_display_order) {
3526 err = got_object_qid_alloc(&qid, id);
3527 if (err)
3528 break;
3529 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3530 got_object_commit_close(commit);
3531 } else {
3532 err = print_commit(commit, id, repo, path,
3533 show_changed_paths ? &changed_paths : NULL,
3534 show_patch, diff_context, refs);
3535 got_object_commit_close(commit);
3536 if (err)
3537 break;
3539 if ((limit && --limit == 0) ||
3540 (end_id && got_object_id_cmp(id, end_id) == 0))
3541 break;
3543 TAILQ_FOREACH(pe, &changed_paths, entry) {
3544 free((char *)pe->path);
3545 free(pe->data);
3547 got_pathlist_free(&changed_paths);
3549 if (reverse_display_order) {
3550 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3551 err = got_object_open_as_commit(&commit, repo, qid->id);
3552 if (err)
3553 break;
3554 if (show_changed_paths) {
3555 err = get_changed_paths(&changed_paths,
3556 commit, repo);
3557 if (err)
3558 break;
3560 err = print_commit(commit, qid->id, repo, path,
3561 show_changed_paths ? &changed_paths : NULL,
3562 show_patch, diff_context, refs);
3563 got_object_commit_close(commit);
3564 if (err)
3565 break;
3566 TAILQ_FOREACH(pe, &changed_paths, entry) {
3567 free((char *)pe->path);
3568 free(pe->data);
3570 got_pathlist_free(&changed_paths);
3573 done:
3574 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3575 qid = SIMPLEQ_FIRST(&reversed_commits);
3576 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3577 got_object_qid_free(qid);
3579 TAILQ_FOREACH(pe, &changed_paths, entry) {
3580 free((char *)pe->path);
3581 free(pe->data);
3583 got_pathlist_free(&changed_paths);
3584 if (search_pattern)
3585 regfree(&regex);
3586 got_commit_graph_close(graph);
3587 return err;
3590 __dead static void
3591 usage_log(void)
3593 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3594 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3595 "[-R] [path]\n", getprogname());
3596 exit(1);
3599 static int
3600 get_default_log_limit(void)
3602 const char *got_default_log_limit;
3603 long long n;
3604 const char *errstr;
3606 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3607 if (got_default_log_limit == NULL)
3608 return 0;
3609 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3610 if (errstr != NULL)
3611 return 0;
3612 return n;
3615 static const struct got_error *
3616 resolve_commit_arg(struct got_object_id **id, const char *commit_arg,
3617 struct got_repository *repo)
3619 const struct got_error *err = NULL;
3620 struct got_reference *ref;
3622 *id = NULL;
3624 err = got_ref_open(&ref, repo, commit_arg, 0);
3625 if (err == NULL) {
3626 int obj_type;
3627 err = got_ref_resolve(id, repo, ref);
3628 got_ref_close(ref);
3629 if (err)
3630 return err;
3631 err = got_object_get_type(&obj_type, repo, *id);
3632 if (err)
3633 return err;
3634 if (obj_type == GOT_OBJ_TYPE_TAG) {
3635 struct got_tag_object *tag;
3636 err = got_object_open_as_tag(&tag, repo, *id);
3637 if (err)
3638 return err;
3639 if (got_object_tag_get_object_type(tag) !=
3640 GOT_OBJ_TYPE_COMMIT) {
3641 got_object_tag_close(tag);
3642 return got_error(GOT_ERR_OBJ_TYPE);
3644 free(*id);
3645 *id = got_object_id_dup(
3646 got_object_tag_get_object_id(tag));
3647 if (*id == NULL)
3648 err = got_error_from_errno(
3649 "got_object_id_dup");
3650 got_object_tag_close(tag);
3651 if (err)
3652 return err;
3653 } else if (obj_type != GOT_OBJ_TYPE_COMMIT)
3654 return got_error(GOT_ERR_OBJ_TYPE);
3655 } else {
3656 err = got_repo_match_object_id_prefix(id, commit_arg,
3657 GOT_OBJ_TYPE_COMMIT, repo);
3660 return err;
3663 static const struct got_error *
3664 cmd_log(int argc, char *argv[])
3666 const struct got_error *error;
3667 struct got_repository *repo = NULL;
3668 struct got_worktree *worktree = NULL;
3669 struct got_object_id *start_id = NULL, *end_id = NULL;
3670 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3671 const char *start_commit = NULL, *end_commit = NULL;
3672 const char *search_pattern = NULL;
3673 int diff_context = -1, ch;
3674 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3675 int reverse_display_order = 0;
3676 const char *errstr;
3677 struct got_reflist_head refs;
3679 SIMPLEQ_INIT(&refs);
3681 #ifndef PROFILE
3682 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3683 NULL)
3684 == -1)
3685 err(1, "pledge");
3686 #endif
3688 limit = get_default_log_limit();
3690 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3691 switch (ch) {
3692 case 'p':
3693 show_patch = 1;
3694 break;
3695 case 'P':
3696 show_changed_paths = 1;
3697 break;
3698 case 'c':
3699 start_commit = optarg;
3700 break;
3701 case 'C':
3702 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3703 &errstr);
3704 if (errstr != NULL)
3705 err(1, "-C option %s", errstr);
3706 break;
3707 case 'l':
3708 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3709 if (errstr != NULL)
3710 err(1, "-l option %s", errstr);
3711 break;
3712 case 'b':
3713 log_branches = 1;
3714 break;
3715 case 'r':
3716 repo_path = realpath(optarg, NULL);
3717 if (repo_path == NULL)
3718 return got_error_from_errno2("realpath",
3719 optarg);
3720 got_path_strip_trailing_slashes(repo_path);
3721 break;
3722 case 'R':
3723 reverse_display_order = 1;
3724 break;
3725 case 's':
3726 search_pattern = optarg;
3727 break;
3728 case 'x':
3729 end_commit = optarg;
3730 break;
3731 default:
3732 usage_log();
3733 /* NOTREACHED */
3737 argc -= optind;
3738 argv += optind;
3740 if (diff_context == -1)
3741 diff_context = 3;
3742 else if (!show_patch)
3743 errx(1, "-C requires -p");
3745 cwd = getcwd(NULL, 0);
3746 if (cwd == NULL) {
3747 error = got_error_from_errno("getcwd");
3748 goto done;
3751 if (repo_path == NULL) {
3752 error = got_worktree_open(&worktree, cwd);
3753 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3754 goto done;
3755 error = NULL;
3758 if (argc == 0) {
3759 path = strdup("");
3760 if (path == NULL) {
3761 error = got_error_from_errno("strdup");
3762 goto done;
3764 } else if (argc == 1) {
3765 if (worktree) {
3766 error = got_worktree_resolve_path(&path, worktree,
3767 argv[0]);
3768 if (error)
3769 goto done;
3770 } else {
3771 path = strdup(argv[0]);
3772 if (path == NULL) {
3773 error = got_error_from_errno("strdup");
3774 goto done;
3777 } else
3778 usage_log();
3780 if (repo_path == NULL) {
3781 repo_path = worktree ?
3782 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3784 if (repo_path == NULL) {
3785 error = got_error_from_errno("strdup");
3786 goto done;
3789 error = got_repo_open(&repo, repo_path, NULL);
3790 if (error != NULL)
3791 goto done;
3793 error = apply_unveil(got_repo_get_path(repo), 1,
3794 worktree ? got_worktree_get_root_path(worktree) : NULL);
3795 if (error)
3796 goto done;
3798 if (start_commit == NULL) {
3799 struct got_reference *head_ref;
3800 struct got_commit_object *commit = NULL;
3801 error = got_ref_open(&head_ref, repo,
3802 worktree ? got_worktree_get_head_ref_name(worktree)
3803 : GOT_REF_HEAD, 0);
3804 if (error != NULL)
3805 goto done;
3806 error = got_ref_resolve(&start_id, repo, head_ref);
3807 got_ref_close(head_ref);
3808 if (error != NULL)
3809 goto done;
3810 error = got_object_open_as_commit(&commit, repo,
3811 start_id);
3812 if (error != NULL)
3813 goto done;
3814 got_object_commit_close(commit);
3815 } else {
3816 error = resolve_commit_arg(&start_id, start_commit, repo);
3817 if (error != NULL)
3818 goto done;
3820 if (end_commit != NULL) {
3821 error = resolve_commit_arg(&end_id, end_commit, repo);
3822 if (error != NULL)
3823 goto done;
3826 if (worktree) {
3827 const char *prefix = got_worktree_get_path_prefix(worktree);
3828 char *p;
3829 if (asprintf(&p, "%s%s%s", prefix,
3830 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3831 error = got_error_from_errno("asprintf");
3832 goto done;
3834 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3835 free(p);
3836 } else
3837 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3838 if (error != NULL)
3839 goto done;
3840 if (in_repo_path) {
3841 free(path);
3842 path = in_repo_path;
3845 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3846 if (error)
3847 goto done;
3849 error = print_commits(start_id, end_id, repo, path, show_changed_paths,
3850 show_patch, search_pattern, diff_context, limit, log_branches,
3851 reverse_display_order, &refs);
3852 done:
3853 free(path);
3854 free(repo_path);
3855 free(cwd);
3856 if (worktree)
3857 got_worktree_close(worktree);
3858 if (repo) {
3859 const struct got_error *repo_error;
3860 repo_error = got_repo_close(repo);
3861 if (error == NULL)
3862 error = repo_error;
3864 got_ref_list_free(&refs);
3865 return error;
3868 __dead static void
3869 usage_diff(void)
3871 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3872 "[-w] [object1 object2 | path]\n", getprogname());
3873 exit(1);
3876 struct print_diff_arg {
3877 struct got_repository *repo;
3878 struct got_worktree *worktree;
3879 int diff_context;
3880 const char *id_str;
3881 int header_shown;
3882 int diff_staged;
3883 int ignore_whitespace;
3887 * Create a file which contains the target path of a symlink so we can feed
3888 * it as content to the diff engine.
3890 static const struct got_error *
3891 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
3892 const char *abspath)
3894 const struct got_error *err = NULL;
3895 char target_path[PATH_MAX];
3896 ssize_t target_len, outlen;
3898 *fd = -1;
3900 if (dirfd != -1) {
3901 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
3902 if (target_len == -1)
3903 return got_error_from_errno2("readlinkat", abspath);
3904 } else {
3905 target_len = readlink(abspath, target_path, PATH_MAX);
3906 if (target_len == -1)
3907 return got_error_from_errno2("readlink", abspath);
3910 *fd = got_opentempfd();
3911 if (*fd == -1)
3912 return got_error_from_errno("got_opentempfd");
3914 outlen = write(*fd, target_path, target_len);
3915 if (outlen == -1) {
3916 err = got_error_from_errno("got_opentempfd");
3917 goto done;
3920 if (lseek(*fd, 0, SEEK_SET) == -1) {
3921 err = got_error_from_errno2("lseek", abspath);
3922 goto done;
3924 done:
3925 if (err) {
3926 close(*fd);
3927 *fd = -1;
3929 return err;
3932 static const struct got_error *
3933 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3934 const char *path, struct got_object_id *blob_id,
3935 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3936 int dirfd, const char *de_name)
3938 struct print_diff_arg *a = arg;
3939 const struct got_error *err = NULL;
3940 struct got_blob_object *blob1 = NULL;
3941 int fd = -1;
3942 FILE *f2 = NULL;
3943 char *abspath = NULL, *label1 = NULL;
3944 struct stat sb;
3946 if (a->diff_staged) {
3947 if (staged_status != GOT_STATUS_MODIFY &&
3948 staged_status != GOT_STATUS_ADD &&
3949 staged_status != GOT_STATUS_DELETE)
3950 return NULL;
3951 } else {
3952 if (staged_status == GOT_STATUS_DELETE)
3953 return NULL;
3954 if (status == GOT_STATUS_NONEXISTENT)
3955 return got_error_set_errno(ENOENT, path);
3956 if (status != GOT_STATUS_MODIFY &&
3957 status != GOT_STATUS_ADD &&
3958 status != GOT_STATUS_DELETE &&
3959 status != GOT_STATUS_CONFLICT)
3960 return NULL;
3963 if (!a->header_shown) {
3964 printf("diff %s %s%s\n", a->id_str,
3965 got_worktree_get_root_path(a->worktree),
3966 a->diff_staged ? " (staged changes)" : "");
3967 a->header_shown = 1;
3970 if (a->diff_staged) {
3971 const char *label1 = NULL, *label2 = NULL;
3972 switch (staged_status) {
3973 case GOT_STATUS_MODIFY:
3974 label1 = path;
3975 label2 = path;
3976 break;
3977 case GOT_STATUS_ADD:
3978 label2 = path;
3979 break;
3980 case GOT_STATUS_DELETE:
3981 label1 = path;
3982 break;
3983 default:
3984 return got_error(GOT_ERR_FILE_STATUS);
3986 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
3987 label1, label2, a->diff_context, a->ignore_whitespace,
3988 a->repo, stdout);
3991 if (staged_status == GOT_STATUS_ADD ||
3992 staged_status == GOT_STATUS_MODIFY) {
3993 char *id_str;
3994 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
3995 8192);
3996 if (err)
3997 goto done;
3998 err = got_object_id_str(&id_str, staged_blob_id);
3999 if (err)
4000 goto done;
4001 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4002 err = got_error_from_errno("asprintf");
4003 free(id_str);
4004 goto done;
4006 free(id_str);
4007 } else if (status != GOT_STATUS_ADD) {
4008 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4009 if (err)
4010 goto done;
4013 if (status != GOT_STATUS_DELETE) {
4014 if (asprintf(&abspath, "%s/%s",
4015 got_worktree_get_root_path(a->worktree), path) == -1) {
4016 err = got_error_from_errno("asprintf");
4017 goto done;
4020 if (dirfd != -1) {
4021 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
4022 if (fd == -1) {
4023 if (errno != ELOOP) {
4024 err = got_error_from_errno2("openat",
4025 abspath);
4026 goto done;
4028 err = get_symlink_target_file(&fd, dirfd,
4029 de_name, abspath);
4030 if (err)
4031 goto done;
4033 } else {
4034 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
4035 if (fd == -1) {
4036 if (errno != ELOOP) {
4037 err = got_error_from_errno2("open",
4038 abspath);
4039 goto done;
4041 err = get_symlink_target_file(&fd, dirfd,
4042 de_name, abspath);
4043 if (err)
4044 goto done;
4047 if (fstat(fd, &sb) == -1) {
4048 err = got_error_from_errno2("fstat", abspath);
4049 goto done;
4051 f2 = fdopen(fd, "r");
4052 if (f2 == NULL) {
4053 err = got_error_from_errno2("fdopen", abspath);
4054 goto done;
4056 fd = -1;
4057 } else
4058 sb.st_size = 0;
4060 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4061 a->diff_context, a->ignore_whitespace, stdout);
4062 done:
4063 if (blob1)
4064 got_object_blob_close(blob1);
4065 if (f2 && fclose(f2) == EOF && err == NULL)
4066 err = got_error_from_errno("fclose");
4067 if (fd != -1 && close(fd) == -1 && err == NULL)
4068 err = got_error_from_errno("close");
4069 free(abspath);
4070 return err;
4073 static const struct got_error *
4074 cmd_diff(int argc, char *argv[])
4076 const struct got_error *error;
4077 struct got_repository *repo = NULL;
4078 struct got_worktree *worktree = NULL;
4079 char *cwd = NULL, *repo_path = NULL;
4080 struct got_object_id *id1 = NULL, *id2 = NULL;
4081 const char *id_str1 = NULL, *id_str2 = NULL;
4082 char *label1 = NULL, *label2 = NULL;
4083 int type1, type2;
4084 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
4085 const char *errstr;
4086 char *path = NULL;
4088 #ifndef PROFILE
4089 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4090 NULL) == -1)
4091 err(1, "pledge");
4092 #endif
4094 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
4095 switch (ch) {
4096 case 'C':
4097 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4098 &errstr);
4099 if (errstr != NULL)
4100 err(1, "-C option %s", errstr);
4101 break;
4102 case 'r':
4103 repo_path = realpath(optarg, NULL);
4104 if (repo_path == NULL)
4105 return got_error_from_errno2("realpath",
4106 optarg);
4107 got_path_strip_trailing_slashes(repo_path);
4108 break;
4109 case 's':
4110 diff_staged = 1;
4111 break;
4112 case 'w':
4113 ignore_whitespace = 1;
4114 break;
4115 default:
4116 usage_diff();
4117 /* NOTREACHED */
4121 argc -= optind;
4122 argv += optind;
4124 cwd = getcwd(NULL, 0);
4125 if (cwd == NULL) {
4126 error = got_error_from_errno("getcwd");
4127 goto done;
4129 if (argc <= 1) {
4130 if (repo_path)
4131 errx(1,
4132 "-r option can't be used when diffing a work tree");
4133 error = got_worktree_open(&worktree, cwd);
4134 if (error) {
4135 if (error->code == GOT_ERR_NOT_WORKTREE)
4136 error = wrap_not_worktree_error(error, "diff",
4137 cwd);
4138 goto done;
4140 repo_path = strdup(got_worktree_get_repo_path(worktree));
4141 if (repo_path == NULL) {
4142 error = got_error_from_errno("strdup");
4143 goto done;
4145 if (argc == 1) {
4146 error = got_worktree_resolve_path(&path, worktree,
4147 argv[0]);
4148 if (error)
4149 goto done;
4150 } else {
4151 path = strdup("");
4152 if (path == NULL) {
4153 error = got_error_from_errno("strdup");
4154 goto done;
4157 } else if (argc == 2) {
4158 if (diff_staged)
4159 errx(1, "-s option can't be used when diffing "
4160 "objects in repository");
4161 id_str1 = argv[0];
4162 id_str2 = argv[1];
4163 if (repo_path == NULL) {
4164 error = got_worktree_open(&worktree, cwd);
4165 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4166 goto done;
4167 if (worktree) {
4168 repo_path = strdup(
4169 got_worktree_get_repo_path(worktree));
4170 if (repo_path == NULL) {
4171 error = got_error_from_errno("strdup");
4172 goto done;
4174 } else {
4175 repo_path = strdup(cwd);
4176 if (repo_path == NULL) {
4177 error = got_error_from_errno("strdup");
4178 goto done;
4182 } else
4183 usage_diff();
4185 error = got_repo_open(&repo, repo_path, NULL);
4186 free(repo_path);
4187 if (error != NULL)
4188 goto done;
4190 error = apply_unveil(got_repo_get_path(repo), 1,
4191 worktree ? got_worktree_get_root_path(worktree) : NULL);
4192 if (error)
4193 goto done;
4195 if (argc <= 1) {
4196 struct print_diff_arg arg;
4197 struct got_pathlist_head paths;
4198 char *id_str;
4200 TAILQ_INIT(&paths);
4202 error = got_object_id_str(&id_str,
4203 got_worktree_get_base_commit_id(worktree));
4204 if (error)
4205 goto done;
4206 arg.repo = repo;
4207 arg.worktree = worktree;
4208 arg.diff_context = diff_context;
4209 arg.id_str = id_str;
4210 arg.header_shown = 0;
4211 arg.diff_staged = diff_staged;
4212 arg.ignore_whitespace = ignore_whitespace;
4214 error = got_pathlist_append(&paths, path, NULL);
4215 if (error)
4216 goto done;
4218 error = got_worktree_status(worktree, &paths, repo, print_diff,
4219 &arg, check_cancelled, NULL);
4220 free(id_str);
4221 got_pathlist_free(&paths);
4222 goto done;
4225 error = got_repo_match_object_id(&id1, &label1, id_str1,
4226 GOT_OBJ_TYPE_ANY, 1, repo);
4227 if (error)
4228 goto done;
4230 error = got_repo_match_object_id(&id2, &label2, id_str2,
4231 GOT_OBJ_TYPE_ANY, 1, repo);
4232 if (error)
4233 goto done;
4235 error = got_object_get_type(&type1, repo, id1);
4236 if (error)
4237 goto done;
4239 error = got_object_get_type(&type2, repo, id2);
4240 if (error)
4241 goto done;
4243 if (type1 != type2) {
4244 error = got_error(GOT_ERR_OBJ_TYPE);
4245 goto done;
4248 switch (type1) {
4249 case GOT_OBJ_TYPE_BLOB:
4250 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
4251 diff_context, ignore_whitespace, repo, stdout);
4252 break;
4253 case GOT_OBJ_TYPE_TREE:
4254 error = got_diff_objects_as_trees(id1, id2, "", "",
4255 diff_context, ignore_whitespace, repo, stdout);
4256 break;
4257 case GOT_OBJ_TYPE_COMMIT:
4258 printf("diff %s %s\n", label1, label2);
4259 error = got_diff_objects_as_commits(id1, id2, diff_context,
4260 ignore_whitespace, repo, stdout);
4261 break;
4262 default:
4263 error = got_error(GOT_ERR_OBJ_TYPE);
4265 done:
4266 free(label1);
4267 free(label2);
4268 free(id1);
4269 free(id2);
4270 free(path);
4271 if (worktree)
4272 got_worktree_close(worktree);
4273 if (repo) {
4274 const struct got_error *repo_error;
4275 repo_error = got_repo_close(repo);
4276 if (error == NULL)
4277 error = repo_error;
4279 return error;
4282 __dead static void
4283 usage_blame(void)
4285 fprintf(stderr,
4286 "usage: %s blame [-c commit] [-r repository-path] path\n",
4287 getprogname());
4288 exit(1);
4291 struct blame_line {
4292 int annotated;
4293 char *id_str;
4294 char *committer;
4295 char datebuf[11]; /* YYYY-MM-DD + NUL */
4298 struct blame_cb_args {
4299 struct blame_line *lines;
4300 int nlines;
4301 int nlines_prec;
4302 int lineno_cur;
4303 off_t *line_offsets;
4304 FILE *f;
4305 struct got_repository *repo;
4308 static const struct got_error *
4309 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4311 const struct got_error *err = NULL;
4312 struct blame_cb_args *a = arg;
4313 struct blame_line *bline;
4314 char *line = NULL;
4315 size_t linesize = 0;
4316 struct got_commit_object *commit = NULL;
4317 off_t offset;
4318 struct tm tm;
4319 time_t committer_time;
4321 if (nlines != a->nlines ||
4322 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4323 return got_error(GOT_ERR_RANGE);
4325 if (sigint_received)
4326 return got_error(GOT_ERR_ITER_COMPLETED);
4328 if (lineno == -1)
4329 return NULL; /* no change in this commit */
4331 /* Annotate this line. */
4332 bline = &a->lines[lineno - 1];
4333 if (bline->annotated)
4334 return NULL;
4335 err = got_object_id_str(&bline->id_str, id);
4336 if (err)
4337 return err;
4339 err = got_object_open_as_commit(&commit, a->repo, id);
4340 if (err)
4341 goto done;
4343 bline->committer = strdup(got_object_commit_get_committer(commit));
4344 if (bline->committer == NULL) {
4345 err = got_error_from_errno("strdup");
4346 goto done;
4349 committer_time = got_object_commit_get_committer_time(commit);
4350 if (localtime_r(&committer_time, &tm) == NULL)
4351 return got_error_from_errno("localtime_r");
4352 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4353 &tm) >= sizeof(bline->datebuf)) {
4354 err = got_error(GOT_ERR_NO_SPACE);
4355 goto done;
4357 bline->annotated = 1;
4359 /* Print lines annotated so far. */
4360 bline = &a->lines[a->lineno_cur - 1];
4361 if (!bline->annotated)
4362 goto done;
4364 offset = a->line_offsets[a->lineno_cur - 1];
4365 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4366 err = got_error_from_errno("fseeko");
4367 goto done;
4370 while (bline->annotated) {
4371 char *smallerthan, *at, *nl, *committer;
4372 size_t len;
4374 if (getline(&line, &linesize, a->f) == -1) {
4375 if (ferror(a->f))
4376 err = got_error_from_errno("getline");
4377 break;
4380 committer = bline->committer;
4381 smallerthan = strchr(committer, '<');
4382 if (smallerthan && smallerthan[1] != '\0')
4383 committer = smallerthan + 1;
4384 at = strchr(committer, '@');
4385 if (at)
4386 *at = '\0';
4387 len = strlen(committer);
4388 if (len >= 9)
4389 committer[8] = '\0';
4391 nl = strchr(line, '\n');
4392 if (nl)
4393 *nl = '\0';
4394 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4395 bline->id_str, bline->datebuf, committer, line);
4397 a->lineno_cur++;
4398 bline = &a->lines[a->lineno_cur - 1];
4400 done:
4401 if (commit)
4402 got_object_commit_close(commit);
4403 free(line);
4404 return err;
4407 static const struct got_error *
4408 cmd_blame(int argc, char *argv[])
4410 const struct got_error *error;
4411 struct got_repository *repo = NULL;
4412 struct got_worktree *worktree = NULL;
4413 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4414 char *link_target = NULL;
4415 struct got_object_id *obj_id = NULL;
4416 struct got_object_id *commit_id = NULL;
4417 struct got_blob_object *blob = NULL;
4418 char *commit_id_str = NULL;
4419 struct blame_cb_args bca;
4420 int ch, obj_type, i;
4421 size_t filesize;
4423 memset(&bca, 0, sizeof(bca));
4425 #ifndef PROFILE
4426 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4427 NULL) == -1)
4428 err(1, "pledge");
4429 #endif
4431 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4432 switch (ch) {
4433 case 'c':
4434 commit_id_str = optarg;
4435 break;
4436 case 'r':
4437 repo_path = realpath(optarg, NULL);
4438 if (repo_path == NULL)
4439 return got_error_from_errno2("realpath",
4440 optarg);
4441 got_path_strip_trailing_slashes(repo_path);
4442 break;
4443 default:
4444 usage_blame();
4445 /* NOTREACHED */
4449 argc -= optind;
4450 argv += optind;
4452 if (argc == 1)
4453 path = argv[0];
4454 else
4455 usage_blame();
4457 cwd = getcwd(NULL, 0);
4458 if (cwd == NULL) {
4459 error = got_error_from_errno("getcwd");
4460 goto done;
4462 if (repo_path == NULL) {
4463 error = got_worktree_open(&worktree, cwd);
4464 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4465 goto done;
4466 else
4467 error = NULL;
4468 if (worktree) {
4469 repo_path =
4470 strdup(got_worktree_get_repo_path(worktree));
4471 if (repo_path == NULL) {
4472 error = got_error_from_errno("strdup");
4473 if (error)
4474 goto done;
4476 } else {
4477 repo_path = strdup(cwd);
4478 if (repo_path == NULL) {
4479 error = got_error_from_errno("strdup");
4480 goto done;
4485 error = got_repo_open(&repo, repo_path, NULL);
4486 if (error != NULL)
4487 goto done;
4489 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4490 if (error)
4491 goto done;
4493 if (worktree) {
4494 const char *prefix = got_worktree_get_path_prefix(worktree);
4495 char *p, *worktree_subdir = cwd +
4496 strlen(got_worktree_get_root_path(worktree));
4497 if (asprintf(&p, "%s%s%s%s%s",
4498 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
4499 worktree_subdir, worktree_subdir[0] ? "/" : "",
4500 path) == -1) {
4501 error = got_error_from_errno("asprintf");
4502 goto done;
4504 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4505 free(p);
4506 } else {
4507 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4509 if (error)
4510 goto done;
4512 if (commit_id_str == NULL) {
4513 struct got_reference *head_ref;
4514 error = got_ref_open(&head_ref, repo, worktree ?
4515 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4516 if (error != NULL)
4517 goto done;
4518 error = got_ref_resolve(&commit_id, repo, head_ref);
4519 got_ref_close(head_ref);
4520 if (error != NULL)
4521 goto done;
4522 } else {
4523 error = got_repo_match_object_id(&commit_id, NULL,
4524 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4525 if (error)
4526 goto done;
4529 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4530 commit_id, repo);
4531 if (error)
4532 goto done;
4534 error = got_object_id_by_path(&obj_id, repo, commit_id,
4535 link_target ? link_target : in_repo_path);
4536 if (error)
4537 goto done;
4539 error = got_object_get_type(&obj_type, repo, obj_id);
4540 if (error)
4541 goto done;
4543 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4544 error = got_error_path(link_target ? link_target : in_repo_path,
4545 GOT_ERR_OBJ_TYPE);
4546 goto done;
4549 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4550 if (error)
4551 goto done;
4552 bca.f = got_opentemp();
4553 if (bca.f == NULL) {
4554 error = got_error_from_errno("got_opentemp");
4555 goto done;
4557 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4558 &bca.line_offsets, bca.f, blob);
4559 if (error || bca.nlines == 0)
4560 goto done;
4562 /* Don't include \n at EOF in the blame line count. */
4563 if (bca.line_offsets[bca.nlines - 1] == filesize)
4564 bca.nlines--;
4566 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4567 if (bca.lines == NULL) {
4568 error = got_error_from_errno("calloc");
4569 goto done;
4571 bca.lineno_cur = 1;
4572 bca.nlines_prec = 0;
4573 i = bca.nlines;
4574 while (i > 0) {
4575 i /= 10;
4576 bca.nlines_prec++;
4578 bca.repo = repo;
4580 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4581 repo, blame_cb, &bca, check_cancelled, NULL);
4582 done:
4583 free(in_repo_path);
4584 free(link_target);
4585 free(repo_path);
4586 free(cwd);
4587 free(commit_id);
4588 free(obj_id);
4589 if (blob)
4590 got_object_blob_close(blob);
4591 if (worktree)
4592 got_worktree_close(worktree);
4593 if (repo) {
4594 const struct got_error *repo_error;
4595 repo_error = got_repo_close(repo);
4596 if (error == NULL)
4597 error = repo_error;
4599 if (bca.lines) {
4600 for (i = 0; i < bca.nlines; i++) {
4601 struct blame_line *bline = &bca.lines[i];
4602 free(bline->id_str);
4603 free(bline->committer);
4605 free(bca.lines);
4607 free(bca.line_offsets);
4608 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4609 error = got_error_from_errno("fclose");
4610 return error;
4613 __dead static void
4614 usage_tree(void)
4616 fprintf(stderr,
4617 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4618 getprogname());
4619 exit(1);
4622 static const struct got_error *
4623 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4624 const char *root_path, struct got_repository *repo)
4626 const struct got_error *err = NULL;
4627 int is_root_path = (strcmp(path, root_path) == 0);
4628 const char *modestr = "";
4629 mode_t mode = got_tree_entry_get_mode(te);
4630 char *link_target = NULL;
4632 path += strlen(root_path);
4633 while (path[0] == '/')
4634 path++;
4636 if (got_object_tree_entry_is_submodule(te))
4637 modestr = "$";
4638 else if (S_ISLNK(mode)) {
4639 int i;
4641 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4642 if (err)
4643 return err;
4644 for (i = 0; i < strlen(link_target); i++) {
4645 if (!isprint((unsigned char)link_target[i]))
4646 link_target[i] = '?';
4649 modestr = "@";
4651 else if (S_ISDIR(mode))
4652 modestr = "/";
4653 else if (mode & S_IXUSR)
4654 modestr = "*";
4656 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4657 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4658 link_target ? " -> ": "", link_target ? link_target : "");
4660 free(link_target);
4661 return NULL;
4664 static const struct got_error *
4665 print_tree(const char *path, struct got_object_id *commit_id,
4666 int show_ids, int recurse, const char *root_path,
4667 struct got_repository *repo)
4669 const struct got_error *err = NULL;
4670 struct got_object_id *tree_id = NULL;
4671 struct got_tree_object *tree = NULL;
4672 int nentries, i;
4674 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4675 if (err)
4676 goto done;
4678 err = got_object_open_as_tree(&tree, repo, tree_id);
4679 if (err)
4680 goto done;
4681 nentries = got_object_tree_get_nentries(tree);
4682 for (i = 0; i < nentries; i++) {
4683 struct got_tree_entry *te;
4684 char *id = NULL;
4686 if (sigint_received || sigpipe_received)
4687 break;
4689 te = got_object_tree_get_entry(tree, i);
4690 if (show_ids) {
4691 char *id_str;
4692 err = got_object_id_str(&id_str,
4693 got_tree_entry_get_id(te));
4694 if (err)
4695 goto done;
4696 if (asprintf(&id, "%s ", id_str) == -1) {
4697 err = got_error_from_errno("asprintf");
4698 free(id_str);
4699 goto done;
4701 free(id_str);
4703 err = print_entry(te, id, path, root_path, repo);
4704 free(id);
4705 if (err)
4706 goto done;
4708 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4709 char *child_path;
4710 if (asprintf(&child_path, "%s%s%s", path,
4711 path[0] == '/' && path[1] == '\0' ? "" : "/",
4712 got_tree_entry_get_name(te)) == -1) {
4713 err = got_error_from_errno("asprintf");
4714 goto done;
4716 err = print_tree(child_path, commit_id, show_ids, 1,
4717 root_path, repo);
4718 free(child_path);
4719 if (err)
4720 goto done;
4723 done:
4724 if (tree)
4725 got_object_tree_close(tree);
4726 free(tree_id);
4727 return err;
4730 static const struct got_error *
4731 cmd_tree(int argc, char *argv[])
4733 const struct got_error *error;
4734 struct got_repository *repo = NULL;
4735 struct got_worktree *worktree = NULL;
4736 const char *path, *refname = NULL;
4737 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4738 struct got_object_id *commit_id = NULL;
4739 char *commit_id_str = NULL;
4740 int show_ids = 0, recurse = 0;
4741 int ch;
4743 #ifndef PROFILE
4744 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4745 NULL) == -1)
4746 err(1, "pledge");
4747 #endif
4749 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4750 switch (ch) {
4751 case 'c':
4752 commit_id_str = optarg;
4753 break;
4754 case 'r':
4755 repo_path = realpath(optarg, NULL);
4756 if (repo_path == NULL)
4757 return got_error_from_errno2("realpath",
4758 optarg);
4759 got_path_strip_trailing_slashes(repo_path);
4760 break;
4761 case 'i':
4762 show_ids = 1;
4763 break;
4764 case 'R':
4765 recurse = 1;
4766 break;
4767 default:
4768 usage_tree();
4769 /* NOTREACHED */
4773 argc -= optind;
4774 argv += optind;
4776 if (argc == 1)
4777 path = argv[0];
4778 else if (argc > 1)
4779 usage_tree();
4780 else
4781 path = NULL;
4783 cwd = getcwd(NULL, 0);
4784 if (cwd == NULL) {
4785 error = got_error_from_errno("getcwd");
4786 goto done;
4788 if (repo_path == NULL) {
4789 error = got_worktree_open(&worktree, cwd);
4790 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4791 goto done;
4792 else
4793 error = NULL;
4794 if (worktree) {
4795 repo_path =
4796 strdup(got_worktree_get_repo_path(worktree));
4797 if (repo_path == NULL)
4798 error = got_error_from_errno("strdup");
4799 if (error)
4800 goto done;
4801 } else {
4802 repo_path = strdup(cwd);
4803 if (repo_path == NULL) {
4804 error = got_error_from_errno("strdup");
4805 goto done;
4810 error = got_repo_open(&repo, repo_path, NULL);
4811 if (error != NULL)
4812 goto done;
4814 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4815 if (error)
4816 goto done;
4818 if (path == NULL) {
4819 if (worktree) {
4820 char *p, *worktree_subdir = cwd +
4821 strlen(got_worktree_get_root_path(worktree));
4822 if (asprintf(&p, "%s/%s",
4823 got_worktree_get_path_prefix(worktree),
4824 worktree_subdir) == -1) {
4825 error = got_error_from_errno("asprintf");
4826 goto done;
4828 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4829 free(p);
4830 if (error)
4831 goto done;
4832 } else
4833 path = "/";
4835 if (in_repo_path == NULL) {
4836 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4837 if (error != NULL)
4838 goto done;
4841 if (commit_id_str == NULL) {
4842 struct got_reference *head_ref;
4843 if (worktree)
4844 refname = got_worktree_get_head_ref_name(worktree);
4845 else
4846 refname = GOT_REF_HEAD;
4847 error = got_ref_open(&head_ref, repo, refname, 0);
4848 if (error != NULL)
4849 goto done;
4850 error = got_ref_resolve(&commit_id, repo, head_ref);
4851 got_ref_close(head_ref);
4852 if (error != NULL)
4853 goto done;
4854 } else {
4855 error = got_repo_match_object_id(&commit_id, NULL,
4856 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4857 if (error)
4858 goto done;
4861 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4862 in_repo_path, repo);
4863 done:
4864 free(in_repo_path);
4865 free(repo_path);
4866 free(cwd);
4867 free(commit_id);
4868 if (worktree)
4869 got_worktree_close(worktree);
4870 if (repo) {
4871 const struct got_error *repo_error;
4872 repo_error = got_repo_close(repo);
4873 if (error == NULL)
4874 error = repo_error;
4876 return error;
4879 __dead static void
4880 usage_status(void)
4882 fprintf(stderr, "usage: %s status [-s status-codes ] [path ...]\n",
4883 getprogname());
4884 exit(1);
4887 static const struct got_error *
4888 print_status(void *arg, unsigned char status, unsigned char staged_status,
4889 const char *path, struct got_object_id *blob_id,
4890 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4891 int dirfd, const char *de_name)
4893 if (status == staged_status && (status == GOT_STATUS_DELETE))
4894 status = GOT_STATUS_NO_CHANGE;
4895 if (arg) {
4896 char *status_codes = arg;
4897 size_t ncodes = strlen(status_codes);
4898 int i;
4899 for (i = 0; i < ncodes ; i++) {
4900 if (status == status_codes[i] ||
4901 staged_status == status_codes[i])
4902 break;
4904 if (i == ncodes)
4905 return NULL;
4907 printf("%c%c %s\n", status, staged_status, path);
4908 return NULL;
4911 static const struct got_error *
4912 cmd_status(int argc, char *argv[])
4914 const struct got_error *error = NULL;
4915 struct got_repository *repo = NULL;
4916 struct got_worktree *worktree = NULL;
4917 char *cwd = NULL, *status_codes = NULL;;
4918 struct got_pathlist_head paths;
4919 struct got_pathlist_entry *pe;
4920 int ch, i;
4922 TAILQ_INIT(&paths);
4924 while ((ch = getopt(argc, argv, "s:")) != -1) {
4925 switch (ch) {
4926 case 's':
4927 for (i = 0; i < strlen(optarg); i++) {
4928 switch (optarg[i]) {
4929 case GOT_STATUS_MODIFY:
4930 case GOT_STATUS_ADD:
4931 case GOT_STATUS_DELETE:
4932 case GOT_STATUS_CONFLICT:
4933 case GOT_STATUS_MISSING:
4934 case GOT_STATUS_OBSTRUCTED:
4935 case GOT_STATUS_UNVERSIONED:
4936 case GOT_STATUS_MODE_CHANGE:
4937 case GOT_STATUS_NONEXISTENT:
4938 break;
4939 default:
4940 errx(1, "invalid status code '%c'",
4941 optarg[i]);
4944 status_codes = optarg;
4945 break;
4946 default:
4947 usage_status();
4948 /* NOTREACHED */
4952 argc -= optind;
4953 argv += optind;
4955 #ifndef PROFILE
4956 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4957 NULL) == -1)
4958 err(1, "pledge");
4959 #endif
4960 cwd = getcwd(NULL, 0);
4961 if (cwd == NULL) {
4962 error = got_error_from_errno("getcwd");
4963 goto done;
4966 error = got_worktree_open(&worktree, cwd);
4967 if (error) {
4968 if (error->code == GOT_ERR_NOT_WORKTREE)
4969 error = wrap_not_worktree_error(error, "status", cwd);
4970 goto done;
4973 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4974 NULL);
4975 if (error != NULL)
4976 goto done;
4978 error = apply_unveil(got_repo_get_path(repo), 1,
4979 got_worktree_get_root_path(worktree));
4980 if (error)
4981 goto done;
4983 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
4984 if (error)
4985 goto done;
4987 error = got_worktree_status(worktree, &paths, repo, print_status,
4988 status_codes, check_cancelled, NULL);
4989 done:
4990 TAILQ_FOREACH(pe, &paths, entry)
4991 free((char *)pe->path);
4992 got_pathlist_free(&paths);
4993 free(cwd);
4994 return error;
4997 __dead static void
4998 usage_ref(void)
5000 fprintf(stderr,
5001 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
5002 "[-d] [name]\n",
5003 getprogname());
5004 exit(1);
5007 static const struct got_error *
5008 list_refs(struct got_repository *repo, const char *refname)
5010 static const struct got_error *err = NULL;
5011 struct got_reflist_head refs;
5012 struct got_reflist_entry *re;
5014 SIMPLEQ_INIT(&refs);
5015 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
5016 if (err)
5017 return err;
5019 SIMPLEQ_FOREACH(re, &refs, entry) {
5020 char *refstr;
5021 refstr = got_ref_to_str(re->ref);
5022 if (refstr == NULL)
5023 return got_error_from_errno("got_ref_to_str");
5024 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5025 free(refstr);
5028 got_ref_list_free(&refs);
5029 return NULL;
5032 static const struct got_error *
5033 delete_ref(struct got_repository *repo, const char *refname)
5035 const struct got_error *err = NULL;
5036 struct got_reference *ref;
5038 err = got_ref_open(&ref, repo, refname, 0);
5039 if (err)
5040 return err;
5042 err = got_ref_delete(ref, repo);
5043 got_ref_close(ref);
5044 return err;
5047 static const struct got_error *
5048 add_ref(struct got_repository *repo, const char *refname, const char *target)
5050 const struct got_error *err = NULL;
5051 struct got_object_id *id;
5052 struct got_reference *ref = NULL;
5055 * Don't let the user create a reference name with a leading '-'.
5056 * While technically a valid reference name, this case is usually
5057 * an unintended typo.
5059 if (refname[0] == '-')
5060 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5062 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5063 repo);
5064 if (err) {
5065 struct got_reference *target_ref;
5067 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5068 return err;
5069 err = got_ref_open(&target_ref, repo, target, 0);
5070 if (err)
5071 return err;
5072 err = got_ref_resolve(&id, repo, target_ref);
5073 got_ref_close(target_ref);
5074 if (err)
5075 return err;
5078 err = got_ref_alloc(&ref, refname, id);
5079 if (err)
5080 goto done;
5082 err = got_ref_write(ref, repo);
5083 done:
5084 if (ref)
5085 got_ref_close(ref);
5086 free(id);
5087 return err;
5090 static const struct got_error *
5091 add_symref(struct got_repository *repo, const char *refname, const char *target)
5093 const struct got_error *err = NULL;
5094 struct got_reference *ref = NULL;
5095 struct got_reference *target_ref = NULL;
5098 * Don't let the user create a reference name with a leading '-'.
5099 * While technically a valid reference name, this case is usually
5100 * an unintended typo.
5102 if (refname[0] == '-')
5103 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5105 err = got_ref_open(&target_ref, repo, target, 0);
5106 if (err)
5107 return err;
5109 err = got_ref_alloc_symref(&ref, refname, target_ref);
5110 if (err)
5111 goto done;
5113 err = got_ref_write(ref, repo);
5114 done:
5115 if (target_ref)
5116 got_ref_close(target_ref);
5117 if (ref)
5118 got_ref_close(ref);
5119 return err;
5122 static const struct got_error *
5123 cmd_ref(int argc, char *argv[])
5125 const struct got_error *error = NULL;
5126 struct got_repository *repo = NULL;
5127 struct got_worktree *worktree = NULL;
5128 char *cwd = NULL, *repo_path = NULL;
5129 int ch, do_list = 0, do_delete = 0;
5130 const char *obj_arg = NULL, *symref_target= NULL;
5131 char *refname = NULL;
5133 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5134 switch (ch) {
5135 case 'c':
5136 obj_arg = optarg;
5137 break;
5138 case 'd':
5139 do_delete = 1;
5140 break;
5141 case 'r':
5142 repo_path = realpath(optarg, NULL);
5143 if (repo_path == NULL)
5144 return got_error_from_errno2("realpath",
5145 optarg);
5146 got_path_strip_trailing_slashes(repo_path);
5147 break;
5148 case 'l':
5149 do_list = 1;
5150 break;
5151 case 's':
5152 symref_target = optarg;
5153 break;
5154 default:
5155 usage_ref();
5156 /* NOTREACHED */
5160 if (obj_arg && do_list)
5161 errx(1, "-c and -l options are mutually exclusive");
5162 if (obj_arg && do_delete)
5163 errx(1, "-c and -d options are mutually exclusive");
5164 if (obj_arg && symref_target)
5165 errx(1, "-c and -s options are mutually exclusive");
5166 if (symref_target && do_delete)
5167 errx(1, "-s and -d options are mutually exclusive");
5168 if (symref_target && do_list)
5169 errx(1, "-s and -l options are mutually exclusive");
5170 if (do_delete && do_list)
5171 errx(1, "-d and -l options are mutually exclusive");
5173 argc -= optind;
5174 argv += optind;
5176 if (do_list) {
5177 if (argc != 0 && argc != 1)
5178 usage_ref();
5179 if (argc == 1) {
5180 refname = strdup(argv[0]);
5181 if (refname == NULL) {
5182 error = got_error_from_errno("strdup");
5183 goto done;
5186 } else {
5187 if (argc != 1)
5188 usage_ref();
5189 refname = strdup(argv[0]);
5190 if (refname == NULL) {
5191 error = got_error_from_errno("strdup");
5192 goto done;
5196 if (refname)
5197 got_path_strip_trailing_slashes(refname);
5199 #ifndef PROFILE
5200 if (do_list) {
5201 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5202 NULL) == -1)
5203 err(1, "pledge");
5204 } else {
5205 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5206 "sendfd unveil", NULL) == -1)
5207 err(1, "pledge");
5209 #endif
5210 cwd = getcwd(NULL, 0);
5211 if (cwd == NULL) {
5212 error = got_error_from_errno("getcwd");
5213 goto done;
5216 if (repo_path == NULL) {
5217 error = got_worktree_open(&worktree, cwd);
5218 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5219 goto done;
5220 else
5221 error = NULL;
5222 if (worktree) {
5223 repo_path =
5224 strdup(got_worktree_get_repo_path(worktree));
5225 if (repo_path == NULL)
5226 error = got_error_from_errno("strdup");
5227 if (error)
5228 goto done;
5229 } else {
5230 repo_path = strdup(cwd);
5231 if (repo_path == NULL) {
5232 error = got_error_from_errno("strdup");
5233 goto done;
5238 error = got_repo_open(&repo, repo_path, NULL);
5239 if (error != NULL)
5240 goto done;
5242 error = apply_unveil(got_repo_get_path(repo), do_list,
5243 worktree ? got_worktree_get_root_path(worktree) : NULL);
5244 if (error)
5245 goto done;
5247 if (do_list)
5248 error = list_refs(repo, refname);
5249 else if (do_delete)
5250 error = delete_ref(repo, refname);
5251 else if (symref_target)
5252 error = add_symref(repo, refname, symref_target);
5253 else {
5254 if (obj_arg == NULL)
5255 usage_ref();
5256 error = add_ref(repo, refname, obj_arg);
5258 done:
5259 free(refname);
5260 if (repo)
5261 got_repo_close(repo);
5262 if (worktree)
5263 got_worktree_close(worktree);
5264 free(cwd);
5265 free(repo_path);
5266 return error;
5269 __dead static void
5270 usage_branch(void)
5272 fprintf(stderr,
5273 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5274 "[name]\n", getprogname());
5275 exit(1);
5278 static const struct got_error *
5279 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5280 struct got_reference *ref)
5282 const struct got_error *err = NULL;
5283 const char *refname, *marker = " ";
5284 char *refstr;
5286 refname = got_ref_get_name(ref);
5287 if (worktree && strcmp(refname,
5288 got_worktree_get_head_ref_name(worktree)) == 0) {
5289 struct got_object_id *id = NULL;
5291 err = got_ref_resolve(&id, repo, ref);
5292 if (err)
5293 return err;
5294 if (got_object_id_cmp(id,
5295 got_worktree_get_base_commit_id(worktree)) == 0)
5296 marker = "* ";
5297 else
5298 marker = "~ ";
5299 free(id);
5302 if (strncmp(refname, "refs/heads/", 11) == 0)
5303 refname += 11;
5304 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5305 refname += 18;
5307 refstr = got_ref_to_str(ref);
5308 if (refstr == NULL)
5309 return got_error_from_errno("got_ref_to_str");
5311 printf("%s%s: %s\n", marker, refname, refstr);
5312 free(refstr);
5313 return NULL;
5316 static const struct got_error *
5317 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5319 const char *refname;
5321 if (worktree == NULL)
5322 return got_error(GOT_ERR_NOT_WORKTREE);
5324 refname = got_worktree_get_head_ref_name(worktree);
5326 if (strncmp(refname, "refs/heads/", 11) == 0)
5327 refname += 11;
5328 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5329 refname += 18;
5331 printf("%s\n", refname);
5333 return NULL;
5336 static const struct got_error *
5337 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5339 static const struct got_error *err = NULL;
5340 struct got_reflist_head refs;
5341 struct got_reflist_entry *re;
5342 struct got_reference *temp_ref = NULL;
5343 int rebase_in_progress, histedit_in_progress;
5345 SIMPLEQ_INIT(&refs);
5347 if (worktree) {
5348 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5349 worktree);
5350 if (err)
5351 return err;
5353 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5354 worktree);
5355 if (err)
5356 return err;
5358 if (rebase_in_progress || histedit_in_progress) {
5359 err = got_ref_open(&temp_ref, repo,
5360 got_worktree_get_head_ref_name(worktree), 0);
5361 if (err)
5362 return err;
5363 list_branch(repo, worktree, temp_ref);
5364 got_ref_close(temp_ref);
5368 err = got_ref_list(&refs, repo, "refs/heads",
5369 got_ref_cmp_by_name, NULL);
5370 if (err)
5371 return err;
5373 SIMPLEQ_FOREACH(re, &refs, entry)
5374 list_branch(repo, worktree, re->ref);
5376 got_ref_list_free(&refs);
5377 return NULL;
5380 static const struct got_error *
5381 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5382 const char *branch_name)
5384 const struct got_error *err = NULL;
5385 struct got_reference *ref = NULL;
5386 char *refname;
5388 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5389 return got_error_from_errno("asprintf");
5391 err = got_ref_open(&ref, repo, refname, 0);
5392 if (err)
5393 goto done;
5395 if (worktree &&
5396 strcmp(got_worktree_get_head_ref_name(worktree),
5397 got_ref_get_name(ref)) == 0) {
5398 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5399 "will not delete this work tree's current branch");
5400 goto done;
5403 err = got_ref_delete(ref, repo);
5404 done:
5405 if (ref)
5406 got_ref_close(ref);
5407 free(refname);
5408 return err;
5411 static const struct got_error *
5412 add_branch(struct got_repository *repo, const char *branch_name,
5413 struct got_object_id *base_commit_id)
5415 const struct got_error *err = NULL;
5416 struct got_reference *ref = NULL;
5417 char *base_refname = NULL, *refname = NULL;
5420 * Don't let the user create a branch name with a leading '-'.
5421 * While technically a valid reference name, this case is usually
5422 * an unintended typo.
5424 if (branch_name[0] == '-')
5425 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5427 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5428 err = got_error_from_errno("asprintf");
5429 goto done;
5432 err = got_ref_open(&ref, repo, refname, 0);
5433 if (err == NULL) {
5434 err = got_error(GOT_ERR_BRANCH_EXISTS);
5435 goto done;
5436 } else if (err->code != GOT_ERR_NOT_REF)
5437 goto done;
5439 err = got_ref_alloc(&ref, refname, base_commit_id);
5440 if (err)
5441 goto done;
5443 err = got_ref_write(ref, repo);
5444 done:
5445 if (ref)
5446 got_ref_close(ref);
5447 free(base_refname);
5448 free(refname);
5449 return err;
5452 static const struct got_error *
5453 cmd_branch(int argc, char *argv[])
5455 const struct got_error *error = NULL;
5456 struct got_repository *repo = NULL;
5457 struct got_worktree *worktree = NULL;
5458 char *cwd = NULL, *repo_path = NULL;
5459 int ch, do_list = 0, do_show = 0, do_update = 1;
5460 const char *delref = NULL, *commit_id_arg = NULL;
5461 struct got_reference *ref = NULL;
5462 struct got_pathlist_head paths;
5463 struct got_pathlist_entry *pe;
5464 struct got_object_id *commit_id = NULL;
5465 char *commit_id_str = NULL;
5467 TAILQ_INIT(&paths);
5469 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5470 switch (ch) {
5471 case 'c':
5472 commit_id_arg = optarg;
5473 break;
5474 case 'd':
5475 delref = optarg;
5476 break;
5477 case 'r':
5478 repo_path = realpath(optarg, NULL);
5479 if (repo_path == NULL)
5480 return got_error_from_errno2("realpath",
5481 optarg);
5482 got_path_strip_trailing_slashes(repo_path);
5483 break;
5484 case 'l':
5485 do_list = 1;
5486 break;
5487 case 'n':
5488 do_update = 0;
5489 break;
5490 default:
5491 usage_branch();
5492 /* NOTREACHED */
5496 if (do_list && delref)
5497 errx(1, "-l and -d options are mutually exclusive");
5499 argc -= optind;
5500 argv += optind;
5502 if (!do_list && !delref && argc == 0)
5503 do_show = 1;
5505 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5506 errx(1, "-c option can only be used when creating a branch");
5508 if (do_list || delref) {
5509 if (argc > 0)
5510 usage_branch();
5511 } else if (!do_show && argc != 1)
5512 usage_branch();
5514 #ifndef PROFILE
5515 if (do_list || do_show) {
5516 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5517 NULL) == -1)
5518 err(1, "pledge");
5519 } else {
5520 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5521 "sendfd unveil", NULL) == -1)
5522 err(1, "pledge");
5524 #endif
5525 cwd = getcwd(NULL, 0);
5526 if (cwd == NULL) {
5527 error = got_error_from_errno("getcwd");
5528 goto done;
5531 if (repo_path == NULL) {
5532 error = got_worktree_open(&worktree, cwd);
5533 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5534 goto done;
5535 else
5536 error = NULL;
5537 if (worktree) {
5538 repo_path =
5539 strdup(got_worktree_get_repo_path(worktree));
5540 if (repo_path == NULL)
5541 error = got_error_from_errno("strdup");
5542 if (error)
5543 goto done;
5544 } else {
5545 repo_path = strdup(cwd);
5546 if (repo_path == NULL) {
5547 error = got_error_from_errno("strdup");
5548 goto done;
5553 error = got_repo_open(&repo, repo_path, NULL);
5554 if (error != NULL)
5555 goto done;
5557 error = apply_unveil(got_repo_get_path(repo), do_list,
5558 worktree ? got_worktree_get_root_path(worktree) : NULL);
5559 if (error)
5560 goto done;
5562 if (do_show)
5563 error = show_current_branch(repo, worktree);
5564 else if (do_list)
5565 error = list_branches(repo, worktree);
5566 else if (delref)
5567 error = delete_branch(repo, worktree, delref);
5568 else {
5569 if (commit_id_arg == NULL)
5570 commit_id_arg = worktree ?
5571 got_worktree_get_head_ref_name(worktree) :
5572 GOT_REF_HEAD;
5573 error = got_repo_match_object_id(&commit_id, NULL,
5574 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5575 if (error)
5576 goto done;
5577 error = add_branch(repo, argv[0], commit_id);
5578 if (error)
5579 goto done;
5580 if (worktree && do_update) {
5581 struct got_update_progress_arg upa;
5582 char *branch_refname = NULL;
5584 error = got_object_id_str(&commit_id_str, commit_id);
5585 if (error)
5586 goto done;
5587 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5588 worktree);
5589 if (error)
5590 goto done;
5591 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5592 == -1) {
5593 error = got_error_from_errno("asprintf");
5594 goto done;
5596 error = got_ref_open(&ref, repo, branch_refname, 0);
5597 free(branch_refname);
5598 if (error)
5599 goto done;
5600 error = switch_head_ref(ref, commit_id, worktree,
5601 repo);
5602 if (error)
5603 goto done;
5604 error = got_worktree_set_base_commit_id(worktree, repo,
5605 commit_id);
5606 if (error)
5607 goto done;
5608 memset(&upa, 0, sizeof(upa));
5609 error = got_worktree_checkout_files(worktree, &paths,
5610 repo, update_progress, &upa, check_cancelled,
5611 NULL);
5612 if (error)
5613 goto done;
5614 if (upa.did_something)
5615 printf("Updated to commit %s\n", commit_id_str);
5616 print_update_progress_stats(&upa);
5619 done:
5620 if (ref)
5621 got_ref_close(ref);
5622 if (repo)
5623 got_repo_close(repo);
5624 if (worktree)
5625 got_worktree_close(worktree);
5626 free(cwd);
5627 free(repo_path);
5628 free(commit_id);
5629 free(commit_id_str);
5630 TAILQ_FOREACH(pe, &paths, entry)
5631 free((char *)pe->path);
5632 got_pathlist_free(&paths);
5633 return error;
5637 __dead static void
5638 usage_tag(void)
5640 fprintf(stderr,
5641 "usage: %s tag [-c commit] [-r repository] [-l] "
5642 "[-m message] name\n", getprogname());
5643 exit(1);
5646 #if 0
5647 static const struct got_error *
5648 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5650 const struct got_error *err = NULL;
5651 struct got_reflist_entry *re, *se, *new;
5652 struct got_object_id *re_id, *se_id;
5653 struct got_tag_object *re_tag, *se_tag;
5654 time_t re_time, se_time;
5656 SIMPLEQ_FOREACH(re, tags, entry) {
5657 se = SIMPLEQ_FIRST(sorted);
5658 if (se == NULL) {
5659 err = got_reflist_entry_dup(&new, re);
5660 if (err)
5661 return err;
5662 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5663 continue;
5664 } else {
5665 err = got_ref_resolve(&re_id, repo, re->ref);
5666 if (err)
5667 break;
5668 err = got_object_open_as_tag(&re_tag, repo, re_id);
5669 free(re_id);
5670 if (err)
5671 break;
5672 re_time = got_object_tag_get_tagger_time(re_tag);
5673 got_object_tag_close(re_tag);
5676 while (se) {
5677 err = got_ref_resolve(&se_id, repo, re->ref);
5678 if (err)
5679 break;
5680 err = got_object_open_as_tag(&se_tag, repo, se_id);
5681 free(se_id);
5682 if (err)
5683 break;
5684 se_time = got_object_tag_get_tagger_time(se_tag);
5685 got_object_tag_close(se_tag);
5687 if (se_time > re_time) {
5688 err = got_reflist_entry_dup(&new, re);
5689 if (err)
5690 return err;
5691 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5692 break;
5694 se = SIMPLEQ_NEXT(se, entry);
5695 continue;
5698 done:
5699 return err;
5701 #endif
5703 static const struct got_error *
5704 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5706 static const struct got_error *err = NULL;
5707 struct got_reflist_head refs;
5708 struct got_reflist_entry *re;
5710 SIMPLEQ_INIT(&refs);
5712 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5713 if (err)
5714 return err;
5716 SIMPLEQ_FOREACH(re, &refs, entry) {
5717 const char *refname;
5718 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5719 char datebuf[26];
5720 const char *tagger;
5721 time_t tagger_time;
5722 struct got_object_id *id;
5723 struct got_tag_object *tag;
5724 struct got_commit_object *commit = NULL;
5726 refname = got_ref_get_name(re->ref);
5727 if (strncmp(refname, "refs/tags/", 10) != 0)
5728 continue;
5729 refname += 10;
5730 refstr = got_ref_to_str(re->ref);
5731 if (refstr == NULL) {
5732 err = got_error_from_errno("got_ref_to_str");
5733 break;
5735 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5736 free(refstr);
5738 err = got_ref_resolve(&id, repo, re->ref);
5739 if (err)
5740 break;
5741 err = got_object_open_as_tag(&tag, repo, id);
5742 if (err) {
5743 if (err->code != GOT_ERR_OBJ_TYPE) {
5744 free(id);
5745 break;
5747 /* "lightweight" tag */
5748 err = got_object_open_as_commit(&commit, repo, id);
5749 if (err) {
5750 free(id);
5751 break;
5753 tagger = got_object_commit_get_committer(commit);
5754 tagger_time =
5755 got_object_commit_get_committer_time(commit);
5756 err = got_object_id_str(&id_str, id);
5757 free(id);
5758 if (err)
5759 break;
5760 } else {
5761 free(id);
5762 tagger = got_object_tag_get_tagger(tag);
5763 tagger_time = got_object_tag_get_tagger_time(tag);
5764 err = got_object_id_str(&id_str,
5765 got_object_tag_get_object_id(tag));
5766 if (err)
5767 break;
5769 printf("from: %s\n", tagger);
5770 datestr = get_datestr(&tagger_time, datebuf);
5771 if (datestr)
5772 printf("date: %s UTC\n", datestr);
5773 if (commit)
5774 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5775 else {
5776 switch (got_object_tag_get_object_type(tag)) {
5777 case GOT_OBJ_TYPE_BLOB:
5778 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5779 id_str);
5780 break;
5781 case GOT_OBJ_TYPE_TREE:
5782 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5783 id_str);
5784 break;
5785 case GOT_OBJ_TYPE_COMMIT:
5786 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5787 id_str);
5788 break;
5789 case GOT_OBJ_TYPE_TAG:
5790 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5791 id_str);
5792 break;
5793 default:
5794 break;
5797 free(id_str);
5798 if (commit) {
5799 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5800 if (err)
5801 break;
5802 got_object_commit_close(commit);
5803 } else {
5804 tagmsg0 = strdup(got_object_tag_get_message(tag));
5805 got_object_tag_close(tag);
5806 if (tagmsg0 == NULL) {
5807 err = got_error_from_errno("strdup");
5808 break;
5812 tagmsg = tagmsg0;
5813 do {
5814 line = strsep(&tagmsg, "\n");
5815 if (line)
5816 printf(" %s\n", line);
5817 } while (line);
5818 free(tagmsg0);
5821 got_ref_list_free(&refs);
5822 return NULL;
5825 static const struct got_error *
5826 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5827 const char *tag_name, const char *repo_path)
5829 const struct got_error *err = NULL;
5830 char *template = NULL, *initial_content = NULL;
5831 char *editor = NULL;
5832 int initial_content_len;
5833 int fd = -1;
5835 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5836 err = got_error_from_errno("asprintf");
5837 goto done;
5840 initial_content_len = asprintf(&initial_content,
5841 "\n# tagging commit %s as %s\n",
5842 commit_id_str, tag_name);
5843 if (initial_content_len == -1) {
5844 err = got_error_from_errno("asprintf");
5845 goto done;
5848 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5849 if (err)
5850 goto done;
5852 if (write(fd, initial_content, initial_content_len) == -1) {
5853 err = got_error_from_errno2("write", *tagmsg_path);
5854 goto done;
5857 err = get_editor(&editor);
5858 if (err)
5859 goto done;
5860 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
5861 done:
5862 free(initial_content);
5863 free(template);
5864 free(editor);
5866 if (fd != -1 && close(fd) == -1 && err == NULL)
5867 err = got_error_from_errno2("close", *tagmsg_path);
5869 /* Editor is done; we can now apply unveil(2) */
5870 if (err == NULL)
5871 err = apply_unveil(repo_path, 0, NULL);
5872 if (err) {
5873 free(*tagmsg);
5874 *tagmsg = NULL;
5876 return err;
5879 static const struct got_error *
5880 add_tag(struct got_repository *repo, struct got_worktree *worktree,
5881 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
5883 const struct got_error *err = NULL;
5884 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5885 char *label = NULL, *commit_id_str = NULL;
5886 struct got_reference *ref = NULL;
5887 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5888 char *tagmsg_path = NULL, *tag_id_str = NULL;
5889 int preserve_tagmsg = 0;
5892 * Don't let the user create a tag name with a leading '-'.
5893 * While technically a valid reference name, this case is usually
5894 * an unintended typo.
5896 if (tag_name[0] == '-')
5897 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5899 err = get_author(&tagger, repo, worktree);
5900 if (err)
5901 return err;
5903 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5904 GOT_OBJ_TYPE_COMMIT, 1, repo);
5905 if (err)
5906 goto done;
5908 err = got_object_id_str(&commit_id_str, commit_id);
5909 if (err)
5910 goto done;
5912 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5913 refname = strdup(tag_name);
5914 if (refname == NULL) {
5915 err = got_error_from_errno("strdup");
5916 goto done;
5918 tag_name += 10;
5919 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5920 err = got_error_from_errno("asprintf");
5921 goto done;
5924 err = got_ref_open(&ref, repo, refname, 0);
5925 if (err == NULL) {
5926 err = got_error(GOT_ERR_TAG_EXISTS);
5927 goto done;
5928 } else if (err->code != GOT_ERR_NOT_REF)
5929 goto done;
5931 if (tagmsg_arg == NULL) {
5932 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5933 tag_name, got_repo_get_path(repo));
5934 if (err) {
5935 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5936 tagmsg_path != NULL)
5937 preserve_tagmsg = 1;
5938 goto done;
5942 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5943 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5944 if (err) {
5945 if (tagmsg_path)
5946 preserve_tagmsg = 1;
5947 goto done;
5950 err = got_ref_alloc(&ref, refname, tag_id);
5951 if (err) {
5952 if (tagmsg_path)
5953 preserve_tagmsg = 1;
5954 goto done;
5957 err = got_ref_write(ref, repo);
5958 if (err) {
5959 if (tagmsg_path)
5960 preserve_tagmsg = 1;
5961 goto done;
5964 err = got_object_id_str(&tag_id_str, tag_id);
5965 if (err) {
5966 if (tagmsg_path)
5967 preserve_tagmsg = 1;
5968 goto done;
5970 printf("Created tag %s\n", tag_id_str);
5971 done:
5972 if (preserve_tagmsg) {
5973 fprintf(stderr, "%s: tag message preserved in %s\n",
5974 getprogname(), tagmsg_path);
5975 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
5976 err = got_error_from_errno2("unlink", tagmsg_path);
5977 free(tag_id_str);
5978 if (ref)
5979 got_ref_close(ref);
5980 free(commit_id);
5981 free(commit_id_str);
5982 free(refname);
5983 free(tagmsg);
5984 free(tagmsg_path);
5985 free(tagger);
5986 return err;
5989 static const struct got_error *
5990 cmd_tag(int argc, char *argv[])
5992 const struct got_error *error = NULL;
5993 struct got_repository *repo = NULL;
5994 struct got_worktree *worktree = NULL;
5995 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
5996 char *gitconfig_path = NULL;
5997 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
5998 int ch, do_list = 0;
6000 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6001 switch (ch) {
6002 case 'c':
6003 commit_id_arg = optarg;
6004 break;
6005 case 'm':
6006 tagmsg = optarg;
6007 break;
6008 case 'r':
6009 repo_path = realpath(optarg, NULL);
6010 if (repo_path == NULL)
6011 return got_error_from_errno2("realpath",
6012 optarg);
6013 got_path_strip_trailing_slashes(repo_path);
6014 break;
6015 case 'l':
6016 do_list = 1;
6017 break;
6018 default:
6019 usage_tag();
6020 /* NOTREACHED */
6024 argc -= optind;
6025 argv += optind;
6027 if (do_list) {
6028 if (commit_id_arg != NULL)
6029 errx(1,
6030 "-c option can only be used when creating a tag");
6031 if (tagmsg)
6032 errx(1, "-l and -m options are mutually exclusive");
6033 if (argc > 0)
6034 usage_tag();
6035 } else if (argc != 1)
6036 usage_tag();
6038 tag_name = argv[0];
6040 #ifndef PROFILE
6041 if (do_list) {
6042 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6043 NULL) == -1)
6044 err(1, "pledge");
6045 } else {
6046 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6047 "sendfd unveil", NULL) == -1)
6048 err(1, "pledge");
6050 #endif
6051 cwd = getcwd(NULL, 0);
6052 if (cwd == NULL) {
6053 error = got_error_from_errno("getcwd");
6054 goto done;
6057 if (repo_path == NULL) {
6058 error = got_worktree_open(&worktree, cwd);
6059 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6060 goto done;
6061 else
6062 error = NULL;
6063 if (worktree) {
6064 repo_path =
6065 strdup(got_worktree_get_repo_path(worktree));
6066 if (repo_path == NULL)
6067 error = got_error_from_errno("strdup");
6068 if (error)
6069 goto done;
6070 } else {
6071 repo_path = strdup(cwd);
6072 if (repo_path == NULL) {
6073 error = got_error_from_errno("strdup");
6074 goto done;
6079 if (do_list) {
6080 error = got_repo_open(&repo, repo_path, NULL);
6081 if (error != NULL)
6082 goto done;
6083 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6084 if (error)
6085 goto done;
6086 error = list_tags(repo, worktree);
6087 } else {
6088 error = get_gitconfig_path(&gitconfig_path);
6089 if (error)
6090 goto done;
6091 error = got_repo_open(&repo, repo_path, gitconfig_path);
6092 if (error != NULL)
6093 goto done;
6095 if (tagmsg) {
6096 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6097 if (error)
6098 goto done;
6101 if (commit_id_arg == NULL) {
6102 struct got_reference *head_ref;
6103 struct got_object_id *commit_id;
6104 error = got_ref_open(&head_ref, repo,
6105 worktree ? got_worktree_get_head_ref_name(worktree)
6106 : GOT_REF_HEAD, 0);
6107 if (error)
6108 goto done;
6109 error = got_ref_resolve(&commit_id, repo, head_ref);
6110 got_ref_close(head_ref);
6111 if (error)
6112 goto done;
6113 error = got_object_id_str(&commit_id_str, commit_id);
6114 free(commit_id);
6115 if (error)
6116 goto done;
6119 error = add_tag(repo, worktree, tag_name,
6120 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6122 done:
6123 if (repo)
6124 got_repo_close(repo);
6125 if (worktree)
6126 got_worktree_close(worktree);
6127 free(cwd);
6128 free(repo_path);
6129 free(gitconfig_path);
6130 free(commit_id_str);
6131 return error;
6134 __dead static void
6135 usage_add(void)
6137 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6138 getprogname());
6139 exit(1);
6142 static const struct got_error *
6143 add_progress(void *arg, unsigned char status, const char *path)
6145 while (path[0] == '/')
6146 path++;
6147 printf("%c %s\n", status, path);
6148 return NULL;
6151 static const struct got_error *
6152 cmd_add(int argc, char *argv[])
6154 const struct got_error *error = NULL;
6155 struct got_repository *repo = NULL;
6156 struct got_worktree *worktree = NULL;
6157 char *cwd = NULL;
6158 struct got_pathlist_head paths;
6159 struct got_pathlist_entry *pe;
6160 int ch, can_recurse = 0, no_ignores = 0;
6162 TAILQ_INIT(&paths);
6164 while ((ch = getopt(argc, argv, "IR")) != -1) {
6165 switch (ch) {
6166 case 'I':
6167 no_ignores = 1;
6168 break;
6169 case 'R':
6170 can_recurse = 1;
6171 break;
6172 default:
6173 usage_add();
6174 /* NOTREACHED */
6178 argc -= optind;
6179 argv += optind;
6181 #ifndef PROFILE
6182 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6183 NULL) == -1)
6184 err(1, "pledge");
6185 #endif
6186 if (argc < 1)
6187 usage_add();
6189 cwd = getcwd(NULL, 0);
6190 if (cwd == NULL) {
6191 error = got_error_from_errno("getcwd");
6192 goto done;
6195 error = got_worktree_open(&worktree, cwd);
6196 if (error) {
6197 if (error->code == GOT_ERR_NOT_WORKTREE)
6198 error = wrap_not_worktree_error(error, "add", cwd);
6199 goto done;
6202 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6203 NULL);
6204 if (error != NULL)
6205 goto done;
6207 error = apply_unveil(got_repo_get_path(repo), 1,
6208 got_worktree_get_root_path(worktree));
6209 if (error)
6210 goto done;
6212 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6213 if (error)
6214 goto done;
6216 if (!can_recurse && no_ignores) {
6217 error = got_error_msg(GOT_ERR_BAD_PATH,
6218 "disregarding ignores requires -R option");
6219 goto done;
6223 if (!can_recurse) {
6224 char *ondisk_path;
6225 struct stat sb;
6226 TAILQ_FOREACH(pe, &paths, entry) {
6227 if (asprintf(&ondisk_path, "%s/%s",
6228 got_worktree_get_root_path(worktree),
6229 pe->path) == -1) {
6230 error = got_error_from_errno("asprintf");
6231 goto done;
6233 if (lstat(ondisk_path, &sb) == -1) {
6234 if (errno == ENOENT) {
6235 free(ondisk_path);
6236 continue;
6238 error = got_error_from_errno2("lstat",
6239 ondisk_path);
6240 free(ondisk_path);
6241 goto done;
6243 free(ondisk_path);
6244 if (S_ISDIR(sb.st_mode)) {
6245 error = got_error_msg(GOT_ERR_BAD_PATH,
6246 "adding directories requires -R option");
6247 goto done;
6252 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6253 NULL, repo, no_ignores);
6254 done:
6255 if (repo)
6256 got_repo_close(repo);
6257 if (worktree)
6258 got_worktree_close(worktree);
6259 TAILQ_FOREACH(pe, &paths, entry)
6260 free((char *)pe->path);
6261 got_pathlist_free(&paths);
6262 free(cwd);
6263 return error;
6266 __dead static void
6267 usage_remove(void)
6269 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6270 "path ...\n", getprogname());
6271 exit(1);
6274 static const struct got_error *
6275 print_remove_status(void *arg, unsigned char status,
6276 unsigned char staged_status, const char *path)
6278 while (path[0] == '/')
6279 path++;
6280 if (status == GOT_STATUS_NONEXISTENT)
6281 return NULL;
6282 if (status == staged_status && (status == GOT_STATUS_DELETE))
6283 status = GOT_STATUS_NO_CHANGE;
6284 printf("%c%c %s\n", status, staged_status, path);
6285 return NULL;
6288 static const struct got_error *
6289 cmd_remove(int argc, char *argv[])
6291 const struct got_error *error = NULL;
6292 struct got_worktree *worktree = NULL;
6293 struct got_repository *repo = NULL;
6294 const char *status_codes = NULL;
6295 char *cwd = NULL;
6296 struct got_pathlist_head paths;
6297 struct got_pathlist_entry *pe;
6298 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6300 TAILQ_INIT(&paths);
6302 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6303 switch (ch) {
6304 case 'f':
6305 delete_local_mods = 1;
6306 break;
6307 case 'k':
6308 keep_on_disk = 1;
6309 break;
6310 case 'R':
6311 can_recurse = 1;
6312 break;
6313 case 's':
6314 for (i = 0; i < strlen(optarg); i++) {
6315 switch (optarg[i]) {
6316 case GOT_STATUS_MODIFY:
6317 delete_local_mods = 1;
6318 break;
6319 case GOT_STATUS_MISSING:
6320 break;
6321 default:
6322 errx(1, "invalid status code '%c'",
6323 optarg[i]);
6326 status_codes = optarg;
6327 break;
6328 default:
6329 usage_remove();
6330 /* NOTREACHED */
6334 argc -= optind;
6335 argv += optind;
6337 #ifndef PROFILE
6338 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6339 NULL) == -1)
6340 err(1, "pledge");
6341 #endif
6342 if (argc < 1)
6343 usage_remove();
6345 cwd = getcwd(NULL, 0);
6346 if (cwd == NULL) {
6347 error = got_error_from_errno("getcwd");
6348 goto done;
6350 error = got_worktree_open(&worktree, cwd);
6351 if (error) {
6352 if (error->code == GOT_ERR_NOT_WORKTREE)
6353 error = wrap_not_worktree_error(error, "remove", cwd);
6354 goto done;
6357 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6358 NULL);
6359 if (error)
6360 goto done;
6362 error = apply_unveil(got_repo_get_path(repo), 1,
6363 got_worktree_get_root_path(worktree));
6364 if (error)
6365 goto done;
6367 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6368 if (error)
6369 goto done;
6371 if (!can_recurse) {
6372 char *ondisk_path;
6373 struct stat sb;
6374 TAILQ_FOREACH(pe, &paths, entry) {
6375 if (asprintf(&ondisk_path, "%s/%s",
6376 got_worktree_get_root_path(worktree),
6377 pe->path) == -1) {
6378 error = got_error_from_errno("asprintf");
6379 goto done;
6381 if (lstat(ondisk_path, &sb) == -1) {
6382 if (errno == ENOENT) {
6383 free(ondisk_path);
6384 continue;
6386 error = got_error_from_errno2("lstat",
6387 ondisk_path);
6388 free(ondisk_path);
6389 goto done;
6391 free(ondisk_path);
6392 if (S_ISDIR(sb.st_mode)) {
6393 error = got_error_msg(GOT_ERR_BAD_PATH,
6394 "removing directories requires -R option");
6395 goto done;
6400 error = got_worktree_schedule_delete(worktree, &paths,
6401 delete_local_mods, status_codes, print_remove_status, NULL,
6402 repo, keep_on_disk);
6403 done:
6404 if (repo)
6405 got_repo_close(repo);
6406 if (worktree)
6407 got_worktree_close(worktree);
6408 TAILQ_FOREACH(pe, &paths, entry)
6409 free((char *)pe->path);
6410 got_pathlist_free(&paths);
6411 free(cwd);
6412 return error;
6415 __dead static void
6416 usage_revert(void)
6418 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6419 "path ...\n", getprogname());
6420 exit(1);
6423 static const struct got_error *
6424 revert_progress(void *arg, unsigned char status, const char *path)
6426 if (status == GOT_STATUS_UNVERSIONED)
6427 return NULL;
6429 while (path[0] == '/')
6430 path++;
6431 printf("%c %s\n", status, path);
6432 return NULL;
6435 struct choose_patch_arg {
6436 FILE *patch_script_file;
6437 const char *action;
6440 static const struct got_error *
6441 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6442 int nchanges, const char *action)
6444 char *line = NULL;
6445 size_t linesize = 0;
6446 ssize_t linelen;
6448 switch (status) {
6449 case GOT_STATUS_ADD:
6450 printf("A %s\n%s this addition? [y/n] ", path, action);
6451 break;
6452 case GOT_STATUS_DELETE:
6453 printf("D %s\n%s this deletion? [y/n] ", path, action);
6454 break;
6455 case GOT_STATUS_MODIFY:
6456 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6457 return got_error_from_errno("fseek");
6458 printf(GOT_COMMIT_SEP_STR);
6459 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6460 printf("%s", line);
6461 if (ferror(patch_file))
6462 return got_error_from_errno("getline");
6463 printf(GOT_COMMIT_SEP_STR);
6464 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6465 path, n, nchanges, action);
6466 break;
6467 default:
6468 return got_error_path(path, GOT_ERR_FILE_STATUS);
6471 return NULL;
6474 static const struct got_error *
6475 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6476 FILE *patch_file, int n, int nchanges)
6478 const struct got_error *err = NULL;
6479 char *line = NULL;
6480 size_t linesize = 0;
6481 ssize_t linelen;
6482 int resp = ' ';
6483 struct choose_patch_arg *a = arg;
6485 *choice = GOT_PATCH_CHOICE_NONE;
6487 if (a->patch_script_file) {
6488 char *nl;
6489 err = show_change(status, path, patch_file, n, nchanges,
6490 a->action);
6491 if (err)
6492 return err;
6493 linelen = getline(&line, &linesize, a->patch_script_file);
6494 if (linelen == -1) {
6495 if (ferror(a->patch_script_file))
6496 return got_error_from_errno("getline");
6497 return NULL;
6499 nl = strchr(line, '\n');
6500 if (nl)
6501 *nl = '\0';
6502 if (strcmp(line, "y") == 0) {
6503 *choice = GOT_PATCH_CHOICE_YES;
6504 printf("y\n");
6505 } else if (strcmp(line, "n") == 0) {
6506 *choice = GOT_PATCH_CHOICE_NO;
6507 printf("n\n");
6508 } else if (strcmp(line, "q") == 0 &&
6509 status == GOT_STATUS_MODIFY) {
6510 *choice = GOT_PATCH_CHOICE_QUIT;
6511 printf("q\n");
6512 } else
6513 printf("invalid response '%s'\n", line);
6514 free(line);
6515 return NULL;
6518 while (resp != 'y' && resp != 'n' && resp != 'q') {
6519 err = show_change(status, path, patch_file, n, nchanges,
6520 a->action);
6521 if (err)
6522 return err;
6523 resp = getchar();
6524 if (resp == '\n')
6525 resp = getchar();
6526 if (status == GOT_STATUS_MODIFY) {
6527 if (resp != 'y' && resp != 'n' && resp != 'q') {
6528 printf("invalid response '%c'\n", resp);
6529 resp = ' ';
6531 } else if (resp != 'y' && resp != 'n') {
6532 printf("invalid response '%c'\n", resp);
6533 resp = ' ';
6537 if (resp == 'y')
6538 *choice = GOT_PATCH_CHOICE_YES;
6539 else if (resp == 'n')
6540 *choice = GOT_PATCH_CHOICE_NO;
6541 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6542 *choice = GOT_PATCH_CHOICE_QUIT;
6544 return NULL;
6548 static const struct got_error *
6549 cmd_revert(int argc, char *argv[])
6551 const struct got_error *error = NULL;
6552 struct got_worktree *worktree = NULL;
6553 struct got_repository *repo = NULL;
6554 char *cwd = NULL, *path = NULL;
6555 struct got_pathlist_head paths;
6556 struct got_pathlist_entry *pe;
6557 int ch, can_recurse = 0, pflag = 0;
6558 FILE *patch_script_file = NULL;
6559 const char *patch_script_path = NULL;
6560 struct choose_patch_arg cpa;
6562 TAILQ_INIT(&paths);
6564 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6565 switch (ch) {
6566 case 'p':
6567 pflag = 1;
6568 break;
6569 case 'F':
6570 patch_script_path = optarg;
6571 break;
6572 case 'R':
6573 can_recurse = 1;
6574 break;
6575 default:
6576 usage_revert();
6577 /* NOTREACHED */
6581 argc -= optind;
6582 argv += optind;
6584 #ifndef PROFILE
6585 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6586 "unveil", NULL) == -1)
6587 err(1, "pledge");
6588 #endif
6589 if (argc < 1)
6590 usage_revert();
6591 if (patch_script_path && !pflag)
6592 errx(1, "-F option can only be used together with -p option");
6594 cwd = getcwd(NULL, 0);
6595 if (cwd == NULL) {
6596 error = got_error_from_errno("getcwd");
6597 goto done;
6599 error = got_worktree_open(&worktree, cwd);
6600 if (error) {
6601 if (error->code == GOT_ERR_NOT_WORKTREE)
6602 error = wrap_not_worktree_error(error, "revert", cwd);
6603 goto done;
6606 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6607 NULL);
6608 if (error != NULL)
6609 goto done;
6611 if (patch_script_path) {
6612 patch_script_file = fopen(patch_script_path, "r");
6613 if (patch_script_file == NULL) {
6614 error = got_error_from_errno2("fopen",
6615 patch_script_path);
6616 goto done;
6619 error = apply_unveil(got_repo_get_path(repo), 1,
6620 got_worktree_get_root_path(worktree));
6621 if (error)
6622 goto done;
6624 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6625 if (error)
6626 goto done;
6628 if (!can_recurse) {
6629 char *ondisk_path;
6630 struct stat sb;
6631 TAILQ_FOREACH(pe, &paths, entry) {
6632 if (asprintf(&ondisk_path, "%s/%s",
6633 got_worktree_get_root_path(worktree),
6634 pe->path) == -1) {
6635 error = got_error_from_errno("asprintf");
6636 goto done;
6638 if (lstat(ondisk_path, &sb) == -1) {
6639 if (errno == ENOENT) {
6640 free(ondisk_path);
6641 continue;
6643 error = got_error_from_errno2("lstat",
6644 ondisk_path);
6645 free(ondisk_path);
6646 goto done;
6648 free(ondisk_path);
6649 if (S_ISDIR(sb.st_mode)) {
6650 error = got_error_msg(GOT_ERR_BAD_PATH,
6651 "reverting directories requires -R option");
6652 goto done;
6657 cpa.patch_script_file = patch_script_file;
6658 cpa.action = "revert";
6659 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6660 pflag ? choose_patch : NULL, &cpa, repo);
6661 done:
6662 if (patch_script_file && fclose(patch_script_file) == EOF &&
6663 error == NULL)
6664 error = got_error_from_errno2("fclose", patch_script_path);
6665 if (repo)
6666 got_repo_close(repo);
6667 if (worktree)
6668 got_worktree_close(worktree);
6669 free(path);
6670 free(cwd);
6671 return error;
6674 __dead static void
6675 usage_commit(void)
6677 fprintf(stderr, "usage: %s commit [-m msg] [-S] [path ...]\n",
6678 getprogname());
6679 exit(1);
6682 struct collect_commit_logmsg_arg {
6683 const char *cmdline_log;
6684 const char *editor;
6685 const char *worktree_path;
6686 const char *branch_name;
6687 const char *repo_path;
6688 char *logmsg_path;
6692 static const struct got_error *
6693 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6694 void *arg)
6696 char *initial_content = NULL;
6697 struct got_pathlist_entry *pe;
6698 const struct got_error *err = NULL;
6699 char *template = NULL;
6700 struct collect_commit_logmsg_arg *a = arg;
6701 int initial_content_len;
6702 int fd = -1;
6703 size_t len;
6705 /* if a message was specified on the command line, just use it */
6706 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6707 len = strlen(a->cmdline_log) + 1;
6708 *logmsg = malloc(len + 1);
6709 if (*logmsg == NULL)
6710 return got_error_from_errno("malloc");
6711 strlcpy(*logmsg, a->cmdline_log, len);
6712 return NULL;
6715 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6716 return got_error_from_errno("asprintf");
6718 initial_content_len = asprintf(&initial_content,
6719 "\n# changes to be committed on branch %s:\n",
6720 a->branch_name);
6721 if (initial_content_len == -1)
6722 return got_error_from_errno("asprintf");
6724 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6725 if (err)
6726 goto done;
6728 if (write(fd, initial_content, initial_content_len) == -1) {
6729 err = got_error_from_errno2("write", a->logmsg_path);
6730 goto done;
6733 TAILQ_FOREACH(pe, commitable_paths, entry) {
6734 struct got_commitable *ct = pe->data;
6735 dprintf(fd, "# %c %s\n",
6736 got_commitable_get_status(ct),
6737 got_commitable_get_path(ct));
6740 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
6741 done:
6742 free(initial_content);
6743 free(template);
6745 if (fd != -1 && close(fd) == -1 && err == NULL)
6746 err = got_error_from_errno2("close", a->logmsg_path);
6748 /* Editor is done; we can now apply unveil(2) */
6749 if (err == NULL)
6750 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6751 if (err) {
6752 free(*logmsg);
6753 *logmsg = NULL;
6755 return err;
6758 static const struct got_error *
6759 cmd_commit(int argc, char *argv[])
6761 const struct got_error *error = NULL;
6762 struct got_worktree *worktree = NULL;
6763 struct got_repository *repo = NULL;
6764 char *cwd = NULL, *id_str = NULL;
6765 struct got_object_id *id = NULL;
6766 const char *logmsg = NULL;
6767 struct collect_commit_logmsg_arg cl_arg;
6768 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6769 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6770 int allow_bad_symlinks = 0;
6771 struct got_pathlist_head paths;
6773 TAILQ_INIT(&paths);
6774 cl_arg.logmsg_path = NULL;
6776 while ((ch = getopt(argc, argv, "m:S")) != -1) {
6777 switch (ch) {
6778 case 'm':
6779 logmsg = optarg;
6780 break;
6781 case 'S':
6782 allow_bad_symlinks = 1;
6783 break;
6784 default:
6785 usage_commit();
6786 /* NOTREACHED */
6790 argc -= optind;
6791 argv += optind;
6793 #ifndef PROFILE
6794 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6795 "unveil", NULL) == -1)
6796 err(1, "pledge");
6797 #endif
6798 cwd = getcwd(NULL, 0);
6799 if (cwd == NULL) {
6800 error = got_error_from_errno("getcwd");
6801 goto done;
6803 error = got_worktree_open(&worktree, cwd);
6804 if (error) {
6805 if (error->code == GOT_ERR_NOT_WORKTREE)
6806 error = wrap_not_worktree_error(error, "commit", cwd);
6807 goto done;
6810 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6811 if (error)
6812 goto done;
6813 if (rebase_in_progress) {
6814 error = got_error(GOT_ERR_REBASING);
6815 goto done;
6818 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6819 worktree);
6820 if (error)
6821 goto done;
6823 error = get_gitconfig_path(&gitconfig_path);
6824 if (error)
6825 goto done;
6826 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6827 gitconfig_path);
6828 if (error != NULL)
6829 goto done;
6831 error = get_author(&author, repo, worktree);
6832 if (error)
6833 return error;
6836 * unveil(2) traverses exec(2); if an editor is used we have
6837 * to apply unveil after the log message has been written.
6839 if (logmsg == NULL || strlen(logmsg) == 0)
6840 error = get_editor(&editor);
6841 else
6842 error = apply_unveil(got_repo_get_path(repo), 0,
6843 got_worktree_get_root_path(worktree));
6844 if (error)
6845 goto done;
6847 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6848 if (error)
6849 goto done;
6851 cl_arg.editor = editor;
6852 cl_arg.cmdline_log = logmsg;
6853 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6854 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6855 if (!histedit_in_progress) {
6856 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6857 error = got_error(GOT_ERR_COMMIT_BRANCH);
6858 goto done;
6860 cl_arg.branch_name += 11;
6862 cl_arg.repo_path = got_repo_get_path(repo);
6863 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6864 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
6865 print_status, NULL, repo);
6866 if (error) {
6867 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6868 cl_arg.logmsg_path != NULL)
6869 preserve_logmsg = 1;
6870 goto done;
6873 error = got_object_id_str(&id_str, id);
6874 if (error)
6875 goto done;
6876 printf("Created commit %s\n", id_str);
6877 done:
6878 if (preserve_logmsg) {
6879 fprintf(stderr, "%s: log message preserved in %s\n",
6880 getprogname(), cl_arg.logmsg_path);
6881 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6882 error == NULL)
6883 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6884 free(cl_arg.logmsg_path);
6885 if (repo)
6886 got_repo_close(repo);
6887 if (worktree)
6888 got_worktree_close(worktree);
6889 free(cwd);
6890 free(id_str);
6891 free(gitconfig_path);
6892 free(editor);
6893 free(author);
6894 return error;
6897 __dead static void
6898 usage_cherrypick(void)
6900 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6901 exit(1);
6904 static const struct got_error *
6905 cmd_cherrypick(int argc, char *argv[])
6907 const struct got_error *error = NULL;
6908 struct got_worktree *worktree = NULL;
6909 struct got_repository *repo = NULL;
6910 char *cwd = NULL, *commit_id_str = NULL;
6911 struct got_object_id *commit_id = NULL;
6912 struct got_commit_object *commit = NULL;
6913 struct got_object_qid *pid;
6914 struct got_reference *head_ref = NULL;
6915 int ch;
6916 struct got_update_progress_arg upa;
6918 while ((ch = getopt(argc, argv, "")) != -1) {
6919 switch (ch) {
6920 default:
6921 usage_cherrypick();
6922 /* NOTREACHED */
6926 argc -= optind;
6927 argv += optind;
6929 #ifndef PROFILE
6930 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6931 "unveil", NULL) == -1)
6932 err(1, "pledge");
6933 #endif
6934 if (argc != 1)
6935 usage_cherrypick();
6937 cwd = getcwd(NULL, 0);
6938 if (cwd == NULL) {
6939 error = got_error_from_errno("getcwd");
6940 goto done;
6942 error = got_worktree_open(&worktree, cwd);
6943 if (error) {
6944 if (error->code == GOT_ERR_NOT_WORKTREE)
6945 error = wrap_not_worktree_error(error, "cherrypick",
6946 cwd);
6947 goto done;
6950 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6951 NULL);
6952 if (error != NULL)
6953 goto done;
6955 error = apply_unveil(got_repo_get_path(repo), 0,
6956 got_worktree_get_root_path(worktree));
6957 if (error)
6958 goto done;
6960 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6961 GOT_OBJ_TYPE_COMMIT, repo);
6962 if (error != NULL) {
6963 struct got_reference *ref;
6964 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6965 goto done;
6966 error = got_ref_open(&ref, repo, argv[0], 0);
6967 if (error != NULL)
6968 goto done;
6969 error = got_ref_resolve(&commit_id, repo, ref);
6970 got_ref_close(ref);
6971 if (error != NULL)
6972 goto done;
6974 error = got_object_id_str(&commit_id_str, commit_id);
6975 if (error)
6976 goto done;
6978 error = got_ref_open(&head_ref, repo,
6979 got_worktree_get_head_ref_name(worktree), 0);
6980 if (error != NULL)
6981 goto done;
6983 error = check_same_branch(commit_id, head_ref, NULL, repo);
6984 if (error) {
6985 if (error->code != GOT_ERR_ANCESTRY)
6986 goto done;
6987 error = NULL;
6988 } else {
6989 error = got_error(GOT_ERR_SAME_BRANCH);
6990 goto done;
6993 error = got_object_open_as_commit(&commit, repo, commit_id);
6994 if (error)
6995 goto done;
6996 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6997 memset(&upa, 0, sizeof(upa));
6998 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
6999 commit_id, repo, update_progress, &upa, check_cancelled,
7000 NULL);
7001 if (error != NULL)
7002 goto done;
7004 if (upa.did_something)
7005 printf("Merged commit %s\n", commit_id_str);
7006 print_update_progress_stats(&upa);
7007 done:
7008 if (commit)
7009 got_object_commit_close(commit);
7010 free(commit_id_str);
7011 if (head_ref)
7012 got_ref_close(head_ref);
7013 if (worktree)
7014 got_worktree_close(worktree);
7015 if (repo)
7016 got_repo_close(repo);
7017 return error;
7020 __dead static void
7021 usage_backout(void)
7023 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
7024 exit(1);
7027 static const struct got_error *
7028 cmd_backout(int argc, char *argv[])
7030 const struct got_error *error = NULL;
7031 struct got_worktree *worktree = NULL;
7032 struct got_repository *repo = NULL;
7033 char *cwd = NULL, *commit_id_str = NULL;
7034 struct got_object_id *commit_id = NULL;
7035 struct got_commit_object *commit = NULL;
7036 struct got_object_qid *pid;
7037 struct got_reference *head_ref = NULL;
7038 int ch;
7039 struct got_update_progress_arg upa;
7041 while ((ch = getopt(argc, argv, "")) != -1) {
7042 switch (ch) {
7043 default:
7044 usage_backout();
7045 /* NOTREACHED */
7049 argc -= optind;
7050 argv += optind;
7052 #ifndef PROFILE
7053 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7054 "unveil", NULL) == -1)
7055 err(1, "pledge");
7056 #endif
7057 if (argc != 1)
7058 usage_backout();
7060 cwd = getcwd(NULL, 0);
7061 if (cwd == NULL) {
7062 error = got_error_from_errno("getcwd");
7063 goto done;
7065 error = got_worktree_open(&worktree, cwd);
7066 if (error) {
7067 if (error->code == GOT_ERR_NOT_WORKTREE)
7068 error = wrap_not_worktree_error(error, "backout", cwd);
7069 goto done;
7072 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7073 NULL);
7074 if (error != NULL)
7075 goto done;
7077 error = apply_unveil(got_repo_get_path(repo), 0,
7078 got_worktree_get_root_path(worktree));
7079 if (error)
7080 goto done;
7082 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7083 GOT_OBJ_TYPE_COMMIT, repo);
7084 if (error != NULL) {
7085 struct got_reference *ref;
7086 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7087 goto done;
7088 error = got_ref_open(&ref, repo, argv[0], 0);
7089 if (error != NULL)
7090 goto done;
7091 error = got_ref_resolve(&commit_id, repo, ref);
7092 got_ref_close(ref);
7093 if (error != NULL)
7094 goto done;
7096 error = got_object_id_str(&commit_id_str, commit_id);
7097 if (error)
7098 goto done;
7100 error = got_ref_open(&head_ref, repo,
7101 got_worktree_get_head_ref_name(worktree), 0);
7102 if (error != NULL)
7103 goto done;
7105 error = check_same_branch(commit_id, head_ref, NULL, repo);
7106 if (error)
7107 goto done;
7109 error = got_object_open_as_commit(&commit, repo, commit_id);
7110 if (error)
7111 goto done;
7112 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7113 if (pid == NULL) {
7114 error = got_error(GOT_ERR_ROOT_COMMIT);
7115 goto done;
7118 memset(&upa, 0, sizeof(upa));
7119 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
7120 update_progress, &upa, check_cancelled, NULL);
7121 if (error != NULL)
7122 goto done;
7124 if (upa.did_something)
7125 printf("Backed out commit %s\n", commit_id_str);
7126 print_update_progress_stats(&upa);
7127 done:
7128 if (commit)
7129 got_object_commit_close(commit);
7130 free(commit_id_str);
7131 if (head_ref)
7132 got_ref_close(head_ref);
7133 if (worktree)
7134 got_worktree_close(worktree);
7135 if (repo)
7136 got_repo_close(repo);
7137 return error;
7140 __dead static void
7141 usage_rebase(void)
7143 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
7144 getprogname());
7145 exit(1);
7148 void
7149 trim_logmsg(char *logmsg, int limit)
7151 char *nl;
7152 size_t len;
7154 len = strlen(logmsg);
7155 if (len > limit)
7156 len = limit;
7157 logmsg[len] = '\0';
7158 nl = strchr(logmsg, '\n');
7159 if (nl)
7160 *nl = '\0';
7163 static const struct got_error *
7164 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
7166 const struct got_error *err;
7167 char *logmsg0 = NULL;
7168 const char *s;
7170 err = got_object_commit_get_logmsg(&logmsg0, commit);
7171 if (err)
7172 return err;
7174 s = logmsg0;
7175 while (isspace((unsigned char)s[0]))
7176 s++;
7178 *logmsg = strdup(s);
7179 if (*logmsg == NULL) {
7180 err = got_error_from_errno("strdup");
7181 goto done;
7184 trim_logmsg(*logmsg, limit);
7185 done:
7186 free(logmsg0);
7187 return err;
7190 static const struct got_error *
7191 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
7193 const struct got_error *err;
7194 struct got_commit_object *commit = NULL;
7195 char *id_str = NULL, *logmsg = NULL;
7197 err = got_object_open_as_commit(&commit, repo, id);
7198 if (err)
7199 return err;
7201 err = got_object_id_str(&id_str, id);
7202 if (err)
7203 goto done;
7205 id_str[12] = '\0';
7207 err = get_short_logmsg(&logmsg, 42, commit);
7208 if (err)
7209 goto done;
7211 printf("%s -> merge conflict: %s\n", id_str, logmsg);
7212 done:
7213 free(id_str);
7214 got_object_commit_close(commit);
7215 free(logmsg);
7216 return err;
7219 static const struct got_error *
7220 show_rebase_progress(struct got_commit_object *commit,
7221 struct got_object_id *old_id, struct got_object_id *new_id)
7223 const struct got_error *err;
7224 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7226 err = got_object_id_str(&old_id_str, old_id);
7227 if (err)
7228 goto done;
7230 if (new_id) {
7231 err = got_object_id_str(&new_id_str, new_id);
7232 if (err)
7233 goto done;
7236 old_id_str[12] = '\0';
7237 if (new_id_str)
7238 new_id_str[12] = '\0';
7240 err = get_short_logmsg(&logmsg, 42, commit);
7241 if (err)
7242 goto done;
7244 printf("%s -> %s: %s\n", old_id_str,
7245 new_id_str ? new_id_str : "no-op change", logmsg);
7246 done:
7247 free(old_id_str);
7248 free(new_id_str);
7249 free(logmsg);
7250 return err;
7253 static const struct got_error *
7254 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
7255 struct got_reference *branch, struct got_reference *new_base_branch,
7256 struct got_reference *tmp_branch, struct got_repository *repo)
7258 printf("Switching work tree to %s\n", got_ref_get_name(branch));
7259 return got_worktree_rebase_complete(worktree, fileindex,
7260 new_base_branch, tmp_branch, branch, repo);
7263 static const struct got_error *
7264 rebase_commit(struct got_pathlist_head *merged_paths,
7265 struct got_worktree *worktree, struct got_fileindex *fileindex,
7266 struct got_reference *tmp_branch,
7267 struct got_object_id *commit_id, struct got_repository *repo)
7269 const struct got_error *error;
7270 struct got_commit_object *commit;
7271 struct got_object_id *new_commit_id;
7273 error = got_object_open_as_commit(&commit, repo, commit_id);
7274 if (error)
7275 return error;
7277 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
7278 worktree, fileindex, tmp_branch, commit, commit_id, repo);
7279 if (error) {
7280 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
7281 goto done;
7282 error = show_rebase_progress(commit, commit_id, NULL);
7283 } else {
7284 error = show_rebase_progress(commit, commit_id, new_commit_id);
7285 free(new_commit_id);
7287 done:
7288 got_object_commit_close(commit);
7289 return error;
7292 struct check_path_prefix_arg {
7293 const char *path_prefix;
7294 size_t len;
7295 int errcode;
7298 static const struct got_error *
7299 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
7300 struct got_blob_object *blob2, struct got_object_id *id1,
7301 struct got_object_id *id2, const char *path1, const char *path2,
7302 mode_t mode1, mode_t mode2, struct got_repository *repo)
7304 struct check_path_prefix_arg *a = arg;
7306 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
7307 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
7308 return got_error(a->errcode);
7310 return NULL;
7313 static const struct got_error *
7314 check_path_prefix(struct got_object_id *parent_id,
7315 struct got_object_id *commit_id, const char *path_prefix,
7316 int errcode, struct got_repository *repo)
7318 const struct got_error *err;
7319 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7320 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7321 struct check_path_prefix_arg cpp_arg;
7323 if (got_path_is_root_dir(path_prefix))
7324 return NULL;
7326 err = got_object_open_as_commit(&commit, repo, commit_id);
7327 if (err)
7328 goto done;
7330 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7331 if (err)
7332 goto done;
7334 err = got_object_open_as_tree(&tree1, repo,
7335 got_object_commit_get_tree_id(parent_commit));
7336 if (err)
7337 goto done;
7339 err = got_object_open_as_tree(&tree2, repo,
7340 got_object_commit_get_tree_id(commit));
7341 if (err)
7342 goto done;
7344 cpp_arg.path_prefix = path_prefix;
7345 while (cpp_arg.path_prefix[0] == '/')
7346 cpp_arg.path_prefix++;
7347 cpp_arg.len = strlen(cpp_arg.path_prefix);
7348 cpp_arg.errcode = errcode;
7349 err = got_diff_tree(tree1, tree2, "", "", repo,
7350 check_path_prefix_in_diff, &cpp_arg, 0);
7351 done:
7352 if (tree1)
7353 got_object_tree_close(tree1);
7354 if (tree2)
7355 got_object_tree_close(tree2);
7356 if (commit)
7357 got_object_commit_close(commit);
7358 if (parent_commit)
7359 got_object_commit_close(parent_commit);
7360 return err;
7363 static const struct got_error *
7364 collect_commits(struct got_object_id_queue *commits,
7365 struct got_object_id *initial_commit_id,
7366 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7367 const char *path_prefix, int path_prefix_errcode,
7368 struct got_repository *repo)
7370 const struct got_error *err = NULL;
7371 struct got_commit_graph *graph = NULL;
7372 struct got_object_id *parent_id = NULL;
7373 struct got_object_qid *qid;
7374 struct got_object_id *commit_id = initial_commit_id;
7376 err = got_commit_graph_open(&graph, "/", 1);
7377 if (err)
7378 return err;
7380 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7381 check_cancelled, NULL);
7382 if (err)
7383 goto done;
7384 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7385 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7386 check_cancelled, NULL);
7387 if (err) {
7388 if (err->code == GOT_ERR_ITER_COMPLETED) {
7389 err = got_error_msg(GOT_ERR_ANCESTRY,
7390 "ran out of commits to rebase before "
7391 "youngest common ancestor commit has "
7392 "been reached?!?");
7394 goto done;
7395 } else {
7396 err = check_path_prefix(parent_id, commit_id,
7397 path_prefix, path_prefix_errcode, repo);
7398 if (err)
7399 goto done;
7401 err = got_object_qid_alloc(&qid, commit_id);
7402 if (err)
7403 goto done;
7404 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
7405 commit_id = parent_id;
7408 done:
7409 got_commit_graph_close(graph);
7410 return err;
7413 static const struct got_error *
7414 cmd_rebase(int argc, char *argv[])
7416 const struct got_error *error = NULL;
7417 struct got_worktree *worktree = NULL;
7418 struct got_repository *repo = NULL;
7419 struct got_fileindex *fileindex = NULL;
7420 char *cwd = NULL;
7421 struct got_reference *branch = NULL;
7422 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
7423 struct got_object_id *commit_id = NULL, *parent_id = NULL;
7424 struct got_object_id *resume_commit_id = NULL;
7425 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
7426 struct got_commit_object *commit = NULL;
7427 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
7428 int histedit_in_progress = 0;
7429 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7430 struct got_object_id_queue commits;
7431 struct got_pathlist_head merged_paths;
7432 const struct got_object_id_queue *parent_ids;
7433 struct got_object_qid *qid, *pid;
7435 SIMPLEQ_INIT(&commits);
7436 TAILQ_INIT(&merged_paths);
7438 while ((ch = getopt(argc, argv, "ac")) != -1) {
7439 switch (ch) {
7440 case 'a':
7441 abort_rebase = 1;
7442 break;
7443 case 'c':
7444 continue_rebase = 1;
7445 break;
7446 default:
7447 usage_rebase();
7448 /* NOTREACHED */
7452 argc -= optind;
7453 argv += optind;
7455 #ifndef PROFILE
7456 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7457 "unveil", NULL) == -1)
7458 err(1, "pledge");
7459 #endif
7460 if (abort_rebase && continue_rebase)
7461 usage_rebase();
7462 else if (abort_rebase || continue_rebase) {
7463 if (argc != 0)
7464 usage_rebase();
7465 } else if (argc != 1)
7466 usage_rebase();
7468 cwd = getcwd(NULL, 0);
7469 if (cwd == NULL) {
7470 error = got_error_from_errno("getcwd");
7471 goto done;
7473 error = got_worktree_open(&worktree, cwd);
7474 if (error) {
7475 if (error->code == GOT_ERR_NOT_WORKTREE)
7476 error = wrap_not_worktree_error(error, "rebase", cwd);
7477 goto done;
7480 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7481 NULL);
7482 if (error != NULL)
7483 goto done;
7485 error = apply_unveil(got_repo_get_path(repo), 0,
7486 got_worktree_get_root_path(worktree));
7487 if (error)
7488 goto done;
7490 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7491 worktree);
7492 if (error)
7493 goto done;
7494 if (histedit_in_progress) {
7495 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7496 goto done;
7499 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7500 if (error)
7501 goto done;
7503 if (abort_rebase) {
7504 struct got_update_progress_arg upa;
7505 if (!rebase_in_progress) {
7506 error = got_error(GOT_ERR_NOT_REBASING);
7507 goto done;
7509 error = got_worktree_rebase_continue(&resume_commit_id,
7510 &new_base_branch, &tmp_branch, &branch, &fileindex,
7511 worktree, repo);
7512 if (error)
7513 goto done;
7514 printf("Switching work tree to %s\n",
7515 got_ref_get_symref_target(new_base_branch));
7516 memset(&upa, 0, sizeof(upa));
7517 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7518 new_base_branch, update_progress, &upa);
7519 if (error)
7520 goto done;
7521 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7522 print_update_progress_stats(&upa);
7523 goto done; /* nothing else to do */
7526 if (continue_rebase) {
7527 if (!rebase_in_progress) {
7528 error = got_error(GOT_ERR_NOT_REBASING);
7529 goto done;
7531 error = got_worktree_rebase_continue(&resume_commit_id,
7532 &new_base_branch, &tmp_branch, &branch, &fileindex,
7533 worktree, repo);
7534 if (error)
7535 goto done;
7537 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7538 resume_commit_id, repo);
7539 if (error)
7540 goto done;
7542 yca_id = got_object_id_dup(resume_commit_id);
7543 if (yca_id == NULL) {
7544 error = got_error_from_errno("got_object_id_dup");
7545 goto done;
7547 } else {
7548 error = got_ref_open(&branch, repo, argv[0], 0);
7549 if (error != NULL)
7550 goto done;
7553 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7554 if (error)
7555 goto done;
7557 if (!continue_rebase) {
7558 struct got_object_id *base_commit_id;
7560 base_commit_id = got_worktree_get_base_commit_id(worktree);
7561 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7562 base_commit_id, branch_head_commit_id, repo,
7563 check_cancelled, NULL);
7564 if (error)
7565 goto done;
7566 if (yca_id == NULL) {
7567 error = got_error_msg(GOT_ERR_ANCESTRY,
7568 "specified branch shares no common ancestry "
7569 "with work tree's branch");
7570 goto done;
7573 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7574 if (error) {
7575 if (error->code != GOT_ERR_ANCESTRY)
7576 goto done;
7577 error = NULL;
7578 } else {
7579 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7580 "specified branch resolves to a commit which "
7581 "is already contained in work tree's branch");
7582 goto done;
7584 error = got_worktree_rebase_prepare(&new_base_branch,
7585 &tmp_branch, &fileindex, worktree, branch, repo);
7586 if (error)
7587 goto done;
7590 commit_id = branch_head_commit_id;
7591 error = got_object_open_as_commit(&commit, repo, commit_id);
7592 if (error)
7593 goto done;
7595 parent_ids = got_object_commit_get_parent_ids(commit);
7596 pid = SIMPLEQ_FIRST(parent_ids);
7597 if (pid == NULL) {
7598 if (!continue_rebase) {
7599 struct got_update_progress_arg upa;
7600 memset(&upa, 0, sizeof(upa));
7601 error = got_worktree_rebase_abort(worktree, fileindex,
7602 repo, new_base_branch, update_progress, &upa);
7603 if (error)
7604 goto done;
7605 printf("Rebase of %s aborted\n",
7606 got_ref_get_name(branch));
7607 print_update_progress_stats(&upa);
7610 error = got_error(GOT_ERR_EMPTY_REBASE);
7611 goto done;
7613 error = collect_commits(&commits, commit_id, pid->id,
7614 yca_id, got_worktree_get_path_prefix(worktree),
7615 GOT_ERR_REBASE_PATH, repo);
7616 got_object_commit_close(commit);
7617 commit = NULL;
7618 if (error)
7619 goto done;
7621 if (SIMPLEQ_EMPTY(&commits)) {
7622 if (continue_rebase) {
7623 error = rebase_complete(worktree, fileindex,
7624 branch, new_base_branch, tmp_branch, repo);
7625 goto done;
7626 } else {
7627 /* Fast-forward the reference of the branch. */
7628 struct got_object_id *new_head_commit_id;
7629 char *id_str;
7630 error = got_ref_resolve(&new_head_commit_id, repo,
7631 new_base_branch);
7632 if (error)
7633 goto done;
7634 error = got_object_id_str(&id_str, new_head_commit_id);
7635 printf("Forwarding %s to commit %s\n",
7636 got_ref_get_name(branch), id_str);
7637 free(id_str);
7638 error = got_ref_change_ref(branch,
7639 new_head_commit_id);
7640 if (error)
7641 goto done;
7645 pid = NULL;
7646 SIMPLEQ_FOREACH(qid, &commits, entry) {
7647 struct got_update_progress_arg upa;
7649 commit_id = qid->id;
7650 parent_id = pid ? pid->id : yca_id;
7651 pid = qid;
7653 memset(&upa, 0, sizeof(upa));
7654 error = got_worktree_rebase_merge_files(&merged_paths,
7655 worktree, fileindex, parent_id, commit_id, repo,
7656 update_progress, &upa, check_cancelled, NULL);
7657 if (error)
7658 goto done;
7660 print_update_progress_stats(&upa);
7661 if (upa.conflicts > 0)
7662 rebase_status = GOT_STATUS_CONFLICT;
7664 if (rebase_status == GOT_STATUS_CONFLICT) {
7665 error = show_rebase_merge_conflict(qid->id, repo);
7666 if (error)
7667 goto done;
7668 got_worktree_rebase_pathlist_free(&merged_paths);
7669 break;
7672 error = rebase_commit(&merged_paths, worktree, fileindex,
7673 tmp_branch, commit_id, repo);
7674 got_worktree_rebase_pathlist_free(&merged_paths);
7675 if (error)
7676 goto done;
7679 if (rebase_status == GOT_STATUS_CONFLICT) {
7680 error = got_worktree_rebase_postpone(worktree, fileindex);
7681 if (error)
7682 goto done;
7683 error = got_error_msg(GOT_ERR_CONFLICTS,
7684 "conflicts must be resolved before rebasing can continue");
7685 } else
7686 error = rebase_complete(worktree, fileindex, branch,
7687 new_base_branch, tmp_branch, repo);
7688 done:
7689 got_object_id_queue_free(&commits);
7690 free(branch_head_commit_id);
7691 free(resume_commit_id);
7692 free(yca_id);
7693 if (commit)
7694 got_object_commit_close(commit);
7695 if (branch)
7696 got_ref_close(branch);
7697 if (new_base_branch)
7698 got_ref_close(new_base_branch);
7699 if (tmp_branch)
7700 got_ref_close(tmp_branch);
7701 if (worktree)
7702 got_worktree_close(worktree);
7703 if (repo)
7704 got_repo_close(repo);
7705 return error;
7708 __dead static void
7709 usage_histedit(void)
7711 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
7712 getprogname());
7713 exit(1);
7716 #define GOT_HISTEDIT_PICK 'p'
7717 #define GOT_HISTEDIT_EDIT 'e'
7718 #define GOT_HISTEDIT_FOLD 'f'
7719 #define GOT_HISTEDIT_DROP 'd'
7720 #define GOT_HISTEDIT_MESG 'm'
7722 static struct got_histedit_cmd {
7723 unsigned char code;
7724 const char *name;
7725 const char *desc;
7726 } got_histedit_cmds[] = {
7727 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7728 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7729 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7730 "be used" },
7731 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7732 { GOT_HISTEDIT_MESG, "mesg",
7733 "single-line log message for commit above (open editor if empty)" },
7736 struct got_histedit_list_entry {
7737 TAILQ_ENTRY(got_histedit_list_entry) entry;
7738 struct got_object_id *commit_id;
7739 const struct got_histedit_cmd *cmd;
7740 char *logmsg;
7742 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7744 static const struct got_error *
7745 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7746 FILE *f, struct got_repository *repo)
7748 const struct got_error *err = NULL;
7749 char *logmsg = NULL, *id_str = NULL;
7750 struct got_commit_object *commit = NULL;
7751 int n;
7753 err = got_object_open_as_commit(&commit, repo, commit_id);
7754 if (err)
7755 goto done;
7757 err = get_short_logmsg(&logmsg, 34, commit);
7758 if (err)
7759 goto done;
7761 err = got_object_id_str(&id_str, commit_id);
7762 if (err)
7763 goto done;
7765 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7766 if (n < 0)
7767 err = got_ferror(f, GOT_ERR_IO);
7768 done:
7769 if (commit)
7770 got_object_commit_close(commit);
7771 free(id_str);
7772 free(logmsg);
7773 return err;
7776 static const struct got_error *
7777 histedit_write_commit_list(struct got_object_id_queue *commits,
7778 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7780 const struct got_error *err = NULL;
7781 struct got_object_qid *qid;
7783 if (SIMPLEQ_EMPTY(commits))
7784 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7786 SIMPLEQ_FOREACH(qid, commits, entry) {
7787 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7788 f, repo);
7789 if (err)
7790 break;
7791 if (edit_logmsg_only) {
7792 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7793 if (n < 0) {
7794 err = got_ferror(f, GOT_ERR_IO);
7795 break;
7800 return err;
7803 static const struct got_error *
7804 write_cmd_list(FILE *f, const char *branch_name,
7805 struct got_object_id_queue *commits)
7807 const struct got_error *err = NULL;
7808 int n, i;
7809 char *id_str;
7810 struct got_object_qid *qid;
7812 qid = SIMPLEQ_FIRST(commits);
7813 err = got_object_id_str(&id_str, qid->id);
7814 if (err)
7815 return err;
7817 n = fprintf(f,
7818 "# Editing the history of branch '%s' starting at\n"
7819 "# commit %s\n"
7820 "# Commits will be processed in order from top to "
7821 "bottom of this file.\n", branch_name, id_str);
7822 if (n < 0) {
7823 err = got_ferror(f, GOT_ERR_IO);
7824 goto done;
7827 n = fprintf(f, "# Available histedit commands:\n");
7828 if (n < 0) {
7829 err = got_ferror(f, GOT_ERR_IO);
7830 goto done;
7833 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7834 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7835 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7836 cmd->desc);
7837 if (n < 0) {
7838 err = got_ferror(f, GOT_ERR_IO);
7839 break;
7842 done:
7843 free(id_str);
7844 return err;
7847 static const struct got_error *
7848 histedit_syntax_error(int lineno)
7850 static char msg[42];
7851 int ret;
7853 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7854 lineno);
7855 if (ret == -1 || ret >= sizeof(msg))
7856 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7858 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7861 static const struct got_error *
7862 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7863 char *logmsg, struct got_repository *repo)
7865 const struct got_error *err;
7866 struct got_commit_object *folded_commit = NULL;
7867 char *id_str, *folded_logmsg = NULL;
7869 err = got_object_id_str(&id_str, hle->commit_id);
7870 if (err)
7871 return err;
7873 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7874 if (err)
7875 goto done;
7877 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7878 if (err)
7879 goto done;
7880 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7881 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7882 folded_logmsg) == -1) {
7883 err = got_error_from_errno("asprintf");
7885 done:
7886 if (folded_commit)
7887 got_object_commit_close(folded_commit);
7888 free(id_str);
7889 free(folded_logmsg);
7890 return err;
7893 static struct got_histedit_list_entry *
7894 get_folded_commits(struct got_histedit_list_entry *hle)
7896 struct got_histedit_list_entry *prev, *folded = NULL;
7898 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7899 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7900 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7901 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7902 folded = prev;
7903 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7906 return folded;
7909 static const struct got_error *
7910 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7911 struct got_repository *repo)
7913 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7914 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7915 const struct got_error *err = NULL;
7916 struct got_commit_object *commit = NULL;
7917 int logmsg_len;
7918 int fd;
7919 struct got_histedit_list_entry *folded = NULL;
7921 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7922 if (err)
7923 return err;
7925 folded = get_folded_commits(hle);
7926 if (folded) {
7927 while (folded != hle) {
7928 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7929 folded = TAILQ_NEXT(folded, entry);
7930 continue;
7932 err = append_folded_commit_msg(&new_msg, folded,
7933 logmsg, repo);
7934 if (err)
7935 goto done;
7936 free(logmsg);
7937 logmsg = new_msg;
7938 folded = TAILQ_NEXT(folded, entry);
7942 err = got_object_id_str(&id_str, hle->commit_id);
7943 if (err)
7944 goto done;
7945 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7946 if (err)
7947 goto done;
7948 logmsg_len = asprintf(&new_msg,
7949 "%s\n# original log message of commit %s: %s",
7950 logmsg ? logmsg : "", id_str, orig_logmsg);
7951 if (logmsg_len == -1) {
7952 err = got_error_from_errno("asprintf");
7953 goto done;
7955 free(logmsg);
7956 logmsg = new_msg;
7958 err = got_object_id_str(&id_str, hle->commit_id);
7959 if (err)
7960 goto done;
7962 err = got_opentemp_named_fd(&logmsg_path, &fd,
7963 GOT_TMPDIR_STR "/got-logmsg");
7964 if (err)
7965 goto done;
7967 write(fd, logmsg, logmsg_len);
7968 close(fd);
7970 err = get_editor(&editor);
7971 if (err)
7972 goto done;
7974 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
7975 if (err) {
7976 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
7977 goto done;
7978 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
7980 done:
7981 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
7982 err = got_error_from_errno2("unlink", logmsg_path);
7983 free(logmsg_path);
7984 free(logmsg);
7985 free(orig_logmsg);
7986 free(editor);
7987 if (commit)
7988 got_object_commit_close(commit);
7989 return err;
7992 static const struct got_error *
7993 histedit_parse_list(struct got_histedit_list *histedit_cmds,
7994 FILE *f, struct got_repository *repo)
7996 const struct got_error *err = NULL;
7997 char *line = NULL, *p, *end;
7998 size_t size;
7999 ssize_t len;
8000 int lineno = 0, i;
8001 const struct got_histedit_cmd *cmd;
8002 struct got_object_id *commit_id = NULL;
8003 struct got_histedit_list_entry *hle = NULL;
8005 for (;;) {
8006 len = getline(&line, &size, f);
8007 if (len == -1) {
8008 const struct got_error *getline_err;
8009 if (feof(f))
8010 break;
8011 getline_err = got_error_from_errno("getline");
8012 err = got_ferror(f, getline_err->code);
8013 break;
8015 lineno++;
8016 p = line;
8017 while (isspace((unsigned char)p[0]))
8018 p++;
8019 if (p[0] == '#' || p[0] == '\0') {
8020 free(line);
8021 line = NULL;
8022 continue;
8024 cmd = NULL;
8025 for (i = 0; i < nitems(got_histedit_cmds); i++) {
8026 cmd = &got_histedit_cmds[i];
8027 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
8028 isspace((unsigned char)p[strlen(cmd->name)])) {
8029 p += strlen(cmd->name);
8030 break;
8032 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
8033 p++;
8034 break;
8037 if (i == nitems(got_histedit_cmds)) {
8038 err = histedit_syntax_error(lineno);
8039 break;
8041 while (isspace((unsigned char)p[0]))
8042 p++;
8043 if (cmd->code == GOT_HISTEDIT_MESG) {
8044 if (hle == NULL || hle->logmsg != NULL) {
8045 err = got_error(GOT_ERR_HISTEDIT_CMD);
8046 break;
8048 if (p[0] == '\0') {
8049 err = histedit_edit_logmsg(hle, repo);
8050 if (err)
8051 break;
8052 } else {
8053 hle->logmsg = strdup(p);
8054 if (hle->logmsg == NULL) {
8055 err = got_error_from_errno("strdup");
8056 break;
8059 free(line);
8060 line = NULL;
8061 continue;
8062 } else {
8063 end = p;
8064 while (end[0] && !isspace((unsigned char)end[0]))
8065 end++;
8066 *end = '\0';
8068 err = got_object_resolve_id_str(&commit_id, repo, p);
8069 if (err) {
8070 /* override error code */
8071 err = histedit_syntax_error(lineno);
8072 break;
8075 hle = malloc(sizeof(*hle));
8076 if (hle == NULL) {
8077 err = got_error_from_errno("malloc");
8078 break;
8080 hle->cmd = cmd;
8081 hle->commit_id = commit_id;
8082 hle->logmsg = NULL;
8083 commit_id = NULL;
8084 free(line);
8085 line = NULL;
8086 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
8089 free(line);
8090 free(commit_id);
8091 return err;
8094 static const struct got_error *
8095 histedit_check_script(struct got_histedit_list *histedit_cmds,
8096 struct got_object_id_queue *commits, struct got_repository *repo)
8098 const struct got_error *err = NULL;
8099 struct got_object_qid *qid;
8100 struct got_histedit_list_entry *hle;
8101 static char msg[92];
8102 char *id_str;
8104 if (TAILQ_EMPTY(histedit_cmds))
8105 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
8106 "histedit script contains no commands");
8107 if (SIMPLEQ_EMPTY(commits))
8108 return got_error(GOT_ERR_EMPTY_HISTEDIT);
8110 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8111 struct got_histedit_list_entry *hle2;
8112 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
8113 if (hle == hle2)
8114 continue;
8115 if (got_object_id_cmp(hle->commit_id,
8116 hle2->commit_id) != 0)
8117 continue;
8118 err = got_object_id_str(&id_str, hle->commit_id);
8119 if (err)
8120 return err;
8121 snprintf(msg, sizeof(msg), "commit %s is listed "
8122 "more than once in histedit script", id_str);
8123 free(id_str);
8124 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8128 SIMPLEQ_FOREACH(qid, commits, entry) {
8129 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8130 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
8131 break;
8133 if (hle == NULL) {
8134 err = got_object_id_str(&id_str, qid->id);
8135 if (err)
8136 return err;
8137 snprintf(msg, sizeof(msg),
8138 "commit %s missing from histedit script", id_str);
8139 free(id_str);
8140 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8144 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
8145 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
8146 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
8147 "last commit in histedit script cannot be folded");
8149 return NULL;
8152 static const struct got_error *
8153 histedit_run_editor(struct got_histedit_list *histedit_cmds,
8154 const char *path, struct got_object_id_queue *commits,
8155 struct got_repository *repo)
8157 const struct got_error *err = NULL;
8158 char *editor;
8159 FILE *f = NULL;
8161 err = get_editor(&editor);
8162 if (err)
8163 return err;
8165 if (spawn_editor(editor, path) == -1) {
8166 err = got_error_from_errno("failed spawning editor");
8167 goto done;
8170 f = fopen(path, "r");
8171 if (f == NULL) {
8172 err = got_error_from_errno("fopen");
8173 goto done;
8175 err = histedit_parse_list(histedit_cmds, f, repo);
8176 if (err)
8177 goto done;
8179 err = histedit_check_script(histedit_cmds, commits, repo);
8180 done:
8181 if (f && fclose(f) != 0 && err == NULL)
8182 err = got_error_from_errno("fclose");
8183 free(editor);
8184 return err;
8187 static const struct got_error *
8188 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
8189 struct got_object_id_queue *, const char *, const char *,
8190 struct got_repository *);
8192 static const struct got_error *
8193 histedit_edit_script(struct got_histedit_list *histedit_cmds,
8194 struct got_object_id_queue *commits, const char *branch_name,
8195 int edit_logmsg_only, struct got_repository *repo)
8197 const struct got_error *err;
8198 FILE *f = NULL;
8199 char *path = NULL;
8201 err = got_opentemp_named(&path, &f, "got-histedit");
8202 if (err)
8203 return err;
8205 err = write_cmd_list(f, branch_name, commits);
8206 if (err)
8207 goto done;
8209 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
8210 if (err)
8211 goto done;
8213 if (edit_logmsg_only) {
8214 rewind(f);
8215 err = histedit_parse_list(histedit_cmds, f, repo);
8216 } else {
8217 if (fclose(f) != 0) {
8218 err = got_error_from_errno("fclose");
8219 goto done;
8221 f = NULL;
8222 err = histedit_run_editor(histedit_cmds, path, commits, repo);
8223 if (err) {
8224 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8225 err->code != GOT_ERR_HISTEDIT_CMD)
8226 goto done;
8227 err = histedit_edit_list_retry(histedit_cmds, err,
8228 commits, path, branch_name, repo);
8231 done:
8232 if (f && fclose(f) != 0 && err == NULL)
8233 err = got_error_from_errno("fclose");
8234 if (path && unlink(path) != 0 && err == NULL)
8235 err = got_error_from_errno2("unlink", path);
8236 free(path);
8237 return err;
8240 static const struct got_error *
8241 histedit_save_list(struct got_histedit_list *histedit_cmds,
8242 struct got_worktree *worktree, struct got_repository *repo)
8244 const struct got_error *err = NULL;
8245 char *path = NULL;
8246 FILE *f = NULL;
8247 struct got_histedit_list_entry *hle;
8248 struct got_commit_object *commit = NULL;
8250 err = got_worktree_get_histedit_script_path(&path, worktree);
8251 if (err)
8252 return err;
8254 f = fopen(path, "w");
8255 if (f == NULL) {
8256 err = got_error_from_errno2("fopen", path);
8257 goto done;
8259 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8260 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
8261 repo);
8262 if (err)
8263 break;
8265 if (hle->logmsg) {
8266 int n = fprintf(f, "%c %s\n",
8267 GOT_HISTEDIT_MESG, hle->logmsg);
8268 if (n < 0) {
8269 err = got_ferror(f, GOT_ERR_IO);
8270 break;
8274 done:
8275 if (f && fclose(f) != 0 && err == NULL)
8276 err = got_error_from_errno("fclose");
8277 free(path);
8278 if (commit)
8279 got_object_commit_close(commit);
8280 return err;
8283 void
8284 histedit_free_list(struct got_histedit_list *histedit_cmds)
8286 struct got_histedit_list_entry *hle;
8288 while ((hle = TAILQ_FIRST(histedit_cmds))) {
8289 TAILQ_REMOVE(histedit_cmds, hle, entry);
8290 free(hle);
8294 static const struct got_error *
8295 histedit_load_list(struct got_histedit_list *histedit_cmds,
8296 const char *path, struct got_repository *repo)
8298 const struct got_error *err = NULL;
8299 FILE *f = NULL;
8301 f = fopen(path, "r");
8302 if (f == NULL) {
8303 err = got_error_from_errno2("fopen", path);
8304 goto done;
8307 err = histedit_parse_list(histedit_cmds, f, repo);
8308 done:
8309 if (f && fclose(f) != 0 && err == NULL)
8310 err = got_error_from_errno("fclose");
8311 return err;
8314 static const struct got_error *
8315 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
8316 const struct got_error *edit_err, struct got_object_id_queue *commits,
8317 const char *path, const char *branch_name, struct got_repository *repo)
8319 const struct got_error *err = NULL, *prev_err = edit_err;
8320 int resp = ' ';
8322 while (resp != 'c' && resp != 'r' && resp != 'a') {
8323 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
8324 "or (a)bort: ", getprogname(), prev_err->msg);
8325 resp = getchar();
8326 if (resp == '\n')
8327 resp = getchar();
8328 if (resp == 'c') {
8329 histedit_free_list(histedit_cmds);
8330 err = histedit_run_editor(histedit_cmds, path, commits,
8331 repo);
8332 if (err) {
8333 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8334 err->code != GOT_ERR_HISTEDIT_CMD)
8335 break;
8336 prev_err = err;
8337 resp = ' ';
8338 continue;
8340 break;
8341 } else if (resp == 'r') {
8342 histedit_free_list(histedit_cmds);
8343 err = histedit_edit_script(histedit_cmds,
8344 commits, branch_name, 0, repo);
8345 if (err) {
8346 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8347 err->code != GOT_ERR_HISTEDIT_CMD)
8348 break;
8349 prev_err = err;
8350 resp = ' ';
8351 continue;
8353 break;
8354 } else if (resp == 'a') {
8355 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
8356 break;
8357 } else
8358 printf("invalid response '%c'\n", resp);
8361 return err;
8364 static const struct got_error *
8365 histedit_complete(struct got_worktree *worktree,
8366 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
8367 struct got_reference *branch, struct got_repository *repo)
8369 printf("Switching work tree to %s\n",
8370 got_ref_get_symref_target(branch));
8371 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
8372 branch, repo);
8375 static const struct got_error *
8376 show_histedit_progress(struct got_commit_object *commit,
8377 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
8379 const struct got_error *err;
8380 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8382 err = got_object_id_str(&old_id_str, hle->commit_id);
8383 if (err)
8384 goto done;
8386 if (new_id) {
8387 err = got_object_id_str(&new_id_str, new_id);
8388 if (err)
8389 goto done;
8392 old_id_str[12] = '\0';
8393 if (new_id_str)
8394 new_id_str[12] = '\0';
8396 if (hle->logmsg) {
8397 logmsg = strdup(hle->logmsg);
8398 if (logmsg == NULL) {
8399 err = got_error_from_errno("strdup");
8400 goto done;
8402 trim_logmsg(logmsg, 42);
8403 } else {
8404 err = get_short_logmsg(&logmsg, 42, commit);
8405 if (err)
8406 goto done;
8409 switch (hle->cmd->code) {
8410 case GOT_HISTEDIT_PICK:
8411 case GOT_HISTEDIT_EDIT:
8412 printf("%s -> %s: %s\n", old_id_str,
8413 new_id_str ? new_id_str : "no-op change", logmsg);
8414 break;
8415 case GOT_HISTEDIT_DROP:
8416 case GOT_HISTEDIT_FOLD:
8417 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
8418 logmsg);
8419 break;
8420 default:
8421 break;
8423 done:
8424 free(old_id_str);
8425 free(new_id_str);
8426 return err;
8429 static const struct got_error *
8430 histedit_commit(struct got_pathlist_head *merged_paths,
8431 struct got_worktree *worktree, struct got_fileindex *fileindex,
8432 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
8433 struct got_repository *repo)
8435 const struct got_error *err;
8436 struct got_commit_object *commit;
8437 struct got_object_id *new_commit_id;
8439 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
8440 && hle->logmsg == NULL) {
8441 err = histedit_edit_logmsg(hle, repo);
8442 if (err)
8443 return err;
8446 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8447 if (err)
8448 return err;
8450 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
8451 worktree, fileindex, tmp_branch, commit, hle->commit_id,
8452 hle->logmsg, repo);
8453 if (err) {
8454 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
8455 goto done;
8456 err = show_histedit_progress(commit, hle, NULL);
8457 } else {
8458 err = show_histedit_progress(commit, hle, new_commit_id);
8459 free(new_commit_id);
8461 done:
8462 got_object_commit_close(commit);
8463 return err;
8466 static const struct got_error *
8467 histedit_skip_commit(struct got_histedit_list_entry *hle,
8468 struct got_worktree *worktree, struct got_repository *repo)
8470 const struct got_error *error;
8471 struct got_commit_object *commit;
8473 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
8474 repo);
8475 if (error)
8476 return error;
8478 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
8479 if (error)
8480 return error;
8482 error = show_histedit_progress(commit, hle, NULL);
8483 got_object_commit_close(commit);
8484 return error;
8487 static const struct got_error *
8488 check_local_changes(void *arg, unsigned char status,
8489 unsigned char staged_status, const char *path,
8490 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8491 struct got_object_id *commit_id, int dirfd, const char *de_name)
8493 int *have_local_changes = arg;
8495 switch (status) {
8496 case GOT_STATUS_ADD:
8497 case GOT_STATUS_DELETE:
8498 case GOT_STATUS_MODIFY:
8499 case GOT_STATUS_CONFLICT:
8500 *have_local_changes = 1;
8501 return got_error(GOT_ERR_CANCELLED);
8502 default:
8503 break;
8506 switch (staged_status) {
8507 case GOT_STATUS_ADD:
8508 case GOT_STATUS_DELETE:
8509 case GOT_STATUS_MODIFY:
8510 *have_local_changes = 1;
8511 return got_error(GOT_ERR_CANCELLED);
8512 default:
8513 break;
8516 return NULL;
8519 static const struct got_error *
8520 cmd_histedit(int argc, char *argv[])
8522 const struct got_error *error = NULL;
8523 struct got_worktree *worktree = NULL;
8524 struct got_fileindex *fileindex = NULL;
8525 struct got_repository *repo = NULL;
8526 char *cwd = NULL;
8527 struct got_reference *branch = NULL;
8528 struct got_reference *tmp_branch = NULL;
8529 struct got_object_id *resume_commit_id = NULL;
8530 struct got_object_id *base_commit_id = NULL;
8531 struct got_object_id *head_commit_id = NULL;
8532 struct got_commit_object *commit = NULL;
8533 int ch, rebase_in_progress = 0;
8534 struct got_update_progress_arg upa;
8535 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8536 int edit_logmsg_only = 0;
8537 const char *edit_script_path = NULL;
8538 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8539 struct got_object_id_queue commits;
8540 struct got_pathlist_head merged_paths;
8541 const struct got_object_id_queue *parent_ids;
8542 struct got_object_qid *pid;
8543 struct got_histedit_list histedit_cmds;
8544 struct got_histedit_list_entry *hle;
8546 SIMPLEQ_INIT(&commits);
8547 TAILQ_INIT(&histedit_cmds);
8548 TAILQ_INIT(&merged_paths);
8549 memset(&upa, 0, sizeof(upa));
8551 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
8552 switch (ch) {
8553 case 'a':
8554 abort_edit = 1;
8555 break;
8556 case 'c':
8557 continue_edit = 1;
8558 break;
8559 case 'F':
8560 edit_script_path = optarg;
8561 break;
8562 case 'm':
8563 edit_logmsg_only = 1;
8564 break;
8565 default:
8566 usage_histedit();
8567 /* NOTREACHED */
8571 argc -= optind;
8572 argv += optind;
8574 #ifndef PROFILE
8575 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8576 "unveil", NULL) == -1)
8577 err(1, "pledge");
8578 #endif
8579 if (abort_edit && continue_edit)
8580 errx(1, "histedit's -a and -c options are mutually exclusive");
8581 if (edit_script_path && edit_logmsg_only)
8582 errx(1, "histedit's -F and -m options are mutually exclusive");
8583 if (abort_edit && edit_logmsg_only)
8584 errx(1, "histedit's -a and -m options are mutually exclusive");
8585 if (continue_edit && edit_logmsg_only)
8586 errx(1, "histedit's -c and -m options are mutually exclusive");
8587 if (argc != 0)
8588 usage_histedit();
8591 * This command cannot apply unveil(2) in all cases because the
8592 * user may choose to run an editor to edit the histedit script
8593 * and to edit individual commit log messages.
8594 * unveil(2) traverses exec(2); if an editor is used we have to
8595 * apply unveil after edit script and log messages have been written.
8596 * XXX TODO: Make use of unveil(2) where possible.
8599 cwd = getcwd(NULL, 0);
8600 if (cwd == NULL) {
8601 error = got_error_from_errno("getcwd");
8602 goto done;
8604 error = got_worktree_open(&worktree, cwd);
8605 if (error) {
8606 if (error->code == GOT_ERR_NOT_WORKTREE)
8607 error = wrap_not_worktree_error(error, "histedit", cwd);
8608 goto done;
8611 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8612 NULL);
8613 if (error != NULL)
8614 goto done;
8616 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8617 if (error)
8618 goto done;
8619 if (rebase_in_progress) {
8620 error = got_error(GOT_ERR_REBASING);
8621 goto done;
8624 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8625 if (error)
8626 goto done;
8628 if (edit_in_progress && edit_logmsg_only) {
8629 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8630 "histedit operation is in progress in this "
8631 "work tree and must be continued or aborted "
8632 "before the -m option can be used");
8633 goto done;
8636 if (edit_in_progress && abort_edit) {
8637 error = got_worktree_histedit_continue(&resume_commit_id,
8638 &tmp_branch, &branch, &base_commit_id, &fileindex,
8639 worktree, repo);
8640 if (error)
8641 goto done;
8642 printf("Switching work tree to %s\n",
8643 got_ref_get_symref_target(branch));
8644 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8645 branch, base_commit_id, update_progress, &upa);
8646 if (error)
8647 goto done;
8648 printf("Histedit of %s aborted\n",
8649 got_ref_get_symref_target(branch));
8650 print_update_progress_stats(&upa);
8651 goto done; /* nothing else to do */
8652 } else if (abort_edit) {
8653 error = got_error(GOT_ERR_NOT_HISTEDIT);
8654 goto done;
8657 if (continue_edit) {
8658 char *path;
8660 if (!edit_in_progress) {
8661 error = got_error(GOT_ERR_NOT_HISTEDIT);
8662 goto done;
8665 error = got_worktree_get_histedit_script_path(&path, worktree);
8666 if (error)
8667 goto done;
8669 error = histedit_load_list(&histedit_cmds, path, repo);
8670 free(path);
8671 if (error)
8672 goto done;
8674 error = got_worktree_histedit_continue(&resume_commit_id,
8675 &tmp_branch, &branch, &base_commit_id, &fileindex,
8676 worktree, repo);
8677 if (error)
8678 goto done;
8680 error = got_ref_resolve(&head_commit_id, repo, branch);
8681 if (error)
8682 goto done;
8684 error = got_object_open_as_commit(&commit, repo,
8685 head_commit_id);
8686 if (error)
8687 goto done;
8688 parent_ids = got_object_commit_get_parent_ids(commit);
8689 pid = SIMPLEQ_FIRST(parent_ids);
8690 if (pid == NULL) {
8691 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8692 goto done;
8694 error = collect_commits(&commits, head_commit_id, pid->id,
8695 base_commit_id, got_worktree_get_path_prefix(worktree),
8696 GOT_ERR_HISTEDIT_PATH, repo);
8697 got_object_commit_close(commit);
8698 commit = NULL;
8699 if (error)
8700 goto done;
8701 } else {
8702 if (edit_in_progress) {
8703 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8704 goto done;
8707 error = got_ref_open(&branch, repo,
8708 got_worktree_get_head_ref_name(worktree), 0);
8709 if (error != NULL)
8710 goto done;
8712 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8713 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8714 "will not edit commit history of a branch outside "
8715 "the \"refs/heads/\" reference namespace");
8716 goto done;
8719 error = got_ref_resolve(&head_commit_id, repo, branch);
8720 got_ref_close(branch);
8721 branch = NULL;
8722 if (error)
8723 goto done;
8725 error = got_object_open_as_commit(&commit, repo,
8726 head_commit_id);
8727 if (error)
8728 goto done;
8729 parent_ids = got_object_commit_get_parent_ids(commit);
8730 pid = SIMPLEQ_FIRST(parent_ids);
8731 if (pid == NULL) {
8732 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8733 goto done;
8735 error = collect_commits(&commits, head_commit_id, pid->id,
8736 got_worktree_get_base_commit_id(worktree),
8737 got_worktree_get_path_prefix(worktree),
8738 GOT_ERR_HISTEDIT_PATH, repo);
8739 got_object_commit_close(commit);
8740 commit = NULL;
8741 if (error)
8742 goto done;
8744 if (SIMPLEQ_EMPTY(&commits)) {
8745 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8746 goto done;
8749 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8750 &base_commit_id, &fileindex, worktree, repo);
8751 if (error)
8752 goto done;
8754 if (edit_script_path) {
8755 error = histedit_load_list(&histedit_cmds,
8756 edit_script_path, repo);
8757 if (error) {
8758 got_worktree_histedit_abort(worktree, fileindex,
8759 repo, branch, base_commit_id,
8760 update_progress, &upa);
8761 print_update_progress_stats(&upa);
8762 goto done;
8764 } else {
8765 const char *branch_name;
8766 branch_name = got_ref_get_symref_target(branch);
8767 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8768 branch_name += 11;
8769 error = histedit_edit_script(&histedit_cmds, &commits,
8770 branch_name, edit_logmsg_only, repo);
8771 if (error) {
8772 got_worktree_histedit_abort(worktree, fileindex,
8773 repo, branch, base_commit_id,
8774 update_progress, &upa);
8775 print_update_progress_stats(&upa);
8776 goto done;
8781 error = histedit_save_list(&histedit_cmds, worktree,
8782 repo);
8783 if (error) {
8784 got_worktree_histedit_abort(worktree, fileindex,
8785 repo, branch, base_commit_id,
8786 update_progress, &upa);
8787 print_update_progress_stats(&upa);
8788 goto done;
8793 error = histedit_check_script(&histedit_cmds, &commits, repo);
8794 if (error)
8795 goto done;
8797 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8798 if (resume_commit_id) {
8799 if (got_object_id_cmp(hle->commit_id,
8800 resume_commit_id) != 0)
8801 continue;
8803 resume_commit_id = NULL;
8804 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8805 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8806 error = histedit_skip_commit(hle, worktree,
8807 repo);
8808 if (error)
8809 goto done;
8810 } else {
8811 struct got_pathlist_head paths;
8812 int have_changes = 0;
8814 TAILQ_INIT(&paths);
8815 error = got_pathlist_append(&paths, "", NULL);
8816 if (error)
8817 goto done;
8818 error = got_worktree_status(worktree, &paths,
8819 repo, check_local_changes, &have_changes,
8820 check_cancelled, NULL);
8821 got_pathlist_free(&paths);
8822 if (error) {
8823 if (error->code != GOT_ERR_CANCELLED)
8824 goto done;
8825 if (sigint_received || sigpipe_received)
8826 goto done;
8828 if (have_changes) {
8829 error = histedit_commit(NULL, worktree,
8830 fileindex, tmp_branch, hle, repo);
8831 if (error)
8832 goto done;
8833 } else {
8834 error = got_object_open_as_commit(
8835 &commit, repo, hle->commit_id);
8836 if (error)
8837 goto done;
8838 error = show_histedit_progress(commit,
8839 hle, NULL);
8840 got_object_commit_close(commit);
8841 commit = NULL;
8842 if (error)
8843 goto done;
8846 continue;
8849 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8850 error = histedit_skip_commit(hle, worktree, repo);
8851 if (error)
8852 goto done;
8853 continue;
8856 error = got_object_open_as_commit(&commit, repo,
8857 hle->commit_id);
8858 if (error)
8859 goto done;
8860 parent_ids = got_object_commit_get_parent_ids(commit);
8861 pid = SIMPLEQ_FIRST(parent_ids);
8863 error = got_worktree_histedit_merge_files(&merged_paths,
8864 worktree, fileindex, pid->id, hle->commit_id, repo,
8865 update_progress, &upa, check_cancelled, NULL);
8866 if (error)
8867 goto done;
8868 got_object_commit_close(commit);
8869 commit = NULL;
8871 print_update_progress_stats(&upa);
8872 if (upa.conflicts > 0)
8873 rebase_status = GOT_STATUS_CONFLICT;
8875 if (rebase_status == GOT_STATUS_CONFLICT) {
8876 error = show_rebase_merge_conflict(hle->commit_id,
8877 repo);
8878 if (error)
8879 goto done;
8880 got_worktree_rebase_pathlist_free(&merged_paths);
8881 break;
8884 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8885 char *id_str;
8886 error = got_object_id_str(&id_str, hle->commit_id);
8887 if (error)
8888 goto done;
8889 printf("Stopping histedit for amending commit %s\n",
8890 id_str);
8891 free(id_str);
8892 got_worktree_rebase_pathlist_free(&merged_paths);
8893 error = got_worktree_histedit_postpone(worktree,
8894 fileindex);
8895 goto done;
8898 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8899 error = histedit_skip_commit(hle, worktree, repo);
8900 if (error)
8901 goto done;
8902 continue;
8905 error = histedit_commit(&merged_paths, worktree, fileindex,
8906 tmp_branch, hle, repo);
8907 got_worktree_rebase_pathlist_free(&merged_paths);
8908 if (error)
8909 goto done;
8912 if (rebase_status == GOT_STATUS_CONFLICT) {
8913 error = got_worktree_histedit_postpone(worktree, fileindex);
8914 if (error)
8915 goto done;
8916 error = got_error_msg(GOT_ERR_CONFLICTS,
8917 "conflicts must be resolved before histedit can continue");
8918 } else
8919 error = histedit_complete(worktree, fileindex, tmp_branch,
8920 branch, repo);
8921 done:
8922 got_object_id_queue_free(&commits);
8923 histedit_free_list(&histedit_cmds);
8924 free(head_commit_id);
8925 free(base_commit_id);
8926 free(resume_commit_id);
8927 if (commit)
8928 got_object_commit_close(commit);
8929 if (branch)
8930 got_ref_close(branch);
8931 if (tmp_branch)
8932 got_ref_close(tmp_branch);
8933 if (worktree)
8934 got_worktree_close(worktree);
8935 if (repo)
8936 got_repo_close(repo);
8937 return error;
8940 __dead static void
8941 usage_integrate(void)
8943 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
8944 exit(1);
8947 static const struct got_error *
8948 cmd_integrate(int argc, char *argv[])
8950 const struct got_error *error = NULL;
8951 struct got_repository *repo = NULL;
8952 struct got_worktree *worktree = NULL;
8953 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
8954 const char *branch_arg = NULL;
8955 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
8956 struct got_fileindex *fileindex = NULL;
8957 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
8958 int ch;
8959 struct got_update_progress_arg upa;
8961 while ((ch = getopt(argc, argv, "")) != -1) {
8962 switch (ch) {
8963 default:
8964 usage_integrate();
8965 /* NOTREACHED */
8969 argc -= optind;
8970 argv += optind;
8972 if (argc != 1)
8973 usage_integrate();
8974 branch_arg = argv[0];
8975 #ifndef PROFILE
8976 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8977 "unveil", NULL) == -1)
8978 err(1, "pledge");
8979 #endif
8980 cwd = getcwd(NULL, 0);
8981 if (cwd == NULL) {
8982 error = got_error_from_errno("getcwd");
8983 goto done;
8986 error = got_worktree_open(&worktree, cwd);
8987 if (error) {
8988 if (error->code == GOT_ERR_NOT_WORKTREE)
8989 error = wrap_not_worktree_error(error, "integrate",
8990 cwd);
8991 goto done;
8994 error = check_rebase_or_histedit_in_progress(worktree);
8995 if (error)
8996 goto done;
8998 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8999 NULL);
9000 if (error != NULL)
9001 goto done;
9003 error = apply_unveil(got_repo_get_path(repo), 0,
9004 got_worktree_get_root_path(worktree));
9005 if (error)
9006 goto done;
9008 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
9009 error = got_error_from_errno("asprintf");
9010 goto done;
9013 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
9014 &base_branch_ref, worktree, refname, repo);
9015 if (error)
9016 goto done;
9018 refname = strdup(got_ref_get_name(branch_ref));
9019 if (refname == NULL) {
9020 error = got_error_from_errno("strdup");
9021 got_worktree_integrate_abort(worktree, fileindex, repo,
9022 branch_ref, base_branch_ref);
9023 goto done;
9025 base_refname = strdup(got_ref_get_name(base_branch_ref));
9026 if (base_refname == NULL) {
9027 error = got_error_from_errno("strdup");
9028 got_worktree_integrate_abort(worktree, fileindex, repo,
9029 branch_ref, base_branch_ref);
9030 goto done;
9033 error = got_ref_resolve(&commit_id, repo, branch_ref);
9034 if (error)
9035 goto done;
9037 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
9038 if (error)
9039 goto done;
9041 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
9042 error = got_error_msg(GOT_ERR_SAME_BRANCH,
9043 "specified branch has already been integrated");
9044 got_worktree_integrate_abort(worktree, fileindex, repo,
9045 branch_ref, base_branch_ref);
9046 goto done;
9049 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
9050 if (error) {
9051 if (error->code == GOT_ERR_ANCESTRY)
9052 error = got_error(GOT_ERR_REBASE_REQUIRED);
9053 got_worktree_integrate_abort(worktree, fileindex, repo,
9054 branch_ref, base_branch_ref);
9055 goto done;
9058 memset(&upa, 0, sizeof(upa));
9059 error = got_worktree_integrate_continue(worktree, fileindex, repo,
9060 branch_ref, base_branch_ref, update_progress, &upa,
9061 check_cancelled, NULL);
9062 if (error)
9063 goto done;
9065 printf("Integrated %s into %s\n", refname, base_refname);
9066 print_update_progress_stats(&upa);
9067 done:
9068 if (repo)
9069 got_repo_close(repo);
9070 if (worktree)
9071 got_worktree_close(worktree);
9072 free(cwd);
9073 free(base_commit_id);
9074 free(commit_id);
9075 free(refname);
9076 free(base_refname);
9077 return error;
9080 __dead static void
9081 usage_stage(void)
9083 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
9084 "[-S] [file-path ...]\n",
9085 getprogname());
9086 exit(1);
9089 static const struct got_error *
9090 print_stage(void *arg, unsigned char status, unsigned char staged_status,
9091 const char *path, struct got_object_id *blob_id,
9092 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
9093 int dirfd, const char *de_name)
9095 const struct got_error *err = NULL;
9096 char *id_str = NULL;
9098 if (staged_status != GOT_STATUS_ADD &&
9099 staged_status != GOT_STATUS_MODIFY &&
9100 staged_status != GOT_STATUS_DELETE)
9101 return NULL;
9103 if (staged_status == GOT_STATUS_ADD ||
9104 staged_status == GOT_STATUS_MODIFY)
9105 err = got_object_id_str(&id_str, staged_blob_id);
9106 else
9107 err = got_object_id_str(&id_str, blob_id);
9108 if (err)
9109 return err;
9111 printf("%s %c %s\n", id_str, staged_status, path);
9112 free(id_str);
9113 return NULL;
9116 static const struct got_error *
9117 cmd_stage(int argc, char *argv[])
9119 const struct got_error *error = NULL;
9120 struct got_repository *repo = NULL;
9121 struct got_worktree *worktree = NULL;
9122 char *cwd = NULL;
9123 struct got_pathlist_head paths;
9124 struct got_pathlist_entry *pe;
9125 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
9126 FILE *patch_script_file = NULL;
9127 const char *patch_script_path = NULL;
9128 struct choose_patch_arg cpa;
9130 TAILQ_INIT(&paths);
9132 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
9133 switch (ch) {
9134 case 'l':
9135 list_stage = 1;
9136 break;
9137 case 'p':
9138 pflag = 1;
9139 break;
9140 case 'F':
9141 patch_script_path = optarg;
9142 break;
9143 case 'S':
9144 allow_bad_symlinks = 1;
9145 break;
9146 default:
9147 usage_stage();
9148 /* NOTREACHED */
9152 argc -= optind;
9153 argv += optind;
9155 #ifndef PROFILE
9156 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9157 "unveil", NULL) == -1)
9158 err(1, "pledge");
9159 #endif
9160 if (list_stage && (pflag || patch_script_path))
9161 errx(1, "-l option cannot be used with other options");
9162 if (patch_script_path && !pflag)
9163 errx(1, "-F option can only be used together with -p option");
9165 cwd = getcwd(NULL, 0);
9166 if (cwd == NULL) {
9167 error = got_error_from_errno("getcwd");
9168 goto done;
9171 error = got_worktree_open(&worktree, cwd);
9172 if (error) {
9173 if (error->code == GOT_ERR_NOT_WORKTREE)
9174 error = wrap_not_worktree_error(error, "stage", cwd);
9175 goto done;
9178 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9179 NULL);
9180 if (error != NULL)
9181 goto done;
9183 if (patch_script_path) {
9184 patch_script_file = fopen(patch_script_path, "r");
9185 if (patch_script_file == NULL) {
9186 error = got_error_from_errno2("fopen",
9187 patch_script_path);
9188 goto done;
9191 error = apply_unveil(got_repo_get_path(repo), 0,
9192 got_worktree_get_root_path(worktree));
9193 if (error)
9194 goto done;
9196 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9197 if (error)
9198 goto done;
9200 if (list_stage)
9201 error = got_worktree_status(worktree, &paths, repo,
9202 print_stage, NULL, check_cancelled, NULL);
9203 else {
9204 cpa.patch_script_file = patch_script_file;
9205 cpa.action = "stage";
9206 error = got_worktree_stage(worktree, &paths,
9207 pflag ? NULL : print_status, NULL,
9208 pflag ? choose_patch : NULL, &cpa,
9209 allow_bad_symlinks, repo);
9211 done:
9212 if (patch_script_file && fclose(patch_script_file) == EOF &&
9213 error == NULL)
9214 error = got_error_from_errno2("fclose", patch_script_path);
9215 if (repo)
9216 got_repo_close(repo);
9217 if (worktree)
9218 got_worktree_close(worktree);
9219 TAILQ_FOREACH(pe, &paths, entry)
9220 free((char *)pe->path);
9221 got_pathlist_free(&paths);
9222 free(cwd);
9223 return error;
9226 __dead static void
9227 usage_unstage(void)
9229 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
9230 "[file-path ...]\n",
9231 getprogname());
9232 exit(1);
9236 static const struct got_error *
9237 cmd_unstage(int argc, char *argv[])
9239 const struct got_error *error = NULL;
9240 struct got_repository *repo = NULL;
9241 struct got_worktree *worktree = NULL;
9242 char *cwd = NULL;
9243 struct got_pathlist_head paths;
9244 struct got_pathlist_entry *pe;
9245 int ch, pflag = 0;
9246 struct got_update_progress_arg upa;
9247 FILE *patch_script_file = NULL;
9248 const char *patch_script_path = NULL;
9249 struct choose_patch_arg cpa;
9251 TAILQ_INIT(&paths);
9253 while ((ch = getopt(argc, argv, "pF:")) != -1) {
9254 switch (ch) {
9255 case 'p':
9256 pflag = 1;
9257 break;
9258 case 'F':
9259 patch_script_path = optarg;
9260 break;
9261 default:
9262 usage_unstage();
9263 /* NOTREACHED */
9267 argc -= optind;
9268 argv += optind;
9270 #ifndef PROFILE
9271 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9272 "unveil", NULL) == -1)
9273 err(1, "pledge");
9274 #endif
9275 if (patch_script_path && !pflag)
9276 errx(1, "-F option can only be used together with -p option");
9278 cwd = getcwd(NULL, 0);
9279 if (cwd == NULL) {
9280 error = got_error_from_errno("getcwd");
9281 goto done;
9284 error = got_worktree_open(&worktree, cwd);
9285 if (error) {
9286 if (error->code == GOT_ERR_NOT_WORKTREE)
9287 error = wrap_not_worktree_error(error, "unstage", cwd);
9288 goto done;
9291 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9292 NULL);
9293 if (error != NULL)
9294 goto done;
9296 if (patch_script_path) {
9297 patch_script_file = fopen(patch_script_path, "r");
9298 if (patch_script_file == NULL) {
9299 error = got_error_from_errno2("fopen",
9300 patch_script_path);
9301 goto done;
9305 error = apply_unveil(got_repo_get_path(repo), 0,
9306 got_worktree_get_root_path(worktree));
9307 if (error)
9308 goto done;
9310 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9311 if (error)
9312 goto done;
9314 cpa.patch_script_file = patch_script_file;
9315 cpa.action = "unstage";
9316 memset(&upa, 0, sizeof(upa));
9317 error = got_worktree_unstage(worktree, &paths, update_progress,
9318 &upa, pflag ? choose_patch : NULL, &cpa, repo);
9319 if (!error)
9320 print_update_progress_stats(&upa);
9321 done:
9322 if (patch_script_file && fclose(patch_script_file) == EOF &&
9323 error == NULL)
9324 error = got_error_from_errno2("fclose", patch_script_path);
9325 if (repo)
9326 got_repo_close(repo);
9327 if (worktree)
9328 got_worktree_close(worktree);
9329 TAILQ_FOREACH(pe, &paths, entry)
9330 free((char *)pe->path);
9331 got_pathlist_free(&paths);
9332 free(cwd);
9333 return error;
9336 __dead static void
9337 usage_cat(void)
9339 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
9340 "arg1 [arg2 ...]\n", getprogname());
9341 exit(1);
9344 static const struct got_error *
9345 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9347 const struct got_error *err;
9348 struct got_blob_object *blob;
9350 err = got_object_open_as_blob(&blob, repo, id, 8192);
9351 if (err)
9352 return err;
9354 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
9355 got_object_blob_close(blob);
9356 return err;
9359 static const struct got_error *
9360 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9362 const struct got_error *err;
9363 struct got_tree_object *tree;
9364 int nentries, i;
9366 err = got_object_open_as_tree(&tree, repo, id);
9367 if (err)
9368 return err;
9370 nentries = got_object_tree_get_nentries(tree);
9371 for (i = 0; i < nentries; i++) {
9372 struct got_tree_entry *te;
9373 char *id_str;
9374 if (sigint_received || sigpipe_received)
9375 break;
9376 te = got_object_tree_get_entry(tree, i);
9377 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
9378 if (err)
9379 break;
9380 fprintf(outfile, "%s %.7o %s\n", id_str,
9381 got_tree_entry_get_mode(te),
9382 got_tree_entry_get_name(te));
9383 free(id_str);
9386 got_object_tree_close(tree);
9387 return err;
9390 static const struct got_error *
9391 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9393 const struct got_error *err;
9394 struct got_commit_object *commit;
9395 const struct got_object_id_queue *parent_ids;
9396 struct got_object_qid *pid;
9397 char *id_str = NULL;
9398 const char *logmsg = NULL;
9400 err = got_object_open_as_commit(&commit, repo, id);
9401 if (err)
9402 return err;
9404 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
9405 if (err)
9406 goto done;
9408 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
9409 parent_ids = got_object_commit_get_parent_ids(commit);
9410 fprintf(outfile, "numparents %d\n",
9411 got_object_commit_get_nparents(commit));
9412 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
9413 char *pid_str;
9414 err = got_object_id_str(&pid_str, pid->id);
9415 if (err)
9416 goto done;
9417 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
9418 free(pid_str);
9420 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
9421 got_object_commit_get_author(commit),
9422 got_object_commit_get_author_time(commit));
9424 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
9425 got_object_commit_get_author(commit),
9426 got_object_commit_get_committer_time(commit));
9428 logmsg = got_object_commit_get_logmsg_raw(commit);
9429 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
9430 fprintf(outfile, "%s", logmsg);
9431 done:
9432 free(id_str);
9433 got_object_commit_close(commit);
9434 return err;
9437 static const struct got_error *
9438 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9440 const struct got_error *err;
9441 struct got_tag_object *tag;
9442 char *id_str = NULL;
9443 const char *tagmsg = NULL;
9445 err = got_object_open_as_tag(&tag, repo, id);
9446 if (err)
9447 return err;
9449 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
9450 if (err)
9451 goto done;
9453 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
9455 switch (got_object_tag_get_object_type(tag)) {
9456 case GOT_OBJ_TYPE_BLOB:
9457 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9458 GOT_OBJ_LABEL_BLOB);
9459 break;
9460 case GOT_OBJ_TYPE_TREE:
9461 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9462 GOT_OBJ_LABEL_TREE);
9463 break;
9464 case GOT_OBJ_TYPE_COMMIT:
9465 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9466 GOT_OBJ_LABEL_COMMIT);
9467 break;
9468 case GOT_OBJ_TYPE_TAG:
9469 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9470 GOT_OBJ_LABEL_TAG);
9471 break;
9472 default:
9473 break;
9476 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
9477 got_object_tag_get_name(tag));
9479 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
9480 got_object_tag_get_tagger(tag),
9481 got_object_tag_get_tagger_time(tag));
9483 tagmsg = got_object_tag_get_message(tag);
9484 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
9485 fprintf(outfile, "%s", tagmsg);
9486 done:
9487 free(id_str);
9488 got_object_tag_close(tag);
9489 return err;
9492 static const struct got_error *
9493 cmd_cat(int argc, char *argv[])
9495 const struct got_error *error;
9496 struct got_repository *repo = NULL;
9497 struct got_worktree *worktree = NULL;
9498 char *cwd = NULL, *repo_path = NULL, *label = NULL;
9499 const char *commit_id_str = NULL;
9500 struct got_object_id *id = NULL, *commit_id = NULL;
9501 int ch, obj_type, i, force_path = 0;
9503 #ifndef PROFILE
9504 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9505 NULL) == -1)
9506 err(1, "pledge");
9507 #endif
9509 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
9510 switch (ch) {
9511 case 'c':
9512 commit_id_str = optarg;
9513 break;
9514 case 'r':
9515 repo_path = realpath(optarg, NULL);
9516 if (repo_path == NULL)
9517 return got_error_from_errno2("realpath",
9518 optarg);
9519 got_path_strip_trailing_slashes(repo_path);
9520 break;
9521 case 'P':
9522 force_path = 1;
9523 break;
9524 default:
9525 usage_cat();
9526 /* NOTREACHED */
9530 argc -= optind;
9531 argv += optind;
9533 cwd = getcwd(NULL, 0);
9534 if (cwd == NULL) {
9535 error = got_error_from_errno("getcwd");
9536 goto done;
9538 error = got_worktree_open(&worktree, cwd);
9539 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9540 goto done;
9541 if (worktree) {
9542 if (repo_path == NULL) {
9543 repo_path = strdup(
9544 got_worktree_get_repo_path(worktree));
9545 if (repo_path == NULL) {
9546 error = got_error_from_errno("strdup");
9547 goto done;
9552 if (repo_path == NULL) {
9553 repo_path = getcwd(NULL, 0);
9554 if (repo_path == NULL)
9555 return got_error_from_errno("getcwd");
9558 error = got_repo_open(&repo, repo_path, NULL);
9559 free(repo_path);
9560 if (error != NULL)
9561 goto done;
9563 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9564 if (error)
9565 goto done;
9567 if (commit_id_str == NULL)
9568 commit_id_str = GOT_REF_HEAD;
9569 error = got_repo_match_object_id(&commit_id, NULL,
9570 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
9571 if (error)
9572 goto done;
9574 for (i = 0; i < argc; i++) {
9575 if (force_path) {
9576 error = got_object_id_by_path(&id, repo, commit_id,
9577 argv[i]);
9578 if (error)
9579 break;
9580 } else {
9581 error = got_repo_match_object_id(&id, &label, argv[i],
9582 GOT_OBJ_TYPE_ANY, 0, repo);
9583 if (error) {
9584 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9585 error->code != GOT_ERR_NOT_REF)
9586 break;
9587 error = got_object_id_by_path(&id, repo,
9588 commit_id, argv[i]);
9589 if (error)
9590 break;
9594 error = got_object_get_type(&obj_type, repo, id);
9595 if (error)
9596 break;
9598 switch (obj_type) {
9599 case GOT_OBJ_TYPE_BLOB:
9600 error = cat_blob(id, repo, stdout);
9601 break;
9602 case GOT_OBJ_TYPE_TREE:
9603 error = cat_tree(id, repo, stdout);
9604 break;
9605 case GOT_OBJ_TYPE_COMMIT:
9606 error = cat_commit(id, repo, stdout);
9607 break;
9608 case GOT_OBJ_TYPE_TAG:
9609 error = cat_tag(id, repo, stdout);
9610 break;
9611 default:
9612 error = got_error(GOT_ERR_OBJ_TYPE);
9613 break;
9615 if (error)
9616 break;
9617 free(label);
9618 label = NULL;
9619 free(id);
9620 id = NULL;
9622 done:
9623 free(label);
9624 free(id);
9625 free(commit_id);
9626 if (worktree)
9627 got_worktree_close(worktree);
9628 if (repo) {
9629 const struct got_error *repo_error;
9630 repo_error = got_repo_close(repo);
9631 if (error == NULL)
9632 error = repo_error;
9634 return error;
9637 __dead static void
9638 usage_info(void)
9640 fprintf(stderr, "usage: %s info [path ...]\n",
9641 getprogname());
9642 exit(1);
9645 static const struct got_error *
9646 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
9647 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9648 struct got_object_id *commit_id)
9650 const struct got_error *err = NULL;
9651 char *id_str = NULL;
9652 char datebuf[128];
9653 struct tm mytm, *tm;
9654 struct got_pathlist_head *paths = arg;
9655 struct got_pathlist_entry *pe;
9658 * Clear error indication from any of the path arguments which
9659 * would cause this file index entry to be displayed.
9661 TAILQ_FOREACH(pe, paths, entry) {
9662 if (got_path_cmp(path, pe->path, strlen(path),
9663 pe->path_len) == 0 ||
9664 got_path_is_child(path, pe->path, pe->path_len))
9665 pe->data = NULL; /* no error */
9668 printf(GOT_COMMIT_SEP_STR);
9669 if (S_ISLNK(mode))
9670 printf("symlink: %s\n", path);
9671 else if (S_ISREG(mode)) {
9672 printf("file: %s\n", path);
9673 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
9674 } else if (S_ISDIR(mode))
9675 printf("directory: %s\n", path);
9676 else
9677 printf("something: %s\n", path);
9679 tm = localtime_r(&mtime, &mytm);
9680 if (tm == NULL)
9681 return NULL;
9682 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) >= sizeof(datebuf))
9683 return got_error(GOT_ERR_NO_SPACE);
9684 printf("timestamp: %s\n", datebuf);
9686 if (blob_id) {
9687 err = got_object_id_str(&id_str, blob_id);
9688 if (err)
9689 return err;
9690 printf("based on blob: %s\n", id_str);
9691 free(id_str);
9694 if (staged_blob_id) {
9695 err = got_object_id_str(&id_str, staged_blob_id);
9696 if (err)
9697 return err;
9698 printf("based on staged blob: %s\n", id_str);
9699 free(id_str);
9702 if (commit_id) {
9703 err = got_object_id_str(&id_str, commit_id);
9704 if (err)
9705 return err;
9706 printf("based on commit: %s\n", id_str);
9707 free(id_str);
9710 return NULL;
9713 static const struct got_error *
9714 cmd_info(int argc, char *argv[])
9716 const struct got_error *error = NULL;
9717 struct got_worktree *worktree = NULL;
9718 char *cwd = NULL, *id_str = NULL;
9719 struct got_pathlist_head paths;
9720 struct got_pathlist_entry *pe;
9721 char *uuidstr = NULL;
9722 int ch, show_files = 0;
9724 TAILQ_INIT(&paths);
9726 while ((ch = getopt(argc, argv, "")) != -1) {
9727 switch (ch) {
9728 default:
9729 usage_info();
9730 /* NOTREACHED */
9734 argc -= optind;
9735 argv += optind;
9737 #ifndef PROFILE
9738 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
9739 NULL) == -1)
9740 err(1, "pledge");
9741 #endif
9742 cwd = getcwd(NULL, 0);
9743 if (cwd == NULL) {
9744 error = got_error_from_errno("getcwd");
9745 goto done;
9748 error = got_worktree_open(&worktree, cwd);
9749 if (error) {
9750 if (error->code == GOT_ERR_NOT_WORKTREE)
9751 error = wrap_not_worktree_error(error, "status", cwd);
9752 goto done;
9755 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9756 if (error)
9757 goto done;
9759 if (argc >= 1) {
9760 error = get_worktree_paths_from_argv(&paths, argc, argv,
9761 worktree);
9762 if (error)
9763 goto done;
9764 show_files = 1;
9767 error = got_object_id_str(&id_str,
9768 got_worktree_get_base_commit_id(worktree));
9769 if (error)
9770 goto done;
9772 error = got_worktree_get_uuid(&uuidstr, worktree);
9773 if (error)
9774 goto done;
9776 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9777 printf("work tree base commit: %s\n", id_str);
9778 printf("work tree path prefix: %s\n",
9779 got_worktree_get_path_prefix(worktree));
9780 printf("work tree branch reference: %s\n",
9781 got_worktree_get_head_ref_name(worktree));
9782 printf("work tree UUID: %s\n", uuidstr);
9783 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
9785 if (show_files) {
9786 struct got_pathlist_entry *pe;
9787 TAILQ_FOREACH(pe, &paths, entry) {
9788 if (pe->path_len == 0)
9789 continue;
9791 * Assume this path will fail. This will be corrected
9792 * in print_path_info() in case the path does suceeed.
9794 pe->data = (void *)got_error_path(pe->path,
9795 GOT_ERR_BAD_PATH);
9797 error = got_worktree_path_info(worktree, &paths,
9798 print_path_info, &paths, check_cancelled, NULL);
9799 if (error)
9800 goto done;
9801 TAILQ_FOREACH(pe, &paths, entry) {
9802 if (pe->data != NULL) {
9803 error = pe->data; /* bad path */
9804 break;
9808 done:
9809 TAILQ_FOREACH(pe, &paths, entry)
9810 free((char *)pe->path);
9811 got_pathlist_free(&paths);
9812 free(cwd);
9813 free(id_str);
9814 free(uuidstr);
9815 return error;