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"
58 #ifndef nitems
59 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
60 #endif
62 static volatile sig_atomic_t sigint_received;
63 static volatile sig_atomic_t sigpipe_received;
65 static void
66 catch_sigint(int signo)
67 {
68 sigint_received = 1;
69 }
71 static void
72 catch_sigpipe(int signo)
73 {
74 sigpipe_received = 1;
75 }
78 struct got_cmd {
79 const char *cmd_name;
80 const struct got_error *(*cmd_main)(int, char *[]);
81 void (*cmd_usage)(void);
82 const char *cmd_alias;
83 };
85 __dead static void usage(int);
86 __dead static void usage_init(void);
87 __dead static void usage_import(void);
88 __dead static void usage_clone(void);
89 __dead static void usage_fetch(void);
90 __dead static void usage_checkout(void);
91 __dead static void usage_update(void);
92 __dead static void usage_log(void);
93 __dead static void usage_diff(void);
94 __dead static void usage_blame(void);
95 __dead static void usage_tree(void);
96 __dead static void usage_status(void);
97 __dead static void usage_ref(void);
98 __dead static void usage_branch(void);
99 __dead static void usage_tag(void);
100 __dead static void usage_add(void);
101 __dead static void usage_remove(void);
102 __dead static void usage_revert(void);
103 __dead static void usage_commit(void);
104 __dead static void usage_cherrypick(void);
105 __dead static void usage_backout(void);
106 __dead static void usage_rebase(void);
107 __dead static void usage_histedit(void);
108 __dead static void usage_integrate(void);
109 __dead static void usage_stage(void);
110 __dead static void usage_unstage(void);
111 __dead static void usage_cat(void);
113 static const struct got_error* cmd_init(int, char *[]);
114 static const struct got_error* cmd_import(int, char *[]);
115 static const struct got_error* cmd_clone(int, char *[]);
116 static const struct got_error* cmd_fetch(int, char *[]);
117 static const struct got_error* cmd_checkout(int, char *[]);
118 static const struct got_error* cmd_update(int, char *[]);
119 static const struct got_error* cmd_log(int, char *[]);
120 static const struct got_error* cmd_diff(int, char *[]);
121 static const struct got_error* cmd_blame(int, char *[]);
122 static const struct got_error* cmd_tree(int, char *[]);
123 static const struct got_error* cmd_status(int, char *[]);
124 static const struct got_error* cmd_ref(int, char *[]);
125 static const struct got_error* cmd_branch(int, char *[]);
126 static const struct got_error* cmd_tag(int, char *[]);
127 static const struct got_error* cmd_add(int, char *[]);
128 static const struct got_error* cmd_remove(int, char *[]);
129 static const struct got_error* cmd_revert(int, char *[]);
130 static const struct got_error* cmd_commit(int, char *[]);
131 static const struct got_error* cmd_cherrypick(int, char *[]);
132 static const struct got_error* cmd_backout(int, char *[]);
133 static const struct got_error* cmd_rebase(int, char *[]);
134 static const struct got_error* cmd_histedit(int, char *[]);
135 static const struct got_error* cmd_integrate(int, char *[]);
136 static const struct got_error* cmd_stage(int, char *[]);
137 static const struct got_error* cmd_unstage(int, char *[]);
138 static const struct got_error* cmd_cat(int, char *[]);
140 static struct got_cmd got_commands[] = {
141 { "init", cmd_init, usage_init, "in" },
142 { "import", cmd_import, usage_import, "im" },
143 { "clone", cmd_clone, usage_clone, "cl" },
144 { "fetch", cmd_fetch, usage_fetch, "fe" },
145 { "checkout", cmd_checkout, usage_checkout, "co" },
146 { "update", cmd_update, usage_update, "up" },
147 { "log", cmd_log, usage_log, "" },
148 { "diff", cmd_diff, usage_diff, "di" },
149 { "blame", cmd_blame, usage_blame, "bl" },
150 { "tree", cmd_tree, usage_tree, "tr" },
151 { "status", cmd_status, usage_status, "st" },
152 { "ref", cmd_ref, usage_ref, "" },
153 { "branch", cmd_branch, usage_branch, "br" },
154 { "tag", cmd_tag, usage_tag, "" },
155 { "add", cmd_add, usage_add, "" },
156 { "remove", cmd_remove, usage_remove, "rm" },
157 { "revert", cmd_revert, usage_revert, "rv" },
158 { "commit", cmd_commit, usage_commit, "ci" },
159 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
160 { "backout", cmd_backout, usage_backout, "bo" },
161 { "rebase", cmd_rebase, usage_rebase, "rb" },
162 { "histedit", cmd_histedit, usage_histedit, "he" },
163 { "integrate", cmd_integrate, usage_integrate,"ig" },
164 { "stage", cmd_stage, usage_stage, "sg" },
165 { "unstage", cmd_unstage, usage_unstage, "ug" },
166 { "cat", cmd_cat, usage_cat, "" },
167 };
169 static void
170 list_commands(void)
172 int i;
174 fprintf(stderr, "commands:");
175 for (i = 0; i < nitems(got_commands); i++) {
176 struct got_cmd *cmd = &got_commands[i];
177 fprintf(stderr, " %s", cmd->cmd_name);
179 fputc('\n', stderr);
182 int
183 main(int argc, char *argv[])
185 struct got_cmd *cmd;
186 unsigned int i;
187 int ch;
188 int hflag = 0, Vflag = 0;
189 static struct option longopts[] = {
190 { "version", no_argument, NULL, 'V' },
191 { NULL, 0, NULL, 0}
192 };
194 setlocale(LC_CTYPE, "");
196 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
197 switch (ch) {
198 case 'h':
199 hflag = 1;
200 break;
201 case 'V':
202 Vflag = 1;
203 break;
204 default:
205 usage(hflag);
206 /* NOTREACHED */
210 argc -= optind;
211 argv += optind;
212 optind = 0;
214 if (Vflag) {
215 got_version_print_str();
216 return 1;
219 if (argc <= 0)
220 usage(hflag);
222 signal(SIGINT, catch_sigint);
223 signal(SIGPIPE, catch_sigpipe);
225 for (i = 0; i < nitems(got_commands); i++) {
226 const struct got_error *error;
228 cmd = &got_commands[i];
230 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
231 strcmp(cmd->cmd_alias, argv[0]) != 0)
232 continue;
234 if (hflag)
235 got_commands[i].cmd_usage();
237 error = got_commands[i].cmd_main(argc, argv);
238 if (error && error->code != GOT_ERR_CANCELLED &&
239 error->code != GOT_ERR_PRIVSEP_EXIT &&
240 !(sigpipe_received &&
241 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
242 !(sigint_received &&
243 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
244 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
245 return 1;
248 return 0;
251 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
252 list_commands();
253 return 1;
256 __dead static void
257 usage(int hflag)
259 fprintf(stderr, "usage: %s [-h] [-V | --version] command [arg ...]\n",
260 getprogname());
261 if (hflag)
262 list_commands();
263 exit(1);
266 static const struct got_error *
267 get_editor(char **abspath)
269 const struct got_error *err = NULL;
270 const char *editor;
272 *abspath = NULL;
274 editor = getenv("VISUAL");
275 if (editor == NULL)
276 editor = getenv("EDITOR");
278 if (editor) {
279 err = got_path_find_prog(abspath, editor);
280 if (err)
281 return err;
284 if (*abspath == NULL) {
285 *abspath = strdup("/bin/ed");
286 if (*abspath == NULL)
287 return got_error_from_errno("strdup");
290 return NULL;
293 static const struct got_error *
294 apply_unveil(const char *repo_path, int repo_read_only,
295 const char *worktree_path)
297 const struct got_error *err;
299 #ifdef PROFILE
300 if (unveil("gmon.out", "rwc") != 0)
301 return got_error_from_errno2("unveil", "gmon.out");
302 #endif
303 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
304 return got_error_from_errno2("unveil", repo_path);
306 if (worktree_path && unveil(worktree_path, "rwc") != 0)
307 return got_error_from_errno2("unveil", worktree_path);
309 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
310 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
312 err = got_privsep_unveil_exec_helpers();
313 if (err != NULL)
314 return err;
316 if (unveil(NULL, NULL) != 0)
317 return got_error_from_errno("unveil");
319 return NULL;
322 __dead static void
323 usage_init(void)
325 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
326 exit(1);
329 static const struct got_error *
330 cmd_init(int argc, char *argv[])
332 const struct got_error *error = NULL;
333 char *repo_path = NULL;
334 int ch;
336 while ((ch = getopt(argc, argv, "")) != -1) {
337 switch (ch) {
338 default:
339 usage_init();
340 /* NOTREACHED */
344 argc -= optind;
345 argv += optind;
347 #ifndef PROFILE
348 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
349 err(1, "pledge");
350 #endif
351 if (argc != 1)
352 usage_init();
354 repo_path = strdup(argv[0]);
355 if (repo_path == NULL)
356 return got_error_from_errno("strdup");
358 got_path_strip_trailing_slashes(repo_path);
360 error = got_path_mkdir(repo_path);
361 if (error &&
362 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
363 goto done;
365 error = apply_unveil(repo_path, 0, NULL);
366 if (error)
367 goto done;
369 error = got_repo_init(repo_path);
370 done:
371 free(repo_path);
372 return error;
375 __dead static void
376 usage_import(void)
378 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
379 "[-r repository-path] [-I pattern] path\n", getprogname());
380 exit(1);
383 int
384 spawn_editor(const char *editor, const char *file)
386 pid_t pid;
387 sig_t sighup, sigint, sigquit;
388 int st = -1;
390 sighup = signal(SIGHUP, SIG_IGN);
391 sigint = signal(SIGINT, SIG_IGN);
392 sigquit = signal(SIGQUIT, SIG_IGN);
394 switch (pid = fork()) {
395 case -1:
396 goto doneediting;
397 case 0:
398 execl(editor, editor, file, (char *)NULL);
399 _exit(127);
402 while (waitpid(pid, &st, 0) == -1)
403 if (errno != EINTR)
404 break;
406 doneediting:
407 (void)signal(SIGHUP, sighup);
408 (void)signal(SIGINT, sigint);
409 (void)signal(SIGQUIT, sigquit);
411 if (!WIFEXITED(st)) {
412 errno = EINTR;
413 return -1;
416 return WEXITSTATUS(st);
419 static const struct got_error *
420 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
421 const char *initial_content)
423 const struct got_error *err = NULL;
424 char buf[1024];
425 struct stat st, st2;
426 FILE *fp;
427 int content_changed = 0;
428 size_t len;
430 *logmsg = NULL;
432 if (stat(logmsg_path, &st) == -1)
433 return got_error_from_errno2("stat", logmsg_path);
435 if (spawn_editor(editor, logmsg_path) == -1)
436 return got_error_from_errno("failed spawning editor");
438 if (stat(logmsg_path, &st2) == -1)
439 return got_error_from_errno("stat");
441 if (st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
442 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
443 "no changes made to commit message, aborting");
445 *logmsg = malloc(st2.st_size + 1);
446 if (*logmsg == NULL)
447 return got_error_from_errno("malloc");
448 (*logmsg)[0] = '\0';
449 len = 0;
451 fp = fopen(logmsg_path, "r");
452 if (fp == NULL) {
453 err = got_error_from_errno("fopen");
454 goto done;
456 while (fgets(buf, sizeof(buf), fp) != NULL) {
457 if (!content_changed && strcmp(buf, initial_content) != 0)
458 content_changed = 1;
459 if (buf[0] == '#' || (len == 0 && buf[0] == '\n'))
460 continue; /* remove comments and leading empty lines */
461 len = strlcat(*logmsg, buf, st2.st_size);
463 fclose(fp);
465 while (len > 0 && (*logmsg)[len - 1] == '\n') {
466 (*logmsg)[len - 1] = '\0';
467 len--;
470 if (len == 0 || !content_changed)
471 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
472 "commit message cannot be empty, aborting");
473 done:
474 if (err) {
475 free(*logmsg);
476 *logmsg = NULL;
478 return err;
481 static const struct got_error *
482 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
483 const char *path_dir, const char *branch_name)
485 char *initial_content = NULL;
486 const struct got_error *err = NULL;
487 int fd;
489 if (asprintf(&initial_content,
490 "\n# %s to be imported to branch %s\n", path_dir,
491 branch_name) == -1)
492 return got_error_from_errno("asprintf");
494 err = got_opentemp_named_fd(logmsg_path, &fd,
495 GOT_TMPDIR_STR "/got-importmsg");
496 if (err)
497 goto done;
499 dprintf(fd, initial_content);
500 close(fd);
502 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content);
503 done:
504 free(initial_content);
505 return err;
508 static const struct got_error *
509 import_progress(void *arg, const char *path)
511 printf("A %s\n", path);
512 return NULL;
515 static const struct got_error *
516 get_author(char **author, struct got_repository *repo)
518 const struct got_error *err = NULL;
519 const char *got_author, *name, *email;
521 *author = NULL;
523 name = got_repo_get_gitconfig_author_name(repo);
524 email = got_repo_get_gitconfig_author_email(repo);
525 if (name && email) {
526 if (asprintf(author, "%s <%s>", name, email) == -1)
527 return got_error_from_errno("asprintf");
528 return NULL;
531 got_author = getenv("GOT_AUTHOR");
532 if (got_author == NULL) {
533 name = got_repo_get_global_gitconfig_author_name(repo);
534 email = got_repo_get_global_gitconfig_author_email(repo);
535 if (name && email) {
536 if (asprintf(author, "%s <%s>", name, email) == -1)
537 return got_error_from_errno("asprintf");
538 return NULL;
540 /* TODO: Look up user in password database? */
541 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
544 *author = strdup(got_author);
545 if (*author == NULL)
546 return got_error_from_errno("strdup");
548 /*
549 * Really dumb email address check; we're only doing this to
550 * avoid git's object parser breaking on commits we create.
551 */
552 while (*got_author && *got_author != '<')
553 got_author++;
554 if (*got_author != '<') {
555 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
556 goto done;
558 while (*got_author && *got_author != '@')
559 got_author++;
560 if (*got_author != '@') {
561 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
562 goto done;
564 while (*got_author && *got_author != '>')
565 got_author++;
566 if (*got_author != '>')
567 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
568 done:
569 if (err) {
570 free(*author);
571 *author = NULL;
573 return err;
576 static const struct got_error *
577 get_gitconfig_path(char **gitconfig_path)
579 const char *homedir = getenv("HOME");
581 *gitconfig_path = NULL;
582 if (homedir) {
583 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
584 return got_error_from_errno("asprintf");
587 return NULL;
590 static const struct got_error *
591 cmd_import(int argc, char *argv[])
593 const struct got_error *error = NULL;
594 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
595 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
596 const char *branch_name = "main";
597 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
598 struct got_repository *repo = NULL;
599 struct got_reference *branch_ref = NULL, *head_ref = NULL;
600 struct got_object_id *new_commit_id = NULL;
601 int ch;
602 struct got_pathlist_head ignores;
603 struct got_pathlist_entry *pe;
604 int preserve_logmsg = 0;
606 TAILQ_INIT(&ignores);
608 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
609 switch (ch) {
610 case 'b':
611 branch_name = optarg;
612 break;
613 case 'm':
614 logmsg = strdup(optarg);
615 if (logmsg == NULL) {
616 error = got_error_from_errno("strdup");
617 goto done;
619 break;
620 case 'r':
621 repo_path = realpath(optarg, NULL);
622 if (repo_path == NULL) {
623 error = got_error_from_errno2("realpath",
624 optarg);
625 goto done;
627 break;
628 case 'I':
629 if (optarg[0] == '\0')
630 break;
631 error = got_pathlist_insert(&pe, &ignores, optarg,
632 NULL);
633 if (error)
634 goto done;
635 break;
636 default:
637 usage_import();
638 /* NOTREACHED */
642 argc -= optind;
643 argv += optind;
645 #ifndef PROFILE
646 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
647 "unveil",
648 NULL) == -1)
649 err(1, "pledge");
650 #endif
651 if (argc != 1)
652 usage_import();
654 if (repo_path == NULL) {
655 repo_path = getcwd(NULL, 0);
656 if (repo_path == NULL)
657 return got_error_from_errno("getcwd");
659 got_path_strip_trailing_slashes(repo_path);
660 error = get_gitconfig_path(&gitconfig_path);
661 if (error)
662 goto done;
663 error = got_repo_open(&repo, repo_path, gitconfig_path);
664 if (error)
665 goto done;
667 error = get_author(&author, repo);
668 if (error)
669 return error;
671 /*
672 * Don't let the user create a branch name with a leading '-'.
673 * While technically a valid reference name, this case is usually
674 * an unintended typo.
675 */
676 if (branch_name[0] == '-')
677 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
679 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
680 error = got_error_from_errno("asprintf");
681 goto done;
684 error = got_ref_open(&branch_ref, repo, refname, 0);
685 if (error) {
686 if (error->code != GOT_ERR_NOT_REF)
687 goto done;
688 } else {
689 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
690 "import target branch already exists");
691 goto done;
694 path_dir = realpath(argv[0], NULL);
695 if (path_dir == NULL) {
696 error = got_error_from_errno2("realpath", argv[0]);
697 goto done;
699 got_path_strip_trailing_slashes(path_dir);
701 /*
702 * unveil(2) traverses exec(2); if an editor is used we have
703 * to apply unveil after the log message has been written.
704 */
705 if (logmsg == NULL || strlen(logmsg) == 0) {
706 error = get_editor(&editor);
707 if (error)
708 goto done;
709 free(logmsg);
710 error = collect_import_msg(&logmsg, &logmsg_path, editor,
711 path_dir, refname);
712 if (error) {
713 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
714 logmsg_path != NULL)
715 preserve_logmsg = 1;
716 goto done;
720 if (unveil(path_dir, "r") != 0) {
721 error = got_error_from_errno2("unveil", path_dir);
722 if (logmsg_path)
723 preserve_logmsg = 1;
724 goto done;
727 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
728 if (error) {
729 if (logmsg_path)
730 preserve_logmsg = 1;
731 goto done;
734 error = got_repo_import(&new_commit_id, path_dir, logmsg,
735 author, &ignores, repo, import_progress, NULL);
736 if (error) {
737 if (logmsg_path)
738 preserve_logmsg = 1;
739 goto done;
742 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
743 if (error) {
744 if (logmsg_path)
745 preserve_logmsg = 1;
746 goto done;
749 error = got_ref_write(branch_ref, repo);
750 if (error) {
751 if (logmsg_path)
752 preserve_logmsg = 1;
753 goto done;
756 error = got_object_id_str(&id_str, new_commit_id);
757 if (error) {
758 if (logmsg_path)
759 preserve_logmsg = 1;
760 goto done;
763 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
764 if (error) {
765 if (error->code != GOT_ERR_NOT_REF) {
766 if (logmsg_path)
767 preserve_logmsg = 1;
768 goto done;
771 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
772 branch_ref);
773 if (error) {
774 if (logmsg_path)
775 preserve_logmsg = 1;
776 goto done;
779 error = got_ref_write(head_ref, repo);
780 if (error) {
781 if (logmsg_path)
782 preserve_logmsg = 1;
783 goto done;
787 printf("Created branch %s with commit %s\n",
788 got_ref_get_name(branch_ref), id_str);
789 done:
790 if (preserve_logmsg) {
791 fprintf(stderr, "%s: log message preserved in %s\n",
792 getprogname(), logmsg_path);
793 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
794 error = got_error_from_errno2("unlink", logmsg_path);
795 free(logmsg);
796 free(logmsg_path);
797 free(repo_path);
798 free(editor);
799 free(refname);
800 free(new_commit_id);
801 free(id_str);
802 free(author);
803 free(gitconfig_path);
804 if (branch_ref)
805 got_ref_close(branch_ref);
806 if (head_ref)
807 got_ref_close(head_ref);
808 return error;
811 __dead static void
812 usage_clone(void)
814 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
815 "[-R reference] repository-url [directory]\n", getprogname());
816 exit(1);
819 struct got_fetch_progress_arg {
820 char last_scaled_size[FMT_SCALED_STRSIZE];
821 int last_p_indexed;
822 int last_p_resolved;
823 int verbosity;
824 };
826 static const struct got_error *
827 fetch_progress(void *arg, const char *message, off_t packfile_size,
828 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
830 struct got_fetch_progress_arg *a = arg;
831 char scaled_size[FMT_SCALED_STRSIZE];
832 int p_indexed, p_resolved;
833 int print_size = 0, print_indexed = 0, print_resolved = 0;
835 if (a->verbosity < 0)
836 return NULL;
838 if (message && message[0] != '\0') {
839 printf("\rserver: %s", message);
840 fflush(stdout);
841 return NULL;
844 if (packfile_size > 0 || nobj_indexed > 0) {
845 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
846 (a->last_scaled_size[0] == '\0' ||
847 strcmp(scaled_size, a->last_scaled_size)) != 0) {
848 print_size = 1;
849 if (strlcpy(a->last_scaled_size, scaled_size,
850 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
851 return got_error(GOT_ERR_NO_SPACE);
853 if (nobj_indexed > 0) {
854 p_indexed = (nobj_indexed * 100) / nobj_total;
855 if (p_indexed != a->last_p_indexed) {
856 a->last_p_indexed = p_indexed;
857 print_indexed = 1;
858 print_size = 1;
861 if (nobj_resolved > 0) {
862 p_resolved = (nobj_resolved * 100) /
863 (nobj_total - nobj_loose);
864 if (p_resolved != a->last_p_resolved) {
865 a->last_p_resolved = p_resolved;
866 print_resolved = 1;
867 print_indexed = 1;
868 print_size = 1;
873 if (print_size || print_indexed || print_resolved)
874 printf("\r");
875 if (print_size)
876 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
877 if (print_indexed)
878 printf("; indexing %d%%", p_indexed);
879 if (print_resolved)
880 printf("; resolving deltas %d%%", p_resolved);
881 if (print_size || print_indexed || print_resolved)
882 fflush(stdout);
884 return NULL;
887 static const struct got_error *
888 create_head_ref(struct got_reference *target_ref, int verbosity,
889 struct got_repository *repo)
891 const struct got_error *err;
892 struct got_reference *head_symref;
894 err = got_ref_alloc_symref(&head_symref, GOT_REF_HEAD, target_ref);
895 if (err)
896 return err;
898 err = got_ref_write(head_symref, repo);
899 got_ref_close(head_symref);
900 if (err == NULL && verbosity > 0) {
901 printf("Created reference %s: %s\n", GOT_REF_HEAD,
902 got_ref_get_name(target_ref));
904 return err;
907 static const struct got_error *
908 list_remote_refs(struct got_pathlist_head *symrefs,
909 struct got_pathlist_head *refs)
911 const struct got_error *err;
912 struct got_pathlist_entry *pe;
914 TAILQ_FOREACH(pe, symrefs, entry) {
915 const char *refname = pe->path;
916 const char *targetref = pe->data;
918 printf("%s: %s\n", refname, targetref);
921 TAILQ_FOREACH(pe, refs, entry) {
922 const char *refname = pe->path;
923 struct got_object_id *id = pe->data;
924 char *id_str;
926 err = got_object_id_str(&id_str, id);
927 if (err)
928 return err;
929 printf("%s: %s\n", refname, id_str);
930 free(id_str);
933 return NULL;
936 static const struct got_error *
937 create_ref(const char *refname, struct got_object_id *id,
938 int verbosity, struct got_repository *repo)
940 const struct got_error *err = NULL;
941 struct got_reference *ref;
942 char *id_str;
944 err = got_object_id_str(&id_str, id);
945 if (err)
946 return err;
948 err = got_ref_alloc(&ref, refname, id);
949 if (err)
950 goto done;
952 err = got_ref_write(ref, repo);
953 got_ref_close(ref);
955 if (err == NULL && verbosity >= 0)
956 printf("Created reference %s: %s\n", refname, id_str);
957 done:
958 free(id_str);
959 return err;
962 static int
963 match_wanted_ref(const char *refname, const char *wanted_ref)
965 if (strncmp(refname, "refs/", 5) != 0)
966 return 0;
967 refname += 5;
969 /*
970 * Prevent fetching of references that won't make any
971 * sense outside of the remote repository's context.
972 */
973 if (strncmp(refname, "got/", 4) == 0)
974 return 0;
975 if (strncmp(refname, "remotes/", 8) == 0)
976 return 0;
978 if (strncmp(wanted_ref, "refs/", 5) == 0)
979 wanted_ref += 5;
981 /* Allow prefix match. */
982 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
983 return 1;
985 /* Allow exact match. */
986 return (strcmp(refname, wanted_ref) == 0);
989 static int
990 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
992 struct got_pathlist_entry *pe;
994 TAILQ_FOREACH(pe, wanted_refs, entry) {
995 if (match_wanted_ref(refname, pe->path))
996 return 1;
999 return 0;
1002 static const struct got_error *
1003 create_wanted_ref(const char *refname, struct got_object_id *id,
1004 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1006 const struct got_error *err;
1007 char *remote_refname;
1009 if (strncmp("refs/", refname, 5) == 0)
1010 refname += 5;
1012 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1013 remote_repo_name, refname) == -1)
1014 return got_error_from_errno("asprintf");
1016 err = create_ref(remote_refname, id, verbosity, repo);
1017 free(remote_refname);
1018 return err;
1021 static const struct got_error *
1022 cmd_clone(int argc, char *argv[])
1024 const struct got_error *error = NULL;
1025 const char *uri, *dirname;
1026 char *proto, *host, *port, *repo_name, *server_path;
1027 char *default_destdir = NULL, *id_str = NULL;
1028 const char *repo_path;
1029 struct got_repository *repo = NULL;
1030 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1031 struct got_pathlist_entry *pe;
1032 struct got_object_id *pack_hash = NULL;
1033 int ch, fetchfd = -1, fetchstatus;
1034 pid_t fetchpid = -1;
1035 struct got_fetch_progress_arg fpa;
1036 char *git_url = NULL;
1037 char *gitconfig_path = NULL;
1038 char *gitconfig = NULL;
1039 FILE *gitconfig_file = NULL;
1040 ssize_t n;
1041 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1042 int list_refs_only = 0;
1043 struct got_reference *head_symref = NULL;
1045 TAILQ_INIT(&refs);
1046 TAILQ_INIT(&symrefs);
1047 TAILQ_INIT(&wanted_branches);
1048 TAILQ_INIT(&wanted_refs);
1050 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1051 switch (ch) {
1052 case 'a':
1053 fetch_all_branches = 1;
1054 break;
1055 case 'b':
1056 error = got_pathlist_append(&wanted_branches,
1057 optarg, NULL);
1058 if (error)
1059 return error;
1060 break;
1061 case 'l':
1062 list_refs_only = 1;
1063 break;
1064 case 'm':
1065 mirror_references = 1;
1066 break;
1067 case 'v':
1068 if (verbosity < 0)
1069 verbosity = 0;
1070 else if (verbosity < 3)
1071 verbosity++;
1072 break;
1073 case 'q':
1074 verbosity = -1;
1075 break;
1076 case 'R':
1077 error = got_pathlist_append(&wanted_refs,
1078 optarg, NULL);
1079 if (error)
1080 return error;
1081 break;
1082 default:
1083 usage_clone();
1084 break;
1087 argc -= optind;
1088 argv += optind;
1090 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1091 errx(1, "-a and -b options are mutually exclusive");
1092 if (list_refs_only) {
1093 if (!TAILQ_EMPTY(&wanted_branches))
1094 errx(1, "-l and -b options are mutually exclusive");
1095 if (fetch_all_branches)
1096 errx(1, "-l and -a options are mutually exclusive");
1097 if (mirror_references)
1098 errx(1, "-l and -m options are mutually exclusive");
1099 if (verbosity == -1)
1100 errx(1, "-l and -q options are mutually exclusive");
1101 if (!TAILQ_EMPTY(&wanted_refs))
1102 errx(1, "-l and -R options are mutually exclusive");
1105 uri = argv[0];
1107 if (argc == 1)
1108 dirname = NULL;
1109 else if (argc == 2)
1110 dirname = argv[1];
1111 else
1112 usage_clone();
1114 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1115 &repo_name, argv[0]);
1116 if (error)
1117 goto done;
1119 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1120 host, port ? ":" : "", port ? port : "",
1121 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1122 error = got_error_from_errno("asprintf");
1123 goto done;
1126 if (strcmp(proto, "git") == 0) {
1127 #ifndef PROFILE
1128 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1129 "sendfd dns inet unveil", NULL) == -1)
1130 err(1, "pledge");
1131 #endif
1132 } else if (strcmp(proto, "git+ssh") == 0 ||
1133 strcmp(proto, "ssh") == 0) {
1134 #ifndef PROFILE
1135 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1136 "sendfd unveil", NULL) == -1)
1137 err(1, "pledge");
1138 #endif
1139 } else if (strcmp(proto, "http") == 0 ||
1140 strcmp(proto, "git+http") == 0) {
1141 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1142 goto done;
1143 } else {
1144 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1145 goto done;
1147 if (dirname == NULL) {
1148 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1149 error = got_error_from_errno("asprintf");
1150 goto done;
1152 repo_path = default_destdir;
1153 } else
1154 repo_path = dirname;
1156 if (!list_refs_only) {
1157 error = got_path_mkdir(repo_path);
1158 if (error)
1159 goto done;
1161 error = got_repo_init(repo_path);
1162 if (error)
1163 goto done;
1164 error = got_repo_open(&repo, repo_path, NULL);
1165 if (error)
1166 goto done;
1169 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1170 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1171 error = got_error_from_errno2("unveil",
1172 GOT_FETCH_PATH_SSH);
1173 goto done;
1176 error = apply_unveil(repo ? got_repo_get_path(repo) : NULL, 0, NULL);
1177 if (error)
1178 goto done;
1180 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1181 server_path, verbosity);
1182 if (error)
1183 goto done;
1185 if (verbosity >= 0)
1186 printf("Connected to %s%s%s\n", host,
1187 port ? ":" : "", port ? port : "");
1189 fpa.last_scaled_size[0] = '\0';
1190 fpa.last_p_indexed = -1;
1191 fpa.last_p_resolved = -1;
1192 fpa.verbosity = verbosity;
1193 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1194 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1195 fetch_all_branches, &wanted_branches, &wanted_refs,
1196 list_refs_only, verbosity, fetchfd, repo,
1197 fetch_progress, &fpa);
1198 if (error)
1199 goto done;
1201 if (list_refs_only) {
1202 error = list_remote_refs(&symrefs, &refs);
1203 goto done;
1206 error = got_object_id_str(&id_str, pack_hash);
1207 if (error)
1208 goto done;
1209 if (verbosity >= 0)
1210 printf("\nFetched %s.pack\n", id_str);
1211 free(id_str);
1213 /* Set up references provided with the pack file. */
1214 TAILQ_FOREACH(pe, &refs, entry) {
1215 const char *refname = pe->path;
1216 struct got_object_id *id = pe->data;
1217 char *remote_refname;
1219 if (is_wanted_ref(&wanted_refs, refname) &&
1220 !mirror_references) {
1221 error = create_wanted_ref(refname, id,
1222 GOT_FETCH_DEFAULT_REMOTE_NAME,
1223 verbosity - 1, repo);
1224 if (error)
1225 goto done;
1226 continue;
1229 error = create_ref(refname, id, verbosity - 1, repo);
1230 if (error)
1231 goto done;
1233 if (mirror_references)
1234 continue;
1236 if (strncmp("refs/heads/", refname, 11) != 0)
1237 continue;
1239 if (asprintf(&remote_refname,
1240 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1241 refname + 11) == -1) {
1242 error = got_error_from_errno("asprintf");
1243 goto done;
1245 error = create_ref(remote_refname, id, verbosity - 1, repo);
1246 if (error)
1247 goto done;
1250 /* Set the HEAD reference if the server provided one. */
1251 TAILQ_FOREACH(pe, &symrefs, entry) {
1252 struct got_reference *target_ref;
1253 const char *refname = pe->path;
1254 const char *target = pe->data;
1256 if (strcmp(refname, GOT_REF_HEAD) != 0)
1257 continue;
1259 error = got_ref_open(&target_ref, repo, target, 0);
1260 if (error) {
1261 if (error->code == GOT_ERR_NOT_REF) {
1262 error = NULL;
1263 continue;
1265 goto done;
1268 error = create_head_ref(target_ref, verbosity, repo);
1269 got_ref_close(target_ref);
1270 if (error)
1271 goto done;
1273 if (pe == NULL) {
1275 * We failed to set the HEAD reference. If we asked for
1276 * a set of wanted branches use the first of one of those
1277 * which could be fetched instead.
1279 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1280 const char *target = pe->path;
1281 struct got_reference *target_ref;
1283 error = got_ref_open(&target_ref, repo, target, 0);
1284 if (error) {
1285 if (error->code == GOT_ERR_NOT_REF) {
1286 error = NULL;
1287 continue;
1289 goto done;
1292 error = create_head_ref(target_ref, verbosity, repo);
1293 got_ref_close(target_ref);
1294 if (error)
1295 goto done;
1296 break;
1300 /* Create a config file git-fetch(1) can understand. */
1301 gitconfig_path = got_repo_get_path_gitconfig(repo);
1302 if (gitconfig_path == NULL) {
1303 error = got_error_from_errno("got_repo_get_path_gitconfig");
1304 goto done;
1306 gitconfig_file = fopen(gitconfig_path, "a");
1307 if (gitconfig_file == NULL) {
1308 error = got_error_from_errno2("fopen", gitconfig_path);
1309 goto done;
1311 if (mirror_references) {
1312 if (asprintf(&gitconfig,
1313 "[remote \"%s\"]\n"
1314 "\turl = %s\n"
1315 "\tfetch = +refs/*:refs/*\n"
1316 "\tmirror = true\n",
1317 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1318 error = got_error_from_errno("asprintf");
1319 goto done;
1321 } else if (fetch_all_branches) {
1322 if (asprintf(&gitconfig,
1323 "[remote \"%s\"]\n"
1324 "\turl = %s\n"
1325 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1326 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1327 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1328 error = got_error_from_errno("asprintf");
1329 goto done;
1331 } else {
1332 const char *branchname;
1335 * If the server specified a default branch, use just that one.
1336 * Otherwise fall back to fetching all branches on next fetch.
1338 if (head_symref) {
1339 branchname = got_ref_get_symref_target(head_symref);
1340 if (strncmp(branchname, "refs/heads/", 11) == 0)
1341 branchname += 11;
1342 } else
1343 branchname = "*"; /* fall back to all branches */
1344 if (asprintf(&gitconfig,
1345 "[remote \"%s\"]\n"
1346 "\turl = %s\n"
1347 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1348 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1349 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1350 branchname) == -1) {
1351 error = got_error_from_errno("asprintf");
1352 goto done;
1355 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1356 if (n != strlen(gitconfig)) {
1357 error = got_ferror(gitconfig_file, GOT_ERR_IO);
1358 goto done;
1361 if (verbosity >= 0)
1362 printf("Created %s repository '%s'\n",
1363 mirror_references ? "mirrored" : "cloned", repo_path);
1364 done:
1365 if (fetchpid > 0) {
1366 if (kill(fetchpid, SIGTERM) == -1)
1367 error = got_error_from_errno("kill");
1368 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1369 error = got_error_from_errno("waitpid");
1371 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1372 error = got_error_from_errno("close");
1373 if (gitconfig_file && fclose(gitconfig_file) == EOF && error == NULL)
1374 error = got_error_from_errno("fclose");
1375 if (repo)
1376 got_repo_close(repo);
1377 if (head_symref)
1378 got_ref_close(head_symref);
1379 TAILQ_FOREACH(pe, &refs, entry) {
1380 free((void *)pe->path);
1381 free(pe->data);
1383 got_pathlist_free(&refs);
1384 TAILQ_FOREACH(pe, &symrefs, entry) {
1385 free((void *)pe->path);
1386 free(pe->data);
1388 got_pathlist_free(&symrefs);
1389 got_pathlist_free(&wanted_branches);
1390 got_pathlist_free(&wanted_refs);
1391 free(pack_hash);
1392 free(proto);
1393 free(host);
1394 free(port);
1395 free(server_path);
1396 free(repo_name);
1397 free(default_destdir);
1398 free(gitconfig_path);
1399 free(git_url);
1400 return error;
1403 static const struct got_error *
1404 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1405 int replace_tags, int verbosity, struct got_repository *repo)
1407 const struct got_error *err = NULL;
1408 char *new_id_str = NULL;
1409 struct got_object_id *old_id = NULL;
1411 err = got_object_id_str(&new_id_str, new_id);
1412 if (err)
1413 goto done;
1415 if (!replace_tags &&
1416 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1417 if (verbosity >= 0) {
1418 printf("Rejecting update of existing tag %s: %s\n",
1419 got_ref_get_name(ref), new_id_str);
1421 goto done;
1424 if (got_ref_is_symbolic(ref)) {
1425 struct got_reference *new_ref;
1426 err = got_ref_alloc(&new_ref, got_ref_get_name(ref), new_id);
1427 if (err)
1428 goto done;
1429 err = got_ref_delete(ref, repo);
1430 if (err)
1431 goto done;
1432 if (verbosity >= 0) {
1433 printf("Deleted reference %s: %s\n",
1434 got_ref_get_name(ref),
1435 got_ref_get_symref_target(ref));
1437 err = got_ref_write(new_ref, repo);
1438 if (err)
1439 goto done;
1440 } else {
1441 err = got_ref_resolve(&old_id, repo, ref);
1442 if (err)
1443 goto done;
1444 if (got_object_id_cmp(old_id, new_id) == 0)
1445 goto done;
1447 err = got_ref_change_ref(ref, new_id);
1448 if (err)
1449 goto done;
1450 err = got_ref_write(ref, repo);
1451 if (err)
1452 goto done;
1455 if (verbosity >= 0)
1456 printf("Updated reference %s: %s\n", got_ref_get_name(ref),
1457 new_id_str);
1458 done:
1459 free(old_id);
1460 free(new_id_str);
1461 return err;
1464 __dead static void
1465 usage_fetch(void)
1467 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1468 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1469 "[remote-repository-name]\n",
1470 getprogname());
1471 exit(1);
1474 static const struct got_error *
1475 delete_missing_refs(struct got_pathlist_head *their_refs,
1476 int verbosity, struct got_repository *repo)
1478 const struct got_error *err = NULL;
1479 struct got_reflist_head my_refs;
1480 struct got_reflist_entry *re;
1481 struct got_pathlist_entry *pe;
1482 struct got_object_id *id;
1483 char *id_str;
1485 SIMPLEQ_INIT(&my_refs);
1487 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1488 if (err)
1489 return err;
1491 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1492 const char *refname = got_ref_get_name(re->ref);
1494 if (strncmp(refname, "refs/heads/", 11) != 0 &&
1495 strncmp(refname, "refs/tags/", 10) != 0)
1496 continue;
1498 TAILQ_FOREACH(pe, their_refs, entry) {
1499 if (strcmp(refname, pe->path) == 0)
1500 break;
1502 if (pe != NULL)
1503 continue;
1505 err = got_ref_resolve(&id, repo, re->ref);
1506 if (err)
1507 break;
1508 err = got_object_id_str(&id_str, id);
1509 free(id);
1510 if (err)
1511 break;
1513 free(id_str);
1514 err = got_ref_delete(re->ref, repo);
1515 if (err)
1516 break;
1517 if (verbosity >= 0) {
1518 printf("Deleted reference %s: %s\n",
1519 got_ref_get_name(re->ref), id_str);
1523 return err;
1526 static const struct got_error *
1527 update_wanted_ref(const char *refname, struct got_object_id *id,
1528 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1530 const struct got_error *err, *unlock_err;
1531 char *remote_refname;
1532 struct got_reference *ref;
1534 if (strncmp("refs/", refname, 5) == 0)
1535 refname += 5;
1537 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1538 remote_repo_name, refname) == -1)
1539 return got_error_from_errno("asprintf");
1541 err = got_ref_open(&ref, repo, remote_refname, 1);
1542 if (err) {
1543 if (err->code != GOT_ERR_NOT_REF)
1544 goto done;
1545 err = create_ref(remote_refname, id, verbosity, repo);
1546 } else {
1547 err = update_ref(ref, id, 0, verbosity, repo);
1548 unlock_err = got_ref_unlock(ref);
1549 if (unlock_err && err == NULL)
1550 err = unlock_err;
1551 got_ref_close(ref);
1553 done:
1554 free(remote_refname);
1555 return err;
1558 static const struct got_error *
1559 cmd_fetch(int argc, char *argv[])
1561 const struct got_error *error = NULL, *unlock_err;
1562 char *cwd = NULL, *repo_path = NULL;
1563 const char *remote_name;
1564 char *proto = NULL, *host = NULL, *port = NULL;
1565 char *repo_name = NULL, *server_path = NULL;
1566 struct got_remote_repo *remotes, *remote = NULL;
1567 int nremotes;
1568 char *id_str = NULL;
1569 struct got_repository *repo = NULL;
1570 struct got_worktree *worktree = NULL;
1571 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1572 struct got_pathlist_entry *pe;
1573 struct got_object_id *pack_hash = NULL;
1574 int i, ch, fetchfd = -1, fetchstatus;
1575 pid_t fetchpid = -1;
1576 struct got_fetch_progress_arg fpa;
1577 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
1578 int delete_refs = 0, replace_tags = 0;
1580 TAILQ_INIT(&refs);
1581 TAILQ_INIT(&symrefs);
1582 TAILQ_INIT(&wanted_branches);
1583 TAILQ_INIT(&wanted_refs);
1585 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
1586 switch (ch) {
1587 case 'a':
1588 fetch_all_branches = 1;
1589 break;
1590 case 'b':
1591 error = got_pathlist_append(&wanted_branches,
1592 optarg, NULL);
1593 if (error)
1594 return error;
1595 break;
1596 case 'd':
1597 delete_refs = 1;
1598 break;
1599 case 'l':
1600 list_refs_only = 1;
1601 break;
1602 case 'r':
1603 repo_path = realpath(optarg, NULL);
1604 if (repo_path == NULL)
1605 return got_error_from_errno2("realpath",
1606 optarg);
1607 got_path_strip_trailing_slashes(repo_path);
1608 break;
1609 case 't':
1610 replace_tags = 1;
1611 break;
1612 case 'v':
1613 if (verbosity < 0)
1614 verbosity = 0;
1615 else if (verbosity < 3)
1616 verbosity++;
1617 break;
1618 case 'q':
1619 verbosity = -1;
1620 break;
1621 case 'R':
1622 error = got_pathlist_append(&wanted_refs,
1623 optarg, NULL);
1624 if (error)
1625 return error;
1626 break;
1627 default:
1628 usage_fetch();
1629 break;
1632 argc -= optind;
1633 argv += optind;
1635 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1636 errx(1, "-a and -b options are mutually exclusive");
1637 if (list_refs_only) {
1638 if (!TAILQ_EMPTY(&wanted_branches))
1639 errx(1, "-l and -b options are mutually exclusive");
1640 if (fetch_all_branches)
1641 errx(1, "-l and -a options are mutually exclusive");
1642 if (delete_refs)
1643 errx(1, "-l and -d options are mutually exclusive");
1644 if (verbosity == -1)
1645 errx(1, "-l and -q options are mutually exclusive");
1648 if (argc == 0)
1649 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
1650 else if (argc == 1)
1651 remote_name = argv[0];
1652 else
1653 usage_fetch();
1655 cwd = getcwd(NULL, 0);
1656 if (cwd == NULL) {
1657 error = got_error_from_errno("getcwd");
1658 goto done;
1661 if (repo_path == NULL) {
1662 error = got_worktree_open(&worktree, cwd);
1663 if (error && error->code != GOT_ERR_NOT_WORKTREE)
1664 goto done;
1665 else
1666 error = NULL;
1667 if (worktree) {
1668 repo_path =
1669 strdup(got_worktree_get_repo_path(worktree));
1670 if (repo_path == NULL)
1671 error = got_error_from_errno("strdup");
1672 if (error)
1673 goto done;
1674 } else {
1675 repo_path = strdup(cwd);
1676 if (repo_path == NULL) {
1677 error = got_error_from_errno("strdup");
1678 goto done;
1683 error = got_repo_open(&repo, repo_path, NULL);
1684 if (error)
1685 goto done;
1687 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
1688 for (i = 0; i < nremotes; i++) {
1689 remote = &remotes[i];
1690 if (strcmp(remote->name, remote_name) == 0)
1691 break;
1693 if (i == nremotes) {
1694 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
1695 goto done;
1698 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1699 &repo_name, remote->url);
1700 if (error)
1701 goto done;
1703 if (strcmp(proto, "git") == 0) {
1704 #ifndef PROFILE
1705 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1706 "sendfd dns inet unveil", NULL) == -1)
1707 err(1, "pledge");
1708 #endif
1709 } else if (strcmp(proto, "git+ssh") == 0 ||
1710 strcmp(proto, "ssh") == 0) {
1711 #ifndef PROFILE
1712 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1713 "sendfd unveil", NULL) == -1)
1714 err(1, "pledge");
1715 #endif
1716 } else if (strcmp(proto, "http") == 0 ||
1717 strcmp(proto, "git+http") == 0) {
1718 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1719 goto done;
1720 } else {
1721 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1722 goto done;
1725 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1726 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1727 error = got_error_from_errno2("unveil",
1728 GOT_FETCH_PATH_SSH);
1729 goto done;
1732 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
1733 if (error)
1734 goto done;
1736 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1737 server_path, verbosity);
1738 if (error)
1739 goto done;
1741 if (verbosity >= 0)
1742 printf("Connected to \"%s\" %s%s%s\n", remote->name, host,
1743 port ? ":" : "", port ? port : "");
1745 fpa.last_scaled_size[0] = '\0';
1746 fpa.last_p_indexed = -1;
1747 fpa.last_p_resolved = -1;
1748 fpa.verbosity = verbosity;
1749 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
1750 remote->mirror_references, fetch_all_branches, &wanted_branches,
1751 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
1752 fetch_progress, &fpa);
1753 if (error)
1754 goto done;
1756 if (list_refs_only) {
1757 error = list_remote_refs(&symrefs, &refs);
1758 goto done;
1761 if (pack_hash == NULL) {
1762 if (verbosity >= 0)
1763 printf("Already up-to-date\n");
1764 if (delete_refs)
1765 error = delete_missing_refs(&refs, verbosity, repo);
1766 goto done;
1769 if (verbosity >= 0) {
1770 error = got_object_id_str(&id_str, pack_hash);
1771 if (error)
1772 goto done;
1773 printf("\nFetched %s.pack\n", id_str);
1774 free(id_str);
1775 id_str = NULL;
1778 /* Update references provided with the pack file. */
1779 TAILQ_FOREACH(pe, &refs, entry) {
1780 const char *refname = pe->path;
1781 struct got_object_id *id = pe->data;
1782 struct got_reference *ref;
1783 char *remote_refname;
1785 if (is_wanted_ref(&wanted_refs, refname) &&
1786 !remote->mirror_references) {
1787 error = update_wanted_ref(refname, id,
1788 remote->name, verbosity, repo);
1789 if (error)
1790 goto done;
1791 continue;
1794 if (remote->mirror_references ||
1795 strncmp("refs/tags/", refname, 10) == 0) {
1796 error = got_ref_open(&ref, repo, refname, 1);
1797 if (error) {
1798 if (error->code != GOT_ERR_NOT_REF)
1799 goto done;
1800 error = create_ref(refname, id, verbosity,
1801 repo);
1802 if (error)
1803 goto done;
1804 } else {
1805 error = update_ref(ref, id, replace_tags,
1806 verbosity, repo);
1807 unlock_err = got_ref_unlock(ref);
1808 if (unlock_err && error == NULL)
1809 error = unlock_err;
1810 got_ref_close(ref);
1811 if (error)
1812 goto done;
1814 } else if (strncmp("refs/heads/", refname, 11) == 0) {
1815 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1816 remote_name, refname + 11) == -1) {
1817 error = got_error_from_errno("asprintf");
1818 goto done;
1821 error = got_ref_open(&ref, repo, remote_refname, 1);
1822 if (error) {
1823 if (error->code != GOT_ERR_NOT_REF)
1824 goto done;
1825 error = create_ref(remote_refname, id,
1826 verbosity, repo);
1827 if (error)
1828 goto done;
1829 } else {
1830 error = update_ref(ref, id, replace_tags,
1831 verbosity, repo);
1832 unlock_err = got_ref_unlock(ref);
1833 if (unlock_err && error == NULL)
1834 error = unlock_err;
1835 got_ref_close(ref);
1836 if (error)
1837 goto done;
1840 /* Also create a local branch if none exists yet. */
1841 error = got_ref_open(&ref, repo, refname, 1);
1842 if (error) {
1843 if (error->code != GOT_ERR_NOT_REF)
1844 goto done;
1845 error = create_ref(refname, id, verbosity,
1846 repo);
1847 if (error)
1848 goto done;
1849 } else {
1850 unlock_err = got_ref_unlock(ref);
1851 if (unlock_err && error == NULL)
1852 error = unlock_err;
1853 got_ref_close(ref);
1857 if (delete_refs)
1858 error = delete_missing_refs(&refs, verbosity, repo);
1859 done:
1860 if (fetchpid > 0) {
1861 if (kill(fetchpid, SIGTERM) == -1)
1862 error = got_error_from_errno("kill");
1863 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1864 error = got_error_from_errno("waitpid");
1866 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1867 error = got_error_from_errno("close");
1868 if (repo)
1869 got_repo_close(repo);
1870 if (worktree)
1871 got_worktree_close(worktree);
1872 TAILQ_FOREACH(pe, &refs, entry) {
1873 free((void *)pe->path);
1874 free(pe->data);
1876 got_pathlist_free(&refs);
1877 TAILQ_FOREACH(pe, &symrefs, entry) {
1878 free((void *)pe->path);
1879 free(pe->data);
1881 got_pathlist_free(&symrefs);
1882 got_pathlist_free(&wanted_branches);
1883 got_pathlist_free(&wanted_refs);
1884 free(id_str);
1885 free(cwd);
1886 free(repo_path);
1887 free(pack_hash);
1888 free(proto);
1889 free(host);
1890 free(port);
1891 free(server_path);
1892 free(repo_name);
1893 return error;
1897 __dead static void
1898 usage_checkout(void)
1900 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
1901 "[-p prefix] repository-path [worktree-path]\n", getprogname());
1902 exit(1);
1905 static void
1906 show_worktree_base_ref_warning(void)
1908 fprintf(stderr, "%s: warning: could not create a reference "
1909 "to the work tree's base commit; the commit could be "
1910 "garbage-collected by Git; making the repository "
1911 "writable and running 'got update' will prevent this\n",
1912 getprogname());
1915 struct got_checkout_progress_arg {
1916 const char *worktree_path;
1917 int had_base_commit_ref_error;
1920 static const struct got_error *
1921 checkout_progress(void *arg, unsigned char status, const char *path)
1923 struct got_checkout_progress_arg *a = arg;
1925 /* Base commit bump happens silently. */
1926 if (status == GOT_STATUS_BUMP_BASE)
1927 return NULL;
1929 if (status == GOT_STATUS_BASE_REF_ERR) {
1930 a->had_base_commit_ref_error = 1;
1931 return NULL;
1934 while (path[0] == '/')
1935 path++;
1937 printf("%c %s/%s\n", status, a->worktree_path, path);
1938 return NULL;
1941 static const struct got_error *
1942 check_cancelled(void *arg)
1944 if (sigint_received || sigpipe_received)
1945 return got_error(GOT_ERR_CANCELLED);
1946 return NULL;
1949 static const struct got_error *
1950 check_linear_ancestry(struct got_object_id *commit_id,
1951 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
1952 struct got_repository *repo)
1954 const struct got_error *err = NULL;
1955 struct got_object_id *yca_id;
1957 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
1958 commit_id, base_commit_id, repo, check_cancelled, NULL);
1959 if (err)
1960 return err;
1962 if (yca_id == NULL)
1963 return got_error(GOT_ERR_ANCESTRY);
1966 * Require a straight line of history between the target commit
1967 * and the work tree's base commit.
1969 * Non-linear situations such as this require a rebase:
1971 * (commit) D F (base_commit)
1972 * \ /
1973 * C E
1974 * \ /
1975 * B (yca)
1976 * |
1977 * A
1979 * 'got update' only handles linear cases:
1980 * Update forwards in time: A (base/yca) - B - C - D (commit)
1981 * Update backwards in time: D (base) - C - B - A (commit/yca)
1983 if (allow_forwards_in_time_only) {
1984 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
1985 return got_error(GOT_ERR_ANCESTRY);
1986 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
1987 got_object_id_cmp(base_commit_id, yca_id) != 0)
1988 return got_error(GOT_ERR_ANCESTRY);
1990 free(yca_id);
1991 return NULL;
1994 static const struct got_error *
1995 check_same_branch(struct got_object_id *commit_id,
1996 struct got_reference *head_ref, struct got_object_id *yca_id,
1997 struct got_repository *repo)
1999 const struct got_error *err = NULL;
2000 struct got_commit_graph *graph = NULL;
2001 struct got_object_id *head_commit_id = NULL;
2002 int is_same_branch = 0;
2004 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2005 if (err)
2006 goto done;
2008 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2009 is_same_branch = 1;
2010 goto done;
2012 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2013 is_same_branch = 1;
2014 goto done;
2017 err = got_commit_graph_open(&graph, "/", 1);
2018 if (err)
2019 goto done;
2021 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2022 check_cancelled, NULL);
2023 if (err)
2024 goto done;
2026 for (;;) {
2027 struct got_object_id *id;
2028 err = got_commit_graph_iter_next(&id, graph, repo,
2029 check_cancelled, NULL);
2030 if (err) {
2031 if (err->code == GOT_ERR_ITER_COMPLETED)
2032 err = NULL;
2033 break;
2036 if (id) {
2037 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2038 break;
2039 if (got_object_id_cmp(id, commit_id) == 0) {
2040 is_same_branch = 1;
2041 break;
2045 done:
2046 if (graph)
2047 got_commit_graph_close(graph);
2048 free(head_commit_id);
2049 if (!err && !is_same_branch)
2050 err = got_error(GOT_ERR_ANCESTRY);
2051 return err;
2054 static const struct got_error *
2055 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2057 static char msg[512];
2058 const char *branch_name;
2060 if (got_ref_is_symbolic(ref))
2061 branch_name = got_ref_get_symref_target(ref);
2062 else
2063 branch_name = got_ref_get_name(ref);
2065 if (strncmp("refs/heads/", branch_name, 11) == 0)
2066 branch_name += 11;
2068 snprintf(msg, sizeof(msg),
2069 "target commit is not contained in branch '%s'; "
2070 "the branch to use must be specified with -b; "
2071 "if necessary a new branch can be created for "
2072 "this commit with 'got branch -c %s BRANCH_NAME'",
2073 branch_name, commit_id_str);
2075 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2078 static const struct got_error *
2079 cmd_checkout(int argc, char *argv[])
2081 const struct got_error *error = NULL;
2082 struct got_repository *repo = NULL;
2083 struct got_reference *head_ref = NULL;
2084 struct got_worktree *worktree = NULL;
2085 char *repo_path = NULL;
2086 char *worktree_path = NULL;
2087 const char *path_prefix = "";
2088 const char *branch_name = GOT_REF_HEAD;
2089 char *commit_id_str = NULL;
2090 int ch, same_path_prefix, allow_nonempty = 0;
2091 struct got_pathlist_head paths;
2092 struct got_checkout_progress_arg cpa;
2094 TAILQ_INIT(&paths);
2096 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2097 switch (ch) {
2098 case 'b':
2099 branch_name = optarg;
2100 break;
2101 case 'c':
2102 commit_id_str = strdup(optarg);
2103 if (commit_id_str == NULL)
2104 return got_error_from_errno("strdup");
2105 break;
2106 case 'E':
2107 allow_nonempty = 1;
2108 break;
2109 case 'p':
2110 path_prefix = optarg;
2111 break;
2112 default:
2113 usage_checkout();
2114 /* NOTREACHED */
2118 argc -= optind;
2119 argv += optind;
2121 #ifndef PROFILE
2122 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2123 "unveil", NULL) == -1)
2124 err(1, "pledge");
2125 #endif
2126 if (argc == 1) {
2127 char *cwd, *base, *dotgit;
2128 repo_path = realpath(argv[0], NULL);
2129 if (repo_path == NULL)
2130 return got_error_from_errno2("realpath", argv[0]);
2131 cwd = getcwd(NULL, 0);
2132 if (cwd == NULL) {
2133 error = got_error_from_errno("getcwd");
2134 goto done;
2136 if (path_prefix[0]) {
2137 base = basename(path_prefix);
2138 if (base == NULL) {
2139 error = got_error_from_errno2("basename",
2140 path_prefix);
2141 goto done;
2143 } else {
2144 base = basename(repo_path);
2145 if (base == NULL) {
2146 error = got_error_from_errno2("basename",
2147 repo_path);
2148 goto done;
2151 dotgit = strstr(base, ".git");
2152 if (dotgit)
2153 *dotgit = '\0';
2154 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2155 error = got_error_from_errno("asprintf");
2156 free(cwd);
2157 goto done;
2159 free(cwd);
2160 } else if (argc == 2) {
2161 repo_path = realpath(argv[0], NULL);
2162 if (repo_path == NULL) {
2163 error = got_error_from_errno2("realpath", argv[0]);
2164 goto done;
2166 worktree_path = realpath(argv[1], NULL);
2167 if (worktree_path == NULL) {
2168 if (errno != ENOENT) {
2169 error = got_error_from_errno2("realpath",
2170 argv[1]);
2171 goto done;
2173 worktree_path = strdup(argv[1]);
2174 if (worktree_path == NULL) {
2175 error = got_error_from_errno("strdup");
2176 goto done;
2179 } else
2180 usage_checkout();
2182 got_path_strip_trailing_slashes(repo_path);
2183 got_path_strip_trailing_slashes(worktree_path);
2185 error = got_repo_open(&repo, repo_path, NULL);
2186 if (error != NULL)
2187 goto done;
2189 /* Pre-create work tree path for unveil(2) */
2190 error = got_path_mkdir(worktree_path);
2191 if (error) {
2192 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2193 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2194 goto done;
2195 if (!allow_nonempty &&
2196 !got_path_dir_is_empty(worktree_path)) {
2197 error = got_error_path(worktree_path,
2198 GOT_ERR_DIR_NOT_EMPTY);
2199 goto done;
2203 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2204 if (error)
2205 goto done;
2207 error = got_ref_open(&head_ref, repo, branch_name, 0);
2208 if (error != NULL)
2209 goto done;
2211 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2212 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2213 goto done;
2215 error = got_worktree_open(&worktree, worktree_path);
2216 if (error != NULL)
2217 goto done;
2219 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2220 path_prefix);
2221 if (error != NULL)
2222 goto done;
2223 if (!same_path_prefix) {
2224 error = got_error(GOT_ERR_PATH_PREFIX);
2225 goto done;
2228 if (commit_id_str) {
2229 struct got_object_id *commit_id;
2230 error = got_repo_match_object_id(&commit_id, NULL,
2231 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2232 if (error)
2233 goto done;
2234 error = check_linear_ancestry(commit_id,
2235 got_worktree_get_base_commit_id(worktree), 0, repo);
2236 if (error != NULL) {
2237 free(commit_id);
2238 if (error->code == GOT_ERR_ANCESTRY) {
2239 error = checkout_ancestry_error(
2240 head_ref, commit_id_str);
2242 goto done;
2244 error = check_same_branch(commit_id, head_ref, NULL, repo);
2245 if (error) {
2246 if (error->code == GOT_ERR_ANCESTRY) {
2247 error = checkout_ancestry_error(
2248 head_ref, commit_id_str);
2250 goto done;
2252 error = got_worktree_set_base_commit_id(worktree, repo,
2253 commit_id);
2254 free(commit_id);
2255 if (error)
2256 goto done;
2259 error = got_pathlist_append(&paths, "", NULL);
2260 if (error)
2261 goto done;
2262 cpa.worktree_path = worktree_path;
2263 cpa.had_base_commit_ref_error = 0;
2264 error = got_worktree_checkout_files(worktree, &paths, repo,
2265 checkout_progress, &cpa, check_cancelled, NULL);
2266 if (error != NULL)
2267 goto done;
2269 printf("Now shut up and hack\n");
2270 if (cpa.had_base_commit_ref_error)
2271 show_worktree_base_ref_warning();
2272 done:
2273 got_pathlist_free(&paths);
2274 free(commit_id_str);
2275 free(repo_path);
2276 free(worktree_path);
2277 return error;
2280 __dead static void
2281 usage_update(void)
2283 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2284 getprogname());
2285 exit(1);
2288 static const struct got_error *
2289 update_progress(void *arg, unsigned char status, const char *path)
2291 int *did_something = arg;
2293 if (status == GOT_STATUS_EXISTS ||
2294 status == GOT_STATUS_BASE_REF_ERR)
2295 return NULL;
2297 *did_something = 1;
2299 /* Base commit bump happens silently. */
2300 if (status == GOT_STATUS_BUMP_BASE)
2301 return NULL;
2303 while (path[0] == '/')
2304 path++;
2305 printf("%c %s\n", status, path);
2306 return NULL;
2309 static const struct got_error *
2310 switch_head_ref(struct got_reference *head_ref,
2311 struct got_object_id *commit_id, struct got_worktree *worktree,
2312 struct got_repository *repo)
2314 const struct got_error *err = NULL;
2315 char *base_id_str;
2316 int ref_has_moved = 0;
2318 /* Trivial case: switching between two different references. */
2319 if (strcmp(got_ref_get_name(head_ref),
2320 got_worktree_get_head_ref_name(worktree)) != 0) {
2321 printf("Switching work tree from %s to %s\n",
2322 got_worktree_get_head_ref_name(worktree),
2323 got_ref_get_name(head_ref));
2324 return got_worktree_set_head_ref(worktree, head_ref);
2327 err = check_linear_ancestry(commit_id,
2328 got_worktree_get_base_commit_id(worktree), 0, repo);
2329 if (err) {
2330 if (err->code != GOT_ERR_ANCESTRY)
2331 return err;
2332 ref_has_moved = 1;
2334 if (!ref_has_moved)
2335 return NULL;
2337 /* Switching to a rebased branch with the same reference name. */
2338 err = got_object_id_str(&base_id_str,
2339 got_worktree_get_base_commit_id(worktree));
2340 if (err)
2341 return err;
2342 printf("Reference %s now points at a different branch\n",
2343 got_worktree_get_head_ref_name(worktree));
2344 printf("Switching work tree from %s to %s\n", base_id_str,
2345 got_worktree_get_head_ref_name(worktree));
2346 return NULL;
2349 static const struct got_error *
2350 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2352 const struct got_error *err;
2353 int in_progress;
2355 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2356 if (err)
2357 return err;
2358 if (in_progress)
2359 return got_error(GOT_ERR_REBASING);
2361 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2362 if (err)
2363 return err;
2364 if (in_progress)
2365 return got_error(GOT_ERR_HISTEDIT_BUSY);
2367 return NULL;
2370 static const struct got_error *
2371 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2372 char *argv[], struct got_worktree *worktree)
2374 const struct got_error *err = NULL;
2375 char *path;
2376 int i;
2378 if (argc == 0) {
2379 path = strdup("");
2380 if (path == NULL)
2381 return got_error_from_errno("strdup");
2382 return got_pathlist_append(paths, path, NULL);
2385 for (i = 0; i < argc; i++) {
2386 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2387 if (err)
2388 break;
2389 err = got_pathlist_append(paths, path, NULL);
2390 if (err) {
2391 free(path);
2392 break;
2396 return err;
2399 static const struct got_error *
2400 cmd_update(int argc, char *argv[])
2402 const struct got_error *error = NULL;
2403 struct got_repository *repo = NULL;
2404 struct got_worktree *worktree = NULL;
2405 char *worktree_path = NULL;
2406 struct got_object_id *commit_id = NULL;
2407 char *commit_id_str = NULL;
2408 const char *branch_name = NULL;
2409 struct got_reference *head_ref = NULL;
2410 struct got_pathlist_head paths;
2411 struct got_pathlist_entry *pe;
2412 int ch, did_something = 0;
2414 TAILQ_INIT(&paths);
2416 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2417 switch (ch) {
2418 case 'b':
2419 branch_name = optarg;
2420 break;
2421 case 'c':
2422 commit_id_str = strdup(optarg);
2423 if (commit_id_str == NULL)
2424 return got_error_from_errno("strdup");
2425 break;
2426 default:
2427 usage_update();
2428 /* NOTREACHED */
2432 argc -= optind;
2433 argv += optind;
2435 #ifndef PROFILE
2436 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2437 "unveil", NULL) == -1)
2438 err(1, "pledge");
2439 #endif
2440 worktree_path = getcwd(NULL, 0);
2441 if (worktree_path == NULL) {
2442 error = got_error_from_errno("getcwd");
2443 goto done;
2445 error = got_worktree_open(&worktree, worktree_path);
2446 if (error)
2447 goto done;
2449 error = check_rebase_or_histedit_in_progress(worktree);
2450 if (error)
2451 goto done;
2453 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
2454 NULL);
2455 if (error != NULL)
2456 goto done;
2458 error = apply_unveil(got_repo_get_path(repo), 0,
2459 got_worktree_get_root_path(worktree));
2460 if (error)
2461 goto done;
2463 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2464 if (error)
2465 goto done;
2467 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
2468 got_worktree_get_head_ref_name(worktree), 0);
2469 if (error != NULL)
2470 goto done;
2471 if (commit_id_str == NULL) {
2472 error = got_ref_resolve(&commit_id, repo, head_ref);
2473 if (error != NULL)
2474 goto done;
2475 error = got_object_id_str(&commit_id_str, commit_id);
2476 if (error != NULL)
2477 goto done;
2478 } else {
2479 error = got_repo_match_object_id(&commit_id, NULL,
2480 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2481 free(commit_id_str);
2482 commit_id_str = NULL;
2483 if (error)
2484 goto done;
2485 error = got_object_id_str(&commit_id_str, commit_id);
2486 if (error)
2487 goto done;
2490 if (branch_name) {
2491 struct got_object_id *head_commit_id;
2492 TAILQ_FOREACH(pe, &paths, entry) {
2493 if (pe->path_len == 0)
2494 continue;
2495 error = got_error_msg(GOT_ERR_BAD_PATH,
2496 "switching between branches requires that "
2497 "the entire work tree gets updated");
2498 goto done;
2500 error = got_ref_resolve(&head_commit_id, repo, head_ref);
2501 if (error)
2502 goto done;
2503 error = check_linear_ancestry(commit_id, head_commit_id, 0,
2504 repo);
2505 free(head_commit_id);
2506 if (error != NULL)
2507 goto done;
2508 error = check_same_branch(commit_id, head_ref, NULL, repo);
2509 if (error)
2510 goto done;
2511 error = switch_head_ref(head_ref, commit_id, worktree, repo);
2512 if (error)
2513 goto done;
2514 } else {
2515 error = check_linear_ancestry(commit_id,
2516 got_worktree_get_base_commit_id(worktree), 0, repo);
2517 if (error != NULL) {
2518 if (error->code == GOT_ERR_ANCESTRY)
2519 error = got_error(GOT_ERR_BRANCH_MOVED);
2520 goto done;
2522 error = check_same_branch(commit_id, head_ref, NULL, repo);
2523 if (error)
2524 goto done;
2527 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
2528 commit_id) != 0) {
2529 error = got_worktree_set_base_commit_id(worktree, repo,
2530 commit_id);
2531 if (error)
2532 goto done;
2535 error = got_worktree_checkout_files(worktree, &paths, repo,
2536 update_progress, &did_something, check_cancelled, NULL);
2537 if (error != NULL)
2538 goto done;
2540 if (did_something)
2541 printf("Updated to commit %s\n", commit_id_str);
2542 else
2543 printf("Already up-to-date\n");
2544 done:
2545 free(worktree_path);
2546 TAILQ_FOREACH(pe, &paths, entry)
2547 free((char *)pe->path);
2548 got_pathlist_free(&paths);
2549 free(commit_id);
2550 free(commit_id_str);
2551 return error;
2554 static const struct got_error *
2555 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
2556 const char *path, int diff_context, int ignore_whitespace,
2557 struct got_repository *repo)
2559 const struct got_error *err = NULL;
2560 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
2562 if (blob_id1) {
2563 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
2564 if (err)
2565 goto done;
2568 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
2569 if (err)
2570 goto done;
2572 while (path[0] == '/')
2573 path++;
2574 err = got_diff_blob(blob1, blob2, path, path, diff_context,
2575 ignore_whitespace, stdout);
2576 done:
2577 if (blob1)
2578 got_object_blob_close(blob1);
2579 got_object_blob_close(blob2);
2580 return err;
2583 static const struct got_error *
2584 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
2585 const char *path, int diff_context, int ignore_whitespace,
2586 struct got_repository *repo)
2588 const struct got_error *err = NULL;
2589 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
2590 struct got_diff_blob_output_unidiff_arg arg;
2592 if (tree_id1) {
2593 err = got_object_open_as_tree(&tree1, repo, tree_id1);
2594 if (err)
2595 goto done;
2598 err = got_object_open_as_tree(&tree2, repo, tree_id2);
2599 if (err)
2600 goto done;
2602 arg.diff_context = diff_context;
2603 arg.ignore_whitespace = ignore_whitespace;
2604 arg.outfile = stdout;
2605 while (path[0] == '/')
2606 path++;
2607 err = got_diff_tree(tree1, tree2, path, path, repo,
2608 got_diff_blob_output_unidiff, &arg, 1);
2609 done:
2610 if (tree1)
2611 got_object_tree_close(tree1);
2612 if (tree2)
2613 got_object_tree_close(tree2);
2614 return err;
2617 static const struct got_error *
2618 print_patch(struct got_commit_object *commit, struct got_object_id *id,
2619 const char *path, int diff_context, struct got_repository *repo)
2621 const struct got_error *err = NULL;
2622 struct got_commit_object *pcommit = NULL;
2623 char *id_str1 = NULL, *id_str2 = NULL;
2624 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
2625 struct got_object_qid *qid;
2627 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
2628 if (qid != NULL) {
2629 err = got_object_open_as_commit(&pcommit, repo,
2630 qid->id);
2631 if (err)
2632 return err;
2635 if (path && path[0] != '\0') {
2636 int obj_type;
2637 err = got_object_id_by_path(&obj_id2, repo, id, path);
2638 if (err)
2639 goto done;
2640 err = got_object_id_str(&id_str2, obj_id2);
2641 if (err) {
2642 free(obj_id2);
2643 goto done;
2645 if (pcommit) {
2646 err = got_object_id_by_path(&obj_id1, repo,
2647 qid->id, path);
2648 if (err) {
2649 free(obj_id2);
2650 goto done;
2652 err = got_object_id_str(&id_str1, obj_id1);
2653 if (err) {
2654 free(obj_id2);
2655 goto done;
2658 err = got_object_get_type(&obj_type, repo, obj_id2);
2659 if (err) {
2660 free(obj_id2);
2661 goto done;
2663 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2664 switch (obj_type) {
2665 case GOT_OBJ_TYPE_BLOB:
2666 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
2667 0, repo);
2668 break;
2669 case GOT_OBJ_TYPE_TREE:
2670 err = diff_trees(obj_id1, obj_id2, path, diff_context,
2671 0, repo);
2672 break;
2673 default:
2674 err = got_error(GOT_ERR_OBJ_TYPE);
2675 break;
2677 free(obj_id1);
2678 free(obj_id2);
2679 } else {
2680 obj_id2 = got_object_commit_get_tree_id(commit);
2681 err = got_object_id_str(&id_str2, obj_id2);
2682 if (err)
2683 goto done;
2684 obj_id1 = got_object_commit_get_tree_id(pcommit);
2685 err = got_object_id_str(&id_str1, obj_id1);
2686 if (err)
2687 goto done;
2688 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2689 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
2691 done:
2692 free(id_str1);
2693 free(id_str2);
2694 if (pcommit)
2695 got_object_commit_close(pcommit);
2696 return err;
2699 static char *
2700 get_datestr(time_t *time, char *datebuf)
2702 struct tm mytm, *tm;
2703 char *p, *s;
2705 tm = gmtime_r(time, &mytm);
2706 if (tm == NULL)
2707 return NULL;
2708 s = asctime_r(tm, datebuf);
2709 if (s == NULL)
2710 return NULL;
2711 p = strchr(s, '\n');
2712 if (p)
2713 *p = '\0';
2714 return s;
2717 static const struct got_error *
2718 match_logmsg(int *have_match, struct got_object_id *id,
2719 struct got_commit_object *commit, regex_t *regex)
2721 const struct got_error *err = NULL;
2722 regmatch_t regmatch;
2723 char *id_str = NULL, *logmsg = NULL;
2725 *have_match = 0;
2727 err = got_object_id_str(&id_str, id);
2728 if (err)
2729 return err;
2731 err = got_object_commit_get_logmsg(&logmsg, commit);
2732 if (err)
2733 goto done;
2735 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2736 *have_match = 1;
2737 done:
2738 free(id_str);
2739 free(logmsg);
2740 return err;
2743 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
2745 static const struct got_error *
2746 print_commit(struct got_commit_object *commit, struct got_object_id *id,
2747 struct got_repository *repo, const char *path, int show_patch,
2748 int diff_context, struct got_reflist_head *refs)
2750 const struct got_error *err = NULL;
2751 char *id_str, *datestr, *logmsg0, *logmsg, *line;
2752 char datebuf[26];
2753 time_t committer_time;
2754 const char *author, *committer;
2755 char *refs_str = NULL;
2756 struct got_reflist_entry *re;
2758 SIMPLEQ_FOREACH(re, refs, entry) {
2759 char *s;
2760 const char *name;
2761 struct got_tag_object *tag = NULL;
2762 int cmp;
2764 name = got_ref_get_name(re->ref);
2765 if (strcmp(name, GOT_REF_HEAD) == 0)
2766 continue;
2767 if (strncmp(name, "refs/", 5) == 0)
2768 name += 5;
2769 if (strncmp(name, "got/", 4) == 0)
2770 continue;
2771 if (strncmp(name, "heads/", 6) == 0)
2772 name += 6;
2773 if (strncmp(name, "remotes/", 8) == 0)
2774 name += 8;
2775 if (strncmp(name, "tags/", 5) == 0) {
2776 err = got_object_open_as_tag(&tag, repo, re->id);
2777 if (err) {
2778 if (err->code != GOT_ERR_OBJ_TYPE)
2779 return err;
2780 /* Ref points at something other than a tag. */
2781 err = NULL;
2782 tag = NULL;
2785 cmp = got_object_id_cmp(tag ?
2786 got_object_tag_get_object_id(tag) : re->id, id);
2787 if (tag)
2788 got_object_tag_close(tag);
2789 if (cmp != 0)
2790 continue;
2791 s = refs_str;
2792 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
2793 name) == -1) {
2794 err = got_error_from_errno("asprintf");
2795 free(s);
2796 return err;
2798 free(s);
2800 err = got_object_id_str(&id_str, id);
2801 if (err)
2802 return err;
2804 printf(GOT_COMMIT_SEP_STR);
2805 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
2806 refs_str ? refs_str : "", refs_str ? ")" : "");
2807 free(id_str);
2808 id_str = NULL;
2809 free(refs_str);
2810 refs_str = NULL;
2811 printf("from: %s\n", got_object_commit_get_author(commit));
2812 committer_time = got_object_commit_get_committer_time(commit);
2813 datestr = get_datestr(&committer_time, datebuf);
2814 if (datestr)
2815 printf("date: %s UTC\n", datestr);
2816 author = got_object_commit_get_author(commit);
2817 committer = got_object_commit_get_committer(commit);
2818 if (strcmp(author, committer) != 0)
2819 printf("via: %s\n", committer);
2820 if (got_object_commit_get_nparents(commit) > 1) {
2821 const struct got_object_id_queue *parent_ids;
2822 struct got_object_qid *qid;
2823 int n = 1;
2824 parent_ids = got_object_commit_get_parent_ids(commit);
2825 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
2826 err = got_object_id_str(&id_str, qid->id);
2827 if (err)
2828 return err;
2829 printf("parent %d: %s\n", n++, id_str);
2830 free(id_str);
2834 err = got_object_commit_get_logmsg(&logmsg0, commit);
2835 if (err)
2836 return err;
2838 logmsg = logmsg0;
2839 do {
2840 line = strsep(&logmsg, "\n");
2841 if (line)
2842 printf(" %s\n", line);
2843 } while (line);
2844 free(logmsg0);
2846 if (show_patch) {
2847 err = print_patch(commit, id, path, diff_context, repo);
2848 if (err == 0)
2849 printf("\n");
2852 if (fflush(stdout) != 0 && err == NULL)
2853 err = got_error_from_errno("fflush");
2854 return err;
2857 static const struct got_error *
2858 print_commits(struct got_object_id *root_id, struct got_repository *repo,
2859 const char *path, int show_patch, const char *search_pattern,
2860 int diff_context, int limit, int log_branches,
2861 struct got_reflist_head *refs)
2863 const struct got_error *err;
2864 struct got_commit_graph *graph;
2865 regex_t regex;
2866 int have_match;
2868 if (search_pattern &&
2869 regcomp(&regex, search_pattern, REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
2870 return got_error_msg(GOT_ERR_REGEX, search_pattern);
2872 err = got_commit_graph_open(&graph, path, !log_branches);
2873 if (err)
2874 return err;
2875 err = got_commit_graph_iter_start(graph, root_id, repo,
2876 check_cancelled, NULL);
2877 if (err)
2878 goto done;
2879 for (;;) {
2880 struct got_commit_object *commit;
2881 struct got_object_id *id;
2883 if (sigint_received || sigpipe_received)
2884 break;
2886 err = got_commit_graph_iter_next(&id, graph, repo,
2887 check_cancelled, NULL);
2888 if (err) {
2889 if (err->code == GOT_ERR_ITER_COMPLETED)
2890 err = NULL;
2891 break;
2893 if (id == NULL)
2894 break;
2896 err = got_object_open_as_commit(&commit, repo, id);
2897 if (err)
2898 break;
2900 if (search_pattern) {
2901 err = match_logmsg(&have_match, id, commit, &regex);
2902 if (err) {
2903 got_object_commit_close(commit);
2904 break;
2906 if (have_match == 0) {
2907 got_object_commit_close(commit);
2908 continue;
2912 err = print_commit(commit, id, repo, path, show_patch,
2913 diff_context, refs);
2914 got_object_commit_close(commit);
2915 if (err || (limit && --limit == 0))
2916 break;
2918 done:
2919 if (search_pattern)
2920 regfree(&regex);
2921 got_commit_graph_close(graph);
2922 return err;
2925 __dead static void
2926 usage_log(void)
2928 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] [-p] "
2929 "[-s search-pattern] [-r repository-path] [path]\n", getprogname());
2930 exit(1);
2933 static int
2934 get_default_log_limit(void)
2936 const char *got_default_log_limit;
2937 long long n;
2938 const char *errstr;
2940 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
2941 if (got_default_log_limit == NULL)
2942 return 0;
2943 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
2944 if (errstr != NULL)
2945 return 0;
2946 return n;
2949 static const struct got_error *
2950 cmd_log(int argc, char *argv[])
2952 const struct got_error *error;
2953 struct got_repository *repo = NULL;
2954 struct got_worktree *worktree = NULL;
2955 struct got_commit_object *commit = NULL;
2956 struct got_object_id *id = NULL;
2957 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
2958 const char *start_commit = NULL, *search_pattern = NULL;
2959 int diff_context = -1, ch;
2960 int show_patch = 0, limit = 0, log_branches = 0;
2961 const char *errstr;
2962 struct got_reflist_head refs;
2964 SIMPLEQ_INIT(&refs);
2966 #ifndef PROFILE
2967 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
2968 NULL)
2969 == -1)
2970 err(1, "pledge");
2971 #endif
2973 limit = get_default_log_limit();
2975 while ((ch = getopt(argc, argv, "bpc:C:l:r:s:")) != -1) {
2976 switch (ch) {
2977 case 'p':
2978 show_patch = 1;
2979 break;
2980 case 'c':
2981 start_commit = optarg;
2982 break;
2983 case 'C':
2984 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
2985 &errstr);
2986 if (errstr != NULL)
2987 err(1, "-C option %s", errstr);
2988 break;
2989 case 'l':
2990 limit = strtonum(optarg, 0, INT_MAX, &errstr);
2991 if (errstr != NULL)
2992 err(1, "-l option %s", errstr);
2993 break;
2994 case 'b':
2995 log_branches = 1;
2996 break;
2997 case 'r':
2998 repo_path = realpath(optarg, NULL);
2999 if (repo_path == NULL)
3000 return got_error_from_errno2("realpath",
3001 optarg);
3002 got_path_strip_trailing_slashes(repo_path);
3003 break;
3004 case 's':
3005 search_pattern = optarg;
3006 break;
3007 default:
3008 usage_log();
3009 /* NOTREACHED */
3013 argc -= optind;
3014 argv += optind;
3016 if (diff_context == -1)
3017 diff_context = 3;
3018 else if (!show_patch)
3019 errx(1, "-C reguires -p");
3021 cwd = getcwd(NULL, 0);
3022 if (cwd == NULL) {
3023 error = got_error_from_errno("getcwd");
3024 goto done;
3027 error = got_worktree_open(&worktree, cwd);
3028 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3029 goto done;
3030 error = NULL;
3032 if (argc == 0) {
3033 path = strdup("");
3034 if (path == NULL) {
3035 error = got_error_from_errno("strdup");
3036 goto done;
3038 } else if (argc == 1) {
3039 if (worktree) {
3040 error = got_worktree_resolve_path(&path, worktree,
3041 argv[0]);
3042 if (error)
3043 goto done;
3044 } else {
3045 path = strdup(argv[0]);
3046 if (path == NULL) {
3047 error = got_error_from_errno("strdup");
3048 goto done;
3051 } else
3052 usage_log();
3054 if (repo_path == NULL) {
3055 repo_path = worktree ?
3056 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3058 if (repo_path == NULL) {
3059 error = got_error_from_errno("strdup");
3060 goto done;
3063 error = got_repo_open(&repo, repo_path, NULL);
3064 if (error != NULL)
3065 goto done;
3067 error = apply_unveil(got_repo_get_path(repo), 1,
3068 worktree ? got_worktree_get_root_path(worktree) : NULL);
3069 if (error)
3070 goto done;
3072 if (start_commit == NULL) {
3073 struct got_reference *head_ref;
3074 error = got_ref_open(&head_ref, repo,
3075 worktree ? got_worktree_get_head_ref_name(worktree)
3076 : GOT_REF_HEAD, 0);
3077 if (error != NULL)
3078 return error;
3079 error = got_ref_resolve(&id, repo, head_ref);
3080 got_ref_close(head_ref);
3081 if (error != NULL)
3082 return error;
3083 error = got_object_open_as_commit(&commit, repo, id);
3084 } else {
3085 struct got_reference *ref;
3086 error = got_ref_open(&ref, repo, start_commit, 0);
3087 if (error == NULL) {
3088 int obj_type;
3089 error = got_ref_resolve(&id, repo, ref);
3090 got_ref_close(ref);
3091 if (error != NULL)
3092 goto done;
3093 error = got_object_get_type(&obj_type, repo, id);
3094 if (error != NULL)
3095 goto done;
3096 if (obj_type == GOT_OBJ_TYPE_TAG) {
3097 struct got_tag_object *tag;
3098 error = got_object_open_as_tag(&tag, repo, id);
3099 if (error != NULL)
3100 goto done;
3101 if (got_object_tag_get_object_type(tag) !=
3102 GOT_OBJ_TYPE_COMMIT) {
3103 got_object_tag_close(tag);
3104 error = got_error(GOT_ERR_OBJ_TYPE);
3105 goto done;
3107 free(id);
3108 id = got_object_id_dup(
3109 got_object_tag_get_object_id(tag));
3110 if (id == NULL)
3111 error = got_error_from_errno(
3112 "got_object_id_dup");
3113 got_object_tag_close(tag);
3114 if (error)
3115 goto done;
3116 } else if (obj_type != GOT_OBJ_TYPE_COMMIT) {
3117 error = got_error(GOT_ERR_OBJ_TYPE);
3118 goto done;
3120 error = got_object_open_as_commit(&commit, repo, id);
3121 if (error != NULL)
3122 goto done;
3124 if (commit == NULL) {
3125 error = got_repo_match_object_id_prefix(&id,
3126 start_commit, GOT_OBJ_TYPE_COMMIT, repo);
3127 if (error != NULL)
3128 return error;
3131 if (error != NULL)
3132 goto done;
3134 if (worktree) {
3135 const char *prefix = got_worktree_get_path_prefix(worktree);
3136 char *p;
3137 if (asprintf(&p, "%s%s%s", prefix,
3138 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3139 error = got_error_from_errno("asprintf");
3140 goto done;
3142 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3143 free(p);
3144 } else
3145 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3146 if (error != NULL)
3147 goto done;
3148 if (in_repo_path) {
3149 free(path);
3150 path = in_repo_path;
3153 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3154 if (error)
3155 goto done;
3157 error = print_commits(id, repo, path, show_patch, search_pattern,
3158 diff_context, limit, log_branches, &refs);
3159 done:
3160 free(path);
3161 free(repo_path);
3162 free(cwd);
3163 free(id);
3164 if (worktree)
3165 got_worktree_close(worktree);
3166 if (repo) {
3167 const struct got_error *repo_error;
3168 repo_error = got_repo_close(repo);
3169 if (error == NULL)
3170 error = repo_error;
3172 got_ref_list_free(&refs);
3173 return error;
3176 __dead static void
3177 usage_diff(void)
3179 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3180 "[-w] [object1 object2 | path]\n", getprogname());
3181 exit(1);
3184 struct print_diff_arg {
3185 struct got_repository *repo;
3186 struct got_worktree *worktree;
3187 int diff_context;
3188 const char *id_str;
3189 int header_shown;
3190 int diff_staged;
3191 int ignore_whitespace;
3194 static const struct got_error *
3195 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3196 const char *path, struct got_object_id *blob_id,
3197 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3198 int dirfd, const char *de_name)
3200 struct print_diff_arg *a = arg;
3201 const struct got_error *err = NULL;
3202 struct got_blob_object *blob1 = NULL;
3203 int fd = -1;
3204 FILE *f2 = NULL;
3205 char *abspath = NULL, *label1 = NULL;
3206 struct stat sb;
3208 if (a->diff_staged) {
3209 if (staged_status != GOT_STATUS_MODIFY &&
3210 staged_status != GOT_STATUS_ADD &&
3211 staged_status != GOT_STATUS_DELETE)
3212 return NULL;
3213 } else {
3214 if (staged_status == GOT_STATUS_DELETE)
3215 return NULL;
3216 if (status == GOT_STATUS_NONEXISTENT)
3217 return got_error_set_errno(ENOENT, path);
3218 if (status != GOT_STATUS_MODIFY &&
3219 status != GOT_STATUS_ADD &&
3220 status != GOT_STATUS_DELETE &&
3221 status != GOT_STATUS_CONFLICT)
3222 return NULL;
3225 if (!a->header_shown) {
3226 printf("diff %s %s%s\n", a->id_str,
3227 got_worktree_get_root_path(a->worktree),
3228 a->diff_staged ? " (staged changes)" : "");
3229 a->header_shown = 1;
3232 if (a->diff_staged) {
3233 const char *label1 = NULL, *label2 = NULL;
3234 switch (staged_status) {
3235 case GOT_STATUS_MODIFY:
3236 label1 = path;
3237 label2 = path;
3238 break;
3239 case GOT_STATUS_ADD:
3240 label2 = path;
3241 break;
3242 case GOT_STATUS_DELETE:
3243 label1 = path;
3244 break;
3245 default:
3246 return got_error(GOT_ERR_FILE_STATUS);
3248 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
3249 label1, label2, a->diff_context, a->ignore_whitespace,
3250 a->repo, stdout);
3253 if (staged_status == GOT_STATUS_ADD ||
3254 staged_status == GOT_STATUS_MODIFY) {
3255 char *id_str;
3256 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
3257 8192);
3258 if (err)
3259 goto done;
3260 err = got_object_id_str(&id_str, staged_blob_id);
3261 if (err)
3262 goto done;
3263 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
3264 err = got_error_from_errno("asprintf");
3265 free(id_str);
3266 goto done;
3268 free(id_str);
3269 } else if (status != GOT_STATUS_ADD) {
3270 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
3271 if (err)
3272 goto done;
3275 if (status != GOT_STATUS_DELETE) {
3276 if (asprintf(&abspath, "%s/%s",
3277 got_worktree_get_root_path(a->worktree), path) == -1) {
3278 err = got_error_from_errno("asprintf");
3279 goto done;
3282 if (dirfd != -1) {
3283 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
3284 if (fd == -1) {
3285 err = got_error_from_errno2("openat", abspath);
3286 goto done;
3288 } else {
3289 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
3290 if (fd == -1) {
3291 err = got_error_from_errno2("open", abspath);
3292 goto done;
3295 if (fstat(fd, &sb) == -1) {
3296 err = got_error_from_errno2("fstat", abspath);
3297 goto done;
3299 f2 = fdopen(fd, "r");
3300 if (f2 == NULL) {
3301 err = got_error_from_errno2("fdopen", abspath);
3302 goto done;
3304 fd = -1;
3305 } else
3306 sb.st_size = 0;
3308 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
3309 a->diff_context, a->ignore_whitespace, stdout);
3310 done:
3311 if (blob1)
3312 got_object_blob_close(blob1);
3313 if (f2 && fclose(f2) == EOF && err == NULL)
3314 err = got_error_from_errno("fclose");
3315 if (fd != -1 && close(fd) == -1 && err == NULL)
3316 err = got_error_from_errno("close");
3317 free(abspath);
3318 return err;
3321 static const struct got_error *
3322 cmd_diff(int argc, char *argv[])
3324 const struct got_error *error;
3325 struct got_repository *repo = NULL;
3326 struct got_worktree *worktree = NULL;
3327 char *cwd = NULL, *repo_path = NULL;
3328 struct got_object_id *id1 = NULL, *id2 = NULL;
3329 const char *id_str1 = NULL, *id_str2 = NULL;
3330 char *label1 = NULL, *label2 = NULL;
3331 int type1, type2;
3332 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
3333 const char *errstr;
3334 char *path = NULL;
3336 #ifndef PROFILE
3337 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3338 NULL) == -1)
3339 err(1, "pledge");
3340 #endif
3342 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
3343 switch (ch) {
3344 case 'C':
3345 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3346 &errstr);
3347 if (errstr != NULL)
3348 err(1, "-C option %s", errstr);
3349 break;
3350 case 'r':
3351 repo_path = realpath(optarg, NULL);
3352 if (repo_path == NULL)
3353 return got_error_from_errno2("realpath",
3354 optarg);
3355 got_path_strip_trailing_slashes(repo_path);
3356 break;
3357 case 's':
3358 diff_staged = 1;
3359 break;
3360 case 'w':
3361 ignore_whitespace = 1;
3362 break;
3363 default:
3364 usage_diff();
3365 /* NOTREACHED */
3369 argc -= optind;
3370 argv += optind;
3372 cwd = getcwd(NULL, 0);
3373 if (cwd == NULL) {
3374 error = got_error_from_errno("getcwd");
3375 goto done;
3377 if (argc <= 1) {
3378 if (repo_path)
3379 errx(1,
3380 "-r option can't be used when diffing a work tree");
3381 error = got_worktree_open(&worktree, cwd);
3382 if (error)
3383 goto done;
3384 repo_path = strdup(got_worktree_get_repo_path(worktree));
3385 if (repo_path == NULL) {
3386 error = got_error_from_errno("strdup");
3387 goto done;
3389 if (argc == 1) {
3390 error = got_worktree_resolve_path(&path, worktree,
3391 argv[0]);
3392 if (error)
3393 goto done;
3394 } else {
3395 path = strdup("");
3396 if (path == NULL) {
3397 error = got_error_from_errno("strdup");
3398 goto done;
3401 } else if (argc == 2) {
3402 if (diff_staged)
3403 errx(1, "-s option can't be used when diffing "
3404 "objects in repository");
3405 id_str1 = argv[0];
3406 id_str2 = argv[1];
3407 if (repo_path == NULL) {
3408 error = got_worktree_open(&worktree, cwd);
3409 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3410 goto done;
3411 if (worktree) {
3412 repo_path = strdup(
3413 got_worktree_get_repo_path(worktree));
3414 if (repo_path == NULL) {
3415 error = got_error_from_errno("strdup");
3416 goto done;
3418 } else {
3419 repo_path = strdup(cwd);
3420 if (repo_path == NULL) {
3421 error = got_error_from_errno("strdup");
3422 goto done;
3426 } else
3427 usage_diff();
3429 error = got_repo_open(&repo, repo_path, NULL);
3430 free(repo_path);
3431 if (error != NULL)
3432 goto done;
3434 error = apply_unveil(got_repo_get_path(repo), 1,
3435 worktree ? got_worktree_get_root_path(worktree) : NULL);
3436 if (error)
3437 goto done;
3439 if (argc <= 1) {
3440 struct print_diff_arg arg;
3441 struct got_pathlist_head paths;
3442 char *id_str;
3444 TAILQ_INIT(&paths);
3446 error = got_object_id_str(&id_str,
3447 got_worktree_get_base_commit_id(worktree));
3448 if (error)
3449 goto done;
3450 arg.repo = repo;
3451 arg.worktree = worktree;
3452 arg.diff_context = diff_context;
3453 arg.id_str = id_str;
3454 arg.header_shown = 0;
3455 arg.diff_staged = diff_staged;
3456 arg.ignore_whitespace = ignore_whitespace;
3458 error = got_pathlist_append(&paths, path, NULL);
3459 if (error)
3460 goto done;
3462 error = got_worktree_status(worktree, &paths, repo, print_diff,
3463 &arg, check_cancelled, NULL);
3464 free(id_str);
3465 got_pathlist_free(&paths);
3466 goto done;
3469 error = got_repo_match_object_id(&id1, &label1, id_str1,
3470 GOT_OBJ_TYPE_ANY, 1, repo);
3471 if (error)
3472 goto done;
3474 error = got_repo_match_object_id(&id2, &label2, id_str2,
3475 GOT_OBJ_TYPE_ANY, 1, repo);
3476 if (error)
3477 goto done;
3479 error = got_object_get_type(&type1, repo, id1);
3480 if (error)
3481 goto done;
3483 error = got_object_get_type(&type2, repo, id2);
3484 if (error)
3485 goto done;
3487 if (type1 != type2) {
3488 error = got_error(GOT_ERR_OBJ_TYPE);
3489 goto done;
3492 switch (type1) {
3493 case GOT_OBJ_TYPE_BLOB:
3494 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
3495 diff_context, ignore_whitespace, repo, stdout);
3496 break;
3497 case GOT_OBJ_TYPE_TREE:
3498 error = got_diff_objects_as_trees(id1, id2, "", "",
3499 diff_context, ignore_whitespace, repo, stdout);
3500 break;
3501 case GOT_OBJ_TYPE_COMMIT:
3502 printf("diff %s %s\n", label1, label2);
3503 error = got_diff_objects_as_commits(id1, id2, diff_context,
3504 ignore_whitespace, repo, stdout);
3505 break;
3506 default:
3507 error = got_error(GOT_ERR_OBJ_TYPE);
3509 done:
3510 free(label1);
3511 free(label2);
3512 free(id1);
3513 free(id2);
3514 free(path);
3515 if (worktree)
3516 got_worktree_close(worktree);
3517 if (repo) {
3518 const struct got_error *repo_error;
3519 repo_error = got_repo_close(repo);
3520 if (error == NULL)
3521 error = repo_error;
3523 return error;
3526 __dead static void
3527 usage_blame(void)
3529 fprintf(stderr,
3530 "usage: %s blame [-c commit] [-r repository-path] path\n",
3531 getprogname());
3532 exit(1);
3535 struct blame_line {
3536 int annotated;
3537 char *id_str;
3538 char *committer;
3539 char datebuf[11]; /* YYYY-MM-DD + NUL */
3542 struct blame_cb_args {
3543 struct blame_line *lines;
3544 int nlines;
3545 int nlines_prec;
3546 int lineno_cur;
3547 off_t *line_offsets;
3548 FILE *f;
3549 struct got_repository *repo;
3552 static const struct got_error *
3553 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
3555 const struct got_error *err = NULL;
3556 struct blame_cb_args *a = arg;
3557 struct blame_line *bline;
3558 char *line = NULL;
3559 size_t linesize = 0;
3560 struct got_commit_object *commit = NULL;
3561 off_t offset;
3562 struct tm tm;
3563 time_t committer_time;
3565 if (nlines != a->nlines ||
3566 (lineno != -1 && lineno < 1) || lineno > a->nlines)
3567 return got_error(GOT_ERR_RANGE);
3569 if (sigint_received)
3570 return got_error(GOT_ERR_ITER_COMPLETED);
3572 if (lineno == -1)
3573 return NULL; /* no change in this commit */
3575 /* Annotate this line. */
3576 bline = &a->lines[lineno - 1];
3577 if (bline->annotated)
3578 return NULL;
3579 err = got_object_id_str(&bline->id_str, id);
3580 if (err)
3581 return err;
3583 err = got_object_open_as_commit(&commit, a->repo, id);
3584 if (err)
3585 goto done;
3587 bline->committer = strdup(got_object_commit_get_committer(commit));
3588 if (bline->committer == NULL) {
3589 err = got_error_from_errno("strdup");
3590 goto done;
3593 committer_time = got_object_commit_get_committer_time(commit);
3594 if (localtime_r(&committer_time, &tm) == NULL)
3595 return got_error_from_errno("localtime_r");
3596 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
3597 &tm) >= sizeof(bline->datebuf)) {
3598 err = got_error(GOT_ERR_NO_SPACE);
3599 goto done;
3601 bline->annotated = 1;
3603 /* Print lines annotated so far. */
3604 bline = &a->lines[a->lineno_cur - 1];
3605 if (!bline->annotated)
3606 goto done;
3608 offset = a->line_offsets[a->lineno_cur - 1];
3609 if (fseeko(a->f, offset, SEEK_SET) == -1) {
3610 err = got_error_from_errno("fseeko");
3611 goto done;
3614 while (bline->annotated) {
3615 char *smallerthan, *at, *nl, *committer;
3616 size_t len;
3618 if (getline(&line, &linesize, a->f) == -1) {
3619 if (ferror(a->f))
3620 err = got_error_from_errno("getline");
3621 break;
3624 committer = bline->committer;
3625 smallerthan = strchr(committer, '<');
3626 if (smallerthan && smallerthan[1] != '\0')
3627 committer = smallerthan + 1;
3628 at = strchr(committer, '@');
3629 if (at)
3630 *at = '\0';
3631 len = strlen(committer);
3632 if (len >= 9)
3633 committer[8] = '\0';
3635 nl = strchr(line, '\n');
3636 if (nl)
3637 *nl = '\0';
3638 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
3639 bline->id_str, bline->datebuf, committer, line);
3641 a->lineno_cur++;
3642 bline = &a->lines[a->lineno_cur - 1];
3644 done:
3645 if (commit)
3646 got_object_commit_close(commit);
3647 free(line);
3648 return err;
3651 static const struct got_error *
3652 cmd_blame(int argc, char *argv[])
3654 const struct got_error *error;
3655 struct got_repository *repo = NULL;
3656 struct got_worktree *worktree = NULL;
3657 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
3658 struct got_object_id *obj_id = NULL;
3659 struct got_object_id *commit_id = NULL;
3660 struct got_blob_object *blob = NULL;
3661 char *commit_id_str = NULL;
3662 struct blame_cb_args bca;
3663 int ch, obj_type, i;
3664 size_t filesize;
3666 memset(&bca, 0, sizeof(bca));
3668 #ifndef PROFILE
3669 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3670 NULL) == -1)
3671 err(1, "pledge");
3672 #endif
3674 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
3675 switch (ch) {
3676 case 'c':
3677 commit_id_str = optarg;
3678 break;
3679 case 'r':
3680 repo_path = realpath(optarg, NULL);
3681 if (repo_path == NULL)
3682 return got_error_from_errno2("realpath",
3683 optarg);
3684 got_path_strip_trailing_slashes(repo_path);
3685 break;
3686 default:
3687 usage_blame();
3688 /* NOTREACHED */
3692 argc -= optind;
3693 argv += optind;
3695 if (argc == 1)
3696 path = argv[0];
3697 else
3698 usage_blame();
3700 cwd = getcwd(NULL, 0);
3701 if (cwd == NULL) {
3702 error = got_error_from_errno("getcwd");
3703 goto done;
3705 if (repo_path == NULL) {
3706 error = got_worktree_open(&worktree, cwd);
3707 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3708 goto done;
3709 else
3710 error = NULL;
3711 if (worktree) {
3712 repo_path =
3713 strdup(got_worktree_get_repo_path(worktree));
3714 if (repo_path == NULL) {
3715 error = got_error_from_errno("strdup");
3716 if (error)
3717 goto done;
3719 } else {
3720 repo_path = strdup(cwd);
3721 if (repo_path == NULL) {
3722 error = got_error_from_errno("strdup");
3723 goto done;
3728 error = got_repo_open(&repo, repo_path, NULL);
3729 if (error != NULL)
3730 goto done;
3732 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
3733 if (error)
3734 goto done;
3736 if (worktree) {
3737 const char *prefix = got_worktree_get_path_prefix(worktree);
3738 char *p, *worktree_subdir = cwd +
3739 strlen(got_worktree_get_root_path(worktree));
3740 if (asprintf(&p, "%s%s%s%s%s",
3741 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
3742 worktree_subdir, worktree_subdir[0] ? "/" : "",
3743 path) == -1) {
3744 error = got_error_from_errno("asprintf");
3745 goto done;
3747 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3748 free(p);
3749 } else {
3750 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3752 if (error)
3753 goto done;
3755 if (commit_id_str == NULL) {
3756 struct got_reference *head_ref;
3757 error = got_ref_open(&head_ref, repo, worktree ?
3758 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
3759 if (error != NULL)
3760 goto done;
3761 error = got_ref_resolve(&commit_id, repo, head_ref);
3762 got_ref_close(head_ref);
3763 if (error != NULL)
3764 goto done;
3765 } else {
3766 error = got_repo_match_object_id(&commit_id, NULL,
3767 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
3768 if (error)
3769 goto done;
3772 error = got_object_id_by_path(&obj_id, repo, commit_id, in_repo_path);
3773 if (error)
3774 goto done;
3776 error = got_object_get_type(&obj_type, repo, obj_id);
3777 if (error)
3778 goto done;
3780 if (obj_type != GOT_OBJ_TYPE_BLOB) {
3781 error = got_error(GOT_ERR_OBJ_TYPE);
3782 goto done;
3785 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
3786 if (error)
3787 goto done;
3788 bca.f = got_opentemp();
3789 if (bca.f == NULL) {
3790 error = got_error_from_errno("got_opentemp");
3791 goto done;
3793 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
3794 &bca.line_offsets, bca.f, blob);
3795 if (error || bca.nlines == 0)
3796 goto done;
3798 /* Don't include \n at EOF in the blame line count. */
3799 if (bca.line_offsets[bca.nlines - 1] == filesize)
3800 bca.nlines--;
3802 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
3803 if (bca.lines == NULL) {
3804 error = got_error_from_errno("calloc");
3805 goto done;
3807 bca.lineno_cur = 1;
3808 bca.nlines_prec = 0;
3809 i = bca.nlines;
3810 while (i > 0) {
3811 i /= 10;
3812 bca.nlines_prec++;
3814 bca.repo = repo;
3816 error = got_blame(in_repo_path, commit_id, repo, blame_cb, &bca,
3817 check_cancelled, NULL);
3818 done:
3819 free(in_repo_path);
3820 free(repo_path);
3821 free(cwd);
3822 free(commit_id);
3823 free(obj_id);
3824 if (blob)
3825 got_object_blob_close(blob);
3826 if (worktree)
3827 got_worktree_close(worktree);
3828 if (repo) {
3829 const struct got_error *repo_error;
3830 repo_error = got_repo_close(repo);
3831 if (error == NULL)
3832 error = repo_error;
3834 if (bca.lines) {
3835 for (i = 0; i < bca.nlines; i++) {
3836 struct blame_line *bline = &bca.lines[i];
3837 free(bline->id_str);
3838 free(bline->committer);
3840 free(bca.lines);
3842 free(bca.line_offsets);
3843 if (bca.f && fclose(bca.f) == EOF && error == NULL)
3844 error = got_error_from_errno("fclose");
3845 return error;
3848 __dead static void
3849 usage_tree(void)
3851 fprintf(stderr,
3852 "usage: %s tree [-c commit] [-r repository-path] [-iR] path\n",
3853 getprogname());
3854 exit(1);
3857 static void
3858 print_entry(struct got_tree_entry *te, const char *id, const char *path,
3859 const char *root_path)
3861 int is_root_path = (strcmp(path, root_path) == 0);
3862 const char *modestr = "";
3863 mode_t mode = got_tree_entry_get_mode(te);
3865 path += strlen(root_path);
3866 while (path[0] == '/')
3867 path++;
3869 if (got_object_tree_entry_is_submodule(te))
3870 modestr = "$";
3871 else if (S_ISLNK(mode))
3872 modestr = "@";
3873 else if (S_ISDIR(mode))
3874 modestr = "/";
3875 else if (mode & S_IXUSR)
3876 modestr = "*";
3878 printf("%s%s%s%s%s\n", id ? id : "", path,
3879 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr);
3882 static const struct got_error *
3883 print_tree(const char *path, struct got_object_id *commit_id,
3884 int show_ids, int recurse, const char *root_path,
3885 struct got_repository *repo)
3887 const struct got_error *err = NULL;
3888 struct got_object_id *tree_id = NULL;
3889 struct got_tree_object *tree = NULL;
3890 int nentries, i;
3892 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
3893 if (err)
3894 goto done;
3896 err = got_object_open_as_tree(&tree, repo, tree_id);
3897 if (err)
3898 goto done;
3899 nentries = got_object_tree_get_nentries(tree);
3900 for (i = 0; i < nentries; i++) {
3901 struct got_tree_entry *te;
3902 char *id = NULL;
3904 if (sigint_received || sigpipe_received)
3905 break;
3907 te = got_object_tree_get_entry(tree, i);
3908 if (show_ids) {
3909 char *id_str;
3910 err = got_object_id_str(&id_str,
3911 got_tree_entry_get_id(te));
3912 if (err)
3913 goto done;
3914 if (asprintf(&id, "%s ", id_str) == -1) {
3915 err = got_error_from_errno("asprintf");
3916 free(id_str);
3917 goto done;
3919 free(id_str);
3921 print_entry(te, id, path, root_path);
3922 free(id);
3924 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
3925 char *child_path;
3926 if (asprintf(&child_path, "%s%s%s", path,
3927 path[0] == '/' && path[1] == '\0' ? "" : "/",
3928 got_tree_entry_get_name(te)) == -1) {
3929 err = got_error_from_errno("asprintf");
3930 goto done;
3932 err = print_tree(child_path, commit_id, show_ids, 1,
3933 root_path, repo);
3934 free(child_path);
3935 if (err)
3936 goto done;
3939 done:
3940 if (tree)
3941 got_object_tree_close(tree);
3942 free(tree_id);
3943 return err;
3946 static const struct got_error *
3947 cmd_tree(int argc, char *argv[])
3949 const struct got_error *error;
3950 struct got_repository *repo = NULL;
3951 struct got_worktree *worktree = NULL;
3952 const char *path;
3953 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
3954 struct got_object_id *commit_id = NULL;
3955 char *commit_id_str = NULL;
3956 int show_ids = 0, recurse = 0;
3957 int ch;
3959 #ifndef PROFILE
3960 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3961 NULL) == -1)
3962 err(1, "pledge");
3963 #endif
3965 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
3966 switch (ch) {
3967 case 'c':
3968 commit_id_str = optarg;
3969 break;
3970 case 'r':
3971 repo_path = realpath(optarg, NULL);
3972 if (repo_path == NULL)
3973 return got_error_from_errno2("realpath",
3974 optarg);
3975 got_path_strip_trailing_slashes(repo_path);
3976 break;
3977 case 'i':
3978 show_ids = 1;
3979 break;
3980 case 'R':
3981 recurse = 1;
3982 break;
3983 default:
3984 usage_tree();
3985 /* NOTREACHED */
3989 argc -= optind;
3990 argv += optind;
3992 if (argc == 1)
3993 path = argv[0];
3994 else if (argc > 1)
3995 usage_tree();
3996 else
3997 path = NULL;
3999 cwd = getcwd(NULL, 0);
4000 if (cwd == NULL) {
4001 error = got_error_from_errno("getcwd");
4002 goto done;
4004 if (repo_path == NULL) {
4005 error = got_worktree_open(&worktree, cwd);
4006 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4007 goto done;
4008 else
4009 error = NULL;
4010 if (worktree) {
4011 repo_path =
4012 strdup(got_worktree_get_repo_path(worktree));
4013 if (repo_path == NULL)
4014 error = got_error_from_errno("strdup");
4015 if (error)
4016 goto done;
4017 } else {
4018 repo_path = strdup(cwd);
4019 if (repo_path == NULL) {
4020 error = got_error_from_errno("strdup");
4021 goto done;
4026 error = got_repo_open(&repo, repo_path, NULL);
4027 if (error != NULL)
4028 goto done;
4030 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4031 if (error)
4032 goto done;
4034 if (path == NULL) {
4035 if (worktree) {
4036 char *p, *worktree_subdir = cwd +
4037 strlen(got_worktree_get_root_path(worktree));
4038 if (asprintf(&p, "%s/%s",
4039 got_worktree_get_path_prefix(worktree),
4040 worktree_subdir) == -1) {
4041 error = got_error_from_errno("asprintf");
4042 goto done;
4044 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4045 free(p);
4046 if (error)
4047 goto done;
4048 } else
4049 path = "/";
4051 if (in_repo_path == NULL) {
4052 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4053 if (error != NULL)
4054 goto done;
4057 if (commit_id_str == NULL) {
4058 struct got_reference *head_ref;
4059 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
4060 if (error != NULL)
4061 goto done;
4062 error = got_ref_resolve(&commit_id, repo, head_ref);
4063 got_ref_close(head_ref);
4064 if (error != NULL)
4065 goto done;
4066 } else {
4067 error = got_repo_match_object_id(&commit_id, NULL,
4068 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4069 if (error)
4070 goto done;
4073 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4074 in_repo_path, repo);
4075 done:
4076 free(in_repo_path);
4077 free(repo_path);
4078 free(cwd);
4079 free(commit_id);
4080 if (worktree)
4081 got_worktree_close(worktree);
4082 if (repo) {
4083 const struct got_error *repo_error;
4084 repo_error = got_repo_close(repo);
4085 if (error == NULL)
4086 error = repo_error;
4088 return error;
4091 __dead static void
4092 usage_status(void)
4094 fprintf(stderr, "usage: %s status [path ...]\n", getprogname());
4095 exit(1);
4098 static const struct got_error *
4099 print_status(void *arg, unsigned char status, unsigned char staged_status,
4100 const char *path, struct got_object_id *blob_id,
4101 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4102 int dirfd, const char *de_name)
4104 if (status == staged_status && (status == GOT_STATUS_DELETE))
4105 status = GOT_STATUS_NO_CHANGE;
4106 printf("%c%c %s\n", status, staged_status, path);
4107 return NULL;
4110 static const struct got_error *
4111 cmd_status(int argc, char *argv[])
4113 const struct got_error *error = NULL;
4114 struct got_repository *repo = NULL;
4115 struct got_worktree *worktree = NULL;
4116 char *cwd = NULL;
4117 struct got_pathlist_head paths;
4118 struct got_pathlist_entry *pe;
4119 int ch;
4121 TAILQ_INIT(&paths);
4123 while ((ch = getopt(argc, argv, "")) != -1) {
4124 switch (ch) {
4125 default:
4126 usage_status();
4127 /* NOTREACHED */
4131 argc -= optind;
4132 argv += optind;
4134 #ifndef PROFILE
4135 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4136 NULL) == -1)
4137 err(1, "pledge");
4138 #endif
4139 cwd = getcwd(NULL, 0);
4140 if (cwd == NULL) {
4141 error = got_error_from_errno("getcwd");
4142 goto done;
4145 error = got_worktree_open(&worktree, cwd);
4146 if (error != NULL)
4147 goto done;
4149 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4150 NULL);
4151 if (error != NULL)
4152 goto done;
4154 error = apply_unveil(got_repo_get_path(repo), 1,
4155 got_worktree_get_root_path(worktree));
4156 if (error)
4157 goto done;
4159 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
4160 if (error)
4161 goto done;
4163 error = got_worktree_status(worktree, &paths, repo, print_status, NULL,
4164 check_cancelled, NULL);
4165 done:
4166 TAILQ_FOREACH(pe, &paths, entry)
4167 free((char *)pe->path);
4168 got_pathlist_free(&paths);
4169 free(cwd);
4170 return error;
4173 __dead static void
4174 usage_ref(void)
4176 fprintf(stderr,
4177 "usage: %s ref [-r repository] -l | -d name | [-s] name target\n",
4178 getprogname());
4179 exit(1);
4182 static const struct got_error *
4183 list_refs(struct got_repository *repo)
4185 static const struct got_error *err = NULL;
4186 struct got_reflist_head refs;
4187 struct got_reflist_entry *re;
4189 SIMPLEQ_INIT(&refs);
4190 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4191 if (err)
4192 return err;
4194 SIMPLEQ_FOREACH(re, &refs, entry) {
4195 char *refstr;
4196 refstr = got_ref_to_str(re->ref);
4197 if (refstr == NULL)
4198 return got_error_from_errno("got_ref_to_str");
4199 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
4200 free(refstr);
4203 got_ref_list_free(&refs);
4204 return NULL;
4207 static const struct got_error *
4208 delete_ref(struct got_repository *repo, const char *refname)
4210 const struct got_error *err = NULL;
4211 struct got_reference *ref;
4213 err = got_ref_open(&ref, repo, refname, 0);
4214 if (err)
4215 return err;
4217 err = got_ref_delete(ref, repo);
4218 got_ref_close(ref);
4219 return err;
4222 static const struct got_error *
4223 add_ref(struct got_repository *repo, const char *refname, const char *target)
4225 const struct got_error *err = NULL;
4226 struct got_object_id *id;
4227 struct got_reference *ref = NULL;
4230 * Don't let the user create a reference name with a leading '-'.
4231 * While technically a valid reference name, this case is usually
4232 * an unintended typo.
4234 if (refname[0] == '-')
4235 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4237 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
4238 repo);
4239 if (err) {
4240 struct got_reference *target_ref;
4242 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
4243 return err;
4244 err = got_ref_open(&target_ref, repo, target, 0);
4245 if (err)
4246 return err;
4247 err = got_ref_resolve(&id, repo, target_ref);
4248 got_ref_close(target_ref);
4249 if (err)
4250 return err;
4253 err = got_ref_alloc(&ref, refname, id);
4254 if (err)
4255 goto done;
4257 err = got_ref_write(ref, repo);
4258 done:
4259 if (ref)
4260 got_ref_close(ref);
4261 free(id);
4262 return err;
4265 static const struct got_error *
4266 add_symref(struct got_repository *repo, const char *refname, const char *target)
4268 const struct got_error *err = NULL;
4269 struct got_reference *ref = NULL;
4270 struct got_reference *target_ref = NULL;
4273 * Don't let the user create a reference name with a leading '-'.
4274 * While technically a valid reference name, this case is usually
4275 * an unintended typo.
4277 if (refname[0] == '-')
4278 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4280 err = got_ref_open(&target_ref, repo, target, 0);
4281 if (err)
4282 return err;
4284 err = got_ref_alloc_symref(&ref, refname, target_ref);
4285 if (err)
4286 goto done;
4288 err = got_ref_write(ref, repo);
4289 done:
4290 if (target_ref)
4291 got_ref_close(target_ref);
4292 if (ref)
4293 got_ref_close(ref);
4294 return err;
4297 static const struct got_error *
4298 cmd_ref(int argc, char *argv[])
4300 const struct got_error *error = NULL;
4301 struct got_repository *repo = NULL;
4302 struct got_worktree *worktree = NULL;
4303 char *cwd = NULL, *repo_path = NULL;
4304 int ch, do_list = 0, create_symref = 0;
4305 const char *delref = NULL;
4307 /* TODO: Add -s option for adding symbolic references. */
4308 while ((ch = getopt(argc, argv, "d:r:ls")) != -1) {
4309 switch (ch) {
4310 case 'd':
4311 delref = optarg;
4312 break;
4313 case 'r':
4314 repo_path = realpath(optarg, NULL);
4315 if (repo_path == NULL)
4316 return got_error_from_errno2("realpath",
4317 optarg);
4318 got_path_strip_trailing_slashes(repo_path);
4319 break;
4320 case 'l':
4321 do_list = 1;
4322 break;
4323 case 's':
4324 create_symref = 1;
4325 break;
4326 default:
4327 usage_ref();
4328 /* NOTREACHED */
4332 if (do_list && delref)
4333 errx(1, "-l and -d options are mutually exclusive\n");
4335 argc -= optind;
4336 argv += optind;
4338 if (do_list || delref) {
4339 if (create_symref)
4340 errx(1, "-s option cannot be used together with the "
4341 "-l or -d options");
4342 if (argc > 0)
4343 usage_ref();
4344 } else if (argc != 2)
4345 usage_ref();
4347 #ifndef PROFILE
4348 if (do_list) {
4349 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4350 NULL) == -1)
4351 err(1, "pledge");
4352 } else {
4353 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4354 "sendfd unveil", NULL) == -1)
4355 err(1, "pledge");
4357 #endif
4358 cwd = getcwd(NULL, 0);
4359 if (cwd == NULL) {
4360 error = got_error_from_errno("getcwd");
4361 goto done;
4364 if (repo_path == NULL) {
4365 error = got_worktree_open(&worktree, cwd);
4366 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4367 goto done;
4368 else
4369 error = NULL;
4370 if (worktree) {
4371 repo_path =
4372 strdup(got_worktree_get_repo_path(worktree));
4373 if (repo_path == NULL)
4374 error = got_error_from_errno("strdup");
4375 if (error)
4376 goto done;
4377 } else {
4378 repo_path = strdup(cwd);
4379 if (repo_path == NULL) {
4380 error = got_error_from_errno("strdup");
4381 goto done;
4386 error = got_repo_open(&repo, repo_path, NULL);
4387 if (error != NULL)
4388 goto done;
4390 error = apply_unveil(got_repo_get_path(repo), do_list,
4391 worktree ? got_worktree_get_root_path(worktree) : NULL);
4392 if (error)
4393 goto done;
4395 if (do_list)
4396 error = list_refs(repo);
4397 else if (delref)
4398 error = delete_ref(repo, delref);
4399 else if (create_symref)
4400 error = add_symref(repo, argv[0], argv[1]);
4401 else
4402 error = add_ref(repo, argv[0], argv[1]);
4403 done:
4404 if (repo)
4405 got_repo_close(repo);
4406 if (worktree)
4407 got_worktree_close(worktree);
4408 free(cwd);
4409 free(repo_path);
4410 return error;
4413 __dead static void
4414 usage_branch(void)
4416 fprintf(stderr,
4417 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
4418 "[name]\n", getprogname());
4419 exit(1);
4422 static const struct got_error *
4423 list_branch(struct got_repository *repo, struct got_worktree *worktree,
4424 struct got_reference *ref)
4426 const struct got_error *err = NULL;
4427 const char *refname, *marker = " ";
4428 char *refstr;
4430 refname = got_ref_get_name(ref);
4431 if (worktree && strcmp(refname,
4432 got_worktree_get_head_ref_name(worktree)) == 0) {
4433 struct got_object_id *id = NULL;
4435 err = got_ref_resolve(&id, repo, ref);
4436 if (err)
4437 return err;
4438 if (got_object_id_cmp(id,
4439 got_worktree_get_base_commit_id(worktree)) == 0)
4440 marker = "* ";
4441 else
4442 marker = "~ ";
4443 free(id);
4446 if (strncmp(refname, "refs/heads/", 11) == 0)
4447 refname += 11;
4448 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4449 refname += 18;
4451 refstr = got_ref_to_str(ref);
4452 if (refstr == NULL)
4453 return got_error_from_errno("got_ref_to_str");
4455 printf("%s%s: %s\n", marker, refname, refstr);
4456 free(refstr);
4457 return NULL;
4460 static const struct got_error *
4461 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
4463 const char *refname;
4465 if (worktree == NULL)
4466 return got_error(GOT_ERR_NOT_WORKTREE);
4468 refname = got_worktree_get_head_ref_name(worktree);
4470 if (strncmp(refname, "refs/heads/", 11) == 0)
4471 refname += 11;
4472 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4473 refname += 18;
4475 printf("%s\n", refname);
4477 return NULL;
4480 static const struct got_error *
4481 list_branches(struct got_repository *repo, struct got_worktree *worktree)
4483 static const struct got_error *err = NULL;
4484 struct got_reflist_head refs;
4485 struct got_reflist_entry *re;
4486 struct got_reference *temp_ref = NULL;
4487 int rebase_in_progress, histedit_in_progress;
4489 SIMPLEQ_INIT(&refs);
4491 if (worktree) {
4492 err = got_worktree_rebase_in_progress(&rebase_in_progress,
4493 worktree);
4494 if (err)
4495 return err;
4497 err = got_worktree_histedit_in_progress(&histedit_in_progress,
4498 worktree);
4499 if (err)
4500 return err;
4502 if (rebase_in_progress || histedit_in_progress) {
4503 err = got_ref_open(&temp_ref, repo,
4504 got_worktree_get_head_ref_name(worktree), 0);
4505 if (err)
4506 return err;
4507 list_branch(repo, worktree, temp_ref);
4508 got_ref_close(temp_ref);
4512 err = got_ref_list(&refs, repo, "refs/heads",
4513 got_ref_cmp_by_name, NULL);
4514 if (err)
4515 return err;
4517 SIMPLEQ_FOREACH(re, &refs, entry)
4518 list_branch(repo, worktree, re->ref);
4520 got_ref_list_free(&refs);
4521 return NULL;
4524 static const struct got_error *
4525 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
4526 const char *branch_name)
4528 const struct got_error *err = NULL;
4529 struct got_reference *ref = NULL;
4530 char *refname;
4532 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
4533 return got_error_from_errno("asprintf");
4535 err = got_ref_open(&ref, repo, refname, 0);
4536 if (err)
4537 goto done;
4539 if (worktree &&
4540 strcmp(got_worktree_get_head_ref_name(worktree),
4541 got_ref_get_name(ref)) == 0) {
4542 err = got_error_msg(GOT_ERR_SAME_BRANCH,
4543 "will not delete this work tree's current branch");
4544 goto done;
4547 err = got_ref_delete(ref, repo);
4548 done:
4549 if (ref)
4550 got_ref_close(ref);
4551 free(refname);
4552 return err;
4555 static const struct got_error *
4556 add_branch(struct got_repository *repo, const char *branch_name,
4557 struct got_object_id *base_commit_id)
4559 const struct got_error *err = NULL;
4560 struct got_reference *ref = NULL;
4561 char *base_refname = NULL, *refname = NULL;
4564 * Don't let the user create a branch name with a leading '-'.
4565 * While technically a valid reference name, this case is usually
4566 * an unintended typo.
4568 if (branch_name[0] == '-')
4569 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
4571 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
4572 err = got_error_from_errno("asprintf");
4573 goto done;
4576 err = got_ref_open(&ref, repo, refname, 0);
4577 if (err == NULL) {
4578 err = got_error(GOT_ERR_BRANCH_EXISTS);
4579 goto done;
4580 } else if (err->code != GOT_ERR_NOT_REF)
4581 goto done;
4583 err = got_ref_alloc(&ref, refname, base_commit_id);
4584 if (err)
4585 goto done;
4587 err = got_ref_write(ref, repo);
4588 done:
4589 if (ref)
4590 got_ref_close(ref);
4591 free(base_refname);
4592 free(refname);
4593 return err;
4596 static const struct got_error *
4597 cmd_branch(int argc, char *argv[])
4599 const struct got_error *error = NULL;
4600 struct got_repository *repo = NULL;
4601 struct got_worktree *worktree = NULL;
4602 char *cwd = NULL, *repo_path = NULL;
4603 int ch, do_list = 0, do_show = 0, do_update = 1;
4604 const char *delref = NULL, *commit_id_arg = NULL;
4605 struct got_reference *ref = NULL;
4606 struct got_pathlist_head paths;
4607 struct got_pathlist_entry *pe;
4608 struct got_object_id *commit_id = NULL;
4609 char *commit_id_str = NULL;
4611 TAILQ_INIT(&paths);
4613 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
4614 switch (ch) {
4615 case 'c':
4616 commit_id_arg = optarg;
4617 break;
4618 case 'd':
4619 delref = optarg;
4620 break;
4621 case 'r':
4622 repo_path = realpath(optarg, NULL);
4623 if (repo_path == NULL)
4624 return got_error_from_errno2("realpath",
4625 optarg);
4626 got_path_strip_trailing_slashes(repo_path);
4627 break;
4628 case 'l':
4629 do_list = 1;
4630 break;
4631 case 'n':
4632 do_update = 0;
4633 break;
4634 default:
4635 usage_branch();
4636 /* NOTREACHED */
4640 if (do_list && delref)
4641 errx(1, "-l and -d options are mutually exclusive\n");
4643 argc -= optind;
4644 argv += optind;
4646 if (!do_list && !delref && argc == 0)
4647 do_show = 1;
4649 if ((do_list || delref || do_show) && commit_id_arg != NULL)
4650 errx(1, "-c option can only be used when creating a branch");
4652 if (do_list || delref) {
4653 if (argc > 0)
4654 usage_branch();
4655 } else if (!do_show && argc != 1)
4656 usage_branch();
4658 #ifndef PROFILE
4659 if (do_list || do_show) {
4660 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4661 NULL) == -1)
4662 err(1, "pledge");
4663 } else {
4664 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4665 "sendfd unveil", NULL) == -1)
4666 err(1, "pledge");
4668 #endif
4669 cwd = getcwd(NULL, 0);
4670 if (cwd == NULL) {
4671 error = got_error_from_errno("getcwd");
4672 goto done;
4675 if (repo_path == NULL) {
4676 error = got_worktree_open(&worktree, cwd);
4677 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4678 goto done;
4679 else
4680 error = NULL;
4681 if (worktree) {
4682 repo_path =
4683 strdup(got_worktree_get_repo_path(worktree));
4684 if (repo_path == NULL)
4685 error = got_error_from_errno("strdup");
4686 if (error)
4687 goto done;
4688 } else {
4689 repo_path = strdup(cwd);
4690 if (repo_path == NULL) {
4691 error = got_error_from_errno("strdup");
4692 goto done;
4697 error = got_repo_open(&repo, repo_path, NULL);
4698 if (error != NULL)
4699 goto done;
4701 error = apply_unveil(got_repo_get_path(repo), do_list,
4702 worktree ? got_worktree_get_root_path(worktree) : NULL);
4703 if (error)
4704 goto done;
4706 if (do_show)
4707 error = show_current_branch(repo, worktree);
4708 else if (do_list)
4709 error = list_branches(repo, worktree);
4710 else if (delref)
4711 error = delete_branch(repo, worktree, delref);
4712 else {
4713 if (commit_id_arg == NULL)
4714 commit_id_arg = worktree ?
4715 got_worktree_get_head_ref_name(worktree) :
4716 GOT_REF_HEAD;
4717 error = got_repo_match_object_id(&commit_id, NULL,
4718 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
4719 if (error)
4720 goto done;
4721 error = add_branch(repo, argv[0], commit_id);
4722 if (error)
4723 goto done;
4724 if (worktree && do_update) {
4725 int did_something = 0;
4726 char *branch_refname = NULL;
4728 error = got_object_id_str(&commit_id_str, commit_id);
4729 if (error)
4730 goto done;
4731 error = get_worktree_paths_from_argv(&paths, 0, NULL,
4732 worktree);
4733 if (error)
4734 goto done;
4735 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
4736 == -1) {
4737 error = got_error_from_errno("asprintf");
4738 goto done;
4740 error = got_ref_open(&ref, repo, branch_refname, 0);
4741 free(branch_refname);
4742 if (error)
4743 goto done;
4744 error = switch_head_ref(ref, commit_id, worktree,
4745 repo);
4746 if (error)
4747 goto done;
4748 error = got_worktree_set_base_commit_id(worktree, repo,
4749 commit_id);
4750 if (error)
4751 goto done;
4752 error = got_worktree_checkout_files(worktree, &paths,
4753 repo, update_progress, &did_something,
4754 check_cancelled, NULL);
4755 if (error)
4756 goto done;
4757 if (did_something)
4758 printf("Updated to commit %s\n", commit_id_str);
4761 done:
4762 if (ref)
4763 got_ref_close(ref);
4764 if (repo)
4765 got_repo_close(repo);
4766 if (worktree)
4767 got_worktree_close(worktree);
4768 free(cwd);
4769 free(repo_path);
4770 free(commit_id);
4771 free(commit_id_str);
4772 TAILQ_FOREACH(pe, &paths, entry)
4773 free((char *)pe->path);
4774 got_pathlist_free(&paths);
4775 return error;
4779 __dead static void
4780 usage_tag(void)
4782 fprintf(stderr,
4783 "usage: %s tag [-c commit] [-r repository] [-l] "
4784 "[-m message] name\n", getprogname());
4785 exit(1);
4788 #if 0
4789 static const struct got_error *
4790 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
4792 const struct got_error *err = NULL;
4793 struct got_reflist_entry *re, *se, *new;
4794 struct got_object_id *re_id, *se_id;
4795 struct got_tag_object *re_tag, *se_tag;
4796 time_t re_time, se_time;
4798 SIMPLEQ_FOREACH(re, tags, entry) {
4799 se = SIMPLEQ_FIRST(sorted);
4800 if (se == NULL) {
4801 err = got_reflist_entry_dup(&new, re);
4802 if (err)
4803 return err;
4804 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
4805 continue;
4806 } else {
4807 err = got_ref_resolve(&re_id, repo, re->ref);
4808 if (err)
4809 break;
4810 err = got_object_open_as_tag(&re_tag, repo, re_id);
4811 free(re_id);
4812 if (err)
4813 break;
4814 re_time = got_object_tag_get_tagger_time(re_tag);
4815 got_object_tag_close(re_tag);
4818 while (se) {
4819 err = got_ref_resolve(&se_id, repo, re->ref);
4820 if (err)
4821 break;
4822 err = got_object_open_as_tag(&se_tag, repo, se_id);
4823 free(se_id);
4824 if (err)
4825 break;
4826 se_time = got_object_tag_get_tagger_time(se_tag);
4827 got_object_tag_close(se_tag);
4829 if (se_time > re_time) {
4830 err = got_reflist_entry_dup(&new, re);
4831 if (err)
4832 return err;
4833 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
4834 break;
4836 se = SIMPLEQ_NEXT(se, entry);
4837 continue;
4840 done:
4841 return err;
4843 #endif
4845 static const struct got_error *
4846 list_tags(struct got_repository *repo, struct got_worktree *worktree)
4848 static const struct got_error *err = NULL;
4849 struct got_reflist_head refs;
4850 struct got_reflist_entry *re;
4852 SIMPLEQ_INIT(&refs);
4854 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
4855 if (err)
4856 return err;
4858 SIMPLEQ_FOREACH(re, &refs, entry) {
4859 const char *refname;
4860 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
4861 char datebuf[26];
4862 const char *tagger;
4863 time_t tagger_time;
4864 struct got_object_id *id;
4865 struct got_tag_object *tag;
4866 struct got_commit_object *commit = NULL;
4868 refname = got_ref_get_name(re->ref);
4869 if (strncmp(refname, "refs/tags/", 10) != 0)
4870 continue;
4871 refname += 10;
4872 refstr = got_ref_to_str(re->ref);
4873 if (refstr == NULL) {
4874 err = got_error_from_errno("got_ref_to_str");
4875 break;
4877 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
4878 free(refstr);
4880 err = got_ref_resolve(&id, repo, re->ref);
4881 if (err)
4882 break;
4883 err = got_object_open_as_tag(&tag, repo, id);
4884 if (err) {
4885 if (err->code != GOT_ERR_OBJ_TYPE) {
4886 free(id);
4887 break;
4889 /* "lightweight" tag */
4890 err = got_object_open_as_commit(&commit, repo, id);
4891 if (err) {
4892 free(id);
4893 break;
4895 tagger = got_object_commit_get_committer(commit);
4896 tagger_time =
4897 got_object_commit_get_committer_time(commit);
4898 err = got_object_id_str(&id_str, id);
4899 free(id);
4900 if (err)
4901 break;
4902 } else {
4903 free(id);
4904 tagger = got_object_tag_get_tagger(tag);
4905 tagger_time = got_object_tag_get_tagger_time(tag);
4906 err = got_object_id_str(&id_str,
4907 got_object_tag_get_object_id(tag));
4908 if (err)
4909 break;
4911 printf("from: %s\n", tagger);
4912 datestr = get_datestr(&tagger_time, datebuf);
4913 if (datestr)
4914 printf("date: %s UTC\n", datestr);
4915 if (commit)
4916 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
4917 else {
4918 switch (got_object_tag_get_object_type(tag)) {
4919 case GOT_OBJ_TYPE_BLOB:
4920 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
4921 id_str);
4922 break;
4923 case GOT_OBJ_TYPE_TREE:
4924 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
4925 id_str);
4926 break;
4927 case GOT_OBJ_TYPE_COMMIT:
4928 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
4929 id_str);
4930 break;
4931 case GOT_OBJ_TYPE_TAG:
4932 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
4933 id_str);
4934 break;
4935 default:
4936 break;
4939 free(id_str);
4940 if (commit) {
4941 err = got_object_commit_get_logmsg(&tagmsg0, commit);
4942 if (err)
4943 break;
4944 got_object_commit_close(commit);
4945 } else {
4946 tagmsg0 = strdup(got_object_tag_get_message(tag));
4947 got_object_tag_close(tag);
4948 if (tagmsg0 == NULL) {
4949 err = got_error_from_errno("strdup");
4950 break;
4954 tagmsg = tagmsg0;
4955 do {
4956 line = strsep(&tagmsg, "\n");
4957 if (line)
4958 printf(" %s\n", line);
4959 } while (line);
4960 free(tagmsg0);
4963 got_ref_list_free(&refs);
4964 return NULL;
4967 static const struct got_error *
4968 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
4969 const char *tag_name, const char *repo_path)
4971 const struct got_error *err = NULL;
4972 char *template = NULL, *initial_content = NULL;
4973 char *editor = NULL;
4974 int fd = -1;
4976 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
4977 err = got_error_from_errno("asprintf");
4978 goto done;
4981 if (asprintf(&initial_content, "\n# tagging commit %s as %s\n",
4982 commit_id_str, tag_name) == -1) {
4983 err = got_error_from_errno("asprintf");
4984 goto done;
4987 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
4988 if (err)
4989 goto done;
4991 dprintf(fd, initial_content);
4992 close(fd);
4994 err = get_editor(&editor);
4995 if (err)
4996 goto done;
4997 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
4998 done:
4999 free(initial_content);
5000 free(template);
5001 free(editor);
5003 /* Editor is done; we can now apply unveil(2) */
5004 if (err == NULL) {
5005 err = apply_unveil(repo_path, 0, NULL);
5006 if (err) {
5007 free(*tagmsg);
5008 *tagmsg = NULL;
5011 return err;
5014 static const struct got_error *
5015 add_tag(struct got_repository *repo, const char *tag_name,
5016 const char *commit_arg, const char *tagmsg_arg)
5018 const struct got_error *err = NULL;
5019 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5020 char *label = NULL, *commit_id_str = NULL;
5021 struct got_reference *ref = NULL;
5022 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5023 char *tagmsg_path = NULL, *tag_id_str = NULL;
5024 int preserve_tagmsg = 0;
5027 * Don't let the user create a tag name with a leading '-'.
5028 * While technically a valid reference name, this case is usually
5029 * an unintended typo.
5031 if (tag_name[0] == '-')
5032 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5034 err = get_author(&tagger, repo);
5035 if (err)
5036 return err;
5038 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5039 GOT_OBJ_TYPE_COMMIT, 1, repo);
5040 if (err)
5041 goto done;
5043 err = got_object_id_str(&commit_id_str, commit_id);
5044 if (err)
5045 goto done;
5047 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5048 refname = strdup(tag_name);
5049 if (refname == NULL) {
5050 err = got_error_from_errno("strdup");
5051 goto done;
5053 tag_name += 10;
5054 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5055 err = got_error_from_errno("asprintf");
5056 goto done;
5059 err = got_ref_open(&ref, repo, refname, 0);
5060 if (err == NULL) {
5061 err = got_error(GOT_ERR_TAG_EXISTS);
5062 goto done;
5063 } else if (err->code != GOT_ERR_NOT_REF)
5064 goto done;
5066 if (tagmsg_arg == NULL) {
5067 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5068 tag_name, got_repo_get_path(repo));
5069 if (err) {
5070 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5071 tagmsg_path != NULL)
5072 preserve_tagmsg = 1;
5073 goto done;
5077 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5078 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5079 if (err) {
5080 if (tagmsg_path)
5081 preserve_tagmsg = 1;
5082 goto done;
5085 err = got_ref_alloc(&ref, refname, tag_id);
5086 if (err) {
5087 if (tagmsg_path)
5088 preserve_tagmsg = 1;
5089 goto done;
5092 err = got_ref_write(ref, repo);
5093 if (err) {
5094 if (tagmsg_path)
5095 preserve_tagmsg = 1;
5096 goto done;
5099 err = got_object_id_str(&tag_id_str, tag_id);
5100 if (err) {
5101 if (tagmsg_path)
5102 preserve_tagmsg = 1;
5103 goto done;
5105 printf("Created tag %s\n", tag_id_str);
5106 done:
5107 if (preserve_tagmsg) {
5108 fprintf(stderr, "%s: tag message preserved in %s\n",
5109 getprogname(), tagmsg_path);
5110 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
5111 err = got_error_from_errno2("unlink", tagmsg_path);
5112 free(tag_id_str);
5113 if (ref)
5114 got_ref_close(ref);
5115 free(commit_id);
5116 free(commit_id_str);
5117 free(refname);
5118 free(tagmsg);
5119 free(tagmsg_path);
5120 free(tagger);
5121 return err;
5124 static const struct got_error *
5125 cmd_tag(int argc, char *argv[])
5127 const struct got_error *error = NULL;
5128 struct got_repository *repo = NULL;
5129 struct got_worktree *worktree = NULL;
5130 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
5131 char *gitconfig_path = NULL;
5132 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
5133 int ch, do_list = 0;
5135 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
5136 switch (ch) {
5137 case 'c':
5138 commit_id_arg = optarg;
5139 break;
5140 case 'm':
5141 tagmsg = optarg;
5142 break;
5143 case 'r':
5144 repo_path = realpath(optarg, NULL);
5145 if (repo_path == NULL)
5146 return got_error_from_errno2("realpath",
5147 optarg);
5148 got_path_strip_trailing_slashes(repo_path);
5149 break;
5150 case 'l':
5151 do_list = 1;
5152 break;
5153 default:
5154 usage_tag();
5155 /* NOTREACHED */
5159 argc -= optind;
5160 argv += optind;
5162 if (do_list) {
5163 if (commit_id_arg != NULL)
5164 errx(1, "-c option can only be used when creating a tag");
5165 if (tagmsg)
5166 errx(1, "-l and -m options are mutually exclusive");
5167 if (argc > 0)
5168 usage_tag();
5169 } else if (argc != 1)
5170 usage_tag();
5172 tag_name = argv[0];
5174 #ifndef PROFILE
5175 if (do_list) {
5176 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5177 NULL) == -1)
5178 err(1, "pledge");
5179 } else {
5180 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5181 "sendfd unveil", NULL) == -1)
5182 err(1, "pledge");
5184 #endif
5185 cwd = getcwd(NULL, 0);
5186 if (cwd == NULL) {
5187 error = got_error_from_errno("getcwd");
5188 goto done;
5191 if (repo_path == NULL) {
5192 error = got_worktree_open(&worktree, cwd);
5193 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5194 goto done;
5195 else
5196 error = NULL;
5197 if (worktree) {
5198 repo_path =
5199 strdup(got_worktree_get_repo_path(worktree));
5200 if (repo_path == NULL)
5201 error = got_error_from_errno("strdup");
5202 if (error)
5203 goto done;
5204 } else {
5205 repo_path = strdup(cwd);
5206 if (repo_path == NULL) {
5207 error = got_error_from_errno("strdup");
5208 goto done;
5213 if (do_list) {
5214 error = got_repo_open(&repo, repo_path, NULL);
5215 if (error != NULL)
5216 goto done;
5217 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5218 if (error)
5219 goto done;
5220 error = list_tags(repo, worktree);
5221 } else {
5222 error = get_gitconfig_path(&gitconfig_path);
5223 if (error)
5224 goto done;
5225 error = got_repo_open(&repo, repo_path, gitconfig_path);
5226 if (error != NULL)
5227 goto done;
5229 if (tagmsg) {
5230 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5231 if (error)
5232 goto done;
5235 if (commit_id_arg == NULL) {
5236 struct got_reference *head_ref;
5237 struct got_object_id *commit_id;
5238 error = got_ref_open(&head_ref, repo,
5239 worktree ? got_worktree_get_head_ref_name(worktree)
5240 : GOT_REF_HEAD, 0);
5241 if (error)
5242 goto done;
5243 error = got_ref_resolve(&commit_id, repo, head_ref);
5244 got_ref_close(head_ref);
5245 if (error)
5246 goto done;
5247 error = got_object_id_str(&commit_id_str, commit_id);
5248 free(commit_id);
5249 if (error)
5250 goto done;
5253 error = add_tag(repo, tag_name,
5254 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
5256 done:
5257 if (repo)
5258 got_repo_close(repo);
5259 if (worktree)
5260 got_worktree_close(worktree);
5261 free(cwd);
5262 free(repo_path);
5263 free(gitconfig_path);
5264 free(commit_id_str);
5265 return error;
5268 __dead static void
5269 usage_add(void)
5271 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
5272 getprogname());
5273 exit(1);
5276 static const struct got_error *
5277 add_progress(void *arg, unsigned char status, const char *path)
5279 while (path[0] == '/')
5280 path++;
5281 printf("%c %s\n", status, path);
5282 return NULL;
5285 static const struct got_error *
5286 cmd_add(int argc, char *argv[])
5288 const struct got_error *error = NULL;
5289 struct got_repository *repo = NULL;
5290 struct got_worktree *worktree = NULL;
5291 char *cwd = NULL;
5292 struct got_pathlist_head paths;
5293 struct got_pathlist_entry *pe;
5294 int ch, can_recurse = 0, no_ignores = 0;
5296 TAILQ_INIT(&paths);
5298 while ((ch = getopt(argc, argv, "IR")) != -1) {
5299 switch (ch) {
5300 case 'I':
5301 no_ignores = 1;
5302 break;
5303 case 'R':
5304 can_recurse = 1;
5305 break;
5306 default:
5307 usage_add();
5308 /* NOTREACHED */
5312 argc -= optind;
5313 argv += optind;
5315 #ifndef PROFILE
5316 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5317 NULL) == -1)
5318 err(1, "pledge");
5319 #endif
5320 if (argc < 1)
5321 usage_add();
5323 cwd = getcwd(NULL, 0);
5324 if (cwd == NULL) {
5325 error = got_error_from_errno("getcwd");
5326 goto done;
5329 error = got_worktree_open(&worktree, cwd);
5330 if (error)
5331 goto done;
5333 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5334 NULL);
5335 if (error != NULL)
5336 goto done;
5338 error = apply_unveil(got_repo_get_path(repo), 1,
5339 got_worktree_get_root_path(worktree));
5340 if (error)
5341 goto done;
5343 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5344 if (error)
5345 goto done;
5347 if (!can_recurse && no_ignores) {
5348 error = got_error_msg(GOT_ERR_BAD_PATH,
5349 "disregarding ignores requires -R option");
5350 goto done;
5354 if (!can_recurse) {
5355 char *ondisk_path;
5356 struct stat sb;
5357 TAILQ_FOREACH(pe, &paths, entry) {
5358 if (asprintf(&ondisk_path, "%s/%s",
5359 got_worktree_get_root_path(worktree),
5360 pe->path) == -1) {
5361 error = got_error_from_errno("asprintf");
5362 goto done;
5364 if (lstat(ondisk_path, &sb) == -1) {
5365 if (errno == ENOENT) {
5366 free(ondisk_path);
5367 continue;
5369 error = got_error_from_errno2("lstat",
5370 ondisk_path);
5371 free(ondisk_path);
5372 goto done;
5374 free(ondisk_path);
5375 if (S_ISDIR(sb.st_mode)) {
5376 error = got_error_msg(GOT_ERR_BAD_PATH,
5377 "adding directories requires -R option");
5378 goto done;
5383 error = got_worktree_schedule_add(worktree, &paths, add_progress,
5384 NULL, repo, no_ignores);
5385 done:
5386 if (repo)
5387 got_repo_close(repo);
5388 if (worktree)
5389 got_worktree_close(worktree);
5390 TAILQ_FOREACH(pe, &paths, entry)
5391 free((char *)pe->path);
5392 got_pathlist_free(&paths);
5393 free(cwd);
5394 return error;
5397 __dead static void
5398 usage_remove(void)
5400 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] path ...\n",
5401 getprogname());
5402 exit(1);
5405 static const struct got_error *
5406 print_remove_status(void *arg, unsigned char status,
5407 unsigned char staged_status, const char *path)
5409 while (path[0] == '/')
5410 path++;
5411 if (status == GOT_STATUS_NONEXISTENT)
5412 return NULL;
5413 if (status == staged_status && (status == GOT_STATUS_DELETE))
5414 status = GOT_STATUS_NO_CHANGE;
5415 printf("%c%c %s\n", status, staged_status, path);
5416 return NULL;
5419 static const struct got_error *
5420 cmd_remove(int argc, char *argv[])
5422 const struct got_error *error = NULL;
5423 struct got_worktree *worktree = NULL;
5424 struct got_repository *repo = NULL;
5425 char *cwd = NULL;
5426 struct got_pathlist_head paths;
5427 struct got_pathlist_entry *pe;
5428 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0;
5430 TAILQ_INIT(&paths);
5432 while ((ch = getopt(argc, argv, "fkR")) != -1) {
5433 switch (ch) {
5434 case 'f':
5435 delete_local_mods = 1;
5436 break;
5437 case 'k':
5438 keep_on_disk = 1;
5439 break;
5440 case 'R':
5441 can_recurse = 1;
5442 break;
5443 default:
5444 usage_remove();
5445 /* NOTREACHED */
5449 argc -= optind;
5450 argv += optind;
5452 #ifndef PROFILE
5453 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5454 NULL) == -1)
5455 err(1, "pledge");
5456 #endif
5457 if (argc < 1)
5458 usage_remove();
5460 cwd = getcwd(NULL, 0);
5461 if (cwd == NULL) {
5462 error = got_error_from_errno("getcwd");
5463 goto done;
5465 error = got_worktree_open(&worktree, cwd);
5466 if (error)
5467 goto done;
5469 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5470 NULL);
5471 if (error)
5472 goto done;
5474 error = apply_unveil(got_repo_get_path(repo), 1,
5475 got_worktree_get_root_path(worktree));
5476 if (error)
5477 goto done;
5479 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5480 if (error)
5481 goto done;
5483 if (!can_recurse) {
5484 char *ondisk_path;
5485 struct stat sb;
5486 TAILQ_FOREACH(pe, &paths, entry) {
5487 if (asprintf(&ondisk_path, "%s/%s",
5488 got_worktree_get_root_path(worktree),
5489 pe->path) == -1) {
5490 error = got_error_from_errno("asprintf");
5491 goto done;
5493 if (lstat(ondisk_path, &sb) == -1) {
5494 if (errno == ENOENT) {
5495 free(ondisk_path);
5496 continue;
5498 error = got_error_from_errno2("lstat",
5499 ondisk_path);
5500 free(ondisk_path);
5501 goto done;
5503 free(ondisk_path);
5504 if (S_ISDIR(sb.st_mode)) {
5505 error = got_error_msg(GOT_ERR_BAD_PATH,
5506 "removing directories requires -R option");
5507 goto done;
5512 error = got_worktree_schedule_delete(worktree, &paths,
5513 delete_local_mods, print_remove_status, NULL, repo, keep_on_disk);
5514 done:
5515 if (repo)
5516 got_repo_close(repo);
5517 if (worktree)
5518 got_worktree_close(worktree);
5519 TAILQ_FOREACH(pe, &paths, entry)
5520 free((char *)pe->path);
5521 got_pathlist_free(&paths);
5522 free(cwd);
5523 return error;
5526 __dead static void
5527 usage_revert(void)
5529 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
5530 "path ...\n", getprogname());
5531 exit(1);
5534 static const struct got_error *
5535 revert_progress(void *arg, unsigned char status, const char *path)
5537 if (status == GOT_STATUS_UNVERSIONED)
5538 return NULL;
5540 while (path[0] == '/')
5541 path++;
5542 printf("%c %s\n", status, path);
5543 return NULL;
5546 struct choose_patch_arg {
5547 FILE *patch_script_file;
5548 const char *action;
5551 static const struct got_error *
5552 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
5553 int nchanges, const char *action)
5555 char *line = NULL;
5556 size_t linesize = 0;
5557 ssize_t linelen;
5559 switch (status) {
5560 case GOT_STATUS_ADD:
5561 printf("A %s\n%s this addition? [y/n] ", path, action);
5562 break;
5563 case GOT_STATUS_DELETE:
5564 printf("D %s\n%s this deletion? [y/n] ", path, action);
5565 break;
5566 case GOT_STATUS_MODIFY:
5567 if (fseek(patch_file, 0L, SEEK_SET) == -1)
5568 return got_error_from_errno("fseek");
5569 printf(GOT_COMMIT_SEP_STR);
5570 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
5571 printf("%s", line);
5572 if (ferror(patch_file))
5573 return got_error_from_errno("getline");
5574 printf(GOT_COMMIT_SEP_STR);
5575 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
5576 path, n, nchanges, action);
5577 break;
5578 default:
5579 return got_error_path(path, GOT_ERR_FILE_STATUS);
5582 return NULL;
5585 static const struct got_error *
5586 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
5587 FILE *patch_file, int n, int nchanges)
5589 const struct got_error *err = NULL;
5590 char *line = NULL;
5591 size_t linesize = 0;
5592 ssize_t linelen;
5593 int resp = ' ';
5594 struct choose_patch_arg *a = arg;
5596 *choice = GOT_PATCH_CHOICE_NONE;
5598 if (a->patch_script_file) {
5599 char *nl;
5600 err = show_change(status, path, patch_file, n, nchanges,
5601 a->action);
5602 if (err)
5603 return err;
5604 linelen = getline(&line, &linesize, a->patch_script_file);
5605 if (linelen == -1) {
5606 if (ferror(a->patch_script_file))
5607 return got_error_from_errno("getline");
5608 return NULL;
5610 nl = strchr(line, '\n');
5611 if (nl)
5612 *nl = '\0';
5613 if (strcmp(line, "y") == 0) {
5614 *choice = GOT_PATCH_CHOICE_YES;
5615 printf("y\n");
5616 } else if (strcmp(line, "n") == 0) {
5617 *choice = GOT_PATCH_CHOICE_NO;
5618 printf("n\n");
5619 } else if (strcmp(line, "q") == 0 &&
5620 status == GOT_STATUS_MODIFY) {
5621 *choice = GOT_PATCH_CHOICE_QUIT;
5622 printf("q\n");
5623 } else
5624 printf("invalid response '%s'\n", line);
5625 free(line);
5626 return NULL;
5629 while (resp != 'y' && resp != 'n' && resp != 'q') {
5630 err = show_change(status, path, patch_file, n, nchanges,
5631 a->action);
5632 if (err)
5633 return err;
5634 resp = getchar();
5635 if (resp == '\n')
5636 resp = getchar();
5637 if (status == GOT_STATUS_MODIFY) {
5638 if (resp != 'y' && resp != 'n' && resp != 'q') {
5639 printf("invalid response '%c'\n", resp);
5640 resp = ' ';
5642 } else if (resp != 'y' && resp != 'n') {
5643 printf("invalid response '%c'\n", resp);
5644 resp = ' ';
5648 if (resp == 'y')
5649 *choice = GOT_PATCH_CHOICE_YES;
5650 else if (resp == 'n')
5651 *choice = GOT_PATCH_CHOICE_NO;
5652 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
5653 *choice = GOT_PATCH_CHOICE_QUIT;
5655 return NULL;
5659 static const struct got_error *
5660 cmd_revert(int argc, char *argv[])
5662 const struct got_error *error = NULL;
5663 struct got_worktree *worktree = NULL;
5664 struct got_repository *repo = NULL;
5665 char *cwd = NULL, *path = NULL;
5666 struct got_pathlist_head paths;
5667 struct got_pathlist_entry *pe;
5668 int ch, can_recurse = 0, pflag = 0;
5669 FILE *patch_script_file = NULL;
5670 const char *patch_script_path = NULL;
5671 struct choose_patch_arg cpa;
5673 TAILQ_INIT(&paths);
5675 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
5676 switch (ch) {
5677 case 'p':
5678 pflag = 1;
5679 break;
5680 case 'F':
5681 patch_script_path = optarg;
5682 break;
5683 case 'R':
5684 can_recurse = 1;
5685 break;
5686 default:
5687 usage_revert();
5688 /* NOTREACHED */
5692 argc -= optind;
5693 argv += optind;
5695 #ifndef PROFILE
5696 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
5697 "unveil", NULL) == -1)
5698 err(1, "pledge");
5699 #endif
5700 if (argc < 1)
5701 usage_revert();
5702 if (patch_script_path && !pflag)
5703 errx(1, "-F option can only be used together with -p option");
5705 cwd = getcwd(NULL, 0);
5706 if (cwd == NULL) {
5707 error = got_error_from_errno("getcwd");
5708 goto done;
5710 error = got_worktree_open(&worktree, cwd);
5711 if (error)
5712 goto done;
5714 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5715 NULL);
5716 if (error != NULL)
5717 goto done;
5719 if (patch_script_path) {
5720 patch_script_file = fopen(patch_script_path, "r");
5721 if (patch_script_file == NULL) {
5722 error = got_error_from_errno2("fopen",
5723 patch_script_path);
5724 goto done;
5727 error = apply_unveil(got_repo_get_path(repo), 1,
5728 got_worktree_get_root_path(worktree));
5729 if (error)
5730 goto done;
5732 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5733 if (error)
5734 goto done;
5736 if (!can_recurse) {
5737 char *ondisk_path;
5738 struct stat sb;
5739 TAILQ_FOREACH(pe, &paths, entry) {
5740 if (asprintf(&ondisk_path, "%s/%s",
5741 got_worktree_get_root_path(worktree),
5742 pe->path) == -1) {
5743 error = got_error_from_errno("asprintf");
5744 goto done;
5746 if (lstat(ondisk_path, &sb) == -1) {
5747 if (errno == ENOENT) {
5748 free(ondisk_path);
5749 continue;
5751 error = got_error_from_errno2("lstat",
5752 ondisk_path);
5753 free(ondisk_path);
5754 goto done;
5756 free(ondisk_path);
5757 if (S_ISDIR(sb.st_mode)) {
5758 error = got_error_msg(GOT_ERR_BAD_PATH,
5759 "reverting directories requires -R option");
5760 goto done;
5765 cpa.patch_script_file = patch_script_file;
5766 cpa.action = "revert";
5767 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
5768 pflag ? choose_patch : NULL, &cpa, repo);
5769 done:
5770 if (patch_script_file && fclose(patch_script_file) == EOF &&
5771 error == NULL)
5772 error = got_error_from_errno2("fclose", patch_script_path);
5773 if (repo)
5774 got_repo_close(repo);
5775 if (worktree)
5776 got_worktree_close(worktree);
5777 free(path);
5778 free(cwd);
5779 return error;
5782 __dead static void
5783 usage_commit(void)
5785 fprintf(stderr, "usage: %s commit [-m msg] [path ...]\n",
5786 getprogname());
5787 exit(1);
5790 struct collect_commit_logmsg_arg {
5791 const char *cmdline_log;
5792 const char *editor;
5793 const char *worktree_path;
5794 const char *branch_name;
5795 const char *repo_path;
5796 char *logmsg_path;
5800 static const struct got_error *
5801 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
5802 void *arg)
5804 char *initial_content = NULL;
5805 struct got_pathlist_entry *pe;
5806 const struct got_error *err = NULL;
5807 char *template = NULL;
5808 struct collect_commit_logmsg_arg *a = arg;
5809 int fd;
5810 size_t len;
5812 /* if a message was specified on the command line, just use it */
5813 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
5814 len = strlen(a->cmdline_log) + 1;
5815 *logmsg = malloc(len + 1);
5816 if (*logmsg == NULL)
5817 return got_error_from_errno("malloc");
5818 strlcpy(*logmsg, a->cmdline_log, len);
5819 return NULL;
5822 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
5823 return got_error_from_errno("asprintf");
5825 if (asprintf(&initial_content,
5826 "\n# changes to be committed on branch %s:\n",
5827 a->branch_name) == -1)
5828 return got_error_from_errno("asprintf");
5830 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
5831 if (err)
5832 goto done;
5834 dprintf(fd, initial_content);
5836 TAILQ_FOREACH(pe, commitable_paths, entry) {
5837 struct got_commitable *ct = pe->data;
5838 dprintf(fd, "# %c %s\n",
5839 got_commitable_get_status(ct),
5840 got_commitable_get_path(ct));
5842 close(fd);
5844 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
5845 done:
5846 free(initial_content);
5847 free(template);
5849 /* Editor is done; we can now apply unveil(2) */
5850 if (err == NULL) {
5851 err = apply_unveil(a->repo_path, 0, a->worktree_path);
5852 if (err) {
5853 free(*logmsg);
5854 *logmsg = NULL;
5857 return err;
5860 static const struct got_error *
5861 cmd_commit(int argc, char *argv[])
5863 const struct got_error *error = NULL;
5864 struct got_worktree *worktree = NULL;
5865 struct got_repository *repo = NULL;
5866 char *cwd = NULL, *id_str = NULL;
5867 struct got_object_id *id = NULL;
5868 const char *logmsg = NULL;
5869 struct collect_commit_logmsg_arg cl_arg;
5870 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
5871 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
5872 struct got_pathlist_head paths;
5874 TAILQ_INIT(&paths);
5875 cl_arg.logmsg_path = NULL;
5877 while ((ch = getopt(argc, argv, "m:")) != -1) {
5878 switch (ch) {
5879 case 'm':
5880 logmsg = optarg;
5881 break;
5882 default:
5883 usage_commit();
5884 /* NOTREACHED */
5888 argc -= optind;
5889 argv += optind;
5891 #ifndef PROFILE
5892 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
5893 "unveil", NULL) == -1)
5894 err(1, "pledge");
5895 #endif
5896 cwd = getcwd(NULL, 0);
5897 if (cwd == NULL) {
5898 error = got_error_from_errno("getcwd");
5899 goto done;
5901 error = got_worktree_open(&worktree, cwd);
5902 if (error)
5903 goto done;
5905 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
5906 if (error)
5907 goto done;
5908 if (rebase_in_progress) {
5909 error = got_error(GOT_ERR_REBASING);
5910 goto done;
5913 error = got_worktree_histedit_in_progress(&histedit_in_progress,
5914 worktree);
5915 if (error)
5916 goto done;
5918 error = get_gitconfig_path(&gitconfig_path);
5919 if (error)
5920 goto done;
5921 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5922 gitconfig_path);
5923 if (error != NULL)
5924 goto done;
5926 error = get_author(&author, repo);
5927 if (error)
5928 return error;
5931 * unveil(2) traverses exec(2); if an editor is used we have
5932 * to apply unveil after the log message has been written.
5934 if (logmsg == NULL || strlen(logmsg) == 0)
5935 error = get_editor(&editor);
5936 else
5937 error = apply_unveil(got_repo_get_path(repo), 0,
5938 got_worktree_get_root_path(worktree));
5939 if (error)
5940 goto done;
5942 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5943 if (error)
5944 goto done;
5946 cl_arg.editor = editor;
5947 cl_arg.cmdline_log = logmsg;
5948 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
5949 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
5950 if (!histedit_in_progress) {
5951 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
5952 error = got_error(GOT_ERR_COMMIT_BRANCH);
5953 goto done;
5955 cl_arg.branch_name += 11;
5957 cl_arg.repo_path = got_repo_get_path(repo);
5958 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
5959 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
5960 if (error) {
5961 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5962 cl_arg.logmsg_path != NULL)
5963 preserve_logmsg = 1;
5964 goto done;
5967 error = got_object_id_str(&id_str, id);
5968 if (error)
5969 goto done;
5970 printf("Created commit %s\n", id_str);
5971 done:
5972 if (preserve_logmsg) {
5973 fprintf(stderr, "%s: log message preserved in %s\n",
5974 getprogname(), cl_arg.logmsg_path);
5975 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
5976 error == NULL)
5977 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
5978 free(cl_arg.logmsg_path);
5979 if (repo)
5980 got_repo_close(repo);
5981 if (worktree)
5982 got_worktree_close(worktree);
5983 free(cwd);
5984 free(id_str);
5985 free(gitconfig_path);
5986 free(editor);
5987 free(author);
5988 return error;
5991 __dead static void
5992 usage_cherrypick(void)
5994 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
5995 exit(1);
5998 static const struct got_error *
5999 cmd_cherrypick(int argc, char *argv[])
6001 const struct got_error *error = NULL;
6002 struct got_worktree *worktree = NULL;
6003 struct got_repository *repo = NULL;
6004 char *cwd = NULL, *commit_id_str = NULL;
6005 struct got_object_id *commit_id = NULL;
6006 struct got_commit_object *commit = NULL;
6007 struct got_object_qid *pid;
6008 struct got_reference *head_ref = NULL;
6009 int ch, did_something = 0;
6011 while ((ch = getopt(argc, argv, "")) != -1) {
6012 switch (ch) {
6013 default:
6014 usage_cherrypick();
6015 /* NOTREACHED */
6019 argc -= optind;
6020 argv += optind;
6022 #ifndef PROFILE
6023 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6024 "unveil", NULL) == -1)
6025 err(1, "pledge");
6026 #endif
6027 if (argc != 1)
6028 usage_cherrypick();
6030 cwd = getcwd(NULL, 0);
6031 if (cwd == NULL) {
6032 error = got_error_from_errno("getcwd");
6033 goto done;
6035 error = got_worktree_open(&worktree, cwd);
6036 if (error)
6037 goto done;
6039 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6040 NULL);
6041 if (error != NULL)
6042 goto done;
6044 error = apply_unveil(got_repo_get_path(repo), 0,
6045 got_worktree_get_root_path(worktree));
6046 if (error)
6047 goto done;
6049 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6050 GOT_OBJ_TYPE_COMMIT, repo);
6051 if (error != NULL) {
6052 struct got_reference *ref;
6053 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6054 goto done;
6055 error = got_ref_open(&ref, repo, argv[0], 0);
6056 if (error != NULL)
6057 goto done;
6058 error = got_ref_resolve(&commit_id, repo, ref);
6059 got_ref_close(ref);
6060 if (error != NULL)
6061 goto done;
6063 error = got_object_id_str(&commit_id_str, commit_id);
6064 if (error)
6065 goto done;
6067 error = got_ref_open(&head_ref, repo,
6068 got_worktree_get_head_ref_name(worktree), 0);
6069 if (error != NULL)
6070 goto done;
6072 error = check_same_branch(commit_id, head_ref, NULL, repo);
6073 if (error) {
6074 if (error->code != GOT_ERR_ANCESTRY)
6075 goto done;
6076 error = NULL;
6077 } else {
6078 error = got_error(GOT_ERR_SAME_BRANCH);
6079 goto done;
6082 error = got_object_open_as_commit(&commit, repo, commit_id);
6083 if (error)
6084 goto done;
6085 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6086 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
6087 commit_id, repo, update_progress, &did_something, check_cancelled,
6088 NULL);
6089 if (error != NULL)
6090 goto done;
6092 if (did_something)
6093 printf("Merged commit %s\n", commit_id_str);
6094 done:
6095 if (commit)
6096 got_object_commit_close(commit);
6097 free(commit_id_str);
6098 if (head_ref)
6099 got_ref_close(head_ref);
6100 if (worktree)
6101 got_worktree_close(worktree);
6102 if (repo)
6103 got_repo_close(repo);
6104 return error;
6107 __dead static void
6108 usage_backout(void)
6110 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
6111 exit(1);
6114 static const struct got_error *
6115 cmd_backout(int argc, char *argv[])
6117 const struct got_error *error = NULL;
6118 struct got_worktree *worktree = NULL;
6119 struct got_repository *repo = NULL;
6120 char *cwd = NULL, *commit_id_str = NULL;
6121 struct got_object_id *commit_id = NULL;
6122 struct got_commit_object *commit = NULL;
6123 struct got_object_qid *pid;
6124 struct got_reference *head_ref = NULL;
6125 int ch, did_something = 0;
6127 while ((ch = getopt(argc, argv, "")) != -1) {
6128 switch (ch) {
6129 default:
6130 usage_backout();
6131 /* NOTREACHED */
6135 argc -= optind;
6136 argv += optind;
6138 #ifndef PROFILE
6139 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6140 "unveil", NULL) == -1)
6141 err(1, "pledge");
6142 #endif
6143 if (argc != 1)
6144 usage_backout();
6146 cwd = getcwd(NULL, 0);
6147 if (cwd == NULL) {
6148 error = got_error_from_errno("getcwd");
6149 goto done;
6151 error = got_worktree_open(&worktree, cwd);
6152 if (error)
6153 goto done;
6155 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6156 NULL);
6157 if (error != NULL)
6158 goto done;
6160 error = apply_unveil(got_repo_get_path(repo), 0,
6161 got_worktree_get_root_path(worktree));
6162 if (error)
6163 goto done;
6165 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6166 GOT_OBJ_TYPE_COMMIT, repo);
6167 if (error != NULL) {
6168 struct got_reference *ref;
6169 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6170 goto done;
6171 error = got_ref_open(&ref, repo, argv[0], 0);
6172 if (error != NULL)
6173 goto done;
6174 error = got_ref_resolve(&commit_id, repo, ref);
6175 got_ref_close(ref);
6176 if (error != NULL)
6177 goto done;
6179 error = got_object_id_str(&commit_id_str, commit_id);
6180 if (error)
6181 goto done;
6183 error = got_ref_open(&head_ref, repo,
6184 got_worktree_get_head_ref_name(worktree), 0);
6185 if (error != NULL)
6186 goto done;
6188 error = check_same_branch(commit_id, head_ref, NULL, repo);
6189 if (error)
6190 goto done;
6192 error = got_object_open_as_commit(&commit, repo, commit_id);
6193 if (error)
6194 goto done;
6195 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6196 if (pid == NULL) {
6197 error = got_error(GOT_ERR_ROOT_COMMIT);
6198 goto done;
6201 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
6202 update_progress, &did_something, check_cancelled, NULL);
6203 if (error != NULL)
6204 goto done;
6206 if (did_something)
6207 printf("Backed out commit %s\n", commit_id_str);
6208 done:
6209 if (commit)
6210 got_object_commit_close(commit);
6211 free(commit_id_str);
6212 if (head_ref)
6213 got_ref_close(head_ref);
6214 if (worktree)
6215 got_worktree_close(worktree);
6216 if (repo)
6217 got_repo_close(repo);
6218 return error;
6221 __dead static void
6222 usage_rebase(void)
6224 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
6225 getprogname());
6226 exit(1);
6229 void
6230 trim_logmsg(char *logmsg, int limit)
6232 char *nl;
6233 size_t len;
6235 len = strlen(logmsg);
6236 if (len > limit)
6237 len = limit;
6238 logmsg[len] = '\0';
6239 nl = strchr(logmsg, '\n');
6240 if (nl)
6241 *nl = '\0';
6244 static const struct got_error *
6245 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
6247 const struct got_error *err;
6248 char *logmsg0 = NULL;
6249 const char *s;
6251 err = got_object_commit_get_logmsg(&logmsg0, commit);
6252 if (err)
6253 return err;
6255 s = logmsg0;
6256 while (isspace((unsigned char)s[0]))
6257 s++;
6259 *logmsg = strdup(s);
6260 if (*logmsg == NULL) {
6261 err = got_error_from_errno("strdup");
6262 goto done;
6265 trim_logmsg(*logmsg, limit);
6266 done:
6267 free(logmsg0);
6268 return err;
6271 static const struct got_error *
6272 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
6274 const struct got_error *err;
6275 struct got_commit_object *commit = NULL;
6276 char *id_str = NULL, *logmsg = NULL;
6278 err = got_object_open_as_commit(&commit, repo, id);
6279 if (err)
6280 return err;
6282 err = got_object_id_str(&id_str, id);
6283 if (err)
6284 goto done;
6286 id_str[12] = '\0';
6288 err = get_short_logmsg(&logmsg, 42, commit);
6289 if (err)
6290 goto done;
6292 printf("%s -> merge conflict: %s\n", id_str, logmsg);
6293 done:
6294 free(id_str);
6295 got_object_commit_close(commit);
6296 free(logmsg);
6297 return err;
6300 static const struct got_error *
6301 show_rebase_progress(struct got_commit_object *commit,
6302 struct got_object_id *old_id, struct got_object_id *new_id)
6304 const struct got_error *err;
6305 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
6307 err = got_object_id_str(&old_id_str, old_id);
6308 if (err)
6309 goto done;
6311 if (new_id) {
6312 err = got_object_id_str(&new_id_str, new_id);
6313 if (err)
6314 goto done;
6317 old_id_str[12] = '\0';
6318 if (new_id_str)
6319 new_id_str[12] = '\0';
6321 err = get_short_logmsg(&logmsg, 42, commit);
6322 if (err)
6323 goto done;
6325 printf("%s -> %s: %s\n", old_id_str,
6326 new_id_str ? new_id_str : "no-op change", logmsg);
6327 done:
6328 free(old_id_str);
6329 free(new_id_str);
6330 free(logmsg);
6331 return err;
6334 static const struct got_error *
6335 rebase_progress(void *arg, unsigned char status, const char *path)
6337 unsigned char *rebase_status = arg;
6339 while (path[0] == '/')
6340 path++;
6341 printf("%c %s\n", status, path);
6343 if (*rebase_status == GOT_STATUS_CONFLICT)
6344 return NULL;
6345 if (status == GOT_STATUS_CONFLICT || status == GOT_STATUS_MERGE)
6346 *rebase_status = status;
6347 return NULL;
6350 static const struct got_error *
6351 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
6352 struct got_reference *branch, struct got_reference *new_base_branch,
6353 struct got_reference *tmp_branch, struct got_repository *repo)
6355 printf("Switching work tree to %s\n", got_ref_get_name(branch));
6356 return got_worktree_rebase_complete(worktree, fileindex,
6357 new_base_branch, tmp_branch, branch, repo);
6360 static const struct got_error *
6361 rebase_commit(struct got_pathlist_head *merged_paths,
6362 struct got_worktree *worktree, struct got_fileindex *fileindex,
6363 struct got_reference *tmp_branch,
6364 struct got_object_id *commit_id, struct got_repository *repo)
6366 const struct got_error *error;
6367 struct got_commit_object *commit;
6368 struct got_object_id *new_commit_id;
6370 error = got_object_open_as_commit(&commit, repo, commit_id);
6371 if (error)
6372 return error;
6374 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
6375 worktree, fileindex, tmp_branch, commit, commit_id, repo);
6376 if (error) {
6377 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
6378 goto done;
6379 error = show_rebase_progress(commit, commit_id, NULL);
6380 } else {
6381 error = show_rebase_progress(commit, commit_id, new_commit_id);
6382 free(new_commit_id);
6384 done:
6385 got_object_commit_close(commit);
6386 return error;
6389 struct check_path_prefix_arg {
6390 const char *path_prefix;
6391 size_t len;
6392 int errcode;
6395 static const struct got_error *
6396 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
6397 struct got_blob_object *blob2, struct got_object_id *id1,
6398 struct got_object_id *id2, const char *path1, const char *path2,
6399 mode_t mode1, mode_t mode2, struct got_repository *repo)
6401 struct check_path_prefix_arg *a = arg;
6403 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
6404 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
6405 return got_error(a->errcode);
6407 return NULL;
6410 static const struct got_error *
6411 check_path_prefix(struct got_object_id *parent_id,
6412 struct got_object_id *commit_id, const char *path_prefix,
6413 int errcode, struct got_repository *repo)
6415 const struct got_error *err;
6416 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
6417 struct got_commit_object *commit = NULL, *parent_commit = NULL;
6418 struct check_path_prefix_arg cpp_arg;
6420 if (got_path_is_root_dir(path_prefix))
6421 return NULL;
6423 err = got_object_open_as_commit(&commit, repo, commit_id);
6424 if (err)
6425 goto done;
6427 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
6428 if (err)
6429 goto done;
6431 err = got_object_open_as_tree(&tree1, repo,
6432 got_object_commit_get_tree_id(parent_commit));
6433 if (err)
6434 goto done;
6436 err = got_object_open_as_tree(&tree2, repo,
6437 got_object_commit_get_tree_id(commit));
6438 if (err)
6439 goto done;
6441 cpp_arg.path_prefix = path_prefix;
6442 while (cpp_arg.path_prefix[0] == '/')
6443 cpp_arg.path_prefix++;
6444 cpp_arg.len = strlen(cpp_arg.path_prefix);
6445 cpp_arg.errcode = errcode;
6446 err = got_diff_tree(tree1, tree2, "", "", repo,
6447 check_path_prefix_in_diff, &cpp_arg, 0);
6448 done:
6449 if (tree1)
6450 got_object_tree_close(tree1);
6451 if (tree2)
6452 got_object_tree_close(tree2);
6453 if (commit)
6454 got_object_commit_close(commit);
6455 if (parent_commit)
6456 got_object_commit_close(parent_commit);
6457 return err;
6460 static const struct got_error *
6461 collect_commits(struct got_object_id_queue *commits,
6462 struct got_object_id *initial_commit_id,
6463 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
6464 const char *path_prefix, int path_prefix_errcode,
6465 struct got_repository *repo)
6467 const struct got_error *err = NULL;
6468 struct got_commit_graph *graph = NULL;
6469 struct got_object_id *parent_id = NULL;
6470 struct got_object_qid *qid;
6471 struct got_object_id *commit_id = initial_commit_id;
6473 err = got_commit_graph_open(&graph, "/", 1);
6474 if (err)
6475 return err;
6477 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
6478 check_cancelled, NULL);
6479 if (err)
6480 goto done;
6481 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
6482 err = got_commit_graph_iter_next(&parent_id, graph, repo,
6483 check_cancelled, NULL);
6484 if (err) {
6485 if (err->code == GOT_ERR_ITER_COMPLETED) {
6486 err = got_error_msg(GOT_ERR_ANCESTRY,
6487 "ran out of commits to rebase before "
6488 "youngest common ancestor commit has "
6489 "been reached?!?");
6491 goto done;
6492 } else {
6493 err = check_path_prefix(parent_id, commit_id,
6494 path_prefix, path_prefix_errcode, repo);
6495 if (err)
6496 goto done;
6498 err = got_object_qid_alloc(&qid, commit_id);
6499 if (err)
6500 goto done;
6501 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
6502 commit_id = parent_id;
6505 done:
6506 got_commit_graph_close(graph);
6507 return err;
6510 static const struct got_error *
6511 cmd_rebase(int argc, char *argv[])
6513 const struct got_error *error = NULL;
6514 struct got_worktree *worktree = NULL;
6515 struct got_repository *repo = NULL;
6516 struct got_fileindex *fileindex = NULL;
6517 char *cwd = NULL;
6518 struct got_reference *branch = NULL;
6519 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
6520 struct got_object_id *commit_id = NULL, *parent_id = NULL;
6521 struct got_object_id *resume_commit_id = NULL;
6522 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
6523 struct got_commit_object *commit = NULL;
6524 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
6525 int histedit_in_progress = 0;
6526 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
6527 struct got_object_id_queue commits;
6528 struct got_pathlist_head merged_paths;
6529 const struct got_object_id_queue *parent_ids;
6530 struct got_object_qid *qid, *pid;
6532 SIMPLEQ_INIT(&commits);
6533 TAILQ_INIT(&merged_paths);
6535 while ((ch = getopt(argc, argv, "ac")) != -1) {
6536 switch (ch) {
6537 case 'a':
6538 abort_rebase = 1;
6539 break;
6540 case 'c':
6541 continue_rebase = 1;
6542 break;
6543 default:
6544 usage_rebase();
6545 /* NOTREACHED */
6549 argc -= optind;
6550 argv += optind;
6552 #ifndef PROFILE
6553 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6554 "unveil", NULL) == -1)
6555 err(1, "pledge");
6556 #endif
6557 if (abort_rebase && continue_rebase)
6558 usage_rebase();
6559 else if (abort_rebase || continue_rebase) {
6560 if (argc != 0)
6561 usage_rebase();
6562 } else if (argc != 1)
6563 usage_rebase();
6565 cwd = getcwd(NULL, 0);
6566 if (cwd == NULL) {
6567 error = got_error_from_errno("getcwd");
6568 goto done;
6570 error = got_worktree_open(&worktree, cwd);
6571 if (error)
6572 goto done;
6574 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6575 NULL);
6576 if (error != NULL)
6577 goto done;
6579 error = apply_unveil(got_repo_get_path(repo), 0,
6580 got_worktree_get_root_path(worktree));
6581 if (error)
6582 goto done;
6584 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6585 worktree);
6586 if (error)
6587 goto done;
6588 if (histedit_in_progress) {
6589 error = got_error(GOT_ERR_HISTEDIT_BUSY);
6590 goto done;
6593 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6594 if (error)
6595 goto done;
6597 if (abort_rebase) {
6598 int did_something;
6599 if (!rebase_in_progress) {
6600 error = got_error(GOT_ERR_NOT_REBASING);
6601 goto done;
6603 error = got_worktree_rebase_continue(&resume_commit_id,
6604 &new_base_branch, &tmp_branch, &branch, &fileindex,
6605 worktree, repo);
6606 if (error)
6607 goto done;
6608 printf("Switching work tree to %s\n",
6609 got_ref_get_symref_target(new_base_branch));
6610 error = got_worktree_rebase_abort(worktree, fileindex, repo,
6611 new_base_branch, update_progress, &did_something);
6612 if (error)
6613 goto done;
6614 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
6615 goto done; /* nothing else to do */
6618 if (continue_rebase) {
6619 if (!rebase_in_progress) {
6620 error = got_error(GOT_ERR_NOT_REBASING);
6621 goto done;
6623 error = got_worktree_rebase_continue(&resume_commit_id,
6624 &new_base_branch, &tmp_branch, &branch, &fileindex,
6625 worktree, repo);
6626 if (error)
6627 goto done;
6629 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
6630 resume_commit_id, repo);
6631 if (error)
6632 goto done;
6634 yca_id = got_object_id_dup(resume_commit_id);
6635 if (yca_id == NULL) {
6636 error = got_error_from_errno("got_object_id_dup");
6637 goto done;
6639 } else {
6640 error = got_ref_open(&branch, repo, argv[0], 0);
6641 if (error != NULL)
6642 goto done;
6645 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
6646 if (error)
6647 goto done;
6649 if (!continue_rebase) {
6650 struct got_object_id *base_commit_id;
6652 base_commit_id = got_worktree_get_base_commit_id(worktree);
6653 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
6654 base_commit_id, branch_head_commit_id, repo,
6655 check_cancelled, NULL);
6656 if (error)
6657 goto done;
6658 if (yca_id == NULL) {
6659 error = got_error_msg(GOT_ERR_ANCESTRY,
6660 "specified branch shares no common ancestry "
6661 "with work tree's branch");
6662 goto done;
6665 error = check_same_branch(base_commit_id, branch, yca_id, repo);
6666 if (error) {
6667 if (error->code != GOT_ERR_ANCESTRY)
6668 goto done;
6669 error = NULL;
6670 } else {
6671 error = got_error_msg(GOT_ERR_SAME_BRANCH,
6672 "specified branch resolves to a commit which "
6673 "is already contained in work tree's branch");
6674 goto done;
6676 error = got_worktree_rebase_prepare(&new_base_branch,
6677 &tmp_branch, &fileindex, worktree, branch, repo);
6678 if (error)
6679 goto done;
6682 commit_id = branch_head_commit_id;
6683 error = got_object_open_as_commit(&commit, repo, commit_id);
6684 if (error)
6685 goto done;
6687 parent_ids = got_object_commit_get_parent_ids(commit);
6688 pid = SIMPLEQ_FIRST(parent_ids);
6689 if (pid == NULL) {
6690 if (!continue_rebase) {
6691 int did_something;
6692 error = got_worktree_rebase_abort(worktree, fileindex,
6693 repo, new_base_branch, update_progress,
6694 &did_something);
6695 if (error)
6696 goto done;
6697 printf("Rebase of %s aborted\n",
6698 got_ref_get_name(branch));
6700 error = got_error(GOT_ERR_EMPTY_REBASE);
6701 goto done;
6703 error = collect_commits(&commits, commit_id, pid->id,
6704 yca_id, got_worktree_get_path_prefix(worktree),
6705 GOT_ERR_REBASE_PATH, repo);
6706 got_object_commit_close(commit);
6707 commit = NULL;
6708 if (error)
6709 goto done;
6711 if (SIMPLEQ_EMPTY(&commits)) {
6712 if (continue_rebase) {
6713 error = rebase_complete(worktree, fileindex,
6714 branch, new_base_branch, tmp_branch, repo);
6715 goto done;
6716 } else {
6717 /* Fast-forward the reference of the branch. */
6718 struct got_object_id *new_head_commit_id;
6719 char *id_str;
6720 error = got_ref_resolve(&new_head_commit_id, repo,
6721 new_base_branch);
6722 if (error)
6723 goto done;
6724 error = got_object_id_str(&id_str, new_head_commit_id);
6725 printf("Forwarding %s to commit %s\n",
6726 got_ref_get_name(branch), id_str);
6727 free(id_str);
6728 error = got_ref_change_ref(branch,
6729 new_head_commit_id);
6730 if (error)
6731 goto done;
6735 pid = NULL;
6736 SIMPLEQ_FOREACH(qid, &commits, entry) {
6737 commit_id = qid->id;
6738 parent_id = pid ? pid->id : yca_id;
6739 pid = qid;
6741 error = got_worktree_rebase_merge_files(&merged_paths,
6742 worktree, fileindex, parent_id, commit_id, repo,
6743 rebase_progress, &rebase_status, check_cancelled, NULL);
6744 if (error)
6745 goto done;
6747 if (rebase_status == GOT_STATUS_CONFLICT) {
6748 error = show_rebase_merge_conflict(qid->id, repo);
6749 if (error)
6750 goto done;
6751 got_worktree_rebase_pathlist_free(&merged_paths);
6752 break;
6755 error = rebase_commit(&merged_paths, worktree, fileindex,
6756 tmp_branch, commit_id, repo);
6757 got_worktree_rebase_pathlist_free(&merged_paths);
6758 if (error)
6759 goto done;
6762 if (rebase_status == GOT_STATUS_CONFLICT) {
6763 error = got_worktree_rebase_postpone(worktree, fileindex);
6764 if (error)
6765 goto done;
6766 error = got_error_msg(GOT_ERR_CONFLICTS,
6767 "conflicts must be resolved before rebasing can continue");
6768 } else
6769 error = rebase_complete(worktree, fileindex, branch,
6770 new_base_branch, tmp_branch, repo);
6771 done:
6772 got_object_id_queue_free(&commits);
6773 free(branch_head_commit_id);
6774 free(resume_commit_id);
6775 free(yca_id);
6776 if (commit)
6777 got_object_commit_close(commit);
6778 if (branch)
6779 got_ref_close(branch);
6780 if (new_base_branch)
6781 got_ref_close(new_base_branch);
6782 if (tmp_branch)
6783 got_ref_close(tmp_branch);
6784 if (worktree)
6785 got_worktree_close(worktree);
6786 if (repo)
6787 got_repo_close(repo);
6788 return error;
6791 __dead static void
6792 usage_histedit(void)
6794 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
6795 getprogname());
6796 exit(1);
6799 #define GOT_HISTEDIT_PICK 'p'
6800 #define GOT_HISTEDIT_EDIT 'e'
6801 #define GOT_HISTEDIT_FOLD 'f'
6802 #define GOT_HISTEDIT_DROP 'd'
6803 #define GOT_HISTEDIT_MESG 'm'
6805 static struct got_histedit_cmd {
6806 unsigned char code;
6807 const char *name;
6808 const char *desc;
6809 } got_histedit_cmds[] = {
6810 { GOT_HISTEDIT_PICK, "pick", "use commit" },
6811 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
6812 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
6813 "be used" },
6814 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
6815 { GOT_HISTEDIT_MESG, "mesg",
6816 "single-line log message for commit above (open editor if empty)" },
6819 struct got_histedit_list_entry {
6820 TAILQ_ENTRY(got_histedit_list_entry) entry;
6821 struct got_object_id *commit_id;
6822 const struct got_histedit_cmd *cmd;
6823 char *logmsg;
6825 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
6827 static const struct got_error *
6828 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
6829 FILE *f, struct got_repository *repo)
6831 const struct got_error *err = NULL;
6832 char *logmsg = NULL, *id_str = NULL;
6833 struct got_commit_object *commit = NULL;
6834 int n;
6836 err = got_object_open_as_commit(&commit, repo, commit_id);
6837 if (err)
6838 goto done;
6840 err = get_short_logmsg(&logmsg, 34, commit);
6841 if (err)
6842 goto done;
6844 err = got_object_id_str(&id_str, commit_id);
6845 if (err)
6846 goto done;
6848 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
6849 if (n < 0)
6850 err = got_ferror(f, GOT_ERR_IO);
6851 done:
6852 if (commit)
6853 got_object_commit_close(commit);
6854 free(id_str);
6855 free(logmsg);
6856 return err;
6859 static const struct got_error *
6860 histedit_write_commit_list(struct got_object_id_queue *commits,
6861 FILE *f, int edit_logmsg_only, struct got_repository *repo)
6863 const struct got_error *err = NULL;
6864 struct got_object_qid *qid;
6866 if (SIMPLEQ_EMPTY(commits))
6867 return got_error(GOT_ERR_EMPTY_HISTEDIT);
6869 SIMPLEQ_FOREACH(qid, commits, entry) {
6870 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
6871 f, repo);
6872 if (err)
6873 break;
6874 if (edit_logmsg_only) {
6875 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
6876 if (n < 0) {
6877 err = got_ferror(f, GOT_ERR_IO);
6878 break;
6883 return err;
6886 static const struct got_error *
6887 write_cmd_list(FILE *f, const char *branch_name,
6888 struct got_object_id_queue *commits)
6890 const struct got_error *err = NULL;
6891 int n, i;
6892 char *id_str;
6893 struct got_object_qid *qid;
6895 qid = SIMPLEQ_FIRST(commits);
6896 err = got_object_id_str(&id_str, qid->id);
6897 if (err)
6898 return err;
6900 n = fprintf(f,
6901 "# Editing the history of branch '%s' starting at\n"
6902 "# commit %s\n"
6903 "# Commits will be processed in order from top to "
6904 "bottom of this file.\n", branch_name, id_str);
6905 if (n < 0) {
6906 err = got_ferror(f, GOT_ERR_IO);
6907 goto done;
6910 n = fprintf(f, "# Available histedit commands:\n");
6911 if (n < 0) {
6912 err = got_ferror(f, GOT_ERR_IO);
6913 goto done;
6916 for (i = 0; i < nitems(got_histedit_cmds); i++) {
6917 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
6918 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
6919 cmd->desc);
6920 if (n < 0) {
6921 err = got_ferror(f, GOT_ERR_IO);
6922 break;
6925 done:
6926 free(id_str);
6927 return err;
6930 static const struct got_error *
6931 histedit_syntax_error(int lineno)
6933 static char msg[42];
6934 int ret;
6936 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
6937 lineno);
6938 if (ret == -1 || ret >= sizeof(msg))
6939 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
6941 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
6944 static const struct got_error *
6945 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
6946 char *logmsg, struct got_repository *repo)
6948 const struct got_error *err;
6949 struct got_commit_object *folded_commit = NULL;
6950 char *id_str, *folded_logmsg = NULL;
6952 err = got_object_id_str(&id_str, hle->commit_id);
6953 if (err)
6954 return err;
6956 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
6957 if (err)
6958 goto done;
6960 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
6961 if (err)
6962 goto done;
6963 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
6964 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
6965 folded_logmsg) == -1) {
6966 err = got_error_from_errno("asprintf");
6968 done:
6969 if (folded_commit)
6970 got_object_commit_close(folded_commit);
6971 free(id_str);
6972 free(folded_logmsg);
6973 return err;
6976 static struct got_histedit_list_entry *
6977 get_folded_commits(struct got_histedit_list_entry *hle)
6979 struct got_histedit_list_entry *prev, *folded = NULL;
6981 prev = TAILQ_PREV(hle, got_histedit_list, entry);
6982 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
6983 prev->cmd->code == GOT_HISTEDIT_DROP)) {
6984 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
6985 folded = prev;
6986 prev = TAILQ_PREV(prev, got_histedit_list, entry);
6989 return folded;
6992 static const struct got_error *
6993 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
6994 struct got_repository *repo)
6996 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
6997 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
6998 const struct got_error *err = NULL;
6999 struct got_commit_object *commit = NULL;
7000 int fd;
7001 struct got_histedit_list_entry *folded = NULL;
7003 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7004 if (err)
7005 return err;
7007 folded = get_folded_commits(hle);
7008 if (folded) {
7009 while (folded != hle) {
7010 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7011 folded = TAILQ_NEXT(folded, entry);
7012 continue;
7014 err = append_folded_commit_msg(&new_msg, folded,
7015 logmsg, repo);
7016 if (err)
7017 goto done;
7018 free(logmsg);
7019 logmsg = new_msg;
7020 folded = TAILQ_NEXT(folded, entry);
7024 err = got_object_id_str(&id_str, hle->commit_id);
7025 if (err)
7026 goto done;
7027 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7028 if (err)
7029 goto done;
7030 if (asprintf(&new_msg,
7031 "%s\n# original log message of commit %s: %s",
7032 logmsg ? logmsg : "", id_str, orig_logmsg) == -1) {
7033 err = got_error_from_errno("asprintf");
7034 goto done;
7036 free(logmsg);
7037 logmsg = new_msg;
7039 err = got_object_id_str(&id_str, hle->commit_id);
7040 if (err)
7041 goto done;
7043 err = got_opentemp_named_fd(&logmsg_path, &fd,
7044 GOT_TMPDIR_STR "/got-logmsg");
7045 if (err)
7046 goto done;
7048 dprintf(fd, logmsg);
7049 close(fd);
7051 err = get_editor(&editor);
7052 if (err)
7053 goto done;
7055 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
7056 if (err) {
7057 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
7058 goto done;
7059 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
7061 done:
7062 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
7063 err = got_error_from_errno2("unlink", logmsg_path);
7064 free(logmsg_path);
7065 free(logmsg);
7066 free(orig_logmsg);
7067 free(editor);
7068 if (commit)
7069 got_object_commit_close(commit);
7070 return err;
7073 static const struct got_error *
7074 histedit_parse_list(struct got_histedit_list *histedit_cmds,
7075 FILE *f, struct got_repository *repo)
7077 const struct got_error *err = NULL;
7078 char *line = NULL, *p, *end;
7079 size_t size;
7080 ssize_t len;
7081 int lineno = 0, i;
7082 const struct got_histedit_cmd *cmd;
7083 struct got_object_id *commit_id = NULL;
7084 struct got_histedit_list_entry *hle = NULL;
7086 for (;;) {
7087 len = getline(&line, &size, f);
7088 if (len == -1) {
7089 const struct got_error *getline_err;
7090 if (feof(f))
7091 break;
7092 getline_err = got_error_from_errno("getline");
7093 err = got_ferror(f, getline_err->code);
7094 break;
7096 lineno++;
7097 p = line;
7098 while (isspace((unsigned char)p[0]))
7099 p++;
7100 if (p[0] == '#' || p[0] == '\0') {
7101 free(line);
7102 line = NULL;
7103 continue;
7105 cmd = NULL;
7106 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7107 cmd = &got_histedit_cmds[i];
7108 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
7109 isspace((unsigned char)p[strlen(cmd->name)])) {
7110 p += strlen(cmd->name);
7111 break;
7113 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
7114 p++;
7115 break;
7118 if (i == nitems(got_histedit_cmds)) {
7119 err = histedit_syntax_error(lineno);
7120 break;
7122 while (isspace((unsigned char)p[0]))
7123 p++;
7124 if (cmd->code == GOT_HISTEDIT_MESG) {
7125 if (hle == NULL || hle->logmsg != NULL) {
7126 err = got_error(GOT_ERR_HISTEDIT_CMD);
7127 break;
7129 if (p[0] == '\0') {
7130 err = histedit_edit_logmsg(hle, repo);
7131 if (err)
7132 break;
7133 } else {
7134 hle->logmsg = strdup(p);
7135 if (hle->logmsg == NULL) {
7136 err = got_error_from_errno("strdup");
7137 break;
7140 free(line);
7141 line = NULL;
7142 continue;
7143 } else {
7144 end = p;
7145 while (end[0] && !isspace((unsigned char)end[0]))
7146 end++;
7147 *end = '\0';
7149 err = got_object_resolve_id_str(&commit_id, repo, p);
7150 if (err) {
7151 /* override error code */
7152 err = histedit_syntax_error(lineno);
7153 break;
7156 hle = malloc(sizeof(*hle));
7157 if (hle == NULL) {
7158 err = got_error_from_errno("malloc");
7159 break;
7161 hle->cmd = cmd;
7162 hle->commit_id = commit_id;
7163 hle->logmsg = NULL;
7164 commit_id = NULL;
7165 free(line);
7166 line = NULL;
7167 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
7170 free(line);
7171 free(commit_id);
7172 return err;
7175 static const struct got_error *
7176 histedit_check_script(struct got_histedit_list *histedit_cmds,
7177 struct got_object_id_queue *commits, struct got_repository *repo)
7179 const struct got_error *err = NULL;
7180 struct got_object_qid *qid;
7181 struct got_histedit_list_entry *hle;
7182 static char msg[92];
7183 char *id_str;
7185 if (TAILQ_EMPTY(histedit_cmds))
7186 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
7187 "histedit script contains no commands");
7188 if (SIMPLEQ_EMPTY(commits))
7189 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7191 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7192 struct got_histedit_list_entry *hle2;
7193 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
7194 if (hle == hle2)
7195 continue;
7196 if (got_object_id_cmp(hle->commit_id,
7197 hle2->commit_id) != 0)
7198 continue;
7199 err = got_object_id_str(&id_str, hle->commit_id);
7200 if (err)
7201 return err;
7202 snprintf(msg, sizeof(msg), "commit %s is listed "
7203 "more than once in histedit script", id_str);
7204 free(id_str);
7205 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7209 SIMPLEQ_FOREACH(qid, commits, entry) {
7210 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7211 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
7212 break;
7214 if (hle == NULL) {
7215 err = got_object_id_str(&id_str, qid->id);
7216 if (err)
7217 return err;
7218 snprintf(msg, sizeof(msg),
7219 "commit %s missing from histedit script", id_str);
7220 free(id_str);
7221 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7225 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
7226 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
7227 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
7228 "last commit in histedit script cannot be folded");
7230 return NULL;
7233 static const struct got_error *
7234 histedit_run_editor(struct got_histedit_list *histedit_cmds,
7235 const char *path, struct got_object_id_queue *commits,
7236 struct got_repository *repo)
7238 const struct got_error *err = NULL;
7239 char *editor;
7240 FILE *f = NULL;
7242 err = get_editor(&editor);
7243 if (err)
7244 return err;
7246 if (spawn_editor(editor, path) == -1) {
7247 err = got_error_from_errno("failed spawning editor");
7248 goto done;
7251 f = fopen(path, "r");
7252 if (f == NULL) {
7253 err = got_error_from_errno("fopen");
7254 goto done;
7256 err = histedit_parse_list(histedit_cmds, f, repo);
7257 if (err)
7258 goto done;
7260 err = histedit_check_script(histedit_cmds, commits, repo);
7261 done:
7262 if (f && fclose(f) != 0 && err == NULL)
7263 err = got_error_from_errno("fclose");
7264 free(editor);
7265 return err;
7268 static const struct got_error *
7269 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
7270 struct got_object_id_queue *, const char *, const char *,
7271 struct got_repository *);
7273 static const struct got_error *
7274 histedit_edit_script(struct got_histedit_list *histedit_cmds,
7275 struct got_object_id_queue *commits, const char *branch_name,
7276 int edit_logmsg_only, struct got_repository *repo)
7278 const struct got_error *err;
7279 FILE *f = NULL;
7280 char *path = NULL;
7282 err = got_opentemp_named(&path, &f, "got-histedit");
7283 if (err)
7284 return err;
7286 err = write_cmd_list(f, branch_name, commits);
7287 if (err)
7288 goto done;
7290 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
7291 if (err)
7292 goto done;
7294 if (edit_logmsg_only) {
7295 rewind(f);
7296 err = histedit_parse_list(histedit_cmds, f, repo);
7297 } else {
7298 if (fclose(f) != 0) {
7299 err = got_error_from_errno("fclose");
7300 goto done;
7302 f = NULL;
7303 err = histedit_run_editor(histedit_cmds, path, commits, repo);
7304 if (err) {
7305 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7306 err->code != GOT_ERR_HISTEDIT_CMD)
7307 goto done;
7308 err = histedit_edit_list_retry(histedit_cmds, err,
7309 commits, path, branch_name, repo);
7312 done:
7313 if (f && fclose(f) != 0 && err == NULL)
7314 err = got_error_from_errno("fclose");
7315 if (path && unlink(path) != 0 && err == NULL)
7316 err = got_error_from_errno2("unlink", path);
7317 free(path);
7318 return err;
7321 static const struct got_error *
7322 histedit_save_list(struct got_histedit_list *histedit_cmds,
7323 struct got_worktree *worktree, struct got_repository *repo)
7325 const struct got_error *err = NULL;
7326 char *path = NULL;
7327 FILE *f = NULL;
7328 struct got_histedit_list_entry *hle;
7329 struct got_commit_object *commit = NULL;
7331 err = got_worktree_get_histedit_script_path(&path, worktree);
7332 if (err)
7333 return err;
7335 f = fopen(path, "w");
7336 if (f == NULL) {
7337 err = got_error_from_errno2("fopen", path);
7338 goto done;
7340 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7341 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
7342 repo);
7343 if (err)
7344 break;
7346 if (hle->logmsg) {
7347 int n = fprintf(f, "%c %s\n",
7348 GOT_HISTEDIT_MESG, hle->logmsg);
7349 if (n < 0) {
7350 err = got_ferror(f, GOT_ERR_IO);
7351 break;
7355 done:
7356 if (f && fclose(f) != 0 && err == NULL)
7357 err = got_error_from_errno("fclose");
7358 free(path);
7359 if (commit)
7360 got_object_commit_close(commit);
7361 return err;
7364 void
7365 histedit_free_list(struct got_histedit_list *histedit_cmds)
7367 struct got_histedit_list_entry *hle;
7369 while ((hle = TAILQ_FIRST(histedit_cmds))) {
7370 TAILQ_REMOVE(histedit_cmds, hle, entry);
7371 free(hle);
7375 static const struct got_error *
7376 histedit_load_list(struct got_histedit_list *histedit_cmds,
7377 const char *path, struct got_repository *repo)
7379 const struct got_error *err = NULL;
7380 FILE *f = NULL;
7382 f = fopen(path, "r");
7383 if (f == NULL) {
7384 err = got_error_from_errno2("fopen", path);
7385 goto done;
7388 err = histedit_parse_list(histedit_cmds, f, repo);
7389 done:
7390 if (f && fclose(f) != 0 && err == NULL)
7391 err = got_error_from_errno("fclose");
7392 return err;
7395 static const struct got_error *
7396 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
7397 const struct got_error *edit_err, struct got_object_id_queue *commits,
7398 const char *path, const char *branch_name, struct got_repository *repo)
7400 const struct got_error *err = NULL, *prev_err = edit_err;
7401 int resp = ' ';
7403 while (resp != 'c' && resp != 'r' && resp != 'a') {
7404 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
7405 "or (a)bort: ", getprogname(), prev_err->msg);
7406 resp = getchar();
7407 if (resp == '\n')
7408 resp = getchar();
7409 if (resp == 'c') {
7410 histedit_free_list(histedit_cmds);
7411 err = histedit_run_editor(histedit_cmds, path, commits,
7412 repo);
7413 if (err) {
7414 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7415 err->code != GOT_ERR_HISTEDIT_CMD)
7416 break;
7417 prev_err = err;
7418 resp = ' ';
7419 continue;
7421 break;
7422 } else if (resp == 'r') {
7423 histedit_free_list(histedit_cmds);
7424 err = histedit_edit_script(histedit_cmds,
7425 commits, branch_name, 0, repo);
7426 if (err) {
7427 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7428 err->code != GOT_ERR_HISTEDIT_CMD)
7429 break;
7430 prev_err = err;
7431 resp = ' ';
7432 continue;
7434 break;
7435 } else if (resp == 'a') {
7436 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
7437 break;
7438 } else
7439 printf("invalid response '%c'\n", resp);
7442 return err;
7445 static const struct got_error *
7446 histedit_complete(struct got_worktree *worktree,
7447 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
7448 struct got_reference *branch, struct got_repository *repo)
7450 printf("Switching work tree to %s\n",
7451 got_ref_get_symref_target(branch));
7452 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
7453 branch, repo);
7456 static const struct got_error *
7457 show_histedit_progress(struct got_commit_object *commit,
7458 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
7460 const struct got_error *err;
7461 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7463 err = got_object_id_str(&old_id_str, hle->commit_id);
7464 if (err)
7465 goto done;
7467 if (new_id) {
7468 err = got_object_id_str(&new_id_str, new_id);
7469 if (err)
7470 goto done;
7473 old_id_str[12] = '\0';
7474 if (new_id_str)
7475 new_id_str[12] = '\0';
7477 if (hle->logmsg) {
7478 logmsg = strdup(hle->logmsg);
7479 if (logmsg == NULL) {
7480 err = got_error_from_errno("strdup");
7481 goto done;
7483 trim_logmsg(logmsg, 42);
7484 } else {
7485 err = get_short_logmsg(&logmsg, 42, commit);
7486 if (err)
7487 goto done;
7490 switch (hle->cmd->code) {
7491 case GOT_HISTEDIT_PICK:
7492 case GOT_HISTEDIT_EDIT:
7493 printf("%s -> %s: %s\n", old_id_str,
7494 new_id_str ? new_id_str : "no-op change", logmsg);
7495 break;
7496 case GOT_HISTEDIT_DROP:
7497 case GOT_HISTEDIT_FOLD:
7498 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
7499 logmsg);
7500 break;
7501 default:
7502 break;
7504 done:
7505 free(old_id_str);
7506 free(new_id_str);
7507 return err;
7510 static const struct got_error *
7511 histedit_commit(struct got_pathlist_head *merged_paths,
7512 struct got_worktree *worktree, struct got_fileindex *fileindex,
7513 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
7514 struct got_repository *repo)
7516 const struct got_error *err;
7517 struct got_commit_object *commit;
7518 struct got_object_id *new_commit_id;
7520 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
7521 && hle->logmsg == NULL) {
7522 err = histedit_edit_logmsg(hle, repo);
7523 if (err)
7524 return err;
7527 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7528 if (err)
7529 return err;
7531 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
7532 worktree, fileindex, tmp_branch, commit, hle->commit_id,
7533 hle->logmsg, repo);
7534 if (err) {
7535 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
7536 goto done;
7537 err = show_histedit_progress(commit, hle, NULL);
7538 } else {
7539 err = show_histedit_progress(commit, hle, new_commit_id);
7540 free(new_commit_id);
7542 done:
7543 got_object_commit_close(commit);
7544 return err;
7547 static const struct got_error *
7548 histedit_skip_commit(struct got_histedit_list_entry *hle,
7549 struct got_worktree *worktree, struct got_repository *repo)
7551 const struct got_error *error;
7552 struct got_commit_object *commit;
7554 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
7555 repo);
7556 if (error)
7557 return error;
7559 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
7560 if (error)
7561 return error;
7563 error = show_histedit_progress(commit, hle, NULL);
7564 got_object_commit_close(commit);
7565 return error;
7568 static const struct got_error *
7569 check_local_changes(void *arg, unsigned char status,
7570 unsigned char staged_status, const char *path,
7571 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
7572 struct got_object_id *commit_id, int dirfd, const char *de_name)
7574 int *have_local_changes = arg;
7576 switch (status) {
7577 case GOT_STATUS_ADD:
7578 case GOT_STATUS_DELETE:
7579 case GOT_STATUS_MODIFY:
7580 case GOT_STATUS_CONFLICT:
7581 *have_local_changes = 1;
7582 return got_error(GOT_ERR_CANCELLED);
7583 default:
7584 break;
7587 switch (staged_status) {
7588 case GOT_STATUS_ADD:
7589 case GOT_STATUS_DELETE:
7590 case GOT_STATUS_MODIFY:
7591 *have_local_changes = 1;
7592 return got_error(GOT_ERR_CANCELLED);
7593 default:
7594 break;
7597 return NULL;
7600 static const struct got_error *
7601 cmd_histedit(int argc, char *argv[])
7603 const struct got_error *error = NULL;
7604 struct got_worktree *worktree = NULL;
7605 struct got_fileindex *fileindex = NULL;
7606 struct got_repository *repo = NULL;
7607 char *cwd = NULL;
7608 struct got_reference *branch = NULL;
7609 struct got_reference *tmp_branch = NULL;
7610 struct got_object_id *resume_commit_id = NULL;
7611 struct got_object_id *base_commit_id = NULL;
7612 struct got_object_id *head_commit_id = NULL;
7613 struct got_commit_object *commit = NULL;
7614 int ch, rebase_in_progress = 0, did_something;
7615 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
7616 int edit_logmsg_only = 0;
7617 const char *edit_script_path = NULL;
7618 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7619 struct got_object_id_queue commits;
7620 struct got_pathlist_head merged_paths;
7621 const struct got_object_id_queue *parent_ids;
7622 struct got_object_qid *pid;
7623 struct got_histedit_list histedit_cmds;
7624 struct got_histedit_list_entry *hle;
7626 SIMPLEQ_INIT(&commits);
7627 TAILQ_INIT(&histedit_cmds);
7628 TAILQ_INIT(&merged_paths);
7630 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
7631 switch (ch) {
7632 case 'a':
7633 abort_edit = 1;
7634 break;
7635 case 'c':
7636 continue_edit = 1;
7637 break;
7638 case 'F':
7639 edit_script_path = optarg;
7640 break;
7641 case 'm':
7642 edit_logmsg_only = 1;
7643 break;
7644 default:
7645 usage_histedit();
7646 /* NOTREACHED */
7650 argc -= optind;
7651 argv += optind;
7653 #ifndef PROFILE
7654 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7655 "unveil", NULL) == -1)
7656 err(1, "pledge");
7657 #endif
7658 if (abort_edit && continue_edit)
7659 errx(1, "histedit's -a and -c options are mutually exclusive");
7660 if (edit_script_path && edit_logmsg_only)
7661 errx(1, "histedit's -F and -m options are mutually exclusive");
7662 if (abort_edit && edit_logmsg_only)
7663 errx(1, "histedit's -a and -m options are mutually exclusive");
7664 if (continue_edit && edit_logmsg_only)
7665 errx(1, "histedit's -c and -m options are mutually exclusive");
7666 if (argc != 0)
7667 usage_histedit();
7670 * This command cannot apply unveil(2) in all cases because the
7671 * user may choose to run an editor to edit the histedit script
7672 * and to edit individual commit log messages.
7673 * unveil(2) traverses exec(2); if an editor is used we have to
7674 * apply unveil after edit script and log messages have been written.
7675 * XXX TODO: Make use of unveil(2) where possible.
7678 cwd = getcwd(NULL, 0);
7679 if (cwd == NULL) {
7680 error = got_error_from_errno("getcwd");
7681 goto done;
7683 error = got_worktree_open(&worktree, cwd);
7684 if (error)
7685 goto done;
7687 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7688 NULL);
7689 if (error != NULL)
7690 goto done;
7692 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7693 if (error)
7694 goto done;
7695 if (rebase_in_progress) {
7696 error = got_error(GOT_ERR_REBASING);
7697 goto done;
7700 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
7701 if (error)
7702 goto done;
7704 if (edit_in_progress && edit_logmsg_only) {
7705 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
7706 "histedit operation is in progress in this "
7707 "work tree and must be continued or aborted "
7708 "before the -m option can be used");
7709 goto done;
7712 if (edit_in_progress && abort_edit) {
7713 error = got_worktree_histedit_continue(&resume_commit_id,
7714 &tmp_branch, &branch, &base_commit_id, &fileindex,
7715 worktree, repo);
7716 if (error)
7717 goto done;
7718 printf("Switching work tree to %s\n",
7719 got_ref_get_symref_target(branch));
7720 error = got_worktree_histedit_abort(worktree, fileindex, repo,
7721 branch, base_commit_id, update_progress, &did_something);
7722 if (error)
7723 goto done;
7724 printf("Histedit of %s aborted\n",
7725 got_ref_get_symref_target(branch));
7726 goto done; /* nothing else to do */
7727 } else if (abort_edit) {
7728 error = got_error(GOT_ERR_NOT_HISTEDIT);
7729 goto done;
7732 if (continue_edit) {
7733 char *path;
7735 if (!edit_in_progress) {
7736 error = got_error(GOT_ERR_NOT_HISTEDIT);
7737 goto done;
7740 error = got_worktree_get_histedit_script_path(&path, worktree);
7741 if (error)
7742 goto done;
7744 error = histedit_load_list(&histedit_cmds, path, repo);
7745 free(path);
7746 if (error)
7747 goto done;
7749 error = got_worktree_histedit_continue(&resume_commit_id,
7750 &tmp_branch, &branch, &base_commit_id, &fileindex,
7751 worktree, repo);
7752 if (error)
7753 goto done;
7755 error = got_ref_resolve(&head_commit_id, repo, branch);
7756 if (error)
7757 goto done;
7759 error = got_object_open_as_commit(&commit, repo,
7760 head_commit_id);
7761 if (error)
7762 goto done;
7763 parent_ids = got_object_commit_get_parent_ids(commit);
7764 pid = SIMPLEQ_FIRST(parent_ids);
7765 if (pid == NULL) {
7766 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
7767 goto done;
7769 error = collect_commits(&commits, head_commit_id, pid->id,
7770 base_commit_id, got_worktree_get_path_prefix(worktree),
7771 GOT_ERR_HISTEDIT_PATH, repo);
7772 got_object_commit_close(commit);
7773 commit = NULL;
7774 if (error)
7775 goto done;
7776 } else {
7777 if (edit_in_progress) {
7778 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7779 goto done;
7782 error = got_ref_open(&branch, repo,
7783 got_worktree_get_head_ref_name(worktree), 0);
7784 if (error != NULL)
7785 goto done;
7787 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
7788 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
7789 "will not edit commit history of a branch outside "
7790 "the \"refs/heads/\" reference namespace");
7791 goto done;
7794 error = got_ref_resolve(&head_commit_id, repo, branch);
7795 got_ref_close(branch);
7796 branch = NULL;
7797 if (error)
7798 goto done;
7800 error = got_object_open_as_commit(&commit, repo,
7801 head_commit_id);
7802 if (error)
7803 goto done;
7804 parent_ids = got_object_commit_get_parent_ids(commit);
7805 pid = SIMPLEQ_FIRST(parent_ids);
7806 if (pid == NULL) {
7807 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
7808 goto done;
7810 error = collect_commits(&commits, head_commit_id, pid->id,
7811 got_worktree_get_base_commit_id(worktree),
7812 got_worktree_get_path_prefix(worktree),
7813 GOT_ERR_HISTEDIT_PATH, repo);
7814 got_object_commit_close(commit);
7815 commit = NULL;
7816 if (error)
7817 goto done;
7819 if (SIMPLEQ_EMPTY(&commits)) {
7820 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
7821 goto done;
7824 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
7825 &base_commit_id, &fileindex, worktree, repo);
7826 if (error)
7827 goto done;
7829 if (edit_script_path) {
7830 error = histedit_load_list(&histedit_cmds,
7831 edit_script_path, repo);
7832 if (error) {
7833 got_worktree_histedit_abort(worktree, fileindex,
7834 repo, branch, base_commit_id,
7835 update_progress, &did_something);
7836 goto done;
7838 } else {
7839 const char *branch_name;
7840 branch_name = got_ref_get_symref_target(branch);
7841 if (strncmp(branch_name, "refs/heads/", 11) == 0)
7842 branch_name += 11;
7843 error = histedit_edit_script(&histedit_cmds, &commits,
7844 branch_name, edit_logmsg_only, repo);
7845 if (error) {
7846 got_worktree_histedit_abort(worktree, fileindex,
7847 repo, branch, base_commit_id,
7848 update_progress, &did_something);
7849 goto done;
7854 error = histedit_save_list(&histedit_cmds, worktree,
7855 repo);
7856 if (error) {
7857 got_worktree_histedit_abort(worktree, fileindex,
7858 repo, branch, base_commit_id,
7859 update_progress, &did_something);
7860 goto done;
7865 error = histedit_check_script(&histedit_cmds, &commits, repo);
7866 if (error)
7867 goto done;
7869 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
7870 if (resume_commit_id) {
7871 if (got_object_id_cmp(hle->commit_id,
7872 resume_commit_id) != 0)
7873 continue;
7875 resume_commit_id = NULL;
7876 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
7877 hle->cmd->code == GOT_HISTEDIT_FOLD) {
7878 error = histedit_skip_commit(hle, worktree,
7879 repo);
7880 if (error)
7881 goto done;
7882 } else {
7883 struct got_pathlist_head paths;
7884 int have_changes = 0;
7886 TAILQ_INIT(&paths);
7887 error = got_pathlist_append(&paths, "", NULL);
7888 if (error)
7889 goto done;
7890 error = got_worktree_status(worktree, &paths,
7891 repo, check_local_changes, &have_changes,
7892 check_cancelled, NULL);
7893 got_pathlist_free(&paths);
7894 if (error) {
7895 if (error->code != GOT_ERR_CANCELLED)
7896 goto done;
7897 if (sigint_received || sigpipe_received)
7898 goto done;
7900 if (have_changes) {
7901 error = histedit_commit(NULL, worktree,
7902 fileindex, tmp_branch, hle, repo);
7903 if (error)
7904 goto done;
7905 } else {
7906 error = got_object_open_as_commit(
7907 &commit, repo, hle->commit_id);
7908 if (error)
7909 goto done;
7910 error = show_histedit_progress(commit,
7911 hle, NULL);
7912 got_object_commit_close(commit);
7913 commit = NULL;
7914 if (error)
7915 goto done;
7918 continue;
7921 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
7922 error = histedit_skip_commit(hle, worktree, repo);
7923 if (error)
7924 goto done;
7925 continue;
7928 error = got_object_open_as_commit(&commit, repo,
7929 hle->commit_id);
7930 if (error)
7931 goto done;
7932 parent_ids = got_object_commit_get_parent_ids(commit);
7933 pid = SIMPLEQ_FIRST(parent_ids);
7935 error = got_worktree_histedit_merge_files(&merged_paths,
7936 worktree, fileindex, pid->id, hle->commit_id, repo,
7937 rebase_progress, &rebase_status, check_cancelled, NULL);
7938 if (error)
7939 goto done;
7940 got_object_commit_close(commit);
7941 commit = NULL;
7943 if (rebase_status == GOT_STATUS_CONFLICT) {
7944 error = show_rebase_merge_conflict(hle->commit_id,
7945 repo);
7946 if (error)
7947 goto done;
7948 got_worktree_rebase_pathlist_free(&merged_paths);
7949 break;
7952 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
7953 char *id_str;
7954 error = got_object_id_str(&id_str, hle->commit_id);
7955 if (error)
7956 goto done;
7957 printf("Stopping histedit for amending commit %s\n",
7958 id_str);
7959 free(id_str);
7960 got_worktree_rebase_pathlist_free(&merged_paths);
7961 error = got_worktree_histedit_postpone(worktree,
7962 fileindex);
7963 goto done;
7966 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
7967 error = histedit_skip_commit(hle, worktree, repo);
7968 if (error)
7969 goto done;
7970 continue;
7973 error = histedit_commit(&merged_paths, worktree, fileindex,
7974 tmp_branch, hle, repo);
7975 got_worktree_rebase_pathlist_free(&merged_paths);
7976 if (error)
7977 goto done;
7980 if (rebase_status == GOT_STATUS_CONFLICT) {
7981 error = got_worktree_histedit_postpone(worktree, fileindex);
7982 if (error)
7983 goto done;
7984 error = got_error_msg(GOT_ERR_CONFLICTS,
7985 "conflicts must be resolved before histedit can continue");
7986 } else
7987 error = histedit_complete(worktree, fileindex, tmp_branch,
7988 branch, repo);
7989 done:
7990 got_object_id_queue_free(&commits);
7991 histedit_free_list(&histedit_cmds);
7992 free(head_commit_id);
7993 free(base_commit_id);
7994 free(resume_commit_id);
7995 if (commit)
7996 got_object_commit_close(commit);
7997 if (branch)
7998 got_ref_close(branch);
7999 if (tmp_branch)
8000 got_ref_close(tmp_branch);
8001 if (worktree)
8002 got_worktree_close(worktree);
8003 if (repo)
8004 got_repo_close(repo);
8005 return error;
8008 __dead static void
8009 usage_integrate(void)
8011 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
8012 exit(1);
8015 static const struct got_error *
8016 cmd_integrate(int argc, char *argv[])
8018 const struct got_error *error = NULL;
8019 struct got_repository *repo = NULL;
8020 struct got_worktree *worktree = NULL;
8021 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
8022 const char *branch_arg = NULL;
8023 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
8024 struct got_fileindex *fileindex = NULL;
8025 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
8026 int ch, did_something = 0;
8028 while ((ch = getopt(argc, argv, "")) != -1) {
8029 switch (ch) {
8030 default:
8031 usage_integrate();
8032 /* NOTREACHED */
8036 argc -= optind;
8037 argv += optind;
8039 if (argc != 1)
8040 usage_integrate();
8041 branch_arg = argv[0];
8043 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8044 "unveil", NULL) == -1)
8045 err(1, "pledge");
8047 cwd = getcwd(NULL, 0);
8048 if (cwd == NULL) {
8049 error = got_error_from_errno("getcwd");
8050 goto done;
8053 error = got_worktree_open(&worktree, cwd);
8054 if (error)
8055 goto done;
8057 error = check_rebase_or_histedit_in_progress(worktree);
8058 if (error)
8059 goto done;
8061 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8062 NULL);
8063 if (error != NULL)
8064 goto done;
8066 error = apply_unveil(got_repo_get_path(repo), 0,
8067 got_worktree_get_root_path(worktree));
8068 if (error)
8069 goto done;
8071 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
8072 error = got_error_from_errno("asprintf");
8073 goto done;
8076 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
8077 &base_branch_ref, worktree, refname, repo);
8078 if (error)
8079 goto done;
8081 refname = strdup(got_ref_get_name(branch_ref));
8082 if (refname == NULL) {
8083 error = got_error_from_errno("strdup");
8084 got_worktree_integrate_abort(worktree, fileindex, repo,
8085 branch_ref, base_branch_ref);
8086 goto done;
8088 base_refname = strdup(got_ref_get_name(base_branch_ref));
8089 if (base_refname == NULL) {
8090 error = got_error_from_errno("strdup");
8091 got_worktree_integrate_abort(worktree, fileindex, repo,
8092 branch_ref, base_branch_ref);
8093 goto done;
8096 error = got_ref_resolve(&commit_id, repo, branch_ref);
8097 if (error)
8098 goto done;
8100 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
8101 if (error)
8102 goto done;
8104 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
8105 error = got_error_msg(GOT_ERR_SAME_BRANCH,
8106 "specified branch has already been integrated");
8107 got_worktree_integrate_abort(worktree, fileindex, repo,
8108 branch_ref, base_branch_ref);
8109 goto done;
8112 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
8113 if (error) {
8114 if (error->code == GOT_ERR_ANCESTRY)
8115 error = got_error(GOT_ERR_REBASE_REQUIRED);
8116 got_worktree_integrate_abort(worktree, fileindex, repo,
8117 branch_ref, base_branch_ref);
8118 goto done;
8121 error = got_worktree_integrate_continue(worktree, fileindex, repo,
8122 branch_ref, base_branch_ref, update_progress, &did_something,
8123 check_cancelled, NULL);
8124 if (error)
8125 goto done;
8127 printf("Integrated %s into %s\n", refname, base_refname);
8128 done:
8129 if (repo)
8130 got_repo_close(repo);
8131 if (worktree)
8132 got_worktree_close(worktree);
8133 free(cwd);
8134 free(base_commit_id);
8135 free(commit_id);
8136 free(refname);
8137 free(base_refname);
8138 return error;
8141 __dead static void
8142 usage_stage(void)
8144 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
8145 "[file-path ...]\n",
8146 getprogname());
8147 exit(1);
8150 static const struct got_error *
8151 print_stage(void *arg, unsigned char status, unsigned char staged_status,
8152 const char *path, struct got_object_id *blob_id,
8153 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
8154 int dirfd, const char *de_name)
8156 const struct got_error *err = NULL;
8157 char *id_str = NULL;
8159 if (staged_status != GOT_STATUS_ADD &&
8160 staged_status != GOT_STATUS_MODIFY &&
8161 staged_status != GOT_STATUS_DELETE)
8162 return NULL;
8164 if (staged_status == GOT_STATUS_ADD ||
8165 staged_status == GOT_STATUS_MODIFY)
8166 err = got_object_id_str(&id_str, staged_blob_id);
8167 else
8168 err = got_object_id_str(&id_str, blob_id);
8169 if (err)
8170 return err;
8172 printf("%s %c %s\n", id_str, staged_status, path);
8173 free(id_str);
8174 return NULL;
8177 static const struct got_error *
8178 cmd_stage(int argc, char *argv[])
8180 const struct got_error *error = NULL;
8181 struct got_repository *repo = NULL;
8182 struct got_worktree *worktree = NULL;
8183 char *cwd = NULL;
8184 struct got_pathlist_head paths;
8185 struct got_pathlist_entry *pe;
8186 int ch, list_stage = 0, pflag = 0;
8187 FILE *patch_script_file = NULL;
8188 const char *patch_script_path = NULL;
8189 struct choose_patch_arg cpa;
8191 TAILQ_INIT(&paths);
8193 while ((ch = getopt(argc, argv, "lpF:")) != -1) {
8194 switch (ch) {
8195 case 'l':
8196 list_stage = 1;
8197 break;
8198 case 'p':
8199 pflag = 1;
8200 break;
8201 case 'F':
8202 patch_script_path = optarg;
8203 break;
8204 default:
8205 usage_stage();
8206 /* NOTREACHED */
8210 argc -= optind;
8211 argv += optind;
8213 #ifndef PROFILE
8214 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8215 "unveil", NULL) == -1)
8216 err(1, "pledge");
8217 #endif
8218 if (list_stage && (pflag || patch_script_path))
8219 errx(1, "-l option cannot be used with other options");
8220 if (patch_script_path && !pflag)
8221 errx(1, "-F option can only be used together with -p option");
8223 cwd = getcwd(NULL, 0);
8224 if (cwd == NULL) {
8225 error = got_error_from_errno("getcwd");
8226 goto done;
8229 error = got_worktree_open(&worktree, cwd);
8230 if (error)
8231 goto done;
8233 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8234 NULL);
8235 if (error != NULL)
8236 goto done;
8238 if (patch_script_path) {
8239 patch_script_file = fopen(patch_script_path, "r");
8240 if (patch_script_file == NULL) {
8241 error = got_error_from_errno2("fopen",
8242 patch_script_path);
8243 goto done;
8246 error = apply_unveil(got_repo_get_path(repo), 0,
8247 got_worktree_get_root_path(worktree));
8248 if (error)
8249 goto done;
8251 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8252 if (error)
8253 goto done;
8255 if (list_stage)
8256 error = got_worktree_status(worktree, &paths, repo,
8257 print_stage, NULL, check_cancelled, NULL);
8258 else {
8259 cpa.patch_script_file = patch_script_file;
8260 cpa.action = "stage";
8261 error = got_worktree_stage(worktree, &paths,
8262 pflag ? NULL : print_status, NULL,
8263 pflag ? choose_patch : NULL, &cpa, repo);
8265 done:
8266 if (patch_script_file && fclose(patch_script_file) == EOF &&
8267 error == NULL)
8268 error = got_error_from_errno2("fclose", patch_script_path);
8269 if (repo)
8270 got_repo_close(repo);
8271 if (worktree)
8272 got_worktree_close(worktree);
8273 TAILQ_FOREACH(pe, &paths, entry)
8274 free((char *)pe->path);
8275 got_pathlist_free(&paths);
8276 free(cwd);
8277 return error;
8280 __dead static void
8281 usage_unstage(void)
8283 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
8284 "[file-path ...]\n",
8285 getprogname());
8286 exit(1);
8290 static const struct got_error *
8291 cmd_unstage(int argc, char *argv[])
8293 const struct got_error *error = NULL;
8294 struct got_repository *repo = NULL;
8295 struct got_worktree *worktree = NULL;
8296 char *cwd = NULL;
8297 struct got_pathlist_head paths;
8298 struct got_pathlist_entry *pe;
8299 int ch, did_something = 0, pflag = 0;
8300 FILE *patch_script_file = NULL;
8301 const char *patch_script_path = NULL;
8302 struct choose_patch_arg cpa;
8304 TAILQ_INIT(&paths);
8306 while ((ch = getopt(argc, argv, "pF:")) != -1) {
8307 switch (ch) {
8308 case 'p':
8309 pflag = 1;
8310 break;
8311 case 'F':
8312 patch_script_path = optarg;
8313 break;
8314 default:
8315 usage_unstage();
8316 /* NOTREACHED */
8320 argc -= optind;
8321 argv += optind;
8323 #ifndef PROFILE
8324 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8325 "unveil", NULL) == -1)
8326 err(1, "pledge");
8327 #endif
8328 if (patch_script_path && !pflag)
8329 errx(1, "-F option can only be used together with -p option");
8331 cwd = getcwd(NULL, 0);
8332 if (cwd == NULL) {
8333 error = got_error_from_errno("getcwd");
8334 goto done;
8337 error = got_worktree_open(&worktree, cwd);
8338 if (error)
8339 goto done;
8341 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8342 NULL);
8343 if (error != NULL)
8344 goto done;
8346 if (patch_script_path) {
8347 patch_script_file = fopen(patch_script_path, "r");
8348 if (patch_script_file == NULL) {
8349 error = got_error_from_errno2("fopen",
8350 patch_script_path);
8351 goto done;
8355 error = apply_unveil(got_repo_get_path(repo), 0,
8356 got_worktree_get_root_path(worktree));
8357 if (error)
8358 goto done;
8360 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8361 if (error)
8362 goto done;
8364 cpa.patch_script_file = patch_script_file;
8365 cpa.action = "unstage";
8366 error = got_worktree_unstage(worktree, &paths, update_progress,
8367 &did_something, pflag ? choose_patch : NULL, &cpa, repo);
8368 done:
8369 if (patch_script_file && fclose(patch_script_file) == EOF &&
8370 error == NULL)
8371 error = got_error_from_errno2("fclose", patch_script_path);
8372 if (repo)
8373 got_repo_close(repo);
8374 if (worktree)
8375 got_worktree_close(worktree);
8376 TAILQ_FOREACH(pe, &paths, entry)
8377 free((char *)pe->path);
8378 got_pathlist_free(&paths);
8379 free(cwd);
8380 return error;
8383 __dead static void
8384 usage_cat(void)
8386 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
8387 "arg1 [arg2 ...]\n", getprogname());
8388 exit(1);
8391 static const struct got_error *
8392 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8394 const struct got_error *err;
8395 struct got_blob_object *blob;
8397 err = got_object_open_as_blob(&blob, repo, id, 8192);
8398 if (err)
8399 return err;
8401 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
8402 got_object_blob_close(blob);
8403 return err;
8406 static const struct got_error *
8407 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8409 const struct got_error *err;
8410 struct got_tree_object *tree;
8411 int nentries, i;
8413 err = got_object_open_as_tree(&tree, repo, id);
8414 if (err)
8415 return err;
8417 nentries = got_object_tree_get_nentries(tree);
8418 for (i = 0; i < nentries; i++) {
8419 struct got_tree_entry *te;
8420 char *id_str;
8421 if (sigint_received || sigpipe_received)
8422 break;
8423 te = got_object_tree_get_entry(tree, i);
8424 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
8425 if (err)
8426 break;
8427 fprintf(outfile, "%s %.7o %s\n", id_str,
8428 got_tree_entry_get_mode(te),
8429 got_tree_entry_get_name(te));
8430 free(id_str);
8433 got_object_tree_close(tree);
8434 return err;
8437 static const struct got_error *
8438 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8440 const struct got_error *err;
8441 struct got_commit_object *commit;
8442 const struct got_object_id_queue *parent_ids;
8443 struct got_object_qid *pid;
8444 char *id_str = NULL;
8445 const char *logmsg = NULL;
8447 err = got_object_open_as_commit(&commit, repo, id);
8448 if (err)
8449 return err;
8451 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
8452 if (err)
8453 goto done;
8455 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
8456 parent_ids = got_object_commit_get_parent_ids(commit);
8457 fprintf(outfile, "numparents %d\n",
8458 got_object_commit_get_nparents(commit));
8459 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
8460 char *pid_str;
8461 err = got_object_id_str(&pid_str, pid->id);
8462 if (err)
8463 goto done;
8464 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
8465 free(pid_str);
8467 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
8468 got_object_commit_get_author(commit),
8469 got_object_commit_get_author_time(commit));
8471 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
8472 got_object_commit_get_author(commit),
8473 got_object_commit_get_committer_time(commit));
8475 logmsg = got_object_commit_get_logmsg_raw(commit);
8476 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
8477 fprintf(outfile, "%s", logmsg);
8478 done:
8479 free(id_str);
8480 got_object_commit_close(commit);
8481 return err;
8484 static const struct got_error *
8485 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8487 const struct got_error *err;
8488 struct got_tag_object *tag;
8489 char *id_str = NULL;
8490 const char *tagmsg = NULL;
8492 err = got_object_open_as_tag(&tag, repo, id);
8493 if (err)
8494 return err;
8496 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
8497 if (err)
8498 goto done;
8500 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
8502 switch (got_object_tag_get_object_type(tag)) {
8503 case GOT_OBJ_TYPE_BLOB:
8504 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8505 GOT_OBJ_LABEL_BLOB);
8506 break;
8507 case GOT_OBJ_TYPE_TREE:
8508 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8509 GOT_OBJ_LABEL_TREE);
8510 break;
8511 case GOT_OBJ_TYPE_COMMIT:
8512 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8513 GOT_OBJ_LABEL_COMMIT);
8514 break;
8515 case GOT_OBJ_TYPE_TAG:
8516 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8517 GOT_OBJ_LABEL_TAG);
8518 break;
8519 default:
8520 break;
8523 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
8524 got_object_tag_get_name(tag));
8526 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
8527 got_object_tag_get_tagger(tag),
8528 got_object_tag_get_tagger_time(tag));
8530 tagmsg = got_object_tag_get_message(tag);
8531 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
8532 fprintf(outfile, "%s", tagmsg);
8533 done:
8534 free(id_str);
8535 got_object_tag_close(tag);
8536 return err;
8539 static const struct got_error *
8540 cmd_cat(int argc, char *argv[])
8542 const struct got_error *error;
8543 struct got_repository *repo = NULL;
8544 struct got_worktree *worktree = NULL;
8545 char *cwd = NULL, *repo_path = NULL, *label = NULL;
8546 const char *commit_id_str = NULL;
8547 struct got_object_id *id = NULL, *commit_id = NULL;
8548 int ch, obj_type, i, force_path = 0;
8550 #ifndef PROFILE
8551 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8552 NULL) == -1)
8553 err(1, "pledge");
8554 #endif
8556 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
8557 switch (ch) {
8558 case 'c':
8559 commit_id_str = optarg;
8560 break;
8561 case 'r':
8562 repo_path = realpath(optarg, NULL);
8563 if (repo_path == NULL)
8564 return got_error_from_errno2("realpath",
8565 optarg);
8566 got_path_strip_trailing_slashes(repo_path);
8567 break;
8568 case 'P':
8569 force_path = 1;
8570 break;
8571 default:
8572 usage_cat();
8573 /* NOTREACHED */
8577 argc -= optind;
8578 argv += optind;
8580 cwd = getcwd(NULL, 0);
8581 if (cwd == NULL) {
8582 error = got_error_from_errno("getcwd");
8583 goto done;
8585 error = got_worktree_open(&worktree, cwd);
8586 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8587 goto done;
8588 if (worktree) {
8589 if (repo_path == NULL) {
8590 repo_path = strdup(
8591 got_worktree_get_repo_path(worktree));
8592 if (repo_path == NULL) {
8593 error = got_error_from_errno("strdup");
8594 goto done;
8599 if (repo_path == NULL) {
8600 repo_path = getcwd(NULL, 0);
8601 if (repo_path == NULL)
8602 return got_error_from_errno("getcwd");
8605 error = got_repo_open(&repo, repo_path, NULL);
8606 free(repo_path);
8607 if (error != NULL)
8608 goto done;
8610 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
8611 if (error)
8612 goto done;
8614 if (commit_id_str == NULL)
8615 commit_id_str = GOT_REF_HEAD;
8616 error = got_repo_match_object_id(&commit_id, NULL,
8617 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
8618 if (error)
8619 goto done;
8621 for (i = 0; i < argc; i++) {
8622 if (force_path) {
8623 error = got_object_id_by_path(&id, repo, commit_id,
8624 argv[i]);
8625 if (error)
8626 break;
8627 } else {
8628 error = got_repo_match_object_id(&id, &label, argv[i],
8629 GOT_OBJ_TYPE_ANY, 0, repo);
8630 if (error) {
8631 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
8632 error->code != GOT_ERR_NOT_REF)
8633 break;
8634 error = got_object_id_by_path(&id, repo,
8635 commit_id, argv[i]);
8636 if (error)
8637 break;
8641 error = got_object_get_type(&obj_type, repo, id);
8642 if (error)
8643 break;
8645 switch (obj_type) {
8646 case GOT_OBJ_TYPE_BLOB:
8647 error = cat_blob(id, repo, stdout);
8648 break;
8649 case GOT_OBJ_TYPE_TREE:
8650 error = cat_tree(id, repo, stdout);
8651 break;
8652 case GOT_OBJ_TYPE_COMMIT:
8653 error = cat_commit(id, repo, stdout);
8654 break;
8655 case GOT_OBJ_TYPE_TAG:
8656 error = cat_tag(id, repo, stdout);
8657 break;
8658 default:
8659 error = got_error(GOT_ERR_OBJ_TYPE);
8660 break;
8662 if (error)
8663 break;
8664 free(label);
8665 label = NULL;
8666 free(id);
8667 id = NULL;
8669 done:
8670 free(label);
8671 free(id);
8672 free(commit_id);
8673 if (worktree)
8674 got_worktree_close(worktree);
8675 if (repo) {
8676 const struct got_error *repo_error;
8677 repo_error = got_repo_close(repo);
8678 if (error == NULL)
8679 error = repo_error;
8681 return error;