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 if (verbosity >= 0) {
1426 printf("Replacing reference %s: %s\n",
1427 got_ref_get_name(ref),
1428 got_ref_get_symref_target(ref));
1430 err = got_ref_change_symref_to_ref(ref, new_id);
1431 if (err)
1432 goto done;
1433 err = got_ref_write(ref, repo);
1434 if (err)
1435 goto done;
1436 } else {
1437 err = got_ref_resolve(&old_id, repo, ref);
1438 if (err)
1439 goto done;
1440 if (got_object_id_cmp(old_id, new_id) == 0)
1441 goto done;
1443 err = got_ref_change_ref(ref, new_id);
1444 if (err)
1445 goto done;
1446 err = got_ref_write(ref, repo);
1447 if (err)
1448 goto done;
1451 if (verbosity >= 0)
1452 printf("Updated reference %s: %s\n", got_ref_get_name(ref),
1453 new_id_str);
1454 done:
1455 free(old_id);
1456 free(new_id_str);
1457 return err;
1460 __dead static void
1461 usage_fetch(void)
1463 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1464 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1465 "[remote-repository-name]\n",
1466 getprogname());
1467 exit(1);
1470 static const struct got_error *
1471 delete_missing_refs(struct got_pathlist_head *their_refs,
1472 int verbosity, struct got_repository *repo)
1474 const struct got_error *err = NULL;
1475 struct got_reflist_head my_refs;
1476 struct got_reflist_entry *re;
1477 struct got_pathlist_entry *pe;
1478 struct got_object_id *id;
1479 char *id_str;
1481 SIMPLEQ_INIT(&my_refs);
1483 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1484 if (err)
1485 return err;
1487 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1488 const char *refname = got_ref_get_name(re->ref);
1490 if (strncmp(refname, "refs/heads/", 11) != 0 &&
1491 strncmp(refname, "refs/tags/", 10) != 0)
1492 continue;
1494 TAILQ_FOREACH(pe, their_refs, entry) {
1495 if (strcmp(refname, pe->path) == 0)
1496 break;
1498 if (pe != NULL)
1499 continue;
1501 err = got_ref_resolve(&id, repo, re->ref);
1502 if (err)
1503 break;
1504 err = got_object_id_str(&id_str, id);
1505 free(id);
1506 if (err)
1507 break;
1509 free(id_str);
1510 err = got_ref_delete(re->ref, repo);
1511 if (err)
1512 break;
1513 if (verbosity >= 0) {
1514 printf("Deleted reference %s: %s\n",
1515 got_ref_get_name(re->ref), id_str);
1519 return err;
1522 static const struct got_error *
1523 update_wanted_ref(const char *refname, struct got_object_id *id,
1524 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1526 const struct got_error *err, *unlock_err;
1527 char *remote_refname;
1528 struct got_reference *ref;
1530 if (strncmp("refs/", refname, 5) == 0)
1531 refname += 5;
1533 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1534 remote_repo_name, refname) == -1)
1535 return got_error_from_errno("asprintf");
1537 err = got_ref_open(&ref, repo, remote_refname, 1);
1538 if (err) {
1539 if (err->code != GOT_ERR_NOT_REF)
1540 goto done;
1541 err = create_ref(remote_refname, id, verbosity, repo);
1542 } else {
1543 err = update_ref(ref, id, 0, verbosity, repo);
1544 unlock_err = got_ref_unlock(ref);
1545 if (unlock_err && err == NULL)
1546 err = unlock_err;
1547 got_ref_close(ref);
1549 done:
1550 free(remote_refname);
1551 return err;
1554 static const struct got_error *
1555 cmd_fetch(int argc, char *argv[])
1557 const struct got_error *error = NULL, *unlock_err;
1558 char *cwd = NULL, *repo_path = NULL;
1559 const char *remote_name;
1560 char *proto = NULL, *host = NULL, *port = NULL;
1561 char *repo_name = NULL, *server_path = NULL;
1562 struct got_remote_repo *remotes, *remote = NULL;
1563 int nremotes;
1564 char *id_str = NULL;
1565 struct got_repository *repo = NULL;
1566 struct got_worktree *worktree = NULL;
1567 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1568 struct got_pathlist_entry *pe;
1569 struct got_object_id *pack_hash = NULL;
1570 int i, ch, fetchfd = -1, fetchstatus;
1571 pid_t fetchpid = -1;
1572 struct got_fetch_progress_arg fpa;
1573 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
1574 int delete_refs = 0, replace_tags = 0;
1576 TAILQ_INIT(&refs);
1577 TAILQ_INIT(&symrefs);
1578 TAILQ_INIT(&wanted_branches);
1579 TAILQ_INIT(&wanted_refs);
1581 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
1582 switch (ch) {
1583 case 'a':
1584 fetch_all_branches = 1;
1585 break;
1586 case 'b':
1587 error = got_pathlist_append(&wanted_branches,
1588 optarg, NULL);
1589 if (error)
1590 return error;
1591 break;
1592 case 'd':
1593 delete_refs = 1;
1594 break;
1595 case 'l':
1596 list_refs_only = 1;
1597 break;
1598 case 'r':
1599 repo_path = realpath(optarg, NULL);
1600 if (repo_path == NULL)
1601 return got_error_from_errno2("realpath",
1602 optarg);
1603 got_path_strip_trailing_slashes(repo_path);
1604 break;
1605 case 't':
1606 replace_tags = 1;
1607 break;
1608 case 'v':
1609 if (verbosity < 0)
1610 verbosity = 0;
1611 else if (verbosity < 3)
1612 verbosity++;
1613 break;
1614 case 'q':
1615 verbosity = -1;
1616 break;
1617 case 'R':
1618 error = got_pathlist_append(&wanted_refs,
1619 optarg, NULL);
1620 if (error)
1621 return error;
1622 break;
1623 default:
1624 usage_fetch();
1625 break;
1628 argc -= optind;
1629 argv += optind;
1631 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1632 errx(1, "-a and -b options are mutually exclusive");
1633 if (list_refs_only) {
1634 if (!TAILQ_EMPTY(&wanted_branches))
1635 errx(1, "-l and -b options are mutually exclusive");
1636 if (fetch_all_branches)
1637 errx(1, "-l and -a options are mutually exclusive");
1638 if (delete_refs)
1639 errx(1, "-l and -d options are mutually exclusive");
1640 if (verbosity == -1)
1641 errx(1, "-l and -q options are mutually exclusive");
1644 if (argc == 0)
1645 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
1646 else if (argc == 1)
1647 remote_name = argv[0];
1648 else
1649 usage_fetch();
1651 cwd = getcwd(NULL, 0);
1652 if (cwd == NULL) {
1653 error = got_error_from_errno("getcwd");
1654 goto done;
1657 if (repo_path == NULL) {
1658 error = got_worktree_open(&worktree, cwd);
1659 if (error && error->code != GOT_ERR_NOT_WORKTREE)
1660 goto done;
1661 else
1662 error = NULL;
1663 if (worktree) {
1664 repo_path =
1665 strdup(got_worktree_get_repo_path(worktree));
1666 if (repo_path == NULL)
1667 error = got_error_from_errno("strdup");
1668 if (error)
1669 goto done;
1670 } else {
1671 repo_path = strdup(cwd);
1672 if (repo_path == NULL) {
1673 error = got_error_from_errno("strdup");
1674 goto done;
1679 error = got_repo_open(&repo, repo_path, NULL);
1680 if (error)
1681 goto done;
1683 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
1684 for (i = 0; i < nremotes; i++) {
1685 remote = &remotes[i];
1686 if (strcmp(remote->name, remote_name) == 0)
1687 break;
1689 if (i == nremotes) {
1690 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
1691 goto done;
1694 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1695 &repo_name, remote->url);
1696 if (error)
1697 goto done;
1699 if (strcmp(proto, "git") == 0) {
1700 #ifndef PROFILE
1701 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1702 "sendfd dns inet unveil", NULL) == -1)
1703 err(1, "pledge");
1704 #endif
1705 } else if (strcmp(proto, "git+ssh") == 0 ||
1706 strcmp(proto, "ssh") == 0) {
1707 #ifndef PROFILE
1708 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1709 "sendfd unveil", NULL) == -1)
1710 err(1, "pledge");
1711 #endif
1712 } else if (strcmp(proto, "http") == 0 ||
1713 strcmp(proto, "git+http") == 0) {
1714 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1715 goto done;
1716 } else {
1717 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1718 goto done;
1721 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1722 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1723 error = got_error_from_errno2("unveil",
1724 GOT_FETCH_PATH_SSH);
1725 goto done;
1728 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
1729 if (error)
1730 goto done;
1732 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1733 server_path, verbosity);
1734 if (error)
1735 goto done;
1737 if (verbosity >= 0)
1738 printf("Connected to \"%s\" %s%s%s\n", remote->name, host,
1739 port ? ":" : "", port ? port : "");
1741 fpa.last_scaled_size[0] = '\0';
1742 fpa.last_p_indexed = -1;
1743 fpa.last_p_resolved = -1;
1744 fpa.verbosity = verbosity;
1745 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
1746 remote->mirror_references, fetch_all_branches, &wanted_branches,
1747 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
1748 fetch_progress, &fpa);
1749 if (error)
1750 goto done;
1752 if (list_refs_only) {
1753 error = list_remote_refs(&symrefs, &refs);
1754 goto done;
1757 if (pack_hash == NULL) {
1758 if (verbosity >= 0)
1759 printf("Already up-to-date\n");
1760 if (delete_refs)
1761 error = delete_missing_refs(&refs, verbosity, repo);
1762 goto done;
1765 if (verbosity >= 0) {
1766 error = got_object_id_str(&id_str, pack_hash);
1767 if (error)
1768 goto done;
1769 printf("\nFetched %s.pack\n", id_str);
1770 free(id_str);
1771 id_str = NULL;
1774 /* Update references provided with the pack file. */
1775 TAILQ_FOREACH(pe, &refs, entry) {
1776 const char *refname = pe->path;
1777 struct got_object_id *id = pe->data;
1778 struct got_reference *ref;
1779 char *remote_refname;
1781 if (is_wanted_ref(&wanted_refs, refname) &&
1782 !remote->mirror_references) {
1783 error = update_wanted_ref(refname, id,
1784 remote->name, verbosity, repo);
1785 if (error)
1786 goto done;
1787 continue;
1790 if (remote->mirror_references ||
1791 strncmp("refs/tags/", refname, 10) == 0) {
1792 error = got_ref_open(&ref, repo, refname, 1);
1793 if (error) {
1794 if (error->code != GOT_ERR_NOT_REF)
1795 goto done;
1796 error = create_ref(refname, id, verbosity,
1797 repo);
1798 if (error)
1799 goto done;
1800 } else {
1801 error = update_ref(ref, id, replace_tags,
1802 verbosity, repo);
1803 unlock_err = got_ref_unlock(ref);
1804 if (unlock_err && error == NULL)
1805 error = unlock_err;
1806 got_ref_close(ref);
1807 if (error)
1808 goto done;
1810 } else if (strncmp("refs/heads/", refname, 11) == 0) {
1811 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1812 remote_name, refname + 11) == -1) {
1813 error = got_error_from_errno("asprintf");
1814 goto done;
1817 error = got_ref_open(&ref, repo, remote_refname, 1);
1818 if (error) {
1819 if (error->code != GOT_ERR_NOT_REF)
1820 goto done;
1821 error = create_ref(remote_refname, id,
1822 verbosity, repo);
1823 if (error)
1824 goto done;
1825 } else {
1826 error = update_ref(ref, id, replace_tags,
1827 verbosity, repo);
1828 unlock_err = got_ref_unlock(ref);
1829 if (unlock_err && error == NULL)
1830 error = unlock_err;
1831 got_ref_close(ref);
1832 if (error)
1833 goto done;
1836 /* Also create a local branch if none exists yet. */
1837 error = got_ref_open(&ref, repo, refname, 1);
1838 if (error) {
1839 if (error->code != GOT_ERR_NOT_REF)
1840 goto done;
1841 error = create_ref(refname, id, verbosity,
1842 repo);
1843 if (error)
1844 goto done;
1845 } else {
1846 unlock_err = got_ref_unlock(ref);
1847 if (unlock_err && error == NULL)
1848 error = unlock_err;
1849 got_ref_close(ref);
1853 if (delete_refs)
1854 error = delete_missing_refs(&refs, verbosity, repo);
1855 done:
1856 if (fetchpid > 0) {
1857 if (kill(fetchpid, SIGTERM) == -1)
1858 error = got_error_from_errno("kill");
1859 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1860 error = got_error_from_errno("waitpid");
1862 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1863 error = got_error_from_errno("close");
1864 if (repo)
1865 got_repo_close(repo);
1866 if (worktree)
1867 got_worktree_close(worktree);
1868 TAILQ_FOREACH(pe, &refs, entry) {
1869 free((void *)pe->path);
1870 free(pe->data);
1872 got_pathlist_free(&refs);
1873 TAILQ_FOREACH(pe, &symrefs, entry) {
1874 free((void *)pe->path);
1875 free(pe->data);
1877 got_pathlist_free(&symrefs);
1878 got_pathlist_free(&wanted_branches);
1879 got_pathlist_free(&wanted_refs);
1880 free(id_str);
1881 free(cwd);
1882 free(repo_path);
1883 free(pack_hash);
1884 free(proto);
1885 free(host);
1886 free(port);
1887 free(server_path);
1888 free(repo_name);
1889 return error;
1893 __dead static void
1894 usage_checkout(void)
1896 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
1897 "[-p prefix] repository-path [worktree-path]\n", getprogname());
1898 exit(1);
1901 static void
1902 show_worktree_base_ref_warning(void)
1904 fprintf(stderr, "%s: warning: could not create a reference "
1905 "to the work tree's base commit; the commit could be "
1906 "garbage-collected by Git; making the repository "
1907 "writable and running 'got update' will prevent this\n",
1908 getprogname());
1911 struct got_checkout_progress_arg {
1912 const char *worktree_path;
1913 int had_base_commit_ref_error;
1916 static const struct got_error *
1917 checkout_progress(void *arg, unsigned char status, const char *path)
1919 struct got_checkout_progress_arg *a = arg;
1921 /* Base commit bump happens silently. */
1922 if (status == GOT_STATUS_BUMP_BASE)
1923 return NULL;
1925 if (status == GOT_STATUS_BASE_REF_ERR) {
1926 a->had_base_commit_ref_error = 1;
1927 return NULL;
1930 while (path[0] == '/')
1931 path++;
1933 printf("%c %s/%s\n", status, a->worktree_path, path);
1934 return NULL;
1937 static const struct got_error *
1938 check_cancelled(void *arg)
1940 if (sigint_received || sigpipe_received)
1941 return got_error(GOT_ERR_CANCELLED);
1942 return NULL;
1945 static const struct got_error *
1946 check_linear_ancestry(struct got_object_id *commit_id,
1947 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
1948 struct got_repository *repo)
1950 const struct got_error *err = NULL;
1951 struct got_object_id *yca_id;
1953 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
1954 commit_id, base_commit_id, repo, check_cancelled, NULL);
1955 if (err)
1956 return err;
1958 if (yca_id == NULL)
1959 return got_error(GOT_ERR_ANCESTRY);
1962 * Require a straight line of history between the target commit
1963 * and the work tree's base commit.
1965 * Non-linear situations such as this require a rebase:
1967 * (commit) D F (base_commit)
1968 * \ /
1969 * C E
1970 * \ /
1971 * B (yca)
1972 * |
1973 * A
1975 * 'got update' only handles linear cases:
1976 * Update forwards in time: A (base/yca) - B - C - D (commit)
1977 * Update backwards in time: D (base) - C - B - A (commit/yca)
1979 if (allow_forwards_in_time_only) {
1980 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
1981 return got_error(GOT_ERR_ANCESTRY);
1982 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
1983 got_object_id_cmp(base_commit_id, yca_id) != 0)
1984 return got_error(GOT_ERR_ANCESTRY);
1986 free(yca_id);
1987 return NULL;
1990 static const struct got_error *
1991 check_same_branch(struct got_object_id *commit_id,
1992 struct got_reference *head_ref, struct got_object_id *yca_id,
1993 struct got_repository *repo)
1995 const struct got_error *err = NULL;
1996 struct got_commit_graph *graph = NULL;
1997 struct got_object_id *head_commit_id = NULL;
1998 int is_same_branch = 0;
2000 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2001 if (err)
2002 goto done;
2004 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2005 is_same_branch = 1;
2006 goto done;
2008 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2009 is_same_branch = 1;
2010 goto done;
2013 err = got_commit_graph_open(&graph, "/", 1);
2014 if (err)
2015 goto done;
2017 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2018 check_cancelled, NULL);
2019 if (err)
2020 goto done;
2022 for (;;) {
2023 struct got_object_id *id;
2024 err = got_commit_graph_iter_next(&id, graph, repo,
2025 check_cancelled, NULL);
2026 if (err) {
2027 if (err->code == GOT_ERR_ITER_COMPLETED)
2028 err = NULL;
2029 break;
2032 if (id) {
2033 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2034 break;
2035 if (got_object_id_cmp(id, commit_id) == 0) {
2036 is_same_branch = 1;
2037 break;
2041 done:
2042 if (graph)
2043 got_commit_graph_close(graph);
2044 free(head_commit_id);
2045 if (!err && !is_same_branch)
2046 err = got_error(GOT_ERR_ANCESTRY);
2047 return err;
2050 static const struct got_error *
2051 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2053 static char msg[512];
2054 const char *branch_name;
2056 if (got_ref_is_symbolic(ref))
2057 branch_name = got_ref_get_symref_target(ref);
2058 else
2059 branch_name = got_ref_get_name(ref);
2061 if (strncmp("refs/heads/", branch_name, 11) == 0)
2062 branch_name += 11;
2064 snprintf(msg, sizeof(msg),
2065 "target commit is not contained in branch '%s'; "
2066 "the branch to use must be specified with -b; "
2067 "if necessary a new branch can be created for "
2068 "this commit with 'got branch -c %s BRANCH_NAME'",
2069 branch_name, commit_id_str);
2071 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2074 static const struct got_error *
2075 cmd_checkout(int argc, char *argv[])
2077 const struct got_error *error = NULL;
2078 struct got_repository *repo = NULL;
2079 struct got_reference *head_ref = NULL;
2080 struct got_worktree *worktree = NULL;
2081 char *repo_path = NULL;
2082 char *worktree_path = NULL;
2083 const char *path_prefix = "";
2084 const char *branch_name = GOT_REF_HEAD;
2085 char *commit_id_str = NULL;
2086 int ch, same_path_prefix, allow_nonempty = 0;
2087 struct got_pathlist_head paths;
2088 struct got_checkout_progress_arg cpa;
2090 TAILQ_INIT(&paths);
2092 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2093 switch (ch) {
2094 case 'b':
2095 branch_name = optarg;
2096 break;
2097 case 'c':
2098 commit_id_str = strdup(optarg);
2099 if (commit_id_str == NULL)
2100 return got_error_from_errno("strdup");
2101 break;
2102 case 'E':
2103 allow_nonempty = 1;
2104 break;
2105 case 'p':
2106 path_prefix = optarg;
2107 break;
2108 default:
2109 usage_checkout();
2110 /* NOTREACHED */
2114 argc -= optind;
2115 argv += optind;
2117 #ifndef PROFILE
2118 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2119 "unveil", NULL) == -1)
2120 err(1, "pledge");
2121 #endif
2122 if (argc == 1) {
2123 char *cwd, *base, *dotgit;
2124 repo_path = realpath(argv[0], NULL);
2125 if (repo_path == NULL)
2126 return got_error_from_errno2("realpath", argv[0]);
2127 cwd = getcwd(NULL, 0);
2128 if (cwd == NULL) {
2129 error = got_error_from_errno("getcwd");
2130 goto done;
2132 if (path_prefix[0]) {
2133 base = basename(path_prefix);
2134 if (base == NULL) {
2135 error = got_error_from_errno2("basename",
2136 path_prefix);
2137 goto done;
2139 } else {
2140 base = basename(repo_path);
2141 if (base == NULL) {
2142 error = got_error_from_errno2("basename",
2143 repo_path);
2144 goto done;
2147 dotgit = strstr(base, ".git");
2148 if (dotgit)
2149 *dotgit = '\0';
2150 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2151 error = got_error_from_errno("asprintf");
2152 free(cwd);
2153 goto done;
2155 free(cwd);
2156 } else if (argc == 2) {
2157 repo_path = realpath(argv[0], NULL);
2158 if (repo_path == NULL) {
2159 error = got_error_from_errno2("realpath", argv[0]);
2160 goto done;
2162 worktree_path = realpath(argv[1], NULL);
2163 if (worktree_path == NULL) {
2164 if (errno != ENOENT) {
2165 error = got_error_from_errno2("realpath",
2166 argv[1]);
2167 goto done;
2169 worktree_path = strdup(argv[1]);
2170 if (worktree_path == NULL) {
2171 error = got_error_from_errno("strdup");
2172 goto done;
2175 } else
2176 usage_checkout();
2178 got_path_strip_trailing_slashes(repo_path);
2179 got_path_strip_trailing_slashes(worktree_path);
2181 error = got_repo_open(&repo, repo_path, NULL);
2182 if (error != NULL)
2183 goto done;
2185 /* Pre-create work tree path for unveil(2) */
2186 error = got_path_mkdir(worktree_path);
2187 if (error) {
2188 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2189 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2190 goto done;
2191 if (!allow_nonempty &&
2192 !got_path_dir_is_empty(worktree_path)) {
2193 error = got_error_path(worktree_path,
2194 GOT_ERR_DIR_NOT_EMPTY);
2195 goto done;
2199 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2200 if (error)
2201 goto done;
2203 error = got_ref_open(&head_ref, repo, branch_name, 0);
2204 if (error != NULL)
2205 goto done;
2207 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2208 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2209 goto done;
2211 error = got_worktree_open(&worktree, worktree_path);
2212 if (error != NULL)
2213 goto done;
2215 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2216 path_prefix);
2217 if (error != NULL)
2218 goto done;
2219 if (!same_path_prefix) {
2220 error = got_error(GOT_ERR_PATH_PREFIX);
2221 goto done;
2224 if (commit_id_str) {
2225 struct got_object_id *commit_id;
2226 error = got_repo_match_object_id(&commit_id, NULL,
2227 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2228 if (error)
2229 goto done;
2230 error = check_linear_ancestry(commit_id,
2231 got_worktree_get_base_commit_id(worktree), 0, repo);
2232 if (error != NULL) {
2233 free(commit_id);
2234 if (error->code == GOT_ERR_ANCESTRY) {
2235 error = checkout_ancestry_error(
2236 head_ref, commit_id_str);
2238 goto done;
2240 error = check_same_branch(commit_id, head_ref, NULL, repo);
2241 if (error) {
2242 if (error->code == GOT_ERR_ANCESTRY) {
2243 error = checkout_ancestry_error(
2244 head_ref, commit_id_str);
2246 goto done;
2248 error = got_worktree_set_base_commit_id(worktree, repo,
2249 commit_id);
2250 free(commit_id);
2251 if (error)
2252 goto done;
2255 error = got_pathlist_append(&paths, "", NULL);
2256 if (error)
2257 goto done;
2258 cpa.worktree_path = worktree_path;
2259 cpa.had_base_commit_ref_error = 0;
2260 error = got_worktree_checkout_files(worktree, &paths, repo,
2261 checkout_progress, &cpa, check_cancelled, NULL);
2262 if (error != NULL)
2263 goto done;
2265 printf("Now shut up and hack\n");
2266 if (cpa.had_base_commit_ref_error)
2267 show_worktree_base_ref_warning();
2268 done:
2269 got_pathlist_free(&paths);
2270 free(commit_id_str);
2271 free(repo_path);
2272 free(worktree_path);
2273 return error;
2276 __dead static void
2277 usage_update(void)
2279 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2280 getprogname());
2281 exit(1);
2284 static const struct got_error *
2285 update_progress(void *arg, unsigned char status, const char *path)
2287 int *did_something = arg;
2289 if (status == GOT_STATUS_EXISTS ||
2290 status == GOT_STATUS_BASE_REF_ERR)
2291 return NULL;
2293 *did_something = 1;
2295 /* Base commit bump happens silently. */
2296 if (status == GOT_STATUS_BUMP_BASE)
2297 return NULL;
2299 while (path[0] == '/')
2300 path++;
2301 printf("%c %s\n", status, path);
2302 return NULL;
2305 static const struct got_error *
2306 switch_head_ref(struct got_reference *head_ref,
2307 struct got_object_id *commit_id, struct got_worktree *worktree,
2308 struct got_repository *repo)
2310 const struct got_error *err = NULL;
2311 char *base_id_str;
2312 int ref_has_moved = 0;
2314 /* Trivial case: switching between two different references. */
2315 if (strcmp(got_ref_get_name(head_ref),
2316 got_worktree_get_head_ref_name(worktree)) != 0) {
2317 printf("Switching work tree from %s to %s\n",
2318 got_worktree_get_head_ref_name(worktree),
2319 got_ref_get_name(head_ref));
2320 return got_worktree_set_head_ref(worktree, head_ref);
2323 err = check_linear_ancestry(commit_id,
2324 got_worktree_get_base_commit_id(worktree), 0, repo);
2325 if (err) {
2326 if (err->code != GOT_ERR_ANCESTRY)
2327 return err;
2328 ref_has_moved = 1;
2330 if (!ref_has_moved)
2331 return NULL;
2333 /* Switching to a rebased branch with the same reference name. */
2334 err = got_object_id_str(&base_id_str,
2335 got_worktree_get_base_commit_id(worktree));
2336 if (err)
2337 return err;
2338 printf("Reference %s now points at a different branch\n",
2339 got_worktree_get_head_ref_name(worktree));
2340 printf("Switching work tree from %s to %s\n", base_id_str,
2341 got_worktree_get_head_ref_name(worktree));
2342 return NULL;
2345 static const struct got_error *
2346 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2348 const struct got_error *err;
2349 int in_progress;
2351 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2352 if (err)
2353 return err;
2354 if (in_progress)
2355 return got_error(GOT_ERR_REBASING);
2357 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2358 if (err)
2359 return err;
2360 if (in_progress)
2361 return got_error(GOT_ERR_HISTEDIT_BUSY);
2363 return NULL;
2366 static const struct got_error *
2367 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2368 char *argv[], struct got_worktree *worktree)
2370 const struct got_error *err = NULL;
2371 char *path;
2372 int i;
2374 if (argc == 0) {
2375 path = strdup("");
2376 if (path == NULL)
2377 return got_error_from_errno("strdup");
2378 return got_pathlist_append(paths, path, NULL);
2381 for (i = 0; i < argc; i++) {
2382 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2383 if (err)
2384 break;
2385 err = got_pathlist_append(paths, path, NULL);
2386 if (err) {
2387 free(path);
2388 break;
2392 return err;
2395 static const struct got_error *
2396 cmd_update(int argc, char *argv[])
2398 const struct got_error *error = NULL;
2399 struct got_repository *repo = NULL;
2400 struct got_worktree *worktree = NULL;
2401 char *worktree_path = NULL;
2402 struct got_object_id *commit_id = NULL;
2403 char *commit_id_str = NULL;
2404 const char *branch_name = NULL;
2405 struct got_reference *head_ref = NULL;
2406 struct got_pathlist_head paths;
2407 struct got_pathlist_entry *pe;
2408 int ch, did_something = 0;
2410 TAILQ_INIT(&paths);
2412 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2413 switch (ch) {
2414 case 'b':
2415 branch_name = optarg;
2416 break;
2417 case 'c':
2418 commit_id_str = strdup(optarg);
2419 if (commit_id_str == NULL)
2420 return got_error_from_errno("strdup");
2421 break;
2422 default:
2423 usage_update();
2424 /* NOTREACHED */
2428 argc -= optind;
2429 argv += optind;
2431 #ifndef PROFILE
2432 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2433 "unveil", NULL) == -1)
2434 err(1, "pledge");
2435 #endif
2436 worktree_path = getcwd(NULL, 0);
2437 if (worktree_path == NULL) {
2438 error = got_error_from_errno("getcwd");
2439 goto done;
2441 error = got_worktree_open(&worktree, worktree_path);
2442 if (error)
2443 goto done;
2445 error = check_rebase_or_histedit_in_progress(worktree);
2446 if (error)
2447 goto done;
2449 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
2450 NULL);
2451 if (error != NULL)
2452 goto done;
2454 error = apply_unveil(got_repo_get_path(repo), 0,
2455 got_worktree_get_root_path(worktree));
2456 if (error)
2457 goto done;
2459 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2460 if (error)
2461 goto done;
2463 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
2464 got_worktree_get_head_ref_name(worktree), 0);
2465 if (error != NULL)
2466 goto done;
2467 if (commit_id_str == NULL) {
2468 error = got_ref_resolve(&commit_id, repo, head_ref);
2469 if (error != NULL)
2470 goto done;
2471 error = got_object_id_str(&commit_id_str, commit_id);
2472 if (error != NULL)
2473 goto done;
2474 } else {
2475 error = got_repo_match_object_id(&commit_id, NULL,
2476 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2477 free(commit_id_str);
2478 commit_id_str = NULL;
2479 if (error)
2480 goto done;
2481 error = got_object_id_str(&commit_id_str, commit_id);
2482 if (error)
2483 goto done;
2486 if (branch_name) {
2487 struct got_object_id *head_commit_id;
2488 TAILQ_FOREACH(pe, &paths, entry) {
2489 if (pe->path_len == 0)
2490 continue;
2491 error = got_error_msg(GOT_ERR_BAD_PATH,
2492 "switching between branches requires that "
2493 "the entire work tree gets updated");
2494 goto done;
2496 error = got_ref_resolve(&head_commit_id, repo, head_ref);
2497 if (error)
2498 goto done;
2499 error = check_linear_ancestry(commit_id, head_commit_id, 0,
2500 repo);
2501 free(head_commit_id);
2502 if (error != NULL)
2503 goto done;
2504 error = check_same_branch(commit_id, head_ref, NULL, repo);
2505 if (error)
2506 goto done;
2507 error = switch_head_ref(head_ref, commit_id, worktree, repo);
2508 if (error)
2509 goto done;
2510 } else {
2511 error = check_linear_ancestry(commit_id,
2512 got_worktree_get_base_commit_id(worktree), 0, repo);
2513 if (error != NULL) {
2514 if (error->code == GOT_ERR_ANCESTRY)
2515 error = got_error(GOT_ERR_BRANCH_MOVED);
2516 goto done;
2518 error = check_same_branch(commit_id, head_ref, NULL, repo);
2519 if (error)
2520 goto done;
2523 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
2524 commit_id) != 0) {
2525 error = got_worktree_set_base_commit_id(worktree, repo,
2526 commit_id);
2527 if (error)
2528 goto done;
2531 error = got_worktree_checkout_files(worktree, &paths, repo,
2532 update_progress, &did_something, check_cancelled, NULL);
2533 if (error != NULL)
2534 goto done;
2536 if (did_something)
2537 printf("Updated to commit %s\n", commit_id_str);
2538 else
2539 printf("Already up-to-date\n");
2540 done:
2541 free(worktree_path);
2542 TAILQ_FOREACH(pe, &paths, entry)
2543 free((char *)pe->path);
2544 got_pathlist_free(&paths);
2545 free(commit_id);
2546 free(commit_id_str);
2547 return error;
2550 static const struct got_error *
2551 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
2552 const char *path, int diff_context, int ignore_whitespace,
2553 struct got_repository *repo)
2555 const struct got_error *err = NULL;
2556 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
2558 if (blob_id1) {
2559 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
2560 if (err)
2561 goto done;
2564 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
2565 if (err)
2566 goto done;
2568 while (path[0] == '/')
2569 path++;
2570 err = got_diff_blob(blob1, blob2, path, path, diff_context,
2571 ignore_whitespace, stdout);
2572 done:
2573 if (blob1)
2574 got_object_blob_close(blob1);
2575 got_object_blob_close(blob2);
2576 return err;
2579 static const struct got_error *
2580 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
2581 const char *path, int diff_context, int ignore_whitespace,
2582 struct got_repository *repo)
2584 const struct got_error *err = NULL;
2585 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
2586 struct got_diff_blob_output_unidiff_arg arg;
2588 if (tree_id1) {
2589 err = got_object_open_as_tree(&tree1, repo, tree_id1);
2590 if (err)
2591 goto done;
2594 err = got_object_open_as_tree(&tree2, repo, tree_id2);
2595 if (err)
2596 goto done;
2598 arg.diff_context = diff_context;
2599 arg.ignore_whitespace = ignore_whitespace;
2600 arg.outfile = stdout;
2601 while (path[0] == '/')
2602 path++;
2603 err = got_diff_tree(tree1, tree2, path, path, repo,
2604 got_diff_blob_output_unidiff, &arg, 1);
2605 done:
2606 if (tree1)
2607 got_object_tree_close(tree1);
2608 if (tree2)
2609 got_object_tree_close(tree2);
2610 return err;
2613 static const struct got_error *
2614 print_patch(struct got_commit_object *commit, struct got_object_id *id,
2615 const char *path, int diff_context, struct got_repository *repo)
2617 const struct got_error *err = NULL;
2618 struct got_commit_object *pcommit = NULL;
2619 char *id_str1 = NULL, *id_str2 = NULL;
2620 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
2621 struct got_object_qid *qid;
2623 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
2624 if (qid != NULL) {
2625 err = got_object_open_as_commit(&pcommit, repo,
2626 qid->id);
2627 if (err)
2628 return err;
2631 if (path && path[0] != '\0') {
2632 int obj_type;
2633 err = got_object_id_by_path(&obj_id2, repo, id, path);
2634 if (err)
2635 goto done;
2636 err = got_object_id_str(&id_str2, obj_id2);
2637 if (err) {
2638 free(obj_id2);
2639 goto done;
2641 if (pcommit) {
2642 err = got_object_id_by_path(&obj_id1, repo,
2643 qid->id, path);
2644 if (err) {
2645 free(obj_id2);
2646 goto done;
2648 err = got_object_id_str(&id_str1, obj_id1);
2649 if (err) {
2650 free(obj_id2);
2651 goto done;
2654 err = got_object_get_type(&obj_type, repo, obj_id2);
2655 if (err) {
2656 free(obj_id2);
2657 goto done;
2659 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2660 switch (obj_type) {
2661 case GOT_OBJ_TYPE_BLOB:
2662 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
2663 0, repo);
2664 break;
2665 case GOT_OBJ_TYPE_TREE:
2666 err = diff_trees(obj_id1, obj_id2, path, diff_context,
2667 0, repo);
2668 break;
2669 default:
2670 err = got_error(GOT_ERR_OBJ_TYPE);
2671 break;
2673 free(obj_id1);
2674 free(obj_id2);
2675 } else {
2676 obj_id2 = got_object_commit_get_tree_id(commit);
2677 err = got_object_id_str(&id_str2, obj_id2);
2678 if (err)
2679 goto done;
2680 obj_id1 = got_object_commit_get_tree_id(pcommit);
2681 err = got_object_id_str(&id_str1, obj_id1);
2682 if (err)
2683 goto done;
2684 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2685 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
2687 done:
2688 free(id_str1);
2689 free(id_str2);
2690 if (pcommit)
2691 got_object_commit_close(pcommit);
2692 return err;
2695 static char *
2696 get_datestr(time_t *time, char *datebuf)
2698 struct tm mytm, *tm;
2699 char *p, *s;
2701 tm = gmtime_r(time, &mytm);
2702 if (tm == NULL)
2703 return NULL;
2704 s = asctime_r(tm, datebuf);
2705 if (s == NULL)
2706 return NULL;
2707 p = strchr(s, '\n');
2708 if (p)
2709 *p = '\0';
2710 return s;
2713 static const struct got_error *
2714 match_logmsg(int *have_match, struct got_object_id *id,
2715 struct got_commit_object *commit, regex_t *regex)
2717 const struct got_error *err = NULL;
2718 regmatch_t regmatch;
2719 char *id_str = NULL, *logmsg = NULL;
2721 *have_match = 0;
2723 err = got_object_id_str(&id_str, id);
2724 if (err)
2725 return err;
2727 err = got_object_commit_get_logmsg(&logmsg, commit);
2728 if (err)
2729 goto done;
2731 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2732 *have_match = 1;
2733 done:
2734 free(id_str);
2735 free(logmsg);
2736 return err;
2739 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
2741 static const struct got_error *
2742 print_commit(struct got_commit_object *commit, struct got_object_id *id,
2743 struct got_repository *repo, const char *path, int show_patch,
2744 int diff_context, struct got_reflist_head *refs)
2746 const struct got_error *err = NULL;
2747 char *id_str, *datestr, *logmsg0, *logmsg, *line;
2748 char datebuf[26];
2749 time_t committer_time;
2750 const char *author, *committer;
2751 char *refs_str = NULL;
2752 struct got_reflist_entry *re;
2754 SIMPLEQ_FOREACH(re, refs, entry) {
2755 char *s;
2756 const char *name;
2757 struct got_tag_object *tag = NULL;
2758 int cmp;
2760 name = got_ref_get_name(re->ref);
2761 if (strcmp(name, GOT_REF_HEAD) == 0)
2762 continue;
2763 if (strncmp(name, "refs/", 5) == 0)
2764 name += 5;
2765 if (strncmp(name, "got/", 4) == 0)
2766 continue;
2767 if (strncmp(name, "heads/", 6) == 0)
2768 name += 6;
2769 if (strncmp(name, "remotes/", 8) == 0)
2770 name += 8;
2771 if (strncmp(name, "tags/", 5) == 0) {
2772 err = got_object_open_as_tag(&tag, repo, re->id);
2773 if (err) {
2774 if (err->code != GOT_ERR_OBJ_TYPE)
2775 return err;
2776 /* Ref points at something other than a tag. */
2777 err = NULL;
2778 tag = NULL;
2781 cmp = got_object_id_cmp(tag ?
2782 got_object_tag_get_object_id(tag) : re->id, id);
2783 if (tag)
2784 got_object_tag_close(tag);
2785 if (cmp != 0)
2786 continue;
2787 s = refs_str;
2788 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
2789 name) == -1) {
2790 err = got_error_from_errno("asprintf");
2791 free(s);
2792 return err;
2794 free(s);
2796 err = got_object_id_str(&id_str, id);
2797 if (err)
2798 return err;
2800 printf(GOT_COMMIT_SEP_STR);
2801 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
2802 refs_str ? refs_str : "", refs_str ? ")" : "");
2803 free(id_str);
2804 id_str = NULL;
2805 free(refs_str);
2806 refs_str = NULL;
2807 printf("from: %s\n", got_object_commit_get_author(commit));
2808 committer_time = got_object_commit_get_committer_time(commit);
2809 datestr = get_datestr(&committer_time, datebuf);
2810 if (datestr)
2811 printf("date: %s UTC\n", datestr);
2812 author = got_object_commit_get_author(commit);
2813 committer = got_object_commit_get_committer(commit);
2814 if (strcmp(author, committer) != 0)
2815 printf("via: %s\n", committer);
2816 if (got_object_commit_get_nparents(commit) > 1) {
2817 const struct got_object_id_queue *parent_ids;
2818 struct got_object_qid *qid;
2819 int n = 1;
2820 parent_ids = got_object_commit_get_parent_ids(commit);
2821 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
2822 err = got_object_id_str(&id_str, qid->id);
2823 if (err)
2824 return err;
2825 printf("parent %d: %s\n", n++, id_str);
2826 free(id_str);
2830 err = got_object_commit_get_logmsg(&logmsg0, commit);
2831 if (err)
2832 return err;
2834 logmsg = logmsg0;
2835 do {
2836 line = strsep(&logmsg, "\n");
2837 if (line)
2838 printf(" %s\n", line);
2839 } while (line);
2840 free(logmsg0);
2842 if (show_patch) {
2843 err = print_patch(commit, id, path, diff_context, repo);
2844 if (err == 0)
2845 printf("\n");
2848 if (fflush(stdout) != 0 && err == NULL)
2849 err = got_error_from_errno("fflush");
2850 return err;
2853 static const struct got_error *
2854 print_commits(struct got_object_id *root_id, struct got_repository *repo,
2855 const char *path, int show_patch, const char *search_pattern,
2856 int diff_context, int limit, int log_branches,
2857 struct got_reflist_head *refs)
2859 const struct got_error *err;
2860 struct got_commit_graph *graph;
2861 regex_t regex;
2862 int have_match;
2864 if (search_pattern &&
2865 regcomp(&regex, search_pattern, REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
2866 return got_error_msg(GOT_ERR_REGEX, search_pattern);
2868 err = got_commit_graph_open(&graph, path, !log_branches);
2869 if (err)
2870 return err;
2871 err = got_commit_graph_iter_start(graph, root_id, repo,
2872 check_cancelled, NULL);
2873 if (err)
2874 goto done;
2875 for (;;) {
2876 struct got_commit_object *commit;
2877 struct got_object_id *id;
2879 if (sigint_received || sigpipe_received)
2880 break;
2882 err = got_commit_graph_iter_next(&id, graph, repo,
2883 check_cancelled, NULL);
2884 if (err) {
2885 if (err->code == GOT_ERR_ITER_COMPLETED)
2886 err = NULL;
2887 break;
2889 if (id == NULL)
2890 break;
2892 err = got_object_open_as_commit(&commit, repo, id);
2893 if (err)
2894 break;
2896 if (search_pattern) {
2897 err = match_logmsg(&have_match, id, commit, &regex);
2898 if (err) {
2899 got_object_commit_close(commit);
2900 break;
2902 if (have_match == 0) {
2903 got_object_commit_close(commit);
2904 continue;
2908 err = print_commit(commit, id, repo, path, show_patch,
2909 diff_context, refs);
2910 got_object_commit_close(commit);
2911 if (err || (limit && --limit == 0))
2912 break;
2914 done:
2915 if (search_pattern)
2916 regfree(&regex);
2917 got_commit_graph_close(graph);
2918 return err;
2921 __dead static void
2922 usage_log(void)
2924 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] [-p] "
2925 "[-s search-pattern] [-r repository-path] [path]\n", getprogname());
2926 exit(1);
2929 static int
2930 get_default_log_limit(void)
2932 const char *got_default_log_limit;
2933 long long n;
2934 const char *errstr;
2936 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
2937 if (got_default_log_limit == NULL)
2938 return 0;
2939 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
2940 if (errstr != NULL)
2941 return 0;
2942 return n;
2945 static const struct got_error *
2946 cmd_log(int argc, char *argv[])
2948 const struct got_error *error;
2949 struct got_repository *repo = NULL;
2950 struct got_worktree *worktree = NULL;
2951 struct got_commit_object *commit = NULL;
2952 struct got_object_id *id = NULL;
2953 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
2954 const char *start_commit = NULL, *search_pattern = NULL;
2955 int diff_context = -1, ch;
2956 int show_patch = 0, limit = 0, log_branches = 0;
2957 const char *errstr;
2958 struct got_reflist_head refs;
2960 SIMPLEQ_INIT(&refs);
2962 #ifndef PROFILE
2963 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
2964 NULL)
2965 == -1)
2966 err(1, "pledge");
2967 #endif
2969 limit = get_default_log_limit();
2971 while ((ch = getopt(argc, argv, "bpc:C:l:r:s:")) != -1) {
2972 switch (ch) {
2973 case 'p':
2974 show_patch = 1;
2975 break;
2976 case 'c':
2977 start_commit = optarg;
2978 break;
2979 case 'C':
2980 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
2981 &errstr);
2982 if (errstr != NULL)
2983 err(1, "-C option %s", errstr);
2984 break;
2985 case 'l':
2986 limit = strtonum(optarg, 0, INT_MAX, &errstr);
2987 if (errstr != NULL)
2988 err(1, "-l option %s", errstr);
2989 break;
2990 case 'b':
2991 log_branches = 1;
2992 break;
2993 case 'r':
2994 repo_path = realpath(optarg, NULL);
2995 if (repo_path == NULL)
2996 return got_error_from_errno2("realpath",
2997 optarg);
2998 got_path_strip_trailing_slashes(repo_path);
2999 break;
3000 case 's':
3001 search_pattern = optarg;
3002 break;
3003 default:
3004 usage_log();
3005 /* NOTREACHED */
3009 argc -= optind;
3010 argv += optind;
3012 if (diff_context == -1)
3013 diff_context = 3;
3014 else if (!show_patch)
3015 errx(1, "-C reguires -p");
3017 cwd = getcwd(NULL, 0);
3018 if (cwd == NULL) {
3019 error = got_error_from_errno("getcwd");
3020 goto done;
3023 error = got_worktree_open(&worktree, cwd);
3024 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3025 goto done;
3026 error = NULL;
3028 if (argc == 0) {
3029 path = strdup("");
3030 if (path == NULL) {
3031 error = got_error_from_errno("strdup");
3032 goto done;
3034 } else if (argc == 1) {
3035 if (worktree) {
3036 error = got_worktree_resolve_path(&path, worktree,
3037 argv[0]);
3038 if (error)
3039 goto done;
3040 } else {
3041 path = strdup(argv[0]);
3042 if (path == NULL) {
3043 error = got_error_from_errno("strdup");
3044 goto done;
3047 } else
3048 usage_log();
3050 if (repo_path == NULL) {
3051 repo_path = worktree ?
3052 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3054 if (repo_path == NULL) {
3055 error = got_error_from_errno("strdup");
3056 goto done;
3059 error = got_repo_open(&repo, repo_path, NULL);
3060 if (error != NULL)
3061 goto done;
3063 error = apply_unveil(got_repo_get_path(repo), 1,
3064 worktree ? got_worktree_get_root_path(worktree) : NULL);
3065 if (error)
3066 goto done;
3068 if (start_commit == NULL) {
3069 struct got_reference *head_ref;
3070 error = got_ref_open(&head_ref, repo,
3071 worktree ? got_worktree_get_head_ref_name(worktree)
3072 : GOT_REF_HEAD, 0);
3073 if (error != NULL)
3074 return error;
3075 error = got_ref_resolve(&id, repo, head_ref);
3076 got_ref_close(head_ref);
3077 if (error != NULL)
3078 return error;
3079 error = got_object_open_as_commit(&commit, repo, id);
3080 } else {
3081 struct got_reference *ref;
3082 error = got_ref_open(&ref, repo, start_commit, 0);
3083 if (error == NULL) {
3084 int obj_type;
3085 error = got_ref_resolve(&id, repo, ref);
3086 got_ref_close(ref);
3087 if (error != NULL)
3088 goto done;
3089 error = got_object_get_type(&obj_type, repo, id);
3090 if (error != NULL)
3091 goto done;
3092 if (obj_type == GOT_OBJ_TYPE_TAG) {
3093 struct got_tag_object *tag;
3094 error = got_object_open_as_tag(&tag, repo, id);
3095 if (error != NULL)
3096 goto done;
3097 if (got_object_tag_get_object_type(tag) !=
3098 GOT_OBJ_TYPE_COMMIT) {
3099 got_object_tag_close(tag);
3100 error = got_error(GOT_ERR_OBJ_TYPE);
3101 goto done;
3103 free(id);
3104 id = got_object_id_dup(
3105 got_object_tag_get_object_id(tag));
3106 if (id == NULL)
3107 error = got_error_from_errno(
3108 "got_object_id_dup");
3109 got_object_tag_close(tag);
3110 if (error)
3111 goto done;
3112 } else if (obj_type != GOT_OBJ_TYPE_COMMIT) {
3113 error = got_error(GOT_ERR_OBJ_TYPE);
3114 goto done;
3116 error = got_object_open_as_commit(&commit, repo, id);
3117 if (error != NULL)
3118 goto done;
3120 if (commit == NULL) {
3121 error = got_repo_match_object_id_prefix(&id,
3122 start_commit, GOT_OBJ_TYPE_COMMIT, repo);
3123 if (error != NULL)
3124 return error;
3127 if (error != NULL)
3128 goto done;
3130 if (worktree) {
3131 const char *prefix = got_worktree_get_path_prefix(worktree);
3132 char *p;
3133 if (asprintf(&p, "%s%s%s", prefix,
3134 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3135 error = got_error_from_errno("asprintf");
3136 goto done;
3138 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3139 free(p);
3140 } else
3141 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3142 if (error != NULL)
3143 goto done;
3144 if (in_repo_path) {
3145 free(path);
3146 path = in_repo_path;
3149 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3150 if (error)
3151 goto done;
3153 error = print_commits(id, repo, path, show_patch, search_pattern,
3154 diff_context, limit, log_branches, &refs);
3155 done:
3156 free(path);
3157 free(repo_path);
3158 free(cwd);
3159 free(id);
3160 if (worktree)
3161 got_worktree_close(worktree);
3162 if (repo) {
3163 const struct got_error *repo_error;
3164 repo_error = got_repo_close(repo);
3165 if (error == NULL)
3166 error = repo_error;
3168 got_ref_list_free(&refs);
3169 return error;
3172 __dead static void
3173 usage_diff(void)
3175 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3176 "[-w] [object1 object2 | path]\n", getprogname());
3177 exit(1);
3180 struct print_diff_arg {
3181 struct got_repository *repo;
3182 struct got_worktree *worktree;
3183 int diff_context;
3184 const char *id_str;
3185 int header_shown;
3186 int diff_staged;
3187 int ignore_whitespace;
3190 static const struct got_error *
3191 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3192 const char *path, struct got_object_id *blob_id,
3193 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3194 int dirfd, const char *de_name)
3196 struct print_diff_arg *a = arg;
3197 const struct got_error *err = NULL;
3198 struct got_blob_object *blob1 = NULL;
3199 int fd = -1;
3200 FILE *f2 = NULL;
3201 char *abspath = NULL, *label1 = NULL;
3202 struct stat sb;
3204 if (a->diff_staged) {
3205 if (staged_status != GOT_STATUS_MODIFY &&
3206 staged_status != GOT_STATUS_ADD &&
3207 staged_status != GOT_STATUS_DELETE)
3208 return NULL;
3209 } else {
3210 if (staged_status == GOT_STATUS_DELETE)
3211 return NULL;
3212 if (status == GOT_STATUS_NONEXISTENT)
3213 return got_error_set_errno(ENOENT, path);
3214 if (status != GOT_STATUS_MODIFY &&
3215 status != GOT_STATUS_ADD &&
3216 status != GOT_STATUS_DELETE &&
3217 status != GOT_STATUS_CONFLICT)
3218 return NULL;
3221 if (!a->header_shown) {
3222 printf("diff %s %s%s\n", a->id_str,
3223 got_worktree_get_root_path(a->worktree),
3224 a->diff_staged ? " (staged changes)" : "");
3225 a->header_shown = 1;
3228 if (a->diff_staged) {
3229 const char *label1 = NULL, *label2 = NULL;
3230 switch (staged_status) {
3231 case GOT_STATUS_MODIFY:
3232 label1 = path;
3233 label2 = path;
3234 break;
3235 case GOT_STATUS_ADD:
3236 label2 = path;
3237 break;
3238 case GOT_STATUS_DELETE:
3239 label1 = path;
3240 break;
3241 default:
3242 return got_error(GOT_ERR_FILE_STATUS);
3244 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
3245 label1, label2, a->diff_context, a->ignore_whitespace,
3246 a->repo, stdout);
3249 if (staged_status == GOT_STATUS_ADD ||
3250 staged_status == GOT_STATUS_MODIFY) {
3251 char *id_str;
3252 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
3253 8192);
3254 if (err)
3255 goto done;
3256 err = got_object_id_str(&id_str, staged_blob_id);
3257 if (err)
3258 goto done;
3259 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
3260 err = got_error_from_errno("asprintf");
3261 free(id_str);
3262 goto done;
3264 free(id_str);
3265 } else if (status != GOT_STATUS_ADD) {
3266 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
3267 if (err)
3268 goto done;
3271 if (status != GOT_STATUS_DELETE) {
3272 if (asprintf(&abspath, "%s/%s",
3273 got_worktree_get_root_path(a->worktree), path) == -1) {
3274 err = got_error_from_errno("asprintf");
3275 goto done;
3278 if (dirfd != -1) {
3279 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
3280 if (fd == -1) {
3281 err = got_error_from_errno2("openat", abspath);
3282 goto done;
3284 } else {
3285 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
3286 if (fd == -1) {
3287 err = got_error_from_errno2("open", abspath);
3288 goto done;
3291 if (fstat(fd, &sb) == -1) {
3292 err = got_error_from_errno2("fstat", abspath);
3293 goto done;
3295 f2 = fdopen(fd, "r");
3296 if (f2 == NULL) {
3297 err = got_error_from_errno2("fdopen", abspath);
3298 goto done;
3300 fd = -1;
3301 } else
3302 sb.st_size = 0;
3304 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
3305 a->diff_context, a->ignore_whitespace, stdout);
3306 done:
3307 if (blob1)
3308 got_object_blob_close(blob1);
3309 if (f2 && fclose(f2) == EOF && err == NULL)
3310 err = got_error_from_errno("fclose");
3311 if (fd != -1 && close(fd) == -1 && err == NULL)
3312 err = got_error_from_errno("close");
3313 free(abspath);
3314 return err;
3317 static const struct got_error *
3318 cmd_diff(int argc, char *argv[])
3320 const struct got_error *error;
3321 struct got_repository *repo = NULL;
3322 struct got_worktree *worktree = NULL;
3323 char *cwd = NULL, *repo_path = NULL;
3324 struct got_object_id *id1 = NULL, *id2 = NULL;
3325 const char *id_str1 = NULL, *id_str2 = NULL;
3326 char *label1 = NULL, *label2 = NULL;
3327 int type1, type2;
3328 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
3329 const char *errstr;
3330 char *path = NULL;
3332 #ifndef PROFILE
3333 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3334 NULL) == -1)
3335 err(1, "pledge");
3336 #endif
3338 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
3339 switch (ch) {
3340 case 'C':
3341 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3342 &errstr);
3343 if (errstr != NULL)
3344 err(1, "-C option %s", errstr);
3345 break;
3346 case 'r':
3347 repo_path = realpath(optarg, NULL);
3348 if (repo_path == NULL)
3349 return got_error_from_errno2("realpath",
3350 optarg);
3351 got_path_strip_trailing_slashes(repo_path);
3352 break;
3353 case 's':
3354 diff_staged = 1;
3355 break;
3356 case 'w':
3357 ignore_whitespace = 1;
3358 break;
3359 default:
3360 usage_diff();
3361 /* NOTREACHED */
3365 argc -= optind;
3366 argv += optind;
3368 cwd = getcwd(NULL, 0);
3369 if (cwd == NULL) {
3370 error = got_error_from_errno("getcwd");
3371 goto done;
3373 if (argc <= 1) {
3374 if (repo_path)
3375 errx(1,
3376 "-r option can't be used when diffing a work tree");
3377 error = got_worktree_open(&worktree, cwd);
3378 if (error)
3379 goto done;
3380 repo_path = strdup(got_worktree_get_repo_path(worktree));
3381 if (repo_path == NULL) {
3382 error = got_error_from_errno("strdup");
3383 goto done;
3385 if (argc == 1) {
3386 error = got_worktree_resolve_path(&path, worktree,
3387 argv[0]);
3388 if (error)
3389 goto done;
3390 } else {
3391 path = strdup("");
3392 if (path == NULL) {
3393 error = got_error_from_errno("strdup");
3394 goto done;
3397 } else if (argc == 2) {
3398 if (diff_staged)
3399 errx(1, "-s option can't be used when diffing "
3400 "objects in repository");
3401 id_str1 = argv[0];
3402 id_str2 = argv[1];
3403 if (repo_path == NULL) {
3404 error = got_worktree_open(&worktree, cwd);
3405 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3406 goto done;
3407 if (worktree) {
3408 repo_path = strdup(
3409 got_worktree_get_repo_path(worktree));
3410 if (repo_path == NULL) {
3411 error = got_error_from_errno("strdup");
3412 goto done;
3414 } else {
3415 repo_path = strdup(cwd);
3416 if (repo_path == NULL) {
3417 error = got_error_from_errno("strdup");
3418 goto done;
3422 } else
3423 usage_diff();
3425 error = got_repo_open(&repo, repo_path, NULL);
3426 free(repo_path);
3427 if (error != NULL)
3428 goto done;
3430 error = apply_unveil(got_repo_get_path(repo), 1,
3431 worktree ? got_worktree_get_root_path(worktree) : NULL);
3432 if (error)
3433 goto done;
3435 if (argc <= 1) {
3436 struct print_diff_arg arg;
3437 struct got_pathlist_head paths;
3438 char *id_str;
3440 TAILQ_INIT(&paths);
3442 error = got_object_id_str(&id_str,
3443 got_worktree_get_base_commit_id(worktree));
3444 if (error)
3445 goto done;
3446 arg.repo = repo;
3447 arg.worktree = worktree;
3448 arg.diff_context = diff_context;
3449 arg.id_str = id_str;
3450 arg.header_shown = 0;
3451 arg.diff_staged = diff_staged;
3452 arg.ignore_whitespace = ignore_whitespace;
3454 error = got_pathlist_append(&paths, path, NULL);
3455 if (error)
3456 goto done;
3458 error = got_worktree_status(worktree, &paths, repo, print_diff,
3459 &arg, check_cancelled, NULL);
3460 free(id_str);
3461 got_pathlist_free(&paths);
3462 goto done;
3465 error = got_repo_match_object_id(&id1, &label1, id_str1,
3466 GOT_OBJ_TYPE_ANY, 1, repo);
3467 if (error)
3468 goto done;
3470 error = got_repo_match_object_id(&id2, &label2, id_str2,
3471 GOT_OBJ_TYPE_ANY, 1, repo);
3472 if (error)
3473 goto done;
3475 error = got_object_get_type(&type1, repo, id1);
3476 if (error)
3477 goto done;
3479 error = got_object_get_type(&type2, repo, id2);
3480 if (error)
3481 goto done;
3483 if (type1 != type2) {
3484 error = got_error(GOT_ERR_OBJ_TYPE);
3485 goto done;
3488 switch (type1) {
3489 case GOT_OBJ_TYPE_BLOB:
3490 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
3491 diff_context, ignore_whitespace, repo, stdout);
3492 break;
3493 case GOT_OBJ_TYPE_TREE:
3494 error = got_diff_objects_as_trees(id1, id2, "", "",
3495 diff_context, ignore_whitespace, repo, stdout);
3496 break;
3497 case GOT_OBJ_TYPE_COMMIT:
3498 printf("diff %s %s\n", label1, label2);
3499 error = got_diff_objects_as_commits(id1, id2, diff_context,
3500 ignore_whitespace, repo, stdout);
3501 break;
3502 default:
3503 error = got_error(GOT_ERR_OBJ_TYPE);
3505 done:
3506 free(label1);
3507 free(label2);
3508 free(id1);
3509 free(id2);
3510 free(path);
3511 if (worktree)
3512 got_worktree_close(worktree);
3513 if (repo) {
3514 const struct got_error *repo_error;
3515 repo_error = got_repo_close(repo);
3516 if (error == NULL)
3517 error = repo_error;
3519 return error;
3522 __dead static void
3523 usage_blame(void)
3525 fprintf(stderr,
3526 "usage: %s blame [-c commit] [-r repository-path] path\n",
3527 getprogname());
3528 exit(1);
3531 struct blame_line {
3532 int annotated;
3533 char *id_str;
3534 char *committer;
3535 char datebuf[11]; /* YYYY-MM-DD + NUL */
3538 struct blame_cb_args {
3539 struct blame_line *lines;
3540 int nlines;
3541 int nlines_prec;
3542 int lineno_cur;
3543 off_t *line_offsets;
3544 FILE *f;
3545 struct got_repository *repo;
3548 static const struct got_error *
3549 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
3551 const struct got_error *err = NULL;
3552 struct blame_cb_args *a = arg;
3553 struct blame_line *bline;
3554 char *line = NULL;
3555 size_t linesize = 0;
3556 struct got_commit_object *commit = NULL;
3557 off_t offset;
3558 struct tm tm;
3559 time_t committer_time;
3561 if (nlines != a->nlines ||
3562 (lineno != -1 && lineno < 1) || lineno > a->nlines)
3563 return got_error(GOT_ERR_RANGE);
3565 if (sigint_received)
3566 return got_error(GOT_ERR_ITER_COMPLETED);
3568 if (lineno == -1)
3569 return NULL; /* no change in this commit */
3571 /* Annotate this line. */
3572 bline = &a->lines[lineno - 1];
3573 if (bline->annotated)
3574 return NULL;
3575 err = got_object_id_str(&bline->id_str, id);
3576 if (err)
3577 return err;
3579 err = got_object_open_as_commit(&commit, a->repo, id);
3580 if (err)
3581 goto done;
3583 bline->committer = strdup(got_object_commit_get_committer(commit));
3584 if (bline->committer == NULL) {
3585 err = got_error_from_errno("strdup");
3586 goto done;
3589 committer_time = got_object_commit_get_committer_time(commit);
3590 if (localtime_r(&committer_time, &tm) == NULL)
3591 return got_error_from_errno("localtime_r");
3592 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
3593 &tm) >= sizeof(bline->datebuf)) {
3594 err = got_error(GOT_ERR_NO_SPACE);
3595 goto done;
3597 bline->annotated = 1;
3599 /* Print lines annotated so far. */
3600 bline = &a->lines[a->lineno_cur - 1];
3601 if (!bline->annotated)
3602 goto done;
3604 offset = a->line_offsets[a->lineno_cur - 1];
3605 if (fseeko(a->f, offset, SEEK_SET) == -1) {
3606 err = got_error_from_errno("fseeko");
3607 goto done;
3610 while (bline->annotated) {
3611 char *smallerthan, *at, *nl, *committer;
3612 size_t len;
3614 if (getline(&line, &linesize, a->f) == -1) {
3615 if (ferror(a->f))
3616 err = got_error_from_errno("getline");
3617 break;
3620 committer = bline->committer;
3621 smallerthan = strchr(committer, '<');
3622 if (smallerthan && smallerthan[1] != '\0')
3623 committer = smallerthan + 1;
3624 at = strchr(committer, '@');
3625 if (at)
3626 *at = '\0';
3627 len = strlen(committer);
3628 if (len >= 9)
3629 committer[8] = '\0';
3631 nl = strchr(line, '\n');
3632 if (nl)
3633 *nl = '\0';
3634 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
3635 bline->id_str, bline->datebuf, committer, line);
3637 a->lineno_cur++;
3638 bline = &a->lines[a->lineno_cur - 1];
3640 done:
3641 if (commit)
3642 got_object_commit_close(commit);
3643 free(line);
3644 return err;
3647 static const struct got_error *
3648 cmd_blame(int argc, char *argv[])
3650 const struct got_error *error;
3651 struct got_repository *repo = NULL;
3652 struct got_worktree *worktree = NULL;
3653 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
3654 struct got_object_id *obj_id = NULL;
3655 struct got_object_id *commit_id = NULL;
3656 struct got_blob_object *blob = NULL;
3657 char *commit_id_str = NULL;
3658 struct blame_cb_args bca;
3659 int ch, obj_type, i;
3660 size_t filesize;
3662 memset(&bca, 0, sizeof(bca));
3664 #ifndef PROFILE
3665 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3666 NULL) == -1)
3667 err(1, "pledge");
3668 #endif
3670 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
3671 switch (ch) {
3672 case 'c':
3673 commit_id_str = optarg;
3674 break;
3675 case 'r':
3676 repo_path = realpath(optarg, NULL);
3677 if (repo_path == NULL)
3678 return got_error_from_errno2("realpath",
3679 optarg);
3680 got_path_strip_trailing_slashes(repo_path);
3681 break;
3682 default:
3683 usage_blame();
3684 /* NOTREACHED */
3688 argc -= optind;
3689 argv += optind;
3691 if (argc == 1)
3692 path = argv[0];
3693 else
3694 usage_blame();
3696 cwd = getcwd(NULL, 0);
3697 if (cwd == NULL) {
3698 error = got_error_from_errno("getcwd");
3699 goto done;
3701 if (repo_path == NULL) {
3702 error = got_worktree_open(&worktree, cwd);
3703 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3704 goto done;
3705 else
3706 error = NULL;
3707 if (worktree) {
3708 repo_path =
3709 strdup(got_worktree_get_repo_path(worktree));
3710 if (repo_path == NULL) {
3711 error = got_error_from_errno("strdup");
3712 if (error)
3713 goto done;
3715 } else {
3716 repo_path = strdup(cwd);
3717 if (repo_path == NULL) {
3718 error = got_error_from_errno("strdup");
3719 goto done;
3724 error = got_repo_open(&repo, repo_path, NULL);
3725 if (error != NULL)
3726 goto done;
3728 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
3729 if (error)
3730 goto done;
3732 if (worktree) {
3733 const char *prefix = got_worktree_get_path_prefix(worktree);
3734 char *p, *worktree_subdir = cwd +
3735 strlen(got_worktree_get_root_path(worktree));
3736 if (asprintf(&p, "%s%s%s%s%s",
3737 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
3738 worktree_subdir, worktree_subdir[0] ? "/" : "",
3739 path) == -1) {
3740 error = got_error_from_errno("asprintf");
3741 goto done;
3743 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3744 free(p);
3745 } else {
3746 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3748 if (error)
3749 goto done;
3751 if (commit_id_str == NULL) {
3752 struct got_reference *head_ref;
3753 error = got_ref_open(&head_ref, repo, worktree ?
3754 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
3755 if (error != NULL)
3756 goto done;
3757 error = got_ref_resolve(&commit_id, repo, head_ref);
3758 got_ref_close(head_ref);
3759 if (error != NULL)
3760 goto done;
3761 } else {
3762 error = got_repo_match_object_id(&commit_id, NULL,
3763 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
3764 if (error)
3765 goto done;
3768 error = got_object_id_by_path(&obj_id, repo, commit_id, in_repo_path);
3769 if (error)
3770 goto done;
3772 error = got_object_get_type(&obj_type, repo, obj_id);
3773 if (error)
3774 goto done;
3776 if (obj_type != GOT_OBJ_TYPE_BLOB) {
3777 error = got_error(GOT_ERR_OBJ_TYPE);
3778 goto done;
3781 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
3782 if (error)
3783 goto done;
3784 bca.f = got_opentemp();
3785 if (bca.f == NULL) {
3786 error = got_error_from_errno("got_opentemp");
3787 goto done;
3789 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
3790 &bca.line_offsets, bca.f, blob);
3791 if (error || bca.nlines == 0)
3792 goto done;
3794 /* Don't include \n at EOF in the blame line count. */
3795 if (bca.line_offsets[bca.nlines - 1] == filesize)
3796 bca.nlines--;
3798 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
3799 if (bca.lines == NULL) {
3800 error = got_error_from_errno("calloc");
3801 goto done;
3803 bca.lineno_cur = 1;
3804 bca.nlines_prec = 0;
3805 i = bca.nlines;
3806 while (i > 0) {
3807 i /= 10;
3808 bca.nlines_prec++;
3810 bca.repo = repo;
3812 error = got_blame(in_repo_path, commit_id, repo, blame_cb, &bca,
3813 check_cancelled, NULL);
3814 done:
3815 free(in_repo_path);
3816 free(repo_path);
3817 free(cwd);
3818 free(commit_id);
3819 free(obj_id);
3820 if (blob)
3821 got_object_blob_close(blob);
3822 if (worktree)
3823 got_worktree_close(worktree);
3824 if (repo) {
3825 const struct got_error *repo_error;
3826 repo_error = got_repo_close(repo);
3827 if (error == NULL)
3828 error = repo_error;
3830 if (bca.lines) {
3831 for (i = 0; i < bca.nlines; i++) {
3832 struct blame_line *bline = &bca.lines[i];
3833 free(bline->id_str);
3834 free(bline->committer);
3836 free(bca.lines);
3838 free(bca.line_offsets);
3839 if (bca.f && fclose(bca.f) == EOF && error == NULL)
3840 error = got_error_from_errno("fclose");
3841 return error;
3844 __dead static void
3845 usage_tree(void)
3847 fprintf(stderr,
3848 "usage: %s tree [-c commit] [-r repository-path] [-iR] path\n",
3849 getprogname());
3850 exit(1);
3853 static void
3854 print_entry(struct got_tree_entry *te, const char *id, const char *path,
3855 const char *root_path)
3857 int is_root_path = (strcmp(path, root_path) == 0);
3858 const char *modestr = "";
3859 mode_t mode = got_tree_entry_get_mode(te);
3861 path += strlen(root_path);
3862 while (path[0] == '/')
3863 path++;
3865 if (got_object_tree_entry_is_submodule(te))
3866 modestr = "$";
3867 else if (S_ISLNK(mode))
3868 modestr = "@";
3869 else if (S_ISDIR(mode))
3870 modestr = "/";
3871 else if (mode & S_IXUSR)
3872 modestr = "*";
3874 printf("%s%s%s%s%s\n", id ? id : "", path,
3875 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr);
3878 static const struct got_error *
3879 print_tree(const char *path, struct got_object_id *commit_id,
3880 int show_ids, int recurse, const char *root_path,
3881 struct got_repository *repo)
3883 const struct got_error *err = NULL;
3884 struct got_object_id *tree_id = NULL;
3885 struct got_tree_object *tree = NULL;
3886 int nentries, i;
3888 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
3889 if (err)
3890 goto done;
3892 err = got_object_open_as_tree(&tree, repo, tree_id);
3893 if (err)
3894 goto done;
3895 nentries = got_object_tree_get_nentries(tree);
3896 for (i = 0; i < nentries; i++) {
3897 struct got_tree_entry *te;
3898 char *id = NULL;
3900 if (sigint_received || sigpipe_received)
3901 break;
3903 te = got_object_tree_get_entry(tree, i);
3904 if (show_ids) {
3905 char *id_str;
3906 err = got_object_id_str(&id_str,
3907 got_tree_entry_get_id(te));
3908 if (err)
3909 goto done;
3910 if (asprintf(&id, "%s ", id_str) == -1) {
3911 err = got_error_from_errno("asprintf");
3912 free(id_str);
3913 goto done;
3915 free(id_str);
3917 print_entry(te, id, path, root_path);
3918 free(id);
3920 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
3921 char *child_path;
3922 if (asprintf(&child_path, "%s%s%s", path,
3923 path[0] == '/' && path[1] == '\0' ? "" : "/",
3924 got_tree_entry_get_name(te)) == -1) {
3925 err = got_error_from_errno("asprintf");
3926 goto done;
3928 err = print_tree(child_path, commit_id, show_ids, 1,
3929 root_path, repo);
3930 free(child_path);
3931 if (err)
3932 goto done;
3935 done:
3936 if (tree)
3937 got_object_tree_close(tree);
3938 free(tree_id);
3939 return err;
3942 static const struct got_error *
3943 cmd_tree(int argc, char *argv[])
3945 const struct got_error *error;
3946 struct got_repository *repo = NULL;
3947 struct got_worktree *worktree = NULL;
3948 const char *path;
3949 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
3950 struct got_object_id *commit_id = NULL;
3951 char *commit_id_str = NULL;
3952 int show_ids = 0, recurse = 0;
3953 int ch;
3955 #ifndef PROFILE
3956 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3957 NULL) == -1)
3958 err(1, "pledge");
3959 #endif
3961 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
3962 switch (ch) {
3963 case 'c':
3964 commit_id_str = optarg;
3965 break;
3966 case 'r':
3967 repo_path = realpath(optarg, NULL);
3968 if (repo_path == NULL)
3969 return got_error_from_errno2("realpath",
3970 optarg);
3971 got_path_strip_trailing_slashes(repo_path);
3972 break;
3973 case 'i':
3974 show_ids = 1;
3975 break;
3976 case 'R':
3977 recurse = 1;
3978 break;
3979 default:
3980 usage_tree();
3981 /* NOTREACHED */
3985 argc -= optind;
3986 argv += optind;
3988 if (argc == 1)
3989 path = argv[0];
3990 else if (argc > 1)
3991 usage_tree();
3992 else
3993 path = NULL;
3995 cwd = getcwd(NULL, 0);
3996 if (cwd == NULL) {
3997 error = got_error_from_errno("getcwd");
3998 goto done;
4000 if (repo_path == NULL) {
4001 error = got_worktree_open(&worktree, cwd);
4002 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4003 goto done;
4004 else
4005 error = NULL;
4006 if (worktree) {
4007 repo_path =
4008 strdup(got_worktree_get_repo_path(worktree));
4009 if (repo_path == NULL)
4010 error = got_error_from_errno("strdup");
4011 if (error)
4012 goto done;
4013 } else {
4014 repo_path = strdup(cwd);
4015 if (repo_path == NULL) {
4016 error = got_error_from_errno("strdup");
4017 goto done;
4022 error = got_repo_open(&repo, repo_path, NULL);
4023 if (error != NULL)
4024 goto done;
4026 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4027 if (error)
4028 goto done;
4030 if (path == NULL) {
4031 if (worktree) {
4032 char *p, *worktree_subdir = cwd +
4033 strlen(got_worktree_get_root_path(worktree));
4034 if (asprintf(&p, "%s/%s",
4035 got_worktree_get_path_prefix(worktree),
4036 worktree_subdir) == -1) {
4037 error = got_error_from_errno("asprintf");
4038 goto done;
4040 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4041 free(p);
4042 if (error)
4043 goto done;
4044 } else
4045 path = "/";
4047 if (in_repo_path == NULL) {
4048 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4049 if (error != NULL)
4050 goto done;
4053 if (commit_id_str == NULL) {
4054 struct got_reference *head_ref;
4055 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
4056 if (error != NULL)
4057 goto done;
4058 error = got_ref_resolve(&commit_id, repo, head_ref);
4059 got_ref_close(head_ref);
4060 if (error != NULL)
4061 goto done;
4062 } else {
4063 error = got_repo_match_object_id(&commit_id, NULL,
4064 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4065 if (error)
4066 goto done;
4069 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4070 in_repo_path, repo);
4071 done:
4072 free(in_repo_path);
4073 free(repo_path);
4074 free(cwd);
4075 free(commit_id);
4076 if (worktree)
4077 got_worktree_close(worktree);
4078 if (repo) {
4079 const struct got_error *repo_error;
4080 repo_error = got_repo_close(repo);
4081 if (error == NULL)
4082 error = repo_error;
4084 return error;
4087 __dead static void
4088 usage_status(void)
4090 fprintf(stderr, "usage: %s status [path ...]\n", getprogname());
4091 exit(1);
4094 static const struct got_error *
4095 print_status(void *arg, unsigned char status, unsigned char staged_status,
4096 const char *path, struct got_object_id *blob_id,
4097 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4098 int dirfd, const char *de_name)
4100 if (status == staged_status && (status == GOT_STATUS_DELETE))
4101 status = GOT_STATUS_NO_CHANGE;
4102 printf("%c%c %s\n", status, staged_status, path);
4103 return NULL;
4106 static const struct got_error *
4107 cmd_status(int argc, char *argv[])
4109 const struct got_error *error = NULL;
4110 struct got_repository *repo = NULL;
4111 struct got_worktree *worktree = NULL;
4112 char *cwd = NULL;
4113 struct got_pathlist_head paths;
4114 struct got_pathlist_entry *pe;
4115 int ch;
4117 TAILQ_INIT(&paths);
4119 while ((ch = getopt(argc, argv, "")) != -1) {
4120 switch (ch) {
4121 default:
4122 usage_status();
4123 /* NOTREACHED */
4127 argc -= optind;
4128 argv += optind;
4130 #ifndef PROFILE
4131 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4132 NULL) == -1)
4133 err(1, "pledge");
4134 #endif
4135 cwd = getcwd(NULL, 0);
4136 if (cwd == NULL) {
4137 error = got_error_from_errno("getcwd");
4138 goto done;
4141 error = got_worktree_open(&worktree, cwd);
4142 if (error != NULL)
4143 goto done;
4145 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4146 NULL);
4147 if (error != NULL)
4148 goto done;
4150 error = apply_unveil(got_repo_get_path(repo), 1,
4151 got_worktree_get_root_path(worktree));
4152 if (error)
4153 goto done;
4155 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
4156 if (error)
4157 goto done;
4159 error = got_worktree_status(worktree, &paths, repo, print_status, NULL,
4160 check_cancelled, NULL);
4161 done:
4162 TAILQ_FOREACH(pe, &paths, entry)
4163 free((char *)pe->path);
4164 got_pathlist_free(&paths);
4165 free(cwd);
4166 return error;
4169 __dead static void
4170 usage_ref(void)
4172 fprintf(stderr,
4173 "usage: %s ref [-r repository] -l | -d name | [-s] name target\n",
4174 getprogname());
4175 exit(1);
4178 static const struct got_error *
4179 list_refs(struct got_repository *repo)
4181 static const struct got_error *err = NULL;
4182 struct got_reflist_head refs;
4183 struct got_reflist_entry *re;
4185 SIMPLEQ_INIT(&refs);
4186 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4187 if (err)
4188 return err;
4190 SIMPLEQ_FOREACH(re, &refs, entry) {
4191 char *refstr;
4192 refstr = got_ref_to_str(re->ref);
4193 if (refstr == NULL)
4194 return got_error_from_errno("got_ref_to_str");
4195 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
4196 free(refstr);
4199 got_ref_list_free(&refs);
4200 return NULL;
4203 static const struct got_error *
4204 delete_ref(struct got_repository *repo, const char *refname)
4206 const struct got_error *err = NULL;
4207 struct got_reference *ref;
4209 err = got_ref_open(&ref, repo, refname, 0);
4210 if (err)
4211 return err;
4213 err = got_ref_delete(ref, repo);
4214 got_ref_close(ref);
4215 return err;
4218 static const struct got_error *
4219 add_ref(struct got_repository *repo, const char *refname, const char *target)
4221 const struct got_error *err = NULL;
4222 struct got_object_id *id;
4223 struct got_reference *ref = NULL;
4226 * Don't let the user create a reference name with a leading '-'.
4227 * While technically a valid reference name, this case is usually
4228 * an unintended typo.
4230 if (refname[0] == '-')
4231 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4233 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
4234 repo);
4235 if (err) {
4236 struct got_reference *target_ref;
4238 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
4239 return err;
4240 err = got_ref_open(&target_ref, repo, target, 0);
4241 if (err)
4242 return err;
4243 err = got_ref_resolve(&id, repo, target_ref);
4244 got_ref_close(target_ref);
4245 if (err)
4246 return err;
4249 err = got_ref_alloc(&ref, refname, id);
4250 if (err)
4251 goto done;
4253 err = got_ref_write(ref, repo);
4254 done:
4255 if (ref)
4256 got_ref_close(ref);
4257 free(id);
4258 return err;
4261 static const struct got_error *
4262 add_symref(struct got_repository *repo, const char *refname, const char *target)
4264 const struct got_error *err = NULL;
4265 struct got_reference *ref = NULL;
4266 struct got_reference *target_ref = NULL;
4269 * Don't let the user create a reference name with a leading '-'.
4270 * While technically a valid reference name, this case is usually
4271 * an unintended typo.
4273 if (refname[0] == '-')
4274 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4276 err = got_ref_open(&target_ref, repo, target, 0);
4277 if (err)
4278 return err;
4280 err = got_ref_alloc_symref(&ref, refname, target_ref);
4281 if (err)
4282 goto done;
4284 err = got_ref_write(ref, repo);
4285 done:
4286 if (target_ref)
4287 got_ref_close(target_ref);
4288 if (ref)
4289 got_ref_close(ref);
4290 return err;
4293 static const struct got_error *
4294 cmd_ref(int argc, char *argv[])
4296 const struct got_error *error = NULL;
4297 struct got_repository *repo = NULL;
4298 struct got_worktree *worktree = NULL;
4299 char *cwd = NULL, *repo_path = NULL;
4300 int ch, do_list = 0, create_symref = 0;
4301 const char *delref = NULL;
4303 /* TODO: Add -s option for adding symbolic references. */
4304 while ((ch = getopt(argc, argv, "d:r:ls")) != -1) {
4305 switch (ch) {
4306 case 'd':
4307 delref = optarg;
4308 break;
4309 case 'r':
4310 repo_path = realpath(optarg, NULL);
4311 if (repo_path == NULL)
4312 return got_error_from_errno2("realpath",
4313 optarg);
4314 got_path_strip_trailing_slashes(repo_path);
4315 break;
4316 case 'l':
4317 do_list = 1;
4318 break;
4319 case 's':
4320 create_symref = 1;
4321 break;
4322 default:
4323 usage_ref();
4324 /* NOTREACHED */
4328 if (do_list && delref)
4329 errx(1, "-l and -d options are mutually exclusive\n");
4331 argc -= optind;
4332 argv += optind;
4334 if (do_list || delref) {
4335 if (create_symref)
4336 errx(1, "-s option cannot be used together with the "
4337 "-l or -d options");
4338 if (argc > 0)
4339 usage_ref();
4340 } else if (argc != 2)
4341 usage_ref();
4343 #ifndef PROFILE
4344 if (do_list) {
4345 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4346 NULL) == -1)
4347 err(1, "pledge");
4348 } else {
4349 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4350 "sendfd unveil", NULL) == -1)
4351 err(1, "pledge");
4353 #endif
4354 cwd = getcwd(NULL, 0);
4355 if (cwd == NULL) {
4356 error = got_error_from_errno("getcwd");
4357 goto done;
4360 if (repo_path == NULL) {
4361 error = got_worktree_open(&worktree, cwd);
4362 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4363 goto done;
4364 else
4365 error = NULL;
4366 if (worktree) {
4367 repo_path =
4368 strdup(got_worktree_get_repo_path(worktree));
4369 if (repo_path == NULL)
4370 error = got_error_from_errno("strdup");
4371 if (error)
4372 goto done;
4373 } else {
4374 repo_path = strdup(cwd);
4375 if (repo_path == NULL) {
4376 error = got_error_from_errno("strdup");
4377 goto done;
4382 error = got_repo_open(&repo, repo_path, NULL);
4383 if (error != NULL)
4384 goto done;
4386 error = apply_unveil(got_repo_get_path(repo), do_list,
4387 worktree ? got_worktree_get_root_path(worktree) : NULL);
4388 if (error)
4389 goto done;
4391 if (do_list)
4392 error = list_refs(repo);
4393 else if (delref)
4394 error = delete_ref(repo, delref);
4395 else if (create_symref)
4396 error = add_symref(repo, argv[0], argv[1]);
4397 else
4398 error = add_ref(repo, argv[0], argv[1]);
4399 done:
4400 if (repo)
4401 got_repo_close(repo);
4402 if (worktree)
4403 got_worktree_close(worktree);
4404 free(cwd);
4405 free(repo_path);
4406 return error;
4409 __dead static void
4410 usage_branch(void)
4412 fprintf(stderr,
4413 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
4414 "[name]\n", getprogname());
4415 exit(1);
4418 static const struct got_error *
4419 list_branch(struct got_repository *repo, struct got_worktree *worktree,
4420 struct got_reference *ref)
4422 const struct got_error *err = NULL;
4423 const char *refname, *marker = " ";
4424 char *refstr;
4426 refname = got_ref_get_name(ref);
4427 if (worktree && strcmp(refname,
4428 got_worktree_get_head_ref_name(worktree)) == 0) {
4429 struct got_object_id *id = NULL;
4431 err = got_ref_resolve(&id, repo, ref);
4432 if (err)
4433 return err;
4434 if (got_object_id_cmp(id,
4435 got_worktree_get_base_commit_id(worktree)) == 0)
4436 marker = "* ";
4437 else
4438 marker = "~ ";
4439 free(id);
4442 if (strncmp(refname, "refs/heads/", 11) == 0)
4443 refname += 11;
4444 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4445 refname += 18;
4447 refstr = got_ref_to_str(ref);
4448 if (refstr == NULL)
4449 return got_error_from_errno("got_ref_to_str");
4451 printf("%s%s: %s\n", marker, refname, refstr);
4452 free(refstr);
4453 return NULL;
4456 static const struct got_error *
4457 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
4459 const char *refname;
4461 if (worktree == NULL)
4462 return got_error(GOT_ERR_NOT_WORKTREE);
4464 refname = got_worktree_get_head_ref_name(worktree);
4466 if (strncmp(refname, "refs/heads/", 11) == 0)
4467 refname += 11;
4468 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4469 refname += 18;
4471 printf("%s\n", refname);
4473 return NULL;
4476 static const struct got_error *
4477 list_branches(struct got_repository *repo, struct got_worktree *worktree)
4479 static const struct got_error *err = NULL;
4480 struct got_reflist_head refs;
4481 struct got_reflist_entry *re;
4482 struct got_reference *temp_ref = NULL;
4483 int rebase_in_progress, histedit_in_progress;
4485 SIMPLEQ_INIT(&refs);
4487 if (worktree) {
4488 err = got_worktree_rebase_in_progress(&rebase_in_progress,
4489 worktree);
4490 if (err)
4491 return err;
4493 err = got_worktree_histedit_in_progress(&histedit_in_progress,
4494 worktree);
4495 if (err)
4496 return err;
4498 if (rebase_in_progress || histedit_in_progress) {
4499 err = got_ref_open(&temp_ref, repo,
4500 got_worktree_get_head_ref_name(worktree), 0);
4501 if (err)
4502 return err;
4503 list_branch(repo, worktree, temp_ref);
4504 got_ref_close(temp_ref);
4508 err = got_ref_list(&refs, repo, "refs/heads",
4509 got_ref_cmp_by_name, NULL);
4510 if (err)
4511 return err;
4513 SIMPLEQ_FOREACH(re, &refs, entry)
4514 list_branch(repo, worktree, re->ref);
4516 got_ref_list_free(&refs);
4517 return NULL;
4520 static const struct got_error *
4521 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
4522 const char *branch_name)
4524 const struct got_error *err = NULL;
4525 struct got_reference *ref = NULL;
4526 char *refname;
4528 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
4529 return got_error_from_errno("asprintf");
4531 err = got_ref_open(&ref, repo, refname, 0);
4532 if (err)
4533 goto done;
4535 if (worktree &&
4536 strcmp(got_worktree_get_head_ref_name(worktree),
4537 got_ref_get_name(ref)) == 0) {
4538 err = got_error_msg(GOT_ERR_SAME_BRANCH,
4539 "will not delete this work tree's current branch");
4540 goto done;
4543 err = got_ref_delete(ref, repo);
4544 done:
4545 if (ref)
4546 got_ref_close(ref);
4547 free(refname);
4548 return err;
4551 static const struct got_error *
4552 add_branch(struct got_repository *repo, const char *branch_name,
4553 struct got_object_id *base_commit_id)
4555 const struct got_error *err = NULL;
4556 struct got_reference *ref = NULL;
4557 char *base_refname = NULL, *refname = NULL;
4560 * Don't let the user create a branch name with a leading '-'.
4561 * While technically a valid reference name, this case is usually
4562 * an unintended typo.
4564 if (branch_name[0] == '-')
4565 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
4567 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
4568 err = got_error_from_errno("asprintf");
4569 goto done;
4572 err = got_ref_open(&ref, repo, refname, 0);
4573 if (err == NULL) {
4574 err = got_error(GOT_ERR_BRANCH_EXISTS);
4575 goto done;
4576 } else if (err->code != GOT_ERR_NOT_REF)
4577 goto done;
4579 err = got_ref_alloc(&ref, refname, base_commit_id);
4580 if (err)
4581 goto done;
4583 err = got_ref_write(ref, repo);
4584 done:
4585 if (ref)
4586 got_ref_close(ref);
4587 free(base_refname);
4588 free(refname);
4589 return err;
4592 static const struct got_error *
4593 cmd_branch(int argc, char *argv[])
4595 const struct got_error *error = NULL;
4596 struct got_repository *repo = NULL;
4597 struct got_worktree *worktree = NULL;
4598 char *cwd = NULL, *repo_path = NULL;
4599 int ch, do_list = 0, do_show = 0, do_update = 1;
4600 const char *delref = NULL, *commit_id_arg = NULL;
4601 struct got_reference *ref = NULL;
4602 struct got_pathlist_head paths;
4603 struct got_pathlist_entry *pe;
4604 struct got_object_id *commit_id = NULL;
4605 char *commit_id_str = NULL;
4607 TAILQ_INIT(&paths);
4609 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
4610 switch (ch) {
4611 case 'c':
4612 commit_id_arg = optarg;
4613 break;
4614 case 'd':
4615 delref = optarg;
4616 break;
4617 case 'r':
4618 repo_path = realpath(optarg, NULL);
4619 if (repo_path == NULL)
4620 return got_error_from_errno2("realpath",
4621 optarg);
4622 got_path_strip_trailing_slashes(repo_path);
4623 break;
4624 case 'l':
4625 do_list = 1;
4626 break;
4627 case 'n':
4628 do_update = 0;
4629 break;
4630 default:
4631 usage_branch();
4632 /* NOTREACHED */
4636 if (do_list && delref)
4637 errx(1, "-l and -d options are mutually exclusive\n");
4639 argc -= optind;
4640 argv += optind;
4642 if (!do_list && !delref && argc == 0)
4643 do_show = 1;
4645 if ((do_list || delref || do_show) && commit_id_arg != NULL)
4646 errx(1, "-c option can only be used when creating a branch");
4648 if (do_list || delref) {
4649 if (argc > 0)
4650 usage_branch();
4651 } else if (!do_show && argc != 1)
4652 usage_branch();
4654 #ifndef PROFILE
4655 if (do_list || do_show) {
4656 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4657 NULL) == -1)
4658 err(1, "pledge");
4659 } else {
4660 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4661 "sendfd unveil", NULL) == -1)
4662 err(1, "pledge");
4664 #endif
4665 cwd = getcwd(NULL, 0);
4666 if (cwd == NULL) {
4667 error = got_error_from_errno("getcwd");
4668 goto done;
4671 if (repo_path == NULL) {
4672 error = got_worktree_open(&worktree, cwd);
4673 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4674 goto done;
4675 else
4676 error = NULL;
4677 if (worktree) {
4678 repo_path =
4679 strdup(got_worktree_get_repo_path(worktree));
4680 if (repo_path == NULL)
4681 error = got_error_from_errno("strdup");
4682 if (error)
4683 goto done;
4684 } else {
4685 repo_path = strdup(cwd);
4686 if (repo_path == NULL) {
4687 error = got_error_from_errno("strdup");
4688 goto done;
4693 error = got_repo_open(&repo, repo_path, NULL);
4694 if (error != NULL)
4695 goto done;
4697 error = apply_unveil(got_repo_get_path(repo), do_list,
4698 worktree ? got_worktree_get_root_path(worktree) : NULL);
4699 if (error)
4700 goto done;
4702 if (do_show)
4703 error = show_current_branch(repo, worktree);
4704 else if (do_list)
4705 error = list_branches(repo, worktree);
4706 else if (delref)
4707 error = delete_branch(repo, worktree, delref);
4708 else {
4709 if (commit_id_arg == NULL)
4710 commit_id_arg = worktree ?
4711 got_worktree_get_head_ref_name(worktree) :
4712 GOT_REF_HEAD;
4713 error = got_repo_match_object_id(&commit_id, NULL,
4714 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
4715 if (error)
4716 goto done;
4717 error = add_branch(repo, argv[0], commit_id);
4718 if (error)
4719 goto done;
4720 if (worktree && do_update) {
4721 int did_something = 0;
4722 char *branch_refname = NULL;
4724 error = got_object_id_str(&commit_id_str, commit_id);
4725 if (error)
4726 goto done;
4727 error = get_worktree_paths_from_argv(&paths, 0, NULL,
4728 worktree);
4729 if (error)
4730 goto done;
4731 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
4732 == -1) {
4733 error = got_error_from_errno("asprintf");
4734 goto done;
4736 error = got_ref_open(&ref, repo, branch_refname, 0);
4737 free(branch_refname);
4738 if (error)
4739 goto done;
4740 error = switch_head_ref(ref, commit_id, worktree,
4741 repo);
4742 if (error)
4743 goto done;
4744 error = got_worktree_set_base_commit_id(worktree, repo,
4745 commit_id);
4746 if (error)
4747 goto done;
4748 error = got_worktree_checkout_files(worktree, &paths,
4749 repo, update_progress, &did_something,
4750 check_cancelled, NULL);
4751 if (error)
4752 goto done;
4753 if (did_something)
4754 printf("Updated to commit %s\n", commit_id_str);
4757 done:
4758 if (ref)
4759 got_ref_close(ref);
4760 if (repo)
4761 got_repo_close(repo);
4762 if (worktree)
4763 got_worktree_close(worktree);
4764 free(cwd);
4765 free(repo_path);
4766 free(commit_id);
4767 free(commit_id_str);
4768 TAILQ_FOREACH(pe, &paths, entry)
4769 free((char *)pe->path);
4770 got_pathlist_free(&paths);
4771 return error;
4775 __dead static void
4776 usage_tag(void)
4778 fprintf(stderr,
4779 "usage: %s tag [-c commit] [-r repository] [-l] "
4780 "[-m message] name\n", getprogname());
4781 exit(1);
4784 #if 0
4785 static const struct got_error *
4786 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
4788 const struct got_error *err = NULL;
4789 struct got_reflist_entry *re, *se, *new;
4790 struct got_object_id *re_id, *se_id;
4791 struct got_tag_object *re_tag, *se_tag;
4792 time_t re_time, se_time;
4794 SIMPLEQ_FOREACH(re, tags, entry) {
4795 se = SIMPLEQ_FIRST(sorted);
4796 if (se == NULL) {
4797 err = got_reflist_entry_dup(&new, re);
4798 if (err)
4799 return err;
4800 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
4801 continue;
4802 } else {
4803 err = got_ref_resolve(&re_id, repo, re->ref);
4804 if (err)
4805 break;
4806 err = got_object_open_as_tag(&re_tag, repo, re_id);
4807 free(re_id);
4808 if (err)
4809 break;
4810 re_time = got_object_tag_get_tagger_time(re_tag);
4811 got_object_tag_close(re_tag);
4814 while (se) {
4815 err = got_ref_resolve(&se_id, repo, re->ref);
4816 if (err)
4817 break;
4818 err = got_object_open_as_tag(&se_tag, repo, se_id);
4819 free(se_id);
4820 if (err)
4821 break;
4822 se_time = got_object_tag_get_tagger_time(se_tag);
4823 got_object_tag_close(se_tag);
4825 if (se_time > re_time) {
4826 err = got_reflist_entry_dup(&new, re);
4827 if (err)
4828 return err;
4829 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
4830 break;
4832 se = SIMPLEQ_NEXT(se, entry);
4833 continue;
4836 done:
4837 return err;
4839 #endif
4841 static const struct got_error *
4842 list_tags(struct got_repository *repo, struct got_worktree *worktree)
4844 static const struct got_error *err = NULL;
4845 struct got_reflist_head refs;
4846 struct got_reflist_entry *re;
4848 SIMPLEQ_INIT(&refs);
4850 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
4851 if (err)
4852 return err;
4854 SIMPLEQ_FOREACH(re, &refs, entry) {
4855 const char *refname;
4856 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
4857 char datebuf[26];
4858 const char *tagger;
4859 time_t tagger_time;
4860 struct got_object_id *id;
4861 struct got_tag_object *tag;
4862 struct got_commit_object *commit = NULL;
4864 refname = got_ref_get_name(re->ref);
4865 if (strncmp(refname, "refs/tags/", 10) != 0)
4866 continue;
4867 refname += 10;
4868 refstr = got_ref_to_str(re->ref);
4869 if (refstr == NULL) {
4870 err = got_error_from_errno("got_ref_to_str");
4871 break;
4873 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
4874 free(refstr);
4876 err = got_ref_resolve(&id, repo, re->ref);
4877 if (err)
4878 break;
4879 err = got_object_open_as_tag(&tag, repo, id);
4880 if (err) {
4881 if (err->code != GOT_ERR_OBJ_TYPE) {
4882 free(id);
4883 break;
4885 /* "lightweight" tag */
4886 err = got_object_open_as_commit(&commit, repo, id);
4887 if (err) {
4888 free(id);
4889 break;
4891 tagger = got_object_commit_get_committer(commit);
4892 tagger_time =
4893 got_object_commit_get_committer_time(commit);
4894 err = got_object_id_str(&id_str, id);
4895 free(id);
4896 if (err)
4897 break;
4898 } else {
4899 free(id);
4900 tagger = got_object_tag_get_tagger(tag);
4901 tagger_time = got_object_tag_get_tagger_time(tag);
4902 err = got_object_id_str(&id_str,
4903 got_object_tag_get_object_id(tag));
4904 if (err)
4905 break;
4907 printf("from: %s\n", tagger);
4908 datestr = get_datestr(&tagger_time, datebuf);
4909 if (datestr)
4910 printf("date: %s UTC\n", datestr);
4911 if (commit)
4912 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
4913 else {
4914 switch (got_object_tag_get_object_type(tag)) {
4915 case GOT_OBJ_TYPE_BLOB:
4916 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
4917 id_str);
4918 break;
4919 case GOT_OBJ_TYPE_TREE:
4920 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
4921 id_str);
4922 break;
4923 case GOT_OBJ_TYPE_COMMIT:
4924 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
4925 id_str);
4926 break;
4927 case GOT_OBJ_TYPE_TAG:
4928 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
4929 id_str);
4930 break;
4931 default:
4932 break;
4935 free(id_str);
4936 if (commit) {
4937 err = got_object_commit_get_logmsg(&tagmsg0, commit);
4938 if (err)
4939 break;
4940 got_object_commit_close(commit);
4941 } else {
4942 tagmsg0 = strdup(got_object_tag_get_message(tag));
4943 got_object_tag_close(tag);
4944 if (tagmsg0 == NULL) {
4945 err = got_error_from_errno("strdup");
4946 break;
4950 tagmsg = tagmsg0;
4951 do {
4952 line = strsep(&tagmsg, "\n");
4953 if (line)
4954 printf(" %s\n", line);
4955 } while (line);
4956 free(tagmsg0);
4959 got_ref_list_free(&refs);
4960 return NULL;
4963 static const struct got_error *
4964 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
4965 const char *tag_name, const char *repo_path)
4967 const struct got_error *err = NULL;
4968 char *template = NULL, *initial_content = NULL;
4969 char *editor = NULL;
4970 int fd = -1;
4972 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
4973 err = got_error_from_errno("asprintf");
4974 goto done;
4977 if (asprintf(&initial_content, "\n# tagging commit %s as %s\n",
4978 commit_id_str, tag_name) == -1) {
4979 err = got_error_from_errno("asprintf");
4980 goto done;
4983 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
4984 if (err)
4985 goto done;
4987 dprintf(fd, initial_content);
4988 close(fd);
4990 err = get_editor(&editor);
4991 if (err)
4992 goto done;
4993 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
4994 done:
4995 free(initial_content);
4996 free(template);
4997 free(editor);
4999 /* Editor is done; we can now apply unveil(2) */
5000 if (err == NULL) {
5001 err = apply_unveil(repo_path, 0, NULL);
5002 if (err) {
5003 free(*tagmsg);
5004 *tagmsg = NULL;
5007 return err;
5010 static const struct got_error *
5011 add_tag(struct got_repository *repo, const char *tag_name,
5012 const char *commit_arg, const char *tagmsg_arg)
5014 const struct got_error *err = NULL;
5015 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5016 char *label = NULL, *commit_id_str = NULL;
5017 struct got_reference *ref = NULL;
5018 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5019 char *tagmsg_path = NULL, *tag_id_str = NULL;
5020 int preserve_tagmsg = 0;
5023 * Don't let the user create a tag name with a leading '-'.
5024 * While technically a valid reference name, this case is usually
5025 * an unintended typo.
5027 if (tag_name[0] == '-')
5028 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5030 err = get_author(&tagger, repo);
5031 if (err)
5032 return err;
5034 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5035 GOT_OBJ_TYPE_COMMIT, 1, repo);
5036 if (err)
5037 goto done;
5039 err = got_object_id_str(&commit_id_str, commit_id);
5040 if (err)
5041 goto done;
5043 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5044 refname = strdup(tag_name);
5045 if (refname == NULL) {
5046 err = got_error_from_errno("strdup");
5047 goto done;
5049 tag_name += 10;
5050 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5051 err = got_error_from_errno("asprintf");
5052 goto done;
5055 err = got_ref_open(&ref, repo, refname, 0);
5056 if (err == NULL) {
5057 err = got_error(GOT_ERR_TAG_EXISTS);
5058 goto done;
5059 } else if (err->code != GOT_ERR_NOT_REF)
5060 goto done;
5062 if (tagmsg_arg == NULL) {
5063 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5064 tag_name, got_repo_get_path(repo));
5065 if (err) {
5066 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5067 tagmsg_path != NULL)
5068 preserve_tagmsg = 1;
5069 goto done;
5073 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5074 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5075 if (err) {
5076 if (tagmsg_path)
5077 preserve_tagmsg = 1;
5078 goto done;
5081 err = got_ref_alloc(&ref, refname, tag_id);
5082 if (err) {
5083 if (tagmsg_path)
5084 preserve_tagmsg = 1;
5085 goto done;
5088 err = got_ref_write(ref, repo);
5089 if (err) {
5090 if (tagmsg_path)
5091 preserve_tagmsg = 1;
5092 goto done;
5095 err = got_object_id_str(&tag_id_str, tag_id);
5096 if (err) {
5097 if (tagmsg_path)
5098 preserve_tagmsg = 1;
5099 goto done;
5101 printf("Created tag %s\n", tag_id_str);
5102 done:
5103 if (preserve_tagmsg) {
5104 fprintf(stderr, "%s: tag message preserved in %s\n",
5105 getprogname(), tagmsg_path);
5106 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
5107 err = got_error_from_errno2("unlink", tagmsg_path);
5108 free(tag_id_str);
5109 if (ref)
5110 got_ref_close(ref);
5111 free(commit_id);
5112 free(commit_id_str);
5113 free(refname);
5114 free(tagmsg);
5115 free(tagmsg_path);
5116 free(tagger);
5117 return err;
5120 static const struct got_error *
5121 cmd_tag(int argc, char *argv[])
5123 const struct got_error *error = NULL;
5124 struct got_repository *repo = NULL;
5125 struct got_worktree *worktree = NULL;
5126 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
5127 char *gitconfig_path = NULL;
5128 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
5129 int ch, do_list = 0;
5131 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
5132 switch (ch) {
5133 case 'c':
5134 commit_id_arg = optarg;
5135 break;
5136 case 'm':
5137 tagmsg = optarg;
5138 break;
5139 case 'r':
5140 repo_path = realpath(optarg, NULL);
5141 if (repo_path == NULL)
5142 return got_error_from_errno2("realpath",
5143 optarg);
5144 got_path_strip_trailing_slashes(repo_path);
5145 break;
5146 case 'l':
5147 do_list = 1;
5148 break;
5149 default:
5150 usage_tag();
5151 /* NOTREACHED */
5155 argc -= optind;
5156 argv += optind;
5158 if (do_list) {
5159 if (commit_id_arg != NULL)
5160 errx(1, "-c option can only be used when creating a tag");
5161 if (tagmsg)
5162 errx(1, "-l and -m options are mutually exclusive");
5163 if (argc > 0)
5164 usage_tag();
5165 } else if (argc != 1)
5166 usage_tag();
5168 tag_name = argv[0];
5170 #ifndef PROFILE
5171 if (do_list) {
5172 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5173 NULL) == -1)
5174 err(1, "pledge");
5175 } else {
5176 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5177 "sendfd unveil", NULL) == -1)
5178 err(1, "pledge");
5180 #endif
5181 cwd = getcwd(NULL, 0);
5182 if (cwd == NULL) {
5183 error = got_error_from_errno("getcwd");
5184 goto done;
5187 if (repo_path == NULL) {
5188 error = got_worktree_open(&worktree, cwd);
5189 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5190 goto done;
5191 else
5192 error = NULL;
5193 if (worktree) {
5194 repo_path =
5195 strdup(got_worktree_get_repo_path(worktree));
5196 if (repo_path == NULL)
5197 error = got_error_from_errno("strdup");
5198 if (error)
5199 goto done;
5200 } else {
5201 repo_path = strdup(cwd);
5202 if (repo_path == NULL) {
5203 error = got_error_from_errno("strdup");
5204 goto done;
5209 if (do_list) {
5210 error = got_repo_open(&repo, repo_path, NULL);
5211 if (error != NULL)
5212 goto done;
5213 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5214 if (error)
5215 goto done;
5216 error = list_tags(repo, worktree);
5217 } else {
5218 error = get_gitconfig_path(&gitconfig_path);
5219 if (error)
5220 goto done;
5221 error = got_repo_open(&repo, repo_path, gitconfig_path);
5222 if (error != NULL)
5223 goto done;
5225 if (tagmsg) {
5226 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5227 if (error)
5228 goto done;
5231 if (commit_id_arg == NULL) {
5232 struct got_reference *head_ref;
5233 struct got_object_id *commit_id;
5234 error = got_ref_open(&head_ref, repo,
5235 worktree ? got_worktree_get_head_ref_name(worktree)
5236 : GOT_REF_HEAD, 0);
5237 if (error)
5238 goto done;
5239 error = got_ref_resolve(&commit_id, repo, head_ref);
5240 got_ref_close(head_ref);
5241 if (error)
5242 goto done;
5243 error = got_object_id_str(&commit_id_str, commit_id);
5244 free(commit_id);
5245 if (error)
5246 goto done;
5249 error = add_tag(repo, tag_name,
5250 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
5252 done:
5253 if (repo)
5254 got_repo_close(repo);
5255 if (worktree)
5256 got_worktree_close(worktree);
5257 free(cwd);
5258 free(repo_path);
5259 free(gitconfig_path);
5260 free(commit_id_str);
5261 return error;
5264 __dead static void
5265 usage_add(void)
5267 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
5268 getprogname());
5269 exit(1);
5272 static const struct got_error *
5273 add_progress(void *arg, unsigned char status, const char *path)
5275 while (path[0] == '/')
5276 path++;
5277 printf("%c %s\n", status, path);
5278 return NULL;
5281 static const struct got_error *
5282 cmd_add(int argc, char *argv[])
5284 const struct got_error *error = NULL;
5285 struct got_repository *repo = NULL;
5286 struct got_worktree *worktree = NULL;
5287 char *cwd = NULL;
5288 struct got_pathlist_head paths;
5289 struct got_pathlist_entry *pe;
5290 int ch, can_recurse = 0, no_ignores = 0;
5292 TAILQ_INIT(&paths);
5294 while ((ch = getopt(argc, argv, "IR")) != -1) {
5295 switch (ch) {
5296 case 'I':
5297 no_ignores = 1;
5298 break;
5299 case 'R':
5300 can_recurse = 1;
5301 break;
5302 default:
5303 usage_add();
5304 /* NOTREACHED */
5308 argc -= optind;
5309 argv += optind;
5311 #ifndef PROFILE
5312 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5313 NULL) == -1)
5314 err(1, "pledge");
5315 #endif
5316 if (argc < 1)
5317 usage_add();
5319 cwd = getcwd(NULL, 0);
5320 if (cwd == NULL) {
5321 error = got_error_from_errno("getcwd");
5322 goto done;
5325 error = got_worktree_open(&worktree, cwd);
5326 if (error)
5327 goto done;
5329 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5330 NULL);
5331 if (error != NULL)
5332 goto done;
5334 error = apply_unveil(got_repo_get_path(repo), 1,
5335 got_worktree_get_root_path(worktree));
5336 if (error)
5337 goto done;
5339 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5340 if (error)
5341 goto done;
5343 if (!can_recurse && no_ignores) {
5344 error = got_error_msg(GOT_ERR_BAD_PATH,
5345 "disregarding ignores requires -R option");
5346 goto done;
5350 if (!can_recurse) {
5351 char *ondisk_path;
5352 struct stat sb;
5353 TAILQ_FOREACH(pe, &paths, entry) {
5354 if (asprintf(&ondisk_path, "%s/%s",
5355 got_worktree_get_root_path(worktree),
5356 pe->path) == -1) {
5357 error = got_error_from_errno("asprintf");
5358 goto done;
5360 if (lstat(ondisk_path, &sb) == -1) {
5361 if (errno == ENOENT) {
5362 free(ondisk_path);
5363 continue;
5365 error = got_error_from_errno2("lstat",
5366 ondisk_path);
5367 free(ondisk_path);
5368 goto done;
5370 free(ondisk_path);
5371 if (S_ISDIR(sb.st_mode)) {
5372 error = got_error_msg(GOT_ERR_BAD_PATH,
5373 "adding directories requires -R option");
5374 goto done;
5379 error = got_worktree_schedule_add(worktree, &paths, add_progress,
5380 NULL, repo, no_ignores);
5381 done:
5382 if (repo)
5383 got_repo_close(repo);
5384 if (worktree)
5385 got_worktree_close(worktree);
5386 TAILQ_FOREACH(pe, &paths, entry)
5387 free((char *)pe->path);
5388 got_pathlist_free(&paths);
5389 free(cwd);
5390 return error;
5393 __dead static void
5394 usage_remove(void)
5396 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] path ...\n",
5397 getprogname());
5398 exit(1);
5401 static const struct got_error *
5402 print_remove_status(void *arg, unsigned char status,
5403 unsigned char staged_status, const char *path)
5405 while (path[0] == '/')
5406 path++;
5407 if (status == GOT_STATUS_NONEXISTENT)
5408 return NULL;
5409 if (status == staged_status && (status == GOT_STATUS_DELETE))
5410 status = GOT_STATUS_NO_CHANGE;
5411 printf("%c%c %s\n", status, staged_status, path);
5412 return NULL;
5415 static const struct got_error *
5416 cmd_remove(int argc, char *argv[])
5418 const struct got_error *error = NULL;
5419 struct got_worktree *worktree = NULL;
5420 struct got_repository *repo = NULL;
5421 char *cwd = NULL;
5422 struct got_pathlist_head paths;
5423 struct got_pathlist_entry *pe;
5424 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0;
5426 TAILQ_INIT(&paths);
5428 while ((ch = getopt(argc, argv, "fkR")) != -1) {
5429 switch (ch) {
5430 case 'f':
5431 delete_local_mods = 1;
5432 break;
5433 case 'k':
5434 keep_on_disk = 1;
5435 break;
5436 case 'R':
5437 can_recurse = 1;
5438 break;
5439 default:
5440 usage_remove();
5441 /* NOTREACHED */
5445 argc -= optind;
5446 argv += optind;
5448 #ifndef PROFILE
5449 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5450 NULL) == -1)
5451 err(1, "pledge");
5452 #endif
5453 if (argc < 1)
5454 usage_remove();
5456 cwd = getcwd(NULL, 0);
5457 if (cwd == NULL) {
5458 error = got_error_from_errno("getcwd");
5459 goto done;
5461 error = got_worktree_open(&worktree, cwd);
5462 if (error)
5463 goto done;
5465 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5466 NULL);
5467 if (error)
5468 goto done;
5470 error = apply_unveil(got_repo_get_path(repo), 1,
5471 got_worktree_get_root_path(worktree));
5472 if (error)
5473 goto done;
5475 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5476 if (error)
5477 goto done;
5479 if (!can_recurse) {
5480 char *ondisk_path;
5481 struct stat sb;
5482 TAILQ_FOREACH(pe, &paths, entry) {
5483 if (asprintf(&ondisk_path, "%s/%s",
5484 got_worktree_get_root_path(worktree),
5485 pe->path) == -1) {
5486 error = got_error_from_errno("asprintf");
5487 goto done;
5489 if (lstat(ondisk_path, &sb) == -1) {
5490 if (errno == ENOENT) {
5491 free(ondisk_path);
5492 continue;
5494 error = got_error_from_errno2("lstat",
5495 ondisk_path);
5496 free(ondisk_path);
5497 goto done;
5499 free(ondisk_path);
5500 if (S_ISDIR(sb.st_mode)) {
5501 error = got_error_msg(GOT_ERR_BAD_PATH,
5502 "removing directories requires -R option");
5503 goto done;
5508 error = got_worktree_schedule_delete(worktree, &paths,
5509 delete_local_mods, print_remove_status, NULL, repo, keep_on_disk);
5510 done:
5511 if (repo)
5512 got_repo_close(repo);
5513 if (worktree)
5514 got_worktree_close(worktree);
5515 TAILQ_FOREACH(pe, &paths, entry)
5516 free((char *)pe->path);
5517 got_pathlist_free(&paths);
5518 free(cwd);
5519 return error;
5522 __dead static void
5523 usage_revert(void)
5525 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
5526 "path ...\n", getprogname());
5527 exit(1);
5530 static const struct got_error *
5531 revert_progress(void *arg, unsigned char status, const char *path)
5533 if (status == GOT_STATUS_UNVERSIONED)
5534 return NULL;
5536 while (path[0] == '/')
5537 path++;
5538 printf("%c %s\n", status, path);
5539 return NULL;
5542 struct choose_patch_arg {
5543 FILE *patch_script_file;
5544 const char *action;
5547 static const struct got_error *
5548 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
5549 int nchanges, const char *action)
5551 char *line = NULL;
5552 size_t linesize = 0;
5553 ssize_t linelen;
5555 switch (status) {
5556 case GOT_STATUS_ADD:
5557 printf("A %s\n%s this addition? [y/n] ", path, action);
5558 break;
5559 case GOT_STATUS_DELETE:
5560 printf("D %s\n%s this deletion? [y/n] ", path, action);
5561 break;
5562 case GOT_STATUS_MODIFY:
5563 if (fseek(patch_file, 0L, SEEK_SET) == -1)
5564 return got_error_from_errno("fseek");
5565 printf(GOT_COMMIT_SEP_STR);
5566 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
5567 printf("%s", line);
5568 if (ferror(patch_file))
5569 return got_error_from_errno("getline");
5570 printf(GOT_COMMIT_SEP_STR);
5571 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
5572 path, n, nchanges, action);
5573 break;
5574 default:
5575 return got_error_path(path, GOT_ERR_FILE_STATUS);
5578 return NULL;
5581 static const struct got_error *
5582 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
5583 FILE *patch_file, int n, int nchanges)
5585 const struct got_error *err = NULL;
5586 char *line = NULL;
5587 size_t linesize = 0;
5588 ssize_t linelen;
5589 int resp = ' ';
5590 struct choose_patch_arg *a = arg;
5592 *choice = GOT_PATCH_CHOICE_NONE;
5594 if (a->patch_script_file) {
5595 char *nl;
5596 err = show_change(status, path, patch_file, n, nchanges,
5597 a->action);
5598 if (err)
5599 return err;
5600 linelen = getline(&line, &linesize, a->patch_script_file);
5601 if (linelen == -1) {
5602 if (ferror(a->patch_script_file))
5603 return got_error_from_errno("getline");
5604 return NULL;
5606 nl = strchr(line, '\n');
5607 if (nl)
5608 *nl = '\0';
5609 if (strcmp(line, "y") == 0) {
5610 *choice = GOT_PATCH_CHOICE_YES;
5611 printf("y\n");
5612 } else if (strcmp(line, "n") == 0) {
5613 *choice = GOT_PATCH_CHOICE_NO;
5614 printf("n\n");
5615 } else if (strcmp(line, "q") == 0 &&
5616 status == GOT_STATUS_MODIFY) {
5617 *choice = GOT_PATCH_CHOICE_QUIT;
5618 printf("q\n");
5619 } else
5620 printf("invalid response '%s'\n", line);
5621 free(line);
5622 return NULL;
5625 while (resp != 'y' && resp != 'n' && resp != 'q') {
5626 err = show_change(status, path, patch_file, n, nchanges,
5627 a->action);
5628 if (err)
5629 return err;
5630 resp = getchar();
5631 if (resp == '\n')
5632 resp = getchar();
5633 if (status == GOT_STATUS_MODIFY) {
5634 if (resp != 'y' && resp != 'n' && resp != 'q') {
5635 printf("invalid response '%c'\n", resp);
5636 resp = ' ';
5638 } else if (resp != 'y' && resp != 'n') {
5639 printf("invalid response '%c'\n", resp);
5640 resp = ' ';
5644 if (resp == 'y')
5645 *choice = GOT_PATCH_CHOICE_YES;
5646 else if (resp == 'n')
5647 *choice = GOT_PATCH_CHOICE_NO;
5648 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
5649 *choice = GOT_PATCH_CHOICE_QUIT;
5651 return NULL;
5655 static const struct got_error *
5656 cmd_revert(int argc, char *argv[])
5658 const struct got_error *error = NULL;
5659 struct got_worktree *worktree = NULL;
5660 struct got_repository *repo = NULL;
5661 char *cwd = NULL, *path = NULL;
5662 struct got_pathlist_head paths;
5663 struct got_pathlist_entry *pe;
5664 int ch, can_recurse = 0, pflag = 0;
5665 FILE *patch_script_file = NULL;
5666 const char *patch_script_path = NULL;
5667 struct choose_patch_arg cpa;
5669 TAILQ_INIT(&paths);
5671 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
5672 switch (ch) {
5673 case 'p':
5674 pflag = 1;
5675 break;
5676 case 'F':
5677 patch_script_path = optarg;
5678 break;
5679 case 'R':
5680 can_recurse = 1;
5681 break;
5682 default:
5683 usage_revert();
5684 /* NOTREACHED */
5688 argc -= optind;
5689 argv += optind;
5691 #ifndef PROFILE
5692 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
5693 "unveil", NULL) == -1)
5694 err(1, "pledge");
5695 #endif
5696 if (argc < 1)
5697 usage_revert();
5698 if (patch_script_path && !pflag)
5699 errx(1, "-F option can only be used together with -p option");
5701 cwd = getcwd(NULL, 0);
5702 if (cwd == NULL) {
5703 error = got_error_from_errno("getcwd");
5704 goto done;
5706 error = got_worktree_open(&worktree, cwd);
5707 if (error)
5708 goto done;
5710 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5711 NULL);
5712 if (error != NULL)
5713 goto done;
5715 if (patch_script_path) {
5716 patch_script_file = fopen(patch_script_path, "r");
5717 if (patch_script_file == NULL) {
5718 error = got_error_from_errno2("fopen",
5719 patch_script_path);
5720 goto done;
5723 error = apply_unveil(got_repo_get_path(repo), 1,
5724 got_worktree_get_root_path(worktree));
5725 if (error)
5726 goto done;
5728 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5729 if (error)
5730 goto done;
5732 if (!can_recurse) {
5733 char *ondisk_path;
5734 struct stat sb;
5735 TAILQ_FOREACH(pe, &paths, entry) {
5736 if (asprintf(&ondisk_path, "%s/%s",
5737 got_worktree_get_root_path(worktree),
5738 pe->path) == -1) {
5739 error = got_error_from_errno("asprintf");
5740 goto done;
5742 if (lstat(ondisk_path, &sb) == -1) {
5743 if (errno == ENOENT) {
5744 free(ondisk_path);
5745 continue;
5747 error = got_error_from_errno2("lstat",
5748 ondisk_path);
5749 free(ondisk_path);
5750 goto done;
5752 free(ondisk_path);
5753 if (S_ISDIR(sb.st_mode)) {
5754 error = got_error_msg(GOT_ERR_BAD_PATH,
5755 "reverting directories requires -R option");
5756 goto done;
5761 cpa.patch_script_file = patch_script_file;
5762 cpa.action = "revert";
5763 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
5764 pflag ? choose_patch : NULL, &cpa, repo);
5765 done:
5766 if (patch_script_file && fclose(patch_script_file) == EOF &&
5767 error == NULL)
5768 error = got_error_from_errno2("fclose", patch_script_path);
5769 if (repo)
5770 got_repo_close(repo);
5771 if (worktree)
5772 got_worktree_close(worktree);
5773 free(path);
5774 free(cwd);
5775 return error;
5778 __dead static void
5779 usage_commit(void)
5781 fprintf(stderr, "usage: %s commit [-m msg] [path ...]\n",
5782 getprogname());
5783 exit(1);
5786 struct collect_commit_logmsg_arg {
5787 const char *cmdline_log;
5788 const char *editor;
5789 const char *worktree_path;
5790 const char *branch_name;
5791 const char *repo_path;
5792 char *logmsg_path;
5796 static const struct got_error *
5797 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
5798 void *arg)
5800 char *initial_content = NULL;
5801 struct got_pathlist_entry *pe;
5802 const struct got_error *err = NULL;
5803 char *template = NULL;
5804 struct collect_commit_logmsg_arg *a = arg;
5805 int fd;
5806 size_t len;
5808 /* if a message was specified on the command line, just use it */
5809 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
5810 len = strlen(a->cmdline_log) + 1;
5811 *logmsg = malloc(len + 1);
5812 if (*logmsg == NULL)
5813 return got_error_from_errno("malloc");
5814 strlcpy(*logmsg, a->cmdline_log, len);
5815 return NULL;
5818 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
5819 return got_error_from_errno("asprintf");
5821 if (asprintf(&initial_content,
5822 "\n# changes to be committed on branch %s:\n",
5823 a->branch_name) == -1)
5824 return got_error_from_errno("asprintf");
5826 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
5827 if (err)
5828 goto done;
5830 dprintf(fd, initial_content);
5832 TAILQ_FOREACH(pe, commitable_paths, entry) {
5833 struct got_commitable *ct = pe->data;
5834 dprintf(fd, "# %c %s\n",
5835 got_commitable_get_status(ct),
5836 got_commitable_get_path(ct));
5838 close(fd);
5840 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
5841 done:
5842 free(initial_content);
5843 free(template);
5845 /* Editor is done; we can now apply unveil(2) */
5846 if (err == NULL) {
5847 err = apply_unveil(a->repo_path, 0, a->worktree_path);
5848 if (err) {
5849 free(*logmsg);
5850 *logmsg = NULL;
5853 return err;
5856 static const struct got_error *
5857 cmd_commit(int argc, char *argv[])
5859 const struct got_error *error = NULL;
5860 struct got_worktree *worktree = NULL;
5861 struct got_repository *repo = NULL;
5862 char *cwd = NULL, *id_str = NULL;
5863 struct got_object_id *id = NULL;
5864 const char *logmsg = NULL;
5865 struct collect_commit_logmsg_arg cl_arg;
5866 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
5867 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
5868 struct got_pathlist_head paths;
5870 TAILQ_INIT(&paths);
5871 cl_arg.logmsg_path = NULL;
5873 while ((ch = getopt(argc, argv, "m:")) != -1) {
5874 switch (ch) {
5875 case 'm':
5876 logmsg = optarg;
5877 break;
5878 default:
5879 usage_commit();
5880 /* NOTREACHED */
5884 argc -= optind;
5885 argv += optind;
5887 #ifndef PROFILE
5888 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
5889 "unveil", NULL) == -1)
5890 err(1, "pledge");
5891 #endif
5892 cwd = getcwd(NULL, 0);
5893 if (cwd == NULL) {
5894 error = got_error_from_errno("getcwd");
5895 goto done;
5897 error = got_worktree_open(&worktree, cwd);
5898 if (error)
5899 goto done;
5901 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
5902 if (error)
5903 goto done;
5904 if (rebase_in_progress) {
5905 error = got_error(GOT_ERR_REBASING);
5906 goto done;
5909 error = got_worktree_histedit_in_progress(&histedit_in_progress,
5910 worktree);
5911 if (error)
5912 goto done;
5914 error = get_gitconfig_path(&gitconfig_path);
5915 if (error)
5916 goto done;
5917 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5918 gitconfig_path);
5919 if (error != NULL)
5920 goto done;
5922 error = get_author(&author, repo);
5923 if (error)
5924 return error;
5927 * unveil(2) traverses exec(2); if an editor is used we have
5928 * to apply unveil after the log message has been written.
5930 if (logmsg == NULL || strlen(logmsg) == 0)
5931 error = get_editor(&editor);
5932 else
5933 error = apply_unveil(got_repo_get_path(repo), 0,
5934 got_worktree_get_root_path(worktree));
5935 if (error)
5936 goto done;
5938 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5939 if (error)
5940 goto done;
5942 cl_arg.editor = editor;
5943 cl_arg.cmdline_log = logmsg;
5944 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
5945 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
5946 if (!histedit_in_progress) {
5947 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
5948 error = got_error(GOT_ERR_COMMIT_BRANCH);
5949 goto done;
5951 cl_arg.branch_name += 11;
5953 cl_arg.repo_path = got_repo_get_path(repo);
5954 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
5955 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
5956 if (error) {
5957 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5958 cl_arg.logmsg_path != NULL)
5959 preserve_logmsg = 1;
5960 goto done;
5963 error = got_object_id_str(&id_str, id);
5964 if (error)
5965 goto done;
5966 printf("Created commit %s\n", id_str);
5967 done:
5968 if (preserve_logmsg) {
5969 fprintf(stderr, "%s: log message preserved in %s\n",
5970 getprogname(), cl_arg.logmsg_path);
5971 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
5972 error == NULL)
5973 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
5974 free(cl_arg.logmsg_path);
5975 if (repo)
5976 got_repo_close(repo);
5977 if (worktree)
5978 got_worktree_close(worktree);
5979 free(cwd);
5980 free(id_str);
5981 free(gitconfig_path);
5982 free(editor);
5983 free(author);
5984 return error;
5987 __dead static void
5988 usage_cherrypick(void)
5990 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
5991 exit(1);
5994 static const struct got_error *
5995 cmd_cherrypick(int argc, char *argv[])
5997 const struct got_error *error = NULL;
5998 struct got_worktree *worktree = NULL;
5999 struct got_repository *repo = NULL;
6000 char *cwd = NULL, *commit_id_str = NULL;
6001 struct got_object_id *commit_id = NULL;
6002 struct got_commit_object *commit = NULL;
6003 struct got_object_qid *pid;
6004 struct got_reference *head_ref = NULL;
6005 int ch, did_something = 0;
6007 while ((ch = getopt(argc, argv, "")) != -1) {
6008 switch (ch) {
6009 default:
6010 usage_cherrypick();
6011 /* NOTREACHED */
6015 argc -= optind;
6016 argv += optind;
6018 #ifndef PROFILE
6019 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6020 "unveil", NULL) == -1)
6021 err(1, "pledge");
6022 #endif
6023 if (argc != 1)
6024 usage_cherrypick();
6026 cwd = getcwd(NULL, 0);
6027 if (cwd == NULL) {
6028 error = got_error_from_errno("getcwd");
6029 goto done;
6031 error = got_worktree_open(&worktree, cwd);
6032 if (error)
6033 goto done;
6035 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6036 NULL);
6037 if (error != NULL)
6038 goto done;
6040 error = apply_unveil(got_repo_get_path(repo), 0,
6041 got_worktree_get_root_path(worktree));
6042 if (error)
6043 goto done;
6045 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6046 GOT_OBJ_TYPE_COMMIT, repo);
6047 if (error != NULL) {
6048 struct got_reference *ref;
6049 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6050 goto done;
6051 error = got_ref_open(&ref, repo, argv[0], 0);
6052 if (error != NULL)
6053 goto done;
6054 error = got_ref_resolve(&commit_id, repo, ref);
6055 got_ref_close(ref);
6056 if (error != NULL)
6057 goto done;
6059 error = got_object_id_str(&commit_id_str, commit_id);
6060 if (error)
6061 goto done;
6063 error = got_ref_open(&head_ref, repo,
6064 got_worktree_get_head_ref_name(worktree), 0);
6065 if (error != NULL)
6066 goto done;
6068 error = check_same_branch(commit_id, head_ref, NULL, repo);
6069 if (error) {
6070 if (error->code != GOT_ERR_ANCESTRY)
6071 goto done;
6072 error = NULL;
6073 } else {
6074 error = got_error(GOT_ERR_SAME_BRANCH);
6075 goto done;
6078 error = got_object_open_as_commit(&commit, repo, commit_id);
6079 if (error)
6080 goto done;
6081 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6082 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
6083 commit_id, repo, update_progress, &did_something, check_cancelled,
6084 NULL);
6085 if (error != NULL)
6086 goto done;
6088 if (did_something)
6089 printf("Merged commit %s\n", commit_id_str);
6090 done:
6091 if (commit)
6092 got_object_commit_close(commit);
6093 free(commit_id_str);
6094 if (head_ref)
6095 got_ref_close(head_ref);
6096 if (worktree)
6097 got_worktree_close(worktree);
6098 if (repo)
6099 got_repo_close(repo);
6100 return error;
6103 __dead static void
6104 usage_backout(void)
6106 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
6107 exit(1);
6110 static const struct got_error *
6111 cmd_backout(int argc, char *argv[])
6113 const struct got_error *error = NULL;
6114 struct got_worktree *worktree = NULL;
6115 struct got_repository *repo = NULL;
6116 char *cwd = NULL, *commit_id_str = NULL;
6117 struct got_object_id *commit_id = NULL;
6118 struct got_commit_object *commit = NULL;
6119 struct got_object_qid *pid;
6120 struct got_reference *head_ref = NULL;
6121 int ch, did_something = 0;
6123 while ((ch = getopt(argc, argv, "")) != -1) {
6124 switch (ch) {
6125 default:
6126 usage_backout();
6127 /* NOTREACHED */
6131 argc -= optind;
6132 argv += optind;
6134 #ifndef PROFILE
6135 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6136 "unveil", NULL) == -1)
6137 err(1, "pledge");
6138 #endif
6139 if (argc != 1)
6140 usage_backout();
6142 cwd = getcwd(NULL, 0);
6143 if (cwd == NULL) {
6144 error = got_error_from_errno("getcwd");
6145 goto done;
6147 error = got_worktree_open(&worktree, cwd);
6148 if (error)
6149 goto done;
6151 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6152 NULL);
6153 if (error != NULL)
6154 goto done;
6156 error = apply_unveil(got_repo_get_path(repo), 0,
6157 got_worktree_get_root_path(worktree));
6158 if (error)
6159 goto done;
6161 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6162 GOT_OBJ_TYPE_COMMIT, repo);
6163 if (error != NULL) {
6164 struct got_reference *ref;
6165 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6166 goto done;
6167 error = got_ref_open(&ref, repo, argv[0], 0);
6168 if (error != NULL)
6169 goto done;
6170 error = got_ref_resolve(&commit_id, repo, ref);
6171 got_ref_close(ref);
6172 if (error != NULL)
6173 goto done;
6175 error = got_object_id_str(&commit_id_str, commit_id);
6176 if (error)
6177 goto done;
6179 error = got_ref_open(&head_ref, repo,
6180 got_worktree_get_head_ref_name(worktree), 0);
6181 if (error != NULL)
6182 goto done;
6184 error = check_same_branch(commit_id, head_ref, NULL, repo);
6185 if (error)
6186 goto done;
6188 error = got_object_open_as_commit(&commit, repo, commit_id);
6189 if (error)
6190 goto done;
6191 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6192 if (pid == NULL) {
6193 error = got_error(GOT_ERR_ROOT_COMMIT);
6194 goto done;
6197 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
6198 update_progress, &did_something, check_cancelled, NULL);
6199 if (error != NULL)
6200 goto done;
6202 if (did_something)
6203 printf("Backed out commit %s\n", commit_id_str);
6204 done:
6205 if (commit)
6206 got_object_commit_close(commit);
6207 free(commit_id_str);
6208 if (head_ref)
6209 got_ref_close(head_ref);
6210 if (worktree)
6211 got_worktree_close(worktree);
6212 if (repo)
6213 got_repo_close(repo);
6214 return error;
6217 __dead static void
6218 usage_rebase(void)
6220 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
6221 getprogname());
6222 exit(1);
6225 void
6226 trim_logmsg(char *logmsg, int limit)
6228 char *nl;
6229 size_t len;
6231 len = strlen(logmsg);
6232 if (len > limit)
6233 len = limit;
6234 logmsg[len] = '\0';
6235 nl = strchr(logmsg, '\n');
6236 if (nl)
6237 *nl = '\0';
6240 static const struct got_error *
6241 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
6243 const struct got_error *err;
6244 char *logmsg0 = NULL;
6245 const char *s;
6247 err = got_object_commit_get_logmsg(&logmsg0, commit);
6248 if (err)
6249 return err;
6251 s = logmsg0;
6252 while (isspace((unsigned char)s[0]))
6253 s++;
6255 *logmsg = strdup(s);
6256 if (*logmsg == NULL) {
6257 err = got_error_from_errno("strdup");
6258 goto done;
6261 trim_logmsg(*logmsg, limit);
6262 done:
6263 free(logmsg0);
6264 return err;
6267 static const struct got_error *
6268 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
6270 const struct got_error *err;
6271 struct got_commit_object *commit = NULL;
6272 char *id_str = NULL, *logmsg = NULL;
6274 err = got_object_open_as_commit(&commit, repo, id);
6275 if (err)
6276 return err;
6278 err = got_object_id_str(&id_str, id);
6279 if (err)
6280 goto done;
6282 id_str[12] = '\0';
6284 err = get_short_logmsg(&logmsg, 42, commit);
6285 if (err)
6286 goto done;
6288 printf("%s -> merge conflict: %s\n", id_str, logmsg);
6289 done:
6290 free(id_str);
6291 got_object_commit_close(commit);
6292 free(logmsg);
6293 return err;
6296 static const struct got_error *
6297 show_rebase_progress(struct got_commit_object *commit,
6298 struct got_object_id *old_id, struct got_object_id *new_id)
6300 const struct got_error *err;
6301 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
6303 err = got_object_id_str(&old_id_str, old_id);
6304 if (err)
6305 goto done;
6307 if (new_id) {
6308 err = got_object_id_str(&new_id_str, new_id);
6309 if (err)
6310 goto done;
6313 old_id_str[12] = '\0';
6314 if (new_id_str)
6315 new_id_str[12] = '\0';
6317 err = get_short_logmsg(&logmsg, 42, commit);
6318 if (err)
6319 goto done;
6321 printf("%s -> %s: %s\n", old_id_str,
6322 new_id_str ? new_id_str : "no-op change", logmsg);
6323 done:
6324 free(old_id_str);
6325 free(new_id_str);
6326 free(logmsg);
6327 return err;
6330 static const struct got_error *
6331 rebase_progress(void *arg, unsigned char status, const char *path)
6333 unsigned char *rebase_status = arg;
6335 while (path[0] == '/')
6336 path++;
6337 printf("%c %s\n", status, path);
6339 if (*rebase_status == GOT_STATUS_CONFLICT)
6340 return NULL;
6341 if (status == GOT_STATUS_CONFLICT || status == GOT_STATUS_MERGE)
6342 *rebase_status = status;
6343 return NULL;
6346 static const struct got_error *
6347 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
6348 struct got_reference *branch, struct got_reference *new_base_branch,
6349 struct got_reference *tmp_branch, struct got_repository *repo)
6351 printf("Switching work tree to %s\n", got_ref_get_name(branch));
6352 return got_worktree_rebase_complete(worktree, fileindex,
6353 new_base_branch, tmp_branch, branch, repo);
6356 static const struct got_error *
6357 rebase_commit(struct got_pathlist_head *merged_paths,
6358 struct got_worktree *worktree, struct got_fileindex *fileindex,
6359 struct got_reference *tmp_branch,
6360 struct got_object_id *commit_id, struct got_repository *repo)
6362 const struct got_error *error;
6363 struct got_commit_object *commit;
6364 struct got_object_id *new_commit_id;
6366 error = got_object_open_as_commit(&commit, repo, commit_id);
6367 if (error)
6368 return error;
6370 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
6371 worktree, fileindex, tmp_branch, commit, commit_id, repo);
6372 if (error) {
6373 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
6374 goto done;
6375 error = show_rebase_progress(commit, commit_id, NULL);
6376 } else {
6377 error = show_rebase_progress(commit, commit_id, new_commit_id);
6378 free(new_commit_id);
6380 done:
6381 got_object_commit_close(commit);
6382 return error;
6385 struct check_path_prefix_arg {
6386 const char *path_prefix;
6387 size_t len;
6388 int errcode;
6391 static const struct got_error *
6392 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
6393 struct got_blob_object *blob2, struct got_object_id *id1,
6394 struct got_object_id *id2, const char *path1, const char *path2,
6395 mode_t mode1, mode_t mode2, struct got_repository *repo)
6397 struct check_path_prefix_arg *a = arg;
6399 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
6400 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
6401 return got_error(a->errcode);
6403 return NULL;
6406 static const struct got_error *
6407 check_path_prefix(struct got_object_id *parent_id,
6408 struct got_object_id *commit_id, const char *path_prefix,
6409 int errcode, struct got_repository *repo)
6411 const struct got_error *err;
6412 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
6413 struct got_commit_object *commit = NULL, *parent_commit = NULL;
6414 struct check_path_prefix_arg cpp_arg;
6416 if (got_path_is_root_dir(path_prefix))
6417 return NULL;
6419 err = got_object_open_as_commit(&commit, repo, commit_id);
6420 if (err)
6421 goto done;
6423 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
6424 if (err)
6425 goto done;
6427 err = got_object_open_as_tree(&tree1, repo,
6428 got_object_commit_get_tree_id(parent_commit));
6429 if (err)
6430 goto done;
6432 err = got_object_open_as_tree(&tree2, repo,
6433 got_object_commit_get_tree_id(commit));
6434 if (err)
6435 goto done;
6437 cpp_arg.path_prefix = path_prefix;
6438 while (cpp_arg.path_prefix[0] == '/')
6439 cpp_arg.path_prefix++;
6440 cpp_arg.len = strlen(cpp_arg.path_prefix);
6441 cpp_arg.errcode = errcode;
6442 err = got_diff_tree(tree1, tree2, "", "", repo,
6443 check_path_prefix_in_diff, &cpp_arg, 0);
6444 done:
6445 if (tree1)
6446 got_object_tree_close(tree1);
6447 if (tree2)
6448 got_object_tree_close(tree2);
6449 if (commit)
6450 got_object_commit_close(commit);
6451 if (parent_commit)
6452 got_object_commit_close(parent_commit);
6453 return err;
6456 static const struct got_error *
6457 collect_commits(struct got_object_id_queue *commits,
6458 struct got_object_id *initial_commit_id,
6459 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
6460 const char *path_prefix, int path_prefix_errcode,
6461 struct got_repository *repo)
6463 const struct got_error *err = NULL;
6464 struct got_commit_graph *graph = NULL;
6465 struct got_object_id *parent_id = NULL;
6466 struct got_object_qid *qid;
6467 struct got_object_id *commit_id = initial_commit_id;
6469 err = got_commit_graph_open(&graph, "/", 1);
6470 if (err)
6471 return err;
6473 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
6474 check_cancelled, NULL);
6475 if (err)
6476 goto done;
6477 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
6478 err = got_commit_graph_iter_next(&parent_id, graph, repo,
6479 check_cancelled, NULL);
6480 if (err) {
6481 if (err->code == GOT_ERR_ITER_COMPLETED) {
6482 err = got_error_msg(GOT_ERR_ANCESTRY,
6483 "ran out of commits to rebase before "
6484 "youngest common ancestor commit has "
6485 "been reached?!?");
6487 goto done;
6488 } else {
6489 err = check_path_prefix(parent_id, commit_id,
6490 path_prefix, path_prefix_errcode, repo);
6491 if (err)
6492 goto done;
6494 err = got_object_qid_alloc(&qid, commit_id);
6495 if (err)
6496 goto done;
6497 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
6498 commit_id = parent_id;
6501 done:
6502 got_commit_graph_close(graph);
6503 return err;
6506 static const struct got_error *
6507 cmd_rebase(int argc, char *argv[])
6509 const struct got_error *error = NULL;
6510 struct got_worktree *worktree = NULL;
6511 struct got_repository *repo = NULL;
6512 struct got_fileindex *fileindex = NULL;
6513 char *cwd = NULL;
6514 struct got_reference *branch = NULL;
6515 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
6516 struct got_object_id *commit_id = NULL, *parent_id = NULL;
6517 struct got_object_id *resume_commit_id = NULL;
6518 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
6519 struct got_commit_object *commit = NULL;
6520 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
6521 int histedit_in_progress = 0;
6522 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
6523 struct got_object_id_queue commits;
6524 struct got_pathlist_head merged_paths;
6525 const struct got_object_id_queue *parent_ids;
6526 struct got_object_qid *qid, *pid;
6528 SIMPLEQ_INIT(&commits);
6529 TAILQ_INIT(&merged_paths);
6531 while ((ch = getopt(argc, argv, "ac")) != -1) {
6532 switch (ch) {
6533 case 'a':
6534 abort_rebase = 1;
6535 break;
6536 case 'c':
6537 continue_rebase = 1;
6538 break;
6539 default:
6540 usage_rebase();
6541 /* NOTREACHED */
6545 argc -= optind;
6546 argv += optind;
6548 #ifndef PROFILE
6549 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6550 "unveil", NULL) == -1)
6551 err(1, "pledge");
6552 #endif
6553 if (abort_rebase && continue_rebase)
6554 usage_rebase();
6555 else if (abort_rebase || continue_rebase) {
6556 if (argc != 0)
6557 usage_rebase();
6558 } else if (argc != 1)
6559 usage_rebase();
6561 cwd = getcwd(NULL, 0);
6562 if (cwd == NULL) {
6563 error = got_error_from_errno("getcwd");
6564 goto done;
6566 error = got_worktree_open(&worktree, cwd);
6567 if (error)
6568 goto done;
6570 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6571 NULL);
6572 if (error != NULL)
6573 goto done;
6575 error = apply_unveil(got_repo_get_path(repo), 0,
6576 got_worktree_get_root_path(worktree));
6577 if (error)
6578 goto done;
6580 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6581 worktree);
6582 if (error)
6583 goto done;
6584 if (histedit_in_progress) {
6585 error = got_error(GOT_ERR_HISTEDIT_BUSY);
6586 goto done;
6589 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6590 if (error)
6591 goto done;
6593 if (abort_rebase) {
6594 int did_something;
6595 if (!rebase_in_progress) {
6596 error = got_error(GOT_ERR_NOT_REBASING);
6597 goto done;
6599 error = got_worktree_rebase_continue(&resume_commit_id,
6600 &new_base_branch, &tmp_branch, &branch, &fileindex,
6601 worktree, repo);
6602 if (error)
6603 goto done;
6604 printf("Switching work tree to %s\n",
6605 got_ref_get_symref_target(new_base_branch));
6606 error = got_worktree_rebase_abort(worktree, fileindex, repo,
6607 new_base_branch, update_progress, &did_something);
6608 if (error)
6609 goto done;
6610 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
6611 goto done; /* nothing else to do */
6614 if (continue_rebase) {
6615 if (!rebase_in_progress) {
6616 error = got_error(GOT_ERR_NOT_REBASING);
6617 goto done;
6619 error = got_worktree_rebase_continue(&resume_commit_id,
6620 &new_base_branch, &tmp_branch, &branch, &fileindex,
6621 worktree, repo);
6622 if (error)
6623 goto done;
6625 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
6626 resume_commit_id, repo);
6627 if (error)
6628 goto done;
6630 yca_id = got_object_id_dup(resume_commit_id);
6631 if (yca_id == NULL) {
6632 error = got_error_from_errno("got_object_id_dup");
6633 goto done;
6635 } else {
6636 error = got_ref_open(&branch, repo, argv[0], 0);
6637 if (error != NULL)
6638 goto done;
6641 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
6642 if (error)
6643 goto done;
6645 if (!continue_rebase) {
6646 struct got_object_id *base_commit_id;
6648 base_commit_id = got_worktree_get_base_commit_id(worktree);
6649 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
6650 base_commit_id, branch_head_commit_id, repo,
6651 check_cancelled, NULL);
6652 if (error)
6653 goto done;
6654 if (yca_id == NULL) {
6655 error = got_error_msg(GOT_ERR_ANCESTRY,
6656 "specified branch shares no common ancestry "
6657 "with work tree's branch");
6658 goto done;
6661 error = check_same_branch(base_commit_id, branch, yca_id, repo);
6662 if (error) {
6663 if (error->code != GOT_ERR_ANCESTRY)
6664 goto done;
6665 error = NULL;
6666 } else {
6667 error = got_error_msg(GOT_ERR_SAME_BRANCH,
6668 "specified branch resolves to a commit which "
6669 "is already contained in work tree's branch");
6670 goto done;
6672 error = got_worktree_rebase_prepare(&new_base_branch,
6673 &tmp_branch, &fileindex, worktree, branch, repo);
6674 if (error)
6675 goto done;
6678 commit_id = branch_head_commit_id;
6679 error = got_object_open_as_commit(&commit, repo, commit_id);
6680 if (error)
6681 goto done;
6683 parent_ids = got_object_commit_get_parent_ids(commit);
6684 pid = SIMPLEQ_FIRST(parent_ids);
6685 if (pid == NULL) {
6686 if (!continue_rebase) {
6687 int did_something;
6688 error = got_worktree_rebase_abort(worktree, fileindex,
6689 repo, new_base_branch, update_progress,
6690 &did_something);
6691 if (error)
6692 goto done;
6693 printf("Rebase of %s aborted\n",
6694 got_ref_get_name(branch));
6696 error = got_error(GOT_ERR_EMPTY_REBASE);
6697 goto done;
6699 error = collect_commits(&commits, commit_id, pid->id,
6700 yca_id, got_worktree_get_path_prefix(worktree),
6701 GOT_ERR_REBASE_PATH, repo);
6702 got_object_commit_close(commit);
6703 commit = NULL;
6704 if (error)
6705 goto done;
6707 if (SIMPLEQ_EMPTY(&commits)) {
6708 if (continue_rebase) {
6709 error = rebase_complete(worktree, fileindex,
6710 branch, new_base_branch, tmp_branch, repo);
6711 goto done;
6712 } else {
6713 /* Fast-forward the reference of the branch. */
6714 struct got_object_id *new_head_commit_id;
6715 char *id_str;
6716 error = got_ref_resolve(&new_head_commit_id, repo,
6717 new_base_branch);
6718 if (error)
6719 goto done;
6720 error = got_object_id_str(&id_str, new_head_commit_id);
6721 printf("Forwarding %s to commit %s\n",
6722 got_ref_get_name(branch), id_str);
6723 free(id_str);
6724 error = got_ref_change_ref(branch,
6725 new_head_commit_id);
6726 if (error)
6727 goto done;
6731 pid = NULL;
6732 SIMPLEQ_FOREACH(qid, &commits, entry) {
6733 commit_id = qid->id;
6734 parent_id = pid ? pid->id : yca_id;
6735 pid = qid;
6737 error = got_worktree_rebase_merge_files(&merged_paths,
6738 worktree, fileindex, parent_id, commit_id, repo,
6739 rebase_progress, &rebase_status, check_cancelled, NULL);
6740 if (error)
6741 goto done;
6743 if (rebase_status == GOT_STATUS_CONFLICT) {
6744 error = show_rebase_merge_conflict(qid->id, repo);
6745 if (error)
6746 goto done;
6747 got_worktree_rebase_pathlist_free(&merged_paths);
6748 break;
6751 error = rebase_commit(&merged_paths, worktree, fileindex,
6752 tmp_branch, commit_id, repo);
6753 got_worktree_rebase_pathlist_free(&merged_paths);
6754 if (error)
6755 goto done;
6758 if (rebase_status == GOT_STATUS_CONFLICT) {
6759 error = got_worktree_rebase_postpone(worktree, fileindex);
6760 if (error)
6761 goto done;
6762 error = got_error_msg(GOT_ERR_CONFLICTS,
6763 "conflicts must be resolved before rebasing can continue");
6764 } else
6765 error = rebase_complete(worktree, fileindex, branch,
6766 new_base_branch, tmp_branch, repo);
6767 done:
6768 got_object_id_queue_free(&commits);
6769 free(branch_head_commit_id);
6770 free(resume_commit_id);
6771 free(yca_id);
6772 if (commit)
6773 got_object_commit_close(commit);
6774 if (branch)
6775 got_ref_close(branch);
6776 if (new_base_branch)
6777 got_ref_close(new_base_branch);
6778 if (tmp_branch)
6779 got_ref_close(tmp_branch);
6780 if (worktree)
6781 got_worktree_close(worktree);
6782 if (repo)
6783 got_repo_close(repo);
6784 return error;
6787 __dead static void
6788 usage_histedit(void)
6790 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
6791 getprogname());
6792 exit(1);
6795 #define GOT_HISTEDIT_PICK 'p'
6796 #define GOT_HISTEDIT_EDIT 'e'
6797 #define GOT_HISTEDIT_FOLD 'f'
6798 #define GOT_HISTEDIT_DROP 'd'
6799 #define GOT_HISTEDIT_MESG 'm'
6801 static struct got_histedit_cmd {
6802 unsigned char code;
6803 const char *name;
6804 const char *desc;
6805 } got_histedit_cmds[] = {
6806 { GOT_HISTEDIT_PICK, "pick", "use commit" },
6807 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
6808 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
6809 "be used" },
6810 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
6811 { GOT_HISTEDIT_MESG, "mesg",
6812 "single-line log message for commit above (open editor if empty)" },
6815 struct got_histedit_list_entry {
6816 TAILQ_ENTRY(got_histedit_list_entry) entry;
6817 struct got_object_id *commit_id;
6818 const struct got_histedit_cmd *cmd;
6819 char *logmsg;
6821 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
6823 static const struct got_error *
6824 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
6825 FILE *f, struct got_repository *repo)
6827 const struct got_error *err = NULL;
6828 char *logmsg = NULL, *id_str = NULL;
6829 struct got_commit_object *commit = NULL;
6830 int n;
6832 err = got_object_open_as_commit(&commit, repo, commit_id);
6833 if (err)
6834 goto done;
6836 err = get_short_logmsg(&logmsg, 34, commit);
6837 if (err)
6838 goto done;
6840 err = got_object_id_str(&id_str, commit_id);
6841 if (err)
6842 goto done;
6844 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
6845 if (n < 0)
6846 err = got_ferror(f, GOT_ERR_IO);
6847 done:
6848 if (commit)
6849 got_object_commit_close(commit);
6850 free(id_str);
6851 free(logmsg);
6852 return err;
6855 static const struct got_error *
6856 histedit_write_commit_list(struct got_object_id_queue *commits,
6857 FILE *f, int edit_logmsg_only, struct got_repository *repo)
6859 const struct got_error *err = NULL;
6860 struct got_object_qid *qid;
6862 if (SIMPLEQ_EMPTY(commits))
6863 return got_error(GOT_ERR_EMPTY_HISTEDIT);
6865 SIMPLEQ_FOREACH(qid, commits, entry) {
6866 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
6867 f, repo);
6868 if (err)
6869 break;
6870 if (edit_logmsg_only) {
6871 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
6872 if (n < 0) {
6873 err = got_ferror(f, GOT_ERR_IO);
6874 break;
6879 return err;
6882 static const struct got_error *
6883 write_cmd_list(FILE *f, const char *branch_name,
6884 struct got_object_id_queue *commits)
6886 const struct got_error *err = NULL;
6887 int n, i;
6888 char *id_str;
6889 struct got_object_qid *qid;
6891 qid = SIMPLEQ_FIRST(commits);
6892 err = got_object_id_str(&id_str, qid->id);
6893 if (err)
6894 return err;
6896 n = fprintf(f,
6897 "# Editing the history of branch '%s' starting at\n"
6898 "# commit %s\n"
6899 "# Commits will be processed in order from top to "
6900 "bottom of this file.\n", branch_name, id_str);
6901 if (n < 0) {
6902 err = got_ferror(f, GOT_ERR_IO);
6903 goto done;
6906 n = fprintf(f, "# Available histedit commands:\n");
6907 if (n < 0) {
6908 err = got_ferror(f, GOT_ERR_IO);
6909 goto done;
6912 for (i = 0; i < nitems(got_histedit_cmds); i++) {
6913 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
6914 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
6915 cmd->desc);
6916 if (n < 0) {
6917 err = got_ferror(f, GOT_ERR_IO);
6918 break;
6921 done:
6922 free(id_str);
6923 return err;
6926 static const struct got_error *
6927 histedit_syntax_error(int lineno)
6929 static char msg[42];
6930 int ret;
6932 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
6933 lineno);
6934 if (ret == -1 || ret >= sizeof(msg))
6935 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
6937 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
6940 static const struct got_error *
6941 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
6942 char *logmsg, struct got_repository *repo)
6944 const struct got_error *err;
6945 struct got_commit_object *folded_commit = NULL;
6946 char *id_str, *folded_logmsg = NULL;
6948 err = got_object_id_str(&id_str, hle->commit_id);
6949 if (err)
6950 return err;
6952 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
6953 if (err)
6954 goto done;
6956 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
6957 if (err)
6958 goto done;
6959 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
6960 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
6961 folded_logmsg) == -1) {
6962 err = got_error_from_errno("asprintf");
6964 done:
6965 if (folded_commit)
6966 got_object_commit_close(folded_commit);
6967 free(id_str);
6968 free(folded_logmsg);
6969 return err;
6972 static struct got_histedit_list_entry *
6973 get_folded_commits(struct got_histedit_list_entry *hle)
6975 struct got_histedit_list_entry *prev, *folded = NULL;
6977 prev = TAILQ_PREV(hle, got_histedit_list, entry);
6978 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
6979 prev->cmd->code == GOT_HISTEDIT_DROP)) {
6980 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
6981 folded = prev;
6982 prev = TAILQ_PREV(prev, got_histedit_list, entry);
6985 return folded;
6988 static const struct got_error *
6989 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
6990 struct got_repository *repo)
6992 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
6993 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
6994 const struct got_error *err = NULL;
6995 struct got_commit_object *commit = NULL;
6996 int fd;
6997 struct got_histedit_list_entry *folded = NULL;
6999 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7000 if (err)
7001 return err;
7003 folded = get_folded_commits(hle);
7004 if (folded) {
7005 while (folded != hle) {
7006 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7007 folded = TAILQ_NEXT(folded, entry);
7008 continue;
7010 err = append_folded_commit_msg(&new_msg, folded,
7011 logmsg, repo);
7012 if (err)
7013 goto done;
7014 free(logmsg);
7015 logmsg = new_msg;
7016 folded = TAILQ_NEXT(folded, entry);
7020 err = got_object_id_str(&id_str, hle->commit_id);
7021 if (err)
7022 goto done;
7023 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7024 if (err)
7025 goto done;
7026 if (asprintf(&new_msg,
7027 "%s\n# original log message of commit %s: %s",
7028 logmsg ? logmsg : "", id_str, orig_logmsg) == -1) {
7029 err = got_error_from_errno("asprintf");
7030 goto done;
7032 free(logmsg);
7033 logmsg = new_msg;
7035 err = got_object_id_str(&id_str, hle->commit_id);
7036 if (err)
7037 goto done;
7039 err = got_opentemp_named_fd(&logmsg_path, &fd,
7040 GOT_TMPDIR_STR "/got-logmsg");
7041 if (err)
7042 goto done;
7044 dprintf(fd, logmsg);
7045 close(fd);
7047 err = get_editor(&editor);
7048 if (err)
7049 goto done;
7051 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
7052 if (err) {
7053 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
7054 goto done;
7055 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
7057 done:
7058 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
7059 err = got_error_from_errno2("unlink", logmsg_path);
7060 free(logmsg_path);
7061 free(logmsg);
7062 free(orig_logmsg);
7063 free(editor);
7064 if (commit)
7065 got_object_commit_close(commit);
7066 return err;
7069 static const struct got_error *
7070 histedit_parse_list(struct got_histedit_list *histedit_cmds,
7071 FILE *f, struct got_repository *repo)
7073 const struct got_error *err = NULL;
7074 char *line = NULL, *p, *end;
7075 size_t size;
7076 ssize_t len;
7077 int lineno = 0, i;
7078 const struct got_histedit_cmd *cmd;
7079 struct got_object_id *commit_id = NULL;
7080 struct got_histedit_list_entry *hle = NULL;
7082 for (;;) {
7083 len = getline(&line, &size, f);
7084 if (len == -1) {
7085 const struct got_error *getline_err;
7086 if (feof(f))
7087 break;
7088 getline_err = got_error_from_errno("getline");
7089 err = got_ferror(f, getline_err->code);
7090 break;
7092 lineno++;
7093 p = line;
7094 while (isspace((unsigned char)p[0]))
7095 p++;
7096 if (p[0] == '#' || p[0] == '\0') {
7097 free(line);
7098 line = NULL;
7099 continue;
7101 cmd = NULL;
7102 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7103 cmd = &got_histedit_cmds[i];
7104 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
7105 isspace((unsigned char)p[strlen(cmd->name)])) {
7106 p += strlen(cmd->name);
7107 break;
7109 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
7110 p++;
7111 break;
7114 if (i == nitems(got_histedit_cmds)) {
7115 err = histedit_syntax_error(lineno);
7116 break;
7118 while (isspace((unsigned char)p[0]))
7119 p++;
7120 if (cmd->code == GOT_HISTEDIT_MESG) {
7121 if (hle == NULL || hle->logmsg != NULL) {
7122 err = got_error(GOT_ERR_HISTEDIT_CMD);
7123 break;
7125 if (p[0] == '\0') {
7126 err = histedit_edit_logmsg(hle, repo);
7127 if (err)
7128 break;
7129 } else {
7130 hle->logmsg = strdup(p);
7131 if (hle->logmsg == NULL) {
7132 err = got_error_from_errno("strdup");
7133 break;
7136 free(line);
7137 line = NULL;
7138 continue;
7139 } else {
7140 end = p;
7141 while (end[0] && !isspace((unsigned char)end[0]))
7142 end++;
7143 *end = '\0';
7145 err = got_object_resolve_id_str(&commit_id, repo, p);
7146 if (err) {
7147 /* override error code */
7148 err = histedit_syntax_error(lineno);
7149 break;
7152 hle = malloc(sizeof(*hle));
7153 if (hle == NULL) {
7154 err = got_error_from_errno("malloc");
7155 break;
7157 hle->cmd = cmd;
7158 hle->commit_id = commit_id;
7159 hle->logmsg = NULL;
7160 commit_id = NULL;
7161 free(line);
7162 line = NULL;
7163 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
7166 free(line);
7167 free(commit_id);
7168 return err;
7171 static const struct got_error *
7172 histedit_check_script(struct got_histedit_list *histedit_cmds,
7173 struct got_object_id_queue *commits, struct got_repository *repo)
7175 const struct got_error *err = NULL;
7176 struct got_object_qid *qid;
7177 struct got_histedit_list_entry *hle;
7178 static char msg[92];
7179 char *id_str;
7181 if (TAILQ_EMPTY(histedit_cmds))
7182 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
7183 "histedit script contains no commands");
7184 if (SIMPLEQ_EMPTY(commits))
7185 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7187 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7188 struct got_histedit_list_entry *hle2;
7189 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
7190 if (hle == hle2)
7191 continue;
7192 if (got_object_id_cmp(hle->commit_id,
7193 hle2->commit_id) != 0)
7194 continue;
7195 err = got_object_id_str(&id_str, hle->commit_id);
7196 if (err)
7197 return err;
7198 snprintf(msg, sizeof(msg), "commit %s is listed "
7199 "more than once in histedit script", id_str);
7200 free(id_str);
7201 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7205 SIMPLEQ_FOREACH(qid, commits, entry) {
7206 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7207 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
7208 break;
7210 if (hle == NULL) {
7211 err = got_object_id_str(&id_str, qid->id);
7212 if (err)
7213 return err;
7214 snprintf(msg, sizeof(msg),
7215 "commit %s missing from histedit script", id_str);
7216 free(id_str);
7217 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7221 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
7222 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
7223 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
7224 "last commit in histedit script cannot be folded");
7226 return NULL;
7229 static const struct got_error *
7230 histedit_run_editor(struct got_histedit_list *histedit_cmds,
7231 const char *path, struct got_object_id_queue *commits,
7232 struct got_repository *repo)
7234 const struct got_error *err = NULL;
7235 char *editor;
7236 FILE *f = NULL;
7238 err = get_editor(&editor);
7239 if (err)
7240 return err;
7242 if (spawn_editor(editor, path) == -1) {
7243 err = got_error_from_errno("failed spawning editor");
7244 goto done;
7247 f = fopen(path, "r");
7248 if (f == NULL) {
7249 err = got_error_from_errno("fopen");
7250 goto done;
7252 err = histedit_parse_list(histedit_cmds, f, repo);
7253 if (err)
7254 goto done;
7256 err = histedit_check_script(histedit_cmds, commits, repo);
7257 done:
7258 if (f && fclose(f) != 0 && err == NULL)
7259 err = got_error_from_errno("fclose");
7260 free(editor);
7261 return err;
7264 static const struct got_error *
7265 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
7266 struct got_object_id_queue *, const char *, const char *,
7267 struct got_repository *);
7269 static const struct got_error *
7270 histedit_edit_script(struct got_histedit_list *histedit_cmds,
7271 struct got_object_id_queue *commits, const char *branch_name,
7272 int edit_logmsg_only, struct got_repository *repo)
7274 const struct got_error *err;
7275 FILE *f = NULL;
7276 char *path = NULL;
7278 err = got_opentemp_named(&path, &f, "got-histedit");
7279 if (err)
7280 return err;
7282 err = write_cmd_list(f, branch_name, commits);
7283 if (err)
7284 goto done;
7286 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
7287 if (err)
7288 goto done;
7290 if (edit_logmsg_only) {
7291 rewind(f);
7292 err = histedit_parse_list(histedit_cmds, f, repo);
7293 } else {
7294 if (fclose(f) != 0) {
7295 err = got_error_from_errno("fclose");
7296 goto done;
7298 f = NULL;
7299 err = histedit_run_editor(histedit_cmds, path, commits, repo);
7300 if (err) {
7301 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7302 err->code != GOT_ERR_HISTEDIT_CMD)
7303 goto done;
7304 err = histedit_edit_list_retry(histedit_cmds, err,
7305 commits, path, branch_name, repo);
7308 done:
7309 if (f && fclose(f) != 0 && err == NULL)
7310 err = got_error_from_errno("fclose");
7311 if (path && unlink(path) != 0 && err == NULL)
7312 err = got_error_from_errno2("unlink", path);
7313 free(path);
7314 return err;
7317 static const struct got_error *
7318 histedit_save_list(struct got_histedit_list *histedit_cmds,
7319 struct got_worktree *worktree, struct got_repository *repo)
7321 const struct got_error *err = NULL;
7322 char *path = NULL;
7323 FILE *f = NULL;
7324 struct got_histedit_list_entry *hle;
7325 struct got_commit_object *commit = NULL;
7327 err = got_worktree_get_histedit_script_path(&path, worktree);
7328 if (err)
7329 return err;
7331 f = fopen(path, "w");
7332 if (f == NULL) {
7333 err = got_error_from_errno2("fopen", path);
7334 goto done;
7336 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7337 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
7338 repo);
7339 if (err)
7340 break;
7342 if (hle->logmsg) {
7343 int n = fprintf(f, "%c %s\n",
7344 GOT_HISTEDIT_MESG, hle->logmsg);
7345 if (n < 0) {
7346 err = got_ferror(f, GOT_ERR_IO);
7347 break;
7351 done:
7352 if (f && fclose(f) != 0 && err == NULL)
7353 err = got_error_from_errno("fclose");
7354 free(path);
7355 if (commit)
7356 got_object_commit_close(commit);
7357 return err;
7360 void
7361 histedit_free_list(struct got_histedit_list *histedit_cmds)
7363 struct got_histedit_list_entry *hle;
7365 while ((hle = TAILQ_FIRST(histedit_cmds))) {
7366 TAILQ_REMOVE(histedit_cmds, hle, entry);
7367 free(hle);
7371 static const struct got_error *
7372 histedit_load_list(struct got_histedit_list *histedit_cmds,
7373 const char *path, struct got_repository *repo)
7375 const struct got_error *err = NULL;
7376 FILE *f = NULL;
7378 f = fopen(path, "r");
7379 if (f == NULL) {
7380 err = got_error_from_errno2("fopen", path);
7381 goto done;
7384 err = histedit_parse_list(histedit_cmds, f, repo);
7385 done:
7386 if (f && fclose(f) != 0 && err == NULL)
7387 err = got_error_from_errno("fclose");
7388 return err;
7391 static const struct got_error *
7392 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
7393 const struct got_error *edit_err, struct got_object_id_queue *commits,
7394 const char *path, const char *branch_name, struct got_repository *repo)
7396 const struct got_error *err = NULL, *prev_err = edit_err;
7397 int resp = ' ';
7399 while (resp != 'c' && resp != 'r' && resp != 'a') {
7400 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
7401 "or (a)bort: ", getprogname(), prev_err->msg);
7402 resp = getchar();
7403 if (resp == '\n')
7404 resp = getchar();
7405 if (resp == 'c') {
7406 histedit_free_list(histedit_cmds);
7407 err = histedit_run_editor(histedit_cmds, path, commits,
7408 repo);
7409 if (err) {
7410 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7411 err->code != GOT_ERR_HISTEDIT_CMD)
7412 break;
7413 prev_err = err;
7414 resp = ' ';
7415 continue;
7417 break;
7418 } else if (resp == 'r') {
7419 histedit_free_list(histedit_cmds);
7420 err = histedit_edit_script(histedit_cmds,
7421 commits, branch_name, 0, repo);
7422 if (err) {
7423 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7424 err->code != GOT_ERR_HISTEDIT_CMD)
7425 break;
7426 prev_err = err;
7427 resp = ' ';
7428 continue;
7430 break;
7431 } else if (resp == 'a') {
7432 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
7433 break;
7434 } else
7435 printf("invalid response '%c'\n", resp);
7438 return err;
7441 static const struct got_error *
7442 histedit_complete(struct got_worktree *worktree,
7443 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
7444 struct got_reference *branch, struct got_repository *repo)
7446 printf("Switching work tree to %s\n",
7447 got_ref_get_symref_target(branch));
7448 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
7449 branch, repo);
7452 static const struct got_error *
7453 show_histedit_progress(struct got_commit_object *commit,
7454 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
7456 const struct got_error *err;
7457 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7459 err = got_object_id_str(&old_id_str, hle->commit_id);
7460 if (err)
7461 goto done;
7463 if (new_id) {
7464 err = got_object_id_str(&new_id_str, new_id);
7465 if (err)
7466 goto done;
7469 old_id_str[12] = '\0';
7470 if (new_id_str)
7471 new_id_str[12] = '\0';
7473 if (hle->logmsg) {
7474 logmsg = strdup(hle->logmsg);
7475 if (logmsg == NULL) {
7476 err = got_error_from_errno("strdup");
7477 goto done;
7479 trim_logmsg(logmsg, 42);
7480 } else {
7481 err = get_short_logmsg(&logmsg, 42, commit);
7482 if (err)
7483 goto done;
7486 switch (hle->cmd->code) {
7487 case GOT_HISTEDIT_PICK:
7488 case GOT_HISTEDIT_EDIT:
7489 printf("%s -> %s: %s\n", old_id_str,
7490 new_id_str ? new_id_str : "no-op change", logmsg);
7491 break;
7492 case GOT_HISTEDIT_DROP:
7493 case GOT_HISTEDIT_FOLD:
7494 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
7495 logmsg);
7496 break;
7497 default:
7498 break;
7500 done:
7501 free(old_id_str);
7502 free(new_id_str);
7503 return err;
7506 static const struct got_error *
7507 histedit_commit(struct got_pathlist_head *merged_paths,
7508 struct got_worktree *worktree, struct got_fileindex *fileindex,
7509 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
7510 struct got_repository *repo)
7512 const struct got_error *err;
7513 struct got_commit_object *commit;
7514 struct got_object_id *new_commit_id;
7516 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
7517 && hle->logmsg == NULL) {
7518 err = histedit_edit_logmsg(hle, repo);
7519 if (err)
7520 return err;
7523 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7524 if (err)
7525 return err;
7527 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
7528 worktree, fileindex, tmp_branch, commit, hle->commit_id,
7529 hle->logmsg, repo);
7530 if (err) {
7531 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
7532 goto done;
7533 err = show_histedit_progress(commit, hle, NULL);
7534 } else {
7535 err = show_histedit_progress(commit, hle, new_commit_id);
7536 free(new_commit_id);
7538 done:
7539 got_object_commit_close(commit);
7540 return err;
7543 static const struct got_error *
7544 histedit_skip_commit(struct got_histedit_list_entry *hle,
7545 struct got_worktree *worktree, struct got_repository *repo)
7547 const struct got_error *error;
7548 struct got_commit_object *commit;
7550 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
7551 repo);
7552 if (error)
7553 return error;
7555 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
7556 if (error)
7557 return error;
7559 error = show_histedit_progress(commit, hle, NULL);
7560 got_object_commit_close(commit);
7561 return error;
7564 static const struct got_error *
7565 check_local_changes(void *arg, unsigned char status,
7566 unsigned char staged_status, const char *path,
7567 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
7568 struct got_object_id *commit_id, int dirfd, const char *de_name)
7570 int *have_local_changes = arg;
7572 switch (status) {
7573 case GOT_STATUS_ADD:
7574 case GOT_STATUS_DELETE:
7575 case GOT_STATUS_MODIFY:
7576 case GOT_STATUS_CONFLICT:
7577 *have_local_changes = 1;
7578 return got_error(GOT_ERR_CANCELLED);
7579 default:
7580 break;
7583 switch (staged_status) {
7584 case GOT_STATUS_ADD:
7585 case GOT_STATUS_DELETE:
7586 case GOT_STATUS_MODIFY:
7587 *have_local_changes = 1;
7588 return got_error(GOT_ERR_CANCELLED);
7589 default:
7590 break;
7593 return NULL;
7596 static const struct got_error *
7597 cmd_histedit(int argc, char *argv[])
7599 const struct got_error *error = NULL;
7600 struct got_worktree *worktree = NULL;
7601 struct got_fileindex *fileindex = NULL;
7602 struct got_repository *repo = NULL;
7603 char *cwd = NULL;
7604 struct got_reference *branch = NULL;
7605 struct got_reference *tmp_branch = NULL;
7606 struct got_object_id *resume_commit_id = NULL;
7607 struct got_object_id *base_commit_id = NULL;
7608 struct got_object_id *head_commit_id = NULL;
7609 struct got_commit_object *commit = NULL;
7610 int ch, rebase_in_progress = 0, did_something;
7611 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
7612 int edit_logmsg_only = 0;
7613 const char *edit_script_path = NULL;
7614 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7615 struct got_object_id_queue commits;
7616 struct got_pathlist_head merged_paths;
7617 const struct got_object_id_queue *parent_ids;
7618 struct got_object_qid *pid;
7619 struct got_histedit_list histedit_cmds;
7620 struct got_histedit_list_entry *hle;
7622 SIMPLEQ_INIT(&commits);
7623 TAILQ_INIT(&histedit_cmds);
7624 TAILQ_INIT(&merged_paths);
7626 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
7627 switch (ch) {
7628 case 'a':
7629 abort_edit = 1;
7630 break;
7631 case 'c':
7632 continue_edit = 1;
7633 break;
7634 case 'F':
7635 edit_script_path = optarg;
7636 break;
7637 case 'm':
7638 edit_logmsg_only = 1;
7639 break;
7640 default:
7641 usage_histedit();
7642 /* NOTREACHED */
7646 argc -= optind;
7647 argv += optind;
7649 #ifndef PROFILE
7650 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7651 "unveil", NULL) == -1)
7652 err(1, "pledge");
7653 #endif
7654 if (abort_edit && continue_edit)
7655 errx(1, "histedit's -a and -c options are mutually exclusive");
7656 if (edit_script_path && edit_logmsg_only)
7657 errx(1, "histedit's -F and -m options are mutually exclusive");
7658 if (abort_edit && edit_logmsg_only)
7659 errx(1, "histedit's -a and -m options are mutually exclusive");
7660 if (continue_edit && edit_logmsg_only)
7661 errx(1, "histedit's -c and -m options are mutually exclusive");
7662 if (argc != 0)
7663 usage_histedit();
7666 * This command cannot apply unveil(2) in all cases because the
7667 * user may choose to run an editor to edit the histedit script
7668 * and to edit individual commit log messages.
7669 * unveil(2) traverses exec(2); if an editor is used we have to
7670 * apply unveil after edit script and log messages have been written.
7671 * XXX TODO: Make use of unveil(2) where possible.
7674 cwd = getcwd(NULL, 0);
7675 if (cwd == NULL) {
7676 error = got_error_from_errno("getcwd");
7677 goto done;
7679 error = got_worktree_open(&worktree, cwd);
7680 if (error)
7681 goto done;
7683 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7684 NULL);
7685 if (error != NULL)
7686 goto done;
7688 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7689 if (error)
7690 goto done;
7691 if (rebase_in_progress) {
7692 error = got_error(GOT_ERR_REBASING);
7693 goto done;
7696 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
7697 if (error)
7698 goto done;
7700 if (edit_in_progress && edit_logmsg_only) {
7701 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
7702 "histedit operation is in progress in this "
7703 "work tree and must be continued or aborted "
7704 "before the -m option can be used");
7705 goto done;
7708 if (edit_in_progress && abort_edit) {
7709 error = got_worktree_histedit_continue(&resume_commit_id,
7710 &tmp_branch, &branch, &base_commit_id, &fileindex,
7711 worktree, repo);
7712 if (error)
7713 goto done;
7714 printf("Switching work tree to %s\n",
7715 got_ref_get_symref_target(branch));
7716 error = got_worktree_histedit_abort(worktree, fileindex, repo,
7717 branch, base_commit_id, update_progress, &did_something);
7718 if (error)
7719 goto done;
7720 printf("Histedit of %s aborted\n",
7721 got_ref_get_symref_target(branch));
7722 goto done; /* nothing else to do */
7723 } else if (abort_edit) {
7724 error = got_error(GOT_ERR_NOT_HISTEDIT);
7725 goto done;
7728 if (continue_edit) {
7729 char *path;
7731 if (!edit_in_progress) {
7732 error = got_error(GOT_ERR_NOT_HISTEDIT);
7733 goto done;
7736 error = got_worktree_get_histedit_script_path(&path, worktree);
7737 if (error)
7738 goto done;
7740 error = histedit_load_list(&histedit_cmds, path, repo);
7741 free(path);
7742 if (error)
7743 goto done;
7745 error = got_worktree_histedit_continue(&resume_commit_id,
7746 &tmp_branch, &branch, &base_commit_id, &fileindex,
7747 worktree, repo);
7748 if (error)
7749 goto done;
7751 error = got_ref_resolve(&head_commit_id, repo, branch);
7752 if (error)
7753 goto done;
7755 error = got_object_open_as_commit(&commit, repo,
7756 head_commit_id);
7757 if (error)
7758 goto done;
7759 parent_ids = got_object_commit_get_parent_ids(commit);
7760 pid = SIMPLEQ_FIRST(parent_ids);
7761 if (pid == NULL) {
7762 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
7763 goto done;
7765 error = collect_commits(&commits, head_commit_id, pid->id,
7766 base_commit_id, got_worktree_get_path_prefix(worktree),
7767 GOT_ERR_HISTEDIT_PATH, repo);
7768 got_object_commit_close(commit);
7769 commit = NULL;
7770 if (error)
7771 goto done;
7772 } else {
7773 if (edit_in_progress) {
7774 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7775 goto done;
7778 error = got_ref_open(&branch, repo,
7779 got_worktree_get_head_ref_name(worktree), 0);
7780 if (error != NULL)
7781 goto done;
7783 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
7784 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
7785 "will not edit commit history of a branch outside "
7786 "the \"refs/heads/\" reference namespace");
7787 goto done;
7790 error = got_ref_resolve(&head_commit_id, repo, branch);
7791 got_ref_close(branch);
7792 branch = NULL;
7793 if (error)
7794 goto done;
7796 error = got_object_open_as_commit(&commit, repo,
7797 head_commit_id);
7798 if (error)
7799 goto done;
7800 parent_ids = got_object_commit_get_parent_ids(commit);
7801 pid = SIMPLEQ_FIRST(parent_ids);
7802 if (pid == NULL) {
7803 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
7804 goto done;
7806 error = collect_commits(&commits, head_commit_id, pid->id,
7807 got_worktree_get_base_commit_id(worktree),
7808 got_worktree_get_path_prefix(worktree),
7809 GOT_ERR_HISTEDIT_PATH, repo);
7810 got_object_commit_close(commit);
7811 commit = NULL;
7812 if (error)
7813 goto done;
7815 if (SIMPLEQ_EMPTY(&commits)) {
7816 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
7817 goto done;
7820 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
7821 &base_commit_id, &fileindex, worktree, repo);
7822 if (error)
7823 goto done;
7825 if (edit_script_path) {
7826 error = histedit_load_list(&histedit_cmds,
7827 edit_script_path, repo);
7828 if (error) {
7829 got_worktree_histedit_abort(worktree, fileindex,
7830 repo, branch, base_commit_id,
7831 update_progress, &did_something);
7832 goto done;
7834 } else {
7835 const char *branch_name;
7836 branch_name = got_ref_get_symref_target(branch);
7837 if (strncmp(branch_name, "refs/heads/", 11) == 0)
7838 branch_name += 11;
7839 error = histedit_edit_script(&histedit_cmds, &commits,
7840 branch_name, edit_logmsg_only, repo);
7841 if (error) {
7842 got_worktree_histedit_abort(worktree, fileindex,
7843 repo, branch, base_commit_id,
7844 update_progress, &did_something);
7845 goto done;
7850 error = histedit_save_list(&histedit_cmds, worktree,
7851 repo);
7852 if (error) {
7853 got_worktree_histedit_abort(worktree, fileindex,
7854 repo, branch, base_commit_id,
7855 update_progress, &did_something);
7856 goto done;
7861 error = histedit_check_script(&histedit_cmds, &commits, repo);
7862 if (error)
7863 goto done;
7865 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
7866 if (resume_commit_id) {
7867 if (got_object_id_cmp(hle->commit_id,
7868 resume_commit_id) != 0)
7869 continue;
7871 resume_commit_id = NULL;
7872 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
7873 hle->cmd->code == GOT_HISTEDIT_FOLD) {
7874 error = histedit_skip_commit(hle, worktree,
7875 repo);
7876 if (error)
7877 goto done;
7878 } else {
7879 struct got_pathlist_head paths;
7880 int have_changes = 0;
7882 TAILQ_INIT(&paths);
7883 error = got_pathlist_append(&paths, "", NULL);
7884 if (error)
7885 goto done;
7886 error = got_worktree_status(worktree, &paths,
7887 repo, check_local_changes, &have_changes,
7888 check_cancelled, NULL);
7889 got_pathlist_free(&paths);
7890 if (error) {
7891 if (error->code != GOT_ERR_CANCELLED)
7892 goto done;
7893 if (sigint_received || sigpipe_received)
7894 goto done;
7896 if (have_changes) {
7897 error = histedit_commit(NULL, worktree,
7898 fileindex, tmp_branch, hle, repo);
7899 if (error)
7900 goto done;
7901 } else {
7902 error = got_object_open_as_commit(
7903 &commit, repo, hle->commit_id);
7904 if (error)
7905 goto done;
7906 error = show_histedit_progress(commit,
7907 hle, NULL);
7908 got_object_commit_close(commit);
7909 commit = NULL;
7910 if (error)
7911 goto done;
7914 continue;
7917 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
7918 error = histedit_skip_commit(hle, worktree, repo);
7919 if (error)
7920 goto done;
7921 continue;
7924 error = got_object_open_as_commit(&commit, repo,
7925 hle->commit_id);
7926 if (error)
7927 goto done;
7928 parent_ids = got_object_commit_get_parent_ids(commit);
7929 pid = SIMPLEQ_FIRST(parent_ids);
7931 error = got_worktree_histedit_merge_files(&merged_paths,
7932 worktree, fileindex, pid->id, hle->commit_id, repo,
7933 rebase_progress, &rebase_status, check_cancelled, NULL);
7934 if (error)
7935 goto done;
7936 got_object_commit_close(commit);
7937 commit = NULL;
7939 if (rebase_status == GOT_STATUS_CONFLICT) {
7940 error = show_rebase_merge_conflict(hle->commit_id,
7941 repo);
7942 if (error)
7943 goto done;
7944 got_worktree_rebase_pathlist_free(&merged_paths);
7945 break;
7948 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
7949 char *id_str;
7950 error = got_object_id_str(&id_str, hle->commit_id);
7951 if (error)
7952 goto done;
7953 printf("Stopping histedit for amending commit %s\n",
7954 id_str);
7955 free(id_str);
7956 got_worktree_rebase_pathlist_free(&merged_paths);
7957 error = got_worktree_histedit_postpone(worktree,
7958 fileindex);
7959 goto done;
7962 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
7963 error = histedit_skip_commit(hle, worktree, repo);
7964 if (error)
7965 goto done;
7966 continue;
7969 error = histedit_commit(&merged_paths, worktree, fileindex,
7970 tmp_branch, hle, repo);
7971 got_worktree_rebase_pathlist_free(&merged_paths);
7972 if (error)
7973 goto done;
7976 if (rebase_status == GOT_STATUS_CONFLICT) {
7977 error = got_worktree_histedit_postpone(worktree, fileindex);
7978 if (error)
7979 goto done;
7980 error = got_error_msg(GOT_ERR_CONFLICTS,
7981 "conflicts must be resolved before histedit can continue");
7982 } else
7983 error = histedit_complete(worktree, fileindex, tmp_branch,
7984 branch, repo);
7985 done:
7986 got_object_id_queue_free(&commits);
7987 histedit_free_list(&histedit_cmds);
7988 free(head_commit_id);
7989 free(base_commit_id);
7990 free(resume_commit_id);
7991 if (commit)
7992 got_object_commit_close(commit);
7993 if (branch)
7994 got_ref_close(branch);
7995 if (tmp_branch)
7996 got_ref_close(tmp_branch);
7997 if (worktree)
7998 got_worktree_close(worktree);
7999 if (repo)
8000 got_repo_close(repo);
8001 return error;
8004 __dead static void
8005 usage_integrate(void)
8007 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
8008 exit(1);
8011 static const struct got_error *
8012 cmd_integrate(int argc, char *argv[])
8014 const struct got_error *error = NULL;
8015 struct got_repository *repo = NULL;
8016 struct got_worktree *worktree = NULL;
8017 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
8018 const char *branch_arg = NULL;
8019 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
8020 struct got_fileindex *fileindex = NULL;
8021 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
8022 int ch, did_something = 0;
8024 while ((ch = getopt(argc, argv, "")) != -1) {
8025 switch (ch) {
8026 default:
8027 usage_integrate();
8028 /* NOTREACHED */
8032 argc -= optind;
8033 argv += optind;
8035 if (argc != 1)
8036 usage_integrate();
8037 branch_arg = argv[0];
8039 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8040 "unveil", NULL) == -1)
8041 err(1, "pledge");
8043 cwd = getcwd(NULL, 0);
8044 if (cwd == NULL) {
8045 error = got_error_from_errno("getcwd");
8046 goto done;
8049 error = got_worktree_open(&worktree, cwd);
8050 if (error)
8051 goto done;
8053 error = check_rebase_or_histedit_in_progress(worktree);
8054 if (error)
8055 goto done;
8057 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8058 NULL);
8059 if (error != NULL)
8060 goto done;
8062 error = apply_unveil(got_repo_get_path(repo), 0,
8063 got_worktree_get_root_path(worktree));
8064 if (error)
8065 goto done;
8067 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
8068 error = got_error_from_errno("asprintf");
8069 goto done;
8072 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
8073 &base_branch_ref, worktree, refname, repo);
8074 if (error)
8075 goto done;
8077 refname = strdup(got_ref_get_name(branch_ref));
8078 if (refname == NULL) {
8079 error = got_error_from_errno("strdup");
8080 got_worktree_integrate_abort(worktree, fileindex, repo,
8081 branch_ref, base_branch_ref);
8082 goto done;
8084 base_refname = strdup(got_ref_get_name(base_branch_ref));
8085 if (base_refname == NULL) {
8086 error = got_error_from_errno("strdup");
8087 got_worktree_integrate_abort(worktree, fileindex, repo,
8088 branch_ref, base_branch_ref);
8089 goto done;
8092 error = got_ref_resolve(&commit_id, repo, branch_ref);
8093 if (error)
8094 goto done;
8096 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
8097 if (error)
8098 goto done;
8100 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
8101 error = got_error_msg(GOT_ERR_SAME_BRANCH,
8102 "specified branch has already been integrated");
8103 got_worktree_integrate_abort(worktree, fileindex, repo,
8104 branch_ref, base_branch_ref);
8105 goto done;
8108 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
8109 if (error) {
8110 if (error->code == GOT_ERR_ANCESTRY)
8111 error = got_error(GOT_ERR_REBASE_REQUIRED);
8112 got_worktree_integrate_abort(worktree, fileindex, repo,
8113 branch_ref, base_branch_ref);
8114 goto done;
8117 error = got_worktree_integrate_continue(worktree, fileindex, repo,
8118 branch_ref, base_branch_ref, update_progress, &did_something,
8119 check_cancelled, NULL);
8120 if (error)
8121 goto done;
8123 printf("Integrated %s into %s\n", refname, base_refname);
8124 done:
8125 if (repo)
8126 got_repo_close(repo);
8127 if (worktree)
8128 got_worktree_close(worktree);
8129 free(cwd);
8130 free(base_commit_id);
8131 free(commit_id);
8132 free(refname);
8133 free(base_refname);
8134 return error;
8137 __dead static void
8138 usage_stage(void)
8140 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
8141 "[file-path ...]\n",
8142 getprogname());
8143 exit(1);
8146 static const struct got_error *
8147 print_stage(void *arg, unsigned char status, unsigned char staged_status,
8148 const char *path, struct got_object_id *blob_id,
8149 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
8150 int dirfd, const char *de_name)
8152 const struct got_error *err = NULL;
8153 char *id_str = NULL;
8155 if (staged_status != GOT_STATUS_ADD &&
8156 staged_status != GOT_STATUS_MODIFY &&
8157 staged_status != GOT_STATUS_DELETE)
8158 return NULL;
8160 if (staged_status == GOT_STATUS_ADD ||
8161 staged_status == GOT_STATUS_MODIFY)
8162 err = got_object_id_str(&id_str, staged_blob_id);
8163 else
8164 err = got_object_id_str(&id_str, blob_id);
8165 if (err)
8166 return err;
8168 printf("%s %c %s\n", id_str, staged_status, path);
8169 free(id_str);
8170 return NULL;
8173 static const struct got_error *
8174 cmd_stage(int argc, char *argv[])
8176 const struct got_error *error = NULL;
8177 struct got_repository *repo = NULL;
8178 struct got_worktree *worktree = NULL;
8179 char *cwd = NULL;
8180 struct got_pathlist_head paths;
8181 struct got_pathlist_entry *pe;
8182 int ch, list_stage = 0, pflag = 0;
8183 FILE *patch_script_file = NULL;
8184 const char *patch_script_path = NULL;
8185 struct choose_patch_arg cpa;
8187 TAILQ_INIT(&paths);
8189 while ((ch = getopt(argc, argv, "lpF:")) != -1) {
8190 switch (ch) {
8191 case 'l':
8192 list_stage = 1;
8193 break;
8194 case 'p':
8195 pflag = 1;
8196 break;
8197 case 'F':
8198 patch_script_path = optarg;
8199 break;
8200 default:
8201 usage_stage();
8202 /* NOTREACHED */
8206 argc -= optind;
8207 argv += optind;
8209 #ifndef PROFILE
8210 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8211 "unveil", NULL) == -1)
8212 err(1, "pledge");
8213 #endif
8214 if (list_stage && (pflag || patch_script_path))
8215 errx(1, "-l option cannot be used with other options");
8216 if (patch_script_path && !pflag)
8217 errx(1, "-F option can only be used together with -p option");
8219 cwd = getcwd(NULL, 0);
8220 if (cwd == NULL) {
8221 error = got_error_from_errno("getcwd");
8222 goto done;
8225 error = got_worktree_open(&worktree, cwd);
8226 if (error)
8227 goto done;
8229 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8230 NULL);
8231 if (error != NULL)
8232 goto done;
8234 if (patch_script_path) {
8235 patch_script_file = fopen(patch_script_path, "r");
8236 if (patch_script_file == NULL) {
8237 error = got_error_from_errno2("fopen",
8238 patch_script_path);
8239 goto done;
8242 error = apply_unveil(got_repo_get_path(repo), 0,
8243 got_worktree_get_root_path(worktree));
8244 if (error)
8245 goto done;
8247 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8248 if (error)
8249 goto done;
8251 if (list_stage)
8252 error = got_worktree_status(worktree, &paths, repo,
8253 print_stage, NULL, check_cancelled, NULL);
8254 else {
8255 cpa.patch_script_file = patch_script_file;
8256 cpa.action = "stage";
8257 error = got_worktree_stage(worktree, &paths,
8258 pflag ? NULL : print_status, NULL,
8259 pflag ? choose_patch : NULL, &cpa, repo);
8261 done:
8262 if (patch_script_file && fclose(patch_script_file) == EOF &&
8263 error == NULL)
8264 error = got_error_from_errno2("fclose", patch_script_path);
8265 if (repo)
8266 got_repo_close(repo);
8267 if (worktree)
8268 got_worktree_close(worktree);
8269 TAILQ_FOREACH(pe, &paths, entry)
8270 free((char *)pe->path);
8271 got_pathlist_free(&paths);
8272 free(cwd);
8273 return error;
8276 __dead static void
8277 usage_unstage(void)
8279 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
8280 "[file-path ...]\n",
8281 getprogname());
8282 exit(1);
8286 static const struct got_error *
8287 cmd_unstage(int argc, char *argv[])
8289 const struct got_error *error = NULL;
8290 struct got_repository *repo = NULL;
8291 struct got_worktree *worktree = NULL;
8292 char *cwd = NULL;
8293 struct got_pathlist_head paths;
8294 struct got_pathlist_entry *pe;
8295 int ch, did_something = 0, pflag = 0;
8296 FILE *patch_script_file = NULL;
8297 const char *patch_script_path = NULL;
8298 struct choose_patch_arg cpa;
8300 TAILQ_INIT(&paths);
8302 while ((ch = getopt(argc, argv, "pF:")) != -1) {
8303 switch (ch) {
8304 case 'p':
8305 pflag = 1;
8306 break;
8307 case 'F':
8308 patch_script_path = optarg;
8309 break;
8310 default:
8311 usage_unstage();
8312 /* NOTREACHED */
8316 argc -= optind;
8317 argv += optind;
8319 #ifndef PROFILE
8320 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8321 "unveil", NULL) == -1)
8322 err(1, "pledge");
8323 #endif
8324 if (patch_script_path && !pflag)
8325 errx(1, "-F option can only be used together with -p option");
8327 cwd = getcwd(NULL, 0);
8328 if (cwd == NULL) {
8329 error = got_error_from_errno("getcwd");
8330 goto done;
8333 error = got_worktree_open(&worktree, cwd);
8334 if (error)
8335 goto done;
8337 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8338 NULL);
8339 if (error != NULL)
8340 goto done;
8342 if (patch_script_path) {
8343 patch_script_file = fopen(patch_script_path, "r");
8344 if (patch_script_file == NULL) {
8345 error = got_error_from_errno2("fopen",
8346 patch_script_path);
8347 goto done;
8351 error = apply_unveil(got_repo_get_path(repo), 0,
8352 got_worktree_get_root_path(worktree));
8353 if (error)
8354 goto done;
8356 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8357 if (error)
8358 goto done;
8360 cpa.patch_script_file = patch_script_file;
8361 cpa.action = "unstage";
8362 error = got_worktree_unstage(worktree, &paths, update_progress,
8363 &did_something, pflag ? choose_patch : NULL, &cpa, repo);
8364 done:
8365 if (patch_script_file && fclose(patch_script_file) == EOF &&
8366 error == NULL)
8367 error = got_error_from_errno2("fclose", patch_script_path);
8368 if (repo)
8369 got_repo_close(repo);
8370 if (worktree)
8371 got_worktree_close(worktree);
8372 TAILQ_FOREACH(pe, &paths, entry)
8373 free((char *)pe->path);
8374 got_pathlist_free(&paths);
8375 free(cwd);
8376 return error;
8379 __dead static void
8380 usage_cat(void)
8382 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
8383 "arg1 [arg2 ...]\n", getprogname());
8384 exit(1);
8387 static const struct got_error *
8388 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8390 const struct got_error *err;
8391 struct got_blob_object *blob;
8393 err = got_object_open_as_blob(&blob, repo, id, 8192);
8394 if (err)
8395 return err;
8397 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
8398 got_object_blob_close(blob);
8399 return err;
8402 static const struct got_error *
8403 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8405 const struct got_error *err;
8406 struct got_tree_object *tree;
8407 int nentries, i;
8409 err = got_object_open_as_tree(&tree, repo, id);
8410 if (err)
8411 return err;
8413 nentries = got_object_tree_get_nentries(tree);
8414 for (i = 0; i < nentries; i++) {
8415 struct got_tree_entry *te;
8416 char *id_str;
8417 if (sigint_received || sigpipe_received)
8418 break;
8419 te = got_object_tree_get_entry(tree, i);
8420 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
8421 if (err)
8422 break;
8423 fprintf(outfile, "%s %.7o %s\n", id_str,
8424 got_tree_entry_get_mode(te),
8425 got_tree_entry_get_name(te));
8426 free(id_str);
8429 got_object_tree_close(tree);
8430 return err;
8433 static const struct got_error *
8434 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8436 const struct got_error *err;
8437 struct got_commit_object *commit;
8438 const struct got_object_id_queue *parent_ids;
8439 struct got_object_qid *pid;
8440 char *id_str = NULL;
8441 const char *logmsg = NULL;
8443 err = got_object_open_as_commit(&commit, repo, id);
8444 if (err)
8445 return err;
8447 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
8448 if (err)
8449 goto done;
8451 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
8452 parent_ids = got_object_commit_get_parent_ids(commit);
8453 fprintf(outfile, "numparents %d\n",
8454 got_object_commit_get_nparents(commit));
8455 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
8456 char *pid_str;
8457 err = got_object_id_str(&pid_str, pid->id);
8458 if (err)
8459 goto done;
8460 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
8461 free(pid_str);
8463 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
8464 got_object_commit_get_author(commit),
8465 got_object_commit_get_author_time(commit));
8467 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
8468 got_object_commit_get_author(commit),
8469 got_object_commit_get_committer_time(commit));
8471 logmsg = got_object_commit_get_logmsg_raw(commit);
8472 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
8473 fprintf(outfile, "%s", logmsg);
8474 done:
8475 free(id_str);
8476 got_object_commit_close(commit);
8477 return err;
8480 static const struct got_error *
8481 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8483 const struct got_error *err;
8484 struct got_tag_object *tag;
8485 char *id_str = NULL;
8486 const char *tagmsg = NULL;
8488 err = got_object_open_as_tag(&tag, repo, id);
8489 if (err)
8490 return err;
8492 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
8493 if (err)
8494 goto done;
8496 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
8498 switch (got_object_tag_get_object_type(tag)) {
8499 case GOT_OBJ_TYPE_BLOB:
8500 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8501 GOT_OBJ_LABEL_BLOB);
8502 break;
8503 case GOT_OBJ_TYPE_TREE:
8504 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8505 GOT_OBJ_LABEL_TREE);
8506 break;
8507 case GOT_OBJ_TYPE_COMMIT:
8508 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8509 GOT_OBJ_LABEL_COMMIT);
8510 break;
8511 case GOT_OBJ_TYPE_TAG:
8512 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8513 GOT_OBJ_LABEL_TAG);
8514 break;
8515 default:
8516 break;
8519 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
8520 got_object_tag_get_name(tag));
8522 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
8523 got_object_tag_get_tagger(tag),
8524 got_object_tag_get_tagger_time(tag));
8526 tagmsg = got_object_tag_get_message(tag);
8527 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
8528 fprintf(outfile, "%s", tagmsg);
8529 done:
8530 free(id_str);
8531 got_object_tag_close(tag);
8532 return err;
8535 static const struct got_error *
8536 cmd_cat(int argc, char *argv[])
8538 const struct got_error *error;
8539 struct got_repository *repo = NULL;
8540 struct got_worktree *worktree = NULL;
8541 char *cwd = NULL, *repo_path = NULL, *label = NULL;
8542 const char *commit_id_str = NULL;
8543 struct got_object_id *id = NULL, *commit_id = NULL;
8544 int ch, obj_type, i, force_path = 0;
8546 #ifndef PROFILE
8547 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8548 NULL) == -1)
8549 err(1, "pledge");
8550 #endif
8552 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
8553 switch (ch) {
8554 case 'c':
8555 commit_id_str = optarg;
8556 break;
8557 case 'r':
8558 repo_path = realpath(optarg, NULL);
8559 if (repo_path == NULL)
8560 return got_error_from_errno2("realpath",
8561 optarg);
8562 got_path_strip_trailing_slashes(repo_path);
8563 break;
8564 case 'P':
8565 force_path = 1;
8566 break;
8567 default:
8568 usage_cat();
8569 /* NOTREACHED */
8573 argc -= optind;
8574 argv += optind;
8576 cwd = getcwd(NULL, 0);
8577 if (cwd == NULL) {
8578 error = got_error_from_errno("getcwd");
8579 goto done;
8581 error = got_worktree_open(&worktree, cwd);
8582 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8583 goto done;
8584 if (worktree) {
8585 if (repo_path == NULL) {
8586 repo_path = strdup(
8587 got_worktree_get_repo_path(worktree));
8588 if (repo_path == NULL) {
8589 error = got_error_from_errno("strdup");
8590 goto done;
8595 if (repo_path == NULL) {
8596 repo_path = getcwd(NULL, 0);
8597 if (repo_path == NULL)
8598 return got_error_from_errno("getcwd");
8601 error = got_repo_open(&repo, repo_path, NULL);
8602 free(repo_path);
8603 if (error != NULL)
8604 goto done;
8606 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
8607 if (error)
8608 goto done;
8610 if (commit_id_str == NULL)
8611 commit_id_str = GOT_REF_HEAD;
8612 error = got_repo_match_object_id(&commit_id, NULL,
8613 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
8614 if (error)
8615 goto done;
8617 for (i = 0; i < argc; i++) {
8618 if (force_path) {
8619 error = got_object_id_by_path(&id, repo, commit_id,
8620 argv[i]);
8621 if (error)
8622 break;
8623 } else {
8624 error = got_repo_match_object_id(&id, &label, argv[i],
8625 GOT_OBJ_TYPE_ANY, 0, repo);
8626 if (error) {
8627 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
8628 error->code != GOT_ERR_NOT_REF)
8629 break;
8630 error = got_object_id_by_path(&id, repo,
8631 commit_id, argv[i]);
8632 if (error)
8633 break;
8637 error = got_object_get_type(&obj_type, repo, id);
8638 if (error)
8639 break;
8641 switch (obj_type) {
8642 case GOT_OBJ_TYPE_BLOB:
8643 error = cat_blob(id, repo, stdout);
8644 break;
8645 case GOT_OBJ_TYPE_TREE:
8646 error = cat_tree(id, repo, stdout);
8647 break;
8648 case GOT_OBJ_TYPE_COMMIT:
8649 error = cat_commit(id, repo, stdout);
8650 break;
8651 case GOT_OBJ_TYPE_TAG:
8652 error = cat_tag(id, repo, stdout);
8653 break;
8654 default:
8655 error = got_error(GOT_ERR_OBJ_TYPE);
8656 break;
8658 if (error)
8659 break;
8660 free(label);
8661 label = NULL;
8662 free(id);
8663 id = NULL;
8665 done:
8666 free(label);
8667 free(id);
8668 free(commit_id);
8669 if (worktree)
8670 got_worktree_close(worktree);
8671 if (repo) {
8672 const struct got_error *repo_error;
8673 repo_error = got_repo_close(repo);
8674 if (error == NULL)
8675 error = repo_error;
8677 return error;