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 "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, struct got_repository *repo)
890 const struct got_error *err;
891 struct got_reference *head_symref;
893 err = got_ref_alloc_symref(&head_symref, GOT_REF_HEAD, target_ref);
894 if (err)
895 return err;
897 err = got_ref_write(head_symref, repo);
898 got_ref_close(head_symref);
899 return err;
902 static const struct got_error *
903 list_remote_refs(struct got_pathlist_head *symrefs,
904 struct got_pathlist_head *refs)
906 const struct got_error *err;
907 struct got_pathlist_entry *pe;
909 TAILQ_FOREACH(pe, symrefs, entry) {
910 const char *refname = pe->path;
911 const char *targetref = pe->data;
913 printf("%s: %s\n", refname, targetref);
916 TAILQ_FOREACH(pe, refs, entry) {
917 const char *refname = pe->path;
918 struct got_object_id *id = pe->data;
919 char *id_str;
921 err = got_object_id_str(&id_str, id);
922 if (err)
923 return err;
924 printf("%s: %s\n", refname, id_str);
925 free(id_str);
928 return NULL;
931 static const struct got_error *
932 cmd_clone(int argc, char *argv[])
934 const struct got_error *error = NULL;
935 const char *uri, *dirname;
936 char *proto, *host, *port, *repo_name, *server_path;
937 char *default_destdir = NULL, *id_str = NULL;
938 const char *repo_path;
939 struct got_repository *repo = NULL;
940 struct got_pathlist_head refs, symrefs, wanted_branches;
941 struct got_pathlist_entry *pe;
942 struct got_object_id *pack_hash = NULL;
943 int ch, fetchfd = -1, fetchstatus;
944 pid_t fetchpid = -1;
945 struct got_fetch_progress_arg fpa;
946 char *git_url = NULL;
947 char *gitconfig_path = NULL;
948 char *gitconfig = NULL;
949 FILE *gitconfig_file = NULL;
950 ssize_t n;
951 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
952 int list_refs_only = 0;
953 struct got_reference *head_symref = NULL;
955 TAILQ_INIT(&refs);
956 TAILQ_INIT(&symrefs);
957 TAILQ_INIT(&wanted_branches);
959 while ((ch = getopt(argc, argv, "ab:lmvq")) != -1) {
960 switch (ch) {
961 case 'a':
962 fetch_all_branches = 1;
963 break;
964 case 'b':
965 error = got_pathlist_append(&wanted_branches,
966 optarg, NULL);
967 if (error)
968 return error;
969 break;
970 case 'l':
971 list_refs_only = 1;
972 break;
973 case 'm':
974 mirror_references = 1;
975 break;
976 case 'v':
977 if (verbosity < 0)
978 verbosity = 0;
979 else if (verbosity < 3)
980 verbosity++;
981 break;
982 case 'q':
983 verbosity = -1;
984 break;
985 default:
986 usage_clone();
987 break;
990 argc -= optind;
991 argv += optind;
993 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
994 errx(1, "-a and -b options are mutually exclusive");
995 if (list_refs_only) {
996 if (!TAILQ_EMPTY(&wanted_branches))
997 errx(1, "-l and -b options are mutually exclusive");
998 if (fetch_all_branches)
999 errx(1, "-l and -a options are mutually exclusive");
1000 if (mirror_references)
1001 errx(1, "-l and -m options are mutually exclusive");
1002 if (verbosity == -1)
1003 errx(1, "-l and -q options are mutually exclusive");
1006 uri = argv[0];
1008 if (argc == 1)
1009 dirname = NULL;
1010 else if (argc == 2)
1011 dirname = argv[1];
1012 else
1013 usage_clone();
1015 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1016 &repo_name, argv[0]);
1017 if (error)
1018 goto done;
1020 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1021 host, port ? ":" : "", port ? port : "",
1022 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1023 error = got_error_from_errno("asprintf");
1024 goto done;
1027 if (strcmp(proto, "git") == 0) {
1028 #ifndef PROFILE
1029 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1030 "sendfd dns inet unveil", NULL) == -1)
1031 err(1, "pledge");
1032 #endif
1033 } else if (strcmp(proto, "git+ssh") == 0 ||
1034 strcmp(proto, "ssh") == 0) {
1035 #ifndef PROFILE
1036 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1037 "sendfd unveil", NULL) == -1)
1038 err(1, "pledge");
1039 #endif
1040 } else if (strcmp(proto, "http") == 0 ||
1041 strcmp(proto, "git+http") == 0) {
1042 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1043 goto done;
1044 } else {
1045 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1046 goto done;
1048 if (dirname == NULL) {
1049 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1050 error = got_error_from_errno("asprintf");
1051 goto done;
1053 repo_path = default_destdir;
1054 } else
1055 repo_path = dirname;
1057 if (!list_refs_only) {
1058 error = got_path_mkdir(repo_path);
1059 if (error)
1060 goto done;
1062 error = got_repo_init(repo_path);
1063 if (error)
1064 goto done;
1065 error = got_repo_open(&repo, repo_path, NULL);
1066 if (error)
1067 goto done;
1070 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1071 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1072 error = got_error_from_errno2("unveil",
1073 GOT_FETCH_PATH_SSH);
1074 goto done;
1077 error = apply_unveil(repo ? got_repo_get_path(repo) : NULL, 0, NULL);
1078 if (error)
1079 goto done;
1081 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1082 server_path, verbosity);
1083 if (error)
1084 goto done;
1086 if (verbosity >= 0)
1087 printf("Connected to %s%s%s\n", host,
1088 port ? ":" : "", port ? port : "");
1090 fpa.last_scaled_size[0] = '\0';
1091 fpa.last_p_indexed = -1;
1092 fpa.last_p_resolved = -1;
1093 fpa.verbosity = verbosity;
1094 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1095 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1096 fetch_all_branches, &wanted_branches, list_refs_only,
1097 fetchfd, repo, fetch_progress, &fpa);
1098 if (error)
1099 goto done;
1101 if (list_refs_only) {
1102 error = list_remote_refs(&symrefs, &refs);
1103 goto done;
1106 error = got_object_id_str(&id_str, pack_hash);
1107 if (error)
1108 goto done;
1109 if (verbosity >= 0)
1110 printf("\nFetched %s.pack\n", id_str);
1111 free(id_str);
1113 /* Set up references provided with the pack file. */
1114 TAILQ_FOREACH(pe, &refs, entry) {
1115 const char *refname = pe->path;
1116 struct got_object_id *id = pe->data;
1117 struct got_reference *ref;
1118 char *remote_refname;
1120 error = got_ref_alloc(&ref, refname, id);
1121 if (error)
1122 goto done;
1123 error = got_ref_write(ref, repo);
1124 got_ref_close(ref);
1125 if (error)
1126 goto done;
1128 if (mirror_references)
1129 continue;
1131 if (strncmp("refs/heads/", refname, 11) != 0)
1132 continue;
1134 if (asprintf(&remote_refname,
1135 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1136 refname + 11) == -1) {
1137 error = got_error_from_errno("asprintf");
1138 goto done;
1140 error = got_ref_alloc(&ref, remote_refname, id);
1141 if (error)
1142 goto done;
1143 error = got_ref_write(ref, repo);
1144 got_ref_close(ref);
1145 if (error)
1146 goto done;
1149 /* Set the HEAD reference if the server provided one. */
1150 TAILQ_FOREACH(pe, &symrefs, entry) {
1151 struct got_reference *target_ref;
1152 const char *refname = pe->path;
1153 const char *target = pe->data;
1155 if (strcmp(refname, GOT_REF_HEAD) != 0)
1156 continue;
1158 error = got_ref_open(&target_ref, repo, target, 0);
1159 if (error) {
1160 if (error->code == GOT_ERR_NOT_REF) {
1161 error = NULL;
1162 continue;
1164 goto done;
1167 if (verbosity >= 0)
1168 printf("Setting %s to %s\n", refname, target);
1169 error = create_head_ref(target_ref, repo);
1170 got_ref_close(target_ref);
1171 if (error)
1172 goto done;
1174 if (pe == NULL) {
1176 * We failed to set the HEAD reference. If we asked for
1177 * a set of wanted branches use the first of one of those
1178 * which could be fetched instead.
1180 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1181 const char *target = pe->path;
1182 struct got_reference *target_ref;
1184 error = got_ref_open(&target_ref, repo, target, 0);
1185 if (error) {
1186 if (error->code == GOT_ERR_NOT_REF) {
1187 error = NULL;
1188 continue;
1190 goto done;
1193 if (verbosity >= 0)
1194 printf("Setting %s to %s\n", GOT_REF_HEAD,
1195 got_ref_get_name(target_ref));
1196 error = create_head_ref(target_ref, repo);
1197 got_ref_close(target_ref);
1198 if (error)
1199 goto done;
1200 break;
1204 /* Create a config file git-fetch(1) can understand. */
1205 gitconfig_path = got_repo_get_path_gitconfig(repo);
1206 if (gitconfig_path == NULL) {
1207 error = got_error_from_errno("got_repo_get_path_gitconfig");
1208 goto done;
1210 gitconfig_file = fopen(gitconfig_path, "a");
1211 if (gitconfig_file == NULL) {
1212 error = got_error_from_errno2("fopen", gitconfig_path);
1213 goto done;
1215 if (mirror_references) {
1216 if (asprintf(&gitconfig,
1217 "[remote \"%s\"]\n"
1218 "\turl = %s\n"
1219 "\tfetch = +refs/*:refs/*\n"
1220 "\tmirror = true\n",
1221 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1222 error = got_error_from_errno("asprintf");
1223 goto done;
1225 } else if (fetch_all_branches) {
1226 if (asprintf(&gitconfig,
1227 "[remote \"%s\"]\n"
1228 "\turl = %s\n"
1229 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1230 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1231 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1232 error = got_error_from_errno("asprintf");
1233 goto done;
1235 } else {
1236 const char *branchname;
1239 * If the server specified a default branch, use just that one.
1240 * Otherwise fall back to fetching all branches on next fetch.
1242 if (head_symref) {
1243 branchname = got_ref_get_symref_target(head_symref);
1244 if (strncmp(branchname, "refs/heads/", 11) == 0)
1245 branchname += 11;
1246 } else
1247 branchname = "*"; /* fall back to all branches */
1248 if (asprintf(&gitconfig,
1249 "[remote \"%s\"]\n"
1250 "\turl = %s\n"
1251 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1252 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1253 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1254 branchname) == -1) {
1255 error = got_error_from_errno("asprintf");
1256 goto done;
1259 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1260 if (n != strlen(gitconfig)) {
1261 error = got_ferror(gitconfig_file, GOT_ERR_IO);
1262 goto done;
1266 if (verbosity >= 0)
1267 printf("Created %s repository '%s'\n",
1268 mirror_references ? "mirrored" : "cloned", repo_path);
1269 done:
1270 if (fetchpid > 0) {
1271 if (kill(fetchpid, SIGTERM) == -1)
1272 error = got_error_from_errno("kill");
1273 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1274 error = got_error_from_errno("waitpid");
1276 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1277 error = got_error_from_errno("close");
1278 if (gitconfig_file && fclose(gitconfig_file) == EOF && error == NULL)
1279 error = got_error_from_errno("fclose");
1280 if (repo)
1281 got_repo_close(repo);
1282 if (head_symref)
1283 got_ref_close(head_symref);
1284 TAILQ_FOREACH(pe, &refs, entry) {
1285 free((void *)pe->path);
1286 free(pe->data);
1288 got_pathlist_free(&refs);
1289 TAILQ_FOREACH(pe, &symrefs, entry) {
1290 free((void *)pe->path);
1291 free(pe->data);
1293 got_pathlist_free(&symrefs);
1294 got_pathlist_free(&wanted_branches);
1295 free(pack_hash);
1296 free(proto);
1297 free(host);
1298 free(port);
1299 free(server_path);
1300 free(repo_name);
1301 free(default_destdir);
1302 free(gitconfig_path);
1303 free(git_url);
1304 return error;
1307 static const struct got_error *
1308 create_ref(const char *refname, struct got_object_id *id,
1309 const char *id_str, int verbosity, struct got_repository *repo)
1311 const struct got_error *err = NULL;
1312 struct got_reference *ref;
1314 if (verbosity >= 0)
1315 printf("Creating %s: %s\n", refname, id_str);
1317 err = got_ref_alloc(&ref, refname, id);
1318 if (err)
1319 return err;
1321 err = got_ref_write(ref, repo);
1322 got_ref_close(ref);
1323 return err;
1326 static const struct got_error *
1327 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1328 int verbosity, struct got_repository *repo)
1330 const struct got_error *err = NULL;
1331 char *new_id_str = NULL;
1332 struct got_object_id *old_id = NULL;
1334 err = got_object_id_str(&new_id_str, new_id);
1335 if (err)
1336 goto done;
1338 if (got_ref_is_symbolic(ref)) {
1339 struct got_reference *new_ref;
1340 err = got_ref_alloc(&new_ref, got_ref_get_name(ref), new_id);
1341 if (err)
1342 goto done;
1343 if (verbosity >= 0) {
1344 printf("Deleting symbolic reference %s -> %s\n",
1345 got_ref_get_name(ref),
1346 got_ref_get_symref_target(ref));
1348 err = got_ref_delete(ref, repo);
1349 if (err)
1350 goto done;
1351 if (verbosity >= 0) {
1352 printf("Setting %s to %s\n", got_ref_get_name(ref),
1353 new_id_str);
1355 err = got_ref_write(new_ref, repo);
1356 if (err)
1357 goto done;
1358 } else {
1359 err = got_ref_resolve(&old_id, repo, ref);
1360 if (err)
1361 goto done;
1362 if (got_object_id_cmp(old_id, new_id) != 0) {
1363 if (verbosity >= 0) {
1364 printf("Setting %s to %s\n",
1365 got_ref_get_name(ref), new_id_str);
1367 err = got_ref_change_ref(ref, new_id);
1368 if (err)
1369 goto done;
1370 err = got_ref_write(ref, repo);
1371 if (err)
1372 goto done;
1375 done:
1376 free(old_id);
1377 free(new_id_str);
1378 return err;
1381 __dead static void
1382 usage_fetch(void)
1384 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1385 "[-r repository-path] [-q] [-v] [remote-repository-name]\n",
1386 getprogname());
1387 exit(1);
1390 static const struct got_error *
1391 delete_missing_refs(struct got_pathlist_head *their_refs,
1392 int verbosity, struct got_repository *repo)
1394 const struct got_error *err = NULL;
1395 struct got_reflist_head my_refs;
1396 struct got_reflist_entry *re;
1397 struct got_pathlist_entry *pe;
1398 struct got_object_id *id;
1399 char *id_str;
1401 SIMPLEQ_INIT(&my_refs);
1403 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1404 if (err)
1405 return err;
1407 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1408 const char *refname = got_ref_get_name(re->ref);
1410 if (strncmp(refname, "refs/heads/", 11) != 0 &&
1411 strncmp(refname, "refs/tags/", 10) != 0)
1412 continue;
1414 TAILQ_FOREACH(pe, their_refs, entry) {
1415 if (strcmp(refname, pe->path) == 0)
1416 break;
1418 if (pe != NULL)
1419 continue;
1421 err = got_ref_resolve(&id, repo, re->ref);
1422 if (err)
1423 break;
1424 err = got_object_id_str(&id_str, id);
1425 free(id);
1426 if (err)
1427 break;
1429 if (verbosity >= 0) {
1430 printf("Deleting %s: %s\n",
1431 got_ref_get_name(re->ref), id_str);
1433 free(id_str);
1434 err = got_ref_delete(re->ref, repo);
1435 if (err)
1436 break;
1439 return err;
1442 static const struct got_error *
1443 cmd_fetch(int argc, char *argv[])
1445 const struct got_error *error = NULL;
1446 char *cwd = NULL, *repo_path = NULL;
1447 const char *remote_name;
1448 char *proto = NULL, *host = NULL, *port = NULL;
1449 char *repo_name = NULL, *server_path = NULL;
1450 struct got_remote_repo *remotes, *remote = NULL;
1451 int nremotes;
1452 char *id_str = NULL;
1453 struct got_repository *repo = NULL;
1454 struct got_worktree *worktree = NULL;
1455 struct got_pathlist_head refs, symrefs, wanted_branches;
1456 struct got_pathlist_entry *pe;
1457 struct got_object_id *pack_hash = NULL;
1458 int i, ch, fetchfd = -1, fetchstatus;
1459 pid_t fetchpid = -1;
1460 struct got_fetch_progress_arg fpa;
1461 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
1462 int delete_refs = 0;
1464 TAILQ_INIT(&refs);
1465 TAILQ_INIT(&symrefs);
1466 TAILQ_INIT(&wanted_branches);
1468 while ((ch = getopt(argc, argv, "ab:dlr:vq")) != -1) {
1469 switch (ch) {
1470 case 'a':
1471 fetch_all_branches = 1;
1472 break;
1473 case 'b':
1474 error = got_pathlist_append(&wanted_branches,
1475 optarg, NULL);
1476 if (error)
1477 return error;
1478 break;
1479 case 'd':
1480 delete_refs = 1;
1481 break;
1482 case 'l':
1483 list_refs_only = 1;
1484 break;
1485 case 'r':
1486 repo_path = realpath(optarg, NULL);
1487 if (repo_path == NULL)
1488 return got_error_from_errno2("realpath",
1489 optarg);
1490 got_path_strip_trailing_slashes(repo_path);
1491 break;
1492 case 'v':
1493 if (verbosity < 0)
1494 verbosity = 0;
1495 else if (verbosity < 3)
1496 verbosity++;
1497 break;
1498 case 'q':
1499 verbosity = -1;
1500 break;
1501 default:
1502 usage_fetch();
1503 break;
1506 argc -= optind;
1507 argv += optind;
1509 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1510 errx(1, "-a and -b options are mutually exclusive");
1511 if (list_refs_only) {
1512 if (!TAILQ_EMPTY(&wanted_branches))
1513 errx(1, "-l and -b options are mutually exclusive");
1514 if (fetch_all_branches)
1515 errx(1, "-l and -a options are mutually exclusive");
1516 if (delete_refs)
1517 errx(1, "-l and -d options are mutually exclusive");
1518 if (verbosity == -1)
1519 errx(1, "-l and -q options are mutually exclusive");
1522 if (argc == 0)
1523 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
1524 else if (argc == 1)
1525 remote_name = argv[0];
1526 else
1527 usage_fetch();
1529 cwd = getcwd(NULL, 0);
1530 if (cwd == NULL) {
1531 error = got_error_from_errno("getcwd");
1532 goto done;
1535 if (repo_path == NULL) {
1536 error = got_worktree_open(&worktree, cwd);
1537 if (error && error->code != GOT_ERR_NOT_WORKTREE)
1538 goto done;
1539 else
1540 error = NULL;
1541 if (worktree) {
1542 repo_path =
1543 strdup(got_worktree_get_repo_path(worktree));
1544 if (repo_path == NULL)
1545 error = got_error_from_errno("strdup");
1546 if (error)
1547 goto done;
1548 } else {
1549 repo_path = strdup(cwd);
1550 if (repo_path == NULL) {
1551 error = got_error_from_errno("strdup");
1552 goto done;
1557 error = got_repo_open(&repo, repo_path, NULL);
1558 if (error)
1559 goto done;
1561 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
1562 for (i = 0; i < nremotes; i++) {
1563 remote = &remotes[i];
1564 if (strcmp(remote->name, remote_name) == 0)
1565 break;
1567 if (i == nremotes) {
1568 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
1569 goto done;
1572 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1573 &repo_name, remote->url);
1574 if (error)
1575 goto done;
1577 if (strcmp(proto, "git") == 0) {
1578 #ifndef PROFILE
1579 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1580 "sendfd dns inet unveil", NULL) == -1)
1581 err(1, "pledge");
1582 #endif
1583 } else if (strcmp(proto, "git+ssh") == 0 ||
1584 strcmp(proto, "ssh") == 0) {
1585 #ifndef PROFILE
1586 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1587 "sendfd unveil", NULL) == -1)
1588 err(1, "pledge");
1589 #endif
1590 } else if (strcmp(proto, "http") == 0 ||
1591 strcmp(proto, "git+http") == 0) {
1592 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1593 goto done;
1594 } else {
1595 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1596 goto done;
1599 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1600 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1601 error = got_error_from_errno2("unveil",
1602 GOT_FETCH_PATH_SSH);
1603 goto done;
1606 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
1607 if (error)
1608 goto done;
1610 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1611 server_path, verbosity);
1612 if (error)
1613 goto done;
1615 if (verbosity >= 0)
1616 printf("Connected to \"%s\" %s%s%s\n", remote->name, host,
1617 port ? ":" : "", port ? port : "");
1619 fpa.last_scaled_size[0] = '\0';
1620 fpa.last_p_indexed = -1;
1621 fpa.last_p_resolved = -1;
1622 fpa.verbosity = verbosity;
1623 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
1624 remote->mirror_references, fetch_all_branches, &wanted_branches,
1625 list_refs_only, fetchfd, repo, fetch_progress, &fpa);
1626 if (error)
1627 goto done;
1629 if (list_refs_only) {
1630 error = list_remote_refs(&symrefs, &refs);
1631 goto done;
1634 if (pack_hash == NULL) {
1635 if (verbosity >= 0)
1636 printf("Already up-to-date\n");
1637 if (delete_refs)
1638 error = delete_missing_refs(&refs, verbosity, repo);
1639 goto done;
1642 if (verbosity >= 0) {
1643 error = got_object_id_str(&id_str, pack_hash);
1644 if (error)
1645 goto done;
1646 printf("\nFetched %s.pack\n", id_str);
1647 free(id_str);
1648 id_str = NULL;
1651 /* Update references provided with the pack file. */
1652 TAILQ_FOREACH(pe, &refs, entry) {
1653 const char *refname = pe->path;
1654 struct got_object_id *id = pe->data;
1655 struct got_reference *ref;
1656 char *remote_refname;
1658 error = got_object_id_str(&id_str, id);
1659 if (error)
1660 goto done;
1662 if (remote->mirror_references ||
1663 strncmp("refs/tags/", refname, 10) == 0) {
1664 error = got_ref_open(&ref, repo, refname, 0);
1665 if (error) {
1666 if (error->code != GOT_ERR_NOT_REF)
1667 goto done;
1668 error = create_ref(refname, id, id_str,
1669 verbosity, repo);
1670 if (error)
1671 goto done;
1672 } else {
1673 error = update_ref(ref, id, verbosity, repo);
1674 got_ref_close(ref);
1675 if (error)
1676 goto done;
1678 } else if (strncmp("refs/heads/", refname, 11) == 0) {
1679 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1680 remote_name, refname + 11) == -1) {
1681 error = got_error_from_errno("asprintf");
1682 goto done;
1685 error = got_ref_open(&ref, repo, remote_refname, 0);
1686 if (error) {
1687 if (error->code != GOT_ERR_NOT_REF)
1688 goto done;
1689 error = create_ref(remote_refname, id, id_str,
1690 verbosity, repo);
1691 if (error)
1692 goto done;
1693 } else {
1694 error = update_ref(ref, id, verbosity, repo);
1695 got_ref_close(ref);
1696 if (error)
1697 goto done;
1700 /* Also create a local branch if none exists yet. */
1701 error = got_ref_open(&ref, repo, refname, 0);
1702 if (error) {
1703 if (error->code != GOT_ERR_NOT_REF)
1704 goto done;
1705 error = create_ref(refname, id, id_str,
1706 verbosity, repo);
1707 if (error)
1708 goto done;
1709 } else
1710 got_ref_close(ref);
1712 free(id_str);
1713 id_str = NULL;
1715 if (delete_refs)
1716 error = delete_missing_refs(&refs, verbosity, repo);
1717 done:
1718 if (fetchpid > 0) {
1719 if (kill(fetchpid, SIGTERM) == -1)
1720 error = got_error_from_errno("kill");
1721 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1722 error = got_error_from_errno("waitpid");
1724 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1725 error = got_error_from_errno("close");
1726 if (repo)
1727 got_repo_close(repo);
1728 if (worktree)
1729 got_worktree_close(worktree);
1730 TAILQ_FOREACH(pe, &refs, entry) {
1731 free((void *)pe->path);
1732 free(pe->data);
1734 got_pathlist_free(&refs);
1735 TAILQ_FOREACH(pe, &symrefs, entry) {
1736 free((void *)pe->path);
1737 free(pe->data);
1739 got_pathlist_free(&symrefs);
1740 got_pathlist_free(&wanted_branches);
1741 free(id_str);
1742 free(cwd);
1743 free(repo_path);
1744 free(pack_hash);
1745 free(proto);
1746 free(host);
1747 free(port);
1748 free(server_path);
1749 free(repo_name);
1750 return error;
1754 __dead static void
1755 usage_checkout(void)
1757 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
1758 "[-p prefix] repository-path [worktree-path]\n", getprogname());
1759 exit(1);
1762 static void
1763 show_worktree_base_ref_warning(void)
1765 fprintf(stderr, "%s: warning: could not create a reference "
1766 "to the work tree's base commit; the commit could be "
1767 "garbage-collected by Git; making the repository "
1768 "writable and running 'got update' will prevent this\n",
1769 getprogname());
1772 struct got_checkout_progress_arg {
1773 const char *worktree_path;
1774 int had_base_commit_ref_error;
1777 static const struct got_error *
1778 checkout_progress(void *arg, unsigned char status, const char *path)
1780 struct got_checkout_progress_arg *a = arg;
1782 /* Base commit bump happens silently. */
1783 if (status == GOT_STATUS_BUMP_BASE)
1784 return NULL;
1786 if (status == GOT_STATUS_BASE_REF_ERR) {
1787 a->had_base_commit_ref_error = 1;
1788 return NULL;
1791 while (path[0] == '/')
1792 path++;
1794 printf("%c %s/%s\n", status, a->worktree_path, path);
1795 return NULL;
1798 static const struct got_error *
1799 check_cancelled(void *arg)
1801 if (sigint_received || sigpipe_received)
1802 return got_error(GOT_ERR_CANCELLED);
1803 return NULL;
1806 static const struct got_error *
1807 check_linear_ancestry(struct got_object_id *commit_id,
1808 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
1809 struct got_repository *repo)
1811 const struct got_error *err = NULL;
1812 struct got_object_id *yca_id;
1814 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
1815 commit_id, base_commit_id, repo, check_cancelled, NULL);
1816 if (err)
1817 return err;
1819 if (yca_id == NULL)
1820 return got_error(GOT_ERR_ANCESTRY);
1823 * Require a straight line of history between the target commit
1824 * and the work tree's base commit.
1826 * Non-linear situations such as this require a rebase:
1828 * (commit) D F (base_commit)
1829 * \ /
1830 * C E
1831 * \ /
1832 * B (yca)
1833 * |
1834 * A
1836 * 'got update' only handles linear cases:
1837 * Update forwards in time: A (base/yca) - B - C - D (commit)
1838 * Update backwards in time: D (base) - C - B - A (commit/yca)
1840 if (allow_forwards_in_time_only) {
1841 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
1842 return got_error(GOT_ERR_ANCESTRY);
1843 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
1844 got_object_id_cmp(base_commit_id, yca_id) != 0)
1845 return got_error(GOT_ERR_ANCESTRY);
1847 free(yca_id);
1848 return NULL;
1851 static const struct got_error *
1852 check_same_branch(struct got_object_id *commit_id,
1853 struct got_reference *head_ref, struct got_object_id *yca_id,
1854 struct got_repository *repo)
1856 const struct got_error *err = NULL;
1857 struct got_commit_graph *graph = NULL;
1858 struct got_object_id *head_commit_id = NULL;
1859 int is_same_branch = 0;
1861 err = got_ref_resolve(&head_commit_id, repo, head_ref);
1862 if (err)
1863 goto done;
1865 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
1866 is_same_branch = 1;
1867 goto done;
1869 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
1870 is_same_branch = 1;
1871 goto done;
1874 err = got_commit_graph_open(&graph, "/", 1);
1875 if (err)
1876 goto done;
1878 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
1879 check_cancelled, NULL);
1880 if (err)
1881 goto done;
1883 for (;;) {
1884 struct got_object_id *id;
1885 err = got_commit_graph_iter_next(&id, graph, repo,
1886 check_cancelled, NULL);
1887 if (err) {
1888 if (err->code == GOT_ERR_ITER_COMPLETED)
1889 err = NULL;
1890 break;
1893 if (id) {
1894 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
1895 break;
1896 if (got_object_id_cmp(id, commit_id) == 0) {
1897 is_same_branch = 1;
1898 break;
1902 done:
1903 if (graph)
1904 got_commit_graph_close(graph);
1905 free(head_commit_id);
1906 if (!err && !is_same_branch)
1907 err = got_error(GOT_ERR_ANCESTRY);
1908 return err;
1911 static const struct got_error *
1912 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
1914 static char msg[512];
1915 const char *branch_name;
1917 if (got_ref_is_symbolic(ref))
1918 branch_name = got_ref_get_symref_target(ref);
1919 else
1920 branch_name = got_ref_get_name(ref);
1922 if (strncmp("refs/heads/", branch_name, 11) == 0)
1923 branch_name += 11;
1925 snprintf(msg, sizeof(msg),
1926 "target commit is not contained in branch '%s'; "
1927 "the branch to use must be specified with -b; "
1928 "if necessary a new branch can be created for "
1929 "this commit with 'got branch -c %s BRANCH_NAME'",
1930 branch_name, commit_id_str);
1932 return got_error_msg(GOT_ERR_ANCESTRY, msg);
1935 static const struct got_error *
1936 cmd_checkout(int argc, char *argv[])
1938 const struct got_error *error = NULL;
1939 struct got_repository *repo = NULL;
1940 struct got_reference *head_ref = NULL;
1941 struct got_worktree *worktree = NULL;
1942 char *repo_path = NULL;
1943 char *worktree_path = NULL;
1944 const char *path_prefix = "";
1945 const char *branch_name = GOT_REF_HEAD;
1946 char *commit_id_str = NULL;
1947 int ch, same_path_prefix, allow_nonempty = 0;
1948 struct got_pathlist_head paths;
1949 struct got_checkout_progress_arg cpa;
1951 TAILQ_INIT(&paths);
1953 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
1954 switch (ch) {
1955 case 'b':
1956 branch_name = optarg;
1957 break;
1958 case 'c':
1959 commit_id_str = strdup(optarg);
1960 if (commit_id_str == NULL)
1961 return got_error_from_errno("strdup");
1962 break;
1963 case 'E':
1964 allow_nonempty = 1;
1965 break;
1966 case 'p':
1967 path_prefix = optarg;
1968 break;
1969 default:
1970 usage_checkout();
1971 /* NOTREACHED */
1975 argc -= optind;
1976 argv += optind;
1978 #ifndef PROFILE
1979 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
1980 "unveil", NULL) == -1)
1981 err(1, "pledge");
1982 #endif
1983 if (argc == 1) {
1984 char *cwd, *base, *dotgit;
1985 repo_path = realpath(argv[0], NULL);
1986 if (repo_path == NULL)
1987 return got_error_from_errno2("realpath", argv[0]);
1988 cwd = getcwd(NULL, 0);
1989 if (cwd == NULL) {
1990 error = got_error_from_errno("getcwd");
1991 goto done;
1993 if (path_prefix[0]) {
1994 base = basename(path_prefix);
1995 if (base == NULL) {
1996 error = got_error_from_errno2("basename",
1997 path_prefix);
1998 goto done;
2000 } else {
2001 base = basename(repo_path);
2002 if (base == NULL) {
2003 error = got_error_from_errno2("basename",
2004 repo_path);
2005 goto done;
2008 dotgit = strstr(base, ".git");
2009 if (dotgit)
2010 *dotgit = '\0';
2011 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2012 error = got_error_from_errno("asprintf");
2013 free(cwd);
2014 goto done;
2016 free(cwd);
2017 } else if (argc == 2) {
2018 repo_path = realpath(argv[0], NULL);
2019 if (repo_path == NULL) {
2020 error = got_error_from_errno2("realpath", argv[0]);
2021 goto done;
2023 worktree_path = realpath(argv[1], NULL);
2024 if (worktree_path == NULL) {
2025 if (errno != ENOENT) {
2026 error = got_error_from_errno2("realpath",
2027 argv[1]);
2028 goto done;
2030 worktree_path = strdup(argv[1]);
2031 if (worktree_path == NULL) {
2032 error = got_error_from_errno("strdup");
2033 goto done;
2036 } else
2037 usage_checkout();
2039 got_path_strip_trailing_slashes(repo_path);
2040 got_path_strip_trailing_slashes(worktree_path);
2042 error = got_repo_open(&repo, repo_path, NULL);
2043 if (error != NULL)
2044 goto done;
2046 /* Pre-create work tree path for unveil(2) */
2047 error = got_path_mkdir(worktree_path);
2048 if (error) {
2049 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2050 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2051 goto done;
2052 if (!allow_nonempty &&
2053 !got_path_dir_is_empty(worktree_path)) {
2054 error = got_error_path(worktree_path,
2055 GOT_ERR_DIR_NOT_EMPTY);
2056 goto done;
2060 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2061 if (error)
2062 goto done;
2064 error = got_ref_open(&head_ref, repo, branch_name, 0);
2065 if (error != NULL)
2066 goto done;
2068 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2069 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2070 goto done;
2072 error = got_worktree_open(&worktree, worktree_path);
2073 if (error != NULL)
2074 goto done;
2076 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2077 path_prefix);
2078 if (error != NULL)
2079 goto done;
2080 if (!same_path_prefix) {
2081 error = got_error(GOT_ERR_PATH_PREFIX);
2082 goto done;
2085 if (commit_id_str) {
2086 struct got_object_id *commit_id;
2087 error = got_repo_match_object_id(&commit_id, NULL,
2088 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2089 if (error)
2090 goto done;
2091 error = check_linear_ancestry(commit_id,
2092 got_worktree_get_base_commit_id(worktree), 0, repo);
2093 if (error != NULL) {
2094 free(commit_id);
2095 if (error->code == GOT_ERR_ANCESTRY) {
2096 error = checkout_ancestry_error(
2097 head_ref, commit_id_str);
2099 goto done;
2101 error = check_same_branch(commit_id, head_ref, NULL, repo);
2102 if (error) {
2103 if (error->code == GOT_ERR_ANCESTRY) {
2104 error = checkout_ancestry_error(
2105 head_ref, commit_id_str);
2107 goto done;
2109 error = got_worktree_set_base_commit_id(worktree, repo,
2110 commit_id);
2111 free(commit_id);
2112 if (error)
2113 goto done;
2116 error = got_pathlist_append(&paths, "", NULL);
2117 if (error)
2118 goto done;
2119 cpa.worktree_path = worktree_path;
2120 cpa.had_base_commit_ref_error = 0;
2121 error = got_worktree_checkout_files(worktree, &paths, repo,
2122 checkout_progress, &cpa, check_cancelled, NULL);
2123 if (error != NULL)
2124 goto done;
2126 printf("Now shut up and hack\n");
2127 if (cpa.had_base_commit_ref_error)
2128 show_worktree_base_ref_warning();
2129 done:
2130 got_pathlist_free(&paths);
2131 free(commit_id_str);
2132 free(repo_path);
2133 free(worktree_path);
2134 return error;
2137 __dead static void
2138 usage_update(void)
2140 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2141 getprogname());
2142 exit(1);
2145 static const struct got_error *
2146 update_progress(void *arg, unsigned char status, const char *path)
2148 int *did_something = arg;
2150 if (status == GOT_STATUS_EXISTS ||
2151 status == GOT_STATUS_BASE_REF_ERR)
2152 return NULL;
2154 *did_something = 1;
2156 /* Base commit bump happens silently. */
2157 if (status == GOT_STATUS_BUMP_BASE)
2158 return NULL;
2160 while (path[0] == '/')
2161 path++;
2162 printf("%c %s\n", status, path);
2163 return NULL;
2166 static const struct got_error *
2167 switch_head_ref(struct got_reference *head_ref,
2168 struct got_object_id *commit_id, struct got_worktree *worktree,
2169 struct got_repository *repo)
2171 const struct got_error *err = NULL;
2172 char *base_id_str;
2173 int ref_has_moved = 0;
2175 /* Trivial case: switching between two different references. */
2176 if (strcmp(got_ref_get_name(head_ref),
2177 got_worktree_get_head_ref_name(worktree)) != 0) {
2178 printf("Switching work tree from %s to %s\n",
2179 got_worktree_get_head_ref_name(worktree),
2180 got_ref_get_name(head_ref));
2181 return got_worktree_set_head_ref(worktree, head_ref);
2184 err = check_linear_ancestry(commit_id,
2185 got_worktree_get_base_commit_id(worktree), 0, repo);
2186 if (err) {
2187 if (err->code != GOT_ERR_ANCESTRY)
2188 return err;
2189 ref_has_moved = 1;
2191 if (!ref_has_moved)
2192 return NULL;
2194 /* Switching to a rebased branch with the same reference name. */
2195 err = got_object_id_str(&base_id_str,
2196 got_worktree_get_base_commit_id(worktree));
2197 if (err)
2198 return err;
2199 printf("Reference %s now points at a different branch\n",
2200 got_worktree_get_head_ref_name(worktree));
2201 printf("Switching work tree from %s to %s\n", base_id_str,
2202 got_worktree_get_head_ref_name(worktree));
2203 return NULL;
2206 static const struct got_error *
2207 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2209 const struct got_error *err;
2210 int in_progress;
2212 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2213 if (err)
2214 return err;
2215 if (in_progress)
2216 return got_error(GOT_ERR_REBASING);
2218 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2219 if (err)
2220 return err;
2221 if (in_progress)
2222 return got_error(GOT_ERR_HISTEDIT_BUSY);
2224 return NULL;
2227 static const struct got_error *
2228 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2229 char *argv[], struct got_worktree *worktree)
2231 const struct got_error *err = NULL;
2232 char *path;
2233 int i;
2235 if (argc == 0) {
2236 path = strdup("");
2237 if (path == NULL)
2238 return got_error_from_errno("strdup");
2239 return got_pathlist_append(paths, path, NULL);
2242 for (i = 0; i < argc; i++) {
2243 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2244 if (err)
2245 break;
2246 err = got_pathlist_append(paths, path, NULL);
2247 if (err) {
2248 free(path);
2249 break;
2253 return err;
2256 static const struct got_error *
2257 cmd_update(int argc, char *argv[])
2259 const struct got_error *error = NULL;
2260 struct got_repository *repo = NULL;
2261 struct got_worktree *worktree = NULL;
2262 char *worktree_path = NULL;
2263 struct got_object_id *commit_id = NULL;
2264 char *commit_id_str = NULL;
2265 const char *branch_name = NULL;
2266 struct got_reference *head_ref = NULL;
2267 struct got_pathlist_head paths;
2268 struct got_pathlist_entry *pe;
2269 int ch, did_something = 0;
2271 TAILQ_INIT(&paths);
2273 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2274 switch (ch) {
2275 case 'b':
2276 branch_name = optarg;
2277 break;
2278 case 'c':
2279 commit_id_str = strdup(optarg);
2280 if (commit_id_str == NULL)
2281 return got_error_from_errno("strdup");
2282 break;
2283 default:
2284 usage_update();
2285 /* NOTREACHED */
2289 argc -= optind;
2290 argv += optind;
2292 #ifndef PROFILE
2293 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2294 "unveil", NULL) == -1)
2295 err(1, "pledge");
2296 #endif
2297 worktree_path = getcwd(NULL, 0);
2298 if (worktree_path == NULL) {
2299 error = got_error_from_errno("getcwd");
2300 goto done;
2302 error = got_worktree_open(&worktree, worktree_path);
2303 if (error)
2304 goto done;
2306 error = check_rebase_or_histedit_in_progress(worktree);
2307 if (error)
2308 goto done;
2310 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
2311 NULL);
2312 if (error != NULL)
2313 goto done;
2315 error = apply_unveil(got_repo_get_path(repo), 0,
2316 got_worktree_get_root_path(worktree));
2317 if (error)
2318 goto done;
2320 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2321 if (error)
2322 goto done;
2324 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
2325 got_worktree_get_head_ref_name(worktree), 0);
2326 if (error != NULL)
2327 goto done;
2328 if (commit_id_str == NULL) {
2329 error = got_ref_resolve(&commit_id, repo, head_ref);
2330 if (error != NULL)
2331 goto done;
2332 error = got_object_id_str(&commit_id_str, commit_id);
2333 if (error != NULL)
2334 goto done;
2335 } else {
2336 error = got_repo_match_object_id(&commit_id, NULL,
2337 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2338 free(commit_id_str);
2339 commit_id_str = NULL;
2340 if (error)
2341 goto done;
2342 error = got_object_id_str(&commit_id_str, commit_id);
2343 if (error)
2344 goto done;
2347 if (branch_name) {
2348 struct got_object_id *head_commit_id;
2349 TAILQ_FOREACH(pe, &paths, entry) {
2350 if (pe->path_len == 0)
2351 continue;
2352 error = got_error_msg(GOT_ERR_BAD_PATH,
2353 "switching between branches requires that "
2354 "the entire work tree gets updated");
2355 goto done;
2357 error = got_ref_resolve(&head_commit_id, repo, head_ref);
2358 if (error)
2359 goto done;
2360 error = check_linear_ancestry(commit_id, head_commit_id, 0,
2361 repo);
2362 free(head_commit_id);
2363 if (error != NULL)
2364 goto done;
2365 error = check_same_branch(commit_id, head_ref, NULL, repo);
2366 if (error)
2367 goto done;
2368 error = switch_head_ref(head_ref, commit_id, worktree, repo);
2369 if (error)
2370 goto done;
2371 } else {
2372 error = check_linear_ancestry(commit_id,
2373 got_worktree_get_base_commit_id(worktree), 0, repo);
2374 if (error != NULL) {
2375 if (error->code == GOT_ERR_ANCESTRY)
2376 error = got_error(GOT_ERR_BRANCH_MOVED);
2377 goto done;
2379 error = check_same_branch(commit_id, head_ref, NULL, repo);
2380 if (error)
2381 goto done;
2384 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
2385 commit_id) != 0) {
2386 error = got_worktree_set_base_commit_id(worktree, repo,
2387 commit_id);
2388 if (error)
2389 goto done;
2392 error = got_worktree_checkout_files(worktree, &paths, repo,
2393 update_progress, &did_something, check_cancelled, NULL);
2394 if (error != NULL)
2395 goto done;
2397 if (did_something)
2398 printf("Updated to commit %s\n", commit_id_str);
2399 else
2400 printf("Already up-to-date\n");
2401 done:
2402 free(worktree_path);
2403 TAILQ_FOREACH(pe, &paths, entry)
2404 free((char *)pe->path);
2405 got_pathlist_free(&paths);
2406 free(commit_id);
2407 free(commit_id_str);
2408 return error;
2411 static const struct got_error *
2412 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
2413 const char *path, int diff_context, int ignore_whitespace,
2414 struct got_repository *repo)
2416 const struct got_error *err = NULL;
2417 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
2419 if (blob_id1) {
2420 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
2421 if (err)
2422 goto done;
2425 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
2426 if (err)
2427 goto done;
2429 while (path[0] == '/')
2430 path++;
2431 err = got_diff_blob(blob1, blob2, path, path, diff_context,
2432 ignore_whitespace, stdout);
2433 done:
2434 if (blob1)
2435 got_object_blob_close(blob1);
2436 got_object_blob_close(blob2);
2437 return err;
2440 static const struct got_error *
2441 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
2442 const char *path, int diff_context, int ignore_whitespace,
2443 struct got_repository *repo)
2445 const struct got_error *err = NULL;
2446 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
2447 struct got_diff_blob_output_unidiff_arg arg;
2449 if (tree_id1) {
2450 err = got_object_open_as_tree(&tree1, repo, tree_id1);
2451 if (err)
2452 goto done;
2455 err = got_object_open_as_tree(&tree2, repo, tree_id2);
2456 if (err)
2457 goto done;
2459 arg.diff_context = diff_context;
2460 arg.ignore_whitespace = ignore_whitespace;
2461 arg.outfile = stdout;
2462 while (path[0] == '/')
2463 path++;
2464 err = got_diff_tree(tree1, tree2, path, path, repo,
2465 got_diff_blob_output_unidiff, &arg, 1);
2466 done:
2467 if (tree1)
2468 got_object_tree_close(tree1);
2469 if (tree2)
2470 got_object_tree_close(tree2);
2471 return err;
2474 static const struct got_error *
2475 print_patch(struct got_commit_object *commit, struct got_object_id *id,
2476 const char *path, int diff_context, struct got_repository *repo)
2478 const struct got_error *err = NULL;
2479 struct got_commit_object *pcommit = NULL;
2480 char *id_str1 = NULL, *id_str2 = NULL;
2481 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
2482 struct got_object_qid *qid;
2484 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
2485 if (qid != NULL) {
2486 err = got_object_open_as_commit(&pcommit, repo,
2487 qid->id);
2488 if (err)
2489 return err;
2492 if (path && path[0] != '\0') {
2493 int obj_type;
2494 err = got_object_id_by_path(&obj_id2, repo, id, path);
2495 if (err)
2496 goto done;
2497 err = got_object_id_str(&id_str2, obj_id2);
2498 if (err) {
2499 free(obj_id2);
2500 goto done;
2502 if (pcommit) {
2503 err = got_object_id_by_path(&obj_id1, repo,
2504 qid->id, path);
2505 if (err) {
2506 free(obj_id2);
2507 goto done;
2509 err = got_object_id_str(&id_str1, obj_id1);
2510 if (err) {
2511 free(obj_id2);
2512 goto done;
2515 err = got_object_get_type(&obj_type, repo, obj_id2);
2516 if (err) {
2517 free(obj_id2);
2518 goto done;
2520 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2521 switch (obj_type) {
2522 case GOT_OBJ_TYPE_BLOB:
2523 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
2524 0, repo);
2525 break;
2526 case GOT_OBJ_TYPE_TREE:
2527 err = diff_trees(obj_id1, obj_id2, path, diff_context,
2528 0, repo);
2529 break;
2530 default:
2531 err = got_error(GOT_ERR_OBJ_TYPE);
2532 break;
2534 free(obj_id1);
2535 free(obj_id2);
2536 } else {
2537 obj_id2 = got_object_commit_get_tree_id(commit);
2538 err = got_object_id_str(&id_str2, obj_id2);
2539 if (err)
2540 goto done;
2541 obj_id1 = got_object_commit_get_tree_id(pcommit);
2542 err = got_object_id_str(&id_str1, obj_id1);
2543 if (err)
2544 goto done;
2545 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2546 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
2548 done:
2549 free(id_str1);
2550 free(id_str2);
2551 if (pcommit)
2552 got_object_commit_close(pcommit);
2553 return err;
2556 static char *
2557 get_datestr(time_t *time, char *datebuf)
2559 struct tm mytm, *tm;
2560 char *p, *s;
2562 tm = gmtime_r(time, &mytm);
2563 if (tm == NULL)
2564 return NULL;
2565 s = asctime_r(tm, datebuf);
2566 if (s == NULL)
2567 return NULL;
2568 p = strchr(s, '\n');
2569 if (p)
2570 *p = '\0';
2571 return s;
2574 static const struct got_error *
2575 match_logmsg(int *have_match, struct got_object_id *id,
2576 struct got_commit_object *commit, regex_t *regex)
2578 const struct got_error *err = NULL;
2579 regmatch_t regmatch;
2580 char *id_str = NULL, *logmsg = NULL;
2582 *have_match = 0;
2584 err = got_object_id_str(&id_str, id);
2585 if (err)
2586 return err;
2588 err = got_object_commit_get_logmsg(&logmsg, commit);
2589 if (err)
2590 goto done;
2592 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2593 *have_match = 1;
2594 done:
2595 free(id_str);
2596 free(logmsg);
2597 return err;
2600 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
2602 static const struct got_error *
2603 print_commit(struct got_commit_object *commit, struct got_object_id *id,
2604 struct got_repository *repo, const char *path, int show_patch,
2605 int diff_context, struct got_reflist_head *refs)
2607 const struct got_error *err = NULL;
2608 char *id_str, *datestr, *logmsg0, *logmsg, *line;
2609 char datebuf[26];
2610 time_t committer_time;
2611 const char *author, *committer;
2612 char *refs_str = NULL;
2613 struct got_reflist_entry *re;
2615 SIMPLEQ_FOREACH(re, refs, entry) {
2616 char *s;
2617 const char *name;
2618 struct got_tag_object *tag = NULL;
2619 int cmp;
2621 name = got_ref_get_name(re->ref);
2622 if (strcmp(name, GOT_REF_HEAD) == 0)
2623 continue;
2624 if (strncmp(name, "refs/", 5) == 0)
2625 name += 5;
2626 if (strncmp(name, "got/", 4) == 0)
2627 continue;
2628 if (strncmp(name, "heads/", 6) == 0)
2629 name += 6;
2630 if (strncmp(name, "remotes/", 8) == 0)
2631 name += 8;
2632 if (strncmp(name, "tags/", 5) == 0) {
2633 err = got_object_open_as_tag(&tag, repo, re->id);
2634 if (err) {
2635 if (err->code != GOT_ERR_OBJ_TYPE)
2636 return err;
2637 /* Ref points at something other than a tag. */
2638 err = NULL;
2639 tag = NULL;
2642 cmp = got_object_id_cmp(tag ?
2643 got_object_tag_get_object_id(tag) : re->id, id);
2644 if (tag)
2645 got_object_tag_close(tag);
2646 if (cmp != 0)
2647 continue;
2648 s = refs_str;
2649 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
2650 name) == -1) {
2651 err = got_error_from_errno("asprintf");
2652 free(s);
2653 return err;
2655 free(s);
2657 err = got_object_id_str(&id_str, id);
2658 if (err)
2659 return err;
2661 printf(GOT_COMMIT_SEP_STR);
2662 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
2663 refs_str ? refs_str : "", refs_str ? ")" : "");
2664 free(id_str);
2665 id_str = NULL;
2666 free(refs_str);
2667 refs_str = NULL;
2668 printf("from: %s\n", got_object_commit_get_author(commit));
2669 committer_time = got_object_commit_get_committer_time(commit);
2670 datestr = get_datestr(&committer_time, datebuf);
2671 if (datestr)
2672 printf("date: %s UTC\n", datestr);
2673 author = got_object_commit_get_author(commit);
2674 committer = got_object_commit_get_committer(commit);
2675 if (strcmp(author, committer) != 0)
2676 printf("via: %s\n", committer);
2677 if (got_object_commit_get_nparents(commit) > 1) {
2678 const struct got_object_id_queue *parent_ids;
2679 struct got_object_qid *qid;
2680 int n = 1;
2681 parent_ids = got_object_commit_get_parent_ids(commit);
2682 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
2683 err = got_object_id_str(&id_str, qid->id);
2684 if (err)
2685 return err;
2686 printf("parent %d: %s\n", n++, id_str);
2687 free(id_str);
2691 err = got_object_commit_get_logmsg(&logmsg0, commit);
2692 if (err)
2693 return err;
2695 logmsg = logmsg0;
2696 do {
2697 line = strsep(&logmsg, "\n");
2698 if (line)
2699 printf(" %s\n", line);
2700 } while (line);
2701 free(logmsg0);
2703 if (show_patch) {
2704 err = print_patch(commit, id, path, diff_context, repo);
2705 if (err == 0)
2706 printf("\n");
2709 if (fflush(stdout) != 0 && err == NULL)
2710 err = got_error_from_errno("fflush");
2711 return err;
2714 static const struct got_error *
2715 print_commits(struct got_object_id *root_id, struct got_repository *repo,
2716 const char *path, int show_patch, const char *search_pattern,
2717 int diff_context, int limit, int log_branches,
2718 struct got_reflist_head *refs)
2720 const struct got_error *err;
2721 struct got_commit_graph *graph;
2722 regex_t regex;
2723 int have_match;
2725 if (search_pattern &&
2726 regcomp(&regex, search_pattern, REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
2727 return got_error_msg(GOT_ERR_REGEX, search_pattern);
2729 err = got_commit_graph_open(&graph, path, !log_branches);
2730 if (err)
2731 return err;
2732 err = got_commit_graph_iter_start(graph, root_id, repo,
2733 check_cancelled, NULL);
2734 if (err)
2735 goto done;
2736 for (;;) {
2737 struct got_commit_object *commit;
2738 struct got_object_id *id;
2740 if (sigint_received || sigpipe_received)
2741 break;
2743 err = got_commit_graph_iter_next(&id, graph, repo,
2744 check_cancelled, NULL);
2745 if (err) {
2746 if (err->code == GOT_ERR_ITER_COMPLETED)
2747 err = NULL;
2748 break;
2750 if (id == NULL)
2751 break;
2753 err = got_object_open_as_commit(&commit, repo, id);
2754 if (err)
2755 break;
2757 if (search_pattern) {
2758 err = match_logmsg(&have_match, id, commit, &regex);
2759 if (err) {
2760 got_object_commit_close(commit);
2761 break;
2763 if (have_match == 0) {
2764 got_object_commit_close(commit);
2765 continue;
2769 err = print_commit(commit, id, repo, path, show_patch,
2770 diff_context, refs);
2771 got_object_commit_close(commit);
2772 if (err || (limit && --limit == 0))
2773 break;
2775 done:
2776 if (search_pattern)
2777 regfree(&regex);
2778 got_commit_graph_close(graph);
2779 return err;
2782 __dead static void
2783 usage_log(void)
2785 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] [-p] "
2786 "[-s search-pattern] [-r repository-path] [path]\n", getprogname());
2787 exit(1);
2790 static int
2791 get_default_log_limit(void)
2793 const char *got_default_log_limit;
2794 long long n;
2795 const char *errstr;
2797 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
2798 if (got_default_log_limit == NULL)
2799 return 0;
2800 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
2801 if (errstr != NULL)
2802 return 0;
2803 return n;
2806 static const struct got_error *
2807 cmd_log(int argc, char *argv[])
2809 const struct got_error *error;
2810 struct got_repository *repo = NULL;
2811 struct got_worktree *worktree = NULL;
2812 struct got_commit_object *commit = NULL;
2813 struct got_object_id *id = NULL;
2814 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
2815 const char *start_commit = NULL, *search_pattern = NULL;
2816 int diff_context = -1, ch;
2817 int show_patch = 0, limit = 0, log_branches = 0;
2818 const char *errstr;
2819 struct got_reflist_head refs;
2821 SIMPLEQ_INIT(&refs);
2823 #ifndef PROFILE
2824 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
2825 NULL)
2826 == -1)
2827 err(1, "pledge");
2828 #endif
2830 limit = get_default_log_limit();
2832 while ((ch = getopt(argc, argv, "bpc:C:l:r:s:")) != -1) {
2833 switch (ch) {
2834 case 'p':
2835 show_patch = 1;
2836 break;
2837 case 'c':
2838 start_commit = optarg;
2839 break;
2840 case 'C':
2841 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
2842 &errstr);
2843 if (errstr != NULL)
2844 err(1, "-C option %s", errstr);
2845 break;
2846 case 'l':
2847 limit = strtonum(optarg, 0, INT_MAX, &errstr);
2848 if (errstr != NULL)
2849 err(1, "-l option %s", errstr);
2850 break;
2851 case 'b':
2852 log_branches = 1;
2853 break;
2854 case 'r':
2855 repo_path = realpath(optarg, NULL);
2856 if (repo_path == NULL)
2857 return got_error_from_errno2("realpath",
2858 optarg);
2859 got_path_strip_trailing_slashes(repo_path);
2860 break;
2861 case 's':
2862 search_pattern = optarg;
2863 break;
2864 default:
2865 usage_log();
2866 /* NOTREACHED */
2870 argc -= optind;
2871 argv += optind;
2873 if (diff_context == -1)
2874 diff_context = 3;
2875 else if (!show_patch)
2876 errx(1, "-C reguires -p");
2878 cwd = getcwd(NULL, 0);
2879 if (cwd == NULL) {
2880 error = got_error_from_errno("getcwd");
2881 goto done;
2884 error = got_worktree_open(&worktree, cwd);
2885 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2886 goto done;
2887 error = NULL;
2889 if (argc == 0) {
2890 path = strdup("");
2891 if (path == NULL) {
2892 error = got_error_from_errno("strdup");
2893 goto done;
2895 } else if (argc == 1) {
2896 if (worktree) {
2897 error = got_worktree_resolve_path(&path, worktree,
2898 argv[0]);
2899 if (error)
2900 goto done;
2901 } else {
2902 path = strdup(argv[0]);
2903 if (path == NULL) {
2904 error = got_error_from_errno("strdup");
2905 goto done;
2908 } else
2909 usage_log();
2911 if (repo_path == NULL) {
2912 repo_path = worktree ?
2913 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
2915 if (repo_path == NULL) {
2916 error = got_error_from_errno("strdup");
2917 goto done;
2920 error = got_repo_open(&repo, repo_path, NULL);
2921 if (error != NULL)
2922 goto done;
2924 error = apply_unveil(got_repo_get_path(repo), 1,
2925 worktree ? got_worktree_get_root_path(worktree) : NULL);
2926 if (error)
2927 goto done;
2929 if (start_commit == NULL) {
2930 struct got_reference *head_ref;
2931 error = got_ref_open(&head_ref, repo,
2932 worktree ? got_worktree_get_head_ref_name(worktree)
2933 : GOT_REF_HEAD, 0);
2934 if (error != NULL)
2935 return error;
2936 error = got_ref_resolve(&id, repo, head_ref);
2937 got_ref_close(head_ref);
2938 if (error != NULL)
2939 return error;
2940 error = got_object_open_as_commit(&commit, repo, id);
2941 } else {
2942 struct got_reference *ref;
2943 error = got_ref_open(&ref, repo, start_commit, 0);
2944 if (error == NULL) {
2945 int obj_type;
2946 error = got_ref_resolve(&id, repo, ref);
2947 got_ref_close(ref);
2948 if (error != NULL)
2949 goto done;
2950 error = got_object_get_type(&obj_type, repo, id);
2951 if (error != NULL)
2952 goto done;
2953 if (obj_type == GOT_OBJ_TYPE_TAG) {
2954 struct got_tag_object *tag;
2955 error = got_object_open_as_tag(&tag, repo, id);
2956 if (error != NULL)
2957 goto done;
2958 if (got_object_tag_get_object_type(tag) !=
2959 GOT_OBJ_TYPE_COMMIT) {
2960 got_object_tag_close(tag);
2961 error = got_error(GOT_ERR_OBJ_TYPE);
2962 goto done;
2964 free(id);
2965 id = got_object_id_dup(
2966 got_object_tag_get_object_id(tag));
2967 if (id == NULL)
2968 error = got_error_from_errno(
2969 "got_object_id_dup");
2970 got_object_tag_close(tag);
2971 if (error)
2972 goto done;
2973 } else if (obj_type != GOT_OBJ_TYPE_COMMIT) {
2974 error = got_error(GOT_ERR_OBJ_TYPE);
2975 goto done;
2977 error = got_object_open_as_commit(&commit, repo, id);
2978 if (error != NULL)
2979 goto done;
2981 if (commit == NULL) {
2982 error = got_repo_match_object_id_prefix(&id,
2983 start_commit, GOT_OBJ_TYPE_COMMIT, repo);
2984 if (error != NULL)
2985 return error;
2988 if (error != NULL)
2989 goto done;
2991 if (worktree) {
2992 const char *prefix = got_worktree_get_path_prefix(worktree);
2993 char *p;
2994 if (asprintf(&p, "%s%s%s", prefix,
2995 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
2996 error = got_error_from_errno("asprintf");
2997 goto done;
2999 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3000 free(p);
3001 } else
3002 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3003 if (error != NULL)
3004 goto done;
3005 if (in_repo_path) {
3006 free(path);
3007 path = in_repo_path;
3010 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3011 if (error)
3012 goto done;
3014 error = print_commits(id, repo, path, show_patch, search_pattern,
3015 diff_context, limit, log_branches, &refs);
3016 done:
3017 free(path);
3018 free(repo_path);
3019 free(cwd);
3020 free(id);
3021 if (worktree)
3022 got_worktree_close(worktree);
3023 if (repo) {
3024 const struct got_error *repo_error;
3025 repo_error = got_repo_close(repo);
3026 if (error == NULL)
3027 error = repo_error;
3029 got_ref_list_free(&refs);
3030 return error;
3033 __dead static void
3034 usage_diff(void)
3036 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3037 "[-w] [object1 object2 | path]\n", getprogname());
3038 exit(1);
3041 struct print_diff_arg {
3042 struct got_repository *repo;
3043 struct got_worktree *worktree;
3044 int diff_context;
3045 const char *id_str;
3046 int header_shown;
3047 int diff_staged;
3048 int ignore_whitespace;
3051 static const struct got_error *
3052 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3053 const char *path, struct got_object_id *blob_id,
3054 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3055 int dirfd, const char *de_name)
3057 struct print_diff_arg *a = arg;
3058 const struct got_error *err = NULL;
3059 struct got_blob_object *blob1 = NULL;
3060 int fd = -1;
3061 FILE *f2 = NULL;
3062 char *abspath = NULL, *label1 = NULL;
3063 struct stat sb;
3065 if (a->diff_staged) {
3066 if (staged_status != GOT_STATUS_MODIFY &&
3067 staged_status != GOT_STATUS_ADD &&
3068 staged_status != GOT_STATUS_DELETE)
3069 return NULL;
3070 } else {
3071 if (staged_status == GOT_STATUS_DELETE)
3072 return NULL;
3073 if (status == GOT_STATUS_NONEXISTENT)
3074 return got_error_set_errno(ENOENT, path);
3075 if (status != GOT_STATUS_MODIFY &&
3076 status != GOT_STATUS_ADD &&
3077 status != GOT_STATUS_DELETE &&
3078 status != GOT_STATUS_CONFLICT)
3079 return NULL;
3082 if (!a->header_shown) {
3083 printf("diff %s %s%s\n", a->id_str,
3084 got_worktree_get_root_path(a->worktree),
3085 a->diff_staged ? " (staged changes)" : "");
3086 a->header_shown = 1;
3089 if (a->diff_staged) {
3090 const char *label1 = NULL, *label2 = NULL;
3091 switch (staged_status) {
3092 case GOT_STATUS_MODIFY:
3093 label1 = path;
3094 label2 = path;
3095 break;
3096 case GOT_STATUS_ADD:
3097 label2 = path;
3098 break;
3099 case GOT_STATUS_DELETE:
3100 label1 = path;
3101 break;
3102 default:
3103 return got_error(GOT_ERR_FILE_STATUS);
3105 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
3106 label1, label2, a->diff_context, a->ignore_whitespace,
3107 a->repo, stdout);
3110 if (staged_status == GOT_STATUS_ADD ||
3111 staged_status == GOT_STATUS_MODIFY) {
3112 char *id_str;
3113 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
3114 8192);
3115 if (err)
3116 goto done;
3117 err = got_object_id_str(&id_str, staged_blob_id);
3118 if (err)
3119 goto done;
3120 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
3121 err = got_error_from_errno("asprintf");
3122 free(id_str);
3123 goto done;
3125 free(id_str);
3126 } else if (status != GOT_STATUS_ADD) {
3127 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
3128 if (err)
3129 goto done;
3132 if (status != GOT_STATUS_DELETE) {
3133 if (asprintf(&abspath, "%s/%s",
3134 got_worktree_get_root_path(a->worktree), path) == -1) {
3135 err = got_error_from_errno("asprintf");
3136 goto done;
3139 if (dirfd != -1) {
3140 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
3141 if (fd == -1) {
3142 err = got_error_from_errno2("openat", abspath);
3143 goto done;
3145 } else {
3146 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
3147 if (fd == -1) {
3148 err = got_error_from_errno2("open", abspath);
3149 goto done;
3152 if (fstat(fd, &sb) == -1) {
3153 err = got_error_from_errno2("fstat", abspath);
3154 goto done;
3156 f2 = fdopen(fd, "r");
3157 if (f2 == NULL) {
3158 err = got_error_from_errno2("fdopen", abspath);
3159 goto done;
3161 fd = -1;
3162 } else
3163 sb.st_size = 0;
3165 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
3166 a->diff_context, a->ignore_whitespace, stdout);
3167 done:
3168 if (blob1)
3169 got_object_blob_close(blob1);
3170 if (f2 && fclose(f2) == EOF && err == NULL)
3171 err = got_error_from_errno("fclose");
3172 if (fd != -1 && close(fd) == -1 && err == NULL)
3173 err = got_error_from_errno("close");
3174 free(abspath);
3175 return err;
3178 static const struct got_error *
3179 cmd_diff(int argc, char *argv[])
3181 const struct got_error *error;
3182 struct got_repository *repo = NULL;
3183 struct got_worktree *worktree = NULL;
3184 char *cwd = NULL, *repo_path = NULL;
3185 struct got_object_id *id1 = NULL, *id2 = NULL;
3186 const char *id_str1 = NULL, *id_str2 = NULL;
3187 char *label1 = NULL, *label2 = NULL;
3188 int type1, type2;
3189 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
3190 const char *errstr;
3191 char *path = NULL;
3193 #ifndef PROFILE
3194 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3195 NULL) == -1)
3196 err(1, "pledge");
3197 #endif
3199 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
3200 switch (ch) {
3201 case 'C':
3202 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3203 &errstr);
3204 if (errstr != NULL)
3205 err(1, "-C option %s", errstr);
3206 break;
3207 case 'r':
3208 repo_path = realpath(optarg, NULL);
3209 if (repo_path == NULL)
3210 return got_error_from_errno2("realpath",
3211 optarg);
3212 got_path_strip_trailing_slashes(repo_path);
3213 break;
3214 case 's':
3215 diff_staged = 1;
3216 break;
3217 case 'w':
3218 ignore_whitespace = 1;
3219 break;
3220 default:
3221 usage_diff();
3222 /* NOTREACHED */
3226 argc -= optind;
3227 argv += optind;
3229 cwd = getcwd(NULL, 0);
3230 if (cwd == NULL) {
3231 error = got_error_from_errno("getcwd");
3232 goto done;
3234 if (argc <= 1) {
3235 if (repo_path)
3236 errx(1,
3237 "-r option can't be used when diffing a work tree");
3238 error = got_worktree_open(&worktree, cwd);
3239 if (error)
3240 goto done;
3241 repo_path = strdup(got_worktree_get_repo_path(worktree));
3242 if (repo_path == NULL) {
3243 error = got_error_from_errno("strdup");
3244 goto done;
3246 if (argc == 1) {
3247 error = got_worktree_resolve_path(&path, worktree,
3248 argv[0]);
3249 if (error)
3250 goto done;
3251 } else {
3252 path = strdup("");
3253 if (path == NULL) {
3254 error = got_error_from_errno("strdup");
3255 goto done;
3258 } else if (argc == 2) {
3259 if (diff_staged)
3260 errx(1, "-s option can't be used when diffing "
3261 "objects in repository");
3262 id_str1 = argv[0];
3263 id_str2 = argv[1];
3264 if (repo_path == NULL) {
3265 error = got_worktree_open(&worktree, cwd);
3266 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3267 goto done;
3268 if (worktree) {
3269 repo_path = strdup(
3270 got_worktree_get_repo_path(worktree));
3271 if (repo_path == NULL) {
3272 error = got_error_from_errno("strdup");
3273 goto done;
3275 } else {
3276 repo_path = strdup(cwd);
3277 if (repo_path == NULL) {
3278 error = got_error_from_errno("strdup");
3279 goto done;
3283 } else
3284 usage_diff();
3286 error = got_repo_open(&repo, repo_path, NULL);
3287 free(repo_path);
3288 if (error != NULL)
3289 goto done;
3291 error = apply_unveil(got_repo_get_path(repo), 1,
3292 worktree ? got_worktree_get_root_path(worktree) : NULL);
3293 if (error)
3294 goto done;
3296 if (argc <= 1) {
3297 struct print_diff_arg arg;
3298 struct got_pathlist_head paths;
3299 char *id_str;
3301 TAILQ_INIT(&paths);
3303 error = got_object_id_str(&id_str,
3304 got_worktree_get_base_commit_id(worktree));
3305 if (error)
3306 goto done;
3307 arg.repo = repo;
3308 arg.worktree = worktree;
3309 arg.diff_context = diff_context;
3310 arg.id_str = id_str;
3311 arg.header_shown = 0;
3312 arg.diff_staged = diff_staged;
3313 arg.ignore_whitespace = ignore_whitespace;
3315 error = got_pathlist_append(&paths, path, NULL);
3316 if (error)
3317 goto done;
3319 error = got_worktree_status(worktree, &paths, repo, print_diff,
3320 &arg, check_cancelled, NULL);
3321 free(id_str);
3322 got_pathlist_free(&paths);
3323 goto done;
3326 error = got_repo_match_object_id(&id1, &label1, id_str1,
3327 GOT_OBJ_TYPE_ANY, 1, repo);
3328 if (error)
3329 goto done;
3331 error = got_repo_match_object_id(&id2, &label2, id_str2,
3332 GOT_OBJ_TYPE_ANY, 1, repo);
3333 if (error)
3334 goto done;
3336 error = got_object_get_type(&type1, repo, id1);
3337 if (error)
3338 goto done;
3340 error = got_object_get_type(&type2, repo, id2);
3341 if (error)
3342 goto done;
3344 if (type1 != type2) {
3345 error = got_error(GOT_ERR_OBJ_TYPE);
3346 goto done;
3349 switch (type1) {
3350 case GOT_OBJ_TYPE_BLOB:
3351 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
3352 diff_context, ignore_whitespace, repo, stdout);
3353 break;
3354 case GOT_OBJ_TYPE_TREE:
3355 error = got_diff_objects_as_trees(id1, id2, "", "",
3356 diff_context, ignore_whitespace, repo, stdout);
3357 break;
3358 case GOT_OBJ_TYPE_COMMIT:
3359 printf("diff %s %s\n", label1, label2);
3360 error = got_diff_objects_as_commits(id1, id2, diff_context,
3361 ignore_whitespace, repo, stdout);
3362 break;
3363 default:
3364 error = got_error(GOT_ERR_OBJ_TYPE);
3366 done:
3367 free(label1);
3368 free(label2);
3369 free(id1);
3370 free(id2);
3371 free(path);
3372 if (worktree)
3373 got_worktree_close(worktree);
3374 if (repo) {
3375 const struct got_error *repo_error;
3376 repo_error = got_repo_close(repo);
3377 if (error == NULL)
3378 error = repo_error;
3380 return error;
3383 __dead static void
3384 usage_blame(void)
3386 fprintf(stderr,
3387 "usage: %s blame [-c commit] [-r repository-path] path\n",
3388 getprogname());
3389 exit(1);
3392 struct blame_line {
3393 int annotated;
3394 char *id_str;
3395 char *committer;
3396 char datebuf[11]; /* YYYY-MM-DD + NUL */
3399 struct blame_cb_args {
3400 struct blame_line *lines;
3401 int nlines;
3402 int nlines_prec;
3403 int lineno_cur;
3404 off_t *line_offsets;
3405 FILE *f;
3406 struct got_repository *repo;
3409 static const struct got_error *
3410 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
3412 const struct got_error *err = NULL;
3413 struct blame_cb_args *a = arg;
3414 struct blame_line *bline;
3415 char *line = NULL;
3416 size_t linesize = 0;
3417 struct got_commit_object *commit = NULL;
3418 off_t offset;
3419 struct tm tm;
3420 time_t committer_time;
3422 if (nlines != a->nlines ||
3423 (lineno != -1 && lineno < 1) || lineno > a->nlines)
3424 return got_error(GOT_ERR_RANGE);
3426 if (sigint_received)
3427 return got_error(GOT_ERR_ITER_COMPLETED);
3429 if (lineno == -1)
3430 return NULL; /* no change in this commit */
3432 /* Annotate this line. */
3433 bline = &a->lines[lineno - 1];
3434 if (bline->annotated)
3435 return NULL;
3436 err = got_object_id_str(&bline->id_str, id);
3437 if (err)
3438 return err;
3440 err = got_object_open_as_commit(&commit, a->repo, id);
3441 if (err)
3442 goto done;
3444 bline->committer = strdup(got_object_commit_get_committer(commit));
3445 if (bline->committer == NULL) {
3446 err = got_error_from_errno("strdup");
3447 goto done;
3450 committer_time = got_object_commit_get_committer_time(commit);
3451 if (localtime_r(&committer_time, &tm) == NULL)
3452 return got_error_from_errno("localtime_r");
3453 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
3454 &tm) >= sizeof(bline->datebuf)) {
3455 err = got_error(GOT_ERR_NO_SPACE);
3456 goto done;
3458 bline->annotated = 1;
3460 /* Print lines annotated so far. */
3461 bline = &a->lines[a->lineno_cur - 1];
3462 if (!bline->annotated)
3463 goto done;
3465 offset = a->line_offsets[a->lineno_cur - 1];
3466 if (fseeko(a->f, offset, SEEK_SET) == -1) {
3467 err = got_error_from_errno("fseeko");
3468 goto done;
3471 while (bline->annotated) {
3472 char *smallerthan, *at, *nl, *committer;
3473 size_t len;
3475 if (getline(&line, &linesize, a->f) == -1) {
3476 if (ferror(a->f))
3477 err = got_error_from_errno("getline");
3478 break;
3481 committer = bline->committer;
3482 smallerthan = strchr(committer, '<');
3483 if (smallerthan && smallerthan[1] != '\0')
3484 committer = smallerthan + 1;
3485 at = strchr(committer, '@');
3486 if (at)
3487 *at = '\0';
3488 len = strlen(committer);
3489 if (len >= 9)
3490 committer[8] = '\0';
3492 nl = strchr(line, '\n');
3493 if (nl)
3494 *nl = '\0';
3495 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
3496 bline->id_str, bline->datebuf, committer, line);
3498 a->lineno_cur++;
3499 bline = &a->lines[a->lineno_cur - 1];
3501 done:
3502 if (commit)
3503 got_object_commit_close(commit);
3504 free(line);
3505 return err;
3508 static const struct got_error *
3509 cmd_blame(int argc, char *argv[])
3511 const struct got_error *error;
3512 struct got_repository *repo = NULL;
3513 struct got_worktree *worktree = NULL;
3514 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
3515 struct got_object_id *obj_id = NULL;
3516 struct got_object_id *commit_id = NULL;
3517 struct got_blob_object *blob = NULL;
3518 char *commit_id_str = NULL;
3519 struct blame_cb_args bca;
3520 int ch, obj_type, i;
3521 size_t filesize;
3523 memset(&bca, 0, sizeof(bca));
3525 #ifndef PROFILE
3526 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3527 NULL) == -1)
3528 err(1, "pledge");
3529 #endif
3531 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
3532 switch (ch) {
3533 case 'c':
3534 commit_id_str = optarg;
3535 break;
3536 case 'r':
3537 repo_path = realpath(optarg, NULL);
3538 if (repo_path == NULL)
3539 return got_error_from_errno2("realpath",
3540 optarg);
3541 got_path_strip_trailing_slashes(repo_path);
3542 break;
3543 default:
3544 usage_blame();
3545 /* NOTREACHED */
3549 argc -= optind;
3550 argv += optind;
3552 if (argc == 1)
3553 path = argv[0];
3554 else
3555 usage_blame();
3557 cwd = getcwd(NULL, 0);
3558 if (cwd == NULL) {
3559 error = got_error_from_errno("getcwd");
3560 goto done;
3562 if (repo_path == NULL) {
3563 error = got_worktree_open(&worktree, cwd);
3564 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3565 goto done;
3566 else
3567 error = NULL;
3568 if (worktree) {
3569 repo_path =
3570 strdup(got_worktree_get_repo_path(worktree));
3571 if (repo_path == NULL) {
3572 error = got_error_from_errno("strdup");
3573 if (error)
3574 goto done;
3576 } else {
3577 repo_path = strdup(cwd);
3578 if (repo_path == NULL) {
3579 error = got_error_from_errno("strdup");
3580 goto done;
3585 error = got_repo_open(&repo, repo_path, NULL);
3586 if (error != NULL)
3587 goto done;
3589 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
3590 if (error)
3591 goto done;
3593 if (worktree) {
3594 const char *prefix = got_worktree_get_path_prefix(worktree);
3595 char *p, *worktree_subdir = cwd +
3596 strlen(got_worktree_get_root_path(worktree));
3597 if (asprintf(&p, "%s%s%s%s%s",
3598 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
3599 worktree_subdir, worktree_subdir[0] ? "/" : "",
3600 path) == -1) {
3601 error = got_error_from_errno("asprintf");
3602 goto done;
3604 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3605 free(p);
3606 } else {
3607 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3609 if (error)
3610 goto done;
3612 if (commit_id_str == NULL) {
3613 struct got_reference *head_ref;
3614 error = got_ref_open(&head_ref, repo, worktree ?
3615 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
3616 if (error != NULL)
3617 goto done;
3618 error = got_ref_resolve(&commit_id, repo, head_ref);
3619 got_ref_close(head_ref);
3620 if (error != NULL)
3621 goto done;
3622 } else {
3623 error = got_repo_match_object_id(&commit_id, NULL,
3624 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
3625 if (error)
3626 goto done;
3629 error = got_object_id_by_path(&obj_id, repo, commit_id, in_repo_path);
3630 if (error)
3631 goto done;
3633 error = got_object_get_type(&obj_type, repo, obj_id);
3634 if (error)
3635 goto done;
3637 if (obj_type != GOT_OBJ_TYPE_BLOB) {
3638 error = got_error(GOT_ERR_OBJ_TYPE);
3639 goto done;
3642 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
3643 if (error)
3644 goto done;
3645 bca.f = got_opentemp();
3646 if (bca.f == NULL) {
3647 error = got_error_from_errno("got_opentemp");
3648 goto done;
3650 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
3651 &bca.line_offsets, bca.f, blob);
3652 if (error || bca.nlines == 0)
3653 goto done;
3655 /* Don't include \n at EOF in the blame line count. */
3656 if (bca.line_offsets[bca.nlines - 1] == filesize)
3657 bca.nlines--;
3659 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
3660 if (bca.lines == NULL) {
3661 error = got_error_from_errno("calloc");
3662 goto done;
3664 bca.lineno_cur = 1;
3665 bca.nlines_prec = 0;
3666 i = bca.nlines;
3667 while (i > 0) {
3668 i /= 10;
3669 bca.nlines_prec++;
3671 bca.repo = repo;
3673 error = got_blame(in_repo_path, commit_id, repo, blame_cb, &bca,
3674 check_cancelled, NULL);
3675 done:
3676 free(in_repo_path);
3677 free(repo_path);
3678 free(cwd);
3679 free(commit_id);
3680 free(obj_id);
3681 if (blob)
3682 got_object_blob_close(blob);
3683 if (worktree)
3684 got_worktree_close(worktree);
3685 if (repo) {
3686 const struct got_error *repo_error;
3687 repo_error = got_repo_close(repo);
3688 if (error == NULL)
3689 error = repo_error;
3691 if (bca.lines) {
3692 for (i = 0; i < bca.nlines; i++) {
3693 struct blame_line *bline = &bca.lines[i];
3694 free(bline->id_str);
3695 free(bline->committer);
3697 free(bca.lines);
3699 free(bca.line_offsets);
3700 if (bca.f && fclose(bca.f) == EOF && error == NULL)
3701 error = got_error_from_errno("fclose");
3702 return error;
3705 __dead static void
3706 usage_tree(void)
3708 fprintf(stderr,
3709 "usage: %s tree [-c commit] [-r repository-path] [-iR] path\n",
3710 getprogname());
3711 exit(1);
3714 static void
3715 print_entry(struct got_tree_entry *te, const char *id, const char *path,
3716 const char *root_path)
3718 int is_root_path = (strcmp(path, root_path) == 0);
3719 const char *modestr = "";
3720 mode_t mode = got_tree_entry_get_mode(te);
3722 path += strlen(root_path);
3723 while (path[0] == '/')
3724 path++;
3726 if (got_object_tree_entry_is_submodule(te))
3727 modestr = "$";
3728 else if (S_ISLNK(mode))
3729 modestr = "@";
3730 else if (S_ISDIR(mode))
3731 modestr = "/";
3732 else if (mode & S_IXUSR)
3733 modestr = "*";
3735 printf("%s%s%s%s%s\n", id ? id : "", path,
3736 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr);
3739 static const struct got_error *
3740 print_tree(const char *path, struct got_object_id *commit_id,
3741 int show_ids, int recurse, const char *root_path,
3742 struct got_repository *repo)
3744 const struct got_error *err = NULL;
3745 struct got_object_id *tree_id = NULL;
3746 struct got_tree_object *tree = NULL;
3747 int nentries, i;
3749 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
3750 if (err)
3751 goto done;
3753 err = got_object_open_as_tree(&tree, repo, tree_id);
3754 if (err)
3755 goto done;
3756 nentries = got_object_tree_get_nentries(tree);
3757 for (i = 0; i < nentries; i++) {
3758 struct got_tree_entry *te;
3759 char *id = NULL;
3761 if (sigint_received || sigpipe_received)
3762 break;
3764 te = got_object_tree_get_entry(tree, i);
3765 if (show_ids) {
3766 char *id_str;
3767 err = got_object_id_str(&id_str,
3768 got_tree_entry_get_id(te));
3769 if (err)
3770 goto done;
3771 if (asprintf(&id, "%s ", id_str) == -1) {
3772 err = got_error_from_errno("asprintf");
3773 free(id_str);
3774 goto done;
3776 free(id_str);
3778 print_entry(te, id, path, root_path);
3779 free(id);
3781 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
3782 char *child_path;
3783 if (asprintf(&child_path, "%s%s%s", path,
3784 path[0] == '/' && path[1] == '\0' ? "" : "/",
3785 got_tree_entry_get_name(te)) == -1) {
3786 err = got_error_from_errno("asprintf");
3787 goto done;
3789 err = print_tree(child_path, commit_id, show_ids, 1,
3790 root_path, repo);
3791 free(child_path);
3792 if (err)
3793 goto done;
3796 done:
3797 if (tree)
3798 got_object_tree_close(tree);
3799 free(tree_id);
3800 return err;
3803 static const struct got_error *
3804 cmd_tree(int argc, char *argv[])
3806 const struct got_error *error;
3807 struct got_repository *repo = NULL;
3808 struct got_worktree *worktree = NULL;
3809 const char *path;
3810 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
3811 struct got_object_id *commit_id = NULL;
3812 char *commit_id_str = NULL;
3813 int show_ids = 0, recurse = 0;
3814 int ch;
3816 #ifndef PROFILE
3817 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3818 NULL) == -1)
3819 err(1, "pledge");
3820 #endif
3822 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
3823 switch (ch) {
3824 case 'c':
3825 commit_id_str = optarg;
3826 break;
3827 case 'r':
3828 repo_path = realpath(optarg, NULL);
3829 if (repo_path == NULL)
3830 return got_error_from_errno2("realpath",
3831 optarg);
3832 got_path_strip_trailing_slashes(repo_path);
3833 break;
3834 case 'i':
3835 show_ids = 1;
3836 break;
3837 case 'R':
3838 recurse = 1;
3839 break;
3840 default:
3841 usage_tree();
3842 /* NOTREACHED */
3846 argc -= optind;
3847 argv += optind;
3849 if (argc == 1)
3850 path = argv[0];
3851 else if (argc > 1)
3852 usage_tree();
3853 else
3854 path = NULL;
3856 cwd = getcwd(NULL, 0);
3857 if (cwd == NULL) {
3858 error = got_error_from_errno("getcwd");
3859 goto done;
3861 if (repo_path == NULL) {
3862 error = got_worktree_open(&worktree, cwd);
3863 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3864 goto done;
3865 else
3866 error = NULL;
3867 if (worktree) {
3868 repo_path =
3869 strdup(got_worktree_get_repo_path(worktree));
3870 if (repo_path == NULL)
3871 error = got_error_from_errno("strdup");
3872 if (error)
3873 goto done;
3874 } else {
3875 repo_path = strdup(cwd);
3876 if (repo_path == NULL) {
3877 error = got_error_from_errno("strdup");
3878 goto done;
3883 error = got_repo_open(&repo, repo_path, NULL);
3884 if (error != NULL)
3885 goto done;
3887 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
3888 if (error)
3889 goto done;
3891 if (path == NULL) {
3892 if (worktree) {
3893 char *p, *worktree_subdir = cwd +
3894 strlen(got_worktree_get_root_path(worktree));
3895 if (asprintf(&p, "%s/%s",
3896 got_worktree_get_path_prefix(worktree),
3897 worktree_subdir) == -1) {
3898 error = got_error_from_errno("asprintf");
3899 goto done;
3901 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3902 free(p);
3903 if (error)
3904 goto done;
3905 } else
3906 path = "/";
3908 if (in_repo_path == NULL) {
3909 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3910 if (error != NULL)
3911 goto done;
3914 if (commit_id_str == NULL) {
3915 struct got_reference *head_ref;
3916 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
3917 if (error != NULL)
3918 goto done;
3919 error = got_ref_resolve(&commit_id, repo, head_ref);
3920 got_ref_close(head_ref);
3921 if (error != NULL)
3922 goto done;
3923 } else {
3924 error = got_repo_match_object_id(&commit_id, NULL,
3925 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
3926 if (error)
3927 goto done;
3930 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
3931 in_repo_path, repo);
3932 done:
3933 free(in_repo_path);
3934 free(repo_path);
3935 free(cwd);
3936 free(commit_id);
3937 if (worktree)
3938 got_worktree_close(worktree);
3939 if (repo) {
3940 const struct got_error *repo_error;
3941 repo_error = got_repo_close(repo);
3942 if (error == NULL)
3943 error = repo_error;
3945 return error;
3948 __dead static void
3949 usage_status(void)
3951 fprintf(stderr, "usage: %s status [path ...]\n", getprogname());
3952 exit(1);
3955 static const struct got_error *
3956 print_status(void *arg, unsigned char status, unsigned char staged_status,
3957 const char *path, struct got_object_id *blob_id,
3958 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3959 int dirfd, const char *de_name)
3961 if (status == staged_status && (status == GOT_STATUS_DELETE))
3962 status = GOT_STATUS_NO_CHANGE;
3963 printf("%c%c %s\n", status, staged_status, path);
3964 return NULL;
3967 static const struct got_error *
3968 cmd_status(int argc, char *argv[])
3970 const struct got_error *error = NULL;
3971 struct got_repository *repo = NULL;
3972 struct got_worktree *worktree = NULL;
3973 char *cwd = NULL;
3974 struct got_pathlist_head paths;
3975 struct got_pathlist_entry *pe;
3976 int ch;
3978 TAILQ_INIT(&paths);
3980 while ((ch = getopt(argc, argv, "")) != -1) {
3981 switch (ch) {
3982 default:
3983 usage_status();
3984 /* NOTREACHED */
3988 argc -= optind;
3989 argv += optind;
3991 #ifndef PROFILE
3992 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3993 NULL) == -1)
3994 err(1, "pledge");
3995 #endif
3996 cwd = getcwd(NULL, 0);
3997 if (cwd == NULL) {
3998 error = got_error_from_errno("getcwd");
3999 goto done;
4002 error = got_worktree_open(&worktree, cwd);
4003 if (error != NULL)
4004 goto done;
4006 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4007 NULL);
4008 if (error != NULL)
4009 goto done;
4011 error = apply_unveil(got_repo_get_path(repo), 1,
4012 got_worktree_get_root_path(worktree));
4013 if (error)
4014 goto done;
4016 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
4017 if (error)
4018 goto done;
4020 error = got_worktree_status(worktree, &paths, repo, print_status, NULL,
4021 check_cancelled, NULL);
4022 done:
4023 TAILQ_FOREACH(pe, &paths, entry)
4024 free((char *)pe->path);
4025 got_pathlist_free(&paths);
4026 free(cwd);
4027 return error;
4030 __dead static void
4031 usage_ref(void)
4033 fprintf(stderr,
4034 "usage: %s ref [-r repository] -l | -d name | [-s] name target\n",
4035 getprogname());
4036 exit(1);
4039 static const struct got_error *
4040 list_refs(struct got_repository *repo)
4042 static const struct got_error *err = NULL;
4043 struct got_reflist_head refs;
4044 struct got_reflist_entry *re;
4046 SIMPLEQ_INIT(&refs);
4047 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4048 if (err)
4049 return err;
4051 SIMPLEQ_FOREACH(re, &refs, entry) {
4052 char *refstr;
4053 refstr = got_ref_to_str(re->ref);
4054 if (refstr == NULL)
4055 return got_error_from_errno("got_ref_to_str");
4056 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
4057 free(refstr);
4060 got_ref_list_free(&refs);
4061 return NULL;
4064 static const struct got_error *
4065 delete_ref(struct got_repository *repo, const char *refname)
4067 const struct got_error *err = NULL;
4068 struct got_reference *ref;
4070 err = got_ref_open(&ref, repo, refname, 0);
4071 if (err)
4072 return err;
4074 err = got_ref_delete(ref, repo);
4075 got_ref_close(ref);
4076 return err;
4079 static const struct got_error *
4080 add_ref(struct got_repository *repo, const char *refname, const char *target)
4082 const struct got_error *err = NULL;
4083 struct got_object_id *id;
4084 struct got_reference *ref = NULL;
4087 * Don't let the user create a reference name with a leading '-'.
4088 * While technically a valid reference name, this case is usually
4089 * an unintended typo.
4091 if (refname[0] == '-')
4092 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4094 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
4095 repo);
4096 if (err) {
4097 struct got_reference *target_ref;
4099 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
4100 return err;
4101 err = got_ref_open(&target_ref, repo, target, 0);
4102 if (err)
4103 return err;
4104 err = got_ref_resolve(&id, repo, target_ref);
4105 got_ref_close(target_ref);
4106 if (err)
4107 return err;
4110 err = got_ref_alloc(&ref, refname, id);
4111 if (err)
4112 goto done;
4114 err = got_ref_write(ref, repo);
4115 done:
4116 if (ref)
4117 got_ref_close(ref);
4118 free(id);
4119 return err;
4122 static const struct got_error *
4123 add_symref(struct got_repository *repo, const char *refname, const char *target)
4125 const struct got_error *err = NULL;
4126 struct got_reference *ref = NULL;
4127 struct got_reference *target_ref = NULL;
4130 * Don't let the user create a reference name with a leading '-'.
4131 * While technically a valid reference name, this case is usually
4132 * an unintended typo.
4134 if (refname[0] == '-')
4135 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4137 err = got_ref_open(&target_ref, repo, target, 0);
4138 if (err)
4139 return err;
4141 err = got_ref_alloc_symref(&ref, refname, target_ref);
4142 if (err)
4143 goto done;
4145 err = got_ref_write(ref, repo);
4146 done:
4147 if (target_ref)
4148 got_ref_close(target_ref);
4149 if (ref)
4150 got_ref_close(ref);
4151 return err;
4154 static const struct got_error *
4155 cmd_ref(int argc, char *argv[])
4157 const struct got_error *error = NULL;
4158 struct got_repository *repo = NULL;
4159 struct got_worktree *worktree = NULL;
4160 char *cwd = NULL, *repo_path = NULL;
4161 int ch, do_list = 0, create_symref = 0;
4162 const char *delref = NULL;
4164 /* TODO: Add -s option for adding symbolic references. */
4165 while ((ch = getopt(argc, argv, "d:r:ls")) != -1) {
4166 switch (ch) {
4167 case 'd':
4168 delref = optarg;
4169 break;
4170 case 'r':
4171 repo_path = realpath(optarg, NULL);
4172 if (repo_path == NULL)
4173 return got_error_from_errno2("realpath",
4174 optarg);
4175 got_path_strip_trailing_slashes(repo_path);
4176 break;
4177 case 'l':
4178 do_list = 1;
4179 break;
4180 case 's':
4181 create_symref = 1;
4182 break;
4183 default:
4184 usage_ref();
4185 /* NOTREACHED */
4189 if (do_list && delref)
4190 errx(1, "-l and -d options are mutually exclusive\n");
4192 argc -= optind;
4193 argv += optind;
4195 if (do_list || delref) {
4196 if (create_symref)
4197 errx(1, "-s option cannot be used together with the "
4198 "-l or -d options");
4199 if (argc > 0)
4200 usage_ref();
4201 } else if (argc != 2)
4202 usage_ref();
4204 #ifndef PROFILE
4205 if (do_list) {
4206 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4207 NULL) == -1)
4208 err(1, "pledge");
4209 } else {
4210 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4211 "sendfd unveil", NULL) == -1)
4212 err(1, "pledge");
4214 #endif
4215 cwd = getcwd(NULL, 0);
4216 if (cwd == NULL) {
4217 error = got_error_from_errno("getcwd");
4218 goto done;
4221 if (repo_path == NULL) {
4222 error = got_worktree_open(&worktree, cwd);
4223 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4224 goto done;
4225 else
4226 error = NULL;
4227 if (worktree) {
4228 repo_path =
4229 strdup(got_worktree_get_repo_path(worktree));
4230 if (repo_path == NULL)
4231 error = got_error_from_errno("strdup");
4232 if (error)
4233 goto done;
4234 } else {
4235 repo_path = strdup(cwd);
4236 if (repo_path == NULL) {
4237 error = got_error_from_errno("strdup");
4238 goto done;
4243 error = got_repo_open(&repo, repo_path, NULL);
4244 if (error != NULL)
4245 goto done;
4247 error = apply_unveil(got_repo_get_path(repo), do_list,
4248 worktree ? got_worktree_get_root_path(worktree) : NULL);
4249 if (error)
4250 goto done;
4252 if (do_list)
4253 error = list_refs(repo);
4254 else if (delref)
4255 error = delete_ref(repo, delref);
4256 else if (create_symref)
4257 error = add_symref(repo, argv[0], argv[1]);
4258 else
4259 error = add_ref(repo, argv[0], argv[1]);
4260 done:
4261 if (repo)
4262 got_repo_close(repo);
4263 if (worktree)
4264 got_worktree_close(worktree);
4265 free(cwd);
4266 free(repo_path);
4267 return error;
4270 __dead static void
4271 usage_branch(void)
4273 fprintf(stderr,
4274 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
4275 "[name]\n", getprogname());
4276 exit(1);
4279 static const struct got_error *
4280 list_branch(struct got_repository *repo, struct got_worktree *worktree,
4281 struct got_reference *ref)
4283 const struct got_error *err = NULL;
4284 const char *refname, *marker = " ";
4285 char *refstr;
4287 refname = got_ref_get_name(ref);
4288 if (worktree && strcmp(refname,
4289 got_worktree_get_head_ref_name(worktree)) == 0) {
4290 struct got_object_id *id = NULL;
4292 err = got_ref_resolve(&id, repo, ref);
4293 if (err)
4294 return err;
4295 if (got_object_id_cmp(id,
4296 got_worktree_get_base_commit_id(worktree)) == 0)
4297 marker = "* ";
4298 else
4299 marker = "~ ";
4300 free(id);
4303 if (strncmp(refname, "refs/heads/", 11) == 0)
4304 refname += 11;
4305 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4306 refname += 18;
4308 refstr = got_ref_to_str(ref);
4309 if (refstr == NULL)
4310 return got_error_from_errno("got_ref_to_str");
4312 printf("%s%s: %s\n", marker, refname, refstr);
4313 free(refstr);
4314 return NULL;
4317 static const struct got_error *
4318 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
4320 const char *refname;
4322 if (worktree == NULL)
4323 return got_error(GOT_ERR_NOT_WORKTREE);
4325 refname = got_worktree_get_head_ref_name(worktree);
4327 if (strncmp(refname, "refs/heads/", 11) == 0)
4328 refname += 11;
4329 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4330 refname += 18;
4332 printf("%s\n", refname);
4334 return NULL;
4337 static const struct got_error *
4338 list_branches(struct got_repository *repo, struct got_worktree *worktree)
4340 static const struct got_error *err = NULL;
4341 struct got_reflist_head refs;
4342 struct got_reflist_entry *re;
4343 struct got_reference *temp_ref = NULL;
4344 int rebase_in_progress, histedit_in_progress;
4346 SIMPLEQ_INIT(&refs);
4348 if (worktree) {
4349 err = got_worktree_rebase_in_progress(&rebase_in_progress,
4350 worktree);
4351 if (err)
4352 return err;
4354 err = got_worktree_histedit_in_progress(&histedit_in_progress,
4355 worktree);
4356 if (err)
4357 return err;
4359 if (rebase_in_progress || histedit_in_progress) {
4360 err = got_ref_open(&temp_ref, repo,
4361 got_worktree_get_head_ref_name(worktree), 0);
4362 if (err)
4363 return err;
4364 list_branch(repo, worktree, temp_ref);
4365 got_ref_close(temp_ref);
4369 err = got_ref_list(&refs, repo, "refs/heads",
4370 got_ref_cmp_by_name, NULL);
4371 if (err)
4372 return err;
4374 SIMPLEQ_FOREACH(re, &refs, entry)
4375 list_branch(repo, worktree, re->ref);
4377 got_ref_list_free(&refs);
4378 return NULL;
4381 static const struct got_error *
4382 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
4383 const char *branch_name)
4385 const struct got_error *err = NULL;
4386 struct got_reference *ref = NULL;
4387 char *refname;
4389 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
4390 return got_error_from_errno("asprintf");
4392 err = got_ref_open(&ref, repo, refname, 0);
4393 if (err)
4394 goto done;
4396 if (worktree &&
4397 strcmp(got_worktree_get_head_ref_name(worktree),
4398 got_ref_get_name(ref)) == 0) {
4399 err = got_error_msg(GOT_ERR_SAME_BRANCH,
4400 "will not delete this work tree's current branch");
4401 goto done;
4404 err = got_ref_delete(ref, repo);
4405 done:
4406 if (ref)
4407 got_ref_close(ref);
4408 free(refname);
4409 return err;
4412 static const struct got_error *
4413 add_branch(struct got_repository *repo, const char *branch_name,
4414 struct got_object_id *base_commit_id)
4416 const struct got_error *err = NULL;
4417 struct got_reference *ref = NULL;
4418 char *base_refname = NULL, *refname = NULL;
4421 * Don't let the user create a branch name with a leading '-'.
4422 * While technically a valid reference name, this case is usually
4423 * an unintended typo.
4425 if (branch_name[0] == '-')
4426 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
4428 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
4429 err = got_error_from_errno("asprintf");
4430 goto done;
4433 err = got_ref_open(&ref, repo, refname, 0);
4434 if (err == NULL) {
4435 err = got_error(GOT_ERR_BRANCH_EXISTS);
4436 goto done;
4437 } else if (err->code != GOT_ERR_NOT_REF)
4438 goto done;
4440 err = got_ref_alloc(&ref, refname, base_commit_id);
4441 if (err)
4442 goto done;
4444 err = got_ref_write(ref, repo);
4445 done:
4446 if (ref)
4447 got_ref_close(ref);
4448 free(base_refname);
4449 free(refname);
4450 return err;
4453 static const struct got_error *
4454 cmd_branch(int argc, char *argv[])
4456 const struct got_error *error = NULL;
4457 struct got_repository *repo = NULL;
4458 struct got_worktree *worktree = NULL;
4459 char *cwd = NULL, *repo_path = NULL;
4460 int ch, do_list = 0, do_show = 0, do_update = 1;
4461 const char *delref = NULL, *commit_id_arg = NULL;
4462 struct got_reference *ref = NULL;
4463 struct got_pathlist_head paths;
4464 struct got_pathlist_entry *pe;
4465 struct got_object_id *commit_id = NULL;
4466 char *commit_id_str = NULL;
4468 TAILQ_INIT(&paths);
4470 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
4471 switch (ch) {
4472 case 'c':
4473 commit_id_arg = optarg;
4474 break;
4475 case 'd':
4476 delref = optarg;
4477 break;
4478 case 'r':
4479 repo_path = realpath(optarg, NULL);
4480 if (repo_path == NULL)
4481 return got_error_from_errno2("realpath",
4482 optarg);
4483 got_path_strip_trailing_slashes(repo_path);
4484 break;
4485 case 'l':
4486 do_list = 1;
4487 break;
4488 case 'n':
4489 do_update = 0;
4490 break;
4491 default:
4492 usage_branch();
4493 /* NOTREACHED */
4497 if (do_list && delref)
4498 errx(1, "-l and -d options are mutually exclusive\n");
4500 argc -= optind;
4501 argv += optind;
4503 if (!do_list && !delref && argc == 0)
4504 do_show = 1;
4506 if ((do_list || delref || do_show) && commit_id_arg != NULL)
4507 errx(1, "-c option can only be used when creating a branch");
4509 if (do_list || delref) {
4510 if (argc > 0)
4511 usage_branch();
4512 } else if (!do_show && argc != 1)
4513 usage_branch();
4515 #ifndef PROFILE
4516 if (do_list || do_show) {
4517 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4518 NULL) == -1)
4519 err(1, "pledge");
4520 } else {
4521 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4522 "sendfd unveil", NULL) == -1)
4523 err(1, "pledge");
4525 #endif
4526 cwd = getcwd(NULL, 0);
4527 if (cwd == NULL) {
4528 error = got_error_from_errno("getcwd");
4529 goto done;
4532 if (repo_path == NULL) {
4533 error = got_worktree_open(&worktree, cwd);
4534 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4535 goto done;
4536 else
4537 error = NULL;
4538 if (worktree) {
4539 repo_path =
4540 strdup(got_worktree_get_repo_path(worktree));
4541 if (repo_path == NULL)
4542 error = got_error_from_errno("strdup");
4543 if (error)
4544 goto done;
4545 } else {
4546 repo_path = strdup(cwd);
4547 if (repo_path == NULL) {
4548 error = got_error_from_errno("strdup");
4549 goto done;
4554 error = got_repo_open(&repo, repo_path, NULL);
4555 if (error != NULL)
4556 goto done;
4558 error = apply_unveil(got_repo_get_path(repo), do_list,
4559 worktree ? got_worktree_get_root_path(worktree) : NULL);
4560 if (error)
4561 goto done;
4563 if (do_show)
4564 error = show_current_branch(repo, worktree);
4565 else if (do_list)
4566 error = list_branches(repo, worktree);
4567 else if (delref)
4568 error = delete_branch(repo, worktree, delref);
4569 else {
4570 if (commit_id_arg == NULL)
4571 commit_id_arg = worktree ?
4572 got_worktree_get_head_ref_name(worktree) :
4573 GOT_REF_HEAD;
4574 error = got_repo_match_object_id(&commit_id, NULL,
4575 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
4576 if (error)
4577 goto done;
4578 error = add_branch(repo, argv[0], commit_id);
4579 if (error)
4580 goto done;
4581 if (worktree && do_update) {
4582 int did_something = 0;
4583 char *branch_refname = NULL;
4585 error = got_object_id_str(&commit_id_str, commit_id);
4586 if (error)
4587 goto done;
4588 error = get_worktree_paths_from_argv(&paths, 0, NULL,
4589 worktree);
4590 if (error)
4591 goto done;
4592 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
4593 == -1) {
4594 error = got_error_from_errno("asprintf");
4595 goto done;
4597 error = got_ref_open(&ref, repo, branch_refname, 0);
4598 free(branch_refname);
4599 if (error)
4600 goto done;
4601 error = switch_head_ref(ref, commit_id, worktree,
4602 repo);
4603 if (error)
4604 goto done;
4605 error = got_worktree_set_base_commit_id(worktree, repo,
4606 commit_id);
4607 if (error)
4608 goto done;
4609 error = got_worktree_checkout_files(worktree, &paths,
4610 repo, update_progress, &did_something,
4611 check_cancelled, NULL);
4612 if (error)
4613 goto done;
4614 if (did_something)
4615 printf("Updated to commit %s\n", commit_id_str);
4618 done:
4619 if (ref)
4620 got_ref_close(ref);
4621 if (repo)
4622 got_repo_close(repo);
4623 if (worktree)
4624 got_worktree_close(worktree);
4625 free(cwd);
4626 free(repo_path);
4627 free(commit_id);
4628 free(commit_id_str);
4629 TAILQ_FOREACH(pe, &paths, entry)
4630 free((char *)pe->path);
4631 got_pathlist_free(&paths);
4632 return error;
4636 __dead static void
4637 usage_tag(void)
4639 fprintf(stderr,
4640 "usage: %s tag [-c commit] [-r repository] [-l] "
4641 "[-m message] name\n", getprogname());
4642 exit(1);
4645 #if 0
4646 static const struct got_error *
4647 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
4649 const struct got_error *err = NULL;
4650 struct got_reflist_entry *re, *se, *new;
4651 struct got_object_id *re_id, *se_id;
4652 struct got_tag_object *re_tag, *se_tag;
4653 time_t re_time, se_time;
4655 SIMPLEQ_FOREACH(re, tags, entry) {
4656 se = SIMPLEQ_FIRST(sorted);
4657 if (se == NULL) {
4658 err = got_reflist_entry_dup(&new, re);
4659 if (err)
4660 return err;
4661 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
4662 continue;
4663 } else {
4664 err = got_ref_resolve(&re_id, repo, re->ref);
4665 if (err)
4666 break;
4667 err = got_object_open_as_tag(&re_tag, repo, re_id);
4668 free(re_id);
4669 if (err)
4670 break;
4671 re_time = got_object_tag_get_tagger_time(re_tag);
4672 got_object_tag_close(re_tag);
4675 while (se) {
4676 err = got_ref_resolve(&se_id, repo, re->ref);
4677 if (err)
4678 break;
4679 err = got_object_open_as_tag(&se_tag, repo, se_id);
4680 free(se_id);
4681 if (err)
4682 break;
4683 se_time = got_object_tag_get_tagger_time(se_tag);
4684 got_object_tag_close(se_tag);
4686 if (se_time > re_time) {
4687 err = got_reflist_entry_dup(&new, re);
4688 if (err)
4689 return err;
4690 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
4691 break;
4693 se = SIMPLEQ_NEXT(se, entry);
4694 continue;
4697 done:
4698 return err;
4700 #endif
4702 static const struct got_error *
4703 list_tags(struct got_repository *repo, struct got_worktree *worktree)
4705 static const struct got_error *err = NULL;
4706 struct got_reflist_head refs;
4707 struct got_reflist_entry *re;
4709 SIMPLEQ_INIT(&refs);
4711 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
4712 if (err)
4713 return err;
4715 SIMPLEQ_FOREACH(re, &refs, entry) {
4716 const char *refname;
4717 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
4718 char datebuf[26];
4719 const char *tagger;
4720 time_t tagger_time;
4721 struct got_object_id *id;
4722 struct got_tag_object *tag;
4723 struct got_commit_object *commit = NULL;
4725 refname = got_ref_get_name(re->ref);
4726 if (strncmp(refname, "refs/tags/", 10) != 0)
4727 continue;
4728 refname += 10;
4729 refstr = got_ref_to_str(re->ref);
4730 if (refstr == NULL) {
4731 err = got_error_from_errno("got_ref_to_str");
4732 break;
4734 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
4735 free(refstr);
4737 err = got_ref_resolve(&id, repo, re->ref);
4738 if (err)
4739 break;
4740 err = got_object_open_as_tag(&tag, repo, id);
4741 if (err) {
4742 if (err->code != GOT_ERR_OBJ_TYPE) {
4743 free(id);
4744 break;
4746 /* "lightweight" tag */
4747 err = got_object_open_as_commit(&commit, repo, id);
4748 if (err) {
4749 free(id);
4750 break;
4752 tagger = got_object_commit_get_committer(commit);
4753 tagger_time =
4754 got_object_commit_get_committer_time(commit);
4755 err = got_object_id_str(&id_str, id);
4756 free(id);
4757 if (err)
4758 break;
4759 } else {
4760 free(id);
4761 tagger = got_object_tag_get_tagger(tag);
4762 tagger_time = got_object_tag_get_tagger_time(tag);
4763 err = got_object_id_str(&id_str,
4764 got_object_tag_get_object_id(tag));
4765 if (err)
4766 break;
4768 printf("from: %s\n", tagger);
4769 datestr = get_datestr(&tagger_time, datebuf);
4770 if (datestr)
4771 printf("date: %s UTC\n", datestr);
4772 if (commit)
4773 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
4774 else {
4775 switch (got_object_tag_get_object_type(tag)) {
4776 case GOT_OBJ_TYPE_BLOB:
4777 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
4778 id_str);
4779 break;
4780 case GOT_OBJ_TYPE_TREE:
4781 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
4782 id_str);
4783 break;
4784 case GOT_OBJ_TYPE_COMMIT:
4785 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
4786 id_str);
4787 break;
4788 case GOT_OBJ_TYPE_TAG:
4789 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
4790 id_str);
4791 break;
4792 default:
4793 break;
4796 free(id_str);
4797 if (commit) {
4798 err = got_object_commit_get_logmsg(&tagmsg0, commit);
4799 if (err)
4800 break;
4801 got_object_commit_close(commit);
4802 } else {
4803 tagmsg0 = strdup(got_object_tag_get_message(tag));
4804 got_object_tag_close(tag);
4805 if (tagmsg0 == NULL) {
4806 err = got_error_from_errno("strdup");
4807 break;
4811 tagmsg = tagmsg0;
4812 do {
4813 line = strsep(&tagmsg, "\n");
4814 if (line)
4815 printf(" %s\n", line);
4816 } while (line);
4817 free(tagmsg0);
4820 got_ref_list_free(&refs);
4821 return NULL;
4824 static const struct got_error *
4825 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
4826 const char *tag_name, const char *repo_path)
4828 const struct got_error *err = NULL;
4829 char *template = NULL, *initial_content = NULL;
4830 char *editor = NULL;
4831 int fd = -1;
4833 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
4834 err = got_error_from_errno("asprintf");
4835 goto done;
4838 if (asprintf(&initial_content, "\n# tagging commit %s as %s\n",
4839 commit_id_str, tag_name) == -1) {
4840 err = got_error_from_errno("asprintf");
4841 goto done;
4844 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
4845 if (err)
4846 goto done;
4848 dprintf(fd, initial_content);
4849 close(fd);
4851 err = get_editor(&editor);
4852 if (err)
4853 goto done;
4854 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
4855 done:
4856 free(initial_content);
4857 free(template);
4858 free(editor);
4860 /* Editor is done; we can now apply unveil(2) */
4861 if (err == NULL) {
4862 err = apply_unveil(repo_path, 0, NULL);
4863 if (err) {
4864 free(*tagmsg);
4865 *tagmsg = NULL;
4868 return err;
4871 static const struct got_error *
4872 add_tag(struct got_repository *repo, const char *tag_name,
4873 const char *commit_arg, const char *tagmsg_arg)
4875 const struct got_error *err = NULL;
4876 struct got_object_id *commit_id = NULL, *tag_id = NULL;
4877 char *label = NULL, *commit_id_str = NULL;
4878 struct got_reference *ref = NULL;
4879 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
4880 char *tagmsg_path = NULL, *tag_id_str = NULL;
4881 int preserve_tagmsg = 0;
4884 * Don't let the user create a tag name with a leading '-'.
4885 * While technically a valid reference name, this case is usually
4886 * an unintended typo.
4888 if (tag_name[0] == '-')
4889 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
4891 err = get_author(&tagger, repo);
4892 if (err)
4893 return err;
4895 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
4896 GOT_OBJ_TYPE_COMMIT, 1, repo);
4897 if (err)
4898 goto done;
4900 err = got_object_id_str(&commit_id_str, commit_id);
4901 if (err)
4902 goto done;
4904 if (strncmp("refs/tags/", tag_name, 10) == 0) {
4905 refname = strdup(tag_name);
4906 if (refname == NULL) {
4907 err = got_error_from_errno("strdup");
4908 goto done;
4910 tag_name += 10;
4911 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
4912 err = got_error_from_errno("asprintf");
4913 goto done;
4916 err = got_ref_open(&ref, repo, refname, 0);
4917 if (err == NULL) {
4918 err = got_error(GOT_ERR_TAG_EXISTS);
4919 goto done;
4920 } else if (err->code != GOT_ERR_NOT_REF)
4921 goto done;
4923 if (tagmsg_arg == NULL) {
4924 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
4925 tag_name, got_repo_get_path(repo));
4926 if (err) {
4927 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
4928 tagmsg_path != NULL)
4929 preserve_tagmsg = 1;
4930 goto done;
4934 err = got_object_tag_create(&tag_id, tag_name, commit_id,
4935 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
4936 if (err) {
4937 if (tagmsg_path)
4938 preserve_tagmsg = 1;
4939 goto done;
4942 err = got_ref_alloc(&ref, refname, tag_id);
4943 if (err) {
4944 if (tagmsg_path)
4945 preserve_tagmsg = 1;
4946 goto done;
4949 err = got_ref_write(ref, repo);
4950 if (err) {
4951 if (tagmsg_path)
4952 preserve_tagmsg = 1;
4953 goto done;
4956 err = got_object_id_str(&tag_id_str, tag_id);
4957 if (err) {
4958 if (tagmsg_path)
4959 preserve_tagmsg = 1;
4960 goto done;
4962 printf("Created tag %s\n", tag_id_str);
4963 done:
4964 if (preserve_tagmsg) {
4965 fprintf(stderr, "%s: tag message preserved in %s\n",
4966 getprogname(), tagmsg_path);
4967 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
4968 err = got_error_from_errno2("unlink", tagmsg_path);
4969 free(tag_id_str);
4970 if (ref)
4971 got_ref_close(ref);
4972 free(commit_id);
4973 free(commit_id_str);
4974 free(refname);
4975 free(tagmsg);
4976 free(tagmsg_path);
4977 free(tagger);
4978 return err;
4981 static const struct got_error *
4982 cmd_tag(int argc, char *argv[])
4984 const struct got_error *error = NULL;
4985 struct got_repository *repo = NULL;
4986 struct got_worktree *worktree = NULL;
4987 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
4988 char *gitconfig_path = NULL;
4989 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
4990 int ch, do_list = 0;
4992 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
4993 switch (ch) {
4994 case 'c':
4995 commit_id_arg = optarg;
4996 break;
4997 case 'm':
4998 tagmsg = optarg;
4999 break;
5000 case 'r':
5001 repo_path = realpath(optarg, NULL);
5002 if (repo_path == NULL)
5003 return got_error_from_errno2("realpath",
5004 optarg);
5005 got_path_strip_trailing_slashes(repo_path);
5006 break;
5007 case 'l':
5008 do_list = 1;
5009 break;
5010 default:
5011 usage_tag();
5012 /* NOTREACHED */
5016 argc -= optind;
5017 argv += optind;
5019 if (do_list) {
5020 if (commit_id_arg != NULL)
5021 errx(1, "-c option can only be used when creating a tag");
5022 if (tagmsg)
5023 errx(1, "-l and -m options are mutually exclusive");
5024 if (argc > 0)
5025 usage_tag();
5026 } else if (argc != 1)
5027 usage_tag();
5029 tag_name = argv[0];
5031 #ifndef PROFILE
5032 if (do_list) {
5033 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5034 NULL) == -1)
5035 err(1, "pledge");
5036 } else {
5037 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5038 "sendfd unveil", NULL) == -1)
5039 err(1, "pledge");
5041 #endif
5042 cwd = getcwd(NULL, 0);
5043 if (cwd == NULL) {
5044 error = got_error_from_errno("getcwd");
5045 goto done;
5048 if (repo_path == NULL) {
5049 error = got_worktree_open(&worktree, cwd);
5050 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5051 goto done;
5052 else
5053 error = NULL;
5054 if (worktree) {
5055 repo_path =
5056 strdup(got_worktree_get_repo_path(worktree));
5057 if (repo_path == NULL)
5058 error = got_error_from_errno("strdup");
5059 if (error)
5060 goto done;
5061 } else {
5062 repo_path = strdup(cwd);
5063 if (repo_path == NULL) {
5064 error = got_error_from_errno("strdup");
5065 goto done;
5070 if (do_list) {
5071 error = got_repo_open(&repo, repo_path, NULL);
5072 if (error != NULL)
5073 goto done;
5074 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5075 if (error)
5076 goto done;
5077 error = list_tags(repo, worktree);
5078 } else {
5079 error = get_gitconfig_path(&gitconfig_path);
5080 if (error)
5081 goto done;
5082 error = got_repo_open(&repo, repo_path, gitconfig_path);
5083 if (error != NULL)
5084 goto done;
5086 if (tagmsg) {
5087 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5088 if (error)
5089 goto done;
5092 if (commit_id_arg == NULL) {
5093 struct got_reference *head_ref;
5094 struct got_object_id *commit_id;
5095 error = got_ref_open(&head_ref, repo,
5096 worktree ? got_worktree_get_head_ref_name(worktree)
5097 : GOT_REF_HEAD, 0);
5098 if (error)
5099 goto done;
5100 error = got_ref_resolve(&commit_id, repo, head_ref);
5101 got_ref_close(head_ref);
5102 if (error)
5103 goto done;
5104 error = got_object_id_str(&commit_id_str, commit_id);
5105 free(commit_id);
5106 if (error)
5107 goto done;
5110 error = add_tag(repo, tag_name,
5111 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
5113 done:
5114 if (repo)
5115 got_repo_close(repo);
5116 if (worktree)
5117 got_worktree_close(worktree);
5118 free(cwd);
5119 free(repo_path);
5120 free(gitconfig_path);
5121 free(commit_id_str);
5122 return error;
5125 __dead static void
5126 usage_add(void)
5128 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
5129 getprogname());
5130 exit(1);
5133 static const struct got_error *
5134 add_progress(void *arg, unsigned char status, const char *path)
5136 while (path[0] == '/')
5137 path++;
5138 printf("%c %s\n", status, path);
5139 return NULL;
5142 static const struct got_error *
5143 cmd_add(int argc, char *argv[])
5145 const struct got_error *error = NULL;
5146 struct got_repository *repo = NULL;
5147 struct got_worktree *worktree = NULL;
5148 char *cwd = NULL;
5149 struct got_pathlist_head paths;
5150 struct got_pathlist_entry *pe;
5151 int ch, can_recurse = 0, no_ignores = 0;
5153 TAILQ_INIT(&paths);
5155 while ((ch = getopt(argc, argv, "IR")) != -1) {
5156 switch (ch) {
5157 case 'I':
5158 no_ignores = 1;
5159 break;
5160 case 'R':
5161 can_recurse = 1;
5162 break;
5163 default:
5164 usage_add();
5165 /* NOTREACHED */
5169 argc -= optind;
5170 argv += optind;
5172 #ifndef PROFILE
5173 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5174 NULL) == -1)
5175 err(1, "pledge");
5176 #endif
5177 if (argc < 1)
5178 usage_add();
5180 cwd = getcwd(NULL, 0);
5181 if (cwd == NULL) {
5182 error = got_error_from_errno("getcwd");
5183 goto done;
5186 error = got_worktree_open(&worktree, cwd);
5187 if (error)
5188 goto done;
5190 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5191 NULL);
5192 if (error != NULL)
5193 goto done;
5195 error = apply_unveil(got_repo_get_path(repo), 1,
5196 got_worktree_get_root_path(worktree));
5197 if (error)
5198 goto done;
5200 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5201 if (error)
5202 goto done;
5204 if (!can_recurse && no_ignores) {
5205 error = got_error_msg(GOT_ERR_BAD_PATH,
5206 "disregarding ignores requires -R option");
5207 goto done;
5211 if (!can_recurse) {
5212 char *ondisk_path;
5213 struct stat sb;
5214 TAILQ_FOREACH(pe, &paths, entry) {
5215 if (asprintf(&ondisk_path, "%s/%s",
5216 got_worktree_get_root_path(worktree),
5217 pe->path) == -1) {
5218 error = got_error_from_errno("asprintf");
5219 goto done;
5221 if (lstat(ondisk_path, &sb) == -1) {
5222 if (errno == ENOENT) {
5223 free(ondisk_path);
5224 continue;
5226 error = got_error_from_errno2("lstat",
5227 ondisk_path);
5228 free(ondisk_path);
5229 goto done;
5231 free(ondisk_path);
5232 if (S_ISDIR(sb.st_mode)) {
5233 error = got_error_msg(GOT_ERR_BAD_PATH,
5234 "adding directories requires -R option");
5235 goto done;
5240 error = got_worktree_schedule_add(worktree, &paths, add_progress,
5241 NULL, repo, no_ignores);
5242 done:
5243 if (repo)
5244 got_repo_close(repo);
5245 if (worktree)
5246 got_worktree_close(worktree);
5247 TAILQ_FOREACH(pe, &paths, entry)
5248 free((char *)pe->path);
5249 got_pathlist_free(&paths);
5250 free(cwd);
5251 return error;
5254 __dead static void
5255 usage_remove(void)
5257 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] path ...\n",
5258 getprogname());
5259 exit(1);
5262 static const struct got_error *
5263 print_remove_status(void *arg, unsigned char status,
5264 unsigned char staged_status, const char *path)
5266 while (path[0] == '/')
5267 path++;
5268 if (status == GOT_STATUS_NONEXISTENT)
5269 return NULL;
5270 if (status == staged_status && (status == GOT_STATUS_DELETE))
5271 status = GOT_STATUS_NO_CHANGE;
5272 printf("%c%c %s\n", status, staged_status, path);
5273 return NULL;
5276 static const struct got_error *
5277 cmd_remove(int argc, char *argv[])
5279 const struct got_error *error = NULL;
5280 struct got_worktree *worktree = NULL;
5281 struct got_repository *repo = NULL;
5282 char *cwd = NULL;
5283 struct got_pathlist_head paths;
5284 struct got_pathlist_entry *pe;
5285 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0;
5287 TAILQ_INIT(&paths);
5289 while ((ch = getopt(argc, argv, "fkR")) != -1) {
5290 switch (ch) {
5291 case 'f':
5292 delete_local_mods = 1;
5293 break;
5294 case 'k':
5295 keep_on_disk = 1;
5296 break;
5297 case 'R':
5298 can_recurse = 1;
5299 break;
5300 default:
5301 usage_remove();
5302 /* NOTREACHED */
5306 argc -= optind;
5307 argv += optind;
5309 #ifndef PROFILE
5310 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5311 NULL) == -1)
5312 err(1, "pledge");
5313 #endif
5314 if (argc < 1)
5315 usage_remove();
5317 cwd = getcwd(NULL, 0);
5318 if (cwd == NULL) {
5319 error = got_error_from_errno("getcwd");
5320 goto done;
5322 error = got_worktree_open(&worktree, cwd);
5323 if (error)
5324 goto done;
5326 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5327 NULL);
5328 if (error)
5329 goto done;
5331 error = apply_unveil(got_repo_get_path(repo), 1,
5332 got_worktree_get_root_path(worktree));
5333 if (error)
5334 goto done;
5336 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5337 if (error)
5338 goto done;
5340 if (!can_recurse) {
5341 char *ondisk_path;
5342 struct stat sb;
5343 TAILQ_FOREACH(pe, &paths, entry) {
5344 if (asprintf(&ondisk_path, "%s/%s",
5345 got_worktree_get_root_path(worktree),
5346 pe->path) == -1) {
5347 error = got_error_from_errno("asprintf");
5348 goto done;
5350 if (lstat(ondisk_path, &sb) == -1) {
5351 if (errno == ENOENT) {
5352 free(ondisk_path);
5353 continue;
5355 error = got_error_from_errno2("lstat",
5356 ondisk_path);
5357 free(ondisk_path);
5358 goto done;
5360 free(ondisk_path);
5361 if (S_ISDIR(sb.st_mode)) {
5362 error = got_error_msg(GOT_ERR_BAD_PATH,
5363 "removing directories requires -R option");
5364 goto done;
5369 error = got_worktree_schedule_delete(worktree, &paths,
5370 delete_local_mods, print_remove_status, NULL, repo, keep_on_disk);
5371 done:
5372 if (repo)
5373 got_repo_close(repo);
5374 if (worktree)
5375 got_worktree_close(worktree);
5376 TAILQ_FOREACH(pe, &paths, entry)
5377 free((char *)pe->path);
5378 got_pathlist_free(&paths);
5379 free(cwd);
5380 return error;
5383 __dead static void
5384 usage_revert(void)
5386 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
5387 "path ...\n", getprogname());
5388 exit(1);
5391 static const struct got_error *
5392 revert_progress(void *arg, unsigned char status, const char *path)
5394 if (status == GOT_STATUS_UNVERSIONED)
5395 return NULL;
5397 while (path[0] == '/')
5398 path++;
5399 printf("%c %s\n", status, path);
5400 return NULL;
5403 struct choose_patch_arg {
5404 FILE *patch_script_file;
5405 const char *action;
5408 static const struct got_error *
5409 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
5410 int nchanges, const char *action)
5412 char *line = NULL;
5413 size_t linesize = 0;
5414 ssize_t linelen;
5416 switch (status) {
5417 case GOT_STATUS_ADD:
5418 printf("A %s\n%s this addition? [y/n] ", path, action);
5419 break;
5420 case GOT_STATUS_DELETE:
5421 printf("D %s\n%s this deletion? [y/n] ", path, action);
5422 break;
5423 case GOT_STATUS_MODIFY:
5424 if (fseek(patch_file, 0L, SEEK_SET) == -1)
5425 return got_error_from_errno("fseek");
5426 printf(GOT_COMMIT_SEP_STR);
5427 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
5428 printf("%s", line);
5429 if (ferror(patch_file))
5430 return got_error_from_errno("getline");
5431 printf(GOT_COMMIT_SEP_STR);
5432 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
5433 path, n, nchanges, action);
5434 break;
5435 default:
5436 return got_error_path(path, GOT_ERR_FILE_STATUS);
5439 return NULL;
5442 static const struct got_error *
5443 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
5444 FILE *patch_file, int n, int nchanges)
5446 const struct got_error *err = NULL;
5447 char *line = NULL;
5448 size_t linesize = 0;
5449 ssize_t linelen;
5450 int resp = ' ';
5451 struct choose_patch_arg *a = arg;
5453 *choice = GOT_PATCH_CHOICE_NONE;
5455 if (a->patch_script_file) {
5456 char *nl;
5457 err = show_change(status, path, patch_file, n, nchanges,
5458 a->action);
5459 if (err)
5460 return err;
5461 linelen = getline(&line, &linesize, a->patch_script_file);
5462 if (linelen == -1) {
5463 if (ferror(a->patch_script_file))
5464 return got_error_from_errno("getline");
5465 return NULL;
5467 nl = strchr(line, '\n');
5468 if (nl)
5469 *nl = '\0';
5470 if (strcmp(line, "y") == 0) {
5471 *choice = GOT_PATCH_CHOICE_YES;
5472 printf("y\n");
5473 } else if (strcmp(line, "n") == 0) {
5474 *choice = GOT_PATCH_CHOICE_NO;
5475 printf("n\n");
5476 } else if (strcmp(line, "q") == 0 &&
5477 status == GOT_STATUS_MODIFY) {
5478 *choice = GOT_PATCH_CHOICE_QUIT;
5479 printf("q\n");
5480 } else
5481 printf("invalid response '%s'\n", line);
5482 free(line);
5483 return NULL;
5486 while (resp != 'y' && resp != 'n' && resp != 'q') {
5487 err = show_change(status, path, patch_file, n, nchanges,
5488 a->action);
5489 if (err)
5490 return err;
5491 resp = getchar();
5492 if (resp == '\n')
5493 resp = getchar();
5494 if (status == GOT_STATUS_MODIFY) {
5495 if (resp != 'y' && resp != 'n' && resp != 'q') {
5496 printf("invalid response '%c'\n", resp);
5497 resp = ' ';
5499 } else if (resp != 'y' && resp != 'n') {
5500 printf("invalid response '%c'\n", resp);
5501 resp = ' ';
5505 if (resp == 'y')
5506 *choice = GOT_PATCH_CHOICE_YES;
5507 else if (resp == 'n')
5508 *choice = GOT_PATCH_CHOICE_NO;
5509 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
5510 *choice = GOT_PATCH_CHOICE_QUIT;
5512 return NULL;
5516 static const struct got_error *
5517 cmd_revert(int argc, char *argv[])
5519 const struct got_error *error = NULL;
5520 struct got_worktree *worktree = NULL;
5521 struct got_repository *repo = NULL;
5522 char *cwd = NULL, *path = NULL;
5523 struct got_pathlist_head paths;
5524 struct got_pathlist_entry *pe;
5525 int ch, can_recurse = 0, pflag = 0;
5526 FILE *patch_script_file = NULL;
5527 const char *patch_script_path = NULL;
5528 struct choose_patch_arg cpa;
5530 TAILQ_INIT(&paths);
5532 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
5533 switch (ch) {
5534 case 'p':
5535 pflag = 1;
5536 break;
5537 case 'F':
5538 patch_script_path = optarg;
5539 break;
5540 case 'R':
5541 can_recurse = 1;
5542 break;
5543 default:
5544 usage_revert();
5545 /* NOTREACHED */
5549 argc -= optind;
5550 argv += optind;
5552 #ifndef PROFILE
5553 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
5554 "unveil", NULL) == -1)
5555 err(1, "pledge");
5556 #endif
5557 if (argc < 1)
5558 usage_revert();
5559 if (patch_script_path && !pflag)
5560 errx(1, "-F option can only be used together with -p option");
5562 cwd = getcwd(NULL, 0);
5563 if (cwd == NULL) {
5564 error = got_error_from_errno("getcwd");
5565 goto done;
5567 error = got_worktree_open(&worktree, cwd);
5568 if (error)
5569 goto done;
5571 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5572 NULL);
5573 if (error != NULL)
5574 goto done;
5576 if (patch_script_path) {
5577 patch_script_file = fopen(patch_script_path, "r");
5578 if (patch_script_file == NULL) {
5579 error = got_error_from_errno2("fopen",
5580 patch_script_path);
5581 goto done;
5584 error = apply_unveil(got_repo_get_path(repo), 1,
5585 got_worktree_get_root_path(worktree));
5586 if (error)
5587 goto done;
5589 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5590 if (error)
5591 goto done;
5593 if (!can_recurse) {
5594 char *ondisk_path;
5595 struct stat sb;
5596 TAILQ_FOREACH(pe, &paths, entry) {
5597 if (asprintf(&ondisk_path, "%s/%s",
5598 got_worktree_get_root_path(worktree),
5599 pe->path) == -1) {
5600 error = got_error_from_errno("asprintf");
5601 goto done;
5603 if (lstat(ondisk_path, &sb) == -1) {
5604 if (errno == ENOENT) {
5605 free(ondisk_path);
5606 continue;
5608 error = got_error_from_errno2("lstat",
5609 ondisk_path);
5610 free(ondisk_path);
5611 goto done;
5613 free(ondisk_path);
5614 if (S_ISDIR(sb.st_mode)) {
5615 error = got_error_msg(GOT_ERR_BAD_PATH,
5616 "reverting directories requires -R option");
5617 goto done;
5622 cpa.patch_script_file = patch_script_file;
5623 cpa.action = "revert";
5624 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
5625 pflag ? choose_patch : NULL, &cpa, repo);
5626 done:
5627 if (patch_script_file && fclose(patch_script_file) == EOF &&
5628 error == NULL)
5629 error = got_error_from_errno2("fclose", patch_script_path);
5630 if (repo)
5631 got_repo_close(repo);
5632 if (worktree)
5633 got_worktree_close(worktree);
5634 free(path);
5635 free(cwd);
5636 return error;
5639 __dead static void
5640 usage_commit(void)
5642 fprintf(stderr, "usage: %s commit [-m msg] [path ...]\n",
5643 getprogname());
5644 exit(1);
5647 struct collect_commit_logmsg_arg {
5648 const char *cmdline_log;
5649 const char *editor;
5650 const char *worktree_path;
5651 const char *branch_name;
5652 const char *repo_path;
5653 char *logmsg_path;
5657 static const struct got_error *
5658 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
5659 void *arg)
5661 char *initial_content = NULL;
5662 struct got_pathlist_entry *pe;
5663 const struct got_error *err = NULL;
5664 char *template = NULL;
5665 struct collect_commit_logmsg_arg *a = arg;
5666 int fd;
5667 size_t len;
5669 /* if a message was specified on the command line, just use it */
5670 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
5671 len = strlen(a->cmdline_log) + 1;
5672 *logmsg = malloc(len + 1);
5673 if (*logmsg == NULL)
5674 return got_error_from_errno("malloc");
5675 strlcpy(*logmsg, a->cmdline_log, len);
5676 return NULL;
5679 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
5680 return got_error_from_errno("asprintf");
5682 if (asprintf(&initial_content,
5683 "\n# changes to be committed on branch %s:\n",
5684 a->branch_name) == -1)
5685 return got_error_from_errno("asprintf");
5687 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
5688 if (err)
5689 goto done;
5691 dprintf(fd, initial_content);
5693 TAILQ_FOREACH(pe, commitable_paths, entry) {
5694 struct got_commitable *ct = pe->data;
5695 dprintf(fd, "# %c %s\n",
5696 got_commitable_get_status(ct),
5697 got_commitable_get_path(ct));
5699 close(fd);
5701 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
5702 done:
5703 free(initial_content);
5704 free(template);
5706 /* Editor is done; we can now apply unveil(2) */
5707 if (err == NULL) {
5708 err = apply_unveil(a->repo_path, 0, a->worktree_path);
5709 if (err) {
5710 free(*logmsg);
5711 *logmsg = NULL;
5714 return err;
5717 static const struct got_error *
5718 cmd_commit(int argc, char *argv[])
5720 const struct got_error *error = NULL;
5721 struct got_worktree *worktree = NULL;
5722 struct got_repository *repo = NULL;
5723 char *cwd = NULL, *id_str = NULL;
5724 struct got_object_id *id = NULL;
5725 const char *logmsg = NULL;
5726 struct collect_commit_logmsg_arg cl_arg;
5727 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
5728 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
5729 struct got_pathlist_head paths;
5731 TAILQ_INIT(&paths);
5732 cl_arg.logmsg_path = NULL;
5734 while ((ch = getopt(argc, argv, "m:")) != -1) {
5735 switch (ch) {
5736 case 'm':
5737 logmsg = optarg;
5738 break;
5739 default:
5740 usage_commit();
5741 /* NOTREACHED */
5745 argc -= optind;
5746 argv += optind;
5748 #ifndef PROFILE
5749 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
5750 "unveil", NULL) == -1)
5751 err(1, "pledge");
5752 #endif
5753 cwd = getcwd(NULL, 0);
5754 if (cwd == NULL) {
5755 error = got_error_from_errno("getcwd");
5756 goto done;
5758 error = got_worktree_open(&worktree, cwd);
5759 if (error)
5760 goto done;
5762 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
5763 if (error)
5764 goto done;
5765 if (rebase_in_progress) {
5766 error = got_error(GOT_ERR_REBASING);
5767 goto done;
5770 error = got_worktree_histedit_in_progress(&histedit_in_progress,
5771 worktree);
5772 if (error)
5773 goto done;
5775 error = get_gitconfig_path(&gitconfig_path);
5776 if (error)
5777 goto done;
5778 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5779 gitconfig_path);
5780 if (error != NULL)
5781 goto done;
5783 error = get_author(&author, repo);
5784 if (error)
5785 return error;
5788 * unveil(2) traverses exec(2); if an editor is used we have
5789 * to apply unveil after the log message has been written.
5791 if (logmsg == NULL || strlen(logmsg) == 0)
5792 error = get_editor(&editor);
5793 else
5794 error = apply_unveil(got_repo_get_path(repo), 0,
5795 got_worktree_get_root_path(worktree));
5796 if (error)
5797 goto done;
5799 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5800 if (error)
5801 goto done;
5803 cl_arg.editor = editor;
5804 cl_arg.cmdline_log = logmsg;
5805 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
5806 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
5807 if (!histedit_in_progress) {
5808 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
5809 error = got_error(GOT_ERR_COMMIT_BRANCH);
5810 goto done;
5812 cl_arg.branch_name += 11;
5814 cl_arg.repo_path = got_repo_get_path(repo);
5815 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
5816 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
5817 if (error) {
5818 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5819 cl_arg.logmsg_path != NULL)
5820 preserve_logmsg = 1;
5821 goto done;
5824 error = got_object_id_str(&id_str, id);
5825 if (error)
5826 goto done;
5827 printf("Created commit %s\n", id_str);
5828 done:
5829 if (preserve_logmsg) {
5830 fprintf(stderr, "%s: log message preserved in %s\n",
5831 getprogname(), cl_arg.logmsg_path);
5832 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
5833 error == NULL)
5834 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
5835 free(cl_arg.logmsg_path);
5836 if (repo)
5837 got_repo_close(repo);
5838 if (worktree)
5839 got_worktree_close(worktree);
5840 free(cwd);
5841 free(id_str);
5842 free(gitconfig_path);
5843 free(editor);
5844 free(author);
5845 return error;
5848 __dead static void
5849 usage_cherrypick(void)
5851 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
5852 exit(1);
5855 static const struct got_error *
5856 cmd_cherrypick(int argc, char *argv[])
5858 const struct got_error *error = NULL;
5859 struct got_worktree *worktree = NULL;
5860 struct got_repository *repo = NULL;
5861 char *cwd = NULL, *commit_id_str = NULL;
5862 struct got_object_id *commit_id = NULL;
5863 struct got_commit_object *commit = NULL;
5864 struct got_object_qid *pid;
5865 struct got_reference *head_ref = NULL;
5866 int ch, did_something = 0;
5868 while ((ch = getopt(argc, argv, "")) != -1) {
5869 switch (ch) {
5870 default:
5871 usage_cherrypick();
5872 /* NOTREACHED */
5876 argc -= optind;
5877 argv += optind;
5879 #ifndef PROFILE
5880 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
5881 "unveil", NULL) == -1)
5882 err(1, "pledge");
5883 #endif
5884 if (argc != 1)
5885 usage_cherrypick();
5887 cwd = getcwd(NULL, 0);
5888 if (cwd == NULL) {
5889 error = got_error_from_errno("getcwd");
5890 goto done;
5892 error = got_worktree_open(&worktree, cwd);
5893 if (error)
5894 goto done;
5896 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5897 NULL);
5898 if (error != NULL)
5899 goto done;
5901 error = apply_unveil(got_repo_get_path(repo), 0,
5902 got_worktree_get_root_path(worktree));
5903 if (error)
5904 goto done;
5906 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
5907 GOT_OBJ_TYPE_COMMIT, repo);
5908 if (error != NULL) {
5909 struct got_reference *ref;
5910 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
5911 goto done;
5912 error = got_ref_open(&ref, repo, argv[0], 0);
5913 if (error != NULL)
5914 goto done;
5915 error = got_ref_resolve(&commit_id, repo, ref);
5916 got_ref_close(ref);
5917 if (error != NULL)
5918 goto done;
5920 error = got_object_id_str(&commit_id_str, commit_id);
5921 if (error)
5922 goto done;
5924 error = got_ref_open(&head_ref, repo,
5925 got_worktree_get_head_ref_name(worktree), 0);
5926 if (error != NULL)
5927 goto done;
5929 error = check_same_branch(commit_id, head_ref, NULL, repo);
5930 if (error) {
5931 if (error->code != GOT_ERR_ANCESTRY)
5932 goto done;
5933 error = NULL;
5934 } else {
5935 error = got_error(GOT_ERR_SAME_BRANCH);
5936 goto done;
5939 error = got_object_open_as_commit(&commit, repo, commit_id);
5940 if (error)
5941 goto done;
5942 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
5943 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
5944 commit_id, repo, update_progress, &did_something, check_cancelled,
5945 NULL);
5946 if (error != NULL)
5947 goto done;
5949 if (did_something)
5950 printf("Merged commit %s\n", commit_id_str);
5951 done:
5952 if (commit)
5953 got_object_commit_close(commit);
5954 free(commit_id_str);
5955 if (head_ref)
5956 got_ref_close(head_ref);
5957 if (worktree)
5958 got_worktree_close(worktree);
5959 if (repo)
5960 got_repo_close(repo);
5961 return error;
5964 __dead static void
5965 usage_backout(void)
5967 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
5968 exit(1);
5971 static const struct got_error *
5972 cmd_backout(int argc, char *argv[])
5974 const struct got_error *error = NULL;
5975 struct got_worktree *worktree = NULL;
5976 struct got_repository *repo = NULL;
5977 char *cwd = NULL, *commit_id_str = NULL;
5978 struct got_object_id *commit_id = NULL;
5979 struct got_commit_object *commit = NULL;
5980 struct got_object_qid *pid;
5981 struct got_reference *head_ref = NULL;
5982 int ch, did_something = 0;
5984 while ((ch = getopt(argc, argv, "")) != -1) {
5985 switch (ch) {
5986 default:
5987 usage_backout();
5988 /* NOTREACHED */
5992 argc -= optind;
5993 argv += optind;
5995 #ifndef PROFILE
5996 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
5997 "unveil", NULL) == -1)
5998 err(1, "pledge");
5999 #endif
6000 if (argc != 1)
6001 usage_backout();
6003 cwd = getcwd(NULL, 0);
6004 if (cwd == NULL) {
6005 error = got_error_from_errno("getcwd");
6006 goto done;
6008 error = got_worktree_open(&worktree, cwd);
6009 if (error)
6010 goto done;
6012 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6013 NULL);
6014 if (error != NULL)
6015 goto done;
6017 error = apply_unveil(got_repo_get_path(repo), 0,
6018 got_worktree_get_root_path(worktree));
6019 if (error)
6020 goto done;
6022 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6023 GOT_OBJ_TYPE_COMMIT, repo);
6024 if (error != NULL) {
6025 struct got_reference *ref;
6026 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6027 goto done;
6028 error = got_ref_open(&ref, repo, argv[0], 0);
6029 if (error != NULL)
6030 goto done;
6031 error = got_ref_resolve(&commit_id, repo, ref);
6032 got_ref_close(ref);
6033 if (error != NULL)
6034 goto done;
6036 error = got_object_id_str(&commit_id_str, commit_id);
6037 if (error)
6038 goto done;
6040 error = got_ref_open(&head_ref, repo,
6041 got_worktree_get_head_ref_name(worktree), 0);
6042 if (error != NULL)
6043 goto done;
6045 error = check_same_branch(commit_id, head_ref, NULL, repo);
6046 if (error)
6047 goto done;
6049 error = got_object_open_as_commit(&commit, repo, commit_id);
6050 if (error)
6051 goto done;
6052 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6053 if (pid == NULL) {
6054 error = got_error(GOT_ERR_ROOT_COMMIT);
6055 goto done;
6058 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
6059 update_progress, &did_something, check_cancelled, NULL);
6060 if (error != NULL)
6061 goto done;
6063 if (did_something)
6064 printf("Backed out commit %s\n", commit_id_str);
6065 done:
6066 if (commit)
6067 got_object_commit_close(commit);
6068 free(commit_id_str);
6069 if (head_ref)
6070 got_ref_close(head_ref);
6071 if (worktree)
6072 got_worktree_close(worktree);
6073 if (repo)
6074 got_repo_close(repo);
6075 return error;
6078 __dead static void
6079 usage_rebase(void)
6081 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
6082 getprogname());
6083 exit(1);
6086 void
6087 trim_logmsg(char *logmsg, int limit)
6089 char *nl;
6090 size_t len;
6092 len = strlen(logmsg);
6093 if (len > limit)
6094 len = limit;
6095 logmsg[len] = '\0';
6096 nl = strchr(logmsg, '\n');
6097 if (nl)
6098 *nl = '\0';
6101 static const struct got_error *
6102 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
6104 const struct got_error *err;
6105 char *logmsg0 = NULL;
6106 const char *s;
6108 err = got_object_commit_get_logmsg(&logmsg0, commit);
6109 if (err)
6110 return err;
6112 s = logmsg0;
6113 while (isspace((unsigned char)s[0]))
6114 s++;
6116 *logmsg = strdup(s);
6117 if (*logmsg == NULL) {
6118 err = got_error_from_errno("strdup");
6119 goto done;
6122 trim_logmsg(*logmsg, limit);
6123 done:
6124 free(logmsg0);
6125 return err;
6128 static const struct got_error *
6129 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
6131 const struct got_error *err;
6132 struct got_commit_object *commit = NULL;
6133 char *id_str = NULL, *logmsg = NULL;
6135 err = got_object_open_as_commit(&commit, repo, id);
6136 if (err)
6137 return err;
6139 err = got_object_id_str(&id_str, id);
6140 if (err)
6141 goto done;
6143 id_str[12] = '\0';
6145 err = get_short_logmsg(&logmsg, 42, commit);
6146 if (err)
6147 goto done;
6149 printf("%s -> merge conflict: %s\n", id_str, logmsg);
6150 done:
6151 free(id_str);
6152 got_object_commit_close(commit);
6153 free(logmsg);
6154 return err;
6157 static const struct got_error *
6158 show_rebase_progress(struct got_commit_object *commit,
6159 struct got_object_id *old_id, struct got_object_id *new_id)
6161 const struct got_error *err;
6162 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
6164 err = got_object_id_str(&old_id_str, old_id);
6165 if (err)
6166 goto done;
6168 if (new_id) {
6169 err = got_object_id_str(&new_id_str, new_id);
6170 if (err)
6171 goto done;
6174 old_id_str[12] = '\0';
6175 if (new_id_str)
6176 new_id_str[12] = '\0';
6178 err = get_short_logmsg(&logmsg, 42, commit);
6179 if (err)
6180 goto done;
6182 printf("%s -> %s: %s\n", old_id_str,
6183 new_id_str ? new_id_str : "no-op change", logmsg);
6184 done:
6185 free(old_id_str);
6186 free(new_id_str);
6187 free(logmsg);
6188 return err;
6191 static const struct got_error *
6192 rebase_progress(void *arg, unsigned char status, const char *path)
6194 unsigned char *rebase_status = arg;
6196 while (path[0] == '/')
6197 path++;
6198 printf("%c %s\n", status, path);
6200 if (*rebase_status == GOT_STATUS_CONFLICT)
6201 return NULL;
6202 if (status == GOT_STATUS_CONFLICT || status == GOT_STATUS_MERGE)
6203 *rebase_status = status;
6204 return NULL;
6207 static const struct got_error *
6208 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
6209 struct got_reference *branch, struct got_reference *new_base_branch,
6210 struct got_reference *tmp_branch, struct got_repository *repo)
6212 printf("Switching work tree to %s\n", got_ref_get_name(branch));
6213 return got_worktree_rebase_complete(worktree, fileindex,
6214 new_base_branch, tmp_branch, branch, repo);
6217 static const struct got_error *
6218 rebase_commit(struct got_pathlist_head *merged_paths,
6219 struct got_worktree *worktree, struct got_fileindex *fileindex,
6220 struct got_reference *tmp_branch,
6221 struct got_object_id *commit_id, struct got_repository *repo)
6223 const struct got_error *error;
6224 struct got_commit_object *commit;
6225 struct got_object_id *new_commit_id;
6227 error = got_object_open_as_commit(&commit, repo, commit_id);
6228 if (error)
6229 return error;
6231 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
6232 worktree, fileindex, tmp_branch, commit, commit_id, repo);
6233 if (error) {
6234 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
6235 goto done;
6236 error = show_rebase_progress(commit, commit_id, NULL);
6237 } else {
6238 error = show_rebase_progress(commit, commit_id, new_commit_id);
6239 free(new_commit_id);
6241 done:
6242 got_object_commit_close(commit);
6243 return error;
6246 struct check_path_prefix_arg {
6247 const char *path_prefix;
6248 size_t len;
6249 int errcode;
6252 static const struct got_error *
6253 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
6254 struct got_blob_object *blob2, struct got_object_id *id1,
6255 struct got_object_id *id2, const char *path1, const char *path2,
6256 mode_t mode1, mode_t mode2, struct got_repository *repo)
6258 struct check_path_prefix_arg *a = arg;
6260 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
6261 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
6262 return got_error(a->errcode);
6264 return NULL;
6267 static const struct got_error *
6268 check_path_prefix(struct got_object_id *parent_id,
6269 struct got_object_id *commit_id, const char *path_prefix,
6270 int errcode, struct got_repository *repo)
6272 const struct got_error *err;
6273 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
6274 struct got_commit_object *commit = NULL, *parent_commit = NULL;
6275 struct check_path_prefix_arg cpp_arg;
6277 if (got_path_is_root_dir(path_prefix))
6278 return NULL;
6280 err = got_object_open_as_commit(&commit, repo, commit_id);
6281 if (err)
6282 goto done;
6284 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
6285 if (err)
6286 goto done;
6288 err = got_object_open_as_tree(&tree1, repo,
6289 got_object_commit_get_tree_id(parent_commit));
6290 if (err)
6291 goto done;
6293 err = got_object_open_as_tree(&tree2, repo,
6294 got_object_commit_get_tree_id(commit));
6295 if (err)
6296 goto done;
6298 cpp_arg.path_prefix = path_prefix;
6299 while (cpp_arg.path_prefix[0] == '/')
6300 cpp_arg.path_prefix++;
6301 cpp_arg.len = strlen(cpp_arg.path_prefix);
6302 cpp_arg.errcode = errcode;
6303 err = got_diff_tree(tree1, tree2, "", "", repo,
6304 check_path_prefix_in_diff, &cpp_arg, 0);
6305 done:
6306 if (tree1)
6307 got_object_tree_close(tree1);
6308 if (tree2)
6309 got_object_tree_close(tree2);
6310 if (commit)
6311 got_object_commit_close(commit);
6312 if (parent_commit)
6313 got_object_commit_close(parent_commit);
6314 return err;
6317 static const struct got_error *
6318 collect_commits(struct got_object_id_queue *commits,
6319 struct got_object_id *initial_commit_id,
6320 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
6321 const char *path_prefix, int path_prefix_errcode,
6322 struct got_repository *repo)
6324 const struct got_error *err = NULL;
6325 struct got_commit_graph *graph = NULL;
6326 struct got_object_id *parent_id = NULL;
6327 struct got_object_qid *qid;
6328 struct got_object_id *commit_id = initial_commit_id;
6330 err = got_commit_graph_open(&graph, "/", 1);
6331 if (err)
6332 return err;
6334 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
6335 check_cancelled, NULL);
6336 if (err)
6337 goto done;
6338 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
6339 err = got_commit_graph_iter_next(&parent_id, graph, repo,
6340 check_cancelled, NULL);
6341 if (err) {
6342 if (err->code == GOT_ERR_ITER_COMPLETED) {
6343 err = got_error_msg(GOT_ERR_ANCESTRY,
6344 "ran out of commits to rebase before "
6345 "youngest common ancestor commit has "
6346 "been reached?!?");
6348 goto done;
6349 } else {
6350 err = check_path_prefix(parent_id, commit_id,
6351 path_prefix, path_prefix_errcode, repo);
6352 if (err)
6353 goto done;
6355 err = got_object_qid_alloc(&qid, commit_id);
6356 if (err)
6357 goto done;
6358 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
6359 commit_id = parent_id;
6362 done:
6363 got_commit_graph_close(graph);
6364 return err;
6367 static const struct got_error *
6368 cmd_rebase(int argc, char *argv[])
6370 const struct got_error *error = NULL;
6371 struct got_worktree *worktree = NULL;
6372 struct got_repository *repo = NULL;
6373 struct got_fileindex *fileindex = NULL;
6374 char *cwd = NULL;
6375 struct got_reference *branch = NULL;
6376 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
6377 struct got_object_id *commit_id = NULL, *parent_id = NULL;
6378 struct got_object_id *resume_commit_id = NULL;
6379 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
6380 struct got_commit_object *commit = NULL;
6381 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
6382 int histedit_in_progress = 0;
6383 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
6384 struct got_object_id_queue commits;
6385 struct got_pathlist_head merged_paths;
6386 const struct got_object_id_queue *parent_ids;
6387 struct got_object_qid *qid, *pid;
6389 SIMPLEQ_INIT(&commits);
6390 TAILQ_INIT(&merged_paths);
6392 while ((ch = getopt(argc, argv, "ac")) != -1) {
6393 switch (ch) {
6394 case 'a':
6395 abort_rebase = 1;
6396 break;
6397 case 'c':
6398 continue_rebase = 1;
6399 break;
6400 default:
6401 usage_rebase();
6402 /* NOTREACHED */
6406 argc -= optind;
6407 argv += optind;
6409 #ifndef PROFILE
6410 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6411 "unveil", NULL) == -1)
6412 err(1, "pledge");
6413 #endif
6414 if (abort_rebase && continue_rebase)
6415 usage_rebase();
6416 else if (abort_rebase || continue_rebase) {
6417 if (argc != 0)
6418 usage_rebase();
6419 } else if (argc != 1)
6420 usage_rebase();
6422 cwd = getcwd(NULL, 0);
6423 if (cwd == NULL) {
6424 error = got_error_from_errno("getcwd");
6425 goto done;
6427 error = got_worktree_open(&worktree, cwd);
6428 if (error)
6429 goto done;
6431 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6432 NULL);
6433 if (error != NULL)
6434 goto done;
6436 error = apply_unveil(got_repo_get_path(repo), 0,
6437 got_worktree_get_root_path(worktree));
6438 if (error)
6439 goto done;
6441 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6442 worktree);
6443 if (error)
6444 goto done;
6445 if (histedit_in_progress) {
6446 error = got_error(GOT_ERR_HISTEDIT_BUSY);
6447 goto done;
6450 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6451 if (error)
6452 goto done;
6454 if (abort_rebase) {
6455 int did_something;
6456 if (!rebase_in_progress) {
6457 error = got_error(GOT_ERR_NOT_REBASING);
6458 goto done;
6460 error = got_worktree_rebase_continue(&resume_commit_id,
6461 &new_base_branch, &tmp_branch, &branch, &fileindex,
6462 worktree, repo);
6463 if (error)
6464 goto done;
6465 printf("Switching work tree to %s\n",
6466 got_ref_get_symref_target(new_base_branch));
6467 error = got_worktree_rebase_abort(worktree, fileindex, repo,
6468 new_base_branch, update_progress, &did_something);
6469 if (error)
6470 goto done;
6471 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
6472 goto done; /* nothing else to do */
6475 if (continue_rebase) {
6476 if (!rebase_in_progress) {
6477 error = got_error(GOT_ERR_NOT_REBASING);
6478 goto done;
6480 error = got_worktree_rebase_continue(&resume_commit_id,
6481 &new_base_branch, &tmp_branch, &branch, &fileindex,
6482 worktree, repo);
6483 if (error)
6484 goto done;
6486 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
6487 resume_commit_id, repo);
6488 if (error)
6489 goto done;
6491 yca_id = got_object_id_dup(resume_commit_id);
6492 if (yca_id == NULL) {
6493 error = got_error_from_errno("got_object_id_dup");
6494 goto done;
6496 } else {
6497 error = got_ref_open(&branch, repo, argv[0], 0);
6498 if (error != NULL)
6499 goto done;
6502 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
6503 if (error)
6504 goto done;
6506 if (!continue_rebase) {
6507 struct got_object_id *base_commit_id;
6509 base_commit_id = got_worktree_get_base_commit_id(worktree);
6510 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
6511 base_commit_id, branch_head_commit_id, repo,
6512 check_cancelled, NULL);
6513 if (error)
6514 goto done;
6515 if (yca_id == NULL) {
6516 error = got_error_msg(GOT_ERR_ANCESTRY,
6517 "specified branch shares no common ancestry "
6518 "with work tree's branch");
6519 goto done;
6522 error = check_same_branch(base_commit_id, branch, yca_id, repo);
6523 if (error) {
6524 if (error->code != GOT_ERR_ANCESTRY)
6525 goto done;
6526 error = NULL;
6527 } else {
6528 error = got_error_msg(GOT_ERR_SAME_BRANCH,
6529 "specified branch resolves to a commit which "
6530 "is already contained in work tree's branch");
6531 goto done;
6533 error = got_worktree_rebase_prepare(&new_base_branch,
6534 &tmp_branch, &fileindex, worktree, branch, repo);
6535 if (error)
6536 goto done;
6539 commit_id = branch_head_commit_id;
6540 error = got_object_open_as_commit(&commit, repo, commit_id);
6541 if (error)
6542 goto done;
6544 parent_ids = got_object_commit_get_parent_ids(commit);
6545 pid = SIMPLEQ_FIRST(parent_ids);
6546 if (pid == NULL) {
6547 if (!continue_rebase) {
6548 int did_something;
6549 error = got_worktree_rebase_abort(worktree, fileindex,
6550 repo, new_base_branch, update_progress,
6551 &did_something);
6552 if (error)
6553 goto done;
6554 printf("Rebase of %s aborted\n",
6555 got_ref_get_name(branch));
6557 error = got_error(GOT_ERR_EMPTY_REBASE);
6558 goto done;
6560 error = collect_commits(&commits, commit_id, pid->id,
6561 yca_id, got_worktree_get_path_prefix(worktree),
6562 GOT_ERR_REBASE_PATH, repo);
6563 got_object_commit_close(commit);
6564 commit = NULL;
6565 if (error)
6566 goto done;
6568 if (SIMPLEQ_EMPTY(&commits)) {
6569 if (continue_rebase) {
6570 error = rebase_complete(worktree, fileindex,
6571 branch, new_base_branch, tmp_branch, repo);
6572 goto done;
6573 } else {
6574 /* Fast-forward the reference of the branch. */
6575 struct got_object_id *new_head_commit_id;
6576 char *id_str;
6577 error = got_ref_resolve(&new_head_commit_id, repo,
6578 new_base_branch);
6579 if (error)
6580 goto done;
6581 error = got_object_id_str(&id_str, new_head_commit_id);
6582 printf("Forwarding %s to commit %s\n",
6583 got_ref_get_name(branch), id_str);
6584 free(id_str);
6585 error = got_ref_change_ref(branch,
6586 new_head_commit_id);
6587 if (error)
6588 goto done;
6592 pid = NULL;
6593 SIMPLEQ_FOREACH(qid, &commits, entry) {
6594 commit_id = qid->id;
6595 parent_id = pid ? pid->id : yca_id;
6596 pid = qid;
6598 error = got_worktree_rebase_merge_files(&merged_paths,
6599 worktree, fileindex, parent_id, commit_id, repo,
6600 rebase_progress, &rebase_status, check_cancelled, NULL);
6601 if (error)
6602 goto done;
6604 if (rebase_status == GOT_STATUS_CONFLICT) {
6605 error = show_rebase_merge_conflict(qid->id, repo);
6606 if (error)
6607 goto done;
6608 got_worktree_rebase_pathlist_free(&merged_paths);
6609 break;
6612 error = rebase_commit(&merged_paths, worktree, fileindex,
6613 tmp_branch, commit_id, repo);
6614 got_worktree_rebase_pathlist_free(&merged_paths);
6615 if (error)
6616 goto done;
6619 if (rebase_status == GOT_STATUS_CONFLICT) {
6620 error = got_worktree_rebase_postpone(worktree, fileindex);
6621 if (error)
6622 goto done;
6623 error = got_error_msg(GOT_ERR_CONFLICTS,
6624 "conflicts must be resolved before rebasing can continue");
6625 } else
6626 error = rebase_complete(worktree, fileindex, branch,
6627 new_base_branch, tmp_branch, repo);
6628 done:
6629 got_object_id_queue_free(&commits);
6630 free(branch_head_commit_id);
6631 free(resume_commit_id);
6632 free(yca_id);
6633 if (commit)
6634 got_object_commit_close(commit);
6635 if (branch)
6636 got_ref_close(branch);
6637 if (new_base_branch)
6638 got_ref_close(new_base_branch);
6639 if (tmp_branch)
6640 got_ref_close(tmp_branch);
6641 if (worktree)
6642 got_worktree_close(worktree);
6643 if (repo)
6644 got_repo_close(repo);
6645 return error;
6648 __dead static void
6649 usage_histedit(void)
6651 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
6652 getprogname());
6653 exit(1);
6656 #define GOT_HISTEDIT_PICK 'p'
6657 #define GOT_HISTEDIT_EDIT 'e'
6658 #define GOT_HISTEDIT_FOLD 'f'
6659 #define GOT_HISTEDIT_DROP 'd'
6660 #define GOT_HISTEDIT_MESG 'm'
6662 static struct got_histedit_cmd {
6663 unsigned char code;
6664 const char *name;
6665 const char *desc;
6666 } got_histedit_cmds[] = {
6667 { GOT_HISTEDIT_PICK, "pick", "use commit" },
6668 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
6669 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
6670 "be used" },
6671 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
6672 { GOT_HISTEDIT_MESG, "mesg",
6673 "single-line log message for commit above (open editor if empty)" },
6676 struct got_histedit_list_entry {
6677 TAILQ_ENTRY(got_histedit_list_entry) entry;
6678 struct got_object_id *commit_id;
6679 const struct got_histedit_cmd *cmd;
6680 char *logmsg;
6682 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
6684 static const struct got_error *
6685 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
6686 FILE *f, struct got_repository *repo)
6688 const struct got_error *err = NULL;
6689 char *logmsg = NULL, *id_str = NULL;
6690 struct got_commit_object *commit = NULL;
6691 int n;
6693 err = got_object_open_as_commit(&commit, repo, commit_id);
6694 if (err)
6695 goto done;
6697 err = get_short_logmsg(&logmsg, 34, commit);
6698 if (err)
6699 goto done;
6701 err = got_object_id_str(&id_str, commit_id);
6702 if (err)
6703 goto done;
6705 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
6706 if (n < 0)
6707 err = got_ferror(f, GOT_ERR_IO);
6708 done:
6709 if (commit)
6710 got_object_commit_close(commit);
6711 free(id_str);
6712 free(logmsg);
6713 return err;
6716 static const struct got_error *
6717 histedit_write_commit_list(struct got_object_id_queue *commits,
6718 FILE *f, int edit_logmsg_only, struct got_repository *repo)
6720 const struct got_error *err = NULL;
6721 struct got_object_qid *qid;
6723 if (SIMPLEQ_EMPTY(commits))
6724 return got_error(GOT_ERR_EMPTY_HISTEDIT);
6726 SIMPLEQ_FOREACH(qid, commits, entry) {
6727 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
6728 f, repo);
6729 if (err)
6730 break;
6731 if (edit_logmsg_only) {
6732 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
6733 if (n < 0) {
6734 err = got_ferror(f, GOT_ERR_IO);
6735 break;
6740 return err;
6743 static const struct got_error *
6744 write_cmd_list(FILE *f, const char *branch_name,
6745 struct got_object_id_queue *commits)
6747 const struct got_error *err = NULL;
6748 int n, i;
6749 char *id_str;
6750 struct got_object_qid *qid;
6752 qid = SIMPLEQ_FIRST(commits);
6753 err = got_object_id_str(&id_str, qid->id);
6754 if (err)
6755 return err;
6757 n = fprintf(f,
6758 "# Editing the history of branch '%s' starting at\n"
6759 "# commit %s\n"
6760 "# Commits will be processed in order from top to "
6761 "bottom of this file.\n", branch_name, id_str);
6762 if (n < 0) {
6763 err = got_ferror(f, GOT_ERR_IO);
6764 goto done;
6767 n = fprintf(f, "# Available histedit commands:\n");
6768 if (n < 0) {
6769 err = got_ferror(f, GOT_ERR_IO);
6770 goto done;
6773 for (i = 0; i < nitems(got_histedit_cmds); i++) {
6774 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
6775 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
6776 cmd->desc);
6777 if (n < 0) {
6778 err = got_ferror(f, GOT_ERR_IO);
6779 break;
6782 done:
6783 free(id_str);
6784 return err;
6787 static const struct got_error *
6788 histedit_syntax_error(int lineno)
6790 static char msg[42];
6791 int ret;
6793 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
6794 lineno);
6795 if (ret == -1 || ret >= sizeof(msg))
6796 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
6798 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
6801 static const struct got_error *
6802 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
6803 char *logmsg, struct got_repository *repo)
6805 const struct got_error *err;
6806 struct got_commit_object *folded_commit = NULL;
6807 char *id_str, *folded_logmsg = NULL;
6809 err = got_object_id_str(&id_str, hle->commit_id);
6810 if (err)
6811 return err;
6813 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
6814 if (err)
6815 goto done;
6817 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
6818 if (err)
6819 goto done;
6820 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
6821 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
6822 folded_logmsg) == -1) {
6823 err = got_error_from_errno("asprintf");
6825 done:
6826 if (folded_commit)
6827 got_object_commit_close(folded_commit);
6828 free(id_str);
6829 free(folded_logmsg);
6830 return err;
6833 static struct got_histedit_list_entry *
6834 get_folded_commits(struct got_histedit_list_entry *hle)
6836 struct got_histedit_list_entry *prev, *folded = NULL;
6838 prev = TAILQ_PREV(hle, got_histedit_list, entry);
6839 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
6840 prev->cmd->code == GOT_HISTEDIT_DROP)) {
6841 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
6842 folded = prev;
6843 prev = TAILQ_PREV(prev, got_histedit_list, entry);
6846 return folded;
6849 static const struct got_error *
6850 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
6851 struct got_repository *repo)
6853 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
6854 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
6855 const struct got_error *err = NULL;
6856 struct got_commit_object *commit = NULL;
6857 int fd;
6858 struct got_histedit_list_entry *folded = NULL;
6860 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
6861 if (err)
6862 return err;
6864 folded = get_folded_commits(hle);
6865 if (folded) {
6866 while (folded != hle) {
6867 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
6868 folded = TAILQ_NEXT(folded, entry);
6869 continue;
6871 err = append_folded_commit_msg(&new_msg, folded,
6872 logmsg, repo);
6873 if (err)
6874 goto done;
6875 free(logmsg);
6876 logmsg = new_msg;
6877 folded = TAILQ_NEXT(folded, entry);
6881 err = got_object_id_str(&id_str, hle->commit_id);
6882 if (err)
6883 goto done;
6884 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
6885 if (err)
6886 goto done;
6887 if (asprintf(&new_msg,
6888 "%s\n# original log message of commit %s: %s",
6889 logmsg ? logmsg : "", id_str, orig_logmsg) == -1) {
6890 err = got_error_from_errno("asprintf");
6891 goto done;
6893 free(logmsg);
6894 logmsg = new_msg;
6896 err = got_object_id_str(&id_str, hle->commit_id);
6897 if (err)
6898 goto done;
6900 err = got_opentemp_named_fd(&logmsg_path, &fd,
6901 GOT_TMPDIR_STR "/got-logmsg");
6902 if (err)
6903 goto done;
6905 dprintf(fd, logmsg);
6906 close(fd);
6908 err = get_editor(&editor);
6909 if (err)
6910 goto done;
6912 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
6913 if (err) {
6914 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
6915 goto done;
6916 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
6918 done:
6919 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
6920 err = got_error_from_errno2("unlink", logmsg_path);
6921 free(logmsg_path);
6922 free(logmsg);
6923 free(orig_logmsg);
6924 free(editor);
6925 if (commit)
6926 got_object_commit_close(commit);
6927 return err;
6930 static const struct got_error *
6931 histedit_parse_list(struct got_histedit_list *histedit_cmds,
6932 FILE *f, struct got_repository *repo)
6934 const struct got_error *err = NULL;
6935 char *line = NULL, *p, *end;
6936 size_t size;
6937 ssize_t len;
6938 int lineno = 0, i;
6939 const struct got_histedit_cmd *cmd;
6940 struct got_object_id *commit_id = NULL;
6941 struct got_histedit_list_entry *hle = NULL;
6943 for (;;) {
6944 len = getline(&line, &size, f);
6945 if (len == -1) {
6946 const struct got_error *getline_err;
6947 if (feof(f))
6948 break;
6949 getline_err = got_error_from_errno("getline");
6950 err = got_ferror(f, getline_err->code);
6951 break;
6953 lineno++;
6954 p = line;
6955 while (isspace((unsigned char)p[0]))
6956 p++;
6957 if (p[0] == '#' || p[0] == '\0') {
6958 free(line);
6959 line = NULL;
6960 continue;
6962 cmd = NULL;
6963 for (i = 0; i < nitems(got_histedit_cmds); i++) {
6964 cmd = &got_histedit_cmds[i];
6965 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
6966 isspace((unsigned char)p[strlen(cmd->name)])) {
6967 p += strlen(cmd->name);
6968 break;
6970 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
6971 p++;
6972 break;
6975 if (i == nitems(got_histedit_cmds)) {
6976 err = histedit_syntax_error(lineno);
6977 break;
6979 while (isspace((unsigned char)p[0]))
6980 p++;
6981 if (cmd->code == GOT_HISTEDIT_MESG) {
6982 if (hle == NULL || hle->logmsg != NULL) {
6983 err = got_error(GOT_ERR_HISTEDIT_CMD);
6984 break;
6986 if (p[0] == '\0') {
6987 err = histedit_edit_logmsg(hle, repo);
6988 if (err)
6989 break;
6990 } else {
6991 hle->logmsg = strdup(p);
6992 if (hle->logmsg == NULL) {
6993 err = got_error_from_errno("strdup");
6994 break;
6997 free(line);
6998 line = NULL;
6999 continue;
7000 } else {
7001 end = p;
7002 while (end[0] && !isspace((unsigned char)end[0]))
7003 end++;
7004 *end = '\0';
7006 err = got_object_resolve_id_str(&commit_id, repo, p);
7007 if (err) {
7008 /* override error code */
7009 err = histedit_syntax_error(lineno);
7010 break;
7013 hle = malloc(sizeof(*hle));
7014 if (hle == NULL) {
7015 err = got_error_from_errno("malloc");
7016 break;
7018 hle->cmd = cmd;
7019 hle->commit_id = commit_id;
7020 hle->logmsg = NULL;
7021 commit_id = NULL;
7022 free(line);
7023 line = NULL;
7024 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
7027 free(line);
7028 free(commit_id);
7029 return err;
7032 static const struct got_error *
7033 histedit_check_script(struct got_histedit_list *histedit_cmds,
7034 struct got_object_id_queue *commits, struct got_repository *repo)
7036 const struct got_error *err = NULL;
7037 struct got_object_qid *qid;
7038 struct got_histedit_list_entry *hle;
7039 static char msg[92];
7040 char *id_str;
7042 if (TAILQ_EMPTY(histedit_cmds))
7043 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
7044 "histedit script contains no commands");
7045 if (SIMPLEQ_EMPTY(commits))
7046 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7048 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7049 struct got_histedit_list_entry *hle2;
7050 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
7051 if (hle == hle2)
7052 continue;
7053 if (got_object_id_cmp(hle->commit_id,
7054 hle2->commit_id) != 0)
7055 continue;
7056 err = got_object_id_str(&id_str, hle->commit_id);
7057 if (err)
7058 return err;
7059 snprintf(msg, sizeof(msg), "commit %s is listed "
7060 "more than once in histedit script", id_str);
7061 free(id_str);
7062 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7066 SIMPLEQ_FOREACH(qid, commits, entry) {
7067 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7068 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
7069 break;
7071 if (hle == NULL) {
7072 err = got_object_id_str(&id_str, qid->id);
7073 if (err)
7074 return err;
7075 snprintf(msg, sizeof(msg),
7076 "commit %s missing from histedit script", id_str);
7077 free(id_str);
7078 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7082 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
7083 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
7084 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
7085 "last commit in histedit script cannot be folded");
7087 return NULL;
7090 static const struct got_error *
7091 histedit_run_editor(struct got_histedit_list *histedit_cmds,
7092 const char *path, struct got_object_id_queue *commits,
7093 struct got_repository *repo)
7095 const struct got_error *err = NULL;
7096 char *editor;
7097 FILE *f = NULL;
7099 err = get_editor(&editor);
7100 if (err)
7101 return err;
7103 if (spawn_editor(editor, path) == -1) {
7104 err = got_error_from_errno("failed spawning editor");
7105 goto done;
7108 f = fopen(path, "r");
7109 if (f == NULL) {
7110 err = got_error_from_errno("fopen");
7111 goto done;
7113 err = histedit_parse_list(histedit_cmds, f, repo);
7114 if (err)
7115 goto done;
7117 err = histedit_check_script(histedit_cmds, commits, repo);
7118 done:
7119 if (f && fclose(f) != 0 && err == NULL)
7120 err = got_error_from_errno("fclose");
7121 free(editor);
7122 return err;
7125 static const struct got_error *
7126 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
7127 struct got_object_id_queue *, const char *, const char *,
7128 struct got_repository *);
7130 static const struct got_error *
7131 histedit_edit_script(struct got_histedit_list *histedit_cmds,
7132 struct got_object_id_queue *commits, const char *branch_name,
7133 int edit_logmsg_only, struct got_repository *repo)
7135 const struct got_error *err;
7136 FILE *f = NULL;
7137 char *path = NULL;
7139 err = got_opentemp_named(&path, &f, "got-histedit");
7140 if (err)
7141 return err;
7143 err = write_cmd_list(f, branch_name, commits);
7144 if (err)
7145 goto done;
7147 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
7148 if (err)
7149 goto done;
7151 if (edit_logmsg_only) {
7152 rewind(f);
7153 err = histedit_parse_list(histedit_cmds, f, repo);
7154 } else {
7155 if (fclose(f) != 0) {
7156 err = got_error_from_errno("fclose");
7157 goto done;
7159 f = NULL;
7160 err = histedit_run_editor(histedit_cmds, path, commits, repo);
7161 if (err) {
7162 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7163 err->code != GOT_ERR_HISTEDIT_CMD)
7164 goto done;
7165 err = histedit_edit_list_retry(histedit_cmds, err,
7166 commits, path, branch_name, repo);
7169 done:
7170 if (f && fclose(f) != 0 && err == NULL)
7171 err = got_error_from_errno("fclose");
7172 if (path && unlink(path) != 0 && err == NULL)
7173 err = got_error_from_errno2("unlink", path);
7174 free(path);
7175 return err;
7178 static const struct got_error *
7179 histedit_save_list(struct got_histedit_list *histedit_cmds,
7180 struct got_worktree *worktree, struct got_repository *repo)
7182 const struct got_error *err = NULL;
7183 char *path = NULL;
7184 FILE *f = NULL;
7185 struct got_histedit_list_entry *hle;
7186 struct got_commit_object *commit = NULL;
7188 err = got_worktree_get_histedit_script_path(&path, worktree);
7189 if (err)
7190 return err;
7192 f = fopen(path, "w");
7193 if (f == NULL) {
7194 err = got_error_from_errno2("fopen", path);
7195 goto done;
7197 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7198 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
7199 repo);
7200 if (err)
7201 break;
7203 if (hle->logmsg) {
7204 int n = fprintf(f, "%c %s\n",
7205 GOT_HISTEDIT_MESG, hle->logmsg);
7206 if (n < 0) {
7207 err = got_ferror(f, GOT_ERR_IO);
7208 break;
7212 done:
7213 if (f && fclose(f) != 0 && err == NULL)
7214 err = got_error_from_errno("fclose");
7215 free(path);
7216 if (commit)
7217 got_object_commit_close(commit);
7218 return err;
7221 void
7222 histedit_free_list(struct got_histedit_list *histedit_cmds)
7224 struct got_histedit_list_entry *hle;
7226 while ((hle = TAILQ_FIRST(histedit_cmds))) {
7227 TAILQ_REMOVE(histedit_cmds, hle, entry);
7228 free(hle);
7232 static const struct got_error *
7233 histedit_load_list(struct got_histedit_list *histedit_cmds,
7234 const char *path, struct got_repository *repo)
7236 const struct got_error *err = NULL;
7237 FILE *f = NULL;
7239 f = fopen(path, "r");
7240 if (f == NULL) {
7241 err = got_error_from_errno2("fopen", path);
7242 goto done;
7245 err = histedit_parse_list(histedit_cmds, f, repo);
7246 done:
7247 if (f && fclose(f) != 0 && err == NULL)
7248 err = got_error_from_errno("fclose");
7249 return err;
7252 static const struct got_error *
7253 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
7254 const struct got_error *edit_err, struct got_object_id_queue *commits,
7255 const char *path, const char *branch_name, struct got_repository *repo)
7257 const struct got_error *err = NULL, *prev_err = edit_err;
7258 int resp = ' ';
7260 while (resp != 'c' && resp != 'r' && resp != 'a') {
7261 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
7262 "or (a)bort: ", getprogname(), prev_err->msg);
7263 resp = getchar();
7264 if (resp == '\n')
7265 resp = getchar();
7266 if (resp == 'c') {
7267 histedit_free_list(histedit_cmds);
7268 err = histedit_run_editor(histedit_cmds, path, commits,
7269 repo);
7270 if (err) {
7271 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7272 err->code != GOT_ERR_HISTEDIT_CMD)
7273 break;
7274 prev_err = err;
7275 resp = ' ';
7276 continue;
7278 break;
7279 } else if (resp == 'r') {
7280 histedit_free_list(histedit_cmds);
7281 err = histedit_edit_script(histedit_cmds,
7282 commits, branch_name, 0, repo);
7283 if (err) {
7284 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7285 err->code != GOT_ERR_HISTEDIT_CMD)
7286 break;
7287 prev_err = err;
7288 resp = ' ';
7289 continue;
7291 break;
7292 } else if (resp == 'a') {
7293 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
7294 break;
7295 } else
7296 printf("invalid response '%c'\n", resp);
7299 return err;
7302 static const struct got_error *
7303 histedit_complete(struct got_worktree *worktree,
7304 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
7305 struct got_reference *branch, struct got_repository *repo)
7307 printf("Switching work tree to %s\n",
7308 got_ref_get_symref_target(branch));
7309 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
7310 branch, repo);
7313 static const struct got_error *
7314 show_histedit_progress(struct got_commit_object *commit,
7315 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
7317 const struct got_error *err;
7318 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7320 err = got_object_id_str(&old_id_str, hle->commit_id);
7321 if (err)
7322 goto done;
7324 if (new_id) {
7325 err = got_object_id_str(&new_id_str, new_id);
7326 if (err)
7327 goto done;
7330 old_id_str[12] = '\0';
7331 if (new_id_str)
7332 new_id_str[12] = '\0';
7334 if (hle->logmsg) {
7335 logmsg = strdup(hle->logmsg);
7336 if (logmsg == NULL) {
7337 err = got_error_from_errno("strdup");
7338 goto done;
7340 trim_logmsg(logmsg, 42);
7341 } else {
7342 err = get_short_logmsg(&logmsg, 42, commit);
7343 if (err)
7344 goto done;
7347 switch (hle->cmd->code) {
7348 case GOT_HISTEDIT_PICK:
7349 case GOT_HISTEDIT_EDIT:
7350 printf("%s -> %s: %s\n", old_id_str,
7351 new_id_str ? new_id_str : "no-op change", logmsg);
7352 break;
7353 case GOT_HISTEDIT_DROP:
7354 case GOT_HISTEDIT_FOLD:
7355 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
7356 logmsg);
7357 break;
7358 default:
7359 break;
7361 done:
7362 free(old_id_str);
7363 free(new_id_str);
7364 return err;
7367 static const struct got_error *
7368 histedit_commit(struct got_pathlist_head *merged_paths,
7369 struct got_worktree *worktree, struct got_fileindex *fileindex,
7370 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
7371 struct got_repository *repo)
7373 const struct got_error *err;
7374 struct got_commit_object *commit;
7375 struct got_object_id *new_commit_id;
7377 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
7378 && hle->logmsg == NULL) {
7379 err = histedit_edit_logmsg(hle, repo);
7380 if (err)
7381 return err;
7384 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7385 if (err)
7386 return err;
7388 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
7389 worktree, fileindex, tmp_branch, commit, hle->commit_id,
7390 hle->logmsg, repo);
7391 if (err) {
7392 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
7393 goto done;
7394 err = show_histedit_progress(commit, hle, NULL);
7395 } else {
7396 err = show_histedit_progress(commit, hle, new_commit_id);
7397 free(new_commit_id);
7399 done:
7400 got_object_commit_close(commit);
7401 return err;
7404 static const struct got_error *
7405 histedit_skip_commit(struct got_histedit_list_entry *hle,
7406 struct got_worktree *worktree, struct got_repository *repo)
7408 const struct got_error *error;
7409 struct got_commit_object *commit;
7411 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
7412 repo);
7413 if (error)
7414 return error;
7416 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
7417 if (error)
7418 return error;
7420 error = show_histedit_progress(commit, hle, NULL);
7421 got_object_commit_close(commit);
7422 return error;
7425 static const struct got_error *
7426 check_local_changes(void *arg, unsigned char status,
7427 unsigned char staged_status, const char *path,
7428 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
7429 struct got_object_id *commit_id, int dirfd, const char *de_name)
7431 int *have_local_changes = arg;
7433 switch (status) {
7434 case GOT_STATUS_ADD:
7435 case GOT_STATUS_DELETE:
7436 case GOT_STATUS_MODIFY:
7437 case GOT_STATUS_CONFLICT:
7438 *have_local_changes = 1;
7439 return got_error(GOT_ERR_CANCELLED);
7440 default:
7441 break;
7444 switch (staged_status) {
7445 case GOT_STATUS_ADD:
7446 case GOT_STATUS_DELETE:
7447 case GOT_STATUS_MODIFY:
7448 *have_local_changes = 1;
7449 return got_error(GOT_ERR_CANCELLED);
7450 default:
7451 break;
7454 return NULL;
7457 static const struct got_error *
7458 cmd_histedit(int argc, char *argv[])
7460 const struct got_error *error = NULL;
7461 struct got_worktree *worktree = NULL;
7462 struct got_fileindex *fileindex = NULL;
7463 struct got_repository *repo = NULL;
7464 char *cwd = NULL;
7465 struct got_reference *branch = NULL;
7466 struct got_reference *tmp_branch = NULL;
7467 struct got_object_id *resume_commit_id = NULL;
7468 struct got_object_id *base_commit_id = NULL;
7469 struct got_object_id *head_commit_id = NULL;
7470 struct got_commit_object *commit = NULL;
7471 int ch, rebase_in_progress = 0, did_something;
7472 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
7473 int edit_logmsg_only = 0;
7474 const char *edit_script_path = NULL;
7475 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7476 struct got_object_id_queue commits;
7477 struct got_pathlist_head merged_paths;
7478 const struct got_object_id_queue *parent_ids;
7479 struct got_object_qid *pid;
7480 struct got_histedit_list histedit_cmds;
7481 struct got_histedit_list_entry *hle;
7483 SIMPLEQ_INIT(&commits);
7484 TAILQ_INIT(&histedit_cmds);
7485 TAILQ_INIT(&merged_paths);
7487 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
7488 switch (ch) {
7489 case 'a':
7490 abort_edit = 1;
7491 break;
7492 case 'c':
7493 continue_edit = 1;
7494 break;
7495 case 'F':
7496 edit_script_path = optarg;
7497 break;
7498 case 'm':
7499 edit_logmsg_only = 1;
7500 break;
7501 default:
7502 usage_histedit();
7503 /* NOTREACHED */
7507 argc -= optind;
7508 argv += optind;
7510 #ifndef PROFILE
7511 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7512 "unveil", NULL) == -1)
7513 err(1, "pledge");
7514 #endif
7515 if (abort_edit && continue_edit)
7516 errx(1, "histedit's -a and -c options are mutually exclusive");
7517 if (edit_script_path && edit_logmsg_only)
7518 errx(1, "histedit's -F and -m options are mutually exclusive");
7519 if (abort_edit && edit_logmsg_only)
7520 errx(1, "histedit's -a and -m options are mutually exclusive");
7521 if (continue_edit && edit_logmsg_only)
7522 errx(1, "histedit's -c and -m options are mutually exclusive");
7523 if (argc != 0)
7524 usage_histedit();
7527 * This command cannot apply unveil(2) in all cases because the
7528 * user may choose to run an editor to edit the histedit script
7529 * and to edit individual commit log messages.
7530 * unveil(2) traverses exec(2); if an editor is used we have to
7531 * apply unveil after edit script and log messages have been written.
7532 * XXX TODO: Make use of unveil(2) where possible.
7535 cwd = getcwd(NULL, 0);
7536 if (cwd == NULL) {
7537 error = got_error_from_errno("getcwd");
7538 goto done;
7540 error = got_worktree_open(&worktree, cwd);
7541 if (error)
7542 goto done;
7544 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7545 NULL);
7546 if (error != NULL)
7547 goto done;
7549 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7550 if (error)
7551 goto done;
7552 if (rebase_in_progress) {
7553 error = got_error(GOT_ERR_REBASING);
7554 goto done;
7557 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
7558 if (error)
7559 goto done;
7561 if (edit_in_progress && edit_logmsg_only) {
7562 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
7563 "histedit operation is in progress in this "
7564 "work tree and must be continued or aborted "
7565 "before the -m option can be used");
7566 goto done;
7569 if (edit_in_progress && abort_edit) {
7570 error = got_worktree_histedit_continue(&resume_commit_id,
7571 &tmp_branch, &branch, &base_commit_id, &fileindex,
7572 worktree, repo);
7573 if (error)
7574 goto done;
7575 printf("Switching work tree to %s\n",
7576 got_ref_get_symref_target(branch));
7577 error = got_worktree_histedit_abort(worktree, fileindex, repo,
7578 branch, base_commit_id, update_progress, &did_something);
7579 if (error)
7580 goto done;
7581 printf("Histedit of %s aborted\n",
7582 got_ref_get_symref_target(branch));
7583 goto done; /* nothing else to do */
7584 } else if (abort_edit) {
7585 error = got_error(GOT_ERR_NOT_HISTEDIT);
7586 goto done;
7589 if (continue_edit) {
7590 char *path;
7592 if (!edit_in_progress) {
7593 error = got_error(GOT_ERR_NOT_HISTEDIT);
7594 goto done;
7597 error = got_worktree_get_histedit_script_path(&path, worktree);
7598 if (error)
7599 goto done;
7601 error = histedit_load_list(&histedit_cmds, path, repo);
7602 free(path);
7603 if (error)
7604 goto done;
7606 error = got_worktree_histedit_continue(&resume_commit_id,
7607 &tmp_branch, &branch, &base_commit_id, &fileindex,
7608 worktree, repo);
7609 if (error)
7610 goto done;
7612 error = got_ref_resolve(&head_commit_id, repo, branch);
7613 if (error)
7614 goto done;
7616 error = got_object_open_as_commit(&commit, repo,
7617 head_commit_id);
7618 if (error)
7619 goto done;
7620 parent_ids = got_object_commit_get_parent_ids(commit);
7621 pid = SIMPLEQ_FIRST(parent_ids);
7622 if (pid == NULL) {
7623 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
7624 goto done;
7626 error = collect_commits(&commits, head_commit_id, pid->id,
7627 base_commit_id, got_worktree_get_path_prefix(worktree),
7628 GOT_ERR_HISTEDIT_PATH, repo);
7629 got_object_commit_close(commit);
7630 commit = NULL;
7631 if (error)
7632 goto done;
7633 } else {
7634 if (edit_in_progress) {
7635 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7636 goto done;
7639 error = got_ref_open(&branch, repo,
7640 got_worktree_get_head_ref_name(worktree), 0);
7641 if (error != NULL)
7642 goto done;
7644 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
7645 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
7646 "will not edit commit history of a branch outside "
7647 "the \"refs/heads/\" reference namespace");
7648 goto done;
7651 error = got_ref_resolve(&head_commit_id, repo, branch);
7652 got_ref_close(branch);
7653 branch = NULL;
7654 if (error)
7655 goto done;
7657 error = got_object_open_as_commit(&commit, repo,
7658 head_commit_id);
7659 if (error)
7660 goto done;
7661 parent_ids = got_object_commit_get_parent_ids(commit);
7662 pid = SIMPLEQ_FIRST(parent_ids);
7663 if (pid == NULL) {
7664 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
7665 goto done;
7667 error = collect_commits(&commits, head_commit_id, pid->id,
7668 got_worktree_get_base_commit_id(worktree),
7669 got_worktree_get_path_prefix(worktree),
7670 GOT_ERR_HISTEDIT_PATH, repo);
7671 got_object_commit_close(commit);
7672 commit = NULL;
7673 if (error)
7674 goto done;
7676 if (SIMPLEQ_EMPTY(&commits)) {
7677 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
7678 goto done;
7681 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
7682 &base_commit_id, &fileindex, worktree, repo);
7683 if (error)
7684 goto done;
7686 if (edit_script_path) {
7687 error = histedit_load_list(&histedit_cmds,
7688 edit_script_path, repo);
7689 if (error) {
7690 got_worktree_histedit_abort(worktree, fileindex,
7691 repo, branch, base_commit_id,
7692 update_progress, &did_something);
7693 goto done;
7695 } else {
7696 const char *branch_name;
7697 branch_name = got_ref_get_symref_target(branch);
7698 if (strncmp(branch_name, "refs/heads/", 11) == 0)
7699 branch_name += 11;
7700 error = histedit_edit_script(&histedit_cmds, &commits,
7701 branch_name, edit_logmsg_only, repo);
7702 if (error) {
7703 got_worktree_histedit_abort(worktree, fileindex,
7704 repo, branch, base_commit_id,
7705 update_progress, &did_something);
7706 goto done;
7711 error = histedit_save_list(&histedit_cmds, worktree,
7712 repo);
7713 if (error) {
7714 got_worktree_histedit_abort(worktree, fileindex,
7715 repo, branch, base_commit_id,
7716 update_progress, &did_something);
7717 goto done;
7722 error = histedit_check_script(&histedit_cmds, &commits, repo);
7723 if (error)
7724 goto done;
7726 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
7727 if (resume_commit_id) {
7728 if (got_object_id_cmp(hle->commit_id,
7729 resume_commit_id) != 0)
7730 continue;
7732 resume_commit_id = NULL;
7733 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
7734 hle->cmd->code == GOT_HISTEDIT_FOLD) {
7735 error = histedit_skip_commit(hle, worktree,
7736 repo);
7737 if (error)
7738 goto done;
7739 } else {
7740 struct got_pathlist_head paths;
7741 int have_changes = 0;
7743 TAILQ_INIT(&paths);
7744 error = got_pathlist_append(&paths, "", NULL);
7745 if (error)
7746 goto done;
7747 error = got_worktree_status(worktree, &paths,
7748 repo, check_local_changes, &have_changes,
7749 check_cancelled, NULL);
7750 got_pathlist_free(&paths);
7751 if (error) {
7752 if (error->code != GOT_ERR_CANCELLED)
7753 goto done;
7754 if (sigint_received || sigpipe_received)
7755 goto done;
7757 if (have_changes) {
7758 error = histedit_commit(NULL, worktree,
7759 fileindex, tmp_branch, hle, repo);
7760 if (error)
7761 goto done;
7762 } else {
7763 error = got_object_open_as_commit(
7764 &commit, repo, hle->commit_id);
7765 if (error)
7766 goto done;
7767 error = show_histedit_progress(commit,
7768 hle, NULL);
7769 got_object_commit_close(commit);
7770 commit = NULL;
7771 if (error)
7772 goto done;
7775 continue;
7778 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
7779 error = histedit_skip_commit(hle, worktree, repo);
7780 if (error)
7781 goto done;
7782 continue;
7785 error = got_object_open_as_commit(&commit, repo,
7786 hle->commit_id);
7787 if (error)
7788 goto done;
7789 parent_ids = got_object_commit_get_parent_ids(commit);
7790 pid = SIMPLEQ_FIRST(parent_ids);
7792 error = got_worktree_histedit_merge_files(&merged_paths,
7793 worktree, fileindex, pid->id, hle->commit_id, repo,
7794 rebase_progress, &rebase_status, check_cancelled, NULL);
7795 if (error)
7796 goto done;
7797 got_object_commit_close(commit);
7798 commit = NULL;
7800 if (rebase_status == GOT_STATUS_CONFLICT) {
7801 error = show_rebase_merge_conflict(hle->commit_id,
7802 repo);
7803 if (error)
7804 goto done;
7805 got_worktree_rebase_pathlist_free(&merged_paths);
7806 break;
7809 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
7810 char *id_str;
7811 error = got_object_id_str(&id_str, hle->commit_id);
7812 if (error)
7813 goto done;
7814 printf("Stopping histedit for amending commit %s\n",
7815 id_str);
7816 free(id_str);
7817 got_worktree_rebase_pathlist_free(&merged_paths);
7818 error = got_worktree_histedit_postpone(worktree,
7819 fileindex);
7820 goto done;
7823 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
7824 error = histedit_skip_commit(hle, worktree, repo);
7825 if (error)
7826 goto done;
7827 continue;
7830 error = histedit_commit(&merged_paths, worktree, fileindex,
7831 tmp_branch, hle, repo);
7832 got_worktree_rebase_pathlist_free(&merged_paths);
7833 if (error)
7834 goto done;
7837 if (rebase_status == GOT_STATUS_CONFLICT) {
7838 error = got_worktree_histedit_postpone(worktree, fileindex);
7839 if (error)
7840 goto done;
7841 error = got_error_msg(GOT_ERR_CONFLICTS,
7842 "conflicts must be resolved before histedit can continue");
7843 } else
7844 error = histedit_complete(worktree, fileindex, tmp_branch,
7845 branch, repo);
7846 done:
7847 got_object_id_queue_free(&commits);
7848 histedit_free_list(&histedit_cmds);
7849 free(head_commit_id);
7850 free(base_commit_id);
7851 free(resume_commit_id);
7852 if (commit)
7853 got_object_commit_close(commit);
7854 if (branch)
7855 got_ref_close(branch);
7856 if (tmp_branch)
7857 got_ref_close(tmp_branch);
7858 if (worktree)
7859 got_worktree_close(worktree);
7860 if (repo)
7861 got_repo_close(repo);
7862 return error;
7865 __dead static void
7866 usage_integrate(void)
7868 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
7869 exit(1);
7872 static const struct got_error *
7873 cmd_integrate(int argc, char *argv[])
7875 const struct got_error *error = NULL;
7876 struct got_repository *repo = NULL;
7877 struct got_worktree *worktree = NULL;
7878 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
7879 const char *branch_arg = NULL;
7880 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
7881 struct got_fileindex *fileindex = NULL;
7882 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
7883 int ch, did_something = 0;
7885 while ((ch = getopt(argc, argv, "")) != -1) {
7886 switch (ch) {
7887 default:
7888 usage_integrate();
7889 /* NOTREACHED */
7893 argc -= optind;
7894 argv += optind;
7896 if (argc != 1)
7897 usage_integrate();
7898 branch_arg = argv[0];
7900 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7901 "unveil", NULL) == -1)
7902 err(1, "pledge");
7904 cwd = getcwd(NULL, 0);
7905 if (cwd == NULL) {
7906 error = got_error_from_errno("getcwd");
7907 goto done;
7910 error = got_worktree_open(&worktree, cwd);
7911 if (error)
7912 goto done;
7914 error = check_rebase_or_histedit_in_progress(worktree);
7915 if (error)
7916 goto done;
7918 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7919 NULL);
7920 if (error != NULL)
7921 goto done;
7923 error = apply_unveil(got_repo_get_path(repo), 0,
7924 got_worktree_get_root_path(worktree));
7925 if (error)
7926 goto done;
7928 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
7929 error = got_error_from_errno("asprintf");
7930 goto done;
7933 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
7934 &base_branch_ref, worktree, refname, repo);
7935 if (error)
7936 goto done;
7938 refname = strdup(got_ref_get_name(branch_ref));
7939 if (refname == NULL) {
7940 error = got_error_from_errno("strdup");
7941 got_worktree_integrate_abort(worktree, fileindex, repo,
7942 branch_ref, base_branch_ref);
7943 goto done;
7945 base_refname = strdup(got_ref_get_name(base_branch_ref));
7946 if (base_refname == NULL) {
7947 error = got_error_from_errno("strdup");
7948 got_worktree_integrate_abort(worktree, fileindex, repo,
7949 branch_ref, base_branch_ref);
7950 goto done;
7953 error = got_ref_resolve(&commit_id, repo, branch_ref);
7954 if (error)
7955 goto done;
7957 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
7958 if (error)
7959 goto done;
7961 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
7962 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7963 "specified branch has already been integrated");
7964 got_worktree_integrate_abort(worktree, fileindex, repo,
7965 branch_ref, base_branch_ref);
7966 goto done;
7969 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
7970 if (error) {
7971 if (error->code == GOT_ERR_ANCESTRY)
7972 error = got_error(GOT_ERR_REBASE_REQUIRED);
7973 got_worktree_integrate_abort(worktree, fileindex, repo,
7974 branch_ref, base_branch_ref);
7975 goto done;
7978 error = got_worktree_integrate_continue(worktree, fileindex, repo,
7979 branch_ref, base_branch_ref, update_progress, &did_something,
7980 check_cancelled, NULL);
7981 if (error)
7982 goto done;
7984 printf("Integrated %s into %s\n", refname, base_refname);
7985 done:
7986 if (repo)
7987 got_repo_close(repo);
7988 if (worktree)
7989 got_worktree_close(worktree);
7990 free(cwd);
7991 free(base_commit_id);
7992 free(commit_id);
7993 free(refname);
7994 free(base_refname);
7995 return error;
7998 __dead static void
7999 usage_stage(void)
8001 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
8002 "[file-path ...]\n",
8003 getprogname());
8004 exit(1);
8007 static const struct got_error *
8008 print_stage(void *arg, unsigned char status, unsigned char staged_status,
8009 const char *path, struct got_object_id *blob_id,
8010 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
8011 int dirfd, const char *de_name)
8013 const struct got_error *err = NULL;
8014 char *id_str = NULL;
8016 if (staged_status != GOT_STATUS_ADD &&
8017 staged_status != GOT_STATUS_MODIFY &&
8018 staged_status != GOT_STATUS_DELETE)
8019 return NULL;
8021 if (staged_status == GOT_STATUS_ADD ||
8022 staged_status == GOT_STATUS_MODIFY)
8023 err = got_object_id_str(&id_str, staged_blob_id);
8024 else
8025 err = got_object_id_str(&id_str, blob_id);
8026 if (err)
8027 return err;
8029 printf("%s %c %s\n", id_str, staged_status, path);
8030 free(id_str);
8031 return NULL;
8034 static const struct got_error *
8035 cmd_stage(int argc, char *argv[])
8037 const struct got_error *error = NULL;
8038 struct got_repository *repo = NULL;
8039 struct got_worktree *worktree = NULL;
8040 char *cwd = NULL;
8041 struct got_pathlist_head paths;
8042 struct got_pathlist_entry *pe;
8043 int ch, list_stage = 0, pflag = 0;
8044 FILE *patch_script_file = NULL;
8045 const char *patch_script_path = NULL;
8046 struct choose_patch_arg cpa;
8048 TAILQ_INIT(&paths);
8050 while ((ch = getopt(argc, argv, "lpF:")) != -1) {
8051 switch (ch) {
8052 case 'l':
8053 list_stage = 1;
8054 break;
8055 case 'p':
8056 pflag = 1;
8057 break;
8058 case 'F':
8059 patch_script_path = optarg;
8060 break;
8061 default:
8062 usage_stage();
8063 /* NOTREACHED */
8067 argc -= optind;
8068 argv += optind;
8070 #ifndef PROFILE
8071 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8072 "unveil", NULL) == -1)
8073 err(1, "pledge");
8074 #endif
8075 if (list_stage && (pflag || patch_script_path))
8076 errx(1, "-l option cannot be used with other options");
8077 if (patch_script_path && !pflag)
8078 errx(1, "-F option can only be used together with -p option");
8080 cwd = getcwd(NULL, 0);
8081 if (cwd == NULL) {
8082 error = got_error_from_errno("getcwd");
8083 goto done;
8086 error = got_worktree_open(&worktree, cwd);
8087 if (error)
8088 goto done;
8090 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8091 NULL);
8092 if (error != NULL)
8093 goto done;
8095 if (patch_script_path) {
8096 patch_script_file = fopen(patch_script_path, "r");
8097 if (patch_script_file == NULL) {
8098 error = got_error_from_errno2("fopen",
8099 patch_script_path);
8100 goto done;
8103 error = apply_unveil(got_repo_get_path(repo), 0,
8104 got_worktree_get_root_path(worktree));
8105 if (error)
8106 goto done;
8108 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8109 if (error)
8110 goto done;
8112 if (list_stage)
8113 error = got_worktree_status(worktree, &paths, repo,
8114 print_stage, NULL, check_cancelled, NULL);
8115 else {
8116 cpa.patch_script_file = patch_script_file;
8117 cpa.action = "stage";
8118 error = got_worktree_stage(worktree, &paths,
8119 pflag ? NULL : print_status, NULL,
8120 pflag ? choose_patch : NULL, &cpa, repo);
8122 done:
8123 if (patch_script_file && fclose(patch_script_file) == EOF &&
8124 error == NULL)
8125 error = got_error_from_errno2("fclose", patch_script_path);
8126 if (repo)
8127 got_repo_close(repo);
8128 if (worktree)
8129 got_worktree_close(worktree);
8130 TAILQ_FOREACH(pe, &paths, entry)
8131 free((char *)pe->path);
8132 got_pathlist_free(&paths);
8133 free(cwd);
8134 return error;
8137 __dead static void
8138 usage_unstage(void)
8140 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
8141 "[file-path ...]\n",
8142 getprogname());
8143 exit(1);
8147 static const struct got_error *
8148 cmd_unstage(int argc, char *argv[])
8150 const struct got_error *error = NULL;
8151 struct got_repository *repo = NULL;
8152 struct got_worktree *worktree = NULL;
8153 char *cwd = NULL;
8154 struct got_pathlist_head paths;
8155 struct got_pathlist_entry *pe;
8156 int ch, did_something = 0, pflag = 0;
8157 FILE *patch_script_file = NULL;
8158 const char *patch_script_path = NULL;
8159 struct choose_patch_arg cpa;
8161 TAILQ_INIT(&paths);
8163 while ((ch = getopt(argc, argv, "pF:")) != -1) {
8164 switch (ch) {
8165 case 'p':
8166 pflag = 1;
8167 break;
8168 case 'F':
8169 patch_script_path = optarg;
8170 break;
8171 default:
8172 usage_unstage();
8173 /* NOTREACHED */
8177 argc -= optind;
8178 argv += optind;
8180 #ifndef PROFILE
8181 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8182 "unveil", NULL) == -1)
8183 err(1, "pledge");
8184 #endif
8185 if (patch_script_path && !pflag)
8186 errx(1, "-F option can only be used together with -p option");
8188 cwd = getcwd(NULL, 0);
8189 if (cwd == NULL) {
8190 error = got_error_from_errno("getcwd");
8191 goto done;
8194 error = got_worktree_open(&worktree, cwd);
8195 if (error)
8196 goto done;
8198 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8199 NULL);
8200 if (error != NULL)
8201 goto done;
8203 if (patch_script_path) {
8204 patch_script_file = fopen(patch_script_path, "r");
8205 if (patch_script_file == NULL) {
8206 error = got_error_from_errno2("fopen",
8207 patch_script_path);
8208 goto done;
8212 error = apply_unveil(got_repo_get_path(repo), 0,
8213 got_worktree_get_root_path(worktree));
8214 if (error)
8215 goto done;
8217 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8218 if (error)
8219 goto done;
8221 cpa.patch_script_file = patch_script_file;
8222 cpa.action = "unstage";
8223 error = got_worktree_unstage(worktree, &paths, update_progress,
8224 &did_something, pflag ? choose_patch : NULL, &cpa, repo);
8225 done:
8226 if (patch_script_file && fclose(patch_script_file) == EOF &&
8227 error == NULL)
8228 error = got_error_from_errno2("fclose", patch_script_path);
8229 if (repo)
8230 got_repo_close(repo);
8231 if (worktree)
8232 got_worktree_close(worktree);
8233 TAILQ_FOREACH(pe, &paths, entry)
8234 free((char *)pe->path);
8235 got_pathlist_free(&paths);
8236 free(cwd);
8237 return error;
8240 __dead static void
8241 usage_cat(void)
8243 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
8244 "arg1 [arg2 ...]\n", getprogname());
8245 exit(1);
8248 static const struct got_error *
8249 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8251 const struct got_error *err;
8252 struct got_blob_object *blob;
8254 err = got_object_open_as_blob(&blob, repo, id, 8192);
8255 if (err)
8256 return err;
8258 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
8259 got_object_blob_close(blob);
8260 return err;
8263 static const struct got_error *
8264 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8266 const struct got_error *err;
8267 struct got_tree_object *tree;
8268 int nentries, i;
8270 err = got_object_open_as_tree(&tree, repo, id);
8271 if (err)
8272 return err;
8274 nentries = got_object_tree_get_nentries(tree);
8275 for (i = 0; i < nentries; i++) {
8276 struct got_tree_entry *te;
8277 char *id_str;
8278 if (sigint_received || sigpipe_received)
8279 break;
8280 te = got_object_tree_get_entry(tree, i);
8281 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
8282 if (err)
8283 break;
8284 fprintf(outfile, "%s %.7o %s\n", id_str,
8285 got_tree_entry_get_mode(te),
8286 got_tree_entry_get_name(te));
8287 free(id_str);
8290 got_object_tree_close(tree);
8291 return err;
8294 static const struct got_error *
8295 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8297 const struct got_error *err;
8298 struct got_commit_object *commit;
8299 const struct got_object_id_queue *parent_ids;
8300 struct got_object_qid *pid;
8301 char *id_str = NULL;
8302 const char *logmsg = NULL;
8304 err = got_object_open_as_commit(&commit, repo, id);
8305 if (err)
8306 return err;
8308 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
8309 if (err)
8310 goto done;
8312 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
8313 parent_ids = got_object_commit_get_parent_ids(commit);
8314 fprintf(outfile, "numparents %d\n",
8315 got_object_commit_get_nparents(commit));
8316 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
8317 char *pid_str;
8318 err = got_object_id_str(&pid_str, pid->id);
8319 if (err)
8320 goto done;
8321 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
8322 free(pid_str);
8324 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
8325 got_object_commit_get_author(commit),
8326 got_object_commit_get_author_time(commit));
8328 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
8329 got_object_commit_get_author(commit),
8330 got_object_commit_get_committer_time(commit));
8332 logmsg = got_object_commit_get_logmsg_raw(commit);
8333 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
8334 fprintf(outfile, "%s", logmsg);
8335 done:
8336 free(id_str);
8337 got_object_commit_close(commit);
8338 return err;
8341 static const struct got_error *
8342 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8344 const struct got_error *err;
8345 struct got_tag_object *tag;
8346 char *id_str = NULL;
8347 const char *tagmsg = NULL;
8349 err = got_object_open_as_tag(&tag, repo, id);
8350 if (err)
8351 return err;
8353 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
8354 if (err)
8355 goto done;
8357 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
8359 switch (got_object_tag_get_object_type(tag)) {
8360 case GOT_OBJ_TYPE_BLOB:
8361 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8362 GOT_OBJ_LABEL_BLOB);
8363 break;
8364 case GOT_OBJ_TYPE_TREE:
8365 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8366 GOT_OBJ_LABEL_TREE);
8367 break;
8368 case GOT_OBJ_TYPE_COMMIT:
8369 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8370 GOT_OBJ_LABEL_COMMIT);
8371 break;
8372 case GOT_OBJ_TYPE_TAG:
8373 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8374 GOT_OBJ_LABEL_TAG);
8375 break;
8376 default:
8377 break;
8380 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
8381 got_object_tag_get_name(tag));
8383 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
8384 got_object_tag_get_tagger(tag),
8385 got_object_tag_get_tagger_time(tag));
8387 tagmsg = got_object_tag_get_message(tag);
8388 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
8389 fprintf(outfile, "%s", tagmsg);
8390 done:
8391 free(id_str);
8392 got_object_tag_close(tag);
8393 return err;
8396 static const struct got_error *
8397 cmd_cat(int argc, char *argv[])
8399 const struct got_error *error;
8400 struct got_repository *repo = NULL;
8401 struct got_worktree *worktree = NULL;
8402 char *cwd = NULL, *repo_path = NULL, *label = NULL;
8403 const char *commit_id_str = NULL;
8404 struct got_object_id *id = NULL, *commit_id = NULL;
8405 int ch, obj_type, i, force_path = 0;
8407 #ifndef PROFILE
8408 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8409 NULL) == -1)
8410 err(1, "pledge");
8411 #endif
8413 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
8414 switch (ch) {
8415 case 'c':
8416 commit_id_str = optarg;
8417 break;
8418 case 'r':
8419 repo_path = realpath(optarg, NULL);
8420 if (repo_path == NULL)
8421 return got_error_from_errno2("realpath",
8422 optarg);
8423 got_path_strip_trailing_slashes(repo_path);
8424 break;
8425 case 'P':
8426 force_path = 1;
8427 break;
8428 default:
8429 usage_cat();
8430 /* NOTREACHED */
8434 argc -= optind;
8435 argv += optind;
8437 cwd = getcwd(NULL, 0);
8438 if (cwd == NULL) {
8439 error = got_error_from_errno("getcwd");
8440 goto done;
8442 error = got_worktree_open(&worktree, cwd);
8443 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8444 goto done;
8445 if (worktree) {
8446 if (repo_path == NULL) {
8447 repo_path = strdup(
8448 got_worktree_get_repo_path(worktree));
8449 if (repo_path == NULL) {
8450 error = got_error_from_errno("strdup");
8451 goto done;
8456 if (repo_path == NULL) {
8457 repo_path = getcwd(NULL, 0);
8458 if (repo_path == NULL)
8459 return got_error_from_errno("getcwd");
8462 error = got_repo_open(&repo, repo_path, NULL);
8463 free(repo_path);
8464 if (error != NULL)
8465 goto done;
8467 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
8468 if (error)
8469 goto done;
8471 if (commit_id_str == NULL)
8472 commit_id_str = GOT_REF_HEAD;
8473 error = got_repo_match_object_id(&commit_id, NULL,
8474 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
8475 if (error)
8476 goto done;
8478 for (i = 0; i < argc; i++) {
8479 if (force_path) {
8480 error = got_object_id_by_path(&id, repo, commit_id,
8481 argv[i]);
8482 if (error)
8483 break;
8484 } else {
8485 error = got_repo_match_object_id(&id, &label, argv[i],
8486 GOT_OBJ_TYPE_ANY, 0, repo);
8487 if (error) {
8488 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
8489 error->code != GOT_ERR_NOT_REF)
8490 break;
8491 error = got_object_id_by_path(&id, repo,
8492 commit_id, argv[i]);
8493 if (error)
8494 break;
8498 error = got_object_get_type(&obj_type, repo, id);
8499 if (error)
8500 break;
8502 switch (obj_type) {
8503 case GOT_OBJ_TYPE_BLOB:
8504 error = cat_blob(id, repo, stdout);
8505 break;
8506 case GOT_OBJ_TYPE_TREE:
8507 error = cat_tree(id, repo, stdout);
8508 break;
8509 case GOT_OBJ_TYPE_COMMIT:
8510 error = cat_commit(id, repo, stdout);
8511 break;
8512 case GOT_OBJ_TYPE_TAG:
8513 error = cat_tag(id, repo, stdout);
8514 break;
8515 default:
8516 error = got_error(GOT_ERR_OBJ_TYPE);
8517 break;
8519 if (error)
8520 break;
8521 free(label);
8522 label = NULL;
8523 free(id);
8524 id = NULL;
8526 done:
8527 free(label);
8528 free(id);
8529 free(commit_id);
8530 if (worktree)
8531 got_worktree_close(worktree);
8532 if (repo) {
8533 const struct got_error *repo_error;
8534 repo_error = got_repo_close(repo);
8535 if (error == NULL)
8536 error = repo_error;
8538 return error;