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 err = got_ref_resolve(&old_id, repo, ref);
1418 if (err)
1419 goto done;
1420 if (got_object_id_cmp(old_id, new_id) == 0)
1421 goto done;
1422 if (verbosity >= 0) {
1423 printf("Rejecting update of existing tag %s: %s\n",
1424 got_ref_get_name(ref), new_id_str);
1426 goto done;
1429 if (got_ref_is_symbolic(ref)) {
1430 if (verbosity >= 0) {
1431 printf("Replacing reference %s: %s\n",
1432 got_ref_get_name(ref),
1433 got_ref_get_symref_target(ref));
1435 err = got_ref_change_symref_to_ref(ref, new_id);
1436 if (err)
1437 goto done;
1438 err = got_ref_write(ref, repo);
1439 if (err)
1440 goto done;
1441 } else {
1442 err = got_ref_resolve(&old_id, repo, ref);
1443 if (err)
1444 goto done;
1445 if (got_object_id_cmp(old_id, new_id) == 0)
1446 goto done;
1448 err = got_ref_change_ref(ref, new_id);
1449 if (err)
1450 goto done;
1451 err = got_ref_write(ref, repo);
1452 if (err)
1453 goto done;
1456 if (verbosity >= 0)
1457 printf("Updated reference %s: %s\n", got_ref_get_name(ref),
1458 new_id_str);
1459 done:
1460 free(old_id);
1461 free(new_id_str);
1462 return err;
1465 __dead static void
1466 usage_fetch(void)
1468 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1469 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1470 "[remote-repository-name]\n",
1471 getprogname());
1472 exit(1);
1475 static const struct got_error *
1476 delete_missing_refs(struct got_pathlist_head *their_refs,
1477 int verbosity, struct got_repository *repo)
1479 const struct got_error *err = NULL;
1480 struct got_reflist_head my_refs;
1481 struct got_reflist_entry *re;
1482 struct got_pathlist_entry *pe;
1483 struct got_object_id *id;
1484 char *id_str;
1486 SIMPLEQ_INIT(&my_refs);
1488 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1489 if (err)
1490 return err;
1492 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1493 const char *refname = got_ref_get_name(re->ref);
1495 if (strncmp(refname, "refs/heads/", 11) != 0 &&
1496 strncmp(refname, "refs/tags/", 10) != 0)
1497 continue;
1499 TAILQ_FOREACH(pe, their_refs, entry) {
1500 if (strcmp(refname, pe->path) == 0)
1501 break;
1503 if (pe != NULL)
1504 continue;
1506 err = got_ref_resolve(&id, repo, re->ref);
1507 if (err)
1508 break;
1509 err = got_object_id_str(&id_str, id);
1510 free(id);
1511 if (err)
1512 break;
1514 free(id_str);
1515 err = got_ref_delete(re->ref, repo);
1516 if (err)
1517 break;
1518 if (verbosity >= 0) {
1519 printf("Deleted reference %s: %s\n",
1520 got_ref_get_name(re->ref), id_str);
1524 return err;
1527 static const struct got_error *
1528 update_wanted_ref(const char *refname, struct got_object_id *id,
1529 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1531 const struct got_error *err, *unlock_err;
1532 char *remote_refname;
1533 struct got_reference *ref;
1535 if (strncmp("refs/", refname, 5) == 0)
1536 refname += 5;
1538 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1539 remote_repo_name, refname) == -1)
1540 return got_error_from_errno("asprintf");
1542 err = got_ref_open(&ref, repo, remote_refname, 1);
1543 if (err) {
1544 if (err->code != GOT_ERR_NOT_REF)
1545 goto done;
1546 err = create_ref(remote_refname, id, verbosity, repo);
1547 } else {
1548 err = update_ref(ref, id, 0, verbosity, repo);
1549 unlock_err = got_ref_unlock(ref);
1550 if (unlock_err && err == NULL)
1551 err = unlock_err;
1552 got_ref_close(ref);
1554 done:
1555 free(remote_refname);
1556 return err;
1559 static const struct got_error *
1560 cmd_fetch(int argc, char *argv[])
1562 const struct got_error *error = NULL, *unlock_err;
1563 char *cwd = NULL, *repo_path = NULL;
1564 const char *remote_name;
1565 char *proto = NULL, *host = NULL, *port = NULL;
1566 char *repo_name = NULL, *server_path = NULL;
1567 struct got_remote_repo *remotes, *remote = NULL;
1568 int nremotes;
1569 char *id_str = NULL;
1570 struct got_repository *repo = NULL;
1571 struct got_worktree *worktree = NULL;
1572 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1573 struct got_pathlist_entry *pe;
1574 struct got_object_id *pack_hash = NULL;
1575 int i, ch, fetchfd = -1, fetchstatus;
1576 pid_t fetchpid = -1;
1577 struct got_fetch_progress_arg fpa;
1578 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
1579 int delete_refs = 0, replace_tags = 0;
1581 TAILQ_INIT(&refs);
1582 TAILQ_INIT(&symrefs);
1583 TAILQ_INIT(&wanted_branches);
1584 TAILQ_INIT(&wanted_refs);
1586 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
1587 switch (ch) {
1588 case 'a':
1589 fetch_all_branches = 1;
1590 break;
1591 case 'b':
1592 error = got_pathlist_append(&wanted_branches,
1593 optarg, NULL);
1594 if (error)
1595 return error;
1596 break;
1597 case 'd':
1598 delete_refs = 1;
1599 break;
1600 case 'l':
1601 list_refs_only = 1;
1602 break;
1603 case 'r':
1604 repo_path = realpath(optarg, NULL);
1605 if (repo_path == NULL)
1606 return got_error_from_errno2("realpath",
1607 optarg);
1608 got_path_strip_trailing_slashes(repo_path);
1609 break;
1610 case 't':
1611 replace_tags = 1;
1612 break;
1613 case 'v':
1614 if (verbosity < 0)
1615 verbosity = 0;
1616 else if (verbosity < 3)
1617 verbosity++;
1618 break;
1619 case 'q':
1620 verbosity = -1;
1621 break;
1622 case 'R':
1623 error = got_pathlist_append(&wanted_refs,
1624 optarg, NULL);
1625 if (error)
1626 return error;
1627 break;
1628 default:
1629 usage_fetch();
1630 break;
1633 argc -= optind;
1634 argv += optind;
1636 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1637 errx(1, "-a and -b options are mutually exclusive");
1638 if (list_refs_only) {
1639 if (!TAILQ_EMPTY(&wanted_branches))
1640 errx(1, "-l and -b options are mutually exclusive");
1641 if (fetch_all_branches)
1642 errx(1, "-l and -a options are mutually exclusive");
1643 if (delete_refs)
1644 errx(1, "-l and -d options are mutually exclusive");
1645 if (verbosity == -1)
1646 errx(1, "-l and -q options are mutually exclusive");
1649 if (argc == 0)
1650 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
1651 else if (argc == 1)
1652 remote_name = argv[0];
1653 else
1654 usage_fetch();
1656 cwd = getcwd(NULL, 0);
1657 if (cwd == NULL) {
1658 error = got_error_from_errno("getcwd");
1659 goto done;
1662 if (repo_path == NULL) {
1663 error = got_worktree_open(&worktree, cwd);
1664 if (error && error->code != GOT_ERR_NOT_WORKTREE)
1665 goto done;
1666 else
1667 error = NULL;
1668 if (worktree) {
1669 repo_path =
1670 strdup(got_worktree_get_repo_path(worktree));
1671 if (repo_path == NULL)
1672 error = got_error_from_errno("strdup");
1673 if (error)
1674 goto done;
1675 } else {
1676 repo_path = strdup(cwd);
1677 if (repo_path == NULL) {
1678 error = got_error_from_errno("strdup");
1679 goto done;
1684 error = got_repo_open(&repo, repo_path, NULL);
1685 if (error)
1686 goto done;
1688 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
1689 for (i = 0; i < nremotes; i++) {
1690 remote = &remotes[i];
1691 if (strcmp(remote->name, remote_name) == 0)
1692 break;
1694 if (i == nremotes) {
1695 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
1696 goto done;
1699 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1700 &repo_name, remote->url);
1701 if (error)
1702 goto done;
1704 if (strcmp(proto, "git") == 0) {
1705 #ifndef PROFILE
1706 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1707 "sendfd dns inet unveil", NULL) == -1)
1708 err(1, "pledge");
1709 #endif
1710 } else if (strcmp(proto, "git+ssh") == 0 ||
1711 strcmp(proto, "ssh") == 0) {
1712 #ifndef PROFILE
1713 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1714 "sendfd unveil", NULL) == -1)
1715 err(1, "pledge");
1716 #endif
1717 } else if (strcmp(proto, "http") == 0 ||
1718 strcmp(proto, "git+http") == 0) {
1719 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1720 goto done;
1721 } else {
1722 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1723 goto done;
1726 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1727 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1728 error = got_error_from_errno2("unveil",
1729 GOT_FETCH_PATH_SSH);
1730 goto done;
1733 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
1734 if (error)
1735 goto done;
1737 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1738 server_path, verbosity);
1739 if (error)
1740 goto done;
1742 if (verbosity >= 0)
1743 printf("Connected to \"%s\" %s%s%s\n", remote->name, host,
1744 port ? ":" : "", port ? port : "");
1746 fpa.last_scaled_size[0] = '\0';
1747 fpa.last_p_indexed = -1;
1748 fpa.last_p_resolved = -1;
1749 fpa.verbosity = verbosity;
1750 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
1751 remote->mirror_references, fetch_all_branches, &wanted_branches,
1752 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
1753 fetch_progress, &fpa);
1754 if (error)
1755 goto done;
1757 if (list_refs_only) {
1758 error = list_remote_refs(&symrefs, &refs);
1759 goto done;
1762 if (pack_hash == NULL) {
1763 if (verbosity >= 0)
1764 printf("Already up-to-date\n");
1765 if (delete_refs)
1766 error = delete_missing_refs(&refs, verbosity, repo);
1767 goto done;
1770 if (verbosity >= 0) {
1771 error = got_object_id_str(&id_str, pack_hash);
1772 if (error)
1773 goto done;
1774 printf("\nFetched %s.pack\n", id_str);
1775 free(id_str);
1776 id_str = NULL;
1779 /* Update references provided with the pack file. */
1780 TAILQ_FOREACH(pe, &refs, entry) {
1781 const char *refname = pe->path;
1782 struct got_object_id *id = pe->data;
1783 struct got_reference *ref;
1784 char *remote_refname;
1786 if (is_wanted_ref(&wanted_refs, refname) &&
1787 !remote->mirror_references) {
1788 error = update_wanted_ref(refname, id,
1789 remote->name, verbosity, repo);
1790 if (error)
1791 goto done;
1792 continue;
1795 if (remote->mirror_references ||
1796 strncmp("refs/tags/", refname, 10) == 0) {
1797 error = got_ref_open(&ref, repo, refname, 1);
1798 if (error) {
1799 if (error->code != GOT_ERR_NOT_REF)
1800 goto done;
1801 error = create_ref(refname, id, verbosity,
1802 repo);
1803 if (error)
1804 goto done;
1805 } else {
1806 error = update_ref(ref, id, replace_tags,
1807 verbosity, repo);
1808 unlock_err = got_ref_unlock(ref);
1809 if (unlock_err && error == NULL)
1810 error = unlock_err;
1811 got_ref_close(ref);
1812 if (error)
1813 goto done;
1815 } else if (strncmp("refs/heads/", refname, 11) == 0) {
1816 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1817 remote_name, refname + 11) == -1) {
1818 error = got_error_from_errno("asprintf");
1819 goto done;
1822 error = got_ref_open(&ref, repo, remote_refname, 1);
1823 if (error) {
1824 if (error->code != GOT_ERR_NOT_REF)
1825 goto done;
1826 error = create_ref(remote_refname, id,
1827 verbosity, repo);
1828 if (error)
1829 goto done;
1830 } else {
1831 error = update_ref(ref, id, replace_tags,
1832 verbosity, repo);
1833 unlock_err = got_ref_unlock(ref);
1834 if (unlock_err && error == NULL)
1835 error = unlock_err;
1836 got_ref_close(ref);
1837 if (error)
1838 goto done;
1841 /* Also create a local branch if none exists yet. */
1842 error = got_ref_open(&ref, repo, refname, 1);
1843 if (error) {
1844 if (error->code != GOT_ERR_NOT_REF)
1845 goto done;
1846 error = create_ref(refname, id, verbosity,
1847 repo);
1848 if (error)
1849 goto done;
1850 } else {
1851 unlock_err = got_ref_unlock(ref);
1852 if (unlock_err && error == NULL)
1853 error = unlock_err;
1854 got_ref_close(ref);
1858 if (delete_refs)
1859 error = delete_missing_refs(&refs, verbosity, repo);
1860 done:
1861 if (fetchpid > 0) {
1862 if (kill(fetchpid, SIGTERM) == -1)
1863 error = got_error_from_errno("kill");
1864 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1865 error = got_error_from_errno("waitpid");
1867 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1868 error = got_error_from_errno("close");
1869 if (repo)
1870 got_repo_close(repo);
1871 if (worktree)
1872 got_worktree_close(worktree);
1873 TAILQ_FOREACH(pe, &refs, entry) {
1874 free((void *)pe->path);
1875 free(pe->data);
1877 got_pathlist_free(&refs);
1878 TAILQ_FOREACH(pe, &symrefs, entry) {
1879 free((void *)pe->path);
1880 free(pe->data);
1882 got_pathlist_free(&symrefs);
1883 got_pathlist_free(&wanted_branches);
1884 got_pathlist_free(&wanted_refs);
1885 free(id_str);
1886 free(cwd);
1887 free(repo_path);
1888 free(pack_hash);
1889 free(proto);
1890 free(host);
1891 free(port);
1892 free(server_path);
1893 free(repo_name);
1894 return error;
1898 __dead static void
1899 usage_checkout(void)
1901 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
1902 "[-p prefix] repository-path [worktree-path]\n", getprogname());
1903 exit(1);
1906 static void
1907 show_worktree_base_ref_warning(void)
1909 fprintf(stderr, "%s: warning: could not create a reference "
1910 "to the work tree's base commit; the commit could be "
1911 "garbage-collected by Git; making the repository "
1912 "writable and running 'got update' will prevent this\n",
1913 getprogname());
1916 struct got_checkout_progress_arg {
1917 const char *worktree_path;
1918 int had_base_commit_ref_error;
1921 static const struct got_error *
1922 checkout_progress(void *arg, unsigned char status, const char *path)
1924 struct got_checkout_progress_arg *a = arg;
1926 /* Base commit bump happens silently. */
1927 if (status == GOT_STATUS_BUMP_BASE)
1928 return NULL;
1930 if (status == GOT_STATUS_BASE_REF_ERR) {
1931 a->had_base_commit_ref_error = 1;
1932 return NULL;
1935 while (path[0] == '/')
1936 path++;
1938 printf("%c %s/%s\n", status, a->worktree_path, path);
1939 return NULL;
1942 static const struct got_error *
1943 check_cancelled(void *arg)
1945 if (sigint_received || sigpipe_received)
1946 return got_error(GOT_ERR_CANCELLED);
1947 return NULL;
1950 static const struct got_error *
1951 check_linear_ancestry(struct got_object_id *commit_id,
1952 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
1953 struct got_repository *repo)
1955 const struct got_error *err = NULL;
1956 struct got_object_id *yca_id;
1958 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
1959 commit_id, base_commit_id, repo, check_cancelled, NULL);
1960 if (err)
1961 return err;
1963 if (yca_id == NULL)
1964 return got_error(GOT_ERR_ANCESTRY);
1967 * Require a straight line of history between the target commit
1968 * and the work tree's base commit.
1970 * Non-linear situations such as this require a rebase:
1972 * (commit) D F (base_commit)
1973 * \ /
1974 * C E
1975 * \ /
1976 * B (yca)
1977 * |
1978 * A
1980 * 'got update' only handles linear cases:
1981 * Update forwards in time: A (base/yca) - B - C - D (commit)
1982 * Update backwards in time: D (base) - C - B - A (commit/yca)
1984 if (allow_forwards_in_time_only) {
1985 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
1986 return got_error(GOT_ERR_ANCESTRY);
1987 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
1988 got_object_id_cmp(base_commit_id, yca_id) != 0)
1989 return got_error(GOT_ERR_ANCESTRY);
1991 free(yca_id);
1992 return NULL;
1995 static const struct got_error *
1996 check_same_branch(struct got_object_id *commit_id,
1997 struct got_reference *head_ref, struct got_object_id *yca_id,
1998 struct got_repository *repo)
2000 const struct got_error *err = NULL;
2001 struct got_commit_graph *graph = NULL;
2002 struct got_object_id *head_commit_id = NULL;
2003 int is_same_branch = 0;
2005 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2006 if (err)
2007 goto done;
2009 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2010 is_same_branch = 1;
2011 goto done;
2013 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2014 is_same_branch = 1;
2015 goto done;
2018 err = got_commit_graph_open(&graph, "/", 1);
2019 if (err)
2020 goto done;
2022 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2023 check_cancelled, NULL);
2024 if (err)
2025 goto done;
2027 for (;;) {
2028 struct got_object_id *id;
2029 err = got_commit_graph_iter_next(&id, graph, repo,
2030 check_cancelled, NULL);
2031 if (err) {
2032 if (err->code == GOT_ERR_ITER_COMPLETED)
2033 err = NULL;
2034 break;
2037 if (id) {
2038 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2039 break;
2040 if (got_object_id_cmp(id, commit_id) == 0) {
2041 is_same_branch = 1;
2042 break;
2046 done:
2047 if (graph)
2048 got_commit_graph_close(graph);
2049 free(head_commit_id);
2050 if (!err && !is_same_branch)
2051 err = got_error(GOT_ERR_ANCESTRY);
2052 return err;
2055 static const struct got_error *
2056 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2058 static char msg[512];
2059 const char *branch_name;
2061 if (got_ref_is_symbolic(ref))
2062 branch_name = got_ref_get_symref_target(ref);
2063 else
2064 branch_name = got_ref_get_name(ref);
2066 if (strncmp("refs/heads/", branch_name, 11) == 0)
2067 branch_name += 11;
2069 snprintf(msg, sizeof(msg),
2070 "target commit is not contained in branch '%s'; "
2071 "the branch to use must be specified with -b; "
2072 "if necessary a new branch can be created for "
2073 "this commit with 'got branch -c %s BRANCH_NAME'",
2074 branch_name, commit_id_str);
2076 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2079 static const struct got_error *
2080 cmd_checkout(int argc, char *argv[])
2082 const struct got_error *error = NULL;
2083 struct got_repository *repo = NULL;
2084 struct got_reference *head_ref = NULL;
2085 struct got_worktree *worktree = NULL;
2086 char *repo_path = NULL;
2087 char *worktree_path = NULL;
2088 const char *path_prefix = "";
2089 const char *branch_name = GOT_REF_HEAD;
2090 char *commit_id_str = NULL;
2091 int ch, same_path_prefix, allow_nonempty = 0;
2092 struct got_pathlist_head paths;
2093 struct got_checkout_progress_arg cpa;
2095 TAILQ_INIT(&paths);
2097 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2098 switch (ch) {
2099 case 'b':
2100 branch_name = optarg;
2101 break;
2102 case 'c':
2103 commit_id_str = strdup(optarg);
2104 if (commit_id_str == NULL)
2105 return got_error_from_errno("strdup");
2106 break;
2107 case 'E':
2108 allow_nonempty = 1;
2109 break;
2110 case 'p':
2111 path_prefix = optarg;
2112 break;
2113 default:
2114 usage_checkout();
2115 /* NOTREACHED */
2119 argc -= optind;
2120 argv += optind;
2122 #ifndef PROFILE
2123 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2124 "unveil", NULL) == -1)
2125 err(1, "pledge");
2126 #endif
2127 if (argc == 1) {
2128 char *cwd, *base, *dotgit;
2129 repo_path = realpath(argv[0], NULL);
2130 if (repo_path == NULL)
2131 return got_error_from_errno2("realpath", argv[0]);
2132 cwd = getcwd(NULL, 0);
2133 if (cwd == NULL) {
2134 error = got_error_from_errno("getcwd");
2135 goto done;
2137 if (path_prefix[0]) {
2138 base = basename(path_prefix);
2139 if (base == NULL) {
2140 error = got_error_from_errno2("basename",
2141 path_prefix);
2142 goto done;
2144 } else {
2145 base = basename(repo_path);
2146 if (base == NULL) {
2147 error = got_error_from_errno2("basename",
2148 repo_path);
2149 goto done;
2152 dotgit = strstr(base, ".git");
2153 if (dotgit)
2154 *dotgit = '\0';
2155 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2156 error = got_error_from_errno("asprintf");
2157 free(cwd);
2158 goto done;
2160 free(cwd);
2161 } else if (argc == 2) {
2162 repo_path = realpath(argv[0], NULL);
2163 if (repo_path == NULL) {
2164 error = got_error_from_errno2("realpath", argv[0]);
2165 goto done;
2167 worktree_path = realpath(argv[1], NULL);
2168 if (worktree_path == NULL) {
2169 if (errno != ENOENT) {
2170 error = got_error_from_errno2("realpath",
2171 argv[1]);
2172 goto done;
2174 worktree_path = strdup(argv[1]);
2175 if (worktree_path == NULL) {
2176 error = got_error_from_errno("strdup");
2177 goto done;
2180 } else
2181 usage_checkout();
2183 got_path_strip_trailing_slashes(repo_path);
2184 got_path_strip_trailing_slashes(worktree_path);
2186 error = got_repo_open(&repo, repo_path, NULL);
2187 if (error != NULL)
2188 goto done;
2190 /* Pre-create work tree path for unveil(2) */
2191 error = got_path_mkdir(worktree_path);
2192 if (error) {
2193 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2194 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2195 goto done;
2196 if (!allow_nonempty &&
2197 !got_path_dir_is_empty(worktree_path)) {
2198 error = got_error_path(worktree_path,
2199 GOT_ERR_DIR_NOT_EMPTY);
2200 goto done;
2204 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2205 if (error)
2206 goto done;
2208 error = got_ref_open(&head_ref, repo, branch_name, 0);
2209 if (error != NULL)
2210 goto done;
2212 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2213 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2214 goto done;
2216 error = got_worktree_open(&worktree, worktree_path);
2217 if (error != NULL)
2218 goto done;
2220 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2221 path_prefix);
2222 if (error != NULL)
2223 goto done;
2224 if (!same_path_prefix) {
2225 error = got_error(GOT_ERR_PATH_PREFIX);
2226 goto done;
2229 if (commit_id_str) {
2230 struct got_object_id *commit_id;
2231 error = got_repo_match_object_id(&commit_id, NULL,
2232 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2233 if (error)
2234 goto done;
2235 error = check_linear_ancestry(commit_id,
2236 got_worktree_get_base_commit_id(worktree), 0, repo);
2237 if (error != NULL) {
2238 free(commit_id);
2239 if (error->code == GOT_ERR_ANCESTRY) {
2240 error = checkout_ancestry_error(
2241 head_ref, commit_id_str);
2243 goto done;
2245 error = check_same_branch(commit_id, head_ref, NULL, repo);
2246 if (error) {
2247 if (error->code == GOT_ERR_ANCESTRY) {
2248 error = checkout_ancestry_error(
2249 head_ref, commit_id_str);
2251 goto done;
2253 error = got_worktree_set_base_commit_id(worktree, repo,
2254 commit_id);
2255 free(commit_id);
2256 if (error)
2257 goto done;
2260 error = got_pathlist_append(&paths, "", NULL);
2261 if (error)
2262 goto done;
2263 cpa.worktree_path = worktree_path;
2264 cpa.had_base_commit_ref_error = 0;
2265 error = got_worktree_checkout_files(worktree, &paths, repo,
2266 checkout_progress, &cpa, check_cancelled, NULL);
2267 if (error != NULL)
2268 goto done;
2270 printf("Now shut up and hack\n");
2271 if (cpa.had_base_commit_ref_error)
2272 show_worktree_base_ref_warning();
2273 done:
2274 got_pathlist_free(&paths);
2275 free(commit_id_str);
2276 free(repo_path);
2277 free(worktree_path);
2278 return error;
2281 __dead static void
2282 usage_update(void)
2284 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2285 getprogname());
2286 exit(1);
2289 static const struct got_error *
2290 update_progress(void *arg, unsigned char status, const char *path)
2292 int *did_something = arg;
2294 if (status == GOT_STATUS_EXISTS ||
2295 status == GOT_STATUS_BASE_REF_ERR)
2296 return NULL;
2298 *did_something = 1;
2300 /* Base commit bump happens silently. */
2301 if (status == GOT_STATUS_BUMP_BASE)
2302 return NULL;
2304 while (path[0] == '/')
2305 path++;
2306 printf("%c %s\n", status, path);
2307 return NULL;
2310 static const struct got_error *
2311 switch_head_ref(struct got_reference *head_ref,
2312 struct got_object_id *commit_id, struct got_worktree *worktree,
2313 struct got_repository *repo)
2315 const struct got_error *err = NULL;
2316 char *base_id_str;
2317 int ref_has_moved = 0;
2319 /* Trivial case: switching between two different references. */
2320 if (strcmp(got_ref_get_name(head_ref),
2321 got_worktree_get_head_ref_name(worktree)) != 0) {
2322 printf("Switching work tree from %s to %s\n",
2323 got_worktree_get_head_ref_name(worktree),
2324 got_ref_get_name(head_ref));
2325 return got_worktree_set_head_ref(worktree, head_ref);
2328 err = check_linear_ancestry(commit_id,
2329 got_worktree_get_base_commit_id(worktree), 0, repo);
2330 if (err) {
2331 if (err->code != GOT_ERR_ANCESTRY)
2332 return err;
2333 ref_has_moved = 1;
2335 if (!ref_has_moved)
2336 return NULL;
2338 /* Switching to a rebased branch with the same reference name. */
2339 err = got_object_id_str(&base_id_str,
2340 got_worktree_get_base_commit_id(worktree));
2341 if (err)
2342 return err;
2343 printf("Reference %s now points at a different branch\n",
2344 got_worktree_get_head_ref_name(worktree));
2345 printf("Switching work tree from %s to %s\n", base_id_str,
2346 got_worktree_get_head_ref_name(worktree));
2347 return NULL;
2350 static const struct got_error *
2351 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2353 const struct got_error *err;
2354 int in_progress;
2356 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2357 if (err)
2358 return err;
2359 if (in_progress)
2360 return got_error(GOT_ERR_REBASING);
2362 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2363 if (err)
2364 return err;
2365 if (in_progress)
2366 return got_error(GOT_ERR_HISTEDIT_BUSY);
2368 return NULL;
2371 static const struct got_error *
2372 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2373 char *argv[], struct got_worktree *worktree)
2375 const struct got_error *err = NULL;
2376 char *path;
2377 int i;
2379 if (argc == 0) {
2380 path = strdup("");
2381 if (path == NULL)
2382 return got_error_from_errno("strdup");
2383 return got_pathlist_append(paths, path, NULL);
2386 for (i = 0; i < argc; i++) {
2387 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2388 if (err)
2389 break;
2390 err = got_pathlist_append(paths, path, NULL);
2391 if (err) {
2392 free(path);
2393 break;
2397 return err;
2400 static const struct got_error *
2401 cmd_update(int argc, char *argv[])
2403 const struct got_error *error = NULL;
2404 struct got_repository *repo = NULL;
2405 struct got_worktree *worktree = NULL;
2406 char *worktree_path = NULL;
2407 struct got_object_id *commit_id = NULL;
2408 char *commit_id_str = NULL;
2409 const char *branch_name = NULL;
2410 struct got_reference *head_ref = NULL;
2411 struct got_pathlist_head paths;
2412 struct got_pathlist_entry *pe;
2413 int ch, did_something = 0;
2415 TAILQ_INIT(&paths);
2417 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2418 switch (ch) {
2419 case 'b':
2420 branch_name = optarg;
2421 break;
2422 case 'c':
2423 commit_id_str = strdup(optarg);
2424 if (commit_id_str == NULL)
2425 return got_error_from_errno("strdup");
2426 break;
2427 default:
2428 usage_update();
2429 /* NOTREACHED */
2433 argc -= optind;
2434 argv += optind;
2436 #ifndef PROFILE
2437 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2438 "unveil", NULL) == -1)
2439 err(1, "pledge");
2440 #endif
2441 worktree_path = getcwd(NULL, 0);
2442 if (worktree_path == NULL) {
2443 error = got_error_from_errno("getcwd");
2444 goto done;
2446 error = got_worktree_open(&worktree, worktree_path);
2447 if (error)
2448 goto done;
2450 error = check_rebase_or_histedit_in_progress(worktree);
2451 if (error)
2452 goto done;
2454 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
2455 NULL);
2456 if (error != NULL)
2457 goto done;
2459 error = apply_unveil(got_repo_get_path(repo), 0,
2460 got_worktree_get_root_path(worktree));
2461 if (error)
2462 goto done;
2464 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2465 if (error)
2466 goto done;
2468 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
2469 got_worktree_get_head_ref_name(worktree), 0);
2470 if (error != NULL)
2471 goto done;
2472 if (commit_id_str == NULL) {
2473 error = got_ref_resolve(&commit_id, repo, head_ref);
2474 if (error != NULL)
2475 goto done;
2476 error = got_object_id_str(&commit_id_str, commit_id);
2477 if (error != NULL)
2478 goto done;
2479 } else {
2480 error = got_repo_match_object_id(&commit_id, NULL,
2481 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2482 free(commit_id_str);
2483 commit_id_str = NULL;
2484 if (error)
2485 goto done;
2486 error = got_object_id_str(&commit_id_str, commit_id);
2487 if (error)
2488 goto done;
2491 if (branch_name) {
2492 struct got_object_id *head_commit_id;
2493 TAILQ_FOREACH(pe, &paths, entry) {
2494 if (pe->path_len == 0)
2495 continue;
2496 error = got_error_msg(GOT_ERR_BAD_PATH,
2497 "switching between branches requires that "
2498 "the entire work tree gets updated");
2499 goto done;
2501 error = got_ref_resolve(&head_commit_id, repo, head_ref);
2502 if (error)
2503 goto done;
2504 error = check_linear_ancestry(commit_id, head_commit_id, 0,
2505 repo);
2506 free(head_commit_id);
2507 if (error != NULL)
2508 goto done;
2509 error = check_same_branch(commit_id, head_ref, NULL, repo);
2510 if (error)
2511 goto done;
2512 error = switch_head_ref(head_ref, commit_id, worktree, repo);
2513 if (error)
2514 goto done;
2515 } else {
2516 error = check_linear_ancestry(commit_id,
2517 got_worktree_get_base_commit_id(worktree), 0, repo);
2518 if (error != NULL) {
2519 if (error->code == GOT_ERR_ANCESTRY)
2520 error = got_error(GOT_ERR_BRANCH_MOVED);
2521 goto done;
2523 error = check_same_branch(commit_id, head_ref, NULL, repo);
2524 if (error)
2525 goto done;
2528 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
2529 commit_id) != 0) {
2530 error = got_worktree_set_base_commit_id(worktree, repo,
2531 commit_id);
2532 if (error)
2533 goto done;
2536 error = got_worktree_checkout_files(worktree, &paths, repo,
2537 update_progress, &did_something, check_cancelled, NULL);
2538 if (error != NULL)
2539 goto done;
2541 if (did_something)
2542 printf("Updated to commit %s\n", commit_id_str);
2543 else
2544 printf("Already up-to-date\n");
2545 done:
2546 free(worktree_path);
2547 TAILQ_FOREACH(pe, &paths, entry)
2548 free((char *)pe->path);
2549 got_pathlist_free(&paths);
2550 free(commit_id);
2551 free(commit_id_str);
2552 return error;
2555 static const struct got_error *
2556 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
2557 const char *path, int diff_context, int ignore_whitespace,
2558 struct got_repository *repo)
2560 const struct got_error *err = NULL;
2561 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
2563 if (blob_id1) {
2564 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
2565 if (err)
2566 goto done;
2569 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
2570 if (err)
2571 goto done;
2573 while (path[0] == '/')
2574 path++;
2575 err = got_diff_blob(blob1, blob2, path, path, diff_context,
2576 ignore_whitespace, stdout);
2577 done:
2578 if (blob1)
2579 got_object_blob_close(blob1);
2580 got_object_blob_close(blob2);
2581 return err;
2584 static const struct got_error *
2585 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
2586 const char *path, int diff_context, int ignore_whitespace,
2587 struct got_repository *repo)
2589 const struct got_error *err = NULL;
2590 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
2591 struct got_diff_blob_output_unidiff_arg arg;
2593 if (tree_id1) {
2594 err = got_object_open_as_tree(&tree1, repo, tree_id1);
2595 if (err)
2596 goto done;
2599 err = got_object_open_as_tree(&tree2, repo, tree_id2);
2600 if (err)
2601 goto done;
2603 arg.diff_context = diff_context;
2604 arg.ignore_whitespace = ignore_whitespace;
2605 arg.outfile = stdout;
2606 while (path[0] == '/')
2607 path++;
2608 err = got_diff_tree(tree1, tree2, path, path, repo,
2609 got_diff_blob_output_unidiff, &arg, 1);
2610 done:
2611 if (tree1)
2612 got_object_tree_close(tree1);
2613 if (tree2)
2614 got_object_tree_close(tree2);
2615 return err;
2618 static const struct got_error *
2619 print_patch(struct got_commit_object *commit, struct got_object_id *id,
2620 const char *path, int diff_context, struct got_repository *repo)
2622 const struct got_error *err = NULL;
2623 struct got_commit_object *pcommit = NULL;
2624 char *id_str1 = NULL, *id_str2 = NULL;
2625 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
2626 struct got_object_qid *qid;
2628 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
2629 if (qid != NULL) {
2630 err = got_object_open_as_commit(&pcommit, repo,
2631 qid->id);
2632 if (err)
2633 return err;
2636 if (path && path[0] != '\0') {
2637 int obj_type;
2638 err = got_object_id_by_path(&obj_id2, repo, id, path);
2639 if (err)
2640 goto done;
2641 err = got_object_id_str(&id_str2, obj_id2);
2642 if (err) {
2643 free(obj_id2);
2644 goto done;
2646 if (pcommit) {
2647 err = got_object_id_by_path(&obj_id1, repo,
2648 qid->id, path);
2649 if (err) {
2650 free(obj_id2);
2651 goto done;
2653 err = got_object_id_str(&id_str1, obj_id1);
2654 if (err) {
2655 free(obj_id2);
2656 goto done;
2659 err = got_object_get_type(&obj_type, repo, obj_id2);
2660 if (err) {
2661 free(obj_id2);
2662 goto done;
2664 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2665 switch (obj_type) {
2666 case GOT_OBJ_TYPE_BLOB:
2667 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
2668 0, repo);
2669 break;
2670 case GOT_OBJ_TYPE_TREE:
2671 err = diff_trees(obj_id1, obj_id2, path, diff_context,
2672 0, repo);
2673 break;
2674 default:
2675 err = got_error(GOT_ERR_OBJ_TYPE);
2676 break;
2678 free(obj_id1);
2679 free(obj_id2);
2680 } else {
2681 obj_id2 = got_object_commit_get_tree_id(commit);
2682 err = got_object_id_str(&id_str2, obj_id2);
2683 if (err)
2684 goto done;
2685 obj_id1 = got_object_commit_get_tree_id(pcommit);
2686 err = got_object_id_str(&id_str1, obj_id1);
2687 if (err)
2688 goto done;
2689 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2690 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
2692 done:
2693 free(id_str1);
2694 free(id_str2);
2695 if (pcommit)
2696 got_object_commit_close(pcommit);
2697 return err;
2700 static char *
2701 get_datestr(time_t *time, char *datebuf)
2703 struct tm mytm, *tm;
2704 char *p, *s;
2706 tm = gmtime_r(time, &mytm);
2707 if (tm == NULL)
2708 return NULL;
2709 s = asctime_r(tm, datebuf);
2710 if (s == NULL)
2711 return NULL;
2712 p = strchr(s, '\n');
2713 if (p)
2714 *p = '\0';
2715 return s;
2718 static const struct got_error *
2719 match_logmsg(int *have_match, struct got_object_id *id,
2720 struct got_commit_object *commit, regex_t *regex)
2722 const struct got_error *err = NULL;
2723 regmatch_t regmatch;
2724 char *id_str = NULL, *logmsg = NULL;
2726 *have_match = 0;
2728 err = got_object_id_str(&id_str, id);
2729 if (err)
2730 return err;
2732 err = got_object_commit_get_logmsg(&logmsg, commit);
2733 if (err)
2734 goto done;
2736 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2737 *have_match = 1;
2738 done:
2739 free(id_str);
2740 free(logmsg);
2741 return err;
2744 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
2746 static const struct got_error *
2747 print_commit(struct got_commit_object *commit, struct got_object_id *id,
2748 struct got_repository *repo, const char *path, int show_patch,
2749 int diff_context, struct got_reflist_head *refs)
2751 const struct got_error *err = NULL;
2752 char *id_str, *datestr, *logmsg0, *logmsg, *line;
2753 char datebuf[26];
2754 time_t committer_time;
2755 const char *author, *committer;
2756 char *refs_str = NULL;
2757 struct got_reflist_entry *re;
2759 SIMPLEQ_FOREACH(re, refs, entry) {
2760 char *s;
2761 const char *name;
2762 struct got_tag_object *tag = NULL;
2763 int cmp;
2765 name = got_ref_get_name(re->ref);
2766 if (strcmp(name, GOT_REF_HEAD) == 0)
2767 continue;
2768 if (strncmp(name, "refs/", 5) == 0)
2769 name += 5;
2770 if (strncmp(name, "got/", 4) == 0)
2771 continue;
2772 if (strncmp(name, "heads/", 6) == 0)
2773 name += 6;
2774 if (strncmp(name, "remotes/", 8) == 0)
2775 name += 8;
2776 if (strncmp(name, "tags/", 5) == 0) {
2777 err = got_object_open_as_tag(&tag, repo, re->id);
2778 if (err) {
2779 if (err->code != GOT_ERR_OBJ_TYPE)
2780 return err;
2781 /* Ref points at something other than a tag. */
2782 err = NULL;
2783 tag = NULL;
2786 cmp = got_object_id_cmp(tag ?
2787 got_object_tag_get_object_id(tag) : re->id, id);
2788 if (tag)
2789 got_object_tag_close(tag);
2790 if (cmp != 0)
2791 continue;
2792 s = refs_str;
2793 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
2794 name) == -1) {
2795 err = got_error_from_errno("asprintf");
2796 free(s);
2797 return err;
2799 free(s);
2801 err = got_object_id_str(&id_str, id);
2802 if (err)
2803 return err;
2805 printf(GOT_COMMIT_SEP_STR);
2806 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
2807 refs_str ? refs_str : "", refs_str ? ")" : "");
2808 free(id_str);
2809 id_str = NULL;
2810 free(refs_str);
2811 refs_str = NULL;
2812 printf("from: %s\n", got_object_commit_get_author(commit));
2813 committer_time = got_object_commit_get_committer_time(commit);
2814 datestr = get_datestr(&committer_time, datebuf);
2815 if (datestr)
2816 printf("date: %s UTC\n", datestr);
2817 author = got_object_commit_get_author(commit);
2818 committer = got_object_commit_get_committer(commit);
2819 if (strcmp(author, committer) != 0)
2820 printf("via: %s\n", committer);
2821 if (got_object_commit_get_nparents(commit) > 1) {
2822 const struct got_object_id_queue *parent_ids;
2823 struct got_object_qid *qid;
2824 int n = 1;
2825 parent_ids = got_object_commit_get_parent_ids(commit);
2826 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
2827 err = got_object_id_str(&id_str, qid->id);
2828 if (err)
2829 return err;
2830 printf("parent %d: %s\n", n++, id_str);
2831 free(id_str);
2835 err = got_object_commit_get_logmsg(&logmsg0, commit);
2836 if (err)
2837 return err;
2839 logmsg = logmsg0;
2840 do {
2841 line = strsep(&logmsg, "\n");
2842 if (line)
2843 printf(" %s\n", line);
2844 } while (line);
2845 free(logmsg0);
2847 if (show_patch) {
2848 err = print_patch(commit, id, path, diff_context, repo);
2849 if (err == 0)
2850 printf("\n");
2853 if (fflush(stdout) != 0 && err == NULL)
2854 err = got_error_from_errno("fflush");
2855 return err;
2858 static const struct got_error *
2859 print_commits(struct got_object_id *root_id, struct got_repository *repo,
2860 const char *path, int show_patch, const char *search_pattern,
2861 int diff_context, int limit, int log_branches,
2862 struct got_reflist_head *refs)
2864 const struct got_error *err;
2865 struct got_commit_graph *graph;
2866 regex_t regex;
2867 int have_match;
2869 if (search_pattern &&
2870 regcomp(&regex, search_pattern, REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
2871 return got_error_msg(GOT_ERR_REGEX, search_pattern);
2873 err = got_commit_graph_open(&graph, path, !log_branches);
2874 if (err)
2875 return err;
2876 err = got_commit_graph_iter_start(graph, root_id, repo,
2877 check_cancelled, NULL);
2878 if (err)
2879 goto done;
2880 for (;;) {
2881 struct got_commit_object *commit;
2882 struct got_object_id *id;
2884 if (sigint_received || sigpipe_received)
2885 break;
2887 err = got_commit_graph_iter_next(&id, graph, repo,
2888 check_cancelled, NULL);
2889 if (err) {
2890 if (err->code == GOT_ERR_ITER_COMPLETED)
2891 err = NULL;
2892 break;
2894 if (id == NULL)
2895 break;
2897 err = got_object_open_as_commit(&commit, repo, id);
2898 if (err)
2899 break;
2901 if (search_pattern) {
2902 err = match_logmsg(&have_match, id, commit, &regex);
2903 if (err) {
2904 got_object_commit_close(commit);
2905 break;
2907 if (have_match == 0) {
2908 got_object_commit_close(commit);
2909 continue;
2913 err = print_commit(commit, id, repo, path, show_patch,
2914 diff_context, refs);
2915 got_object_commit_close(commit);
2916 if (err || (limit && --limit == 0))
2917 break;
2919 done:
2920 if (search_pattern)
2921 regfree(&regex);
2922 got_commit_graph_close(graph);
2923 return err;
2926 __dead static void
2927 usage_log(void)
2929 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] [-p] "
2930 "[-s search-pattern] [-r repository-path] [path]\n", getprogname());
2931 exit(1);
2934 static int
2935 get_default_log_limit(void)
2937 const char *got_default_log_limit;
2938 long long n;
2939 const char *errstr;
2941 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
2942 if (got_default_log_limit == NULL)
2943 return 0;
2944 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
2945 if (errstr != NULL)
2946 return 0;
2947 return n;
2950 static const struct got_error *
2951 cmd_log(int argc, char *argv[])
2953 const struct got_error *error;
2954 struct got_repository *repo = NULL;
2955 struct got_worktree *worktree = NULL;
2956 struct got_commit_object *commit = NULL;
2957 struct got_object_id *id = NULL;
2958 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
2959 const char *start_commit = NULL, *search_pattern = NULL;
2960 int diff_context = -1, ch;
2961 int show_patch = 0, limit = 0, log_branches = 0;
2962 const char *errstr;
2963 struct got_reflist_head refs;
2965 SIMPLEQ_INIT(&refs);
2967 #ifndef PROFILE
2968 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
2969 NULL)
2970 == -1)
2971 err(1, "pledge");
2972 #endif
2974 limit = get_default_log_limit();
2976 while ((ch = getopt(argc, argv, "bpc:C:l:r:s:")) != -1) {
2977 switch (ch) {
2978 case 'p':
2979 show_patch = 1;
2980 break;
2981 case 'c':
2982 start_commit = optarg;
2983 break;
2984 case 'C':
2985 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
2986 &errstr);
2987 if (errstr != NULL)
2988 err(1, "-C option %s", errstr);
2989 break;
2990 case 'l':
2991 limit = strtonum(optarg, 0, INT_MAX, &errstr);
2992 if (errstr != NULL)
2993 err(1, "-l option %s", errstr);
2994 break;
2995 case 'b':
2996 log_branches = 1;
2997 break;
2998 case 'r':
2999 repo_path = realpath(optarg, NULL);
3000 if (repo_path == NULL)
3001 return got_error_from_errno2("realpath",
3002 optarg);
3003 got_path_strip_trailing_slashes(repo_path);
3004 break;
3005 case 's':
3006 search_pattern = optarg;
3007 break;
3008 default:
3009 usage_log();
3010 /* NOTREACHED */
3014 argc -= optind;
3015 argv += optind;
3017 if (diff_context == -1)
3018 diff_context = 3;
3019 else if (!show_patch)
3020 errx(1, "-C reguires -p");
3022 cwd = getcwd(NULL, 0);
3023 if (cwd == NULL) {
3024 error = got_error_from_errno("getcwd");
3025 goto done;
3028 error = got_worktree_open(&worktree, cwd);
3029 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3030 goto done;
3031 error = NULL;
3033 if (argc == 0) {
3034 path = strdup("");
3035 if (path == NULL) {
3036 error = got_error_from_errno("strdup");
3037 goto done;
3039 } else if (argc == 1) {
3040 if (worktree) {
3041 error = got_worktree_resolve_path(&path, worktree,
3042 argv[0]);
3043 if (error)
3044 goto done;
3045 } else {
3046 path = strdup(argv[0]);
3047 if (path == NULL) {
3048 error = got_error_from_errno("strdup");
3049 goto done;
3052 } else
3053 usage_log();
3055 if (repo_path == NULL) {
3056 repo_path = worktree ?
3057 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3059 if (repo_path == NULL) {
3060 error = got_error_from_errno("strdup");
3061 goto done;
3064 error = got_repo_open(&repo, repo_path, NULL);
3065 if (error != NULL)
3066 goto done;
3068 error = apply_unveil(got_repo_get_path(repo), 1,
3069 worktree ? got_worktree_get_root_path(worktree) : NULL);
3070 if (error)
3071 goto done;
3073 if (start_commit == NULL) {
3074 struct got_reference *head_ref;
3075 error = got_ref_open(&head_ref, repo,
3076 worktree ? got_worktree_get_head_ref_name(worktree)
3077 : GOT_REF_HEAD, 0);
3078 if (error != NULL)
3079 return error;
3080 error = got_ref_resolve(&id, repo, head_ref);
3081 got_ref_close(head_ref);
3082 if (error != NULL)
3083 return error;
3084 error = got_object_open_as_commit(&commit, repo, id);
3085 } else {
3086 struct got_reference *ref;
3087 error = got_ref_open(&ref, repo, start_commit, 0);
3088 if (error == NULL) {
3089 int obj_type;
3090 error = got_ref_resolve(&id, repo, ref);
3091 got_ref_close(ref);
3092 if (error != NULL)
3093 goto done;
3094 error = got_object_get_type(&obj_type, repo, id);
3095 if (error != NULL)
3096 goto done;
3097 if (obj_type == GOT_OBJ_TYPE_TAG) {
3098 struct got_tag_object *tag;
3099 error = got_object_open_as_tag(&tag, repo, id);
3100 if (error != NULL)
3101 goto done;
3102 if (got_object_tag_get_object_type(tag) !=
3103 GOT_OBJ_TYPE_COMMIT) {
3104 got_object_tag_close(tag);
3105 error = got_error(GOT_ERR_OBJ_TYPE);
3106 goto done;
3108 free(id);
3109 id = got_object_id_dup(
3110 got_object_tag_get_object_id(tag));
3111 if (id == NULL)
3112 error = got_error_from_errno(
3113 "got_object_id_dup");
3114 got_object_tag_close(tag);
3115 if (error)
3116 goto done;
3117 } else if (obj_type != GOT_OBJ_TYPE_COMMIT) {
3118 error = got_error(GOT_ERR_OBJ_TYPE);
3119 goto done;
3121 error = got_object_open_as_commit(&commit, repo, id);
3122 if (error != NULL)
3123 goto done;
3125 if (commit == NULL) {
3126 error = got_repo_match_object_id_prefix(&id,
3127 start_commit, GOT_OBJ_TYPE_COMMIT, repo);
3128 if (error != NULL)
3129 return error;
3132 if (error != NULL)
3133 goto done;
3135 if (worktree) {
3136 const char *prefix = got_worktree_get_path_prefix(worktree);
3137 char *p;
3138 if (asprintf(&p, "%s%s%s", prefix,
3139 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3140 error = got_error_from_errno("asprintf");
3141 goto done;
3143 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3144 free(p);
3145 } else
3146 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3147 if (error != NULL)
3148 goto done;
3149 if (in_repo_path) {
3150 free(path);
3151 path = in_repo_path;
3154 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3155 if (error)
3156 goto done;
3158 error = print_commits(id, repo, path, show_patch, search_pattern,
3159 diff_context, limit, log_branches, &refs);
3160 done:
3161 free(path);
3162 free(repo_path);
3163 free(cwd);
3164 free(id);
3165 if (worktree)
3166 got_worktree_close(worktree);
3167 if (repo) {
3168 const struct got_error *repo_error;
3169 repo_error = got_repo_close(repo);
3170 if (error == NULL)
3171 error = repo_error;
3173 got_ref_list_free(&refs);
3174 return error;
3177 __dead static void
3178 usage_diff(void)
3180 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3181 "[-w] [object1 object2 | path]\n", getprogname());
3182 exit(1);
3185 struct print_diff_arg {
3186 struct got_repository *repo;
3187 struct got_worktree *worktree;
3188 int diff_context;
3189 const char *id_str;
3190 int header_shown;
3191 int diff_staged;
3192 int ignore_whitespace;
3195 static const struct got_error *
3196 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3197 const char *path, struct got_object_id *blob_id,
3198 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3199 int dirfd, const char *de_name)
3201 struct print_diff_arg *a = arg;
3202 const struct got_error *err = NULL;
3203 struct got_blob_object *blob1 = NULL;
3204 int fd = -1;
3205 FILE *f2 = NULL;
3206 char *abspath = NULL, *label1 = NULL;
3207 struct stat sb;
3209 if (a->diff_staged) {
3210 if (staged_status != GOT_STATUS_MODIFY &&
3211 staged_status != GOT_STATUS_ADD &&
3212 staged_status != GOT_STATUS_DELETE)
3213 return NULL;
3214 } else {
3215 if (staged_status == GOT_STATUS_DELETE)
3216 return NULL;
3217 if (status == GOT_STATUS_NONEXISTENT)
3218 return got_error_set_errno(ENOENT, path);
3219 if (status != GOT_STATUS_MODIFY &&
3220 status != GOT_STATUS_ADD &&
3221 status != GOT_STATUS_DELETE &&
3222 status != GOT_STATUS_CONFLICT)
3223 return NULL;
3226 if (!a->header_shown) {
3227 printf("diff %s %s%s\n", a->id_str,
3228 got_worktree_get_root_path(a->worktree),
3229 a->diff_staged ? " (staged changes)" : "");
3230 a->header_shown = 1;
3233 if (a->diff_staged) {
3234 const char *label1 = NULL, *label2 = NULL;
3235 switch (staged_status) {
3236 case GOT_STATUS_MODIFY:
3237 label1 = path;
3238 label2 = path;
3239 break;
3240 case GOT_STATUS_ADD:
3241 label2 = path;
3242 break;
3243 case GOT_STATUS_DELETE:
3244 label1 = path;
3245 break;
3246 default:
3247 return got_error(GOT_ERR_FILE_STATUS);
3249 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
3250 label1, label2, a->diff_context, a->ignore_whitespace,
3251 a->repo, stdout);
3254 if (staged_status == GOT_STATUS_ADD ||
3255 staged_status == GOT_STATUS_MODIFY) {
3256 char *id_str;
3257 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
3258 8192);
3259 if (err)
3260 goto done;
3261 err = got_object_id_str(&id_str, staged_blob_id);
3262 if (err)
3263 goto done;
3264 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
3265 err = got_error_from_errno("asprintf");
3266 free(id_str);
3267 goto done;
3269 free(id_str);
3270 } else if (status != GOT_STATUS_ADD) {
3271 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
3272 if (err)
3273 goto done;
3276 if (status != GOT_STATUS_DELETE) {
3277 if (asprintf(&abspath, "%s/%s",
3278 got_worktree_get_root_path(a->worktree), path) == -1) {
3279 err = got_error_from_errno("asprintf");
3280 goto done;
3283 if (dirfd != -1) {
3284 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
3285 if (fd == -1) {
3286 err = got_error_from_errno2("openat", abspath);
3287 goto done;
3289 } else {
3290 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
3291 if (fd == -1) {
3292 err = got_error_from_errno2("open", abspath);
3293 goto done;
3296 if (fstat(fd, &sb) == -1) {
3297 err = got_error_from_errno2("fstat", abspath);
3298 goto done;
3300 f2 = fdopen(fd, "r");
3301 if (f2 == NULL) {
3302 err = got_error_from_errno2("fdopen", abspath);
3303 goto done;
3305 fd = -1;
3306 } else
3307 sb.st_size = 0;
3309 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
3310 a->diff_context, a->ignore_whitespace, stdout);
3311 done:
3312 if (blob1)
3313 got_object_blob_close(blob1);
3314 if (f2 && fclose(f2) == EOF && err == NULL)
3315 err = got_error_from_errno("fclose");
3316 if (fd != -1 && close(fd) == -1 && err == NULL)
3317 err = got_error_from_errno("close");
3318 free(abspath);
3319 return err;
3322 static const struct got_error *
3323 cmd_diff(int argc, char *argv[])
3325 const struct got_error *error;
3326 struct got_repository *repo = NULL;
3327 struct got_worktree *worktree = NULL;
3328 char *cwd = NULL, *repo_path = NULL;
3329 struct got_object_id *id1 = NULL, *id2 = NULL;
3330 const char *id_str1 = NULL, *id_str2 = NULL;
3331 char *label1 = NULL, *label2 = NULL;
3332 int type1, type2;
3333 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
3334 const char *errstr;
3335 char *path = NULL;
3337 #ifndef PROFILE
3338 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3339 NULL) == -1)
3340 err(1, "pledge");
3341 #endif
3343 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
3344 switch (ch) {
3345 case 'C':
3346 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3347 &errstr);
3348 if (errstr != NULL)
3349 err(1, "-C option %s", errstr);
3350 break;
3351 case 'r':
3352 repo_path = realpath(optarg, NULL);
3353 if (repo_path == NULL)
3354 return got_error_from_errno2("realpath",
3355 optarg);
3356 got_path_strip_trailing_slashes(repo_path);
3357 break;
3358 case 's':
3359 diff_staged = 1;
3360 break;
3361 case 'w':
3362 ignore_whitespace = 1;
3363 break;
3364 default:
3365 usage_diff();
3366 /* NOTREACHED */
3370 argc -= optind;
3371 argv += optind;
3373 cwd = getcwd(NULL, 0);
3374 if (cwd == NULL) {
3375 error = got_error_from_errno("getcwd");
3376 goto done;
3378 if (argc <= 1) {
3379 if (repo_path)
3380 errx(1,
3381 "-r option can't be used when diffing a work tree");
3382 error = got_worktree_open(&worktree, cwd);
3383 if (error)
3384 goto done;
3385 repo_path = strdup(got_worktree_get_repo_path(worktree));
3386 if (repo_path == NULL) {
3387 error = got_error_from_errno("strdup");
3388 goto done;
3390 if (argc == 1) {
3391 error = got_worktree_resolve_path(&path, worktree,
3392 argv[0]);
3393 if (error)
3394 goto done;
3395 } else {
3396 path = strdup("");
3397 if (path == NULL) {
3398 error = got_error_from_errno("strdup");
3399 goto done;
3402 } else if (argc == 2) {
3403 if (diff_staged)
3404 errx(1, "-s option can't be used when diffing "
3405 "objects in repository");
3406 id_str1 = argv[0];
3407 id_str2 = argv[1];
3408 if (repo_path == NULL) {
3409 error = got_worktree_open(&worktree, cwd);
3410 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3411 goto done;
3412 if (worktree) {
3413 repo_path = strdup(
3414 got_worktree_get_repo_path(worktree));
3415 if (repo_path == NULL) {
3416 error = got_error_from_errno("strdup");
3417 goto done;
3419 } else {
3420 repo_path = strdup(cwd);
3421 if (repo_path == NULL) {
3422 error = got_error_from_errno("strdup");
3423 goto done;
3427 } else
3428 usage_diff();
3430 error = got_repo_open(&repo, repo_path, NULL);
3431 free(repo_path);
3432 if (error != NULL)
3433 goto done;
3435 error = apply_unveil(got_repo_get_path(repo), 1,
3436 worktree ? got_worktree_get_root_path(worktree) : NULL);
3437 if (error)
3438 goto done;
3440 if (argc <= 1) {
3441 struct print_diff_arg arg;
3442 struct got_pathlist_head paths;
3443 char *id_str;
3445 TAILQ_INIT(&paths);
3447 error = got_object_id_str(&id_str,
3448 got_worktree_get_base_commit_id(worktree));
3449 if (error)
3450 goto done;
3451 arg.repo = repo;
3452 arg.worktree = worktree;
3453 arg.diff_context = diff_context;
3454 arg.id_str = id_str;
3455 arg.header_shown = 0;
3456 arg.diff_staged = diff_staged;
3457 arg.ignore_whitespace = ignore_whitespace;
3459 error = got_pathlist_append(&paths, path, NULL);
3460 if (error)
3461 goto done;
3463 error = got_worktree_status(worktree, &paths, repo, print_diff,
3464 &arg, check_cancelled, NULL);
3465 free(id_str);
3466 got_pathlist_free(&paths);
3467 goto done;
3470 error = got_repo_match_object_id(&id1, &label1, id_str1,
3471 GOT_OBJ_TYPE_ANY, 1, repo);
3472 if (error)
3473 goto done;
3475 error = got_repo_match_object_id(&id2, &label2, id_str2,
3476 GOT_OBJ_TYPE_ANY, 1, repo);
3477 if (error)
3478 goto done;
3480 error = got_object_get_type(&type1, repo, id1);
3481 if (error)
3482 goto done;
3484 error = got_object_get_type(&type2, repo, id2);
3485 if (error)
3486 goto done;
3488 if (type1 != type2) {
3489 error = got_error(GOT_ERR_OBJ_TYPE);
3490 goto done;
3493 switch (type1) {
3494 case GOT_OBJ_TYPE_BLOB:
3495 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
3496 diff_context, ignore_whitespace, repo, stdout);
3497 break;
3498 case GOT_OBJ_TYPE_TREE:
3499 error = got_diff_objects_as_trees(id1, id2, "", "",
3500 diff_context, ignore_whitespace, repo, stdout);
3501 break;
3502 case GOT_OBJ_TYPE_COMMIT:
3503 printf("diff %s %s\n", label1, label2);
3504 error = got_diff_objects_as_commits(id1, id2, diff_context,
3505 ignore_whitespace, repo, stdout);
3506 break;
3507 default:
3508 error = got_error(GOT_ERR_OBJ_TYPE);
3510 done:
3511 free(label1);
3512 free(label2);
3513 free(id1);
3514 free(id2);
3515 free(path);
3516 if (worktree)
3517 got_worktree_close(worktree);
3518 if (repo) {
3519 const struct got_error *repo_error;
3520 repo_error = got_repo_close(repo);
3521 if (error == NULL)
3522 error = repo_error;
3524 return error;
3527 __dead static void
3528 usage_blame(void)
3530 fprintf(stderr,
3531 "usage: %s blame [-c commit] [-r repository-path] path\n",
3532 getprogname());
3533 exit(1);
3536 struct blame_line {
3537 int annotated;
3538 char *id_str;
3539 char *committer;
3540 char datebuf[11]; /* YYYY-MM-DD + NUL */
3543 struct blame_cb_args {
3544 struct blame_line *lines;
3545 int nlines;
3546 int nlines_prec;
3547 int lineno_cur;
3548 off_t *line_offsets;
3549 FILE *f;
3550 struct got_repository *repo;
3553 static const struct got_error *
3554 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
3556 const struct got_error *err = NULL;
3557 struct blame_cb_args *a = arg;
3558 struct blame_line *bline;
3559 char *line = NULL;
3560 size_t linesize = 0;
3561 struct got_commit_object *commit = NULL;
3562 off_t offset;
3563 struct tm tm;
3564 time_t committer_time;
3566 if (nlines != a->nlines ||
3567 (lineno != -1 && lineno < 1) || lineno > a->nlines)
3568 return got_error(GOT_ERR_RANGE);
3570 if (sigint_received)
3571 return got_error(GOT_ERR_ITER_COMPLETED);
3573 if (lineno == -1)
3574 return NULL; /* no change in this commit */
3576 /* Annotate this line. */
3577 bline = &a->lines[lineno - 1];
3578 if (bline->annotated)
3579 return NULL;
3580 err = got_object_id_str(&bline->id_str, id);
3581 if (err)
3582 return err;
3584 err = got_object_open_as_commit(&commit, a->repo, id);
3585 if (err)
3586 goto done;
3588 bline->committer = strdup(got_object_commit_get_committer(commit));
3589 if (bline->committer == NULL) {
3590 err = got_error_from_errno("strdup");
3591 goto done;
3594 committer_time = got_object_commit_get_committer_time(commit);
3595 if (localtime_r(&committer_time, &tm) == NULL)
3596 return got_error_from_errno("localtime_r");
3597 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
3598 &tm) >= sizeof(bline->datebuf)) {
3599 err = got_error(GOT_ERR_NO_SPACE);
3600 goto done;
3602 bline->annotated = 1;
3604 /* Print lines annotated so far. */
3605 bline = &a->lines[a->lineno_cur - 1];
3606 if (!bline->annotated)
3607 goto done;
3609 offset = a->line_offsets[a->lineno_cur - 1];
3610 if (fseeko(a->f, offset, SEEK_SET) == -1) {
3611 err = got_error_from_errno("fseeko");
3612 goto done;
3615 while (bline->annotated) {
3616 char *smallerthan, *at, *nl, *committer;
3617 size_t len;
3619 if (getline(&line, &linesize, a->f) == -1) {
3620 if (ferror(a->f))
3621 err = got_error_from_errno("getline");
3622 break;
3625 committer = bline->committer;
3626 smallerthan = strchr(committer, '<');
3627 if (smallerthan && smallerthan[1] != '\0')
3628 committer = smallerthan + 1;
3629 at = strchr(committer, '@');
3630 if (at)
3631 *at = '\0';
3632 len = strlen(committer);
3633 if (len >= 9)
3634 committer[8] = '\0';
3636 nl = strchr(line, '\n');
3637 if (nl)
3638 *nl = '\0';
3639 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
3640 bline->id_str, bline->datebuf, committer, line);
3642 a->lineno_cur++;
3643 bline = &a->lines[a->lineno_cur - 1];
3645 done:
3646 if (commit)
3647 got_object_commit_close(commit);
3648 free(line);
3649 return err;
3652 static const struct got_error *
3653 cmd_blame(int argc, char *argv[])
3655 const struct got_error *error;
3656 struct got_repository *repo = NULL;
3657 struct got_worktree *worktree = NULL;
3658 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
3659 struct got_object_id *obj_id = NULL;
3660 struct got_object_id *commit_id = NULL;
3661 struct got_blob_object *blob = NULL;
3662 char *commit_id_str = NULL;
3663 struct blame_cb_args bca;
3664 int ch, obj_type, i;
3665 size_t filesize;
3667 memset(&bca, 0, sizeof(bca));
3669 #ifndef PROFILE
3670 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3671 NULL) == -1)
3672 err(1, "pledge");
3673 #endif
3675 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
3676 switch (ch) {
3677 case 'c':
3678 commit_id_str = optarg;
3679 break;
3680 case 'r':
3681 repo_path = realpath(optarg, NULL);
3682 if (repo_path == NULL)
3683 return got_error_from_errno2("realpath",
3684 optarg);
3685 got_path_strip_trailing_slashes(repo_path);
3686 break;
3687 default:
3688 usage_blame();
3689 /* NOTREACHED */
3693 argc -= optind;
3694 argv += optind;
3696 if (argc == 1)
3697 path = argv[0];
3698 else
3699 usage_blame();
3701 cwd = getcwd(NULL, 0);
3702 if (cwd == NULL) {
3703 error = got_error_from_errno("getcwd");
3704 goto done;
3706 if (repo_path == NULL) {
3707 error = got_worktree_open(&worktree, cwd);
3708 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3709 goto done;
3710 else
3711 error = NULL;
3712 if (worktree) {
3713 repo_path =
3714 strdup(got_worktree_get_repo_path(worktree));
3715 if (repo_path == NULL) {
3716 error = got_error_from_errno("strdup");
3717 if (error)
3718 goto done;
3720 } else {
3721 repo_path = strdup(cwd);
3722 if (repo_path == NULL) {
3723 error = got_error_from_errno("strdup");
3724 goto done;
3729 error = got_repo_open(&repo, repo_path, NULL);
3730 if (error != NULL)
3731 goto done;
3733 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
3734 if (error)
3735 goto done;
3737 if (worktree) {
3738 const char *prefix = got_worktree_get_path_prefix(worktree);
3739 char *p, *worktree_subdir = cwd +
3740 strlen(got_worktree_get_root_path(worktree));
3741 if (asprintf(&p, "%s%s%s%s%s",
3742 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
3743 worktree_subdir, worktree_subdir[0] ? "/" : "",
3744 path) == -1) {
3745 error = got_error_from_errno("asprintf");
3746 goto done;
3748 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3749 free(p);
3750 } else {
3751 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3753 if (error)
3754 goto done;
3756 if (commit_id_str == NULL) {
3757 struct got_reference *head_ref;
3758 error = got_ref_open(&head_ref, repo, worktree ?
3759 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
3760 if (error != NULL)
3761 goto done;
3762 error = got_ref_resolve(&commit_id, repo, head_ref);
3763 got_ref_close(head_ref);
3764 if (error != NULL)
3765 goto done;
3766 } else {
3767 error = got_repo_match_object_id(&commit_id, NULL,
3768 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
3769 if (error)
3770 goto done;
3773 error = got_object_id_by_path(&obj_id, repo, commit_id, in_repo_path);
3774 if (error)
3775 goto done;
3777 error = got_object_get_type(&obj_type, repo, obj_id);
3778 if (error)
3779 goto done;
3781 if (obj_type != GOT_OBJ_TYPE_BLOB) {
3782 error = got_error(GOT_ERR_OBJ_TYPE);
3783 goto done;
3786 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
3787 if (error)
3788 goto done;
3789 bca.f = got_opentemp();
3790 if (bca.f == NULL) {
3791 error = got_error_from_errno("got_opentemp");
3792 goto done;
3794 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
3795 &bca.line_offsets, bca.f, blob);
3796 if (error || bca.nlines == 0)
3797 goto done;
3799 /* Don't include \n at EOF in the blame line count. */
3800 if (bca.line_offsets[bca.nlines - 1] == filesize)
3801 bca.nlines--;
3803 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
3804 if (bca.lines == NULL) {
3805 error = got_error_from_errno("calloc");
3806 goto done;
3808 bca.lineno_cur = 1;
3809 bca.nlines_prec = 0;
3810 i = bca.nlines;
3811 while (i > 0) {
3812 i /= 10;
3813 bca.nlines_prec++;
3815 bca.repo = repo;
3817 error = got_blame(in_repo_path, commit_id, repo, blame_cb, &bca,
3818 check_cancelled, NULL);
3819 done:
3820 free(in_repo_path);
3821 free(repo_path);
3822 free(cwd);
3823 free(commit_id);
3824 free(obj_id);
3825 if (blob)
3826 got_object_blob_close(blob);
3827 if (worktree)
3828 got_worktree_close(worktree);
3829 if (repo) {
3830 const struct got_error *repo_error;
3831 repo_error = got_repo_close(repo);
3832 if (error == NULL)
3833 error = repo_error;
3835 if (bca.lines) {
3836 for (i = 0; i < bca.nlines; i++) {
3837 struct blame_line *bline = &bca.lines[i];
3838 free(bline->id_str);
3839 free(bline->committer);
3841 free(bca.lines);
3843 free(bca.line_offsets);
3844 if (bca.f && fclose(bca.f) == EOF && error == NULL)
3845 error = got_error_from_errno("fclose");
3846 return error;
3849 __dead static void
3850 usage_tree(void)
3852 fprintf(stderr,
3853 "usage: %s tree [-c commit] [-r repository-path] [-iR] path\n",
3854 getprogname());
3855 exit(1);
3858 static void
3859 print_entry(struct got_tree_entry *te, const char *id, const char *path,
3860 const char *root_path)
3862 int is_root_path = (strcmp(path, root_path) == 0);
3863 const char *modestr = "";
3864 mode_t mode = got_tree_entry_get_mode(te);
3866 path += strlen(root_path);
3867 while (path[0] == '/')
3868 path++;
3870 if (got_object_tree_entry_is_submodule(te))
3871 modestr = "$";
3872 else if (S_ISLNK(mode))
3873 modestr = "@";
3874 else if (S_ISDIR(mode))
3875 modestr = "/";
3876 else if (mode & S_IXUSR)
3877 modestr = "*";
3879 printf("%s%s%s%s%s\n", id ? id : "", path,
3880 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr);
3883 static const struct got_error *
3884 print_tree(const char *path, struct got_object_id *commit_id,
3885 int show_ids, int recurse, const char *root_path,
3886 struct got_repository *repo)
3888 const struct got_error *err = NULL;
3889 struct got_object_id *tree_id = NULL;
3890 struct got_tree_object *tree = NULL;
3891 int nentries, i;
3893 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
3894 if (err)
3895 goto done;
3897 err = got_object_open_as_tree(&tree, repo, tree_id);
3898 if (err)
3899 goto done;
3900 nentries = got_object_tree_get_nentries(tree);
3901 for (i = 0; i < nentries; i++) {
3902 struct got_tree_entry *te;
3903 char *id = NULL;
3905 if (sigint_received || sigpipe_received)
3906 break;
3908 te = got_object_tree_get_entry(tree, i);
3909 if (show_ids) {
3910 char *id_str;
3911 err = got_object_id_str(&id_str,
3912 got_tree_entry_get_id(te));
3913 if (err)
3914 goto done;
3915 if (asprintf(&id, "%s ", id_str) == -1) {
3916 err = got_error_from_errno("asprintf");
3917 free(id_str);
3918 goto done;
3920 free(id_str);
3922 print_entry(te, id, path, root_path);
3923 free(id);
3925 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
3926 char *child_path;
3927 if (asprintf(&child_path, "%s%s%s", path,
3928 path[0] == '/' && path[1] == '\0' ? "" : "/",
3929 got_tree_entry_get_name(te)) == -1) {
3930 err = got_error_from_errno("asprintf");
3931 goto done;
3933 err = print_tree(child_path, commit_id, show_ids, 1,
3934 root_path, repo);
3935 free(child_path);
3936 if (err)
3937 goto done;
3940 done:
3941 if (tree)
3942 got_object_tree_close(tree);
3943 free(tree_id);
3944 return err;
3947 static const struct got_error *
3948 cmd_tree(int argc, char *argv[])
3950 const struct got_error *error;
3951 struct got_repository *repo = NULL;
3952 struct got_worktree *worktree = NULL;
3953 const char *path, *refname = NULL;
3954 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
3955 struct got_object_id *commit_id = NULL;
3956 char *commit_id_str = NULL;
3957 int show_ids = 0, recurse = 0;
3958 int ch;
3960 #ifndef PROFILE
3961 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3962 NULL) == -1)
3963 err(1, "pledge");
3964 #endif
3966 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
3967 switch (ch) {
3968 case 'c':
3969 commit_id_str = optarg;
3970 break;
3971 case 'r':
3972 repo_path = realpath(optarg, NULL);
3973 if (repo_path == NULL)
3974 return got_error_from_errno2("realpath",
3975 optarg);
3976 got_path_strip_trailing_slashes(repo_path);
3977 break;
3978 case 'i':
3979 show_ids = 1;
3980 break;
3981 case 'R':
3982 recurse = 1;
3983 break;
3984 default:
3985 usage_tree();
3986 /* NOTREACHED */
3990 argc -= optind;
3991 argv += optind;
3993 if (argc == 1)
3994 path = argv[0];
3995 else if (argc > 1)
3996 usage_tree();
3997 else
3998 path = NULL;
4000 cwd = getcwd(NULL, 0);
4001 if (cwd == NULL) {
4002 error = got_error_from_errno("getcwd");
4003 goto done;
4005 if (repo_path == NULL) {
4006 error = got_worktree_open(&worktree, cwd);
4007 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4008 goto done;
4009 else
4010 error = NULL;
4011 if (worktree) {
4012 repo_path =
4013 strdup(got_worktree_get_repo_path(worktree));
4014 if (repo_path == NULL)
4015 error = got_error_from_errno("strdup");
4016 if (error)
4017 goto done;
4018 } else {
4019 repo_path = strdup(cwd);
4020 if (repo_path == NULL) {
4021 error = got_error_from_errno("strdup");
4022 goto done;
4027 error = got_repo_open(&repo, repo_path, NULL);
4028 if (error != NULL)
4029 goto done;
4031 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4032 if (error)
4033 goto done;
4035 if (path == NULL) {
4036 if (worktree) {
4037 char *p, *worktree_subdir = cwd +
4038 strlen(got_worktree_get_root_path(worktree));
4039 if (asprintf(&p, "%s/%s",
4040 got_worktree_get_path_prefix(worktree),
4041 worktree_subdir) == -1) {
4042 error = got_error_from_errno("asprintf");
4043 goto done;
4045 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4046 free(p);
4047 if (error)
4048 goto done;
4049 } else
4050 path = "/";
4052 if (in_repo_path == NULL) {
4053 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4054 if (error != NULL)
4055 goto done;
4058 if (commit_id_str == NULL) {
4059 struct got_reference *head_ref;
4060 if (worktree)
4061 refname = got_worktree_get_head_ref_name(worktree);
4062 else
4063 refname = GOT_REF_HEAD;
4064 error = got_ref_open(&head_ref, repo, refname, 0);
4065 if (error != NULL)
4066 goto done;
4067 error = got_ref_resolve(&commit_id, repo, head_ref);
4068 got_ref_close(head_ref);
4069 if (error != NULL)
4070 goto done;
4071 } else {
4072 error = got_repo_match_object_id(&commit_id, NULL,
4073 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4074 if (error)
4075 goto done;
4078 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4079 in_repo_path, repo);
4080 done:
4081 free(in_repo_path);
4082 free(repo_path);
4083 free(cwd);
4084 free(commit_id);
4085 if (worktree)
4086 got_worktree_close(worktree);
4087 if (repo) {
4088 const struct got_error *repo_error;
4089 repo_error = got_repo_close(repo);
4090 if (error == NULL)
4091 error = repo_error;
4093 return error;
4096 __dead static void
4097 usage_status(void)
4099 fprintf(stderr, "usage: %s status [path ...]\n", getprogname());
4100 exit(1);
4103 static const struct got_error *
4104 print_status(void *arg, unsigned char status, unsigned char staged_status,
4105 const char *path, struct got_object_id *blob_id,
4106 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4107 int dirfd, const char *de_name)
4109 if (status == staged_status && (status == GOT_STATUS_DELETE))
4110 status = GOT_STATUS_NO_CHANGE;
4111 printf("%c%c %s\n", status, staged_status, path);
4112 return NULL;
4115 static const struct got_error *
4116 cmd_status(int argc, char *argv[])
4118 const struct got_error *error = NULL;
4119 struct got_repository *repo = NULL;
4120 struct got_worktree *worktree = NULL;
4121 char *cwd = NULL;
4122 struct got_pathlist_head paths;
4123 struct got_pathlist_entry *pe;
4124 int ch;
4126 TAILQ_INIT(&paths);
4128 while ((ch = getopt(argc, argv, "")) != -1) {
4129 switch (ch) {
4130 default:
4131 usage_status();
4132 /* NOTREACHED */
4136 argc -= optind;
4137 argv += optind;
4139 #ifndef PROFILE
4140 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4141 NULL) == -1)
4142 err(1, "pledge");
4143 #endif
4144 cwd = getcwd(NULL, 0);
4145 if (cwd == NULL) {
4146 error = got_error_from_errno("getcwd");
4147 goto done;
4150 error = got_worktree_open(&worktree, cwd);
4151 if (error != NULL)
4152 goto done;
4154 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4155 NULL);
4156 if (error != NULL)
4157 goto done;
4159 error = apply_unveil(got_repo_get_path(repo), 1,
4160 got_worktree_get_root_path(worktree));
4161 if (error)
4162 goto done;
4164 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
4165 if (error)
4166 goto done;
4168 error = got_worktree_status(worktree, &paths, repo, print_status, NULL,
4169 check_cancelled, NULL);
4170 done:
4171 TAILQ_FOREACH(pe, &paths, entry)
4172 free((char *)pe->path);
4173 got_pathlist_free(&paths);
4174 free(cwd);
4175 return error;
4178 __dead static void
4179 usage_ref(void)
4181 fprintf(stderr,
4182 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
4183 "[-d] [name]\n",
4184 getprogname());
4185 exit(1);
4188 static const struct got_error *
4189 list_refs(struct got_repository *repo, const char *refname)
4191 static const struct got_error *err = NULL;
4192 struct got_reflist_head refs;
4193 struct got_reflist_entry *re;
4195 SIMPLEQ_INIT(&refs);
4196 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
4197 if (err)
4198 return err;
4200 SIMPLEQ_FOREACH(re, &refs, entry) {
4201 char *refstr;
4202 refstr = got_ref_to_str(re->ref);
4203 if (refstr == NULL)
4204 return got_error_from_errno("got_ref_to_str");
4205 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
4206 free(refstr);
4209 got_ref_list_free(&refs);
4210 return NULL;
4213 static const struct got_error *
4214 delete_ref(struct got_repository *repo, const char *refname)
4216 const struct got_error *err = NULL;
4217 struct got_reference *ref;
4219 err = got_ref_open(&ref, repo, refname, 0);
4220 if (err)
4221 return err;
4223 err = got_ref_delete(ref, repo);
4224 got_ref_close(ref);
4225 return err;
4228 static const struct got_error *
4229 add_ref(struct got_repository *repo, const char *refname, const char *target)
4231 const struct got_error *err = NULL;
4232 struct got_object_id *id;
4233 struct got_reference *ref = NULL;
4236 * Don't let the user create a reference name with a leading '-'.
4237 * While technically a valid reference name, this case is usually
4238 * an unintended typo.
4240 if (refname[0] == '-')
4241 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4243 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
4244 repo);
4245 if (err) {
4246 struct got_reference *target_ref;
4248 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
4249 return err;
4250 err = got_ref_open(&target_ref, repo, target, 0);
4251 if (err)
4252 return err;
4253 err = got_ref_resolve(&id, repo, target_ref);
4254 got_ref_close(target_ref);
4255 if (err)
4256 return err;
4259 err = got_ref_alloc(&ref, refname, id);
4260 if (err)
4261 goto done;
4263 err = got_ref_write(ref, repo);
4264 done:
4265 if (ref)
4266 got_ref_close(ref);
4267 free(id);
4268 return err;
4271 static const struct got_error *
4272 add_symref(struct got_repository *repo, const char *refname, const char *target)
4274 const struct got_error *err = NULL;
4275 struct got_reference *ref = NULL;
4276 struct got_reference *target_ref = NULL;
4279 * Don't let the user create a reference name with a leading '-'.
4280 * While technically a valid reference name, this case is usually
4281 * an unintended typo.
4283 if (refname[0] == '-')
4284 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4286 err = got_ref_open(&target_ref, repo, target, 0);
4287 if (err)
4288 return err;
4290 err = got_ref_alloc_symref(&ref, refname, target_ref);
4291 if (err)
4292 goto done;
4294 err = got_ref_write(ref, repo);
4295 done:
4296 if (target_ref)
4297 got_ref_close(target_ref);
4298 if (ref)
4299 got_ref_close(ref);
4300 return err;
4303 static const struct got_error *
4304 cmd_ref(int argc, char *argv[])
4306 const struct got_error *error = NULL;
4307 struct got_repository *repo = NULL;
4308 struct got_worktree *worktree = NULL;
4309 char *cwd = NULL, *repo_path = NULL;
4310 int ch, do_list = 0, do_delete = 0;
4311 const char *obj_arg = NULL, *symref_target= NULL;
4312 char *refname = NULL;
4314 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
4315 switch (ch) {
4316 case 'c':
4317 obj_arg = optarg;
4318 break;
4319 case 'd':
4320 do_delete = 1;
4321 break;
4322 case 'r':
4323 repo_path = realpath(optarg, NULL);
4324 if (repo_path == NULL)
4325 return got_error_from_errno2("realpath",
4326 optarg);
4327 got_path_strip_trailing_slashes(repo_path);
4328 break;
4329 case 'l':
4330 do_list = 1;
4331 break;
4332 case 's':
4333 symref_target = optarg;
4334 break;
4335 default:
4336 usage_ref();
4337 /* NOTREACHED */
4341 if (obj_arg && do_list)
4342 errx(1, "-c and -l options are mutually exclusive");
4343 if (obj_arg && do_delete)
4344 errx(1, "-c and -d options are mutually exclusive");
4345 if (obj_arg && symref_target)
4346 errx(1, "-c and -s options are mutually exclusive");
4347 if (symref_target && do_delete)
4348 errx(1, "-s and -d options are mutually exclusive");
4349 if (symref_target && do_list)
4350 errx(1, "-s and -l options are mutually exclusive");
4351 if (do_delete && do_list)
4352 errx(1, "-d and -l options are mutually exclusive");
4354 argc -= optind;
4355 argv += optind;
4357 if (do_list) {
4358 if (argc != 0 && argc != 1)
4359 usage_ref();
4360 if (argc == 1) {
4361 refname = strdup(argv[0]);
4362 if (refname == NULL) {
4363 error = got_error_from_errno("strdup");
4364 goto done;
4367 } else {
4368 if (argc != 1)
4369 usage_ref();
4370 refname = strdup(argv[0]);
4371 if (refname == NULL) {
4372 error = got_error_from_errno("strdup");
4373 goto done;
4377 if (refname)
4378 got_path_strip_trailing_slashes(refname);
4380 #ifndef PROFILE
4381 if (do_list) {
4382 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4383 NULL) == -1)
4384 err(1, "pledge");
4385 } else {
4386 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4387 "sendfd unveil", NULL) == -1)
4388 err(1, "pledge");
4390 #endif
4391 cwd = getcwd(NULL, 0);
4392 if (cwd == NULL) {
4393 error = got_error_from_errno("getcwd");
4394 goto done;
4397 if (repo_path == NULL) {
4398 error = got_worktree_open(&worktree, cwd);
4399 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4400 goto done;
4401 else
4402 error = NULL;
4403 if (worktree) {
4404 repo_path =
4405 strdup(got_worktree_get_repo_path(worktree));
4406 if (repo_path == NULL)
4407 error = got_error_from_errno("strdup");
4408 if (error)
4409 goto done;
4410 } else {
4411 repo_path = strdup(cwd);
4412 if (repo_path == NULL) {
4413 error = got_error_from_errno("strdup");
4414 goto done;
4419 error = got_repo_open(&repo, repo_path, NULL);
4420 if (error != NULL)
4421 goto done;
4423 error = apply_unveil(got_repo_get_path(repo), do_list,
4424 worktree ? got_worktree_get_root_path(worktree) : NULL);
4425 if (error)
4426 goto done;
4428 if (do_list)
4429 error = list_refs(repo, refname);
4430 else if (do_delete)
4431 error = delete_ref(repo, refname);
4432 else if (symref_target)
4433 error = add_symref(repo, refname, symref_target);
4434 else {
4435 if (obj_arg == NULL)
4436 usage_ref();
4437 error = add_ref(repo, refname, obj_arg);
4439 done:
4440 free(refname);
4441 if (repo)
4442 got_repo_close(repo);
4443 if (worktree)
4444 got_worktree_close(worktree);
4445 free(cwd);
4446 free(repo_path);
4447 return error;
4450 __dead static void
4451 usage_branch(void)
4453 fprintf(stderr,
4454 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
4455 "[name]\n", getprogname());
4456 exit(1);
4459 static const struct got_error *
4460 list_branch(struct got_repository *repo, struct got_worktree *worktree,
4461 struct got_reference *ref)
4463 const struct got_error *err = NULL;
4464 const char *refname, *marker = " ";
4465 char *refstr;
4467 refname = got_ref_get_name(ref);
4468 if (worktree && strcmp(refname,
4469 got_worktree_get_head_ref_name(worktree)) == 0) {
4470 struct got_object_id *id = NULL;
4472 err = got_ref_resolve(&id, repo, ref);
4473 if (err)
4474 return err;
4475 if (got_object_id_cmp(id,
4476 got_worktree_get_base_commit_id(worktree)) == 0)
4477 marker = "* ";
4478 else
4479 marker = "~ ";
4480 free(id);
4483 if (strncmp(refname, "refs/heads/", 11) == 0)
4484 refname += 11;
4485 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4486 refname += 18;
4488 refstr = got_ref_to_str(ref);
4489 if (refstr == NULL)
4490 return got_error_from_errno("got_ref_to_str");
4492 printf("%s%s: %s\n", marker, refname, refstr);
4493 free(refstr);
4494 return NULL;
4497 static const struct got_error *
4498 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
4500 const char *refname;
4502 if (worktree == NULL)
4503 return got_error(GOT_ERR_NOT_WORKTREE);
4505 refname = got_worktree_get_head_ref_name(worktree);
4507 if (strncmp(refname, "refs/heads/", 11) == 0)
4508 refname += 11;
4509 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4510 refname += 18;
4512 printf("%s\n", refname);
4514 return NULL;
4517 static const struct got_error *
4518 list_branches(struct got_repository *repo, struct got_worktree *worktree)
4520 static const struct got_error *err = NULL;
4521 struct got_reflist_head refs;
4522 struct got_reflist_entry *re;
4523 struct got_reference *temp_ref = NULL;
4524 int rebase_in_progress, histedit_in_progress;
4526 SIMPLEQ_INIT(&refs);
4528 if (worktree) {
4529 err = got_worktree_rebase_in_progress(&rebase_in_progress,
4530 worktree);
4531 if (err)
4532 return err;
4534 err = got_worktree_histedit_in_progress(&histedit_in_progress,
4535 worktree);
4536 if (err)
4537 return err;
4539 if (rebase_in_progress || histedit_in_progress) {
4540 err = got_ref_open(&temp_ref, repo,
4541 got_worktree_get_head_ref_name(worktree), 0);
4542 if (err)
4543 return err;
4544 list_branch(repo, worktree, temp_ref);
4545 got_ref_close(temp_ref);
4549 err = got_ref_list(&refs, repo, "refs/heads",
4550 got_ref_cmp_by_name, NULL);
4551 if (err)
4552 return err;
4554 SIMPLEQ_FOREACH(re, &refs, entry)
4555 list_branch(repo, worktree, re->ref);
4557 got_ref_list_free(&refs);
4558 return NULL;
4561 static const struct got_error *
4562 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
4563 const char *branch_name)
4565 const struct got_error *err = NULL;
4566 struct got_reference *ref = NULL;
4567 char *refname;
4569 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
4570 return got_error_from_errno("asprintf");
4572 err = got_ref_open(&ref, repo, refname, 0);
4573 if (err)
4574 goto done;
4576 if (worktree &&
4577 strcmp(got_worktree_get_head_ref_name(worktree),
4578 got_ref_get_name(ref)) == 0) {
4579 err = got_error_msg(GOT_ERR_SAME_BRANCH,
4580 "will not delete this work tree's current branch");
4581 goto done;
4584 err = got_ref_delete(ref, repo);
4585 done:
4586 if (ref)
4587 got_ref_close(ref);
4588 free(refname);
4589 return err;
4592 static const struct got_error *
4593 add_branch(struct got_repository *repo, const char *branch_name,
4594 struct got_object_id *base_commit_id)
4596 const struct got_error *err = NULL;
4597 struct got_reference *ref = NULL;
4598 char *base_refname = NULL, *refname = NULL;
4601 * Don't let the user create a branch name with a leading '-'.
4602 * While technically a valid reference name, this case is usually
4603 * an unintended typo.
4605 if (branch_name[0] == '-')
4606 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
4608 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
4609 err = got_error_from_errno("asprintf");
4610 goto done;
4613 err = got_ref_open(&ref, repo, refname, 0);
4614 if (err == NULL) {
4615 err = got_error(GOT_ERR_BRANCH_EXISTS);
4616 goto done;
4617 } else if (err->code != GOT_ERR_NOT_REF)
4618 goto done;
4620 err = got_ref_alloc(&ref, refname, base_commit_id);
4621 if (err)
4622 goto done;
4624 err = got_ref_write(ref, repo);
4625 done:
4626 if (ref)
4627 got_ref_close(ref);
4628 free(base_refname);
4629 free(refname);
4630 return err;
4633 static const struct got_error *
4634 cmd_branch(int argc, char *argv[])
4636 const struct got_error *error = NULL;
4637 struct got_repository *repo = NULL;
4638 struct got_worktree *worktree = NULL;
4639 char *cwd = NULL, *repo_path = NULL;
4640 int ch, do_list = 0, do_show = 0, do_update = 1;
4641 const char *delref = NULL, *commit_id_arg = NULL;
4642 struct got_reference *ref = NULL;
4643 struct got_pathlist_head paths;
4644 struct got_pathlist_entry *pe;
4645 struct got_object_id *commit_id = NULL;
4646 char *commit_id_str = NULL;
4648 TAILQ_INIT(&paths);
4650 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
4651 switch (ch) {
4652 case 'c':
4653 commit_id_arg = optarg;
4654 break;
4655 case 'd':
4656 delref = optarg;
4657 break;
4658 case 'r':
4659 repo_path = realpath(optarg, NULL);
4660 if (repo_path == NULL)
4661 return got_error_from_errno2("realpath",
4662 optarg);
4663 got_path_strip_trailing_slashes(repo_path);
4664 break;
4665 case 'l':
4666 do_list = 1;
4667 break;
4668 case 'n':
4669 do_update = 0;
4670 break;
4671 default:
4672 usage_branch();
4673 /* NOTREACHED */
4677 if (do_list && delref)
4678 errx(1, "-l and -d options are mutually exclusive");
4680 argc -= optind;
4681 argv += optind;
4683 if (!do_list && !delref && argc == 0)
4684 do_show = 1;
4686 if ((do_list || delref || do_show) && commit_id_arg != NULL)
4687 errx(1, "-c option can only be used when creating a branch");
4689 if (do_list || delref) {
4690 if (argc > 0)
4691 usage_branch();
4692 } else if (!do_show && argc != 1)
4693 usage_branch();
4695 #ifndef PROFILE
4696 if (do_list || do_show) {
4697 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4698 NULL) == -1)
4699 err(1, "pledge");
4700 } else {
4701 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4702 "sendfd unveil", NULL) == -1)
4703 err(1, "pledge");
4705 #endif
4706 cwd = getcwd(NULL, 0);
4707 if (cwd == NULL) {
4708 error = got_error_from_errno("getcwd");
4709 goto done;
4712 if (repo_path == NULL) {
4713 error = got_worktree_open(&worktree, cwd);
4714 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4715 goto done;
4716 else
4717 error = NULL;
4718 if (worktree) {
4719 repo_path =
4720 strdup(got_worktree_get_repo_path(worktree));
4721 if (repo_path == NULL)
4722 error = got_error_from_errno("strdup");
4723 if (error)
4724 goto done;
4725 } else {
4726 repo_path = strdup(cwd);
4727 if (repo_path == NULL) {
4728 error = got_error_from_errno("strdup");
4729 goto done;
4734 error = got_repo_open(&repo, repo_path, NULL);
4735 if (error != NULL)
4736 goto done;
4738 error = apply_unveil(got_repo_get_path(repo), do_list,
4739 worktree ? got_worktree_get_root_path(worktree) : NULL);
4740 if (error)
4741 goto done;
4743 if (do_show)
4744 error = show_current_branch(repo, worktree);
4745 else if (do_list)
4746 error = list_branches(repo, worktree);
4747 else if (delref)
4748 error = delete_branch(repo, worktree, delref);
4749 else {
4750 if (commit_id_arg == NULL)
4751 commit_id_arg = worktree ?
4752 got_worktree_get_head_ref_name(worktree) :
4753 GOT_REF_HEAD;
4754 error = got_repo_match_object_id(&commit_id, NULL,
4755 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
4756 if (error)
4757 goto done;
4758 error = add_branch(repo, argv[0], commit_id);
4759 if (error)
4760 goto done;
4761 if (worktree && do_update) {
4762 int did_something = 0;
4763 char *branch_refname = NULL;
4765 error = got_object_id_str(&commit_id_str, commit_id);
4766 if (error)
4767 goto done;
4768 error = get_worktree_paths_from_argv(&paths, 0, NULL,
4769 worktree);
4770 if (error)
4771 goto done;
4772 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
4773 == -1) {
4774 error = got_error_from_errno("asprintf");
4775 goto done;
4777 error = got_ref_open(&ref, repo, branch_refname, 0);
4778 free(branch_refname);
4779 if (error)
4780 goto done;
4781 error = switch_head_ref(ref, commit_id, worktree,
4782 repo);
4783 if (error)
4784 goto done;
4785 error = got_worktree_set_base_commit_id(worktree, repo,
4786 commit_id);
4787 if (error)
4788 goto done;
4789 error = got_worktree_checkout_files(worktree, &paths,
4790 repo, update_progress, &did_something,
4791 check_cancelled, NULL);
4792 if (error)
4793 goto done;
4794 if (did_something)
4795 printf("Updated to commit %s\n", commit_id_str);
4798 done:
4799 if (ref)
4800 got_ref_close(ref);
4801 if (repo)
4802 got_repo_close(repo);
4803 if (worktree)
4804 got_worktree_close(worktree);
4805 free(cwd);
4806 free(repo_path);
4807 free(commit_id);
4808 free(commit_id_str);
4809 TAILQ_FOREACH(pe, &paths, entry)
4810 free((char *)pe->path);
4811 got_pathlist_free(&paths);
4812 return error;
4816 __dead static void
4817 usage_tag(void)
4819 fprintf(stderr,
4820 "usage: %s tag [-c commit] [-r repository] [-l] "
4821 "[-m message] name\n", getprogname());
4822 exit(1);
4825 #if 0
4826 static const struct got_error *
4827 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
4829 const struct got_error *err = NULL;
4830 struct got_reflist_entry *re, *se, *new;
4831 struct got_object_id *re_id, *se_id;
4832 struct got_tag_object *re_tag, *se_tag;
4833 time_t re_time, se_time;
4835 SIMPLEQ_FOREACH(re, tags, entry) {
4836 se = SIMPLEQ_FIRST(sorted);
4837 if (se == NULL) {
4838 err = got_reflist_entry_dup(&new, re);
4839 if (err)
4840 return err;
4841 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
4842 continue;
4843 } else {
4844 err = got_ref_resolve(&re_id, repo, re->ref);
4845 if (err)
4846 break;
4847 err = got_object_open_as_tag(&re_tag, repo, re_id);
4848 free(re_id);
4849 if (err)
4850 break;
4851 re_time = got_object_tag_get_tagger_time(re_tag);
4852 got_object_tag_close(re_tag);
4855 while (se) {
4856 err = got_ref_resolve(&se_id, repo, re->ref);
4857 if (err)
4858 break;
4859 err = got_object_open_as_tag(&se_tag, repo, se_id);
4860 free(se_id);
4861 if (err)
4862 break;
4863 se_time = got_object_tag_get_tagger_time(se_tag);
4864 got_object_tag_close(se_tag);
4866 if (se_time > re_time) {
4867 err = got_reflist_entry_dup(&new, re);
4868 if (err)
4869 return err;
4870 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
4871 break;
4873 se = SIMPLEQ_NEXT(se, entry);
4874 continue;
4877 done:
4878 return err;
4880 #endif
4882 static const struct got_error *
4883 list_tags(struct got_repository *repo, struct got_worktree *worktree)
4885 static const struct got_error *err = NULL;
4886 struct got_reflist_head refs;
4887 struct got_reflist_entry *re;
4889 SIMPLEQ_INIT(&refs);
4891 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
4892 if (err)
4893 return err;
4895 SIMPLEQ_FOREACH(re, &refs, entry) {
4896 const char *refname;
4897 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
4898 char datebuf[26];
4899 const char *tagger;
4900 time_t tagger_time;
4901 struct got_object_id *id;
4902 struct got_tag_object *tag;
4903 struct got_commit_object *commit = NULL;
4905 refname = got_ref_get_name(re->ref);
4906 if (strncmp(refname, "refs/tags/", 10) != 0)
4907 continue;
4908 refname += 10;
4909 refstr = got_ref_to_str(re->ref);
4910 if (refstr == NULL) {
4911 err = got_error_from_errno("got_ref_to_str");
4912 break;
4914 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
4915 free(refstr);
4917 err = got_ref_resolve(&id, repo, re->ref);
4918 if (err)
4919 break;
4920 err = got_object_open_as_tag(&tag, repo, id);
4921 if (err) {
4922 if (err->code != GOT_ERR_OBJ_TYPE) {
4923 free(id);
4924 break;
4926 /* "lightweight" tag */
4927 err = got_object_open_as_commit(&commit, repo, id);
4928 if (err) {
4929 free(id);
4930 break;
4932 tagger = got_object_commit_get_committer(commit);
4933 tagger_time =
4934 got_object_commit_get_committer_time(commit);
4935 err = got_object_id_str(&id_str, id);
4936 free(id);
4937 if (err)
4938 break;
4939 } else {
4940 free(id);
4941 tagger = got_object_tag_get_tagger(tag);
4942 tagger_time = got_object_tag_get_tagger_time(tag);
4943 err = got_object_id_str(&id_str,
4944 got_object_tag_get_object_id(tag));
4945 if (err)
4946 break;
4948 printf("from: %s\n", tagger);
4949 datestr = get_datestr(&tagger_time, datebuf);
4950 if (datestr)
4951 printf("date: %s UTC\n", datestr);
4952 if (commit)
4953 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
4954 else {
4955 switch (got_object_tag_get_object_type(tag)) {
4956 case GOT_OBJ_TYPE_BLOB:
4957 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
4958 id_str);
4959 break;
4960 case GOT_OBJ_TYPE_TREE:
4961 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
4962 id_str);
4963 break;
4964 case GOT_OBJ_TYPE_COMMIT:
4965 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
4966 id_str);
4967 break;
4968 case GOT_OBJ_TYPE_TAG:
4969 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
4970 id_str);
4971 break;
4972 default:
4973 break;
4976 free(id_str);
4977 if (commit) {
4978 err = got_object_commit_get_logmsg(&tagmsg0, commit);
4979 if (err)
4980 break;
4981 got_object_commit_close(commit);
4982 } else {
4983 tagmsg0 = strdup(got_object_tag_get_message(tag));
4984 got_object_tag_close(tag);
4985 if (tagmsg0 == NULL) {
4986 err = got_error_from_errno("strdup");
4987 break;
4991 tagmsg = tagmsg0;
4992 do {
4993 line = strsep(&tagmsg, "\n");
4994 if (line)
4995 printf(" %s\n", line);
4996 } while (line);
4997 free(tagmsg0);
5000 got_ref_list_free(&refs);
5001 return NULL;
5004 static const struct got_error *
5005 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5006 const char *tag_name, const char *repo_path)
5008 const struct got_error *err = NULL;
5009 char *template = NULL, *initial_content = NULL;
5010 char *editor = NULL;
5011 int fd = -1;
5013 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5014 err = got_error_from_errno("asprintf");
5015 goto done;
5018 if (asprintf(&initial_content, "\n# tagging commit %s as %s\n",
5019 commit_id_str, tag_name) == -1) {
5020 err = got_error_from_errno("asprintf");
5021 goto done;
5024 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5025 if (err)
5026 goto done;
5028 dprintf(fd, initial_content);
5029 close(fd);
5031 err = get_editor(&editor);
5032 if (err)
5033 goto done;
5034 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
5035 done:
5036 free(initial_content);
5037 free(template);
5038 free(editor);
5040 /* Editor is done; we can now apply unveil(2) */
5041 if (err == NULL) {
5042 err = apply_unveil(repo_path, 0, NULL);
5043 if (err) {
5044 free(*tagmsg);
5045 *tagmsg = NULL;
5048 return err;
5051 static const struct got_error *
5052 add_tag(struct got_repository *repo, const char *tag_name,
5053 const char *commit_arg, const char *tagmsg_arg)
5055 const struct got_error *err = NULL;
5056 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5057 char *label = NULL, *commit_id_str = NULL;
5058 struct got_reference *ref = NULL;
5059 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5060 char *tagmsg_path = NULL, *tag_id_str = NULL;
5061 int preserve_tagmsg = 0;
5064 * Don't let the user create a tag name with a leading '-'.
5065 * While technically a valid reference name, this case is usually
5066 * an unintended typo.
5068 if (tag_name[0] == '-')
5069 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5071 err = get_author(&tagger, repo);
5072 if (err)
5073 return err;
5075 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5076 GOT_OBJ_TYPE_COMMIT, 1, repo);
5077 if (err)
5078 goto done;
5080 err = got_object_id_str(&commit_id_str, commit_id);
5081 if (err)
5082 goto done;
5084 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5085 refname = strdup(tag_name);
5086 if (refname == NULL) {
5087 err = got_error_from_errno("strdup");
5088 goto done;
5090 tag_name += 10;
5091 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5092 err = got_error_from_errno("asprintf");
5093 goto done;
5096 err = got_ref_open(&ref, repo, refname, 0);
5097 if (err == NULL) {
5098 err = got_error(GOT_ERR_TAG_EXISTS);
5099 goto done;
5100 } else if (err->code != GOT_ERR_NOT_REF)
5101 goto done;
5103 if (tagmsg_arg == NULL) {
5104 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5105 tag_name, got_repo_get_path(repo));
5106 if (err) {
5107 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5108 tagmsg_path != NULL)
5109 preserve_tagmsg = 1;
5110 goto done;
5114 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5115 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5116 if (err) {
5117 if (tagmsg_path)
5118 preserve_tagmsg = 1;
5119 goto done;
5122 err = got_ref_alloc(&ref, refname, tag_id);
5123 if (err) {
5124 if (tagmsg_path)
5125 preserve_tagmsg = 1;
5126 goto done;
5129 err = got_ref_write(ref, repo);
5130 if (err) {
5131 if (tagmsg_path)
5132 preserve_tagmsg = 1;
5133 goto done;
5136 err = got_object_id_str(&tag_id_str, tag_id);
5137 if (err) {
5138 if (tagmsg_path)
5139 preserve_tagmsg = 1;
5140 goto done;
5142 printf("Created tag %s\n", tag_id_str);
5143 done:
5144 if (preserve_tagmsg) {
5145 fprintf(stderr, "%s: tag message preserved in %s\n",
5146 getprogname(), tagmsg_path);
5147 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
5148 err = got_error_from_errno2("unlink", tagmsg_path);
5149 free(tag_id_str);
5150 if (ref)
5151 got_ref_close(ref);
5152 free(commit_id);
5153 free(commit_id_str);
5154 free(refname);
5155 free(tagmsg);
5156 free(tagmsg_path);
5157 free(tagger);
5158 return err;
5161 static const struct got_error *
5162 cmd_tag(int argc, char *argv[])
5164 const struct got_error *error = NULL;
5165 struct got_repository *repo = NULL;
5166 struct got_worktree *worktree = NULL;
5167 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
5168 char *gitconfig_path = NULL;
5169 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
5170 int ch, do_list = 0;
5172 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
5173 switch (ch) {
5174 case 'c':
5175 commit_id_arg = optarg;
5176 break;
5177 case 'm':
5178 tagmsg = optarg;
5179 break;
5180 case 'r':
5181 repo_path = realpath(optarg, NULL);
5182 if (repo_path == NULL)
5183 return got_error_from_errno2("realpath",
5184 optarg);
5185 got_path_strip_trailing_slashes(repo_path);
5186 break;
5187 case 'l':
5188 do_list = 1;
5189 break;
5190 default:
5191 usage_tag();
5192 /* NOTREACHED */
5196 argc -= optind;
5197 argv += optind;
5199 if (do_list) {
5200 if (commit_id_arg != NULL)
5201 errx(1,
5202 "-c option can only be used when creating a tag");
5203 if (tagmsg)
5204 errx(1, "-l and -m options are mutually exclusive");
5205 if (argc > 0)
5206 usage_tag();
5207 } else if (argc != 1)
5208 usage_tag();
5210 tag_name = argv[0];
5212 #ifndef PROFILE
5213 if (do_list) {
5214 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5215 NULL) == -1)
5216 err(1, "pledge");
5217 } else {
5218 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5219 "sendfd unveil", NULL) == -1)
5220 err(1, "pledge");
5222 #endif
5223 cwd = getcwd(NULL, 0);
5224 if (cwd == NULL) {
5225 error = got_error_from_errno("getcwd");
5226 goto done;
5229 if (repo_path == NULL) {
5230 error = got_worktree_open(&worktree, cwd);
5231 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5232 goto done;
5233 else
5234 error = NULL;
5235 if (worktree) {
5236 repo_path =
5237 strdup(got_worktree_get_repo_path(worktree));
5238 if (repo_path == NULL)
5239 error = got_error_from_errno("strdup");
5240 if (error)
5241 goto done;
5242 } else {
5243 repo_path = strdup(cwd);
5244 if (repo_path == NULL) {
5245 error = got_error_from_errno("strdup");
5246 goto done;
5251 if (do_list) {
5252 error = got_repo_open(&repo, repo_path, NULL);
5253 if (error != NULL)
5254 goto done;
5255 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5256 if (error)
5257 goto done;
5258 error = list_tags(repo, worktree);
5259 } else {
5260 error = get_gitconfig_path(&gitconfig_path);
5261 if (error)
5262 goto done;
5263 error = got_repo_open(&repo, repo_path, gitconfig_path);
5264 if (error != NULL)
5265 goto done;
5267 if (tagmsg) {
5268 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5269 if (error)
5270 goto done;
5273 if (commit_id_arg == NULL) {
5274 struct got_reference *head_ref;
5275 struct got_object_id *commit_id;
5276 error = got_ref_open(&head_ref, repo,
5277 worktree ? got_worktree_get_head_ref_name(worktree)
5278 : GOT_REF_HEAD, 0);
5279 if (error)
5280 goto done;
5281 error = got_ref_resolve(&commit_id, repo, head_ref);
5282 got_ref_close(head_ref);
5283 if (error)
5284 goto done;
5285 error = got_object_id_str(&commit_id_str, commit_id);
5286 free(commit_id);
5287 if (error)
5288 goto done;
5291 error = add_tag(repo, tag_name,
5292 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
5294 done:
5295 if (repo)
5296 got_repo_close(repo);
5297 if (worktree)
5298 got_worktree_close(worktree);
5299 free(cwd);
5300 free(repo_path);
5301 free(gitconfig_path);
5302 free(commit_id_str);
5303 return error;
5306 __dead static void
5307 usage_add(void)
5309 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
5310 getprogname());
5311 exit(1);
5314 static const struct got_error *
5315 add_progress(void *arg, unsigned char status, const char *path)
5317 while (path[0] == '/')
5318 path++;
5319 printf("%c %s\n", status, path);
5320 return NULL;
5323 static const struct got_error *
5324 cmd_add(int argc, char *argv[])
5326 const struct got_error *error = NULL;
5327 struct got_repository *repo = NULL;
5328 struct got_worktree *worktree = NULL;
5329 char *cwd = NULL;
5330 struct got_pathlist_head paths;
5331 struct got_pathlist_entry *pe;
5332 int ch, can_recurse = 0, no_ignores = 0;
5334 TAILQ_INIT(&paths);
5336 while ((ch = getopt(argc, argv, "IR")) != -1) {
5337 switch (ch) {
5338 case 'I':
5339 no_ignores = 1;
5340 break;
5341 case 'R':
5342 can_recurse = 1;
5343 break;
5344 default:
5345 usage_add();
5346 /* NOTREACHED */
5350 argc -= optind;
5351 argv += optind;
5353 #ifndef PROFILE
5354 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5355 NULL) == -1)
5356 err(1, "pledge");
5357 #endif
5358 if (argc < 1)
5359 usage_add();
5361 cwd = getcwd(NULL, 0);
5362 if (cwd == NULL) {
5363 error = got_error_from_errno("getcwd");
5364 goto done;
5367 error = got_worktree_open(&worktree, cwd);
5368 if (error)
5369 goto done;
5371 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5372 NULL);
5373 if (error != NULL)
5374 goto done;
5376 error = apply_unveil(got_repo_get_path(repo), 1,
5377 got_worktree_get_root_path(worktree));
5378 if (error)
5379 goto done;
5381 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5382 if (error)
5383 goto done;
5385 if (!can_recurse && no_ignores) {
5386 error = got_error_msg(GOT_ERR_BAD_PATH,
5387 "disregarding ignores requires -R option");
5388 goto done;
5392 if (!can_recurse) {
5393 char *ondisk_path;
5394 struct stat sb;
5395 TAILQ_FOREACH(pe, &paths, entry) {
5396 if (asprintf(&ondisk_path, "%s/%s",
5397 got_worktree_get_root_path(worktree),
5398 pe->path) == -1) {
5399 error = got_error_from_errno("asprintf");
5400 goto done;
5402 if (lstat(ondisk_path, &sb) == -1) {
5403 if (errno == ENOENT) {
5404 free(ondisk_path);
5405 continue;
5407 error = got_error_from_errno2("lstat",
5408 ondisk_path);
5409 free(ondisk_path);
5410 goto done;
5412 free(ondisk_path);
5413 if (S_ISDIR(sb.st_mode)) {
5414 error = got_error_msg(GOT_ERR_BAD_PATH,
5415 "adding directories requires -R option");
5416 goto done;
5421 error = got_worktree_schedule_add(worktree, &paths, add_progress,
5422 NULL, repo, no_ignores);
5423 done:
5424 if (repo)
5425 got_repo_close(repo);
5426 if (worktree)
5427 got_worktree_close(worktree);
5428 TAILQ_FOREACH(pe, &paths, entry)
5429 free((char *)pe->path);
5430 got_pathlist_free(&paths);
5431 free(cwd);
5432 return error;
5435 __dead static void
5436 usage_remove(void)
5438 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] path ...\n",
5439 getprogname());
5440 exit(1);
5443 static const struct got_error *
5444 print_remove_status(void *arg, unsigned char status,
5445 unsigned char staged_status, const char *path)
5447 while (path[0] == '/')
5448 path++;
5449 if (status == GOT_STATUS_NONEXISTENT)
5450 return NULL;
5451 if (status == staged_status && (status == GOT_STATUS_DELETE))
5452 status = GOT_STATUS_NO_CHANGE;
5453 printf("%c%c %s\n", status, staged_status, path);
5454 return NULL;
5457 static const struct got_error *
5458 cmd_remove(int argc, char *argv[])
5460 const struct got_error *error = NULL;
5461 struct got_worktree *worktree = NULL;
5462 struct got_repository *repo = NULL;
5463 char *cwd = NULL;
5464 struct got_pathlist_head paths;
5465 struct got_pathlist_entry *pe;
5466 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0;
5468 TAILQ_INIT(&paths);
5470 while ((ch = getopt(argc, argv, "fkR")) != -1) {
5471 switch (ch) {
5472 case 'f':
5473 delete_local_mods = 1;
5474 break;
5475 case 'k':
5476 keep_on_disk = 1;
5477 break;
5478 case 'R':
5479 can_recurse = 1;
5480 break;
5481 default:
5482 usage_remove();
5483 /* NOTREACHED */
5487 argc -= optind;
5488 argv += optind;
5490 #ifndef PROFILE
5491 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5492 NULL) == -1)
5493 err(1, "pledge");
5494 #endif
5495 if (argc < 1)
5496 usage_remove();
5498 cwd = getcwd(NULL, 0);
5499 if (cwd == NULL) {
5500 error = got_error_from_errno("getcwd");
5501 goto done;
5503 error = got_worktree_open(&worktree, cwd);
5504 if (error)
5505 goto done;
5507 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5508 NULL);
5509 if (error)
5510 goto done;
5512 error = apply_unveil(got_repo_get_path(repo), 1,
5513 got_worktree_get_root_path(worktree));
5514 if (error)
5515 goto done;
5517 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5518 if (error)
5519 goto done;
5521 if (!can_recurse) {
5522 char *ondisk_path;
5523 struct stat sb;
5524 TAILQ_FOREACH(pe, &paths, entry) {
5525 if (asprintf(&ondisk_path, "%s/%s",
5526 got_worktree_get_root_path(worktree),
5527 pe->path) == -1) {
5528 error = got_error_from_errno("asprintf");
5529 goto done;
5531 if (lstat(ondisk_path, &sb) == -1) {
5532 if (errno == ENOENT) {
5533 free(ondisk_path);
5534 continue;
5536 error = got_error_from_errno2("lstat",
5537 ondisk_path);
5538 free(ondisk_path);
5539 goto done;
5541 free(ondisk_path);
5542 if (S_ISDIR(sb.st_mode)) {
5543 error = got_error_msg(GOT_ERR_BAD_PATH,
5544 "removing directories requires -R option");
5545 goto done;
5550 error = got_worktree_schedule_delete(worktree, &paths,
5551 delete_local_mods, print_remove_status, NULL, repo, keep_on_disk);
5552 done:
5553 if (repo)
5554 got_repo_close(repo);
5555 if (worktree)
5556 got_worktree_close(worktree);
5557 TAILQ_FOREACH(pe, &paths, entry)
5558 free((char *)pe->path);
5559 got_pathlist_free(&paths);
5560 free(cwd);
5561 return error;
5564 __dead static void
5565 usage_revert(void)
5567 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
5568 "path ...\n", getprogname());
5569 exit(1);
5572 static const struct got_error *
5573 revert_progress(void *arg, unsigned char status, const char *path)
5575 if (status == GOT_STATUS_UNVERSIONED)
5576 return NULL;
5578 while (path[0] == '/')
5579 path++;
5580 printf("%c %s\n", status, path);
5581 return NULL;
5584 struct choose_patch_arg {
5585 FILE *patch_script_file;
5586 const char *action;
5589 static const struct got_error *
5590 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
5591 int nchanges, const char *action)
5593 char *line = NULL;
5594 size_t linesize = 0;
5595 ssize_t linelen;
5597 switch (status) {
5598 case GOT_STATUS_ADD:
5599 printf("A %s\n%s this addition? [y/n] ", path, action);
5600 break;
5601 case GOT_STATUS_DELETE:
5602 printf("D %s\n%s this deletion? [y/n] ", path, action);
5603 break;
5604 case GOT_STATUS_MODIFY:
5605 if (fseek(patch_file, 0L, SEEK_SET) == -1)
5606 return got_error_from_errno("fseek");
5607 printf(GOT_COMMIT_SEP_STR);
5608 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
5609 printf("%s", line);
5610 if (ferror(patch_file))
5611 return got_error_from_errno("getline");
5612 printf(GOT_COMMIT_SEP_STR);
5613 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
5614 path, n, nchanges, action);
5615 break;
5616 default:
5617 return got_error_path(path, GOT_ERR_FILE_STATUS);
5620 return NULL;
5623 static const struct got_error *
5624 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
5625 FILE *patch_file, int n, int nchanges)
5627 const struct got_error *err = NULL;
5628 char *line = NULL;
5629 size_t linesize = 0;
5630 ssize_t linelen;
5631 int resp = ' ';
5632 struct choose_patch_arg *a = arg;
5634 *choice = GOT_PATCH_CHOICE_NONE;
5636 if (a->patch_script_file) {
5637 char *nl;
5638 err = show_change(status, path, patch_file, n, nchanges,
5639 a->action);
5640 if (err)
5641 return err;
5642 linelen = getline(&line, &linesize, a->patch_script_file);
5643 if (linelen == -1) {
5644 if (ferror(a->patch_script_file))
5645 return got_error_from_errno("getline");
5646 return NULL;
5648 nl = strchr(line, '\n');
5649 if (nl)
5650 *nl = '\0';
5651 if (strcmp(line, "y") == 0) {
5652 *choice = GOT_PATCH_CHOICE_YES;
5653 printf("y\n");
5654 } else if (strcmp(line, "n") == 0) {
5655 *choice = GOT_PATCH_CHOICE_NO;
5656 printf("n\n");
5657 } else if (strcmp(line, "q") == 0 &&
5658 status == GOT_STATUS_MODIFY) {
5659 *choice = GOT_PATCH_CHOICE_QUIT;
5660 printf("q\n");
5661 } else
5662 printf("invalid response '%s'\n", line);
5663 free(line);
5664 return NULL;
5667 while (resp != 'y' && resp != 'n' && resp != 'q') {
5668 err = show_change(status, path, patch_file, n, nchanges,
5669 a->action);
5670 if (err)
5671 return err;
5672 resp = getchar();
5673 if (resp == '\n')
5674 resp = getchar();
5675 if (status == GOT_STATUS_MODIFY) {
5676 if (resp != 'y' && resp != 'n' && resp != 'q') {
5677 printf("invalid response '%c'\n", resp);
5678 resp = ' ';
5680 } else if (resp != 'y' && resp != 'n') {
5681 printf("invalid response '%c'\n", resp);
5682 resp = ' ';
5686 if (resp == 'y')
5687 *choice = GOT_PATCH_CHOICE_YES;
5688 else if (resp == 'n')
5689 *choice = GOT_PATCH_CHOICE_NO;
5690 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
5691 *choice = GOT_PATCH_CHOICE_QUIT;
5693 return NULL;
5697 static const struct got_error *
5698 cmd_revert(int argc, char *argv[])
5700 const struct got_error *error = NULL;
5701 struct got_worktree *worktree = NULL;
5702 struct got_repository *repo = NULL;
5703 char *cwd = NULL, *path = NULL;
5704 struct got_pathlist_head paths;
5705 struct got_pathlist_entry *pe;
5706 int ch, can_recurse = 0, pflag = 0;
5707 FILE *patch_script_file = NULL;
5708 const char *patch_script_path = NULL;
5709 struct choose_patch_arg cpa;
5711 TAILQ_INIT(&paths);
5713 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
5714 switch (ch) {
5715 case 'p':
5716 pflag = 1;
5717 break;
5718 case 'F':
5719 patch_script_path = optarg;
5720 break;
5721 case 'R':
5722 can_recurse = 1;
5723 break;
5724 default:
5725 usage_revert();
5726 /* NOTREACHED */
5730 argc -= optind;
5731 argv += optind;
5733 #ifndef PROFILE
5734 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
5735 "unveil", NULL) == -1)
5736 err(1, "pledge");
5737 #endif
5738 if (argc < 1)
5739 usage_revert();
5740 if (patch_script_path && !pflag)
5741 errx(1, "-F option can only be used together with -p option");
5743 cwd = getcwd(NULL, 0);
5744 if (cwd == NULL) {
5745 error = got_error_from_errno("getcwd");
5746 goto done;
5748 error = got_worktree_open(&worktree, cwd);
5749 if (error)
5750 goto done;
5752 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5753 NULL);
5754 if (error != NULL)
5755 goto done;
5757 if (patch_script_path) {
5758 patch_script_file = fopen(patch_script_path, "r");
5759 if (patch_script_file == NULL) {
5760 error = got_error_from_errno2("fopen",
5761 patch_script_path);
5762 goto done;
5765 error = apply_unveil(got_repo_get_path(repo), 1,
5766 got_worktree_get_root_path(worktree));
5767 if (error)
5768 goto done;
5770 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5771 if (error)
5772 goto done;
5774 if (!can_recurse) {
5775 char *ondisk_path;
5776 struct stat sb;
5777 TAILQ_FOREACH(pe, &paths, entry) {
5778 if (asprintf(&ondisk_path, "%s/%s",
5779 got_worktree_get_root_path(worktree),
5780 pe->path) == -1) {
5781 error = got_error_from_errno("asprintf");
5782 goto done;
5784 if (lstat(ondisk_path, &sb) == -1) {
5785 if (errno == ENOENT) {
5786 free(ondisk_path);
5787 continue;
5789 error = got_error_from_errno2("lstat",
5790 ondisk_path);
5791 free(ondisk_path);
5792 goto done;
5794 free(ondisk_path);
5795 if (S_ISDIR(sb.st_mode)) {
5796 error = got_error_msg(GOT_ERR_BAD_PATH,
5797 "reverting directories requires -R option");
5798 goto done;
5803 cpa.patch_script_file = patch_script_file;
5804 cpa.action = "revert";
5805 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
5806 pflag ? choose_patch : NULL, &cpa, repo);
5807 done:
5808 if (patch_script_file && fclose(patch_script_file) == EOF &&
5809 error == NULL)
5810 error = got_error_from_errno2("fclose", patch_script_path);
5811 if (repo)
5812 got_repo_close(repo);
5813 if (worktree)
5814 got_worktree_close(worktree);
5815 free(path);
5816 free(cwd);
5817 return error;
5820 __dead static void
5821 usage_commit(void)
5823 fprintf(stderr, "usage: %s commit [-m msg] [path ...]\n",
5824 getprogname());
5825 exit(1);
5828 struct collect_commit_logmsg_arg {
5829 const char *cmdline_log;
5830 const char *editor;
5831 const char *worktree_path;
5832 const char *branch_name;
5833 const char *repo_path;
5834 char *logmsg_path;
5838 static const struct got_error *
5839 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
5840 void *arg)
5842 char *initial_content = NULL;
5843 struct got_pathlist_entry *pe;
5844 const struct got_error *err = NULL;
5845 char *template = NULL;
5846 struct collect_commit_logmsg_arg *a = arg;
5847 int fd;
5848 size_t len;
5850 /* if a message was specified on the command line, just use it */
5851 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
5852 len = strlen(a->cmdline_log) + 1;
5853 *logmsg = malloc(len + 1);
5854 if (*logmsg == NULL)
5855 return got_error_from_errno("malloc");
5856 strlcpy(*logmsg, a->cmdline_log, len);
5857 return NULL;
5860 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
5861 return got_error_from_errno("asprintf");
5863 if (asprintf(&initial_content,
5864 "\n# changes to be committed on branch %s:\n",
5865 a->branch_name) == -1)
5866 return got_error_from_errno("asprintf");
5868 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
5869 if (err)
5870 goto done;
5872 dprintf(fd, initial_content);
5874 TAILQ_FOREACH(pe, commitable_paths, entry) {
5875 struct got_commitable *ct = pe->data;
5876 dprintf(fd, "# %c %s\n",
5877 got_commitable_get_status(ct),
5878 got_commitable_get_path(ct));
5880 close(fd);
5882 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
5883 done:
5884 free(initial_content);
5885 free(template);
5887 /* Editor is done; we can now apply unveil(2) */
5888 if (err == NULL) {
5889 err = apply_unveil(a->repo_path, 0, a->worktree_path);
5890 if (err) {
5891 free(*logmsg);
5892 *logmsg = NULL;
5895 return err;
5898 static const struct got_error *
5899 cmd_commit(int argc, char *argv[])
5901 const struct got_error *error = NULL;
5902 struct got_worktree *worktree = NULL;
5903 struct got_repository *repo = NULL;
5904 char *cwd = NULL, *id_str = NULL;
5905 struct got_object_id *id = NULL;
5906 const char *logmsg = NULL;
5907 struct collect_commit_logmsg_arg cl_arg;
5908 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
5909 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
5910 struct got_pathlist_head paths;
5912 TAILQ_INIT(&paths);
5913 cl_arg.logmsg_path = NULL;
5915 while ((ch = getopt(argc, argv, "m:")) != -1) {
5916 switch (ch) {
5917 case 'm':
5918 logmsg = optarg;
5919 break;
5920 default:
5921 usage_commit();
5922 /* NOTREACHED */
5926 argc -= optind;
5927 argv += optind;
5929 #ifndef PROFILE
5930 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
5931 "unveil", NULL) == -1)
5932 err(1, "pledge");
5933 #endif
5934 cwd = getcwd(NULL, 0);
5935 if (cwd == NULL) {
5936 error = got_error_from_errno("getcwd");
5937 goto done;
5939 error = got_worktree_open(&worktree, cwd);
5940 if (error)
5941 goto done;
5943 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
5944 if (error)
5945 goto done;
5946 if (rebase_in_progress) {
5947 error = got_error(GOT_ERR_REBASING);
5948 goto done;
5951 error = got_worktree_histedit_in_progress(&histedit_in_progress,
5952 worktree);
5953 if (error)
5954 goto done;
5956 error = get_gitconfig_path(&gitconfig_path);
5957 if (error)
5958 goto done;
5959 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5960 gitconfig_path);
5961 if (error != NULL)
5962 goto done;
5964 error = get_author(&author, repo);
5965 if (error)
5966 return error;
5969 * unveil(2) traverses exec(2); if an editor is used we have
5970 * to apply unveil after the log message has been written.
5972 if (logmsg == NULL || strlen(logmsg) == 0)
5973 error = get_editor(&editor);
5974 else
5975 error = apply_unveil(got_repo_get_path(repo), 0,
5976 got_worktree_get_root_path(worktree));
5977 if (error)
5978 goto done;
5980 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5981 if (error)
5982 goto done;
5984 cl_arg.editor = editor;
5985 cl_arg.cmdline_log = logmsg;
5986 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
5987 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
5988 if (!histedit_in_progress) {
5989 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
5990 error = got_error(GOT_ERR_COMMIT_BRANCH);
5991 goto done;
5993 cl_arg.branch_name += 11;
5995 cl_arg.repo_path = got_repo_get_path(repo);
5996 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
5997 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
5998 if (error) {
5999 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6000 cl_arg.logmsg_path != NULL)
6001 preserve_logmsg = 1;
6002 goto done;
6005 error = got_object_id_str(&id_str, id);
6006 if (error)
6007 goto done;
6008 printf("Created commit %s\n", id_str);
6009 done:
6010 if (preserve_logmsg) {
6011 fprintf(stderr, "%s: log message preserved in %s\n",
6012 getprogname(), cl_arg.logmsg_path);
6013 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6014 error == NULL)
6015 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6016 free(cl_arg.logmsg_path);
6017 if (repo)
6018 got_repo_close(repo);
6019 if (worktree)
6020 got_worktree_close(worktree);
6021 free(cwd);
6022 free(id_str);
6023 free(gitconfig_path);
6024 free(editor);
6025 free(author);
6026 return error;
6029 __dead static void
6030 usage_cherrypick(void)
6032 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6033 exit(1);
6036 static const struct got_error *
6037 cmd_cherrypick(int argc, char *argv[])
6039 const struct got_error *error = NULL;
6040 struct got_worktree *worktree = NULL;
6041 struct got_repository *repo = NULL;
6042 char *cwd = NULL, *commit_id_str = NULL;
6043 struct got_object_id *commit_id = NULL;
6044 struct got_commit_object *commit = NULL;
6045 struct got_object_qid *pid;
6046 struct got_reference *head_ref = NULL;
6047 int ch, did_something = 0;
6049 while ((ch = getopt(argc, argv, "")) != -1) {
6050 switch (ch) {
6051 default:
6052 usage_cherrypick();
6053 /* NOTREACHED */
6057 argc -= optind;
6058 argv += optind;
6060 #ifndef PROFILE
6061 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6062 "unveil", NULL) == -1)
6063 err(1, "pledge");
6064 #endif
6065 if (argc != 1)
6066 usage_cherrypick();
6068 cwd = getcwd(NULL, 0);
6069 if (cwd == NULL) {
6070 error = got_error_from_errno("getcwd");
6071 goto done;
6073 error = got_worktree_open(&worktree, cwd);
6074 if (error)
6075 goto done;
6077 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6078 NULL);
6079 if (error != NULL)
6080 goto done;
6082 error = apply_unveil(got_repo_get_path(repo), 0,
6083 got_worktree_get_root_path(worktree));
6084 if (error)
6085 goto done;
6087 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6088 GOT_OBJ_TYPE_COMMIT, repo);
6089 if (error != NULL) {
6090 struct got_reference *ref;
6091 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6092 goto done;
6093 error = got_ref_open(&ref, repo, argv[0], 0);
6094 if (error != NULL)
6095 goto done;
6096 error = got_ref_resolve(&commit_id, repo, ref);
6097 got_ref_close(ref);
6098 if (error != NULL)
6099 goto done;
6101 error = got_object_id_str(&commit_id_str, commit_id);
6102 if (error)
6103 goto done;
6105 error = got_ref_open(&head_ref, repo,
6106 got_worktree_get_head_ref_name(worktree), 0);
6107 if (error != NULL)
6108 goto done;
6110 error = check_same_branch(commit_id, head_ref, NULL, repo);
6111 if (error) {
6112 if (error->code != GOT_ERR_ANCESTRY)
6113 goto done;
6114 error = NULL;
6115 } else {
6116 error = got_error(GOT_ERR_SAME_BRANCH);
6117 goto done;
6120 error = got_object_open_as_commit(&commit, repo, commit_id);
6121 if (error)
6122 goto done;
6123 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6124 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
6125 commit_id, repo, update_progress, &did_something, check_cancelled,
6126 NULL);
6127 if (error != NULL)
6128 goto done;
6130 if (did_something)
6131 printf("Merged commit %s\n", commit_id_str);
6132 done:
6133 if (commit)
6134 got_object_commit_close(commit);
6135 free(commit_id_str);
6136 if (head_ref)
6137 got_ref_close(head_ref);
6138 if (worktree)
6139 got_worktree_close(worktree);
6140 if (repo)
6141 got_repo_close(repo);
6142 return error;
6145 __dead static void
6146 usage_backout(void)
6148 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
6149 exit(1);
6152 static const struct got_error *
6153 cmd_backout(int argc, char *argv[])
6155 const struct got_error *error = NULL;
6156 struct got_worktree *worktree = NULL;
6157 struct got_repository *repo = NULL;
6158 char *cwd = NULL, *commit_id_str = NULL;
6159 struct got_object_id *commit_id = NULL;
6160 struct got_commit_object *commit = NULL;
6161 struct got_object_qid *pid;
6162 struct got_reference *head_ref = NULL;
6163 int ch, did_something = 0;
6165 while ((ch = getopt(argc, argv, "")) != -1) {
6166 switch (ch) {
6167 default:
6168 usage_backout();
6169 /* NOTREACHED */
6173 argc -= optind;
6174 argv += optind;
6176 #ifndef PROFILE
6177 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6178 "unveil", NULL) == -1)
6179 err(1, "pledge");
6180 #endif
6181 if (argc != 1)
6182 usage_backout();
6184 cwd = getcwd(NULL, 0);
6185 if (cwd == NULL) {
6186 error = got_error_from_errno("getcwd");
6187 goto done;
6189 error = got_worktree_open(&worktree, cwd);
6190 if (error)
6191 goto done;
6193 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6194 NULL);
6195 if (error != NULL)
6196 goto done;
6198 error = apply_unveil(got_repo_get_path(repo), 0,
6199 got_worktree_get_root_path(worktree));
6200 if (error)
6201 goto done;
6203 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6204 GOT_OBJ_TYPE_COMMIT, repo);
6205 if (error != NULL) {
6206 struct got_reference *ref;
6207 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6208 goto done;
6209 error = got_ref_open(&ref, repo, argv[0], 0);
6210 if (error != NULL)
6211 goto done;
6212 error = got_ref_resolve(&commit_id, repo, ref);
6213 got_ref_close(ref);
6214 if (error != NULL)
6215 goto done;
6217 error = got_object_id_str(&commit_id_str, commit_id);
6218 if (error)
6219 goto done;
6221 error = got_ref_open(&head_ref, repo,
6222 got_worktree_get_head_ref_name(worktree), 0);
6223 if (error != NULL)
6224 goto done;
6226 error = check_same_branch(commit_id, head_ref, NULL, repo);
6227 if (error)
6228 goto done;
6230 error = got_object_open_as_commit(&commit, repo, commit_id);
6231 if (error)
6232 goto done;
6233 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6234 if (pid == NULL) {
6235 error = got_error(GOT_ERR_ROOT_COMMIT);
6236 goto done;
6239 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
6240 update_progress, &did_something, check_cancelled, NULL);
6241 if (error != NULL)
6242 goto done;
6244 if (did_something)
6245 printf("Backed out commit %s\n", commit_id_str);
6246 done:
6247 if (commit)
6248 got_object_commit_close(commit);
6249 free(commit_id_str);
6250 if (head_ref)
6251 got_ref_close(head_ref);
6252 if (worktree)
6253 got_worktree_close(worktree);
6254 if (repo)
6255 got_repo_close(repo);
6256 return error;
6259 __dead static void
6260 usage_rebase(void)
6262 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
6263 getprogname());
6264 exit(1);
6267 void
6268 trim_logmsg(char *logmsg, int limit)
6270 char *nl;
6271 size_t len;
6273 len = strlen(logmsg);
6274 if (len > limit)
6275 len = limit;
6276 logmsg[len] = '\0';
6277 nl = strchr(logmsg, '\n');
6278 if (nl)
6279 *nl = '\0';
6282 static const struct got_error *
6283 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
6285 const struct got_error *err;
6286 char *logmsg0 = NULL;
6287 const char *s;
6289 err = got_object_commit_get_logmsg(&logmsg0, commit);
6290 if (err)
6291 return err;
6293 s = logmsg0;
6294 while (isspace((unsigned char)s[0]))
6295 s++;
6297 *logmsg = strdup(s);
6298 if (*logmsg == NULL) {
6299 err = got_error_from_errno("strdup");
6300 goto done;
6303 trim_logmsg(*logmsg, limit);
6304 done:
6305 free(logmsg0);
6306 return err;
6309 static const struct got_error *
6310 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
6312 const struct got_error *err;
6313 struct got_commit_object *commit = NULL;
6314 char *id_str = NULL, *logmsg = NULL;
6316 err = got_object_open_as_commit(&commit, repo, id);
6317 if (err)
6318 return err;
6320 err = got_object_id_str(&id_str, id);
6321 if (err)
6322 goto done;
6324 id_str[12] = '\0';
6326 err = get_short_logmsg(&logmsg, 42, commit);
6327 if (err)
6328 goto done;
6330 printf("%s -> merge conflict: %s\n", id_str, logmsg);
6331 done:
6332 free(id_str);
6333 got_object_commit_close(commit);
6334 free(logmsg);
6335 return err;
6338 static const struct got_error *
6339 show_rebase_progress(struct got_commit_object *commit,
6340 struct got_object_id *old_id, struct got_object_id *new_id)
6342 const struct got_error *err;
6343 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
6345 err = got_object_id_str(&old_id_str, old_id);
6346 if (err)
6347 goto done;
6349 if (new_id) {
6350 err = got_object_id_str(&new_id_str, new_id);
6351 if (err)
6352 goto done;
6355 old_id_str[12] = '\0';
6356 if (new_id_str)
6357 new_id_str[12] = '\0';
6359 err = get_short_logmsg(&logmsg, 42, commit);
6360 if (err)
6361 goto done;
6363 printf("%s -> %s: %s\n", old_id_str,
6364 new_id_str ? new_id_str : "no-op change", logmsg);
6365 done:
6366 free(old_id_str);
6367 free(new_id_str);
6368 free(logmsg);
6369 return err;
6372 static const struct got_error *
6373 rebase_progress(void *arg, unsigned char status, const char *path)
6375 unsigned char *rebase_status = arg;
6377 while (path[0] == '/')
6378 path++;
6379 printf("%c %s\n", status, path);
6381 if (*rebase_status == GOT_STATUS_CONFLICT)
6382 return NULL;
6383 if (status == GOT_STATUS_CONFLICT || status == GOT_STATUS_MERGE)
6384 *rebase_status = status;
6385 return NULL;
6388 static const struct got_error *
6389 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
6390 struct got_reference *branch, struct got_reference *new_base_branch,
6391 struct got_reference *tmp_branch, struct got_repository *repo)
6393 printf("Switching work tree to %s\n", got_ref_get_name(branch));
6394 return got_worktree_rebase_complete(worktree, fileindex,
6395 new_base_branch, tmp_branch, branch, repo);
6398 static const struct got_error *
6399 rebase_commit(struct got_pathlist_head *merged_paths,
6400 struct got_worktree *worktree, struct got_fileindex *fileindex,
6401 struct got_reference *tmp_branch,
6402 struct got_object_id *commit_id, struct got_repository *repo)
6404 const struct got_error *error;
6405 struct got_commit_object *commit;
6406 struct got_object_id *new_commit_id;
6408 error = got_object_open_as_commit(&commit, repo, commit_id);
6409 if (error)
6410 return error;
6412 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
6413 worktree, fileindex, tmp_branch, commit, commit_id, repo);
6414 if (error) {
6415 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
6416 goto done;
6417 error = show_rebase_progress(commit, commit_id, NULL);
6418 } else {
6419 error = show_rebase_progress(commit, commit_id, new_commit_id);
6420 free(new_commit_id);
6422 done:
6423 got_object_commit_close(commit);
6424 return error;
6427 struct check_path_prefix_arg {
6428 const char *path_prefix;
6429 size_t len;
6430 int errcode;
6433 static const struct got_error *
6434 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
6435 struct got_blob_object *blob2, struct got_object_id *id1,
6436 struct got_object_id *id2, const char *path1, const char *path2,
6437 mode_t mode1, mode_t mode2, struct got_repository *repo)
6439 struct check_path_prefix_arg *a = arg;
6441 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
6442 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
6443 return got_error(a->errcode);
6445 return NULL;
6448 static const struct got_error *
6449 check_path_prefix(struct got_object_id *parent_id,
6450 struct got_object_id *commit_id, const char *path_prefix,
6451 int errcode, struct got_repository *repo)
6453 const struct got_error *err;
6454 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
6455 struct got_commit_object *commit = NULL, *parent_commit = NULL;
6456 struct check_path_prefix_arg cpp_arg;
6458 if (got_path_is_root_dir(path_prefix))
6459 return NULL;
6461 err = got_object_open_as_commit(&commit, repo, commit_id);
6462 if (err)
6463 goto done;
6465 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
6466 if (err)
6467 goto done;
6469 err = got_object_open_as_tree(&tree1, repo,
6470 got_object_commit_get_tree_id(parent_commit));
6471 if (err)
6472 goto done;
6474 err = got_object_open_as_tree(&tree2, repo,
6475 got_object_commit_get_tree_id(commit));
6476 if (err)
6477 goto done;
6479 cpp_arg.path_prefix = path_prefix;
6480 while (cpp_arg.path_prefix[0] == '/')
6481 cpp_arg.path_prefix++;
6482 cpp_arg.len = strlen(cpp_arg.path_prefix);
6483 cpp_arg.errcode = errcode;
6484 err = got_diff_tree(tree1, tree2, "", "", repo,
6485 check_path_prefix_in_diff, &cpp_arg, 0);
6486 done:
6487 if (tree1)
6488 got_object_tree_close(tree1);
6489 if (tree2)
6490 got_object_tree_close(tree2);
6491 if (commit)
6492 got_object_commit_close(commit);
6493 if (parent_commit)
6494 got_object_commit_close(parent_commit);
6495 return err;
6498 static const struct got_error *
6499 collect_commits(struct got_object_id_queue *commits,
6500 struct got_object_id *initial_commit_id,
6501 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
6502 const char *path_prefix, int path_prefix_errcode,
6503 struct got_repository *repo)
6505 const struct got_error *err = NULL;
6506 struct got_commit_graph *graph = NULL;
6507 struct got_object_id *parent_id = NULL;
6508 struct got_object_qid *qid;
6509 struct got_object_id *commit_id = initial_commit_id;
6511 err = got_commit_graph_open(&graph, "/", 1);
6512 if (err)
6513 return err;
6515 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
6516 check_cancelled, NULL);
6517 if (err)
6518 goto done;
6519 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
6520 err = got_commit_graph_iter_next(&parent_id, graph, repo,
6521 check_cancelled, NULL);
6522 if (err) {
6523 if (err->code == GOT_ERR_ITER_COMPLETED) {
6524 err = got_error_msg(GOT_ERR_ANCESTRY,
6525 "ran out of commits to rebase before "
6526 "youngest common ancestor commit has "
6527 "been reached?!?");
6529 goto done;
6530 } else {
6531 err = check_path_prefix(parent_id, commit_id,
6532 path_prefix, path_prefix_errcode, repo);
6533 if (err)
6534 goto done;
6536 err = got_object_qid_alloc(&qid, commit_id);
6537 if (err)
6538 goto done;
6539 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
6540 commit_id = parent_id;
6543 done:
6544 got_commit_graph_close(graph);
6545 return err;
6548 static const struct got_error *
6549 cmd_rebase(int argc, char *argv[])
6551 const struct got_error *error = NULL;
6552 struct got_worktree *worktree = NULL;
6553 struct got_repository *repo = NULL;
6554 struct got_fileindex *fileindex = NULL;
6555 char *cwd = NULL;
6556 struct got_reference *branch = NULL;
6557 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
6558 struct got_object_id *commit_id = NULL, *parent_id = NULL;
6559 struct got_object_id *resume_commit_id = NULL;
6560 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
6561 struct got_commit_object *commit = NULL;
6562 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
6563 int histedit_in_progress = 0;
6564 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
6565 struct got_object_id_queue commits;
6566 struct got_pathlist_head merged_paths;
6567 const struct got_object_id_queue *parent_ids;
6568 struct got_object_qid *qid, *pid;
6570 SIMPLEQ_INIT(&commits);
6571 TAILQ_INIT(&merged_paths);
6573 while ((ch = getopt(argc, argv, "ac")) != -1) {
6574 switch (ch) {
6575 case 'a':
6576 abort_rebase = 1;
6577 break;
6578 case 'c':
6579 continue_rebase = 1;
6580 break;
6581 default:
6582 usage_rebase();
6583 /* NOTREACHED */
6587 argc -= optind;
6588 argv += optind;
6590 #ifndef PROFILE
6591 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6592 "unveil", NULL) == -1)
6593 err(1, "pledge");
6594 #endif
6595 if (abort_rebase && continue_rebase)
6596 usage_rebase();
6597 else if (abort_rebase || continue_rebase) {
6598 if (argc != 0)
6599 usage_rebase();
6600 } else if (argc != 1)
6601 usage_rebase();
6603 cwd = getcwd(NULL, 0);
6604 if (cwd == NULL) {
6605 error = got_error_from_errno("getcwd");
6606 goto done;
6608 error = got_worktree_open(&worktree, cwd);
6609 if (error)
6610 goto done;
6612 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6613 NULL);
6614 if (error != NULL)
6615 goto done;
6617 error = apply_unveil(got_repo_get_path(repo), 0,
6618 got_worktree_get_root_path(worktree));
6619 if (error)
6620 goto done;
6622 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6623 worktree);
6624 if (error)
6625 goto done;
6626 if (histedit_in_progress) {
6627 error = got_error(GOT_ERR_HISTEDIT_BUSY);
6628 goto done;
6631 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6632 if (error)
6633 goto done;
6635 if (abort_rebase) {
6636 int did_something;
6637 if (!rebase_in_progress) {
6638 error = got_error(GOT_ERR_NOT_REBASING);
6639 goto done;
6641 error = got_worktree_rebase_continue(&resume_commit_id,
6642 &new_base_branch, &tmp_branch, &branch, &fileindex,
6643 worktree, repo);
6644 if (error)
6645 goto done;
6646 printf("Switching work tree to %s\n",
6647 got_ref_get_symref_target(new_base_branch));
6648 error = got_worktree_rebase_abort(worktree, fileindex, repo,
6649 new_base_branch, update_progress, &did_something);
6650 if (error)
6651 goto done;
6652 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
6653 goto done; /* nothing else to do */
6656 if (continue_rebase) {
6657 if (!rebase_in_progress) {
6658 error = got_error(GOT_ERR_NOT_REBASING);
6659 goto done;
6661 error = got_worktree_rebase_continue(&resume_commit_id,
6662 &new_base_branch, &tmp_branch, &branch, &fileindex,
6663 worktree, repo);
6664 if (error)
6665 goto done;
6667 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
6668 resume_commit_id, repo);
6669 if (error)
6670 goto done;
6672 yca_id = got_object_id_dup(resume_commit_id);
6673 if (yca_id == NULL) {
6674 error = got_error_from_errno("got_object_id_dup");
6675 goto done;
6677 } else {
6678 error = got_ref_open(&branch, repo, argv[0], 0);
6679 if (error != NULL)
6680 goto done;
6683 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
6684 if (error)
6685 goto done;
6687 if (!continue_rebase) {
6688 struct got_object_id *base_commit_id;
6690 base_commit_id = got_worktree_get_base_commit_id(worktree);
6691 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
6692 base_commit_id, branch_head_commit_id, repo,
6693 check_cancelled, NULL);
6694 if (error)
6695 goto done;
6696 if (yca_id == NULL) {
6697 error = got_error_msg(GOT_ERR_ANCESTRY,
6698 "specified branch shares no common ancestry "
6699 "with work tree's branch");
6700 goto done;
6703 error = check_same_branch(base_commit_id, branch, yca_id, repo);
6704 if (error) {
6705 if (error->code != GOT_ERR_ANCESTRY)
6706 goto done;
6707 error = NULL;
6708 } else {
6709 error = got_error_msg(GOT_ERR_SAME_BRANCH,
6710 "specified branch resolves to a commit which "
6711 "is already contained in work tree's branch");
6712 goto done;
6714 error = got_worktree_rebase_prepare(&new_base_branch,
6715 &tmp_branch, &fileindex, worktree, branch, repo);
6716 if (error)
6717 goto done;
6720 commit_id = branch_head_commit_id;
6721 error = got_object_open_as_commit(&commit, repo, commit_id);
6722 if (error)
6723 goto done;
6725 parent_ids = got_object_commit_get_parent_ids(commit);
6726 pid = SIMPLEQ_FIRST(parent_ids);
6727 if (pid == NULL) {
6728 if (!continue_rebase) {
6729 int did_something;
6730 error = got_worktree_rebase_abort(worktree, fileindex,
6731 repo, new_base_branch, update_progress,
6732 &did_something);
6733 if (error)
6734 goto done;
6735 printf("Rebase of %s aborted\n",
6736 got_ref_get_name(branch));
6738 error = got_error(GOT_ERR_EMPTY_REBASE);
6739 goto done;
6741 error = collect_commits(&commits, commit_id, pid->id,
6742 yca_id, got_worktree_get_path_prefix(worktree),
6743 GOT_ERR_REBASE_PATH, repo);
6744 got_object_commit_close(commit);
6745 commit = NULL;
6746 if (error)
6747 goto done;
6749 if (SIMPLEQ_EMPTY(&commits)) {
6750 if (continue_rebase) {
6751 error = rebase_complete(worktree, fileindex,
6752 branch, new_base_branch, tmp_branch, repo);
6753 goto done;
6754 } else {
6755 /* Fast-forward the reference of the branch. */
6756 struct got_object_id *new_head_commit_id;
6757 char *id_str;
6758 error = got_ref_resolve(&new_head_commit_id, repo,
6759 new_base_branch);
6760 if (error)
6761 goto done;
6762 error = got_object_id_str(&id_str, new_head_commit_id);
6763 printf("Forwarding %s to commit %s\n",
6764 got_ref_get_name(branch), id_str);
6765 free(id_str);
6766 error = got_ref_change_ref(branch,
6767 new_head_commit_id);
6768 if (error)
6769 goto done;
6773 pid = NULL;
6774 SIMPLEQ_FOREACH(qid, &commits, entry) {
6775 commit_id = qid->id;
6776 parent_id = pid ? pid->id : yca_id;
6777 pid = qid;
6779 error = got_worktree_rebase_merge_files(&merged_paths,
6780 worktree, fileindex, parent_id, commit_id, repo,
6781 rebase_progress, &rebase_status, check_cancelled, NULL);
6782 if (error)
6783 goto done;
6785 if (rebase_status == GOT_STATUS_CONFLICT) {
6786 error = show_rebase_merge_conflict(qid->id, repo);
6787 if (error)
6788 goto done;
6789 got_worktree_rebase_pathlist_free(&merged_paths);
6790 break;
6793 error = rebase_commit(&merged_paths, worktree, fileindex,
6794 tmp_branch, commit_id, repo);
6795 got_worktree_rebase_pathlist_free(&merged_paths);
6796 if (error)
6797 goto done;
6800 if (rebase_status == GOT_STATUS_CONFLICT) {
6801 error = got_worktree_rebase_postpone(worktree, fileindex);
6802 if (error)
6803 goto done;
6804 error = got_error_msg(GOT_ERR_CONFLICTS,
6805 "conflicts must be resolved before rebasing can continue");
6806 } else
6807 error = rebase_complete(worktree, fileindex, branch,
6808 new_base_branch, tmp_branch, repo);
6809 done:
6810 got_object_id_queue_free(&commits);
6811 free(branch_head_commit_id);
6812 free(resume_commit_id);
6813 free(yca_id);
6814 if (commit)
6815 got_object_commit_close(commit);
6816 if (branch)
6817 got_ref_close(branch);
6818 if (new_base_branch)
6819 got_ref_close(new_base_branch);
6820 if (tmp_branch)
6821 got_ref_close(tmp_branch);
6822 if (worktree)
6823 got_worktree_close(worktree);
6824 if (repo)
6825 got_repo_close(repo);
6826 return error;
6829 __dead static void
6830 usage_histedit(void)
6832 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
6833 getprogname());
6834 exit(1);
6837 #define GOT_HISTEDIT_PICK 'p'
6838 #define GOT_HISTEDIT_EDIT 'e'
6839 #define GOT_HISTEDIT_FOLD 'f'
6840 #define GOT_HISTEDIT_DROP 'd'
6841 #define GOT_HISTEDIT_MESG 'm'
6843 static struct got_histedit_cmd {
6844 unsigned char code;
6845 const char *name;
6846 const char *desc;
6847 } got_histedit_cmds[] = {
6848 { GOT_HISTEDIT_PICK, "pick", "use commit" },
6849 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
6850 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
6851 "be used" },
6852 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
6853 { GOT_HISTEDIT_MESG, "mesg",
6854 "single-line log message for commit above (open editor if empty)" },
6857 struct got_histedit_list_entry {
6858 TAILQ_ENTRY(got_histedit_list_entry) entry;
6859 struct got_object_id *commit_id;
6860 const struct got_histedit_cmd *cmd;
6861 char *logmsg;
6863 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
6865 static const struct got_error *
6866 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
6867 FILE *f, struct got_repository *repo)
6869 const struct got_error *err = NULL;
6870 char *logmsg = NULL, *id_str = NULL;
6871 struct got_commit_object *commit = NULL;
6872 int n;
6874 err = got_object_open_as_commit(&commit, repo, commit_id);
6875 if (err)
6876 goto done;
6878 err = get_short_logmsg(&logmsg, 34, commit);
6879 if (err)
6880 goto done;
6882 err = got_object_id_str(&id_str, commit_id);
6883 if (err)
6884 goto done;
6886 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
6887 if (n < 0)
6888 err = got_ferror(f, GOT_ERR_IO);
6889 done:
6890 if (commit)
6891 got_object_commit_close(commit);
6892 free(id_str);
6893 free(logmsg);
6894 return err;
6897 static const struct got_error *
6898 histedit_write_commit_list(struct got_object_id_queue *commits,
6899 FILE *f, int edit_logmsg_only, struct got_repository *repo)
6901 const struct got_error *err = NULL;
6902 struct got_object_qid *qid;
6904 if (SIMPLEQ_EMPTY(commits))
6905 return got_error(GOT_ERR_EMPTY_HISTEDIT);
6907 SIMPLEQ_FOREACH(qid, commits, entry) {
6908 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
6909 f, repo);
6910 if (err)
6911 break;
6912 if (edit_logmsg_only) {
6913 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
6914 if (n < 0) {
6915 err = got_ferror(f, GOT_ERR_IO);
6916 break;
6921 return err;
6924 static const struct got_error *
6925 write_cmd_list(FILE *f, const char *branch_name,
6926 struct got_object_id_queue *commits)
6928 const struct got_error *err = NULL;
6929 int n, i;
6930 char *id_str;
6931 struct got_object_qid *qid;
6933 qid = SIMPLEQ_FIRST(commits);
6934 err = got_object_id_str(&id_str, qid->id);
6935 if (err)
6936 return err;
6938 n = fprintf(f,
6939 "# Editing the history of branch '%s' starting at\n"
6940 "# commit %s\n"
6941 "# Commits will be processed in order from top to "
6942 "bottom of this file.\n", branch_name, id_str);
6943 if (n < 0) {
6944 err = got_ferror(f, GOT_ERR_IO);
6945 goto done;
6948 n = fprintf(f, "# Available histedit commands:\n");
6949 if (n < 0) {
6950 err = got_ferror(f, GOT_ERR_IO);
6951 goto done;
6954 for (i = 0; i < nitems(got_histedit_cmds); i++) {
6955 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
6956 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
6957 cmd->desc);
6958 if (n < 0) {
6959 err = got_ferror(f, GOT_ERR_IO);
6960 break;
6963 done:
6964 free(id_str);
6965 return err;
6968 static const struct got_error *
6969 histedit_syntax_error(int lineno)
6971 static char msg[42];
6972 int ret;
6974 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
6975 lineno);
6976 if (ret == -1 || ret >= sizeof(msg))
6977 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
6979 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
6982 static const struct got_error *
6983 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
6984 char *logmsg, struct got_repository *repo)
6986 const struct got_error *err;
6987 struct got_commit_object *folded_commit = NULL;
6988 char *id_str, *folded_logmsg = NULL;
6990 err = got_object_id_str(&id_str, hle->commit_id);
6991 if (err)
6992 return err;
6994 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
6995 if (err)
6996 goto done;
6998 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
6999 if (err)
7000 goto done;
7001 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7002 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7003 folded_logmsg) == -1) {
7004 err = got_error_from_errno("asprintf");
7006 done:
7007 if (folded_commit)
7008 got_object_commit_close(folded_commit);
7009 free(id_str);
7010 free(folded_logmsg);
7011 return err;
7014 static struct got_histedit_list_entry *
7015 get_folded_commits(struct got_histedit_list_entry *hle)
7017 struct got_histedit_list_entry *prev, *folded = NULL;
7019 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7020 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7021 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7022 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7023 folded = prev;
7024 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7027 return folded;
7030 static const struct got_error *
7031 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7032 struct got_repository *repo)
7034 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7035 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7036 const struct got_error *err = NULL;
7037 struct got_commit_object *commit = NULL;
7038 int fd;
7039 struct got_histedit_list_entry *folded = NULL;
7041 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7042 if (err)
7043 return err;
7045 folded = get_folded_commits(hle);
7046 if (folded) {
7047 while (folded != hle) {
7048 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7049 folded = TAILQ_NEXT(folded, entry);
7050 continue;
7052 err = append_folded_commit_msg(&new_msg, folded,
7053 logmsg, repo);
7054 if (err)
7055 goto done;
7056 free(logmsg);
7057 logmsg = new_msg;
7058 folded = TAILQ_NEXT(folded, entry);
7062 err = got_object_id_str(&id_str, hle->commit_id);
7063 if (err)
7064 goto done;
7065 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7066 if (err)
7067 goto done;
7068 if (asprintf(&new_msg,
7069 "%s\n# original log message of commit %s: %s",
7070 logmsg ? logmsg : "", id_str, orig_logmsg) == -1) {
7071 err = got_error_from_errno("asprintf");
7072 goto done;
7074 free(logmsg);
7075 logmsg = new_msg;
7077 err = got_object_id_str(&id_str, hle->commit_id);
7078 if (err)
7079 goto done;
7081 err = got_opentemp_named_fd(&logmsg_path, &fd,
7082 GOT_TMPDIR_STR "/got-logmsg");
7083 if (err)
7084 goto done;
7086 dprintf(fd, logmsg);
7087 close(fd);
7089 err = get_editor(&editor);
7090 if (err)
7091 goto done;
7093 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
7094 if (err) {
7095 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
7096 goto done;
7097 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
7099 done:
7100 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
7101 err = got_error_from_errno2("unlink", logmsg_path);
7102 free(logmsg_path);
7103 free(logmsg);
7104 free(orig_logmsg);
7105 free(editor);
7106 if (commit)
7107 got_object_commit_close(commit);
7108 return err;
7111 static const struct got_error *
7112 histedit_parse_list(struct got_histedit_list *histedit_cmds,
7113 FILE *f, struct got_repository *repo)
7115 const struct got_error *err = NULL;
7116 char *line = NULL, *p, *end;
7117 size_t size;
7118 ssize_t len;
7119 int lineno = 0, i;
7120 const struct got_histedit_cmd *cmd;
7121 struct got_object_id *commit_id = NULL;
7122 struct got_histedit_list_entry *hle = NULL;
7124 for (;;) {
7125 len = getline(&line, &size, f);
7126 if (len == -1) {
7127 const struct got_error *getline_err;
7128 if (feof(f))
7129 break;
7130 getline_err = got_error_from_errno("getline");
7131 err = got_ferror(f, getline_err->code);
7132 break;
7134 lineno++;
7135 p = line;
7136 while (isspace((unsigned char)p[0]))
7137 p++;
7138 if (p[0] == '#' || p[0] == '\0') {
7139 free(line);
7140 line = NULL;
7141 continue;
7143 cmd = NULL;
7144 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7145 cmd = &got_histedit_cmds[i];
7146 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
7147 isspace((unsigned char)p[strlen(cmd->name)])) {
7148 p += strlen(cmd->name);
7149 break;
7151 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
7152 p++;
7153 break;
7156 if (i == nitems(got_histedit_cmds)) {
7157 err = histedit_syntax_error(lineno);
7158 break;
7160 while (isspace((unsigned char)p[0]))
7161 p++;
7162 if (cmd->code == GOT_HISTEDIT_MESG) {
7163 if (hle == NULL || hle->logmsg != NULL) {
7164 err = got_error(GOT_ERR_HISTEDIT_CMD);
7165 break;
7167 if (p[0] == '\0') {
7168 err = histedit_edit_logmsg(hle, repo);
7169 if (err)
7170 break;
7171 } else {
7172 hle->logmsg = strdup(p);
7173 if (hle->logmsg == NULL) {
7174 err = got_error_from_errno("strdup");
7175 break;
7178 free(line);
7179 line = NULL;
7180 continue;
7181 } else {
7182 end = p;
7183 while (end[0] && !isspace((unsigned char)end[0]))
7184 end++;
7185 *end = '\0';
7187 err = got_object_resolve_id_str(&commit_id, repo, p);
7188 if (err) {
7189 /* override error code */
7190 err = histedit_syntax_error(lineno);
7191 break;
7194 hle = malloc(sizeof(*hle));
7195 if (hle == NULL) {
7196 err = got_error_from_errno("malloc");
7197 break;
7199 hle->cmd = cmd;
7200 hle->commit_id = commit_id;
7201 hle->logmsg = NULL;
7202 commit_id = NULL;
7203 free(line);
7204 line = NULL;
7205 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
7208 free(line);
7209 free(commit_id);
7210 return err;
7213 static const struct got_error *
7214 histedit_check_script(struct got_histedit_list *histedit_cmds,
7215 struct got_object_id_queue *commits, struct got_repository *repo)
7217 const struct got_error *err = NULL;
7218 struct got_object_qid *qid;
7219 struct got_histedit_list_entry *hle;
7220 static char msg[92];
7221 char *id_str;
7223 if (TAILQ_EMPTY(histedit_cmds))
7224 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
7225 "histedit script contains no commands");
7226 if (SIMPLEQ_EMPTY(commits))
7227 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7229 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7230 struct got_histedit_list_entry *hle2;
7231 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
7232 if (hle == hle2)
7233 continue;
7234 if (got_object_id_cmp(hle->commit_id,
7235 hle2->commit_id) != 0)
7236 continue;
7237 err = got_object_id_str(&id_str, hle->commit_id);
7238 if (err)
7239 return err;
7240 snprintf(msg, sizeof(msg), "commit %s is listed "
7241 "more than once in histedit script", id_str);
7242 free(id_str);
7243 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7247 SIMPLEQ_FOREACH(qid, commits, entry) {
7248 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7249 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
7250 break;
7252 if (hle == NULL) {
7253 err = got_object_id_str(&id_str, qid->id);
7254 if (err)
7255 return err;
7256 snprintf(msg, sizeof(msg),
7257 "commit %s missing from histedit script", id_str);
7258 free(id_str);
7259 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7263 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
7264 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
7265 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
7266 "last commit in histedit script cannot be folded");
7268 return NULL;
7271 static const struct got_error *
7272 histedit_run_editor(struct got_histedit_list *histedit_cmds,
7273 const char *path, struct got_object_id_queue *commits,
7274 struct got_repository *repo)
7276 const struct got_error *err = NULL;
7277 char *editor;
7278 FILE *f = NULL;
7280 err = get_editor(&editor);
7281 if (err)
7282 return err;
7284 if (spawn_editor(editor, path) == -1) {
7285 err = got_error_from_errno("failed spawning editor");
7286 goto done;
7289 f = fopen(path, "r");
7290 if (f == NULL) {
7291 err = got_error_from_errno("fopen");
7292 goto done;
7294 err = histedit_parse_list(histedit_cmds, f, repo);
7295 if (err)
7296 goto done;
7298 err = histedit_check_script(histedit_cmds, commits, repo);
7299 done:
7300 if (f && fclose(f) != 0 && err == NULL)
7301 err = got_error_from_errno("fclose");
7302 free(editor);
7303 return err;
7306 static const struct got_error *
7307 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
7308 struct got_object_id_queue *, const char *, const char *,
7309 struct got_repository *);
7311 static const struct got_error *
7312 histedit_edit_script(struct got_histedit_list *histedit_cmds,
7313 struct got_object_id_queue *commits, const char *branch_name,
7314 int edit_logmsg_only, struct got_repository *repo)
7316 const struct got_error *err;
7317 FILE *f = NULL;
7318 char *path = NULL;
7320 err = got_opentemp_named(&path, &f, "got-histedit");
7321 if (err)
7322 return err;
7324 err = write_cmd_list(f, branch_name, commits);
7325 if (err)
7326 goto done;
7328 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
7329 if (err)
7330 goto done;
7332 if (edit_logmsg_only) {
7333 rewind(f);
7334 err = histedit_parse_list(histedit_cmds, f, repo);
7335 } else {
7336 if (fclose(f) != 0) {
7337 err = got_error_from_errno("fclose");
7338 goto done;
7340 f = NULL;
7341 err = histedit_run_editor(histedit_cmds, path, commits, repo);
7342 if (err) {
7343 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7344 err->code != GOT_ERR_HISTEDIT_CMD)
7345 goto done;
7346 err = histedit_edit_list_retry(histedit_cmds, err,
7347 commits, path, branch_name, repo);
7350 done:
7351 if (f && fclose(f) != 0 && err == NULL)
7352 err = got_error_from_errno("fclose");
7353 if (path && unlink(path) != 0 && err == NULL)
7354 err = got_error_from_errno2("unlink", path);
7355 free(path);
7356 return err;
7359 static const struct got_error *
7360 histedit_save_list(struct got_histedit_list *histedit_cmds,
7361 struct got_worktree *worktree, struct got_repository *repo)
7363 const struct got_error *err = NULL;
7364 char *path = NULL;
7365 FILE *f = NULL;
7366 struct got_histedit_list_entry *hle;
7367 struct got_commit_object *commit = NULL;
7369 err = got_worktree_get_histedit_script_path(&path, worktree);
7370 if (err)
7371 return err;
7373 f = fopen(path, "w");
7374 if (f == NULL) {
7375 err = got_error_from_errno2("fopen", path);
7376 goto done;
7378 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7379 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
7380 repo);
7381 if (err)
7382 break;
7384 if (hle->logmsg) {
7385 int n = fprintf(f, "%c %s\n",
7386 GOT_HISTEDIT_MESG, hle->logmsg);
7387 if (n < 0) {
7388 err = got_ferror(f, GOT_ERR_IO);
7389 break;
7393 done:
7394 if (f && fclose(f) != 0 && err == NULL)
7395 err = got_error_from_errno("fclose");
7396 free(path);
7397 if (commit)
7398 got_object_commit_close(commit);
7399 return err;
7402 void
7403 histedit_free_list(struct got_histedit_list *histedit_cmds)
7405 struct got_histedit_list_entry *hle;
7407 while ((hle = TAILQ_FIRST(histedit_cmds))) {
7408 TAILQ_REMOVE(histedit_cmds, hle, entry);
7409 free(hle);
7413 static const struct got_error *
7414 histedit_load_list(struct got_histedit_list *histedit_cmds,
7415 const char *path, struct got_repository *repo)
7417 const struct got_error *err = NULL;
7418 FILE *f = NULL;
7420 f = fopen(path, "r");
7421 if (f == NULL) {
7422 err = got_error_from_errno2("fopen", path);
7423 goto done;
7426 err = histedit_parse_list(histedit_cmds, f, repo);
7427 done:
7428 if (f && fclose(f) != 0 && err == NULL)
7429 err = got_error_from_errno("fclose");
7430 return err;
7433 static const struct got_error *
7434 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
7435 const struct got_error *edit_err, struct got_object_id_queue *commits,
7436 const char *path, const char *branch_name, struct got_repository *repo)
7438 const struct got_error *err = NULL, *prev_err = edit_err;
7439 int resp = ' ';
7441 while (resp != 'c' && resp != 'r' && resp != 'a') {
7442 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
7443 "or (a)bort: ", getprogname(), prev_err->msg);
7444 resp = getchar();
7445 if (resp == '\n')
7446 resp = getchar();
7447 if (resp == 'c') {
7448 histedit_free_list(histedit_cmds);
7449 err = histedit_run_editor(histedit_cmds, path, commits,
7450 repo);
7451 if (err) {
7452 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7453 err->code != GOT_ERR_HISTEDIT_CMD)
7454 break;
7455 prev_err = err;
7456 resp = ' ';
7457 continue;
7459 break;
7460 } else if (resp == 'r') {
7461 histedit_free_list(histedit_cmds);
7462 err = histedit_edit_script(histedit_cmds,
7463 commits, branch_name, 0, repo);
7464 if (err) {
7465 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7466 err->code != GOT_ERR_HISTEDIT_CMD)
7467 break;
7468 prev_err = err;
7469 resp = ' ';
7470 continue;
7472 break;
7473 } else if (resp == 'a') {
7474 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
7475 break;
7476 } else
7477 printf("invalid response '%c'\n", resp);
7480 return err;
7483 static const struct got_error *
7484 histedit_complete(struct got_worktree *worktree,
7485 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
7486 struct got_reference *branch, struct got_repository *repo)
7488 printf("Switching work tree to %s\n",
7489 got_ref_get_symref_target(branch));
7490 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
7491 branch, repo);
7494 static const struct got_error *
7495 show_histedit_progress(struct got_commit_object *commit,
7496 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
7498 const struct got_error *err;
7499 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7501 err = got_object_id_str(&old_id_str, hle->commit_id);
7502 if (err)
7503 goto done;
7505 if (new_id) {
7506 err = got_object_id_str(&new_id_str, new_id);
7507 if (err)
7508 goto done;
7511 old_id_str[12] = '\0';
7512 if (new_id_str)
7513 new_id_str[12] = '\0';
7515 if (hle->logmsg) {
7516 logmsg = strdup(hle->logmsg);
7517 if (logmsg == NULL) {
7518 err = got_error_from_errno("strdup");
7519 goto done;
7521 trim_logmsg(logmsg, 42);
7522 } else {
7523 err = get_short_logmsg(&logmsg, 42, commit);
7524 if (err)
7525 goto done;
7528 switch (hle->cmd->code) {
7529 case GOT_HISTEDIT_PICK:
7530 case GOT_HISTEDIT_EDIT:
7531 printf("%s -> %s: %s\n", old_id_str,
7532 new_id_str ? new_id_str : "no-op change", logmsg);
7533 break;
7534 case GOT_HISTEDIT_DROP:
7535 case GOT_HISTEDIT_FOLD:
7536 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
7537 logmsg);
7538 break;
7539 default:
7540 break;
7542 done:
7543 free(old_id_str);
7544 free(new_id_str);
7545 return err;
7548 static const struct got_error *
7549 histedit_commit(struct got_pathlist_head *merged_paths,
7550 struct got_worktree *worktree, struct got_fileindex *fileindex,
7551 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
7552 struct got_repository *repo)
7554 const struct got_error *err;
7555 struct got_commit_object *commit;
7556 struct got_object_id *new_commit_id;
7558 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
7559 && hle->logmsg == NULL) {
7560 err = histedit_edit_logmsg(hle, repo);
7561 if (err)
7562 return err;
7565 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7566 if (err)
7567 return err;
7569 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
7570 worktree, fileindex, tmp_branch, commit, hle->commit_id,
7571 hle->logmsg, repo);
7572 if (err) {
7573 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
7574 goto done;
7575 err = show_histedit_progress(commit, hle, NULL);
7576 } else {
7577 err = show_histedit_progress(commit, hle, new_commit_id);
7578 free(new_commit_id);
7580 done:
7581 got_object_commit_close(commit);
7582 return err;
7585 static const struct got_error *
7586 histedit_skip_commit(struct got_histedit_list_entry *hle,
7587 struct got_worktree *worktree, struct got_repository *repo)
7589 const struct got_error *error;
7590 struct got_commit_object *commit;
7592 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
7593 repo);
7594 if (error)
7595 return error;
7597 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
7598 if (error)
7599 return error;
7601 error = show_histedit_progress(commit, hle, NULL);
7602 got_object_commit_close(commit);
7603 return error;
7606 static const struct got_error *
7607 check_local_changes(void *arg, unsigned char status,
7608 unsigned char staged_status, const char *path,
7609 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
7610 struct got_object_id *commit_id, int dirfd, const char *de_name)
7612 int *have_local_changes = arg;
7614 switch (status) {
7615 case GOT_STATUS_ADD:
7616 case GOT_STATUS_DELETE:
7617 case GOT_STATUS_MODIFY:
7618 case GOT_STATUS_CONFLICT:
7619 *have_local_changes = 1;
7620 return got_error(GOT_ERR_CANCELLED);
7621 default:
7622 break;
7625 switch (staged_status) {
7626 case GOT_STATUS_ADD:
7627 case GOT_STATUS_DELETE:
7628 case GOT_STATUS_MODIFY:
7629 *have_local_changes = 1;
7630 return got_error(GOT_ERR_CANCELLED);
7631 default:
7632 break;
7635 return NULL;
7638 static const struct got_error *
7639 cmd_histedit(int argc, char *argv[])
7641 const struct got_error *error = NULL;
7642 struct got_worktree *worktree = NULL;
7643 struct got_fileindex *fileindex = NULL;
7644 struct got_repository *repo = NULL;
7645 char *cwd = NULL;
7646 struct got_reference *branch = NULL;
7647 struct got_reference *tmp_branch = NULL;
7648 struct got_object_id *resume_commit_id = NULL;
7649 struct got_object_id *base_commit_id = NULL;
7650 struct got_object_id *head_commit_id = NULL;
7651 struct got_commit_object *commit = NULL;
7652 int ch, rebase_in_progress = 0, did_something;
7653 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
7654 int edit_logmsg_only = 0;
7655 const char *edit_script_path = NULL;
7656 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7657 struct got_object_id_queue commits;
7658 struct got_pathlist_head merged_paths;
7659 const struct got_object_id_queue *parent_ids;
7660 struct got_object_qid *pid;
7661 struct got_histedit_list histedit_cmds;
7662 struct got_histedit_list_entry *hle;
7664 SIMPLEQ_INIT(&commits);
7665 TAILQ_INIT(&histedit_cmds);
7666 TAILQ_INIT(&merged_paths);
7668 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
7669 switch (ch) {
7670 case 'a':
7671 abort_edit = 1;
7672 break;
7673 case 'c':
7674 continue_edit = 1;
7675 break;
7676 case 'F':
7677 edit_script_path = optarg;
7678 break;
7679 case 'm':
7680 edit_logmsg_only = 1;
7681 break;
7682 default:
7683 usage_histedit();
7684 /* NOTREACHED */
7688 argc -= optind;
7689 argv += optind;
7691 #ifndef PROFILE
7692 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7693 "unveil", NULL) == -1)
7694 err(1, "pledge");
7695 #endif
7696 if (abort_edit && continue_edit)
7697 errx(1, "histedit's -a and -c options are mutually exclusive");
7698 if (edit_script_path && edit_logmsg_only)
7699 errx(1, "histedit's -F and -m options are mutually exclusive");
7700 if (abort_edit && edit_logmsg_only)
7701 errx(1, "histedit's -a and -m options are mutually exclusive");
7702 if (continue_edit && edit_logmsg_only)
7703 errx(1, "histedit's -c and -m options are mutually exclusive");
7704 if (argc != 0)
7705 usage_histedit();
7708 * This command cannot apply unveil(2) in all cases because the
7709 * user may choose to run an editor to edit the histedit script
7710 * and to edit individual commit log messages.
7711 * unveil(2) traverses exec(2); if an editor is used we have to
7712 * apply unveil after edit script and log messages have been written.
7713 * XXX TODO: Make use of unveil(2) where possible.
7716 cwd = getcwd(NULL, 0);
7717 if (cwd == NULL) {
7718 error = got_error_from_errno("getcwd");
7719 goto done;
7721 error = got_worktree_open(&worktree, cwd);
7722 if (error)
7723 goto done;
7725 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7726 NULL);
7727 if (error != NULL)
7728 goto done;
7730 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7731 if (error)
7732 goto done;
7733 if (rebase_in_progress) {
7734 error = got_error(GOT_ERR_REBASING);
7735 goto done;
7738 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
7739 if (error)
7740 goto done;
7742 if (edit_in_progress && edit_logmsg_only) {
7743 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
7744 "histedit operation is in progress in this "
7745 "work tree and must be continued or aborted "
7746 "before the -m option can be used");
7747 goto done;
7750 if (edit_in_progress && abort_edit) {
7751 error = got_worktree_histedit_continue(&resume_commit_id,
7752 &tmp_branch, &branch, &base_commit_id, &fileindex,
7753 worktree, repo);
7754 if (error)
7755 goto done;
7756 printf("Switching work tree to %s\n",
7757 got_ref_get_symref_target(branch));
7758 error = got_worktree_histedit_abort(worktree, fileindex, repo,
7759 branch, base_commit_id, update_progress, &did_something);
7760 if (error)
7761 goto done;
7762 printf("Histedit of %s aborted\n",
7763 got_ref_get_symref_target(branch));
7764 goto done; /* nothing else to do */
7765 } else if (abort_edit) {
7766 error = got_error(GOT_ERR_NOT_HISTEDIT);
7767 goto done;
7770 if (continue_edit) {
7771 char *path;
7773 if (!edit_in_progress) {
7774 error = got_error(GOT_ERR_NOT_HISTEDIT);
7775 goto done;
7778 error = got_worktree_get_histedit_script_path(&path, worktree);
7779 if (error)
7780 goto done;
7782 error = histedit_load_list(&histedit_cmds, path, repo);
7783 free(path);
7784 if (error)
7785 goto done;
7787 error = got_worktree_histedit_continue(&resume_commit_id,
7788 &tmp_branch, &branch, &base_commit_id, &fileindex,
7789 worktree, repo);
7790 if (error)
7791 goto done;
7793 error = got_ref_resolve(&head_commit_id, repo, branch);
7794 if (error)
7795 goto done;
7797 error = got_object_open_as_commit(&commit, repo,
7798 head_commit_id);
7799 if (error)
7800 goto done;
7801 parent_ids = got_object_commit_get_parent_ids(commit);
7802 pid = SIMPLEQ_FIRST(parent_ids);
7803 if (pid == NULL) {
7804 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
7805 goto done;
7807 error = collect_commits(&commits, head_commit_id, pid->id,
7808 base_commit_id, 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;
7814 } else {
7815 if (edit_in_progress) {
7816 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7817 goto done;
7820 error = got_ref_open(&branch, repo,
7821 got_worktree_get_head_ref_name(worktree), 0);
7822 if (error != NULL)
7823 goto done;
7825 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
7826 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
7827 "will not edit commit history of a branch outside "
7828 "the \"refs/heads/\" reference namespace");
7829 goto done;
7832 error = got_ref_resolve(&head_commit_id, repo, branch);
7833 got_ref_close(branch);
7834 branch = NULL;
7835 if (error)
7836 goto done;
7838 error = got_object_open_as_commit(&commit, repo,
7839 head_commit_id);
7840 if (error)
7841 goto done;
7842 parent_ids = got_object_commit_get_parent_ids(commit);
7843 pid = SIMPLEQ_FIRST(parent_ids);
7844 if (pid == NULL) {
7845 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
7846 goto done;
7848 error = collect_commits(&commits, head_commit_id, pid->id,
7849 got_worktree_get_base_commit_id(worktree),
7850 got_worktree_get_path_prefix(worktree),
7851 GOT_ERR_HISTEDIT_PATH, repo);
7852 got_object_commit_close(commit);
7853 commit = NULL;
7854 if (error)
7855 goto done;
7857 if (SIMPLEQ_EMPTY(&commits)) {
7858 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
7859 goto done;
7862 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
7863 &base_commit_id, &fileindex, worktree, repo);
7864 if (error)
7865 goto done;
7867 if (edit_script_path) {
7868 error = histedit_load_list(&histedit_cmds,
7869 edit_script_path, repo);
7870 if (error) {
7871 got_worktree_histedit_abort(worktree, fileindex,
7872 repo, branch, base_commit_id,
7873 update_progress, &did_something);
7874 goto done;
7876 } else {
7877 const char *branch_name;
7878 branch_name = got_ref_get_symref_target(branch);
7879 if (strncmp(branch_name, "refs/heads/", 11) == 0)
7880 branch_name += 11;
7881 error = histedit_edit_script(&histedit_cmds, &commits,
7882 branch_name, edit_logmsg_only, repo);
7883 if (error) {
7884 got_worktree_histedit_abort(worktree, fileindex,
7885 repo, branch, base_commit_id,
7886 update_progress, &did_something);
7887 goto done;
7892 error = histedit_save_list(&histedit_cmds, worktree,
7893 repo);
7894 if (error) {
7895 got_worktree_histedit_abort(worktree, fileindex,
7896 repo, branch, base_commit_id,
7897 update_progress, &did_something);
7898 goto done;
7903 error = histedit_check_script(&histedit_cmds, &commits, repo);
7904 if (error)
7905 goto done;
7907 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
7908 if (resume_commit_id) {
7909 if (got_object_id_cmp(hle->commit_id,
7910 resume_commit_id) != 0)
7911 continue;
7913 resume_commit_id = NULL;
7914 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
7915 hle->cmd->code == GOT_HISTEDIT_FOLD) {
7916 error = histedit_skip_commit(hle, worktree,
7917 repo);
7918 if (error)
7919 goto done;
7920 } else {
7921 struct got_pathlist_head paths;
7922 int have_changes = 0;
7924 TAILQ_INIT(&paths);
7925 error = got_pathlist_append(&paths, "", NULL);
7926 if (error)
7927 goto done;
7928 error = got_worktree_status(worktree, &paths,
7929 repo, check_local_changes, &have_changes,
7930 check_cancelled, NULL);
7931 got_pathlist_free(&paths);
7932 if (error) {
7933 if (error->code != GOT_ERR_CANCELLED)
7934 goto done;
7935 if (sigint_received || sigpipe_received)
7936 goto done;
7938 if (have_changes) {
7939 error = histedit_commit(NULL, worktree,
7940 fileindex, tmp_branch, hle, repo);
7941 if (error)
7942 goto done;
7943 } else {
7944 error = got_object_open_as_commit(
7945 &commit, repo, hle->commit_id);
7946 if (error)
7947 goto done;
7948 error = show_histedit_progress(commit,
7949 hle, NULL);
7950 got_object_commit_close(commit);
7951 commit = NULL;
7952 if (error)
7953 goto done;
7956 continue;
7959 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
7960 error = histedit_skip_commit(hle, worktree, repo);
7961 if (error)
7962 goto done;
7963 continue;
7966 error = got_object_open_as_commit(&commit, repo,
7967 hle->commit_id);
7968 if (error)
7969 goto done;
7970 parent_ids = got_object_commit_get_parent_ids(commit);
7971 pid = SIMPLEQ_FIRST(parent_ids);
7973 error = got_worktree_histedit_merge_files(&merged_paths,
7974 worktree, fileindex, pid->id, hle->commit_id, repo,
7975 rebase_progress, &rebase_status, check_cancelled, NULL);
7976 if (error)
7977 goto done;
7978 got_object_commit_close(commit);
7979 commit = NULL;
7981 if (rebase_status == GOT_STATUS_CONFLICT) {
7982 error = show_rebase_merge_conflict(hle->commit_id,
7983 repo);
7984 if (error)
7985 goto done;
7986 got_worktree_rebase_pathlist_free(&merged_paths);
7987 break;
7990 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
7991 char *id_str;
7992 error = got_object_id_str(&id_str, hle->commit_id);
7993 if (error)
7994 goto done;
7995 printf("Stopping histedit for amending commit %s\n",
7996 id_str);
7997 free(id_str);
7998 got_worktree_rebase_pathlist_free(&merged_paths);
7999 error = got_worktree_histedit_postpone(worktree,
8000 fileindex);
8001 goto done;
8004 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8005 error = histedit_skip_commit(hle, worktree, repo);
8006 if (error)
8007 goto done;
8008 continue;
8011 error = histedit_commit(&merged_paths, worktree, fileindex,
8012 tmp_branch, hle, repo);
8013 got_worktree_rebase_pathlist_free(&merged_paths);
8014 if (error)
8015 goto done;
8018 if (rebase_status == GOT_STATUS_CONFLICT) {
8019 error = got_worktree_histedit_postpone(worktree, fileindex);
8020 if (error)
8021 goto done;
8022 error = got_error_msg(GOT_ERR_CONFLICTS,
8023 "conflicts must be resolved before histedit can continue");
8024 } else
8025 error = histedit_complete(worktree, fileindex, tmp_branch,
8026 branch, repo);
8027 done:
8028 got_object_id_queue_free(&commits);
8029 histedit_free_list(&histedit_cmds);
8030 free(head_commit_id);
8031 free(base_commit_id);
8032 free(resume_commit_id);
8033 if (commit)
8034 got_object_commit_close(commit);
8035 if (branch)
8036 got_ref_close(branch);
8037 if (tmp_branch)
8038 got_ref_close(tmp_branch);
8039 if (worktree)
8040 got_worktree_close(worktree);
8041 if (repo)
8042 got_repo_close(repo);
8043 return error;
8046 __dead static void
8047 usage_integrate(void)
8049 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
8050 exit(1);
8053 static const struct got_error *
8054 cmd_integrate(int argc, char *argv[])
8056 const struct got_error *error = NULL;
8057 struct got_repository *repo = NULL;
8058 struct got_worktree *worktree = NULL;
8059 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
8060 const char *branch_arg = NULL;
8061 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
8062 struct got_fileindex *fileindex = NULL;
8063 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
8064 int ch, did_something = 0;
8066 while ((ch = getopt(argc, argv, "")) != -1) {
8067 switch (ch) {
8068 default:
8069 usage_integrate();
8070 /* NOTREACHED */
8074 argc -= optind;
8075 argv += optind;
8077 if (argc != 1)
8078 usage_integrate();
8079 branch_arg = argv[0];
8081 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8082 "unveil", NULL) == -1)
8083 err(1, "pledge");
8085 cwd = getcwd(NULL, 0);
8086 if (cwd == NULL) {
8087 error = got_error_from_errno("getcwd");
8088 goto done;
8091 error = got_worktree_open(&worktree, cwd);
8092 if (error)
8093 goto done;
8095 error = check_rebase_or_histedit_in_progress(worktree);
8096 if (error)
8097 goto done;
8099 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8100 NULL);
8101 if (error != NULL)
8102 goto done;
8104 error = apply_unveil(got_repo_get_path(repo), 0,
8105 got_worktree_get_root_path(worktree));
8106 if (error)
8107 goto done;
8109 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
8110 error = got_error_from_errno("asprintf");
8111 goto done;
8114 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
8115 &base_branch_ref, worktree, refname, repo);
8116 if (error)
8117 goto done;
8119 refname = strdup(got_ref_get_name(branch_ref));
8120 if (refname == NULL) {
8121 error = got_error_from_errno("strdup");
8122 got_worktree_integrate_abort(worktree, fileindex, repo,
8123 branch_ref, base_branch_ref);
8124 goto done;
8126 base_refname = strdup(got_ref_get_name(base_branch_ref));
8127 if (base_refname == NULL) {
8128 error = got_error_from_errno("strdup");
8129 got_worktree_integrate_abort(worktree, fileindex, repo,
8130 branch_ref, base_branch_ref);
8131 goto done;
8134 error = got_ref_resolve(&commit_id, repo, branch_ref);
8135 if (error)
8136 goto done;
8138 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
8139 if (error)
8140 goto done;
8142 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
8143 error = got_error_msg(GOT_ERR_SAME_BRANCH,
8144 "specified branch has already been integrated");
8145 got_worktree_integrate_abort(worktree, fileindex, repo,
8146 branch_ref, base_branch_ref);
8147 goto done;
8150 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
8151 if (error) {
8152 if (error->code == GOT_ERR_ANCESTRY)
8153 error = got_error(GOT_ERR_REBASE_REQUIRED);
8154 got_worktree_integrate_abort(worktree, fileindex, repo,
8155 branch_ref, base_branch_ref);
8156 goto done;
8159 error = got_worktree_integrate_continue(worktree, fileindex, repo,
8160 branch_ref, base_branch_ref, update_progress, &did_something,
8161 check_cancelled, NULL);
8162 if (error)
8163 goto done;
8165 printf("Integrated %s into %s\n", refname, base_refname);
8166 done:
8167 if (repo)
8168 got_repo_close(repo);
8169 if (worktree)
8170 got_worktree_close(worktree);
8171 free(cwd);
8172 free(base_commit_id);
8173 free(commit_id);
8174 free(refname);
8175 free(base_refname);
8176 return error;
8179 __dead static void
8180 usage_stage(void)
8182 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
8183 "[file-path ...]\n",
8184 getprogname());
8185 exit(1);
8188 static const struct got_error *
8189 print_stage(void *arg, unsigned char status, unsigned char staged_status,
8190 const char *path, struct got_object_id *blob_id,
8191 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
8192 int dirfd, const char *de_name)
8194 const struct got_error *err = NULL;
8195 char *id_str = NULL;
8197 if (staged_status != GOT_STATUS_ADD &&
8198 staged_status != GOT_STATUS_MODIFY &&
8199 staged_status != GOT_STATUS_DELETE)
8200 return NULL;
8202 if (staged_status == GOT_STATUS_ADD ||
8203 staged_status == GOT_STATUS_MODIFY)
8204 err = got_object_id_str(&id_str, staged_blob_id);
8205 else
8206 err = got_object_id_str(&id_str, blob_id);
8207 if (err)
8208 return err;
8210 printf("%s %c %s\n", id_str, staged_status, path);
8211 free(id_str);
8212 return NULL;
8215 static const struct got_error *
8216 cmd_stage(int argc, char *argv[])
8218 const struct got_error *error = NULL;
8219 struct got_repository *repo = NULL;
8220 struct got_worktree *worktree = NULL;
8221 char *cwd = NULL;
8222 struct got_pathlist_head paths;
8223 struct got_pathlist_entry *pe;
8224 int ch, list_stage = 0, pflag = 0;
8225 FILE *patch_script_file = NULL;
8226 const char *patch_script_path = NULL;
8227 struct choose_patch_arg cpa;
8229 TAILQ_INIT(&paths);
8231 while ((ch = getopt(argc, argv, "lpF:")) != -1) {
8232 switch (ch) {
8233 case 'l':
8234 list_stage = 1;
8235 break;
8236 case 'p':
8237 pflag = 1;
8238 break;
8239 case 'F':
8240 patch_script_path = optarg;
8241 break;
8242 default:
8243 usage_stage();
8244 /* NOTREACHED */
8248 argc -= optind;
8249 argv += optind;
8251 #ifndef PROFILE
8252 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8253 "unveil", NULL) == -1)
8254 err(1, "pledge");
8255 #endif
8256 if (list_stage && (pflag || patch_script_path))
8257 errx(1, "-l option cannot be used with other options");
8258 if (patch_script_path && !pflag)
8259 errx(1, "-F option can only be used together with -p option");
8261 cwd = getcwd(NULL, 0);
8262 if (cwd == NULL) {
8263 error = got_error_from_errno("getcwd");
8264 goto done;
8267 error = got_worktree_open(&worktree, cwd);
8268 if (error)
8269 goto done;
8271 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8272 NULL);
8273 if (error != NULL)
8274 goto done;
8276 if (patch_script_path) {
8277 patch_script_file = fopen(patch_script_path, "r");
8278 if (patch_script_file == NULL) {
8279 error = got_error_from_errno2("fopen",
8280 patch_script_path);
8281 goto done;
8284 error = apply_unveil(got_repo_get_path(repo), 0,
8285 got_worktree_get_root_path(worktree));
8286 if (error)
8287 goto done;
8289 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8290 if (error)
8291 goto done;
8293 if (list_stage)
8294 error = got_worktree_status(worktree, &paths, repo,
8295 print_stage, NULL, check_cancelled, NULL);
8296 else {
8297 cpa.patch_script_file = patch_script_file;
8298 cpa.action = "stage";
8299 error = got_worktree_stage(worktree, &paths,
8300 pflag ? NULL : print_status, NULL,
8301 pflag ? choose_patch : NULL, &cpa, repo);
8303 done:
8304 if (patch_script_file && fclose(patch_script_file) == EOF &&
8305 error == NULL)
8306 error = got_error_from_errno2("fclose", patch_script_path);
8307 if (repo)
8308 got_repo_close(repo);
8309 if (worktree)
8310 got_worktree_close(worktree);
8311 TAILQ_FOREACH(pe, &paths, entry)
8312 free((char *)pe->path);
8313 got_pathlist_free(&paths);
8314 free(cwd);
8315 return error;
8318 __dead static void
8319 usage_unstage(void)
8321 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
8322 "[file-path ...]\n",
8323 getprogname());
8324 exit(1);
8328 static const struct got_error *
8329 cmd_unstage(int argc, char *argv[])
8331 const struct got_error *error = NULL;
8332 struct got_repository *repo = NULL;
8333 struct got_worktree *worktree = NULL;
8334 char *cwd = NULL;
8335 struct got_pathlist_head paths;
8336 struct got_pathlist_entry *pe;
8337 int ch, did_something = 0, pflag = 0;
8338 FILE *patch_script_file = NULL;
8339 const char *patch_script_path = NULL;
8340 struct choose_patch_arg cpa;
8342 TAILQ_INIT(&paths);
8344 while ((ch = getopt(argc, argv, "pF:")) != -1) {
8345 switch (ch) {
8346 case 'p':
8347 pflag = 1;
8348 break;
8349 case 'F':
8350 patch_script_path = optarg;
8351 break;
8352 default:
8353 usage_unstage();
8354 /* NOTREACHED */
8358 argc -= optind;
8359 argv += optind;
8361 #ifndef PROFILE
8362 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8363 "unveil", NULL) == -1)
8364 err(1, "pledge");
8365 #endif
8366 if (patch_script_path && !pflag)
8367 errx(1, "-F option can only be used together with -p option");
8369 cwd = getcwd(NULL, 0);
8370 if (cwd == NULL) {
8371 error = got_error_from_errno("getcwd");
8372 goto done;
8375 error = got_worktree_open(&worktree, cwd);
8376 if (error)
8377 goto done;
8379 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8380 NULL);
8381 if (error != NULL)
8382 goto done;
8384 if (patch_script_path) {
8385 patch_script_file = fopen(patch_script_path, "r");
8386 if (patch_script_file == NULL) {
8387 error = got_error_from_errno2("fopen",
8388 patch_script_path);
8389 goto done;
8393 error = apply_unveil(got_repo_get_path(repo), 0,
8394 got_worktree_get_root_path(worktree));
8395 if (error)
8396 goto done;
8398 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8399 if (error)
8400 goto done;
8402 cpa.patch_script_file = patch_script_file;
8403 cpa.action = "unstage";
8404 error = got_worktree_unstage(worktree, &paths, update_progress,
8405 &did_something, pflag ? choose_patch : NULL, &cpa, repo);
8406 done:
8407 if (patch_script_file && fclose(patch_script_file) == EOF &&
8408 error == NULL)
8409 error = got_error_from_errno2("fclose", patch_script_path);
8410 if (repo)
8411 got_repo_close(repo);
8412 if (worktree)
8413 got_worktree_close(worktree);
8414 TAILQ_FOREACH(pe, &paths, entry)
8415 free((char *)pe->path);
8416 got_pathlist_free(&paths);
8417 free(cwd);
8418 return error;
8421 __dead static void
8422 usage_cat(void)
8424 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
8425 "arg1 [arg2 ...]\n", getprogname());
8426 exit(1);
8429 static const struct got_error *
8430 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8432 const struct got_error *err;
8433 struct got_blob_object *blob;
8435 err = got_object_open_as_blob(&blob, repo, id, 8192);
8436 if (err)
8437 return err;
8439 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
8440 got_object_blob_close(blob);
8441 return err;
8444 static const struct got_error *
8445 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8447 const struct got_error *err;
8448 struct got_tree_object *tree;
8449 int nentries, i;
8451 err = got_object_open_as_tree(&tree, repo, id);
8452 if (err)
8453 return err;
8455 nentries = got_object_tree_get_nentries(tree);
8456 for (i = 0; i < nentries; i++) {
8457 struct got_tree_entry *te;
8458 char *id_str;
8459 if (sigint_received || sigpipe_received)
8460 break;
8461 te = got_object_tree_get_entry(tree, i);
8462 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
8463 if (err)
8464 break;
8465 fprintf(outfile, "%s %.7o %s\n", id_str,
8466 got_tree_entry_get_mode(te),
8467 got_tree_entry_get_name(te));
8468 free(id_str);
8471 got_object_tree_close(tree);
8472 return err;
8475 static const struct got_error *
8476 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8478 const struct got_error *err;
8479 struct got_commit_object *commit;
8480 const struct got_object_id_queue *parent_ids;
8481 struct got_object_qid *pid;
8482 char *id_str = NULL;
8483 const char *logmsg = NULL;
8485 err = got_object_open_as_commit(&commit, repo, id);
8486 if (err)
8487 return err;
8489 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
8490 if (err)
8491 goto done;
8493 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
8494 parent_ids = got_object_commit_get_parent_ids(commit);
8495 fprintf(outfile, "numparents %d\n",
8496 got_object_commit_get_nparents(commit));
8497 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
8498 char *pid_str;
8499 err = got_object_id_str(&pid_str, pid->id);
8500 if (err)
8501 goto done;
8502 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
8503 free(pid_str);
8505 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
8506 got_object_commit_get_author(commit),
8507 got_object_commit_get_author_time(commit));
8509 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
8510 got_object_commit_get_author(commit),
8511 got_object_commit_get_committer_time(commit));
8513 logmsg = got_object_commit_get_logmsg_raw(commit);
8514 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
8515 fprintf(outfile, "%s", logmsg);
8516 done:
8517 free(id_str);
8518 got_object_commit_close(commit);
8519 return err;
8522 static const struct got_error *
8523 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8525 const struct got_error *err;
8526 struct got_tag_object *tag;
8527 char *id_str = NULL;
8528 const char *tagmsg = NULL;
8530 err = got_object_open_as_tag(&tag, repo, id);
8531 if (err)
8532 return err;
8534 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
8535 if (err)
8536 goto done;
8538 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
8540 switch (got_object_tag_get_object_type(tag)) {
8541 case GOT_OBJ_TYPE_BLOB:
8542 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8543 GOT_OBJ_LABEL_BLOB);
8544 break;
8545 case GOT_OBJ_TYPE_TREE:
8546 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8547 GOT_OBJ_LABEL_TREE);
8548 break;
8549 case GOT_OBJ_TYPE_COMMIT:
8550 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8551 GOT_OBJ_LABEL_COMMIT);
8552 break;
8553 case GOT_OBJ_TYPE_TAG:
8554 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8555 GOT_OBJ_LABEL_TAG);
8556 break;
8557 default:
8558 break;
8561 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
8562 got_object_tag_get_name(tag));
8564 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
8565 got_object_tag_get_tagger(tag),
8566 got_object_tag_get_tagger_time(tag));
8568 tagmsg = got_object_tag_get_message(tag);
8569 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
8570 fprintf(outfile, "%s", tagmsg);
8571 done:
8572 free(id_str);
8573 got_object_tag_close(tag);
8574 return err;
8577 static const struct got_error *
8578 cmd_cat(int argc, char *argv[])
8580 const struct got_error *error;
8581 struct got_repository *repo = NULL;
8582 struct got_worktree *worktree = NULL;
8583 char *cwd = NULL, *repo_path = NULL, *label = NULL;
8584 const char *commit_id_str = NULL;
8585 struct got_object_id *id = NULL, *commit_id = NULL;
8586 int ch, obj_type, i, force_path = 0;
8588 #ifndef PROFILE
8589 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8590 NULL) == -1)
8591 err(1, "pledge");
8592 #endif
8594 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
8595 switch (ch) {
8596 case 'c':
8597 commit_id_str = optarg;
8598 break;
8599 case 'r':
8600 repo_path = realpath(optarg, NULL);
8601 if (repo_path == NULL)
8602 return got_error_from_errno2("realpath",
8603 optarg);
8604 got_path_strip_trailing_slashes(repo_path);
8605 break;
8606 case 'P':
8607 force_path = 1;
8608 break;
8609 default:
8610 usage_cat();
8611 /* NOTREACHED */
8615 argc -= optind;
8616 argv += optind;
8618 cwd = getcwd(NULL, 0);
8619 if (cwd == NULL) {
8620 error = got_error_from_errno("getcwd");
8621 goto done;
8623 error = got_worktree_open(&worktree, cwd);
8624 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8625 goto done;
8626 if (worktree) {
8627 if (repo_path == NULL) {
8628 repo_path = strdup(
8629 got_worktree_get_repo_path(worktree));
8630 if (repo_path == NULL) {
8631 error = got_error_from_errno("strdup");
8632 goto done;
8637 if (repo_path == NULL) {
8638 repo_path = getcwd(NULL, 0);
8639 if (repo_path == NULL)
8640 return got_error_from_errno("getcwd");
8643 error = got_repo_open(&repo, repo_path, NULL);
8644 free(repo_path);
8645 if (error != NULL)
8646 goto done;
8648 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
8649 if (error)
8650 goto done;
8652 if (commit_id_str == NULL)
8653 commit_id_str = GOT_REF_HEAD;
8654 error = got_repo_match_object_id(&commit_id, NULL,
8655 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
8656 if (error)
8657 goto done;
8659 for (i = 0; i < argc; i++) {
8660 if (force_path) {
8661 error = got_object_id_by_path(&id, repo, commit_id,
8662 argv[i]);
8663 if (error)
8664 break;
8665 } else {
8666 error = got_repo_match_object_id(&id, &label, argv[i],
8667 GOT_OBJ_TYPE_ANY, 0, repo);
8668 if (error) {
8669 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
8670 error->code != GOT_ERR_NOT_REF)
8671 break;
8672 error = got_object_id_by_path(&id, repo,
8673 commit_id, argv[i]);
8674 if (error)
8675 break;
8679 error = got_object_get_type(&obj_type, repo, id);
8680 if (error)
8681 break;
8683 switch (obj_type) {
8684 case GOT_OBJ_TYPE_BLOB:
8685 error = cat_blob(id, repo, stdout);
8686 break;
8687 case GOT_OBJ_TYPE_TREE:
8688 error = cat_tree(id, repo, stdout);
8689 break;
8690 case GOT_OBJ_TYPE_COMMIT:
8691 error = cat_commit(id, repo, stdout);
8692 break;
8693 case GOT_OBJ_TYPE_TAG:
8694 error = cat_tag(id, repo, stdout);
8695 break;
8696 default:
8697 error = got_error(GOT_ERR_OBJ_TYPE);
8698 break;
8700 if (error)
8701 break;
8702 free(label);
8703 label = NULL;
8704 free(id);
8705 id = NULL;
8707 done:
8708 free(label);
8709 free(id);
8710 free(commit_id);
8711 if (worktree)
8712 got_worktree_close(worktree);
8713 if (repo) {
8714 const struct got_error *repo_error;
8715 repo_error = got_repo_close(repo);
8716 if (error == NULL)
8717 error = repo_error;
8719 return error;