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, int verbosity,
889 struct got_repository *repo)
891 const struct got_error *err;
892 struct got_reference *head_symref;
894 err = got_ref_alloc_symref(&head_symref, GOT_REF_HEAD, target_ref);
895 if (err)
896 return err;
898 err = got_ref_write(head_symref, repo);
899 got_ref_close(head_symref);
900 if (err == NULL && verbosity > 0) {
901 printf("Created reference %s: %s\n", GOT_REF_HEAD,
902 got_ref_get_name(target_ref));
904 return err;
907 static const struct got_error *
908 list_remote_refs(struct got_pathlist_head *symrefs,
909 struct got_pathlist_head *refs)
911 const struct got_error *err;
912 struct got_pathlist_entry *pe;
914 TAILQ_FOREACH(pe, symrefs, entry) {
915 const char *refname = pe->path;
916 const char *targetref = pe->data;
918 printf("%s: %s\n", refname, targetref);
921 TAILQ_FOREACH(pe, refs, entry) {
922 const char *refname = pe->path;
923 struct got_object_id *id = pe->data;
924 char *id_str;
926 err = got_object_id_str(&id_str, id);
927 if (err)
928 return err;
929 printf("%s: %s\n", refname, id_str);
930 free(id_str);
933 return NULL;
936 static const struct got_error *
937 create_ref(const char *refname, struct got_object_id *id,
938 int verbosity, struct got_repository *repo)
940 const struct got_error *err = NULL;
941 struct got_reference *ref;
942 char *id_str;
944 err = got_object_id_str(&id_str, id);
945 if (err)
946 return err;
948 err = got_ref_alloc(&ref, refname, id);
949 if (err)
950 goto done;
952 err = got_ref_write(ref, repo);
953 got_ref_close(ref);
955 if (err == NULL && verbosity >= 0)
956 printf("Created reference %s: %s\n", refname, id_str);
957 done:
958 free(id_str);
959 return err;
962 static const struct got_error *
963 cmd_clone(int argc, char *argv[])
965 const struct got_error *error = NULL;
966 const char *uri, *dirname;
967 char *proto, *host, *port, *repo_name, *server_path;
968 char *default_destdir = NULL, *id_str = NULL;
969 const char *repo_path;
970 struct got_repository *repo = NULL;
971 struct got_pathlist_head refs, symrefs, wanted_branches;
972 struct got_pathlist_entry *pe;
973 struct got_object_id *pack_hash = NULL;
974 int ch, fetchfd = -1, fetchstatus;
975 pid_t fetchpid = -1;
976 struct got_fetch_progress_arg fpa;
977 char *git_url = NULL;
978 char *gitconfig_path = NULL;
979 char *gitconfig = NULL;
980 FILE *gitconfig_file = NULL;
981 ssize_t n;
982 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
983 int list_refs_only = 0;
984 struct got_reference *head_symref = NULL;
986 TAILQ_INIT(&refs);
987 TAILQ_INIT(&symrefs);
988 TAILQ_INIT(&wanted_branches);
990 while ((ch = getopt(argc, argv, "ab:lmvq")) != -1) {
991 switch (ch) {
992 case 'a':
993 fetch_all_branches = 1;
994 break;
995 case 'b':
996 error = got_pathlist_append(&wanted_branches,
997 optarg, NULL);
998 if (error)
999 return error;
1000 break;
1001 case 'l':
1002 list_refs_only = 1;
1003 break;
1004 case 'm':
1005 mirror_references = 1;
1006 break;
1007 case 'v':
1008 if (verbosity < 0)
1009 verbosity = 0;
1010 else if (verbosity < 3)
1011 verbosity++;
1012 break;
1013 case 'q':
1014 verbosity = -1;
1015 break;
1016 default:
1017 usage_clone();
1018 break;
1021 argc -= optind;
1022 argv += optind;
1024 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1025 errx(1, "-a and -b options are mutually exclusive");
1026 if (list_refs_only) {
1027 if (!TAILQ_EMPTY(&wanted_branches))
1028 errx(1, "-l and -b options are mutually exclusive");
1029 if (fetch_all_branches)
1030 errx(1, "-l and -a options are mutually exclusive");
1031 if (mirror_references)
1032 errx(1, "-l and -m options are mutually exclusive");
1033 if (verbosity == -1)
1034 errx(1, "-l and -q options are mutually exclusive");
1037 uri = argv[0];
1039 if (argc == 1)
1040 dirname = NULL;
1041 else if (argc == 2)
1042 dirname = argv[1];
1043 else
1044 usage_clone();
1046 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1047 &repo_name, argv[0]);
1048 if (error)
1049 goto done;
1051 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1052 host, port ? ":" : "", port ? port : "",
1053 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1054 error = got_error_from_errno("asprintf");
1055 goto done;
1058 if (strcmp(proto, "git") == 0) {
1059 #ifndef PROFILE
1060 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1061 "sendfd dns inet unveil", NULL) == -1)
1062 err(1, "pledge");
1063 #endif
1064 } else if (strcmp(proto, "git+ssh") == 0 ||
1065 strcmp(proto, "ssh") == 0) {
1066 #ifndef PROFILE
1067 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1068 "sendfd unveil", NULL) == -1)
1069 err(1, "pledge");
1070 #endif
1071 } else if (strcmp(proto, "http") == 0 ||
1072 strcmp(proto, "git+http") == 0) {
1073 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1074 goto done;
1075 } else {
1076 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1077 goto done;
1079 if (dirname == NULL) {
1080 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1081 error = got_error_from_errno("asprintf");
1082 goto done;
1084 repo_path = default_destdir;
1085 } else
1086 repo_path = dirname;
1088 if (!list_refs_only) {
1089 error = got_path_mkdir(repo_path);
1090 if (error)
1091 goto done;
1093 error = got_repo_init(repo_path);
1094 if (error)
1095 goto done;
1096 error = got_repo_open(&repo, repo_path, NULL);
1097 if (error)
1098 goto done;
1101 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1102 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1103 error = got_error_from_errno2("unveil",
1104 GOT_FETCH_PATH_SSH);
1105 goto done;
1108 error = apply_unveil(repo ? got_repo_get_path(repo) : NULL, 0, NULL);
1109 if (error)
1110 goto done;
1112 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1113 server_path, verbosity);
1114 if (error)
1115 goto done;
1117 if (verbosity >= 0)
1118 printf("Connected to %s%s%s\n", host,
1119 port ? ":" : "", port ? port : "");
1121 fpa.last_scaled_size[0] = '\0';
1122 fpa.last_p_indexed = -1;
1123 fpa.last_p_resolved = -1;
1124 fpa.verbosity = verbosity;
1125 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1126 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1127 fetch_all_branches, &wanted_branches, list_refs_only,
1128 verbosity, fetchfd, repo, fetch_progress, &fpa);
1129 if (error)
1130 goto done;
1132 if (list_refs_only) {
1133 error = list_remote_refs(&symrefs, &refs);
1134 goto done;
1137 error = got_object_id_str(&id_str, pack_hash);
1138 if (error)
1139 goto done;
1140 if (verbosity >= 0)
1141 printf("\nFetched %s.pack\n", id_str);
1142 free(id_str);
1144 /* Set up references provided with the pack file. */
1145 TAILQ_FOREACH(pe, &refs, entry) {
1146 const char *refname = pe->path;
1147 struct got_object_id *id = pe->data;
1148 char *remote_refname;
1150 error = create_ref(refname, id, verbosity - 1, repo);
1151 if (error)
1152 goto done;
1154 if (mirror_references)
1155 continue;
1157 if (strncmp("refs/heads/", refname, 11) != 0)
1158 continue;
1160 if (asprintf(&remote_refname,
1161 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1162 refname + 11) == -1) {
1163 error = got_error_from_errno("asprintf");
1164 goto done;
1166 error = create_ref(remote_refname, id, verbosity - 1, repo);
1167 if (error)
1168 goto done;
1171 /* Set the HEAD reference if the server provided one. */
1172 TAILQ_FOREACH(pe, &symrefs, entry) {
1173 struct got_reference *target_ref;
1174 const char *refname = pe->path;
1175 const char *target = pe->data;
1177 if (strcmp(refname, GOT_REF_HEAD) != 0)
1178 continue;
1180 error = got_ref_open(&target_ref, repo, target, 0);
1181 if (error) {
1182 if (error->code == GOT_ERR_NOT_REF) {
1183 error = NULL;
1184 continue;
1186 goto done;
1189 error = create_head_ref(target_ref, verbosity, repo);
1190 got_ref_close(target_ref);
1191 if (error)
1192 goto done;
1194 if (pe == NULL) {
1196 * We failed to set the HEAD reference. If we asked for
1197 * a set of wanted branches use the first of one of those
1198 * which could be fetched instead.
1200 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1201 const char *target = pe->path;
1202 struct got_reference *target_ref;
1204 error = got_ref_open(&target_ref, repo, target, 0);
1205 if (error) {
1206 if (error->code == GOT_ERR_NOT_REF) {
1207 error = NULL;
1208 continue;
1210 goto done;
1213 error = create_head_ref(target_ref, verbosity, repo);
1214 got_ref_close(target_ref);
1215 if (error)
1216 goto done;
1217 break;
1221 /* Create a config file git-fetch(1) can understand. */
1222 gitconfig_path = got_repo_get_path_gitconfig(repo);
1223 if (gitconfig_path == NULL) {
1224 error = got_error_from_errno("got_repo_get_path_gitconfig");
1225 goto done;
1227 gitconfig_file = fopen(gitconfig_path, "a");
1228 if (gitconfig_file == NULL) {
1229 error = got_error_from_errno2("fopen", gitconfig_path);
1230 goto done;
1232 if (mirror_references) {
1233 if (asprintf(&gitconfig,
1234 "[remote \"%s\"]\n"
1235 "\turl = %s\n"
1236 "\tfetch = +refs/*:refs/*\n"
1237 "\tmirror = true\n",
1238 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1239 error = got_error_from_errno("asprintf");
1240 goto done;
1242 } else if (fetch_all_branches) {
1243 if (asprintf(&gitconfig,
1244 "[remote \"%s\"]\n"
1245 "\turl = %s\n"
1246 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1247 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1248 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1249 error = got_error_from_errno("asprintf");
1250 goto done;
1252 } else {
1253 const char *branchname;
1256 * If the server specified a default branch, use just that one.
1257 * Otherwise fall back to fetching all branches on next fetch.
1259 if (head_symref) {
1260 branchname = got_ref_get_symref_target(head_symref);
1261 if (strncmp(branchname, "refs/heads/", 11) == 0)
1262 branchname += 11;
1263 } else
1264 branchname = "*"; /* fall back to all branches */
1265 if (asprintf(&gitconfig,
1266 "[remote \"%s\"]\n"
1267 "\turl = %s\n"
1268 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1269 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1270 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1271 branchname) == -1) {
1272 error = got_error_from_errno("asprintf");
1273 goto done;
1276 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1277 if (n != strlen(gitconfig)) {
1278 error = got_ferror(gitconfig_file, GOT_ERR_IO);
1279 goto done;
1282 if (verbosity >= 0)
1283 printf("Created %s repository '%s'\n",
1284 mirror_references ? "mirrored" : "cloned", repo_path);
1285 done:
1286 if (fetchpid > 0) {
1287 if (kill(fetchpid, SIGTERM) == -1)
1288 error = got_error_from_errno("kill");
1289 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1290 error = got_error_from_errno("waitpid");
1292 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1293 error = got_error_from_errno("close");
1294 if (gitconfig_file && fclose(gitconfig_file) == EOF && error == NULL)
1295 error = got_error_from_errno("fclose");
1296 if (repo)
1297 got_repo_close(repo);
1298 if (head_symref)
1299 got_ref_close(head_symref);
1300 TAILQ_FOREACH(pe, &refs, entry) {
1301 free((void *)pe->path);
1302 free(pe->data);
1304 got_pathlist_free(&refs);
1305 TAILQ_FOREACH(pe, &symrefs, entry) {
1306 free((void *)pe->path);
1307 free(pe->data);
1309 got_pathlist_free(&symrefs);
1310 got_pathlist_free(&wanted_branches);
1311 free(pack_hash);
1312 free(proto);
1313 free(host);
1314 free(port);
1315 free(server_path);
1316 free(repo_name);
1317 free(default_destdir);
1318 free(gitconfig_path);
1319 free(git_url);
1320 return error;
1323 static const struct got_error *
1324 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1325 int replace_tags, int verbosity, struct got_repository *repo)
1327 const struct got_error *err = NULL;
1328 char *new_id_str = NULL;
1329 struct got_object_id *old_id = NULL;
1331 err = got_object_id_str(&new_id_str, new_id);
1332 if (err)
1333 goto done;
1335 if (!replace_tags &&
1336 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1337 if (verbosity >= 0) {
1338 printf("Rejecting update of existing tag %s: %s\n",
1339 got_ref_get_name(ref), new_id_str);
1341 goto done;
1344 if (got_ref_is_symbolic(ref)) {
1345 struct got_reference *new_ref;
1346 err = got_ref_alloc(&new_ref, got_ref_get_name(ref), new_id);
1347 if (err)
1348 goto done;
1349 err = got_ref_delete(ref, repo);
1350 if (err)
1351 goto done;
1352 if (verbosity >= 0) {
1353 printf("Deleted reference %s: %s\n",
1354 got_ref_get_name(ref),
1355 got_ref_get_symref_target(ref));
1357 err = got_ref_write(new_ref, repo);
1358 if (err)
1359 goto done;
1360 } else {
1361 err = got_ref_resolve(&old_id, repo, ref);
1362 if (err)
1363 goto done;
1364 if (got_object_id_cmp(old_id, new_id) == 0)
1365 goto done;
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 if (verbosity >= 0)
1376 printf("Updated reference %s: %s\n", got_ref_get_name(ref),
1377 new_id_str);
1378 done:
1379 free(old_id);
1380 free(new_id_str);
1381 return err;
1384 __dead static void
1385 usage_fetch(void)
1387 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1388 "[-r repository-path] [-t] [-q] [-v] [remote-repository-name]\n",
1389 getprogname());
1390 exit(1);
1393 static const struct got_error *
1394 delete_missing_refs(struct got_pathlist_head *their_refs,
1395 int verbosity, struct got_repository *repo)
1397 const struct got_error *err = NULL;
1398 struct got_reflist_head my_refs;
1399 struct got_reflist_entry *re;
1400 struct got_pathlist_entry *pe;
1401 struct got_object_id *id;
1402 char *id_str;
1404 SIMPLEQ_INIT(&my_refs);
1406 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1407 if (err)
1408 return err;
1410 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1411 const char *refname = got_ref_get_name(re->ref);
1413 if (strncmp(refname, "refs/heads/", 11) != 0 &&
1414 strncmp(refname, "refs/tags/", 10) != 0)
1415 continue;
1417 TAILQ_FOREACH(pe, their_refs, entry) {
1418 if (strcmp(refname, pe->path) == 0)
1419 break;
1421 if (pe != NULL)
1422 continue;
1424 err = got_ref_resolve(&id, repo, re->ref);
1425 if (err)
1426 break;
1427 err = got_object_id_str(&id_str, id);
1428 free(id);
1429 if (err)
1430 break;
1432 free(id_str);
1433 err = got_ref_delete(re->ref, repo);
1434 if (err)
1435 break;
1436 if (verbosity >= 0) {
1437 printf("Deleted reference %s: %s\n",
1438 got_ref_get_name(re->ref), id_str);
1442 return err;
1445 static const struct got_error *
1446 cmd_fetch(int argc, char *argv[])
1448 const struct got_error *error = NULL;
1449 char *cwd = NULL, *repo_path = NULL;
1450 const char *remote_name;
1451 char *proto = NULL, *host = NULL, *port = NULL;
1452 char *repo_name = NULL, *server_path = NULL;
1453 struct got_remote_repo *remotes, *remote = NULL;
1454 int nremotes;
1455 char *id_str = NULL;
1456 struct got_repository *repo = NULL;
1457 struct got_worktree *worktree = NULL;
1458 struct got_pathlist_head refs, symrefs, wanted_branches;
1459 struct got_pathlist_entry *pe;
1460 struct got_object_id *pack_hash = NULL;
1461 int i, ch, fetchfd = -1, fetchstatus;
1462 pid_t fetchpid = -1;
1463 struct got_fetch_progress_arg fpa;
1464 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
1465 int delete_refs = 0, replace_tags = 0;
1467 TAILQ_INIT(&refs);
1468 TAILQ_INIT(&symrefs);
1469 TAILQ_INIT(&wanted_branches);
1471 while ((ch = getopt(argc, argv, "ab:dlr:tvq")) != -1) {
1472 switch (ch) {
1473 case 'a':
1474 fetch_all_branches = 1;
1475 break;
1476 case 'b':
1477 error = got_pathlist_append(&wanted_branches,
1478 optarg, NULL);
1479 if (error)
1480 return error;
1481 break;
1482 case 'd':
1483 delete_refs = 1;
1484 break;
1485 case 'l':
1486 list_refs_only = 1;
1487 break;
1488 case 'r':
1489 repo_path = realpath(optarg, NULL);
1490 if (repo_path == NULL)
1491 return got_error_from_errno2("realpath",
1492 optarg);
1493 got_path_strip_trailing_slashes(repo_path);
1494 break;
1495 case 't':
1496 replace_tags = 1;
1497 break;
1498 case 'v':
1499 if (verbosity < 0)
1500 verbosity = 0;
1501 else if (verbosity < 3)
1502 verbosity++;
1503 break;
1504 case 'q':
1505 verbosity = -1;
1506 break;
1507 default:
1508 usage_fetch();
1509 break;
1512 argc -= optind;
1513 argv += optind;
1515 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1516 errx(1, "-a and -b options are mutually exclusive");
1517 if (list_refs_only) {
1518 if (!TAILQ_EMPTY(&wanted_branches))
1519 errx(1, "-l and -b options are mutually exclusive");
1520 if (fetch_all_branches)
1521 errx(1, "-l and -a options are mutually exclusive");
1522 if (delete_refs)
1523 errx(1, "-l and -d options are mutually exclusive");
1524 if (verbosity == -1)
1525 errx(1, "-l and -q options are mutually exclusive");
1528 if (argc == 0)
1529 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
1530 else if (argc == 1)
1531 remote_name = argv[0];
1532 else
1533 usage_fetch();
1535 cwd = getcwd(NULL, 0);
1536 if (cwd == NULL) {
1537 error = got_error_from_errno("getcwd");
1538 goto done;
1541 if (repo_path == NULL) {
1542 error = got_worktree_open(&worktree, cwd);
1543 if (error && error->code != GOT_ERR_NOT_WORKTREE)
1544 goto done;
1545 else
1546 error = NULL;
1547 if (worktree) {
1548 repo_path =
1549 strdup(got_worktree_get_repo_path(worktree));
1550 if (repo_path == NULL)
1551 error = got_error_from_errno("strdup");
1552 if (error)
1553 goto done;
1554 } else {
1555 repo_path = strdup(cwd);
1556 if (repo_path == NULL) {
1557 error = got_error_from_errno("strdup");
1558 goto done;
1563 error = got_repo_open(&repo, repo_path, NULL);
1564 if (error)
1565 goto done;
1567 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
1568 for (i = 0; i < nremotes; i++) {
1569 remote = &remotes[i];
1570 if (strcmp(remote->name, remote_name) == 0)
1571 break;
1573 if (i == nremotes) {
1574 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
1575 goto done;
1578 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1579 &repo_name, remote->url);
1580 if (error)
1581 goto done;
1583 if (strcmp(proto, "git") == 0) {
1584 #ifndef PROFILE
1585 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1586 "sendfd dns inet unveil", NULL) == -1)
1587 err(1, "pledge");
1588 #endif
1589 } else if (strcmp(proto, "git+ssh") == 0 ||
1590 strcmp(proto, "ssh") == 0) {
1591 #ifndef PROFILE
1592 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1593 "sendfd unveil", NULL) == -1)
1594 err(1, "pledge");
1595 #endif
1596 } else if (strcmp(proto, "http") == 0 ||
1597 strcmp(proto, "git+http") == 0) {
1598 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1599 goto done;
1600 } else {
1601 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1602 goto done;
1605 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1606 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1607 error = got_error_from_errno2("unveil",
1608 GOT_FETCH_PATH_SSH);
1609 goto done;
1612 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
1613 if (error)
1614 goto done;
1616 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1617 server_path, verbosity);
1618 if (error)
1619 goto done;
1621 if (verbosity >= 0)
1622 printf("Connected to \"%s\" %s%s%s\n", remote->name, host,
1623 port ? ":" : "", port ? port : "");
1625 fpa.last_scaled_size[0] = '\0';
1626 fpa.last_p_indexed = -1;
1627 fpa.last_p_resolved = -1;
1628 fpa.verbosity = verbosity;
1629 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
1630 remote->mirror_references, fetch_all_branches, &wanted_branches,
1631 list_refs_only, verbosity, fetchfd, repo, fetch_progress, &fpa);
1632 if (error)
1633 goto done;
1635 if (list_refs_only) {
1636 error = list_remote_refs(&symrefs, &refs);
1637 goto done;
1640 if (pack_hash == NULL) {
1641 if (verbosity >= 0)
1642 printf("Already up-to-date\n");
1643 if (delete_refs)
1644 error = delete_missing_refs(&refs, verbosity, repo);
1645 goto done;
1648 if (verbosity >= 0) {
1649 error = got_object_id_str(&id_str, pack_hash);
1650 if (error)
1651 goto done;
1652 printf("\nFetched %s.pack\n", id_str);
1653 free(id_str);
1654 id_str = NULL;
1657 /* Update references provided with the pack file. */
1658 TAILQ_FOREACH(pe, &refs, entry) {
1659 const char *refname = pe->path;
1660 struct got_object_id *id = pe->data;
1661 struct got_reference *ref;
1662 char *remote_refname;
1664 if (remote->mirror_references ||
1665 strncmp("refs/tags/", refname, 10) == 0) {
1666 error = got_ref_open(&ref, repo, refname, 0);
1667 if (error) {
1668 if (error->code != GOT_ERR_NOT_REF)
1669 goto done;
1670 error = create_ref(refname, id, verbosity,
1671 repo);
1672 if (error)
1673 goto done;
1674 } else {
1675 error = update_ref(ref, id, replace_tags,
1676 verbosity, repo);
1677 got_ref_close(ref);
1678 if (error)
1679 goto done;
1681 } else if (strncmp("refs/heads/", refname, 11) == 0) {
1682 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1683 remote_name, refname + 11) == -1) {
1684 error = got_error_from_errno("asprintf");
1685 goto done;
1688 error = got_ref_open(&ref, repo, remote_refname, 0);
1689 if (error) {
1690 if (error->code != GOT_ERR_NOT_REF)
1691 goto done;
1692 error = create_ref(remote_refname, id,
1693 verbosity, repo);
1694 if (error)
1695 goto done;
1696 } else {
1697 error = update_ref(ref, id, replace_tags,
1698 verbosity, repo);
1699 got_ref_close(ref);
1700 if (error)
1701 goto done;
1704 /* Also create a local branch if none exists yet. */
1705 error = got_ref_open(&ref, repo, refname, 0);
1706 if (error) {
1707 if (error->code != GOT_ERR_NOT_REF)
1708 goto done;
1709 error = create_ref(refname, id, verbosity,
1710 repo);
1711 if (error)
1712 goto done;
1713 } else
1714 got_ref_close(ref);
1717 if (delete_refs)
1718 error = delete_missing_refs(&refs, verbosity, repo);
1719 done:
1720 if (fetchpid > 0) {
1721 if (kill(fetchpid, SIGTERM) == -1)
1722 error = got_error_from_errno("kill");
1723 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1724 error = got_error_from_errno("waitpid");
1726 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1727 error = got_error_from_errno("close");
1728 if (repo)
1729 got_repo_close(repo);
1730 if (worktree)
1731 got_worktree_close(worktree);
1732 TAILQ_FOREACH(pe, &refs, entry) {
1733 free((void *)pe->path);
1734 free(pe->data);
1736 got_pathlist_free(&refs);
1737 TAILQ_FOREACH(pe, &symrefs, entry) {
1738 free((void *)pe->path);
1739 free(pe->data);
1741 got_pathlist_free(&symrefs);
1742 got_pathlist_free(&wanted_branches);
1743 free(id_str);
1744 free(cwd);
1745 free(repo_path);
1746 free(pack_hash);
1747 free(proto);
1748 free(host);
1749 free(port);
1750 free(server_path);
1751 free(repo_name);
1752 return error;
1756 __dead static void
1757 usage_checkout(void)
1759 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
1760 "[-p prefix] repository-path [worktree-path]\n", getprogname());
1761 exit(1);
1764 static void
1765 show_worktree_base_ref_warning(void)
1767 fprintf(stderr, "%s: warning: could not create a reference "
1768 "to the work tree's base commit; the commit could be "
1769 "garbage-collected by Git; making the repository "
1770 "writable and running 'got update' will prevent this\n",
1771 getprogname());
1774 struct got_checkout_progress_arg {
1775 const char *worktree_path;
1776 int had_base_commit_ref_error;
1779 static const struct got_error *
1780 checkout_progress(void *arg, unsigned char status, const char *path)
1782 struct got_checkout_progress_arg *a = arg;
1784 /* Base commit bump happens silently. */
1785 if (status == GOT_STATUS_BUMP_BASE)
1786 return NULL;
1788 if (status == GOT_STATUS_BASE_REF_ERR) {
1789 a->had_base_commit_ref_error = 1;
1790 return NULL;
1793 while (path[0] == '/')
1794 path++;
1796 printf("%c %s/%s\n", status, a->worktree_path, path);
1797 return NULL;
1800 static const struct got_error *
1801 check_cancelled(void *arg)
1803 if (sigint_received || sigpipe_received)
1804 return got_error(GOT_ERR_CANCELLED);
1805 return NULL;
1808 static const struct got_error *
1809 check_linear_ancestry(struct got_object_id *commit_id,
1810 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
1811 struct got_repository *repo)
1813 const struct got_error *err = NULL;
1814 struct got_object_id *yca_id;
1816 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
1817 commit_id, base_commit_id, repo, check_cancelled, NULL);
1818 if (err)
1819 return err;
1821 if (yca_id == NULL)
1822 return got_error(GOT_ERR_ANCESTRY);
1825 * Require a straight line of history between the target commit
1826 * and the work tree's base commit.
1828 * Non-linear situations such as this require a rebase:
1830 * (commit) D F (base_commit)
1831 * \ /
1832 * C E
1833 * \ /
1834 * B (yca)
1835 * |
1836 * A
1838 * 'got update' only handles linear cases:
1839 * Update forwards in time: A (base/yca) - B - C - D (commit)
1840 * Update backwards in time: D (base) - C - B - A (commit/yca)
1842 if (allow_forwards_in_time_only) {
1843 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
1844 return got_error(GOT_ERR_ANCESTRY);
1845 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
1846 got_object_id_cmp(base_commit_id, yca_id) != 0)
1847 return got_error(GOT_ERR_ANCESTRY);
1849 free(yca_id);
1850 return NULL;
1853 static const struct got_error *
1854 check_same_branch(struct got_object_id *commit_id,
1855 struct got_reference *head_ref, struct got_object_id *yca_id,
1856 struct got_repository *repo)
1858 const struct got_error *err = NULL;
1859 struct got_commit_graph *graph = NULL;
1860 struct got_object_id *head_commit_id = NULL;
1861 int is_same_branch = 0;
1863 err = got_ref_resolve(&head_commit_id, repo, head_ref);
1864 if (err)
1865 goto done;
1867 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
1868 is_same_branch = 1;
1869 goto done;
1871 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
1872 is_same_branch = 1;
1873 goto done;
1876 err = got_commit_graph_open(&graph, "/", 1);
1877 if (err)
1878 goto done;
1880 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
1881 check_cancelled, NULL);
1882 if (err)
1883 goto done;
1885 for (;;) {
1886 struct got_object_id *id;
1887 err = got_commit_graph_iter_next(&id, graph, repo,
1888 check_cancelled, NULL);
1889 if (err) {
1890 if (err->code == GOT_ERR_ITER_COMPLETED)
1891 err = NULL;
1892 break;
1895 if (id) {
1896 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
1897 break;
1898 if (got_object_id_cmp(id, commit_id) == 0) {
1899 is_same_branch = 1;
1900 break;
1904 done:
1905 if (graph)
1906 got_commit_graph_close(graph);
1907 free(head_commit_id);
1908 if (!err && !is_same_branch)
1909 err = got_error(GOT_ERR_ANCESTRY);
1910 return err;
1913 static const struct got_error *
1914 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
1916 static char msg[512];
1917 const char *branch_name;
1919 if (got_ref_is_symbolic(ref))
1920 branch_name = got_ref_get_symref_target(ref);
1921 else
1922 branch_name = got_ref_get_name(ref);
1924 if (strncmp("refs/heads/", branch_name, 11) == 0)
1925 branch_name += 11;
1927 snprintf(msg, sizeof(msg),
1928 "target commit is not contained in branch '%s'; "
1929 "the branch to use must be specified with -b; "
1930 "if necessary a new branch can be created for "
1931 "this commit with 'got branch -c %s BRANCH_NAME'",
1932 branch_name, commit_id_str);
1934 return got_error_msg(GOT_ERR_ANCESTRY, msg);
1937 static const struct got_error *
1938 cmd_checkout(int argc, char *argv[])
1940 const struct got_error *error = NULL;
1941 struct got_repository *repo = NULL;
1942 struct got_reference *head_ref = NULL;
1943 struct got_worktree *worktree = NULL;
1944 char *repo_path = NULL;
1945 char *worktree_path = NULL;
1946 const char *path_prefix = "";
1947 const char *branch_name = GOT_REF_HEAD;
1948 char *commit_id_str = NULL;
1949 int ch, same_path_prefix, allow_nonempty = 0;
1950 struct got_pathlist_head paths;
1951 struct got_checkout_progress_arg cpa;
1953 TAILQ_INIT(&paths);
1955 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
1956 switch (ch) {
1957 case 'b':
1958 branch_name = optarg;
1959 break;
1960 case 'c':
1961 commit_id_str = strdup(optarg);
1962 if (commit_id_str == NULL)
1963 return got_error_from_errno("strdup");
1964 break;
1965 case 'E':
1966 allow_nonempty = 1;
1967 break;
1968 case 'p':
1969 path_prefix = optarg;
1970 break;
1971 default:
1972 usage_checkout();
1973 /* NOTREACHED */
1977 argc -= optind;
1978 argv += optind;
1980 #ifndef PROFILE
1981 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
1982 "unveil", NULL) == -1)
1983 err(1, "pledge");
1984 #endif
1985 if (argc == 1) {
1986 char *cwd, *base, *dotgit;
1987 repo_path = realpath(argv[0], NULL);
1988 if (repo_path == NULL)
1989 return got_error_from_errno2("realpath", argv[0]);
1990 cwd = getcwd(NULL, 0);
1991 if (cwd == NULL) {
1992 error = got_error_from_errno("getcwd");
1993 goto done;
1995 if (path_prefix[0]) {
1996 base = basename(path_prefix);
1997 if (base == NULL) {
1998 error = got_error_from_errno2("basename",
1999 path_prefix);
2000 goto done;
2002 } else {
2003 base = basename(repo_path);
2004 if (base == NULL) {
2005 error = got_error_from_errno2("basename",
2006 repo_path);
2007 goto done;
2010 dotgit = strstr(base, ".git");
2011 if (dotgit)
2012 *dotgit = '\0';
2013 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2014 error = got_error_from_errno("asprintf");
2015 free(cwd);
2016 goto done;
2018 free(cwd);
2019 } else if (argc == 2) {
2020 repo_path = realpath(argv[0], NULL);
2021 if (repo_path == NULL) {
2022 error = got_error_from_errno2("realpath", argv[0]);
2023 goto done;
2025 worktree_path = realpath(argv[1], NULL);
2026 if (worktree_path == NULL) {
2027 if (errno != ENOENT) {
2028 error = got_error_from_errno2("realpath",
2029 argv[1]);
2030 goto done;
2032 worktree_path = strdup(argv[1]);
2033 if (worktree_path == NULL) {
2034 error = got_error_from_errno("strdup");
2035 goto done;
2038 } else
2039 usage_checkout();
2041 got_path_strip_trailing_slashes(repo_path);
2042 got_path_strip_trailing_slashes(worktree_path);
2044 error = got_repo_open(&repo, repo_path, NULL);
2045 if (error != NULL)
2046 goto done;
2048 /* Pre-create work tree path for unveil(2) */
2049 error = got_path_mkdir(worktree_path);
2050 if (error) {
2051 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2052 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2053 goto done;
2054 if (!allow_nonempty &&
2055 !got_path_dir_is_empty(worktree_path)) {
2056 error = got_error_path(worktree_path,
2057 GOT_ERR_DIR_NOT_EMPTY);
2058 goto done;
2062 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2063 if (error)
2064 goto done;
2066 error = got_ref_open(&head_ref, repo, branch_name, 0);
2067 if (error != NULL)
2068 goto done;
2070 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2071 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2072 goto done;
2074 error = got_worktree_open(&worktree, worktree_path);
2075 if (error != NULL)
2076 goto done;
2078 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2079 path_prefix);
2080 if (error != NULL)
2081 goto done;
2082 if (!same_path_prefix) {
2083 error = got_error(GOT_ERR_PATH_PREFIX);
2084 goto done;
2087 if (commit_id_str) {
2088 struct got_object_id *commit_id;
2089 error = got_repo_match_object_id(&commit_id, NULL,
2090 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2091 if (error)
2092 goto done;
2093 error = check_linear_ancestry(commit_id,
2094 got_worktree_get_base_commit_id(worktree), 0, repo);
2095 if (error != NULL) {
2096 free(commit_id);
2097 if (error->code == GOT_ERR_ANCESTRY) {
2098 error = checkout_ancestry_error(
2099 head_ref, commit_id_str);
2101 goto done;
2103 error = check_same_branch(commit_id, head_ref, NULL, repo);
2104 if (error) {
2105 if (error->code == GOT_ERR_ANCESTRY) {
2106 error = checkout_ancestry_error(
2107 head_ref, commit_id_str);
2109 goto done;
2111 error = got_worktree_set_base_commit_id(worktree, repo,
2112 commit_id);
2113 free(commit_id);
2114 if (error)
2115 goto done;
2118 error = got_pathlist_append(&paths, "", NULL);
2119 if (error)
2120 goto done;
2121 cpa.worktree_path = worktree_path;
2122 cpa.had_base_commit_ref_error = 0;
2123 error = got_worktree_checkout_files(worktree, &paths, repo,
2124 checkout_progress, &cpa, check_cancelled, NULL);
2125 if (error != NULL)
2126 goto done;
2128 printf("Now shut up and hack\n");
2129 if (cpa.had_base_commit_ref_error)
2130 show_worktree_base_ref_warning();
2131 done:
2132 got_pathlist_free(&paths);
2133 free(commit_id_str);
2134 free(repo_path);
2135 free(worktree_path);
2136 return error;
2139 __dead static void
2140 usage_update(void)
2142 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2143 getprogname());
2144 exit(1);
2147 static const struct got_error *
2148 update_progress(void *arg, unsigned char status, const char *path)
2150 int *did_something = arg;
2152 if (status == GOT_STATUS_EXISTS ||
2153 status == GOT_STATUS_BASE_REF_ERR)
2154 return NULL;
2156 *did_something = 1;
2158 /* Base commit bump happens silently. */
2159 if (status == GOT_STATUS_BUMP_BASE)
2160 return NULL;
2162 while (path[0] == '/')
2163 path++;
2164 printf("%c %s\n", status, path);
2165 return NULL;
2168 static const struct got_error *
2169 switch_head_ref(struct got_reference *head_ref,
2170 struct got_object_id *commit_id, struct got_worktree *worktree,
2171 struct got_repository *repo)
2173 const struct got_error *err = NULL;
2174 char *base_id_str;
2175 int ref_has_moved = 0;
2177 /* Trivial case: switching between two different references. */
2178 if (strcmp(got_ref_get_name(head_ref),
2179 got_worktree_get_head_ref_name(worktree)) != 0) {
2180 printf("Switching work tree from %s to %s\n",
2181 got_worktree_get_head_ref_name(worktree),
2182 got_ref_get_name(head_ref));
2183 return got_worktree_set_head_ref(worktree, head_ref);
2186 err = check_linear_ancestry(commit_id,
2187 got_worktree_get_base_commit_id(worktree), 0, repo);
2188 if (err) {
2189 if (err->code != GOT_ERR_ANCESTRY)
2190 return err;
2191 ref_has_moved = 1;
2193 if (!ref_has_moved)
2194 return NULL;
2196 /* Switching to a rebased branch with the same reference name. */
2197 err = got_object_id_str(&base_id_str,
2198 got_worktree_get_base_commit_id(worktree));
2199 if (err)
2200 return err;
2201 printf("Reference %s now points at a different branch\n",
2202 got_worktree_get_head_ref_name(worktree));
2203 printf("Switching work tree from %s to %s\n", base_id_str,
2204 got_worktree_get_head_ref_name(worktree));
2205 return NULL;
2208 static const struct got_error *
2209 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2211 const struct got_error *err;
2212 int in_progress;
2214 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2215 if (err)
2216 return err;
2217 if (in_progress)
2218 return got_error(GOT_ERR_REBASING);
2220 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2221 if (err)
2222 return err;
2223 if (in_progress)
2224 return got_error(GOT_ERR_HISTEDIT_BUSY);
2226 return NULL;
2229 static const struct got_error *
2230 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2231 char *argv[], struct got_worktree *worktree)
2233 const struct got_error *err = NULL;
2234 char *path;
2235 int i;
2237 if (argc == 0) {
2238 path = strdup("");
2239 if (path == NULL)
2240 return got_error_from_errno("strdup");
2241 return got_pathlist_append(paths, path, NULL);
2244 for (i = 0; i < argc; i++) {
2245 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2246 if (err)
2247 break;
2248 err = got_pathlist_append(paths, path, NULL);
2249 if (err) {
2250 free(path);
2251 break;
2255 return err;
2258 static const struct got_error *
2259 cmd_update(int argc, char *argv[])
2261 const struct got_error *error = NULL;
2262 struct got_repository *repo = NULL;
2263 struct got_worktree *worktree = NULL;
2264 char *worktree_path = NULL;
2265 struct got_object_id *commit_id = NULL;
2266 char *commit_id_str = NULL;
2267 const char *branch_name = NULL;
2268 struct got_reference *head_ref = NULL;
2269 struct got_pathlist_head paths;
2270 struct got_pathlist_entry *pe;
2271 int ch, did_something = 0;
2273 TAILQ_INIT(&paths);
2275 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2276 switch (ch) {
2277 case 'b':
2278 branch_name = optarg;
2279 break;
2280 case 'c':
2281 commit_id_str = strdup(optarg);
2282 if (commit_id_str == NULL)
2283 return got_error_from_errno("strdup");
2284 break;
2285 default:
2286 usage_update();
2287 /* NOTREACHED */
2291 argc -= optind;
2292 argv += optind;
2294 #ifndef PROFILE
2295 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2296 "unveil", NULL) == -1)
2297 err(1, "pledge");
2298 #endif
2299 worktree_path = getcwd(NULL, 0);
2300 if (worktree_path == NULL) {
2301 error = got_error_from_errno("getcwd");
2302 goto done;
2304 error = got_worktree_open(&worktree, worktree_path);
2305 if (error)
2306 goto done;
2308 error = check_rebase_or_histedit_in_progress(worktree);
2309 if (error)
2310 goto done;
2312 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
2313 NULL);
2314 if (error != NULL)
2315 goto done;
2317 error = apply_unveil(got_repo_get_path(repo), 0,
2318 got_worktree_get_root_path(worktree));
2319 if (error)
2320 goto done;
2322 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2323 if (error)
2324 goto done;
2326 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
2327 got_worktree_get_head_ref_name(worktree), 0);
2328 if (error != NULL)
2329 goto done;
2330 if (commit_id_str == NULL) {
2331 error = got_ref_resolve(&commit_id, repo, head_ref);
2332 if (error != NULL)
2333 goto done;
2334 error = got_object_id_str(&commit_id_str, commit_id);
2335 if (error != NULL)
2336 goto done;
2337 } else {
2338 error = got_repo_match_object_id(&commit_id, NULL,
2339 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2340 free(commit_id_str);
2341 commit_id_str = NULL;
2342 if (error)
2343 goto done;
2344 error = got_object_id_str(&commit_id_str, commit_id);
2345 if (error)
2346 goto done;
2349 if (branch_name) {
2350 struct got_object_id *head_commit_id;
2351 TAILQ_FOREACH(pe, &paths, entry) {
2352 if (pe->path_len == 0)
2353 continue;
2354 error = got_error_msg(GOT_ERR_BAD_PATH,
2355 "switching between branches requires that "
2356 "the entire work tree gets updated");
2357 goto done;
2359 error = got_ref_resolve(&head_commit_id, repo, head_ref);
2360 if (error)
2361 goto done;
2362 error = check_linear_ancestry(commit_id, head_commit_id, 0,
2363 repo);
2364 free(head_commit_id);
2365 if (error != NULL)
2366 goto done;
2367 error = check_same_branch(commit_id, head_ref, NULL, repo);
2368 if (error)
2369 goto done;
2370 error = switch_head_ref(head_ref, commit_id, worktree, repo);
2371 if (error)
2372 goto done;
2373 } else {
2374 error = check_linear_ancestry(commit_id,
2375 got_worktree_get_base_commit_id(worktree), 0, repo);
2376 if (error != NULL) {
2377 if (error->code == GOT_ERR_ANCESTRY)
2378 error = got_error(GOT_ERR_BRANCH_MOVED);
2379 goto done;
2381 error = check_same_branch(commit_id, head_ref, NULL, repo);
2382 if (error)
2383 goto done;
2386 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
2387 commit_id) != 0) {
2388 error = got_worktree_set_base_commit_id(worktree, repo,
2389 commit_id);
2390 if (error)
2391 goto done;
2394 error = got_worktree_checkout_files(worktree, &paths, repo,
2395 update_progress, &did_something, check_cancelled, NULL);
2396 if (error != NULL)
2397 goto done;
2399 if (did_something)
2400 printf("Updated to commit %s\n", commit_id_str);
2401 else
2402 printf("Already up-to-date\n");
2403 done:
2404 free(worktree_path);
2405 TAILQ_FOREACH(pe, &paths, entry)
2406 free((char *)pe->path);
2407 got_pathlist_free(&paths);
2408 free(commit_id);
2409 free(commit_id_str);
2410 return error;
2413 static const struct got_error *
2414 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
2415 const char *path, int diff_context, int ignore_whitespace,
2416 struct got_repository *repo)
2418 const struct got_error *err = NULL;
2419 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
2421 if (blob_id1) {
2422 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
2423 if (err)
2424 goto done;
2427 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
2428 if (err)
2429 goto done;
2431 while (path[0] == '/')
2432 path++;
2433 err = got_diff_blob(blob1, blob2, path, path, diff_context,
2434 ignore_whitespace, stdout);
2435 done:
2436 if (blob1)
2437 got_object_blob_close(blob1);
2438 got_object_blob_close(blob2);
2439 return err;
2442 static const struct got_error *
2443 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
2444 const char *path, int diff_context, int ignore_whitespace,
2445 struct got_repository *repo)
2447 const struct got_error *err = NULL;
2448 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
2449 struct got_diff_blob_output_unidiff_arg arg;
2451 if (tree_id1) {
2452 err = got_object_open_as_tree(&tree1, repo, tree_id1);
2453 if (err)
2454 goto done;
2457 err = got_object_open_as_tree(&tree2, repo, tree_id2);
2458 if (err)
2459 goto done;
2461 arg.diff_context = diff_context;
2462 arg.ignore_whitespace = ignore_whitespace;
2463 arg.outfile = stdout;
2464 while (path[0] == '/')
2465 path++;
2466 err = got_diff_tree(tree1, tree2, path, path, repo,
2467 got_diff_blob_output_unidiff, &arg, 1);
2468 done:
2469 if (tree1)
2470 got_object_tree_close(tree1);
2471 if (tree2)
2472 got_object_tree_close(tree2);
2473 return err;
2476 static const struct got_error *
2477 print_patch(struct got_commit_object *commit, struct got_object_id *id,
2478 const char *path, int diff_context, struct got_repository *repo)
2480 const struct got_error *err = NULL;
2481 struct got_commit_object *pcommit = NULL;
2482 char *id_str1 = NULL, *id_str2 = NULL;
2483 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
2484 struct got_object_qid *qid;
2486 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
2487 if (qid != NULL) {
2488 err = got_object_open_as_commit(&pcommit, repo,
2489 qid->id);
2490 if (err)
2491 return err;
2494 if (path && path[0] != '\0') {
2495 int obj_type;
2496 err = got_object_id_by_path(&obj_id2, repo, id, path);
2497 if (err)
2498 goto done;
2499 err = got_object_id_str(&id_str2, obj_id2);
2500 if (err) {
2501 free(obj_id2);
2502 goto done;
2504 if (pcommit) {
2505 err = got_object_id_by_path(&obj_id1, repo,
2506 qid->id, path);
2507 if (err) {
2508 free(obj_id2);
2509 goto done;
2511 err = got_object_id_str(&id_str1, obj_id1);
2512 if (err) {
2513 free(obj_id2);
2514 goto done;
2517 err = got_object_get_type(&obj_type, repo, obj_id2);
2518 if (err) {
2519 free(obj_id2);
2520 goto done;
2522 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2523 switch (obj_type) {
2524 case GOT_OBJ_TYPE_BLOB:
2525 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
2526 0, repo);
2527 break;
2528 case GOT_OBJ_TYPE_TREE:
2529 err = diff_trees(obj_id1, obj_id2, path, diff_context,
2530 0, repo);
2531 break;
2532 default:
2533 err = got_error(GOT_ERR_OBJ_TYPE);
2534 break;
2536 free(obj_id1);
2537 free(obj_id2);
2538 } else {
2539 obj_id2 = got_object_commit_get_tree_id(commit);
2540 err = got_object_id_str(&id_str2, obj_id2);
2541 if (err)
2542 goto done;
2543 obj_id1 = got_object_commit_get_tree_id(pcommit);
2544 err = got_object_id_str(&id_str1, obj_id1);
2545 if (err)
2546 goto done;
2547 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2548 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
2550 done:
2551 free(id_str1);
2552 free(id_str2);
2553 if (pcommit)
2554 got_object_commit_close(pcommit);
2555 return err;
2558 static char *
2559 get_datestr(time_t *time, char *datebuf)
2561 struct tm mytm, *tm;
2562 char *p, *s;
2564 tm = gmtime_r(time, &mytm);
2565 if (tm == NULL)
2566 return NULL;
2567 s = asctime_r(tm, datebuf);
2568 if (s == NULL)
2569 return NULL;
2570 p = strchr(s, '\n');
2571 if (p)
2572 *p = '\0';
2573 return s;
2576 static const struct got_error *
2577 match_logmsg(int *have_match, struct got_object_id *id,
2578 struct got_commit_object *commit, regex_t *regex)
2580 const struct got_error *err = NULL;
2581 regmatch_t regmatch;
2582 char *id_str = NULL, *logmsg = NULL;
2584 *have_match = 0;
2586 err = got_object_id_str(&id_str, id);
2587 if (err)
2588 return err;
2590 err = got_object_commit_get_logmsg(&logmsg, commit);
2591 if (err)
2592 goto done;
2594 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2595 *have_match = 1;
2596 done:
2597 free(id_str);
2598 free(logmsg);
2599 return err;
2602 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
2604 static const struct got_error *
2605 print_commit(struct got_commit_object *commit, struct got_object_id *id,
2606 struct got_repository *repo, const char *path, int show_patch,
2607 int diff_context, struct got_reflist_head *refs)
2609 const struct got_error *err = NULL;
2610 char *id_str, *datestr, *logmsg0, *logmsg, *line;
2611 char datebuf[26];
2612 time_t committer_time;
2613 const char *author, *committer;
2614 char *refs_str = NULL;
2615 struct got_reflist_entry *re;
2617 SIMPLEQ_FOREACH(re, refs, entry) {
2618 char *s;
2619 const char *name;
2620 struct got_tag_object *tag = NULL;
2621 int cmp;
2623 name = got_ref_get_name(re->ref);
2624 if (strcmp(name, GOT_REF_HEAD) == 0)
2625 continue;
2626 if (strncmp(name, "refs/", 5) == 0)
2627 name += 5;
2628 if (strncmp(name, "got/", 4) == 0)
2629 continue;
2630 if (strncmp(name, "heads/", 6) == 0)
2631 name += 6;
2632 if (strncmp(name, "remotes/", 8) == 0)
2633 name += 8;
2634 if (strncmp(name, "tags/", 5) == 0) {
2635 err = got_object_open_as_tag(&tag, repo, re->id);
2636 if (err) {
2637 if (err->code != GOT_ERR_OBJ_TYPE)
2638 return err;
2639 /* Ref points at something other than a tag. */
2640 err = NULL;
2641 tag = NULL;
2644 cmp = got_object_id_cmp(tag ?
2645 got_object_tag_get_object_id(tag) : re->id, id);
2646 if (tag)
2647 got_object_tag_close(tag);
2648 if (cmp != 0)
2649 continue;
2650 s = refs_str;
2651 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
2652 name) == -1) {
2653 err = got_error_from_errno("asprintf");
2654 free(s);
2655 return err;
2657 free(s);
2659 err = got_object_id_str(&id_str, id);
2660 if (err)
2661 return err;
2663 printf(GOT_COMMIT_SEP_STR);
2664 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
2665 refs_str ? refs_str : "", refs_str ? ")" : "");
2666 free(id_str);
2667 id_str = NULL;
2668 free(refs_str);
2669 refs_str = NULL;
2670 printf("from: %s\n", got_object_commit_get_author(commit));
2671 committer_time = got_object_commit_get_committer_time(commit);
2672 datestr = get_datestr(&committer_time, datebuf);
2673 if (datestr)
2674 printf("date: %s UTC\n", datestr);
2675 author = got_object_commit_get_author(commit);
2676 committer = got_object_commit_get_committer(commit);
2677 if (strcmp(author, committer) != 0)
2678 printf("via: %s\n", committer);
2679 if (got_object_commit_get_nparents(commit) > 1) {
2680 const struct got_object_id_queue *parent_ids;
2681 struct got_object_qid *qid;
2682 int n = 1;
2683 parent_ids = got_object_commit_get_parent_ids(commit);
2684 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
2685 err = got_object_id_str(&id_str, qid->id);
2686 if (err)
2687 return err;
2688 printf("parent %d: %s\n", n++, id_str);
2689 free(id_str);
2693 err = got_object_commit_get_logmsg(&logmsg0, commit);
2694 if (err)
2695 return err;
2697 logmsg = logmsg0;
2698 do {
2699 line = strsep(&logmsg, "\n");
2700 if (line)
2701 printf(" %s\n", line);
2702 } while (line);
2703 free(logmsg0);
2705 if (show_patch) {
2706 err = print_patch(commit, id, path, diff_context, repo);
2707 if (err == 0)
2708 printf("\n");
2711 if (fflush(stdout) != 0 && err == NULL)
2712 err = got_error_from_errno("fflush");
2713 return err;
2716 static const struct got_error *
2717 print_commits(struct got_object_id *root_id, struct got_repository *repo,
2718 const char *path, int show_patch, const char *search_pattern,
2719 int diff_context, int limit, int log_branches,
2720 struct got_reflist_head *refs)
2722 const struct got_error *err;
2723 struct got_commit_graph *graph;
2724 regex_t regex;
2725 int have_match;
2727 if (search_pattern &&
2728 regcomp(&regex, search_pattern, REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
2729 return got_error_msg(GOT_ERR_REGEX, search_pattern);
2731 err = got_commit_graph_open(&graph, path, !log_branches);
2732 if (err)
2733 return err;
2734 err = got_commit_graph_iter_start(graph, root_id, repo,
2735 check_cancelled, NULL);
2736 if (err)
2737 goto done;
2738 for (;;) {
2739 struct got_commit_object *commit;
2740 struct got_object_id *id;
2742 if (sigint_received || sigpipe_received)
2743 break;
2745 err = got_commit_graph_iter_next(&id, graph, repo,
2746 check_cancelled, NULL);
2747 if (err) {
2748 if (err->code == GOT_ERR_ITER_COMPLETED)
2749 err = NULL;
2750 break;
2752 if (id == NULL)
2753 break;
2755 err = got_object_open_as_commit(&commit, repo, id);
2756 if (err)
2757 break;
2759 if (search_pattern) {
2760 err = match_logmsg(&have_match, id, commit, &regex);
2761 if (err) {
2762 got_object_commit_close(commit);
2763 break;
2765 if (have_match == 0) {
2766 got_object_commit_close(commit);
2767 continue;
2771 err = print_commit(commit, id, repo, path, show_patch,
2772 diff_context, refs);
2773 got_object_commit_close(commit);
2774 if (err || (limit && --limit == 0))
2775 break;
2777 done:
2778 if (search_pattern)
2779 regfree(&regex);
2780 got_commit_graph_close(graph);
2781 return err;
2784 __dead static void
2785 usage_log(void)
2787 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] [-p] "
2788 "[-s search-pattern] [-r repository-path] [path]\n", getprogname());
2789 exit(1);
2792 static int
2793 get_default_log_limit(void)
2795 const char *got_default_log_limit;
2796 long long n;
2797 const char *errstr;
2799 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
2800 if (got_default_log_limit == NULL)
2801 return 0;
2802 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
2803 if (errstr != NULL)
2804 return 0;
2805 return n;
2808 static const struct got_error *
2809 cmd_log(int argc, char *argv[])
2811 const struct got_error *error;
2812 struct got_repository *repo = NULL;
2813 struct got_worktree *worktree = NULL;
2814 struct got_commit_object *commit = NULL;
2815 struct got_object_id *id = NULL;
2816 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
2817 const char *start_commit = NULL, *search_pattern = NULL;
2818 int diff_context = -1, ch;
2819 int show_patch = 0, limit = 0, log_branches = 0;
2820 const char *errstr;
2821 struct got_reflist_head refs;
2823 SIMPLEQ_INIT(&refs);
2825 #ifndef PROFILE
2826 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
2827 NULL)
2828 == -1)
2829 err(1, "pledge");
2830 #endif
2832 limit = get_default_log_limit();
2834 while ((ch = getopt(argc, argv, "bpc:C:l:r:s:")) != -1) {
2835 switch (ch) {
2836 case 'p':
2837 show_patch = 1;
2838 break;
2839 case 'c':
2840 start_commit = optarg;
2841 break;
2842 case 'C':
2843 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
2844 &errstr);
2845 if (errstr != NULL)
2846 err(1, "-C option %s", errstr);
2847 break;
2848 case 'l':
2849 limit = strtonum(optarg, 0, INT_MAX, &errstr);
2850 if (errstr != NULL)
2851 err(1, "-l option %s", errstr);
2852 break;
2853 case 'b':
2854 log_branches = 1;
2855 break;
2856 case 'r':
2857 repo_path = realpath(optarg, NULL);
2858 if (repo_path == NULL)
2859 return got_error_from_errno2("realpath",
2860 optarg);
2861 got_path_strip_trailing_slashes(repo_path);
2862 break;
2863 case 's':
2864 search_pattern = optarg;
2865 break;
2866 default:
2867 usage_log();
2868 /* NOTREACHED */
2872 argc -= optind;
2873 argv += optind;
2875 if (diff_context == -1)
2876 diff_context = 3;
2877 else if (!show_patch)
2878 errx(1, "-C reguires -p");
2880 cwd = getcwd(NULL, 0);
2881 if (cwd == NULL) {
2882 error = got_error_from_errno("getcwd");
2883 goto done;
2886 error = got_worktree_open(&worktree, cwd);
2887 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2888 goto done;
2889 error = NULL;
2891 if (argc == 0) {
2892 path = strdup("");
2893 if (path == NULL) {
2894 error = got_error_from_errno("strdup");
2895 goto done;
2897 } else if (argc == 1) {
2898 if (worktree) {
2899 error = got_worktree_resolve_path(&path, worktree,
2900 argv[0]);
2901 if (error)
2902 goto done;
2903 } else {
2904 path = strdup(argv[0]);
2905 if (path == NULL) {
2906 error = got_error_from_errno("strdup");
2907 goto done;
2910 } else
2911 usage_log();
2913 if (repo_path == NULL) {
2914 repo_path = worktree ?
2915 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
2917 if (repo_path == NULL) {
2918 error = got_error_from_errno("strdup");
2919 goto done;
2922 error = got_repo_open(&repo, repo_path, NULL);
2923 if (error != NULL)
2924 goto done;
2926 error = apply_unveil(got_repo_get_path(repo), 1,
2927 worktree ? got_worktree_get_root_path(worktree) : NULL);
2928 if (error)
2929 goto done;
2931 if (start_commit == NULL) {
2932 struct got_reference *head_ref;
2933 error = got_ref_open(&head_ref, repo,
2934 worktree ? got_worktree_get_head_ref_name(worktree)
2935 : GOT_REF_HEAD, 0);
2936 if (error != NULL)
2937 return error;
2938 error = got_ref_resolve(&id, repo, head_ref);
2939 got_ref_close(head_ref);
2940 if (error != NULL)
2941 return error;
2942 error = got_object_open_as_commit(&commit, repo, id);
2943 } else {
2944 struct got_reference *ref;
2945 error = got_ref_open(&ref, repo, start_commit, 0);
2946 if (error == NULL) {
2947 int obj_type;
2948 error = got_ref_resolve(&id, repo, ref);
2949 got_ref_close(ref);
2950 if (error != NULL)
2951 goto done;
2952 error = got_object_get_type(&obj_type, repo, id);
2953 if (error != NULL)
2954 goto done;
2955 if (obj_type == GOT_OBJ_TYPE_TAG) {
2956 struct got_tag_object *tag;
2957 error = got_object_open_as_tag(&tag, repo, id);
2958 if (error != NULL)
2959 goto done;
2960 if (got_object_tag_get_object_type(tag) !=
2961 GOT_OBJ_TYPE_COMMIT) {
2962 got_object_tag_close(tag);
2963 error = got_error(GOT_ERR_OBJ_TYPE);
2964 goto done;
2966 free(id);
2967 id = got_object_id_dup(
2968 got_object_tag_get_object_id(tag));
2969 if (id == NULL)
2970 error = got_error_from_errno(
2971 "got_object_id_dup");
2972 got_object_tag_close(tag);
2973 if (error)
2974 goto done;
2975 } else if (obj_type != GOT_OBJ_TYPE_COMMIT) {
2976 error = got_error(GOT_ERR_OBJ_TYPE);
2977 goto done;
2979 error = got_object_open_as_commit(&commit, repo, id);
2980 if (error != NULL)
2981 goto done;
2983 if (commit == NULL) {
2984 error = got_repo_match_object_id_prefix(&id,
2985 start_commit, GOT_OBJ_TYPE_COMMIT, repo);
2986 if (error != NULL)
2987 return error;
2990 if (error != NULL)
2991 goto done;
2993 if (worktree) {
2994 const char *prefix = got_worktree_get_path_prefix(worktree);
2995 char *p;
2996 if (asprintf(&p, "%s%s%s", prefix,
2997 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
2998 error = got_error_from_errno("asprintf");
2999 goto done;
3001 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3002 free(p);
3003 } else
3004 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3005 if (error != NULL)
3006 goto done;
3007 if (in_repo_path) {
3008 free(path);
3009 path = in_repo_path;
3012 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3013 if (error)
3014 goto done;
3016 error = print_commits(id, repo, path, show_patch, search_pattern,
3017 diff_context, limit, log_branches, &refs);
3018 done:
3019 free(path);
3020 free(repo_path);
3021 free(cwd);
3022 free(id);
3023 if (worktree)
3024 got_worktree_close(worktree);
3025 if (repo) {
3026 const struct got_error *repo_error;
3027 repo_error = got_repo_close(repo);
3028 if (error == NULL)
3029 error = repo_error;
3031 got_ref_list_free(&refs);
3032 return error;
3035 __dead static void
3036 usage_diff(void)
3038 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3039 "[-w] [object1 object2 | path]\n", getprogname());
3040 exit(1);
3043 struct print_diff_arg {
3044 struct got_repository *repo;
3045 struct got_worktree *worktree;
3046 int diff_context;
3047 const char *id_str;
3048 int header_shown;
3049 int diff_staged;
3050 int ignore_whitespace;
3053 static const struct got_error *
3054 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3055 const char *path, struct got_object_id *blob_id,
3056 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3057 int dirfd, const char *de_name)
3059 struct print_diff_arg *a = arg;
3060 const struct got_error *err = NULL;
3061 struct got_blob_object *blob1 = NULL;
3062 int fd = -1;
3063 FILE *f2 = NULL;
3064 char *abspath = NULL, *label1 = NULL;
3065 struct stat sb;
3067 if (a->diff_staged) {
3068 if (staged_status != GOT_STATUS_MODIFY &&
3069 staged_status != GOT_STATUS_ADD &&
3070 staged_status != GOT_STATUS_DELETE)
3071 return NULL;
3072 } else {
3073 if (staged_status == GOT_STATUS_DELETE)
3074 return NULL;
3075 if (status == GOT_STATUS_NONEXISTENT)
3076 return got_error_set_errno(ENOENT, path);
3077 if (status != GOT_STATUS_MODIFY &&
3078 status != GOT_STATUS_ADD &&
3079 status != GOT_STATUS_DELETE &&
3080 status != GOT_STATUS_CONFLICT)
3081 return NULL;
3084 if (!a->header_shown) {
3085 printf("diff %s %s%s\n", a->id_str,
3086 got_worktree_get_root_path(a->worktree),
3087 a->diff_staged ? " (staged changes)" : "");
3088 a->header_shown = 1;
3091 if (a->diff_staged) {
3092 const char *label1 = NULL, *label2 = NULL;
3093 switch (staged_status) {
3094 case GOT_STATUS_MODIFY:
3095 label1 = path;
3096 label2 = path;
3097 break;
3098 case GOT_STATUS_ADD:
3099 label2 = path;
3100 break;
3101 case GOT_STATUS_DELETE:
3102 label1 = path;
3103 break;
3104 default:
3105 return got_error(GOT_ERR_FILE_STATUS);
3107 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
3108 label1, label2, a->diff_context, a->ignore_whitespace,
3109 a->repo, stdout);
3112 if (staged_status == GOT_STATUS_ADD ||
3113 staged_status == GOT_STATUS_MODIFY) {
3114 char *id_str;
3115 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
3116 8192);
3117 if (err)
3118 goto done;
3119 err = got_object_id_str(&id_str, staged_blob_id);
3120 if (err)
3121 goto done;
3122 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
3123 err = got_error_from_errno("asprintf");
3124 free(id_str);
3125 goto done;
3127 free(id_str);
3128 } else if (status != GOT_STATUS_ADD) {
3129 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
3130 if (err)
3131 goto done;
3134 if (status != GOT_STATUS_DELETE) {
3135 if (asprintf(&abspath, "%s/%s",
3136 got_worktree_get_root_path(a->worktree), path) == -1) {
3137 err = got_error_from_errno("asprintf");
3138 goto done;
3141 if (dirfd != -1) {
3142 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
3143 if (fd == -1) {
3144 err = got_error_from_errno2("openat", abspath);
3145 goto done;
3147 } else {
3148 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
3149 if (fd == -1) {
3150 err = got_error_from_errno2("open", abspath);
3151 goto done;
3154 if (fstat(fd, &sb) == -1) {
3155 err = got_error_from_errno2("fstat", abspath);
3156 goto done;
3158 f2 = fdopen(fd, "r");
3159 if (f2 == NULL) {
3160 err = got_error_from_errno2("fdopen", abspath);
3161 goto done;
3163 fd = -1;
3164 } else
3165 sb.st_size = 0;
3167 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
3168 a->diff_context, a->ignore_whitespace, stdout);
3169 done:
3170 if (blob1)
3171 got_object_blob_close(blob1);
3172 if (f2 && fclose(f2) == EOF && err == NULL)
3173 err = got_error_from_errno("fclose");
3174 if (fd != -1 && close(fd) == -1 && err == NULL)
3175 err = got_error_from_errno("close");
3176 free(abspath);
3177 return err;
3180 static const struct got_error *
3181 cmd_diff(int argc, char *argv[])
3183 const struct got_error *error;
3184 struct got_repository *repo = NULL;
3185 struct got_worktree *worktree = NULL;
3186 char *cwd = NULL, *repo_path = NULL;
3187 struct got_object_id *id1 = NULL, *id2 = NULL;
3188 const char *id_str1 = NULL, *id_str2 = NULL;
3189 char *label1 = NULL, *label2 = NULL;
3190 int type1, type2;
3191 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
3192 const char *errstr;
3193 char *path = NULL;
3195 #ifndef PROFILE
3196 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3197 NULL) == -1)
3198 err(1, "pledge");
3199 #endif
3201 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
3202 switch (ch) {
3203 case 'C':
3204 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3205 &errstr);
3206 if (errstr != NULL)
3207 err(1, "-C option %s", errstr);
3208 break;
3209 case 'r':
3210 repo_path = realpath(optarg, NULL);
3211 if (repo_path == NULL)
3212 return got_error_from_errno2("realpath",
3213 optarg);
3214 got_path_strip_trailing_slashes(repo_path);
3215 break;
3216 case 's':
3217 diff_staged = 1;
3218 break;
3219 case 'w':
3220 ignore_whitespace = 1;
3221 break;
3222 default:
3223 usage_diff();
3224 /* NOTREACHED */
3228 argc -= optind;
3229 argv += optind;
3231 cwd = getcwd(NULL, 0);
3232 if (cwd == NULL) {
3233 error = got_error_from_errno("getcwd");
3234 goto done;
3236 if (argc <= 1) {
3237 if (repo_path)
3238 errx(1,
3239 "-r option can't be used when diffing a work tree");
3240 error = got_worktree_open(&worktree, cwd);
3241 if (error)
3242 goto done;
3243 repo_path = strdup(got_worktree_get_repo_path(worktree));
3244 if (repo_path == NULL) {
3245 error = got_error_from_errno("strdup");
3246 goto done;
3248 if (argc == 1) {
3249 error = got_worktree_resolve_path(&path, worktree,
3250 argv[0]);
3251 if (error)
3252 goto done;
3253 } else {
3254 path = strdup("");
3255 if (path == NULL) {
3256 error = got_error_from_errno("strdup");
3257 goto done;
3260 } else if (argc == 2) {
3261 if (diff_staged)
3262 errx(1, "-s option can't be used when diffing "
3263 "objects in repository");
3264 id_str1 = argv[0];
3265 id_str2 = argv[1];
3266 if (repo_path == NULL) {
3267 error = got_worktree_open(&worktree, cwd);
3268 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3269 goto done;
3270 if (worktree) {
3271 repo_path = strdup(
3272 got_worktree_get_repo_path(worktree));
3273 if (repo_path == NULL) {
3274 error = got_error_from_errno("strdup");
3275 goto done;
3277 } else {
3278 repo_path = strdup(cwd);
3279 if (repo_path == NULL) {
3280 error = got_error_from_errno("strdup");
3281 goto done;
3285 } else
3286 usage_diff();
3288 error = got_repo_open(&repo, repo_path, NULL);
3289 free(repo_path);
3290 if (error != NULL)
3291 goto done;
3293 error = apply_unveil(got_repo_get_path(repo), 1,
3294 worktree ? got_worktree_get_root_path(worktree) : NULL);
3295 if (error)
3296 goto done;
3298 if (argc <= 1) {
3299 struct print_diff_arg arg;
3300 struct got_pathlist_head paths;
3301 char *id_str;
3303 TAILQ_INIT(&paths);
3305 error = got_object_id_str(&id_str,
3306 got_worktree_get_base_commit_id(worktree));
3307 if (error)
3308 goto done;
3309 arg.repo = repo;
3310 arg.worktree = worktree;
3311 arg.diff_context = diff_context;
3312 arg.id_str = id_str;
3313 arg.header_shown = 0;
3314 arg.diff_staged = diff_staged;
3315 arg.ignore_whitespace = ignore_whitespace;
3317 error = got_pathlist_append(&paths, path, NULL);
3318 if (error)
3319 goto done;
3321 error = got_worktree_status(worktree, &paths, repo, print_diff,
3322 &arg, check_cancelled, NULL);
3323 free(id_str);
3324 got_pathlist_free(&paths);
3325 goto done;
3328 error = got_repo_match_object_id(&id1, &label1, id_str1,
3329 GOT_OBJ_TYPE_ANY, 1, repo);
3330 if (error)
3331 goto done;
3333 error = got_repo_match_object_id(&id2, &label2, id_str2,
3334 GOT_OBJ_TYPE_ANY, 1, repo);
3335 if (error)
3336 goto done;
3338 error = got_object_get_type(&type1, repo, id1);
3339 if (error)
3340 goto done;
3342 error = got_object_get_type(&type2, repo, id2);
3343 if (error)
3344 goto done;
3346 if (type1 != type2) {
3347 error = got_error(GOT_ERR_OBJ_TYPE);
3348 goto done;
3351 switch (type1) {
3352 case GOT_OBJ_TYPE_BLOB:
3353 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
3354 diff_context, ignore_whitespace, repo, stdout);
3355 break;
3356 case GOT_OBJ_TYPE_TREE:
3357 error = got_diff_objects_as_trees(id1, id2, "", "",
3358 diff_context, ignore_whitespace, repo, stdout);
3359 break;
3360 case GOT_OBJ_TYPE_COMMIT:
3361 printf("diff %s %s\n", label1, label2);
3362 error = got_diff_objects_as_commits(id1, id2, diff_context,
3363 ignore_whitespace, repo, stdout);
3364 break;
3365 default:
3366 error = got_error(GOT_ERR_OBJ_TYPE);
3368 done:
3369 free(label1);
3370 free(label2);
3371 free(id1);
3372 free(id2);
3373 free(path);
3374 if (worktree)
3375 got_worktree_close(worktree);
3376 if (repo) {
3377 const struct got_error *repo_error;
3378 repo_error = got_repo_close(repo);
3379 if (error == NULL)
3380 error = repo_error;
3382 return error;
3385 __dead static void
3386 usage_blame(void)
3388 fprintf(stderr,
3389 "usage: %s blame [-c commit] [-r repository-path] path\n",
3390 getprogname());
3391 exit(1);
3394 struct blame_line {
3395 int annotated;
3396 char *id_str;
3397 char *committer;
3398 char datebuf[11]; /* YYYY-MM-DD + NUL */
3401 struct blame_cb_args {
3402 struct blame_line *lines;
3403 int nlines;
3404 int nlines_prec;
3405 int lineno_cur;
3406 off_t *line_offsets;
3407 FILE *f;
3408 struct got_repository *repo;
3411 static const struct got_error *
3412 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
3414 const struct got_error *err = NULL;
3415 struct blame_cb_args *a = arg;
3416 struct blame_line *bline;
3417 char *line = NULL;
3418 size_t linesize = 0;
3419 struct got_commit_object *commit = NULL;
3420 off_t offset;
3421 struct tm tm;
3422 time_t committer_time;
3424 if (nlines != a->nlines ||
3425 (lineno != -1 && lineno < 1) || lineno > a->nlines)
3426 return got_error(GOT_ERR_RANGE);
3428 if (sigint_received)
3429 return got_error(GOT_ERR_ITER_COMPLETED);
3431 if (lineno == -1)
3432 return NULL; /* no change in this commit */
3434 /* Annotate this line. */
3435 bline = &a->lines[lineno - 1];
3436 if (bline->annotated)
3437 return NULL;
3438 err = got_object_id_str(&bline->id_str, id);
3439 if (err)
3440 return err;
3442 err = got_object_open_as_commit(&commit, a->repo, id);
3443 if (err)
3444 goto done;
3446 bline->committer = strdup(got_object_commit_get_committer(commit));
3447 if (bline->committer == NULL) {
3448 err = got_error_from_errno("strdup");
3449 goto done;
3452 committer_time = got_object_commit_get_committer_time(commit);
3453 if (localtime_r(&committer_time, &tm) == NULL)
3454 return got_error_from_errno("localtime_r");
3455 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
3456 &tm) >= sizeof(bline->datebuf)) {
3457 err = got_error(GOT_ERR_NO_SPACE);
3458 goto done;
3460 bline->annotated = 1;
3462 /* Print lines annotated so far. */
3463 bline = &a->lines[a->lineno_cur - 1];
3464 if (!bline->annotated)
3465 goto done;
3467 offset = a->line_offsets[a->lineno_cur - 1];
3468 if (fseeko(a->f, offset, SEEK_SET) == -1) {
3469 err = got_error_from_errno("fseeko");
3470 goto done;
3473 while (bline->annotated) {
3474 char *smallerthan, *at, *nl, *committer;
3475 size_t len;
3477 if (getline(&line, &linesize, a->f) == -1) {
3478 if (ferror(a->f))
3479 err = got_error_from_errno("getline");
3480 break;
3483 committer = bline->committer;
3484 smallerthan = strchr(committer, '<');
3485 if (smallerthan && smallerthan[1] != '\0')
3486 committer = smallerthan + 1;
3487 at = strchr(committer, '@');
3488 if (at)
3489 *at = '\0';
3490 len = strlen(committer);
3491 if (len >= 9)
3492 committer[8] = '\0';
3494 nl = strchr(line, '\n');
3495 if (nl)
3496 *nl = '\0';
3497 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
3498 bline->id_str, bline->datebuf, committer, line);
3500 a->lineno_cur++;
3501 bline = &a->lines[a->lineno_cur - 1];
3503 done:
3504 if (commit)
3505 got_object_commit_close(commit);
3506 free(line);
3507 return err;
3510 static const struct got_error *
3511 cmd_blame(int argc, char *argv[])
3513 const struct got_error *error;
3514 struct got_repository *repo = NULL;
3515 struct got_worktree *worktree = NULL;
3516 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
3517 struct got_object_id *obj_id = NULL;
3518 struct got_object_id *commit_id = NULL;
3519 struct got_blob_object *blob = NULL;
3520 char *commit_id_str = NULL;
3521 struct blame_cb_args bca;
3522 int ch, obj_type, i;
3523 size_t filesize;
3525 memset(&bca, 0, sizeof(bca));
3527 #ifndef PROFILE
3528 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3529 NULL) == -1)
3530 err(1, "pledge");
3531 #endif
3533 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
3534 switch (ch) {
3535 case 'c':
3536 commit_id_str = optarg;
3537 break;
3538 case 'r':
3539 repo_path = realpath(optarg, NULL);
3540 if (repo_path == NULL)
3541 return got_error_from_errno2("realpath",
3542 optarg);
3543 got_path_strip_trailing_slashes(repo_path);
3544 break;
3545 default:
3546 usage_blame();
3547 /* NOTREACHED */
3551 argc -= optind;
3552 argv += optind;
3554 if (argc == 1)
3555 path = argv[0];
3556 else
3557 usage_blame();
3559 cwd = getcwd(NULL, 0);
3560 if (cwd == NULL) {
3561 error = got_error_from_errno("getcwd");
3562 goto done;
3564 if (repo_path == NULL) {
3565 error = got_worktree_open(&worktree, cwd);
3566 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3567 goto done;
3568 else
3569 error = NULL;
3570 if (worktree) {
3571 repo_path =
3572 strdup(got_worktree_get_repo_path(worktree));
3573 if (repo_path == NULL) {
3574 error = got_error_from_errno("strdup");
3575 if (error)
3576 goto done;
3578 } else {
3579 repo_path = strdup(cwd);
3580 if (repo_path == NULL) {
3581 error = got_error_from_errno("strdup");
3582 goto done;
3587 error = got_repo_open(&repo, repo_path, NULL);
3588 if (error != NULL)
3589 goto done;
3591 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
3592 if (error)
3593 goto done;
3595 if (worktree) {
3596 const char *prefix = got_worktree_get_path_prefix(worktree);
3597 char *p, *worktree_subdir = cwd +
3598 strlen(got_worktree_get_root_path(worktree));
3599 if (asprintf(&p, "%s%s%s%s%s",
3600 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
3601 worktree_subdir, worktree_subdir[0] ? "/" : "",
3602 path) == -1) {
3603 error = got_error_from_errno("asprintf");
3604 goto done;
3606 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3607 free(p);
3608 } else {
3609 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3611 if (error)
3612 goto done;
3614 if (commit_id_str == NULL) {
3615 struct got_reference *head_ref;
3616 error = got_ref_open(&head_ref, repo, worktree ?
3617 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
3618 if (error != NULL)
3619 goto done;
3620 error = got_ref_resolve(&commit_id, repo, head_ref);
3621 got_ref_close(head_ref);
3622 if (error != NULL)
3623 goto done;
3624 } else {
3625 error = got_repo_match_object_id(&commit_id, NULL,
3626 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
3627 if (error)
3628 goto done;
3631 error = got_object_id_by_path(&obj_id, repo, commit_id, in_repo_path);
3632 if (error)
3633 goto done;
3635 error = got_object_get_type(&obj_type, repo, obj_id);
3636 if (error)
3637 goto done;
3639 if (obj_type != GOT_OBJ_TYPE_BLOB) {
3640 error = got_error(GOT_ERR_OBJ_TYPE);
3641 goto done;
3644 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
3645 if (error)
3646 goto done;
3647 bca.f = got_opentemp();
3648 if (bca.f == NULL) {
3649 error = got_error_from_errno("got_opentemp");
3650 goto done;
3652 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
3653 &bca.line_offsets, bca.f, blob);
3654 if (error || bca.nlines == 0)
3655 goto done;
3657 /* Don't include \n at EOF in the blame line count. */
3658 if (bca.line_offsets[bca.nlines - 1] == filesize)
3659 bca.nlines--;
3661 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
3662 if (bca.lines == NULL) {
3663 error = got_error_from_errno("calloc");
3664 goto done;
3666 bca.lineno_cur = 1;
3667 bca.nlines_prec = 0;
3668 i = bca.nlines;
3669 while (i > 0) {
3670 i /= 10;
3671 bca.nlines_prec++;
3673 bca.repo = repo;
3675 error = got_blame(in_repo_path, commit_id, repo, blame_cb, &bca,
3676 check_cancelled, NULL);
3677 done:
3678 free(in_repo_path);
3679 free(repo_path);
3680 free(cwd);
3681 free(commit_id);
3682 free(obj_id);
3683 if (blob)
3684 got_object_blob_close(blob);
3685 if (worktree)
3686 got_worktree_close(worktree);
3687 if (repo) {
3688 const struct got_error *repo_error;
3689 repo_error = got_repo_close(repo);
3690 if (error == NULL)
3691 error = repo_error;
3693 if (bca.lines) {
3694 for (i = 0; i < bca.nlines; i++) {
3695 struct blame_line *bline = &bca.lines[i];
3696 free(bline->id_str);
3697 free(bline->committer);
3699 free(bca.lines);
3701 free(bca.line_offsets);
3702 if (bca.f && fclose(bca.f) == EOF && error == NULL)
3703 error = got_error_from_errno("fclose");
3704 return error;
3707 __dead static void
3708 usage_tree(void)
3710 fprintf(stderr,
3711 "usage: %s tree [-c commit] [-r repository-path] [-iR] path\n",
3712 getprogname());
3713 exit(1);
3716 static void
3717 print_entry(struct got_tree_entry *te, const char *id, const char *path,
3718 const char *root_path)
3720 int is_root_path = (strcmp(path, root_path) == 0);
3721 const char *modestr = "";
3722 mode_t mode = got_tree_entry_get_mode(te);
3724 path += strlen(root_path);
3725 while (path[0] == '/')
3726 path++;
3728 if (got_object_tree_entry_is_submodule(te))
3729 modestr = "$";
3730 else if (S_ISLNK(mode))
3731 modestr = "@";
3732 else if (S_ISDIR(mode))
3733 modestr = "/";
3734 else if (mode & S_IXUSR)
3735 modestr = "*";
3737 printf("%s%s%s%s%s\n", id ? id : "", path,
3738 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr);
3741 static const struct got_error *
3742 print_tree(const char *path, struct got_object_id *commit_id,
3743 int show_ids, int recurse, const char *root_path,
3744 struct got_repository *repo)
3746 const struct got_error *err = NULL;
3747 struct got_object_id *tree_id = NULL;
3748 struct got_tree_object *tree = NULL;
3749 int nentries, i;
3751 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
3752 if (err)
3753 goto done;
3755 err = got_object_open_as_tree(&tree, repo, tree_id);
3756 if (err)
3757 goto done;
3758 nentries = got_object_tree_get_nentries(tree);
3759 for (i = 0; i < nentries; i++) {
3760 struct got_tree_entry *te;
3761 char *id = NULL;
3763 if (sigint_received || sigpipe_received)
3764 break;
3766 te = got_object_tree_get_entry(tree, i);
3767 if (show_ids) {
3768 char *id_str;
3769 err = got_object_id_str(&id_str,
3770 got_tree_entry_get_id(te));
3771 if (err)
3772 goto done;
3773 if (asprintf(&id, "%s ", id_str) == -1) {
3774 err = got_error_from_errno("asprintf");
3775 free(id_str);
3776 goto done;
3778 free(id_str);
3780 print_entry(te, id, path, root_path);
3781 free(id);
3783 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
3784 char *child_path;
3785 if (asprintf(&child_path, "%s%s%s", path,
3786 path[0] == '/' && path[1] == '\0' ? "" : "/",
3787 got_tree_entry_get_name(te)) == -1) {
3788 err = got_error_from_errno("asprintf");
3789 goto done;
3791 err = print_tree(child_path, commit_id, show_ids, 1,
3792 root_path, repo);
3793 free(child_path);
3794 if (err)
3795 goto done;
3798 done:
3799 if (tree)
3800 got_object_tree_close(tree);
3801 free(tree_id);
3802 return err;
3805 static const struct got_error *
3806 cmd_tree(int argc, char *argv[])
3808 const struct got_error *error;
3809 struct got_repository *repo = NULL;
3810 struct got_worktree *worktree = NULL;
3811 const char *path;
3812 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
3813 struct got_object_id *commit_id = NULL;
3814 char *commit_id_str = NULL;
3815 int show_ids = 0, recurse = 0;
3816 int ch;
3818 #ifndef PROFILE
3819 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3820 NULL) == -1)
3821 err(1, "pledge");
3822 #endif
3824 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
3825 switch (ch) {
3826 case 'c':
3827 commit_id_str = optarg;
3828 break;
3829 case 'r':
3830 repo_path = realpath(optarg, NULL);
3831 if (repo_path == NULL)
3832 return got_error_from_errno2("realpath",
3833 optarg);
3834 got_path_strip_trailing_slashes(repo_path);
3835 break;
3836 case 'i':
3837 show_ids = 1;
3838 break;
3839 case 'R':
3840 recurse = 1;
3841 break;
3842 default:
3843 usage_tree();
3844 /* NOTREACHED */
3848 argc -= optind;
3849 argv += optind;
3851 if (argc == 1)
3852 path = argv[0];
3853 else if (argc > 1)
3854 usage_tree();
3855 else
3856 path = NULL;
3858 cwd = getcwd(NULL, 0);
3859 if (cwd == NULL) {
3860 error = got_error_from_errno("getcwd");
3861 goto done;
3863 if (repo_path == NULL) {
3864 error = got_worktree_open(&worktree, cwd);
3865 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3866 goto done;
3867 else
3868 error = NULL;
3869 if (worktree) {
3870 repo_path =
3871 strdup(got_worktree_get_repo_path(worktree));
3872 if (repo_path == NULL)
3873 error = got_error_from_errno("strdup");
3874 if (error)
3875 goto done;
3876 } else {
3877 repo_path = strdup(cwd);
3878 if (repo_path == NULL) {
3879 error = got_error_from_errno("strdup");
3880 goto done;
3885 error = got_repo_open(&repo, repo_path, NULL);
3886 if (error != NULL)
3887 goto done;
3889 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
3890 if (error)
3891 goto done;
3893 if (path == NULL) {
3894 if (worktree) {
3895 char *p, *worktree_subdir = cwd +
3896 strlen(got_worktree_get_root_path(worktree));
3897 if (asprintf(&p, "%s/%s",
3898 got_worktree_get_path_prefix(worktree),
3899 worktree_subdir) == -1) {
3900 error = got_error_from_errno("asprintf");
3901 goto done;
3903 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3904 free(p);
3905 if (error)
3906 goto done;
3907 } else
3908 path = "/";
3910 if (in_repo_path == NULL) {
3911 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3912 if (error != NULL)
3913 goto done;
3916 if (commit_id_str == NULL) {
3917 struct got_reference *head_ref;
3918 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
3919 if (error != NULL)
3920 goto done;
3921 error = got_ref_resolve(&commit_id, repo, head_ref);
3922 got_ref_close(head_ref);
3923 if (error != NULL)
3924 goto done;
3925 } else {
3926 error = got_repo_match_object_id(&commit_id, NULL,
3927 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
3928 if (error)
3929 goto done;
3932 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
3933 in_repo_path, repo);
3934 done:
3935 free(in_repo_path);
3936 free(repo_path);
3937 free(cwd);
3938 free(commit_id);
3939 if (worktree)
3940 got_worktree_close(worktree);
3941 if (repo) {
3942 const struct got_error *repo_error;
3943 repo_error = got_repo_close(repo);
3944 if (error == NULL)
3945 error = repo_error;
3947 return error;
3950 __dead static void
3951 usage_status(void)
3953 fprintf(stderr, "usage: %s status [path ...]\n", getprogname());
3954 exit(1);
3957 static const struct got_error *
3958 print_status(void *arg, unsigned char status, unsigned char staged_status,
3959 const char *path, struct got_object_id *blob_id,
3960 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3961 int dirfd, const char *de_name)
3963 if (status == staged_status && (status == GOT_STATUS_DELETE))
3964 status = GOT_STATUS_NO_CHANGE;
3965 printf("%c%c %s\n", status, staged_status, path);
3966 return NULL;
3969 static const struct got_error *
3970 cmd_status(int argc, char *argv[])
3972 const struct got_error *error = NULL;
3973 struct got_repository *repo = NULL;
3974 struct got_worktree *worktree = NULL;
3975 char *cwd = NULL;
3976 struct got_pathlist_head paths;
3977 struct got_pathlist_entry *pe;
3978 int ch;
3980 TAILQ_INIT(&paths);
3982 while ((ch = getopt(argc, argv, "")) != -1) {
3983 switch (ch) {
3984 default:
3985 usage_status();
3986 /* NOTREACHED */
3990 argc -= optind;
3991 argv += optind;
3993 #ifndef PROFILE
3994 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3995 NULL) == -1)
3996 err(1, "pledge");
3997 #endif
3998 cwd = getcwd(NULL, 0);
3999 if (cwd == NULL) {
4000 error = got_error_from_errno("getcwd");
4001 goto done;
4004 error = got_worktree_open(&worktree, cwd);
4005 if (error != NULL)
4006 goto done;
4008 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4009 NULL);
4010 if (error != NULL)
4011 goto done;
4013 error = apply_unveil(got_repo_get_path(repo), 1,
4014 got_worktree_get_root_path(worktree));
4015 if (error)
4016 goto done;
4018 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
4019 if (error)
4020 goto done;
4022 error = got_worktree_status(worktree, &paths, repo, print_status, NULL,
4023 check_cancelled, NULL);
4024 done:
4025 TAILQ_FOREACH(pe, &paths, entry)
4026 free((char *)pe->path);
4027 got_pathlist_free(&paths);
4028 free(cwd);
4029 return error;
4032 __dead static void
4033 usage_ref(void)
4035 fprintf(stderr,
4036 "usage: %s ref [-r repository] -l | -d name | [-s] name target\n",
4037 getprogname());
4038 exit(1);
4041 static const struct got_error *
4042 list_refs(struct got_repository *repo)
4044 static const struct got_error *err = NULL;
4045 struct got_reflist_head refs;
4046 struct got_reflist_entry *re;
4048 SIMPLEQ_INIT(&refs);
4049 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4050 if (err)
4051 return err;
4053 SIMPLEQ_FOREACH(re, &refs, entry) {
4054 char *refstr;
4055 refstr = got_ref_to_str(re->ref);
4056 if (refstr == NULL)
4057 return got_error_from_errno("got_ref_to_str");
4058 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
4059 free(refstr);
4062 got_ref_list_free(&refs);
4063 return NULL;
4066 static const struct got_error *
4067 delete_ref(struct got_repository *repo, const char *refname)
4069 const struct got_error *err = NULL;
4070 struct got_reference *ref;
4072 err = got_ref_open(&ref, repo, refname, 0);
4073 if (err)
4074 return err;
4076 err = got_ref_delete(ref, repo);
4077 got_ref_close(ref);
4078 return err;
4081 static const struct got_error *
4082 add_ref(struct got_repository *repo, const char *refname, const char *target)
4084 const struct got_error *err = NULL;
4085 struct got_object_id *id;
4086 struct got_reference *ref = NULL;
4089 * Don't let the user create a reference name with a leading '-'.
4090 * While technically a valid reference name, this case is usually
4091 * an unintended typo.
4093 if (refname[0] == '-')
4094 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4096 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
4097 repo);
4098 if (err) {
4099 struct got_reference *target_ref;
4101 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
4102 return err;
4103 err = got_ref_open(&target_ref, repo, target, 0);
4104 if (err)
4105 return err;
4106 err = got_ref_resolve(&id, repo, target_ref);
4107 got_ref_close(target_ref);
4108 if (err)
4109 return err;
4112 err = got_ref_alloc(&ref, refname, id);
4113 if (err)
4114 goto done;
4116 err = got_ref_write(ref, repo);
4117 done:
4118 if (ref)
4119 got_ref_close(ref);
4120 free(id);
4121 return err;
4124 static const struct got_error *
4125 add_symref(struct got_repository *repo, const char *refname, const char *target)
4127 const struct got_error *err = NULL;
4128 struct got_reference *ref = NULL;
4129 struct got_reference *target_ref = NULL;
4132 * Don't let the user create a reference name with a leading '-'.
4133 * While technically a valid reference name, this case is usually
4134 * an unintended typo.
4136 if (refname[0] == '-')
4137 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4139 err = got_ref_open(&target_ref, repo, target, 0);
4140 if (err)
4141 return err;
4143 err = got_ref_alloc_symref(&ref, refname, target_ref);
4144 if (err)
4145 goto done;
4147 err = got_ref_write(ref, repo);
4148 done:
4149 if (target_ref)
4150 got_ref_close(target_ref);
4151 if (ref)
4152 got_ref_close(ref);
4153 return err;
4156 static const struct got_error *
4157 cmd_ref(int argc, char *argv[])
4159 const struct got_error *error = NULL;
4160 struct got_repository *repo = NULL;
4161 struct got_worktree *worktree = NULL;
4162 char *cwd = NULL, *repo_path = NULL;
4163 int ch, do_list = 0, create_symref = 0;
4164 const char *delref = NULL;
4166 /* TODO: Add -s option for adding symbolic references. */
4167 while ((ch = getopt(argc, argv, "d:r:ls")) != -1) {
4168 switch (ch) {
4169 case 'd':
4170 delref = optarg;
4171 break;
4172 case 'r':
4173 repo_path = realpath(optarg, NULL);
4174 if (repo_path == NULL)
4175 return got_error_from_errno2("realpath",
4176 optarg);
4177 got_path_strip_trailing_slashes(repo_path);
4178 break;
4179 case 'l':
4180 do_list = 1;
4181 break;
4182 case 's':
4183 create_symref = 1;
4184 break;
4185 default:
4186 usage_ref();
4187 /* NOTREACHED */
4191 if (do_list && delref)
4192 errx(1, "-l and -d options are mutually exclusive\n");
4194 argc -= optind;
4195 argv += optind;
4197 if (do_list || delref) {
4198 if (create_symref)
4199 errx(1, "-s option cannot be used together with the "
4200 "-l or -d options");
4201 if (argc > 0)
4202 usage_ref();
4203 } else if (argc != 2)
4204 usage_ref();
4206 #ifndef PROFILE
4207 if (do_list) {
4208 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4209 NULL) == -1)
4210 err(1, "pledge");
4211 } else {
4212 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4213 "sendfd unveil", NULL) == -1)
4214 err(1, "pledge");
4216 #endif
4217 cwd = getcwd(NULL, 0);
4218 if (cwd == NULL) {
4219 error = got_error_from_errno("getcwd");
4220 goto done;
4223 if (repo_path == NULL) {
4224 error = got_worktree_open(&worktree, cwd);
4225 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4226 goto done;
4227 else
4228 error = NULL;
4229 if (worktree) {
4230 repo_path =
4231 strdup(got_worktree_get_repo_path(worktree));
4232 if (repo_path == NULL)
4233 error = got_error_from_errno("strdup");
4234 if (error)
4235 goto done;
4236 } else {
4237 repo_path = strdup(cwd);
4238 if (repo_path == NULL) {
4239 error = got_error_from_errno("strdup");
4240 goto done;
4245 error = got_repo_open(&repo, repo_path, NULL);
4246 if (error != NULL)
4247 goto done;
4249 error = apply_unveil(got_repo_get_path(repo), do_list,
4250 worktree ? got_worktree_get_root_path(worktree) : NULL);
4251 if (error)
4252 goto done;
4254 if (do_list)
4255 error = list_refs(repo);
4256 else if (delref)
4257 error = delete_ref(repo, delref);
4258 else if (create_symref)
4259 error = add_symref(repo, argv[0], argv[1]);
4260 else
4261 error = add_ref(repo, argv[0], argv[1]);
4262 done:
4263 if (repo)
4264 got_repo_close(repo);
4265 if (worktree)
4266 got_worktree_close(worktree);
4267 free(cwd);
4268 free(repo_path);
4269 return error;
4272 __dead static void
4273 usage_branch(void)
4275 fprintf(stderr,
4276 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
4277 "[name]\n", getprogname());
4278 exit(1);
4281 static const struct got_error *
4282 list_branch(struct got_repository *repo, struct got_worktree *worktree,
4283 struct got_reference *ref)
4285 const struct got_error *err = NULL;
4286 const char *refname, *marker = " ";
4287 char *refstr;
4289 refname = got_ref_get_name(ref);
4290 if (worktree && strcmp(refname,
4291 got_worktree_get_head_ref_name(worktree)) == 0) {
4292 struct got_object_id *id = NULL;
4294 err = got_ref_resolve(&id, repo, ref);
4295 if (err)
4296 return err;
4297 if (got_object_id_cmp(id,
4298 got_worktree_get_base_commit_id(worktree)) == 0)
4299 marker = "* ";
4300 else
4301 marker = "~ ";
4302 free(id);
4305 if (strncmp(refname, "refs/heads/", 11) == 0)
4306 refname += 11;
4307 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4308 refname += 18;
4310 refstr = got_ref_to_str(ref);
4311 if (refstr == NULL)
4312 return got_error_from_errno("got_ref_to_str");
4314 printf("%s%s: %s\n", marker, refname, refstr);
4315 free(refstr);
4316 return NULL;
4319 static const struct got_error *
4320 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
4322 const char *refname;
4324 if (worktree == NULL)
4325 return got_error(GOT_ERR_NOT_WORKTREE);
4327 refname = got_worktree_get_head_ref_name(worktree);
4329 if (strncmp(refname, "refs/heads/", 11) == 0)
4330 refname += 11;
4331 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4332 refname += 18;
4334 printf("%s\n", refname);
4336 return NULL;
4339 static const struct got_error *
4340 list_branches(struct got_repository *repo, struct got_worktree *worktree)
4342 static const struct got_error *err = NULL;
4343 struct got_reflist_head refs;
4344 struct got_reflist_entry *re;
4345 struct got_reference *temp_ref = NULL;
4346 int rebase_in_progress, histedit_in_progress;
4348 SIMPLEQ_INIT(&refs);
4350 if (worktree) {
4351 err = got_worktree_rebase_in_progress(&rebase_in_progress,
4352 worktree);
4353 if (err)
4354 return err;
4356 err = got_worktree_histedit_in_progress(&histedit_in_progress,
4357 worktree);
4358 if (err)
4359 return err;
4361 if (rebase_in_progress || histedit_in_progress) {
4362 err = got_ref_open(&temp_ref, repo,
4363 got_worktree_get_head_ref_name(worktree), 0);
4364 if (err)
4365 return err;
4366 list_branch(repo, worktree, temp_ref);
4367 got_ref_close(temp_ref);
4371 err = got_ref_list(&refs, repo, "refs/heads",
4372 got_ref_cmp_by_name, NULL);
4373 if (err)
4374 return err;
4376 SIMPLEQ_FOREACH(re, &refs, entry)
4377 list_branch(repo, worktree, re->ref);
4379 got_ref_list_free(&refs);
4380 return NULL;
4383 static const struct got_error *
4384 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
4385 const char *branch_name)
4387 const struct got_error *err = NULL;
4388 struct got_reference *ref = NULL;
4389 char *refname;
4391 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
4392 return got_error_from_errno("asprintf");
4394 err = got_ref_open(&ref, repo, refname, 0);
4395 if (err)
4396 goto done;
4398 if (worktree &&
4399 strcmp(got_worktree_get_head_ref_name(worktree),
4400 got_ref_get_name(ref)) == 0) {
4401 err = got_error_msg(GOT_ERR_SAME_BRANCH,
4402 "will not delete this work tree's current branch");
4403 goto done;
4406 err = got_ref_delete(ref, repo);
4407 done:
4408 if (ref)
4409 got_ref_close(ref);
4410 free(refname);
4411 return err;
4414 static const struct got_error *
4415 add_branch(struct got_repository *repo, const char *branch_name,
4416 struct got_object_id *base_commit_id)
4418 const struct got_error *err = NULL;
4419 struct got_reference *ref = NULL;
4420 char *base_refname = NULL, *refname = NULL;
4423 * Don't let the user create a branch name with a leading '-'.
4424 * While technically a valid reference name, this case is usually
4425 * an unintended typo.
4427 if (branch_name[0] == '-')
4428 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
4430 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
4431 err = got_error_from_errno("asprintf");
4432 goto done;
4435 err = got_ref_open(&ref, repo, refname, 0);
4436 if (err == NULL) {
4437 err = got_error(GOT_ERR_BRANCH_EXISTS);
4438 goto done;
4439 } else if (err->code != GOT_ERR_NOT_REF)
4440 goto done;
4442 err = got_ref_alloc(&ref, refname, base_commit_id);
4443 if (err)
4444 goto done;
4446 err = got_ref_write(ref, repo);
4447 done:
4448 if (ref)
4449 got_ref_close(ref);
4450 free(base_refname);
4451 free(refname);
4452 return err;
4455 static const struct got_error *
4456 cmd_branch(int argc, char *argv[])
4458 const struct got_error *error = NULL;
4459 struct got_repository *repo = NULL;
4460 struct got_worktree *worktree = NULL;
4461 char *cwd = NULL, *repo_path = NULL;
4462 int ch, do_list = 0, do_show = 0, do_update = 1;
4463 const char *delref = NULL, *commit_id_arg = NULL;
4464 struct got_reference *ref = NULL;
4465 struct got_pathlist_head paths;
4466 struct got_pathlist_entry *pe;
4467 struct got_object_id *commit_id = NULL;
4468 char *commit_id_str = NULL;
4470 TAILQ_INIT(&paths);
4472 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
4473 switch (ch) {
4474 case 'c':
4475 commit_id_arg = optarg;
4476 break;
4477 case 'd':
4478 delref = optarg;
4479 break;
4480 case 'r':
4481 repo_path = realpath(optarg, NULL);
4482 if (repo_path == NULL)
4483 return got_error_from_errno2("realpath",
4484 optarg);
4485 got_path_strip_trailing_slashes(repo_path);
4486 break;
4487 case 'l':
4488 do_list = 1;
4489 break;
4490 case 'n':
4491 do_update = 0;
4492 break;
4493 default:
4494 usage_branch();
4495 /* NOTREACHED */
4499 if (do_list && delref)
4500 errx(1, "-l and -d options are mutually exclusive\n");
4502 argc -= optind;
4503 argv += optind;
4505 if (!do_list && !delref && argc == 0)
4506 do_show = 1;
4508 if ((do_list || delref || do_show) && commit_id_arg != NULL)
4509 errx(1, "-c option can only be used when creating a branch");
4511 if (do_list || delref) {
4512 if (argc > 0)
4513 usage_branch();
4514 } else if (!do_show && argc != 1)
4515 usage_branch();
4517 #ifndef PROFILE
4518 if (do_list || do_show) {
4519 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4520 NULL) == -1)
4521 err(1, "pledge");
4522 } else {
4523 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4524 "sendfd unveil", NULL) == -1)
4525 err(1, "pledge");
4527 #endif
4528 cwd = getcwd(NULL, 0);
4529 if (cwd == NULL) {
4530 error = got_error_from_errno("getcwd");
4531 goto done;
4534 if (repo_path == NULL) {
4535 error = got_worktree_open(&worktree, cwd);
4536 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4537 goto done;
4538 else
4539 error = NULL;
4540 if (worktree) {
4541 repo_path =
4542 strdup(got_worktree_get_repo_path(worktree));
4543 if (repo_path == NULL)
4544 error = got_error_from_errno("strdup");
4545 if (error)
4546 goto done;
4547 } else {
4548 repo_path = strdup(cwd);
4549 if (repo_path == NULL) {
4550 error = got_error_from_errno("strdup");
4551 goto done;
4556 error = got_repo_open(&repo, repo_path, NULL);
4557 if (error != NULL)
4558 goto done;
4560 error = apply_unveil(got_repo_get_path(repo), do_list,
4561 worktree ? got_worktree_get_root_path(worktree) : NULL);
4562 if (error)
4563 goto done;
4565 if (do_show)
4566 error = show_current_branch(repo, worktree);
4567 else if (do_list)
4568 error = list_branches(repo, worktree);
4569 else if (delref)
4570 error = delete_branch(repo, worktree, delref);
4571 else {
4572 if (commit_id_arg == NULL)
4573 commit_id_arg = worktree ?
4574 got_worktree_get_head_ref_name(worktree) :
4575 GOT_REF_HEAD;
4576 error = got_repo_match_object_id(&commit_id, NULL,
4577 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
4578 if (error)
4579 goto done;
4580 error = add_branch(repo, argv[0], commit_id);
4581 if (error)
4582 goto done;
4583 if (worktree && do_update) {
4584 int did_something = 0;
4585 char *branch_refname = NULL;
4587 error = got_object_id_str(&commit_id_str, commit_id);
4588 if (error)
4589 goto done;
4590 error = get_worktree_paths_from_argv(&paths, 0, NULL,
4591 worktree);
4592 if (error)
4593 goto done;
4594 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
4595 == -1) {
4596 error = got_error_from_errno("asprintf");
4597 goto done;
4599 error = got_ref_open(&ref, repo, branch_refname, 0);
4600 free(branch_refname);
4601 if (error)
4602 goto done;
4603 error = switch_head_ref(ref, commit_id, worktree,
4604 repo);
4605 if (error)
4606 goto done;
4607 error = got_worktree_set_base_commit_id(worktree, repo,
4608 commit_id);
4609 if (error)
4610 goto done;
4611 error = got_worktree_checkout_files(worktree, &paths,
4612 repo, update_progress, &did_something,
4613 check_cancelled, NULL);
4614 if (error)
4615 goto done;
4616 if (did_something)
4617 printf("Updated to commit %s\n", commit_id_str);
4620 done:
4621 if (ref)
4622 got_ref_close(ref);
4623 if (repo)
4624 got_repo_close(repo);
4625 if (worktree)
4626 got_worktree_close(worktree);
4627 free(cwd);
4628 free(repo_path);
4629 free(commit_id);
4630 free(commit_id_str);
4631 TAILQ_FOREACH(pe, &paths, entry)
4632 free((char *)pe->path);
4633 got_pathlist_free(&paths);
4634 return error;
4638 __dead static void
4639 usage_tag(void)
4641 fprintf(stderr,
4642 "usage: %s tag [-c commit] [-r repository] [-l] "
4643 "[-m message] name\n", getprogname());
4644 exit(1);
4647 #if 0
4648 static const struct got_error *
4649 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
4651 const struct got_error *err = NULL;
4652 struct got_reflist_entry *re, *se, *new;
4653 struct got_object_id *re_id, *se_id;
4654 struct got_tag_object *re_tag, *se_tag;
4655 time_t re_time, se_time;
4657 SIMPLEQ_FOREACH(re, tags, entry) {
4658 se = SIMPLEQ_FIRST(sorted);
4659 if (se == NULL) {
4660 err = got_reflist_entry_dup(&new, re);
4661 if (err)
4662 return err;
4663 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
4664 continue;
4665 } else {
4666 err = got_ref_resolve(&re_id, repo, re->ref);
4667 if (err)
4668 break;
4669 err = got_object_open_as_tag(&re_tag, repo, re_id);
4670 free(re_id);
4671 if (err)
4672 break;
4673 re_time = got_object_tag_get_tagger_time(re_tag);
4674 got_object_tag_close(re_tag);
4677 while (se) {
4678 err = got_ref_resolve(&se_id, repo, re->ref);
4679 if (err)
4680 break;
4681 err = got_object_open_as_tag(&se_tag, repo, se_id);
4682 free(se_id);
4683 if (err)
4684 break;
4685 se_time = got_object_tag_get_tagger_time(se_tag);
4686 got_object_tag_close(se_tag);
4688 if (se_time > re_time) {
4689 err = got_reflist_entry_dup(&new, re);
4690 if (err)
4691 return err;
4692 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
4693 break;
4695 se = SIMPLEQ_NEXT(se, entry);
4696 continue;
4699 done:
4700 return err;
4702 #endif
4704 static const struct got_error *
4705 list_tags(struct got_repository *repo, struct got_worktree *worktree)
4707 static const struct got_error *err = NULL;
4708 struct got_reflist_head refs;
4709 struct got_reflist_entry *re;
4711 SIMPLEQ_INIT(&refs);
4713 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
4714 if (err)
4715 return err;
4717 SIMPLEQ_FOREACH(re, &refs, entry) {
4718 const char *refname;
4719 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
4720 char datebuf[26];
4721 const char *tagger;
4722 time_t tagger_time;
4723 struct got_object_id *id;
4724 struct got_tag_object *tag;
4725 struct got_commit_object *commit = NULL;
4727 refname = got_ref_get_name(re->ref);
4728 if (strncmp(refname, "refs/tags/", 10) != 0)
4729 continue;
4730 refname += 10;
4731 refstr = got_ref_to_str(re->ref);
4732 if (refstr == NULL) {
4733 err = got_error_from_errno("got_ref_to_str");
4734 break;
4736 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
4737 free(refstr);
4739 err = got_ref_resolve(&id, repo, re->ref);
4740 if (err)
4741 break;
4742 err = got_object_open_as_tag(&tag, repo, id);
4743 if (err) {
4744 if (err->code != GOT_ERR_OBJ_TYPE) {
4745 free(id);
4746 break;
4748 /* "lightweight" tag */
4749 err = got_object_open_as_commit(&commit, repo, id);
4750 if (err) {
4751 free(id);
4752 break;
4754 tagger = got_object_commit_get_committer(commit);
4755 tagger_time =
4756 got_object_commit_get_committer_time(commit);
4757 err = got_object_id_str(&id_str, id);
4758 free(id);
4759 if (err)
4760 break;
4761 } else {
4762 free(id);
4763 tagger = got_object_tag_get_tagger(tag);
4764 tagger_time = got_object_tag_get_tagger_time(tag);
4765 err = got_object_id_str(&id_str,
4766 got_object_tag_get_object_id(tag));
4767 if (err)
4768 break;
4770 printf("from: %s\n", tagger);
4771 datestr = get_datestr(&tagger_time, datebuf);
4772 if (datestr)
4773 printf("date: %s UTC\n", datestr);
4774 if (commit)
4775 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
4776 else {
4777 switch (got_object_tag_get_object_type(tag)) {
4778 case GOT_OBJ_TYPE_BLOB:
4779 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
4780 id_str);
4781 break;
4782 case GOT_OBJ_TYPE_TREE:
4783 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
4784 id_str);
4785 break;
4786 case GOT_OBJ_TYPE_COMMIT:
4787 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
4788 id_str);
4789 break;
4790 case GOT_OBJ_TYPE_TAG:
4791 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
4792 id_str);
4793 break;
4794 default:
4795 break;
4798 free(id_str);
4799 if (commit) {
4800 err = got_object_commit_get_logmsg(&tagmsg0, commit);
4801 if (err)
4802 break;
4803 got_object_commit_close(commit);
4804 } else {
4805 tagmsg0 = strdup(got_object_tag_get_message(tag));
4806 got_object_tag_close(tag);
4807 if (tagmsg0 == NULL) {
4808 err = got_error_from_errno("strdup");
4809 break;
4813 tagmsg = tagmsg0;
4814 do {
4815 line = strsep(&tagmsg, "\n");
4816 if (line)
4817 printf(" %s\n", line);
4818 } while (line);
4819 free(tagmsg0);
4822 got_ref_list_free(&refs);
4823 return NULL;
4826 static const struct got_error *
4827 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
4828 const char *tag_name, const char *repo_path)
4830 const struct got_error *err = NULL;
4831 char *template = NULL, *initial_content = NULL;
4832 char *editor = NULL;
4833 int fd = -1;
4835 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
4836 err = got_error_from_errno("asprintf");
4837 goto done;
4840 if (asprintf(&initial_content, "\n# tagging commit %s as %s\n",
4841 commit_id_str, tag_name) == -1) {
4842 err = got_error_from_errno("asprintf");
4843 goto done;
4846 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
4847 if (err)
4848 goto done;
4850 dprintf(fd, initial_content);
4851 close(fd);
4853 err = get_editor(&editor);
4854 if (err)
4855 goto done;
4856 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
4857 done:
4858 free(initial_content);
4859 free(template);
4860 free(editor);
4862 /* Editor is done; we can now apply unveil(2) */
4863 if (err == NULL) {
4864 err = apply_unveil(repo_path, 0, NULL);
4865 if (err) {
4866 free(*tagmsg);
4867 *tagmsg = NULL;
4870 return err;
4873 static const struct got_error *
4874 add_tag(struct got_repository *repo, const char *tag_name,
4875 const char *commit_arg, const char *tagmsg_arg)
4877 const struct got_error *err = NULL;
4878 struct got_object_id *commit_id = NULL, *tag_id = NULL;
4879 char *label = NULL, *commit_id_str = NULL;
4880 struct got_reference *ref = NULL;
4881 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
4882 char *tagmsg_path = NULL, *tag_id_str = NULL;
4883 int preserve_tagmsg = 0;
4886 * Don't let the user create a tag name with a leading '-'.
4887 * While technically a valid reference name, this case is usually
4888 * an unintended typo.
4890 if (tag_name[0] == '-')
4891 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
4893 err = get_author(&tagger, repo);
4894 if (err)
4895 return err;
4897 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
4898 GOT_OBJ_TYPE_COMMIT, 1, repo);
4899 if (err)
4900 goto done;
4902 err = got_object_id_str(&commit_id_str, commit_id);
4903 if (err)
4904 goto done;
4906 if (strncmp("refs/tags/", tag_name, 10) == 0) {
4907 refname = strdup(tag_name);
4908 if (refname == NULL) {
4909 err = got_error_from_errno("strdup");
4910 goto done;
4912 tag_name += 10;
4913 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
4914 err = got_error_from_errno("asprintf");
4915 goto done;
4918 err = got_ref_open(&ref, repo, refname, 0);
4919 if (err == NULL) {
4920 err = got_error(GOT_ERR_TAG_EXISTS);
4921 goto done;
4922 } else if (err->code != GOT_ERR_NOT_REF)
4923 goto done;
4925 if (tagmsg_arg == NULL) {
4926 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
4927 tag_name, got_repo_get_path(repo));
4928 if (err) {
4929 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
4930 tagmsg_path != NULL)
4931 preserve_tagmsg = 1;
4932 goto done;
4936 err = got_object_tag_create(&tag_id, tag_name, commit_id,
4937 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
4938 if (err) {
4939 if (tagmsg_path)
4940 preserve_tagmsg = 1;
4941 goto done;
4944 err = got_ref_alloc(&ref, refname, tag_id);
4945 if (err) {
4946 if (tagmsg_path)
4947 preserve_tagmsg = 1;
4948 goto done;
4951 err = got_ref_write(ref, repo);
4952 if (err) {
4953 if (tagmsg_path)
4954 preserve_tagmsg = 1;
4955 goto done;
4958 err = got_object_id_str(&tag_id_str, tag_id);
4959 if (err) {
4960 if (tagmsg_path)
4961 preserve_tagmsg = 1;
4962 goto done;
4964 printf("Created tag %s\n", tag_id_str);
4965 done:
4966 if (preserve_tagmsg) {
4967 fprintf(stderr, "%s: tag message preserved in %s\n",
4968 getprogname(), tagmsg_path);
4969 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
4970 err = got_error_from_errno2("unlink", tagmsg_path);
4971 free(tag_id_str);
4972 if (ref)
4973 got_ref_close(ref);
4974 free(commit_id);
4975 free(commit_id_str);
4976 free(refname);
4977 free(tagmsg);
4978 free(tagmsg_path);
4979 free(tagger);
4980 return err;
4983 static const struct got_error *
4984 cmd_tag(int argc, char *argv[])
4986 const struct got_error *error = NULL;
4987 struct got_repository *repo = NULL;
4988 struct got_worktree *worktree = NULL;
4989 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
4990 char *gitconfig_path = NULL;
4991 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
4992 int ch, do_list = 0;
4994 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
4995 switch (ch) {
4996 case 'c':
4997 commit_id_arg = optarg;
4998 break;
4999 case 'm':
5000 tagmsg = optarg;
5001 break;
5002 case 'r':
5003 repo_path = realpath(optarg, NULL);
5004 if (repo_path == NULL)
5005 return got_error_from_errno2("realpath",
5006 optarg);
5007 got_path_strip_trailing_slashes(repo_path);
5008 break;
5009 case 'l':
5010 do_list = 1;
5011 break;
5012 default:
5013 usage_tag();
5014 /* NOTREACHED */
5018 argc -= optind;
5019 argv += optind;
5021 if (do_list) {
5022 if (commit_id_arg != NULL)
5023 errx(1, "-c option can only be used when creating a tag");
5024 if (tagmsg)
5025 errx(1, "-l and -m options are mutually exclusive");
5026 if (argc > 0)
5027 usage_tag();
5028 } else if (argc != 1)
5029 usage_tag();
5031 tag_name = argv[0];
5033 #ifndef PROFILE
5034 if (do_list) {
5035 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5036 NULL) == -1)
5037 err(1, "pledge");
5038 } else {
5039 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5040 "sendfd unveil", NULL) == -1)
5041 err(1, "pledge");
5043 #endif
5044 cwd = getcwd(NULL, 0);
5045 if (cwd == NULL) {
5046 error = got_error_from_errno("getcwd");
5047 goto done;
5050 if (repo_path == NULL) {
5051 error = got_worktree_open(&worktree, cwd);
5052 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5053 goto done;
5054 else
5055 error = NULL;
5056 if (worktree) {
5057 repo_path =
5058 strdup(got_worktree_get_repo_path(worktree));
5059 if (repo_path == NULL)
5060 error = got_error_from_errno("strdup");
5061 if (error)
5062 goto done;
5063 } else {
5064 repo_path = strdup(cwd);
5065 if (repo_path == NULL) {
5066 error = got_error_from_errno("strdup");
5067 goto done;
5072 if (do_list) {
5073 error = got_repo_open(&repo, repo_path, NULL);
5074 if (error != NULL)
5075 goto done;
5076 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5077 if (error)
5078 goto done;
5079 error = list_tags(repo, worktree);
5080 } else {
5081 error = get_gitconfig_path(&gitconfig_path);
5082 if (error)
5083 goto done;
5084 error = got_repo_open(&repo, repo_path, gitconfig_path);
5085 if (error != NULL)
5086 goto done;
5088 if (tagmsg) {
5089 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5090 if (error)
5091 goto done;
5094 if (commit_id_arg == NULL) {
5095 struct got_reference *head_ref;
5096 struct got_object_id *commit_id;
5097 error = got_ref_open(&head_ref, repo,
5098 worktree ? got_worktree_get_head_ref_name(worktree)
5099 : GOT_REF_HEAD, 0);
5100 if (error)
5101 goto done;
5102 error = got_ref_resolve(&commit_id, repo, head_ref);
5103 got_ref_close(head_ref);
5104 if (error)
5105 goto done;
5106 error = got_object_id_str(&commit_id_str, commit_id);
5107 free(commit_id);
5108 if (error)
5109 goto done;
5112 error = add_tag(repo, tag_name,
5113 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
5115 done:
5116 if (repo)
5117 got_repo_close(repo);
5118 if (worktree)
5119 got_worktree_close(worktree);
5120 free(cwd);
5121 free(repo_path);
5122 free(gitconfig_path);
5123 free(commit_id_str);
5124 return error;
5127 __dead static void
5128 usage_add(void)
5130 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
5131 getprogname());
5132 exit(1);
5135 static const struct got_error *
5136 add_progress(void *arg, unsigned char status, const char *path)
5138 while (path[0] == '/')
5139 path++;
5140 printf("%c %s\n", status, path);
5141 return NULL;
5144 static const struct got_error *
5145 cmd_add(int argc, char *argv[])
5147 const struct got_error *error = NULL;
5148 struct got_repository *repo = NULL;
5149 struct got_worktree *worktree = NULL;
5150 char *cwd = NULL;
5151 struct got_pathlist_head paths;
5152 struct got_pathlist_entry *pe;
5153 int ch, can_recurse = 0, no_ignores = 0;
5155 TAILQ_INIT(&paths);
5157 while ((ch = getopt(argc, argv, "IR")) != -1) {
5158 switch (ch) {
5159 case 'I':
5160 no_ignores = 1;
5161 break;
5162 case 'R':
5163 can_recurse = 1;
5164 break;
5165 default:
5166 usage_add();
5167 /* NOTREACHED */
5171 argc -= optind;
5172 argv += optind;
5174 #ifndef PROFILE
5175 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5176 NULL) == -1)
5177 err(1, "pledge");
5178 #endif
5179 if (argc < 1)
5180 usage_add();
5182 cwd = getcwd(NULL, 0);
5183 if (cwd == NULL) {
5184 error = got_error_from_errno("getcwd");
5185 goto done;
5188 error = got_worktree_open(&worktree, cwd);
5189 if (error)
5190 goto done;
5192 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5193 NULL);
5194 if (error != NULL)
5195 goto done;
5197 error = apply_unveil(got_repo_get_path(repo), 1,
5198 got_worktree_get_root_path(worktree));
5199 if (error)
5200 goto done;
5202 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5203 if (error)
5204 goto done;
5206 if (!can_recurse && no_ignores) {
5207 error = got_error_msg(GOT_ERR_BAD_PATH,
5208 "disregarding ignores requires -R option");
5209 goto done;
5213 if (!can_recurse) {
5214 char *ondisk_path;
5215 struct stat sb;
5216 TAILQ_FOREACH(pe, &paths, entry) {
5217 if (asprintf(&ondisk_path, "%s/%s",
5218 got_worktree_get_root_path(worktree),
5219 pe->path) == -1) {
5220 error = got_error_from_errno("asprintf");
5221 goto done;
5223 if (lstat(ondisk_path, &sb) == -1) {
5224 if (errno == ENOENT) {
5225 free(ondisk_path);
5226 continue;
5228 error = got_error_from_errno2("lstat",
5229 ondisk_path);
5230 free(ondisk_path);
5231 goto done;
5233 free(ondisk_path);
5234 if (S_ISDIR(sb.st_mode)) {
5235 error = got_error_msg(GOT_ERR_BAD_PATH,
5236 "adding directories requires -R option");
5237 goto done;
5242 error = got_worktree_schedule_add(worktree, &paths, add_progress,
5243 NULL, repo, no_ignores);
5244 done:
5245 if (repo)
5246 got_repo_close(repo);
5247 if (worktree)
5248 got_worktree_close(worktree);
5249 TAILQ_FOREACH(pe, &paths, entry)
5250 free((char *)pe->path);
5251 got_pathlist_free(&paths);
5252 free(cwd);
5253 return error;
5256 __dead static void
5257 usage_remove(void)
5259 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] path ...\n",
5260 getprogname());
5261 exit(1);
5264 static const struct got_error *
5265 print_remove_status(void *arg, unsigned char status,
5266 unsigned char staged_status, const char *path)
5268 while (path[0] == '/')
5269 path++;
5270 if (status == GOT_STATUS_NONEXISTENT)
5271 return NULL;
5272 if (status == staged_status && (status == GOT_STATUS_DELETE))
5273 status = GOT_STATUS_NO_CHANGE;
5274 printf("%c%c %s\n", status, staged_status, path);
5275 return NULL;
5278 static const struct got_error *
5279 cmd_remove(int argc, char *argv[])
5281 const struct got_error *error = NULL;
5282 struct got_worktree *worktree = NULL;
5283 struct got_repository *repo = NULL;
5284 char *cwd = NULL;
5285 struct got_pathlist_head paths;
5286 struct got_pathlist_entry *pe;
5287 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0;
5289 TAILQ_INIT(&paths);
5291 while ((ch = getopt(argc, argv, "fkR")) != -1) {
5292 switch (ch) {
5293 case 'f':
5294 delete_local_mods = 1;
5295 break;
5296 case 'k':
5297 keep_on_disk = 1;
5298 break;
5299 case 'R':
5300 can_recurse = 1;
5301 break;
5302 default:
5303 usage_remove();
5304 /* NOTREACHED */
5308 argc -= optind;
5309 argv += optind;
5311 #ifndef PROFILE
5312 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5313 NULL) == -1)
5314 err(1, "pledge");
5315 #endif
5316 if (argc < 1)
5317 usage_remove();
5319 cwd = getcwd(NULL, 0);
5320 if (cwd == NULL) {
5321 error = got_error_from_errno("getcwd");
5322 goto done;
5324 error = got_worktree_open(&worktree, cwd);
5325 if (error)
5326 goto done;
5328 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5329 NULL);
5330 if (error)
5331 goto done;
5333 error = apply_unveil(got_repo_get_path(repo), 1,
5334 got_worktree_get_root_path(worktree));
5335 if (error)
5336 goto done;
5338 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5339 if (error)
5340 goto done;
5342 if (!can_recurse) {
5343 char *ondisk_path;
5344 struct stat sb;
5345 TAILQ_FOREACH(pe, &paths, entry) {
5346 if (asprintf(&ondisk_path, "%s/%s",
5347 got_worktree_get_root_path(worktree),
5348 pe->path) == -1) {
5349 error = got_error_from_errno("asprintf");
5350 goto done;
5352 if (lstat(ondisk_path, &sb) == -1) {
5353 if (errno == ENOENT) {
5354 free(ondisk_path);
5355 continue;
5357 error = got_error_from_errno2("lstat",
5358 ondisk_path);
5359 free(ondisk_path);
5360 goto done;
5362 free(ondisk_path);
5363 if (S_ISDIR(sb.st_mode)) {
5364 error = got_error_msg(GOT_ERR_BAD_PATH,
5365 "removing directories requires -R option");
5366 goto done;
5371 error = got_worktree_schedule_delete(worktree, &paths,
5372 delete_local_mods, print_remove_status, NULL, repo, keep_on_disk);
5373 done:
5374 if (repo)
5375 got_repo_close(repo);
5376 if (worktree)
5377 got_worktree_close(worktree);
5378 TAILQ_FOREACH(pe, &paths, entry)
5379 free((char *)pe->path);
5380 got_pathlist_free(&paths);
5381 free(cwd);
5382 return error;
5385 __dead static void
5386 usage_revert(void)
5388 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
5389 "path ...\n", getprogname());
5390 exit(1);
5393 static const struct got_error *
5394 revert_progress(void *arg, unsigned char status, const char *path)
5396 if (status == GOT_STATUS_UNVERSIONED)
5397 return NULL;
5399 while (path[0] == '/')
5400 path++;
5401 printf("%c %s\n", status, path);
5402 return NULL;
5405 struct choose_patch_arg {
5406 FILE *patch_script_file;
5407 const char *action;
5410 static const struct got_error *
5411 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
5412 int nchanges, const char *action)
5414 char *line = NULL;
5415 size_t linesize = 0;
5416 ssize_t linelen;
5418 switch (status) {
5419 case GOT_STATUS_ADD:
5420 printf("A %s\n%s this addition? [y/n] ", path, action);
5421 break;
5422 case GOT_STATUS_DELETE:
5423 printf("D %s\n%s this deletion? [y/n] ", path, action);
5424 break;
5425 case GOT_STATUS_MODIFY:
5426 if (fseek(patch_file, 0L, SEEK_SET) == -1)
5427 return got_error_from_errno("fseek");
5428 printf(GOT_COMMIT_SEP_STR);
5429 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
5430 printf("%s", line);
5431 if (ferror(patch_file))
5432 return got_error_from_errno("getline");
5433 printf(GOT_COMMIT_SEP_STR);
5434 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
5435 path, n, nchanges, action);
5436 break;
5437 default:
5438 return got_error_path(path, GOT_ERR_FILE_STATUS);
5441 return NULL;
5444 static const struct got_error *
5445 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
5446 FILE *patch_file, int n, int nchanges)
5448 const struct got_error *err = NULL;
5449 char *line = NULL;
5450 size_t linesize = 0;
5451 ssize_t linelen;
5452 int resp = ' ';
5453 struct choose_patch_arg *a = arg;
5455 *choice = GOT_PATCH_CHOICE_NONE;
5457 if (a->patch_script_file) {
5458 char *nl;
5459 err = show_change(status, path, patch_file, n, nchanges,
5460 a->action);
5461 if (err)
5462 return err;
5463 linelen = getline(&line, &linesize, a->patch_script_file);
5464 if (linelen == -1) {
5465 if (ferror(a->patch_script_file))
5466 return got_error_from_errno("getline");
5467 return NULL;
5469 nl = strchr(line, '\n');
5470 if (nl)
5471 *nl = '\0';
5472 if (strcmp(line, "y") == 0) {
5473 *choice = GOT_PATCH_CHOICE_YES;
5474 printf("y\n");
5475 } else if (strcmp(line, "n") == 0) {
5476 *choice = GOT_PATCH_CHOICE_NO;
5477 printf("n\n");
5478 } else if (strcmp(line, "q") == 0 &&
5479 status == GOT_STATUS_MODIFY) {
5480 *choice = GOT_PATCH_CHOICE_QUIT;
5481 printf("q\n");
5482 } else
5483 printf("invalid response '%s'\n", line);
5484 free(line);
5485 return NULL;
5488 while (resp != 'y' && resp != 'n' && resp != 'q') {
5489 err = show_change(status, path, patch_file, n, nchanges,
5490 a->action);
5491 if (err)
5492 return err;
5493 resp = getchar();
5494 if (resp == '\n')
5495 resp = getchar();
5496 if (status == GOT_STATUS_MODIFY) {
5497 if (resp != 'y' && resp != 'n' && resp != 'q') {
5498 printf("invalid response '%c'\n", resp);
5499 resp = ' ';
5501 } else if (resp != 'y' && resp != 'n') {
5502 printf("invalid response '%c'\n", resp);
5503 resp = ' ';
5507 if (resp == 'y')
5508 *choice = GOT_PATCH_CHOICE_YES;
5509 else if (resp == 'n')
5510 *choice = GOT_PATCH_CHOICE_NO;
5511 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
5512 *choice = GOT_PATCH_CHOICE_QUIT;
5514 return NULL;
5518 static const struct got_error *
5519 cmd_revert(int argc, char *argv[])
5521 const struct got_error *error = NULL;
5522 struct got_worktree *worktree = NULL;
5523 struct got_repository *repo = NULL;
5524 char *cwd = NULL, *path = NULL;
5525 struct got_pathlist_head paths;
5526 struct got_pathlist_entry *pe;
5527 int ch, can_recurse = 0, pflag = 0;
5528 FILE *patch_script_file = NULL;
5529 const char *patch_script_path = NULL;
5530 struct choose_patch_arg cpa;
5532 TAILQ_INIT(&paths);
5534 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
5535 switch (ch) {
5536 case 'p':
5537 pflag = 1;
5538 break;
5539 case 'F':
5540 patch_script_path = optarg;
5541 break;
5542 case 'R':
5543 can_recurse = 1;
5544 break;
5545 default:
5546 usage_revert();
5547 /* NOTREACHED */
5551 argc -= optind;
5552 argv += optind;
5554 #ifndef PROFILE
5555 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
5556 "unveil", NULL) == -1)
5557 err(1, "pledge");
5558 #endif
5559 if (argc < 1)
5560 usage_revert();
5561 if (patch_script_path && !pflag)
5562 errx(1, "-F option can only be used together with -p option");
5564 cwd = getcwd(NULL, 0);
5565 if (cwd == NULL) {
5566 error = got_error_from_errno("getcwd");
5567 goto done;
5569 error = got_worktree_open(&worktree, cwd);
5570 if (error)
5571 goto done;
5573 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5574 NULL);
5575 if (error != NULL)
5576 goto done;
5578 if (patch_script_path) {
5579 patch_script_file = fopen(patch_script_path, "r");
5580 if (patch_script_file == NULL) {
5581 error = got_error_from_errno2("fopen",
5582 patch_script_path);
5583 goto done;
5586 error = apply_unveil(got_repo_get_path(repo), 1,
5587 got_worktree_get_root_path(worktree));
5588 if (error)
5589 goto done;
5591 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5592 if (error)
5593 goto done;
5595 if (!can_recurse) {
5596 char *ondisk_path;
5597 struct stat sb;
5598 TAILQ_FOREACH(pe, &paths, entry) {
5599 if (asprintf(&ondisk_path, "%s/%s",
5600 got_worktree_get_root_path(worktree),
5601 pe->path) == -1) {
5602 error = got_error_from_errno("asprintf");
5603 goto done;
5605 if (lstat(ondisk_path, &sb) == -1) {
5606 if (errno == ENOENT) {
5607 free(ondisk_path);
5608 continue;
5610 error = got_error_from_errno2("lstat",
5611 ondisk_path);
5612 free(ondisk_path);
5613 goto done;
5615 free(ondisk_path);
5616 if (S_ISDIR(sb.st_mode)) {
5617 error = got_error_msg(GOT_ERR_BAD_PATH,
5618 "reverting directories requires -R option");
5619 goto done;
5624 cpa.patch_script_file = patch_script_file;
5625 cpa.action = "revert";
5626 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
5627 pflag ? choose_patch : NULL, &cpa, repo);
5628 done:
5629 if (patch_script_file && fclose(patch_script_file) == EOF &&
5630 error == NULL)
5631 error = got_error_from_errno2("fclose", patch_script_path);
5632 if (repo)
5633 got_repo_close(repo);
5634 if (worktree)
5635 got_worktree_close(worktree);
5636 free(path);
5637 free(cwd);
5638 return error;
5641 __dead static void
5642 usage_commit(void)
5644 fprintf(stderr, "usage: %s commit [-m msg] [path ...]\n",
5645 getprogname());
5646 exit(1);
5649 struct collect_commit_logmsg_arg {
5650 const char *cmdline_log;
5651 const char *editor;
5652 const char *worktree_path;
5653 const char *branch_name;
5654 const char *repo_path;
5655 char *logmsg_path;
5659 static const struct got_error *
5660 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
5661 void *arg)
5663 char *initial_content = NULL;
5664 struct got_pathlist_entry *pe;
5665 const struct got_error *err = NULL;
5666 char *template = NULL;
5667 struct collect_commit_logmsg_arg *a = arg;
5668 int fd;
5669 size_t len;
5671 /* if a message was specified on the command line, just use it */
5672 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
5673 len = strlen(a->cmdline_log) + 1;
5674 *logmsg = malloc(len + 1);
5675 if (*logmsg == NULL)
5676 return got_error_from_errno("malloc");
5677 strlcpy(*logmsg, a->cmdline_log, len);
5678 return NULL;
5681 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
5682 return got_error_from_errno("asprintf");
5684 if (asprintf(&initial_content,
5685 "\n# changes to be committed on branch %s:\n",
5686 a->branch_name) == -1)
5687 return got_error_from_errno("asprintf");
5689 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
5690 if (err)
5691 goto done;
5693 dprintf(fd, initial_content);
5695 TAILQ_FOREACH(pe, commitable_paths, entry) {
5696 struct got_commitable *ct = pe->data;
5697 dprintf(fd, "# %c %s\n",
5698 got_commitable_get_status(ct),
5699 got_commitable_get_path(ct));
5701 close(fd);
5703 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
5704 done:
5705 free(initial_content);
5706 free(template);
5708 /* Editor is done; we can now apply unveil(2) */
5709 if (err == NULL) {
5710 err = apply_unveil(a->repo_path, 0, a->worktree_path);
5711 if (err) {
5712 free(*logmsg);
5713 *logmsg = NULL;
5716 return err;
5719 static const struct got_error *
5720 cmd_commit(int argc, char *argv[])
5722 const struct got_error *error = NULL;
5723 struct got_worktree *worktree = NULL;
5724 struct got_repository *repo = NULL;
5725 char *cwd = NULL, *id_str = NULL;
5726 struct got_object_id *id = NULL;
5727 const char *logmsg = NULL;
5728 struct collect_commit_logmsg_arg cl_arg;
5729 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
5730 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
5731 struct got_pathlist_head paths;
5733 TAILQ_INIT(&paths);
5734 cl_arg.logmsg_path = NULL;
5736 while ((ch = getopt(argc, argv, "m:")) != -1) {
5737 switch (ch) {
5738 case 'm':
5739 logmsg = optarg;
5740 break;
5741 default:
5742 usage_commit();
5743 /* NOTREACHED */
5747 argc -= optind;
5748 argv += optind;
5750 #ifndef PROFILE
5751 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
5752 "unveil", NULL) == -1)
5753 err(1, "pledge");
5754 #endif
5755 cwd = getcwd(NULL, 0);
5756 if (cwd == NULL) {
5757 error = got_error_from_errno("getcwd");
5758 goto done;
5760 error = got_worktree_open(&worktree, cwd);
5761 if (error)
5762 goto done;
5764 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
5765 if (error)
5766 goto done;
5767 if (rebase_in_progress) {
5768 error = got_error(GOT_ERR_REBASING);
5769 goto done;
5772 error = got_worktree_histedit_in_progress(&histedit_in_progress,
5773 worktree);
5774 if (error)
5775 goto done;
5777 error = get_gitconfig_path(&gitconfig_path);
5778 if (error)
5779 goto done;
5780 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5781 gitconfig_path);
5782 if (error != NULL)
5783 goto done;
5785 error = get_author(&author, repo);
5786 if (error)
5787 return error;
5790 * unveil(2) traverses exec(2); if an editor is used we have
5791 * to apply unveil after the log message has been written.
5793 if (logmsg == NULL || strlen(logmsg) == 0)
5794 error = get_editor(&editor);
5795 else
5796 error = apply_unveil(got_repo_get_path(repo), 0,
5797 got_worktree_get_root_path(worktree));
5798 if (error)
5799 goto done;
5801 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5802 if (error)
5803 goto done;
5805 cl_arg.editor = editor;
5806 cl_arg.cmdline_log = logmsg;
5807 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
5808 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
5809 if (!histedit_in_progress) {
5810 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
5811 error = got_error(GOT_ERR_COMMIT_BRANCH);
5812 goto done;
5814 cl_arg.branch_name += 11;
5816 cl_arg.repo_path = got_repo_get_path(repo);
5817 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
5818 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
5819 if (error) {
5820 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5821 cl_arg.logmsg_path != NULL)
5822 preserve_logmsg = 1;
5823 goto done;
5826 error = got_object_id_str(&id_str, id);
5827 if (error)
5828 goto done;
5829 printf("Created commit %s\n", id_str);
5830 done:
5831 if (preserve_logmsg) {
5832 fprintf(stderr, "%s: log message preserved in %s\n",
5833 getprogname(), cl_arg.logmsg_path);
5834 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
5835 error == NULL)
5836 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
5837 free(cl_arg.logmsg_path);
5838 if (repo)
5839 got_repo_close(repo);
5840 if (worktree)
5841 got_worktree_close(worktree);
5842 free(cwd);
5843 free(id_str);
5844 free(gitconfig_path);
5845 free(editor);
5846 free(author);
5847 return error;
5850 __dead static void
5851 usage_cherrypick(void)
5853 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
5854 exit(1);
5857 static const struct got_error *
5858 cmd_cherrypick(int argc, char *argv[])
5860 const struct got_error *error = NULL;
5861 struct got_worktree *worktree = NULL;
5862 struct got_repository *repo = NULL;
5863 char *cwd = NULL, *commit_id_str = NULL;
5864 struct got_object_id *commit_id = NULL;
5865 struct got_commit_object *commit = NULL;
5866 struct got_object_qid *pid;
5867 struct got_reference *head_ref = NULL;
5868 int ch, did_something = 0;
5870 while ((ch = getopt(argc, argv, "")) != -1) {
5871 switch (ch) {
5872 default:
5873 usage_cherrypick();
5874 /* NOTREACHED */
5878 argc -= optind;
5879 argv += optind;
5881 #ifndef PROFILE
5882 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
5883 "unveil", NULL) == -1)
5884 err(1, "pledge");
5885 #endif
5886 if (argc != 1)
5887 usage_cherrypick();
5889 cwd = getcwd(NULL, 0);
5890 if (cwd == NULL) {
5891 error = got_error_from_errno("getcwd");
5892 goto done;
5894 error = got_worktree_open(&worktree, cwd);
5895 if (error)
5896 goto done;
5898 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5899 NULL);
5900 if (error != NULL)
5901 goto done;
5903 error = apply_unveil(got_repo_get_path(repo), 0,
5904 got_worktree_get_root_path(worktree));
5905 if (error)
5906 goto done;
5908 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
5909 GOT_OBJ_TYPE_COMMIT, repo);
5910 if (error != NULL) {
5911 struct got_reference *ref;
5912 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
5913 goto done;
5914 error = got_ref_open(&ref, repo, argv[0], 0);
5915 if (error != NULL)
5916 goto done;
5917 error = got_ref_resolve(&commit_id, repo, ref);
5918 got_ref_close(ref);
5919 if (error != NULL)
5920 goto done;
5922 error = got_object_id_str(&commit_id_str, commit_id);
5923 if (error)
5924 goto done;
5926 error = got_ref_open(&head_ref, repo,
5927 got_worktree_get_head_ref_name(worktree), 0);
5928 if (error != NULL)
5929 goto done;
5931 error = check_same_branch(commit_id, head_ref, NULL, repo);
5932 if (error) {
5933 if (error->code != GOT_ERR_ANCESTRY)
5934 goto done;
5935 error = NULL;
5936 } else {
5937 error = got_error(GOT_ERR_SAME_BRANCH);
5938 goto done;
5941 error = got_object_open_as_commit(&commit, repo, commit_id);
5942 if (error)
5943 goto done;
5944 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
5945 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
5946 commit_id, repo, update_progress, &did_something, check_cancelled,
5947 NULL);
5948 if (error != NULL)
5949 goto done;
5951 if (did_something)
5952 printf("Merged commit %s\n", commit_id_str);
5953 done:
5954 if (commit)
5955 got_object_commit_close(commit);
5956 free(commit_id_str);
5957 if (head_ref)
5958 got_ref_close(head_ref);
5959 if (worktree)
5960 got_worktree_close(worktree);
5961 if (repo)
5962 got_repo_close(repo);
5963 return error;
5966 __dead static void
5967 usage_backout(void)
5969 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
5970 exit(1);
5973 static const struct got_error *
5974 cmd_backout(int argc, char *argv[])
5976 const struct got_error *error = NULL;
5977 struct got_worktree *worktree = NULL;
5978 struct got_repository *repo = NULL;
5979 char *cwd = NULL, *commit_id_str = NULL;
5980 struct got_object_id *commit_id = NULL;
5981 struct got_commit_object *commit = NULL;
5982 struct got_object_qid *pid;
5983 struct got_reference *head_ref = NULL;
5984 int ch, did_something = 0;
5986 while ((ch = getopt(argc, argv, "")) != -1) {
5987 switch (ch) {
5988 default:
5989 usage_backout();
5990 /* NOTREACHED */
5994 argc -= optind;
5995 argv += optind;
5997 #ifndef PROFILE
5998 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
5999 "unveil", NULL) == -1)
6000 err(1, "pledge");
6001 #endif
6002 if (argc != 1)
6003 usage_backout();
6005 cwd = getcwd(NULL, 0);
6006 if (cwd == NULL) {
6007 error = got_error_from_errno("getcwd");
6008 goto done;
6010 error = got_worktree_open(&worktree, cwd);
6011 if (error)
6012 goto done;
6014 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6015 NULL);
6016 if (error != NULL)
6017 goto done;
6019 error = apply_unveil(got_repo_get_path(repo), 0,
6020 got_worktree_get_root_path(worktree));
6021 if (error)
6022 goto done;
6024 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6025 GOT_OBJ_TYPE_COMMIT, repo);
6026 if (error != NULL) {
6027 struct got_reference *ref;
6028 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6029 goto done;
6030 error = got_ref_open(&ref, repo, argv[0], 0);
6031 if (error != NULL)
6032 goto done;
6033 error = got_ref_resolve(&commit_id, repo, ref);
6034 got_ref_close(ref);
6035 if (error != NULL)
6036 goto done;
6038 error = got_object_id_str(&commit_id_str, commit_id);
6039 if (error)
6040 goto done;
6042 error = got_ref_open(&head_ref, repo,
6043 got_worktree_get_head_ref_name(worktree), 0);
6044 if (error != NULL)
6045 goto done;
6047 error = check_same_branch(commit_id, head_ref, NULL, repo);
6048 if (error)
6049 goto done;
6051 error = got_object_open_as_commit(&commit, repo, commit_id);
6052 if (error)
6053 goto done;
6054 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6055 if (pid == NULL) {
6056 error = got_error(GOT_ERR_ROOT_COMMIT);
6057 goto done;
6060 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
6061 update_progress, &did_something, check_cancelled, NULL);
6062 if (error != NULL)
6063 goto done;
6065 if (did_something)
6066 printf("Backed out commit %s\n", commit_id_str);
6067 done:
6068 if (commit)
6069 got_object_commit_close(commit);
6070 free(commit_id_str);
6071 if (head_ref)
6072 got_ref_close(head_ref);
6073 if (worktree)
6074 got_worktree_close(worktree);
6075 if (repo)
6076 got_repo_close(repo);
6077 return error;
6080 __dead static void
6081 usage_rebase(void)
6083 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
6084 getprogname());
6085 exit(1);
6088 void
6089 trim_logmsg(char *logmsg, int limit)
6091 char *nl;
6092 size_t len;
6094 len = strlen(logmsg);
6095 if (len > limit)
6096 len = limit;
6097 logmsg[len] = '\0';
6098 nl = strchr(logmsg, '\n');
6099 if (nl)
6100 *nl = '\0';
6103 static const struct got_error *
6104 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
6106 const struct got_error *err;
6107 char *logmsg0 = NULL;
6108 const char *s;
6110 err = got_object_commit_get_logmsg(&logmsg0, commit);
6111 if (err)
6112 return err;
6114 s = logmsg0;
6115 while (isspace((unsigned char)s[0]))
6116 s++;
6118 *logmsg = strdup(s);
6119 if (*logmsg == NULL) {
6120 err = got_error_from_errno("strdup");
6121 goto done;
6124 trim_logmsg(*logmsg, limit);
6125 done:
6126 free(logmsg0);
6127 return err;
6130 static const struct got_error *
6131 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
6133 const struct got_error *err;
6134 struct got_commit_object *commit = NULL;
6135 char *id_str = NULL, *logmsg = NULL;
6137 err = got_object_open_as_commit(&commit, repo, id);
6138 if (err)
6139 return err;
6141 err = got_object_id_str(&id_str, id);
6142 if (err)
6143 goto done;
6145 id_str[12] = '\0';
6147 err = get_short_logmsg(&logmsg, 42, commit);
6148 if (err)
6149 goto done;
6151 printf("%s -> merge conflict: %s\n", id_str, logmsg);
6152 done:
6153 free(id_str);
6154 got_object_commit_close(commit);
6155 free(logmsg);
6156 return err;
6159 static const struct got_error *
6160 show_rebase_progress(struct got_commit_object *commit,
6161 struct got_object_id *old_id, struct got_object_id *new_id)
6163 const struct got_error *err;
6164 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
6166 err = got_object_id_str(&old_id_str, old_id);
6167 if (err)
6168 goto done;
6170 if (new_id) {
6171 err = got_object_id_str(&new_id_str, new_id);
6172 if (err)
6173 goto done;
6176 old_id_str[12] = '\0';
6177 if (new_id_str)
6178 new_id_str[12] = '\0';
6180 err = get_short_logmsg(&logmsg, 42, commit);
6181 if (err)
6182 goto done;
6184 printf("%s -> %s: %s\n", old_id_str,
6185 new_id_str ? new_id_str : "no-op change", logmsg);
6186 done:
6187 free(old_id_str);
6188 free(new_id_str);
6189 free(logmsg);
6190 return err;
6193 static const struct got_error *
6194 rebase_progress(void *arg, unsigned char status, const char *path)
6196 unsigned char *rebase_status = arg;
6198 while (path[0] == '/')
6199 path++;
6200 printf("%c %s\n", status, path);
6202 if (*rebase_status == GOT_STATUS_CONFLICT)
6203 return NULL;
6204 if (status == GOT_STATUS_CONFLICT || status == GOT_STATUS_MERGE)
6205 *rebase_status = status;
6206 return NULL;
6209 static const struct got_error *
6210 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
6211 struct got_reference *branch, struct got_reference *new_base_branch,
6212 struct got_reference *tmp_branch, struct got_repository *repo)
6214 printf("Switching work tree to %s\n", got_ref_get_name(branch));
6215 return got_worktree_rebase_complete(worktree, fileindex,
6216 new_base_branch, tmp_branch, branch, repo);
6219 static const struct got_error *
6220 rebase_commit(struct got_pathlist_head *merged_paths,
6221 struct got_worktree *worktree, struct got_fileindex *fileindex,
6222 struct got_reference *tmp_branch,
6223 struct got_object_id *commit_id, struct got_repository *repo)
6225 const struct got_error *error;
6226 struct got_commit_object *commit;
6227 struct got_object_id *new_commit_id;
6229 error = got_object_open_as_commit(&commit, repo, commit_id);
6230 if (error)
6231 return error;
6233 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
6234 worktree, fileindex, tmp_branch, commit, commit_id, repo);
6235 if (error) {
6236 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
6237 goto done;
6238 error = show_rebase_progress(commit, commit_id, NULL);
6239 } else {
6240 error = show_rebase_progress(commit, commit_id, new_commit_id);
6241 free(new_commit_id);
6243 done:
6244 got_object_commit_close(commit);
6245 return error;
6248 struct check_path_prefix_arg {
6249 const char *path_prefix;
6250 size_t len;
6251 int errcode;
6254 static const struct got_error *
6255 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
6256 struct got_blob_object *blob2, struct got_object_id *id1,
6257 struct got_object_id *id2, const char *path1, const char *path2,
6258 mode_t mode1, mode_t mode2, struct got_repository *repo)
6260 struct check_path_prefix_arg *a = arg;
6262 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
6263 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
6264 return got_error(a->errcode);
6266 return NULL;
6269 static const struct got_error *
6270 check_path_prefix(struct got_object_id *parent_id,
6271 struct got_object_id *commit_id, const char *path_prefix,
6272 int errcode, struct got_repository *repo)
6274 const struct got_error *err;
6275 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
6276 struct got_commit_object *commit = NULL, *parent_commit = NULL;
6277 struct check_path_prefix_arg cpp_arg;
6279 if (got_path_is_root_dir(path_prefix))
6280 return NULL;
6282 err = got_object_open_as_commit(&commit, repo, commit_id);
6283 if (err)
6284 goto done;
6286 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
6287 if (err)
6288 goto done;
6290 err = got_object_open_as_tree(&tree1, repo,
6291 got_object_commit_get_tree_id(parent_commit));
6292 if (err)
6293 goto done;
6295 err = got_object_open_as_tree(&tree2, repo,
6296 got_object_commit_get_tree_id(commit));
6297 if (err)
6298 goto done;
6300 cpp_arg.path_prefix = path_prefix;
6301 while (cpp_arg.path_prefix[0] == '/')
6302 cpp_arg.path_prefix++;
6303 cpp_arg.len = strlen(cpp_arg.path_prefix);
6304 cpp_arg.errcode = errcode;
6305 err = got_diff_tree(tree1, tree2, "", "", repo,
6306 check_path_prefix_in_diff, &cpp_arg, 0);
6307 done:
6308 if (tree1)
6309 got_object_tree_close(tree1);
6310 if (tree2)
6311 got_object_tree_close(tree2);
6312 if (commit)
6313 got_object_commit_close(commit);
6314 if (parent_commit)
6315 got_object_commit_close(parent_commit);
6316 return err;
6319 static const struct got_error *
6320 collect_commits(struct got_object_id_queue *commits,
6321 struct got_object_id *initial_commit_id,
6322 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
6323 const char *path_prefix, int path_prefix_errcode,
6324 struct got_repository *repo)
6326 const struct got_error *err = NULL;
6327 struct got_commit_graph *graph = NULL;
6328 struct got_object_id *parent_id = NULL;
6329 struct got_object_qid *qid;
6330 struct got_object_id *commit_id = initial_commit_id;
6332 err = got_commit_graph_open(&graph, "/", 1);
6333 if (err)
6334 return err;
6336 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
6337 check_cancelled, NULL);
6338 if (err)
6339 goto done;
6340 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
6341 err = got_commit_graph_iter_next(&parent_id, graph, repo,
6342 check_cancelled, NULL);
6343 if (err) {
6344 if (err->code == GOT_ERR_ITER_COMPLETED) {
6345 err = got_error_msg(GOT_ERR_ANCESTRY,
6346 "ran out of commits to rebase before "
6347 "youngest common ancestor commit has "
6348 "been reached?!?");
6350 goto done;
6351 } else {
6352 err = check_path_prefix(parent_id, commit_id,
6353 path_prefix, path_prefix_errcode, repo);
6354 if (err)
6355 goto done;
6357 err = got_object_qid_alloc(&qid, commit_id);
6358 if (err)
6359 goto done;
6360 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
6361 commit_id = parent_id;
6364 done:
6365 got_commit_graph_close(graph);
6366 return err;
6369 static const struct got_error *
6370 cmd_rebase(int argc, char *argv[])
6372 const struct got_error *error = NULL;
6373 struct got_worktree *worktree = NULL;
6374 struct got_repository *repo = NULL;
6375 struct got_fileindex *fileindex = NULL;
6376 char *cwd = NULL;
6377 struct got_reference *branch = NULL;
6378 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
6379 struct got_object_id *commit_id = NULL, *parent_id = NULL;
6380 struct got_object_id *resume_commit_id = NULL;
6381 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
6382 struct got_commit_object *commit = NULL;
6383 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
6384 int histedit_in_progress = 0;
6385 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
6386 struct got_object_id_queue commits;
6387 struct got_pathlist_head merged_paths;
6388 const struct got_object_id_queue *parent_ids;
6389 struct got_object_qid *qid, *pid;
6391 SIMPLEQ_INIT(&commits);
6392 TAILQ_INIT(&merged_paths);
6394 while ((ch = getopt(argc, argv, "ac")) != -1) {
6395 switch (ch) {
6396 case 'a':
6397 abort_rebase = 1;
6398 break;
6399 case 'c':
6400 continue_rebase = 1;
6401 break;
6402 default:
6403 usage_rebase();
6404 /* NOTREACHED */
6408 argc -= optind;
6409 argv += optind;
6411 #ifndef PROFILE
6412 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6413 "unveil", NULL) == -1)
6414 err(1, "pledge");
6415 #endif
6416 if (abort_rebase && continue_rebase)
6417 usage_rebase();
6418 else if (abort_rebase || continue_rebase) {
6419 if (argc != 0)
6420 usage_rebase();
6421 } else if (argc != 1)
6422 usage_rebase();
6424 cwd = getcwd(NULL, 0);
6425 if (cwd == NULL) {
6426 error = got_error_from_errno("getcwd");
6427 goto done;
6429 error = got_worktree_open(&worktree, cwd);
6430 if (error)
6431 goto done;
6433 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6434 NULL);
6435 if (error != NULL)
6436 goto done;
6438 error = apply_unveil(got_repo_get_path(repo), 0,
6439 got_worktree_get_root_path(worktree));
6440 if (error)
6441 goto done;
6443 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6444 worktree);
6445 if (error)
6446 goto done;
6447 if (histedit_in_progress) {
6448 error = got_error(GOT_ERR_HISTEDIT_BUSY);
6449 goto done;
6452 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6453 if (error)
6454 goto done;
6456 if (abort_rebase) {
6457 int did_something;
6458 if (!rebase_in_progress) {
6459 error = got_error(GOT_ERR_NOT_REBASING);
6460 goto done;
6462 error = got_worktree_rebase_continue(&resume_commit_id,
6463 &new_base_branch, &tmp_branch, &branch, &fileindex,
6464 worktree, repo);
6465 if (error)
6466 goto done;
6467 printf("Switching work tree to %s\n",
6468 got_ref_get_symref_target(new_base_branch));
6469 error = got_worktree_rebase_abort(worktree, fileindex, repo,
6470 new_base_branch, update_progress, &did_something);
6471 if (error)
6472 goto done;
6473 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
6474 goto done; /* nothing else to do */
6477 if (continue_rebase) {
6478 if (!rebase_in_progress) {
6479 error = got_error(GOT_ERR_NOT_REBASING);
6480 goto done;
6482 error = got_worktree_rebase_continue(&resume_commit_id,
6483 &new_base_branch, &tmp_branch, &branch, &fileindex,
6484 worktree, repo);
6485 if (error)
6486 goto done;
6488 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
6489 resume_commit_id, repo);
6490 if (error)
6491 goto done;
6493 yca_id = got_object_id_dup(resume_commit_id);
6494 if (yca_id == NULL) {
6495 error = got_error_from_errno("got_object_id_dup");
6496 goto done;
6498 } else {
6499 error = got_ref_open(&branch, repo, argv[0], 0);
6500 if (error != NULL)
6501 goto done;
6504 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
6505 if (error)
6506 goto done;
6508 if (!continue_rebase) {
6509 struct got_object_id *base_commit_id;
6511 base_commit_id = got_worktree_get_base_commit_id(worktree);
6512 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
6513 base_commit_id, branch_head_commit_id, repo,
6514 check_cancelled, NULL);
6515 if (error)
6516 goto done;
6517 if (yca_id == NULL) {
6518 error = got_error_msg(GOT_ERR_ANCESTRY,
6519 "specified branch shares no common ancestry "
6520 "with work tree's branch");
6521 goto done;
6524 error = check_same_branch(base_commit_id, branch, yca_id, repo);
6525 if (error) {
6526 if (error->code != GOT_ERR_ANCESTRY)
6527 goto done;
6528 error = NULL;
6529 } else {
6530 error = got_error_msg(GOT_ERR_SAME_BRANCH,
6531 "specified branch resolves to a commit which "
6532 "is already contained in work tree's branch");
6533 goto done;
6535 error = got_worktree_rebase_prepare(&new_base_branch,
6536 &tmp_branch, &fileindex, worktree, branch, repo);
6537 if (error)
6538 goto done;
6541 commit_id = branch_head_commit_id;
6542 error = got_object_open_as_commit(&commit, repo, commit_id);
6543 if (error)
6544 goto done;
6546 parent_ids = got_object_commit_get_parent_ids(commit);
6547 pid = SIMPLEQ_FIRST(parent_ids);
6548 if (pid == NULL) {
6549 if (!continue_rebase) {
6550 int did_something;
6551 error = got_worktree_rebase_abort(worktree, fileindex,
6552 repo, new_base_branch, update_progress,
6553 &did_something);
6554 if (error)
6555 goto done;
6556 printf("Rebase of %s aborted\n",
6557 got_ref_get_name(branch));
6559 error = got_error(GOT_ERR_EMPTY_REBASE);
6560 goto done;
6562 error = collect_commits(&commits, commit_id, pid->id,
6563 yca_id, got_worktree_get_path_prefix(worktree),
6564 GOT_ERR_REBASE_PATH, repo);
6565 got_object_commit_close(commit);
6566 commit = NULL;
6567 if (error)
6568 goto done;
6570 if (SIMPLEQ_EMPTY(&commits)) {
6571 if (continue_rebase) {
6572 error = rebase_complete(worktree, fileindex,
6573 branch, new_base_branch, tmp_branch, repo);
6574 goto done;
6575 } else {
6576 /* Fast-forward the reference of the branch. */
6577 struct got_object_id *new_head_commit_id;
6578 char *id_str;
6579 error = got_ref_resolve(&new_head_commit_id, repo,
6580 new_base_branch);
6581 if (error)
6582 goto done;
6583 error = got_object_id_str(&id_str, new_head_commit_id);
6584 printf("Forwarding %s to commit %s\n",
6585 got_ref_get_name(branch), id_str);
6586 free(id_str);
6587 error = got_ref_change_ref(branch,
6588 new_head_commit_id);
6589 if (error)
6590 goto done;
6594 pid = NULL;
6595 SIMPLEQ_FOREACH(qid, &commits, entry) {
6596 commit_id = qid->id;
6597 parent_id = pid ? pid->id : yca_id;
6598 pid = qid;
6600 error = got_worktree_rebase_merge_files(&merged_paths,
6601 worktree, fileindex, parent_id, commit_id, repo,
6602 rebase_progress, &rebase_status, check_cancelled, NULL);
6603 if (error)
6604 goto done;
6606 if (rebase_status == GOT_STATUS_CONFLICT) {
6607 error = show_rebase_merge_conflict(qid->id, repo);
6608 if (error)
6609 goto done;
6610 got_worktree_rebase_pathlist_free(&merged_paths);
6611 break;
6614 error = rebase_commit(&merged_paths, worktree, fileindex,
6615 tmp_branch, commit_id, repo);
6616 got_worktree_rebase_pathlist_free(&merged_paths);
6617 if (error)
6618 goto done;
6621 if (rebase_status == GOT_STATUS_CONFLICT) {
6622 error = got_worktree_rebase_postpone(worktree, fileindex);
6623 if (error)
6624 goto done;
6625 error = got_error_msg(GOT_ERR_CONFLICTS,
6626 "conflicts must be resolved before rebasing can continue");
6627 } else
6628 error = rebase_complete(worktree, fileindex, branch,
6629 new_base_branch, tmp_branch, repo);
6630 done:
6631 got_object_id_queue_free(&commits);
6632 free(branch_head_commit_id);
6633 free(resume_commit_id);
6634 free(yca_id);
6635 if (commit)
6636 got_object_commit_close(commit);
6637 if (branch)
6638 got_ref_close(branch);
6639 if (new_base_branch)
6640 got_ref_close(new_base_branch);
6641 if (tmp_branch)
6642 got_ref_close(tmp_branch);
6643 if (worktree)
6644 got_worktree_close(worktree);
6645 if (repo)
6646 got_repo_close(repo);
6647 return error;
6650 __dead static void
6651 usage_histedit(void)
6653 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
6654 getprogname());
6655 exit(1);
6658 #define GOT_HISTEDIT_PICK 'p'
6659 #define GOT_HISTEDIT_EDIT 'e'
6660 #define GOT_HISTEDIT_FOLD 'f'
6661 #define GOT_HISTEDIT_DROP 'd'
6662 #define GOT_HISTEDIT_MESG 'm'
6664 static struct got_histedit_cmd {
6665 unsigned char code;
6666 const char *name;
6667 const char *desc;
6668 } got_histedit_cmds[] = {
6669 { GOT_HISTEDIT_PICK, "pick", "use commit" },
6670 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
6671 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
6672 "be used" },
6673 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
6674 { GOT_HISTEDIT_MESG, "mesg",
6675 "single-line log message for commit above (open editor if empty)" },
6678 struct got_histedit_list_entry {
6679 TAILQ_ENTRY(got_histedit_list_entry) entry;
6680 struct got_object_id *commit_id;
6681 const struct got_histedit_cmd *cmd;
6682 char *logmsg;
6684 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
6686 static const struct got_error *
6687 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
6688 FILE *f, struct got_repository *repo)
6690 const struct got_error *err = NULL;
6691 char *logmsg = NULL, *id_str = NULL;
6692 struct got_commit_object *commit = NULL;
6693 int n;
6695 err = got_object_open_as_commit(&commit, repo, commit_id);
6696 if (err)
6697 goto done;
6699 err = get_short_logmsg(&logmsg, 34, commit);
6700 if (err)
6701 goto done;
6703 err = got_object_id_str(&id_str, commit_id);
6704 if (err)
6705 goto done;
6707 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
6708 if (n < 0)
6709 err = got_ferror(f, GOT_ERR_IO);
6710 done:
6711 if (commit)
6712 got_object_commit_close(commit);
6713 free(id_str);
6714 free(logmsg);
6715 return err;
6718 static const struct got_error *
6719 histedit_write_commit_list(struct got_object_id_queue *commits,
6720 FILE *f, int edit_logmsg_only, struct got_repository *repo)
6722 const struct got_error *err = NULL;
6723 struct got_object_qid *qid;
6725 if (SIMPLEQ_EMPTY(commits))
6726 return got_error(GOT_ERR_EMPTY_HISTEDIT);
6728 SIMPLEQ_FOREACH(qid, commits, entry) {
6729 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
6730 f, repo);
6731 if (err)
6732 break;
6733 if (edit_logmsg_only) {
6734 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
6735 if (n < 0) {
6736 err = got_ferror(f, GOT_ERR_IO);
6737 break;
6742 return err;
6745 static const struct got_error *
6746 write_cmd_list(FILE *f, const char *branch_name,
6747 struct got_object_id_queue *commits)
6749 const struct got_error *err = NULL;
6750 int n, i;
6751 char *id_str;
6752 struct got_object_qid *qid;
6754 qid = SIMPLEQ_FIRST(commits);
6755 err = got_object_id_str(&id_str, qid->id);
6756 if (err)
6757 return err;
6759 n = fprintf(f,
6760 "# Editing the history of branch '%s' starting at\n"
6761 "# commit %s\n"
6762 "# Commits will be processed in order from top to "
6763 "bottom of this file.\n", branch_name, id_str);
6764 if (n < 0) {
6765 err = got_ferror(f, GOT_ERR_IO);
6766 goto done;
6769 n = fprintf(f, "# Available histedit commands:\n");
6770 if (n < 0) {
6771 err = got_ferror(f, GOT_ERR_IO);
6772 goto done;
6775 for (i = 0; i < nitems(got_histedit_cmds); i++) {
6776 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
6777 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
6778 cmd->desc);
6779 if (n < 0) {
6780 err = got_ferror(f, GOT_ERR_IO);
6781 break;
6784 done:
6785 free(id_str);
6786 return err;
6789 static const struct got_error *
6790 histedit_syntax_error(int lineno)
6792 static char msg[42];
6793 int ret;
6795 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
6796 lineno);
6797 if (ret == -1 || ret >= sizeof(msg))
6798 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
6800 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
6803 static const struct got_error *
6804 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
6805 char *logmsg, struct got_repository *repo)
6807 const struct got_error *err;
6808 struct got_commit_object *folded_commit = NULL;
6809 char *id_str, *folded_logmsg = NULL;
6811 err = got_object_id_str(&id_str, hle->commit_id);
6812 if (err)
6813 return err;
6815 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
6816 if (err)
6817 goto done;
6819 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
6820 if (err)
6821 goto done;
6822 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
6823 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
6824 folded_logmsg) == -1) {
6825 err = got_error_from_errno("asprintf");
6827 done:
6828 if (folded_commit)
6829 got_object_commit_close(folded_commit);
6830 free(id_str);
6831 free(folded_logmsg);
6832 return err;
6835 static struct got_histedit_list_entry *
6836 get_folded_commits(struct got_histedit_list_entry *hle)
6838 struct got_histedit_list_entry *prev, *folded = NULL;
6840 prev = TAILQ_PREV(hle, got_histedit_list, entry);
6841 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
6842 prev->cmd->code == GOT_HISTEDIT_DROP)) {
6843 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
6844 folded = prev;
6845 prev = TAILQ_PREV(prev, got_histedit_list, entry);
6848 return folded;
6851 static const struct got_error *
6852 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
6853 struct got_repository *repo)
6855 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
6856 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
6857 const struct got_error *err = NULL;
6858 struct got_commit_object *commit = NULL;
6859 int fd;
6860 struct got_histedit_list_entry *folded = NULL;
6862 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
6863 if (err)
6864 return err;
6866 folded = get_folded_commits(hle);
6867 if (folded) {
6868 while (folded != hle) {
6869 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
6870 folded = TAILQ_NEXT(folded, entry);
6871 continue;
6873 err = append_folded_commit_msg(&new_msg, folded,
6874 logmsg, repo);
6875 if (err)
6876 goto done;
6877 free(logmsg);
6878 logmsg = new_msg;
6879 folded = TAILQ_NEXT(folded, entry);
6883 err = got_object_id_str(&id_str, hle->commit_id);
6884 if (err)
6885 goto done;
6886 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
6887 if (err)
6888 goto done;
6889 if (asprintf(&new_msg,
6890 "%s\n# original log message of commit %s: %s",
6891 logmsg ? logmsg : "", id_str, orig_logmsg) == -1) {
6892 err = got_error_from_errno("asprintf");
6893 goto done;
6895 free(logmsg);
6896 logmsg = new_msg;
6898 err = got_object_id_str(&id_str, hle->commit_id);
6899 if (err)
6900 goto done;
6902 err = got_opentemp_named_fd(&logmsg_path, &fd,
6903 GOT_TMPDIR_STR "/got-logmsg");
6904 if (err)
6905 goto done;
6907 dprintf(fd, logmsg);
6908 close(fd);
6910 err = get_editor(&editor);
6911 if (err)
6912 goto done;
6914 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
6915 if (err) {
6916 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
6917 goto done;
6918 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
6920 done:
6921 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
6922 err = got_error_from_errno2("unlink", logmsg_path);
6923 free(logmsg_path);
6924 free(logmsg);
6925 free(orig_logmsg);
6926 free(editor);
6927 if (commit)
6928 got_object_commit_close(commit);
6929 return err;
6932 static const struct got_error *
6933 histedit_parse_list(struct got_histedit_list *histedit_cmds,
6934 FILE *f, struct got_repository *repo)
6936 const struct got_error *err = NULL;
6937 char *line = NULL, *p, *end;
6938 size_t size;
6939 ssize_t len;
6940 int lineno = 0, i;
6941 const struct got_histedit_cmd *cmd;
6942 struct got_object_id *commit_id = NULL;
6943 struct got_histedit_list_entry *hle = NULL;
6945 for (;;) {
6946 len = getline(&line, &size, f);
6947 if (len == -1) {
6948 const struct got_error *getline_err;
6949 if (feof(f))
6950 break;
6951 getline_err = got_error_from_errno("getline");
6952 err = got_ferror(f, getline_err->code);
6953 break;
6955 lineno++;
6956 p = line;
6957 while (isspace((unsigned char)p[0]))
6958 p++;
6959 if (p[0] == '#' || p[0] == '\0') {
6960 free(line);
6961 line = NULL;
6962 continue;
6964 cmd = NULL;
6965 for (i = 0; i < nitems(got_histedit_cmds); i++) {
6966 cmd = &got_histedit_cmds[i];
6967 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
6968 isspace((unsigned char)p[strlen(cmd->name)])) {
6969 p += strlen(cmd->name);
6970 break;
6972 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
6973 p++;
6974 break;
6977 if (i == nitems(got_histedit_cmds)) {
6978 err = histedit_syntax_error(lineno);
6979 break;
6981 while (isspace((unsigned char)p[0]))
6982 p++;
6983 if (cmd->code == GOT_HISTEDIT_MESG) {
6984 if (hle == NULL || hle->logmsg != NULL) {
6985 err = got_error(GOT_ERR_HISTEDIT_CMD);
6986 break;
6988 if (p[0] == '\0') {
6989 err = histedit_edit_logmsg(hle, repo);
6990 if (err)
6991 break;
6992 } else {
6993 hle->logmsg = strdup(p);
6994 if (hle->logmsg == NULL) {
6995 err = got_error_from_errno("strdup");
6996 break;
6999 free(line);
7000 line = NULL;
7001 continue;
7002 } else {
7003 end = p;
7004 while (end[0] && !isspace((unsigned char)end[0]))
7005 end++;
7006 *end = '\0';
7008 err = got_object_resolve_id_str(&commit_id, repo, p);
7009 if (err) {
7010 /* override error code */
7011 err = histedit_syntax_error(lineno);
7012 break;
7015 hle = malloc(sizeof(*hle));
7016 if (hle == NULL) {
7017 err = got_error_from_errno("malloc");
7018 break;
7020 hle->cmd = cmd;
7021 hle->commit_id = commit_id;
7022 hle->logmsg = NULL;
7023 commit_id = NULL;
7024 free(line);
7025 line = NULL;
7026 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
7029 free(line);
7030 free(commit_id);
7031 return err;
7034 static const struct got_error *
7035 histedit_check_script(struct got_histedit_list *histedit_cmds,
7036 struct got_object_id_queue *commits, struct got_repository *repo)
7038 const struct got_error *err = NULL;
7039 struct got_object_qid *qid;
7040 struct got_histedit_list_entry *hle;
7041 static char msg[92];
7042 char *id_str;
7044 if (TAILQ_EMPTY(histedit_cmds))
7045 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
7046 "histedit script contains no commands");
7047 if (SIMPLEQ_EMPTY(commits))
7048 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7050 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7051 struct got_histedit_list_entry *hle2;
7052 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
7053 if (hle == hle2)
7054 continue;
7055 if (got_object_id_cmp(hle->commit_id,
7056 hle2->commit_id) != 0)
7057 continue;
7058 err = got_object_id_str(&id_str, hle->commit_id);
7059 if (err)
7060 return err;
7061 snprintf(msg, sizeof(msg), "commit %s is listed "
7062 "more than once in histedit script", id_str);
7063 free(id_str);
7064 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7068 SIMPLEQ_FOREACH(qid, commits, entry) {
7069 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7070 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
7071 break;
7073 if (hle == NULL) {
7074 err = got_object_id_str(&id_str, qid->id);
7075 if (err)
7076 return err;
7077 snprintf(msg, sizeof(msg),
7078 "commit %s missing from histedit script", id_str);
7079 free(id_str);
7080 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7084 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
7085 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
7086 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
7087 "last commit in histedit script cannot be folded");
7089 return NULL;
7092 static const struct got_error *
7093 histedit_run_editor(struct got_histedit_list *histedit_cmds,
7094 const char *path, struct got_object_id_queue *commits,
7095 struct got_repository *repo)
7097 const struct got_error *err = NULL;
7098 char *editor;
7099 FILE *f = NULL;
7101 err = get_editor(&editor);
7102 if (err)
7103 return err;
7105 if (spawn_editor(editor, path) == -1) {
7106 err = got_error_from_errno("failed spawning editor");
7107 goto done;
7110 f = fopen(path, "r");
7111 if (f == NULL) {
7112 err = got_error_from_errno("fopen");
7113 goto done;
7115 err = histedit_parse_list(histedit_cmds, f, repo);
7116 if (err)
7117 goto done;
7119 err = histedit_check_script(histedit_cmds, commits, repo);
7120 done:
7121 if (f && fclose(f) != 0 && err == NULL)
7122 err = got_error_from_errno("fclose");
7123 free(editor);
7124 return err;
7127 static const struct got_error *
7128 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
7129 struct got_object_id_queue *, const char *, const char *,
7130 struct got_repository *);
7132 static const struct got_error *
7133 histedit_edit_script(struct got_histedit_list *histedit_cmds,
7134 struct got_object_id_queue *commits, const char *branch_name,
7135 int edit_logmsg_only, struct got_repository *repo)
7137 const struct got_error *err;
7138 FILE *f = NULL;
7139 char *path = NULL;
7141 err = got_opentemp_named(&path, &f, "got-histedit");
7142 if (err)
7143 return err;
7145 err = write_cmd_list(f, branch_name, commits);
7146 if (err)
7147 goto done;
7149 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
7150 if (err)
7151 goto done;
7153 if (edit_logmsg_only) {
7154 rewind(f);
7155 err = histedit_parse_list(histedit_cmds, f, repo);
7156 } else {
7157 if (fclose(f) != 0) {
7158 err = got_error_from_errno("fclose");
7159 goto done;
7161 f = NULL;
7162 err = histedit_run_editor(histedit_cmds, path, commits, repo);
7163 if (err) {
7164 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7165 err->code != GOT_ERR_HISTEDIT_CMD)
7166 goto done;
7167 err = histedit_edit_list_retry(histedit_cmds, err,
7168 commits, path, branch_name, repo);
7171 done:
7172 if (f && fclose(f) != 0 && err == NULL)
7173 err = got_error_from_errno("fclose");
7174 if (path && unlink(path) != 0 && err == NULL)
7175 err = got_error_from_errno2("unlink", path);
7176 free(path);
7177 return err;
7180 static const struct got_error *
7181 histedit_save_list(struct got_histedit_list *histedit_cmds,
7182 struct got_worktree *worktree, struct got_repository *repo)
7184 const struct got_error *err = NULL;
7185 char *path = NULL;
7186 FILE *f = NULL;
7187 struct got_histedit_list_entry *hle;
7188 struct got_commit_object *commit = NULL;
7190 err = got_worktree_get_histedit_script_path(&path, worktree);
7191 if (err)
7192 return err;
7194 f = fopen(path, "w");
7195 if (f == NULL) {
7196 err = got_error_from_errno2("fopen", path);
7197 goto done;
7199 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7200 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
7201 repo);
7202 if (err)
7203 break;
7205 if (hle->logmsg) {
7206 int n = fprintf(f, "%c %s\n",
7207 GOT_HISTEDIT_MESG, hle->logmsg);
7208 if (n < 0) {
7209 err = got_ferror(f, GOT_ERR_IO);
7210 break;
7214 done:
7215 if (f && fclose(f) != 0 && err == NULL)
7216 err = got_error_from_errno("fclose");
7217 free(path);
7218 if (commit)
7219 got_object_commit_close(commit);
7220 return err;
7223 void
7224 histedit_free_list(struct got_histedit_list *histedit_cmds)
7226 struct got_histedit_list_entry *hle;
7228 while ((hle = TAILQ_FIRST(histedit_cmds))) {
7229 TAILQ_REMOVE(histedit_cmds, hle, entry);
7230 free(hle);
7234 static const struct got_error *
7235 histedit_load_list(struct got_histedit_list *histedit_cmds,
7236 const char *path, struct got_repository *repo)
7238 const struct got_error *err = NULL;
7239 FILE *f = NULL;
7241 f = fopen(path, "r");
7242 if (f == NULL) {
7243 err = got_error_from_errno2("fopen", path);
7244 goto done;
7247 err = histedit_parse_list(histedit_cmds, f, repo);
7248 done:
7249 if (f && fclose(f) != 0 && err == NULL)
7250 err = got_error_from_errno("fclose");
7251 return err;
7254 static const struct got_error *
7255 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
7256 const struct got_error *edit_err, struct got_object_id_queue *commits,
7257 const char *path, const char *branch_name, struct got_repository *repo)
7259 const struct got_error *err = NULL, *prev_err = edit_err;
7260 int resp = ' ';
7262 while (resp != 'c' && resp != 'r' && resp != 'a') {
7263 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
7264 "or (a)bort: ", getprogname(), prev_err->msg);
7265 resp = getchar();
7266 if (resp == '\n')
7267 resp = getchar();
7268 if (resp == 'c') {
7269 histedit_free_list(histedit_cmds);
7270 err = histedit_run_editor(histedit_cmds, path, commits,
7271 repo);
7272 if (err) {
7273 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7274 err->code != GOT_ERR_HISTEDIT_CMD)
7275 break;
7276 prev_err = err;
7277 resp = ' ';
7278 continue;
7280 break;
7281 } else if (resp == 'r') {
7282 histedit_free_list(histedit_cmds);
7283 err = histedit_edit_script(histedit_cmds,
7284 commits, branch_name, 0, repo);
7285 if (err) {
7286 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7287 err->code != GOT_ERR_HISTEDIT_CMD)
7288 break;
7289 prev_err = err;
7290 resp = ' ';
7291 continue;
7293 break;
7294 } else if (resp == 'a') {
7295 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
7296 break;
7297 } else
7298 printf("invalid response '%c'\n", resp);
7301 return err;
7304 static const struct got_error *
7305 histedit_complete(struct got_worktree *worktree,
7306 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
7307 struct got_reference *branch, struct got_repository *repo)
7309 printf("Switching work tree to %s\n",
7310 got_ref_get_symref_target(branch));
7311 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
7312 branch, repo);
7315 static const struct got_error *
7316 show_histedit_progress(struct got_commit_object *commit,
7317 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
7319 const struct got_error *err;
7320 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7322 err = got_object_id_str(&old_id_str, hle->commit_id);
7323 if (err)
7324 goto done;
7326 if (new_id) {
7327 err = got_object_id_str(&new_id_str, new_id);
7328 if (err)
7329 goto done;
7332 old_id_str[12] = '\0';
7333 if (new_id_str)
7334 new_id_str[12] = '\0';
7336 if (hle->logmsg) {
7337 logmsg = strdup(hle->logmsg);
7338 if (logmsg == NULL) {
7339 err = got_error_from_errno("strdup");
7340 goto done;
7342 trim_logmsg(logmsg, 42);
7343 } else {
7344 err = get_short_logmsg(&logmsg, 42, commit);
7345 if (err)
7346 goto done;
7349 switch (hle->cmd->code) {
7350 case GOT_HISTEDIT_PICK:
7351 case GOT_HISTEDIT_EDIT:
7352 printf("%s -> %s: %s\n", old_id_str,
7353 new_id_str ? new_id_str : "no-op change", logmsg);
7354 break;
7355 case GOT_HISTEDIT_DROP:
7356 case GOT_HISTEDIT_FOLD:
7357 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
7358 logmsg);
7359 break;
7360 default:
7361 break;
7363 done:
7364 free(old_id_str);
7365 free(new_id_str);
7366 return err;
7369 static const struct got_error *
7370 histedit_commit(struct got_pathlist_head *merged_paths,
7371 struct got_worktree *worktree, struct got_fileindex *fileindex,
7372 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
7373 struct got_repository *repo)
7375 const struct got_error *err;
7376 struct got_commit_object *commit;
7377 struct got_object_id *new_commit_id;
7379 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
7380 && hle->logmsg == NULL) {
7381 err = histedit_edit_logmsg(hle, repo);
7382 if (err)
7383 return err;
7386 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7387 if (err)
7388 return err;
7390 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
7391 worktree, fileindex, tmp_branch, commit, hle->commit_id,
7392 hle->logmsg, repo);
7393 if (err) {
7394 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
7395 goto done;
7396 err = show_histedit_progress(commit, hle, NULL);
7397 } else {
7398 err = show_histedit_progress(commit, hle, new_commit_id);
7399 free(new_commit_id);
7401 done:
7402 got_object_commit_close(commit);
7403 return err;
7406 static const struct got_error *
7407 histedit_skip_commit(struct got_histedit_list_entry *hle,
7408 struct got_worktree *worktree, struct got_repository *repo)
7410 const struct got_error *error;
7411 struct got_commit_object *commit;
7413 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
7414 repo);
7415 if (error)
7416 return error;
7418 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
7419 if (error)
7420 return error;
7422 error = show_histedit_progress(commit, hle, NULL);
7423 got_object_commit_close(commit);
7424 return error;
7427 static const struct got_error *
7428 check_local_changes(void *arg, unsigned char status,
7429 unsigned char staged_status, const char *path,
7430 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
7431 struct got_object_id *commit_id, int dirfd, const char *de_name)
7433 int *have_local_changes = arg;
7435 switch (status) {
7436 case GOT_STATUS_ADD:
7437 case GOT_STATUS_DELETE:
7438 case GOT_STATUS_MODIFY:
7439 case GOT_STATUS_CONFLICT:
7440 *have_local_changes = 1;
7441 return got_error(GOT_ERR_CANCELLED);
7442 default:
7443 break;
7446 switch (staged_status) {
7447 case GOT_STATUS_ADD:
7448 case GOT_STATUS_DELETE:
7449 case GOT_STATUS_MODIFY:
7450 *have_local_changes = 1;
7451 return got_error(GOT_ERR_CANCELLED);
7452 default:
7453 break;
7456 return NULL;
7459 static const struct got_error *
7460 cmd_histedit(int argc, char *argv[])
7462 const struct got_error *error = NULL;
7463 struct got_worktree *worktree = NULL;
7464 struct got_fileindex *fileindex = NULL;
7465 struct got_repository *repo = NULL;
7466 char *cwd = NULL;
7467 struct got_reference *branch = NULL;
7468 struct got_reference *tmp_branch = NULL;
7469 struct got_object_id *resume_commit_id = NULL;
7470 struct got_object_id *base_commit_id = NULL;
7471 struct got_object_id *head_commit_id = NULL;
7472 struct got_commit_object *commit = NULL;
7473 int ch, rebase_in_progress = 0, did_something;
7474 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
7475 int edit_logmsg_only = 0;
7476 const char *edit_script_path = NULL;
7477 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7478 struct got_object_id_queue commits;
7479 struct got_pathlist_head merged_paths;
7480 const struct got_object_id_queue *parent_ids;
7481 struct got_object_qid *pid;
7482 struct got_histedit_list histedit_cmds;
7483 struct got_histedit_list_entry *hle;
7485 SIMPLEQ_INIT(&commits);
7486 TAILQ_INIT(&histedit_cmds);
7487 TAILQ_INIT(&merged_paths);
7489 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
7490 switch (ch) {
7491 case 'a':
7492 abort_edit = 1;
7493 break;
7494 case 'c':
7495 continue_edit = 1;
7496 break;
7497 case 'F':
7498 edit_script_path = optarg;
7499 break;
7500 case 'm':
7501 edit_logmsg_only = 1;
7502 break;
7503 default:
7504 usage_histedit();
7505 /* NOTREACHED */
7509 argc -= optind;
7510 argv += optind;
7512 #ifndef PROFILE
7513 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7514 "unveil", NULL) == -1)
7515 err(1, "pledge");
7516 #endif
7517 if (abort_edit && continue_edit)
7518 errx(1, "histedit's -a and -c options are mutually exclusive");
7519 if (edit_script_path && edit_logmsg_only)
7520 errx(1, "histedit's -F and -m options are mutually exclusive");
7521 if (abort_edit && edit_logmsg_only)
7522 errx(1, "histedit's -a and -m options are mutually exclusive");
7523 if (continue_edit && edit_logmsg_only)
7524 errx(1, "histedit's -c and -m options are mutually exclusive");
7525 if (argc != 0)
7526 usage_histedit();
7529 * This command cannot apply unveil(2) in all cases because the
7530 * user may choose to run an editor to edit the histedit script
7531 * and to edit individual commit log messages.
7532 * unveil(2) traverses exec(2); if an editor is used we have to
7533 * apply unveil after edit script and log messages have been written.
7534 * XXX TODO: Make use of unveil(2) where possible.
7537 cwd = getcwd(NULL, 0);
7538 if (cwd == NULL) {
7539 error = got_error_from_errno("getcwd");
7540 goto done;
7542 error = got_worktree_open(&worktree, cwd);
7543 if (error)
7544 goto done;
7546 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7547 NULL);
7548 if (error != NULL)
7549 goto done;
7551 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7552 if (error)
7553 goto done;
7554 if (rebase_in_progress) {
7555 error = got_error(GOT_ERR_REBASING);
7556 goto done;
7559 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
7560 if (error)
7561 goto done;
7563 if (edit_in_progress && edit_logmsg_only) {
7564 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
7565 "histedit operation is in progress in this "
7566 "work tree and must be continued or aborted "
7567 "before the -m option can be used");
7568 goto done;
7571 if (edit_in_progress && abort_edit) {
7572 error = got_worktree_histedit_continue(&resume_commit_id,
7573 &tmp_branch, &branch, &base_commit_id, &fileindex,
7574 worktree, repo);
7575 if (error)
7576 goto done;
7577 printf("Switching work tree to %s\n",
7578 got_ref_get_symref_target(branch));
7579 error = got_worktree_histedit_abort(worktree, fileindex, repo,
7580 branch, base_commit_id, update_progress, &did_something);
7581 if (error)
7582 goto done;
7583 printf("Histedit of %s aborted\n",
7584 got_ref_get_symref_target(branch));
7585 goto done; /* nothing else to do */
7586 } else if (abort_edit) {
7587 error = got_error(GOT_ERR_NOT_HISTEDIT);
7588 goto done;
7591 if (continue_edit) {
7592 char *path;
7594 if (!edit_in_progress) {
7595 error = got_error(GOT_ERR_NOT_HISTEDIT);
7596 goto done;
7599 error = got_worktree_get_histedit_script_path(&path, worktree);
7600 if (error)
7601 goto done;
7603 error = histedit_load_list(&histedit_cmds, path, repo);
7604 free(path);
7605 if (error)
7606 goto done;
7608 error = got_worktree_histedit_continue(&resume_commit_id,
7609 &tmp_branch, &branch, &base_commit_id, &fileindex,
7610 worktree, repo);
7611 if (error)
7612 goto done;
7614 error = got_ref_resolve(&head_commit_id, repo, branch);
7615 if (error)
7616 goto done;
7618 error = got_object_open_as_commit(&commit, repo,
7619 head_commit_id);
7620 if (error)
7621 goto done;
7622 parent_ids = got_object_commit_get_parent_ids(commit);
7623 pid = SIMPLEQ_FIRST(parent_ids);
7624 if (pid == NULL) {
7625 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
7626 goto done;
7628 error = collect_commits(&commits, head_commit_id, pid->id,
7629 base_commit_id, got_worktree_get_path_prefix(worktree),
7630 GOT_ERR_HISTEDIT_PATH, repo);
7631 got_object_commit_close(commit);
7632 commit = NULL;
7633 if (error)
7634 goto done;
7635 } else {
7636 if (edit_in_progress) {
7637 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7638 goto done;
7641 error = got_ref_open(&branch, repo,
7642 got_worktree_get_head_ref_name(worktree), 0);
7643 if (error != NULL)
7644 goto done;
7646 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
7647 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
7648 "will not edit commit history of a branch outside "
7649 "the \"refs/heads/\" reference namespace");
7650 goto done;
7653 error = got_ref_resolve(&head_commit_id, repo, branch);
7654 got_ref_close(branch);
7655 branch = NULL;
7656 if (error)
7657 goto done;
7659 error = got_object_open_as_commit(&commit, repo,
7660 head_commit_id);
7661 if (error)
7662 goto done;
7663 parent_ids = got_object_commit_get_parent_ids(commit);
7664 pid = SIMPLEQ_FIRST(parent_ids);
7665 if (pid == NULL) {
7666 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
7667 goto done;
7669 error = collect_commits(&commits, head_commit_id, pid->id,
7670 got_worktree_get_base_commit_id(worktree),
7671 got_worktree_get_path_prefix(worktree),
7672 GOT_ERR_HISTEDIT_PATH, repo);
7673 got_object_commit_close(commit);
7674 commit = NULL;
7675 if (error)
7676 goto done;
7678 if (SIMPLEQ_EMPTY(&commits)) {
7679 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
7680 goto done;
7683 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
7684 &base_commit_id, &fileindex, worktree, repo);
7685 if (error)
7686 goto done;
7688 if (edit_script_path) {
7689 error = histedit_load_list(&histedit_cmds,
7690 edit_script_path, repo);
7691 if (error) {
7692 got_worktree_histedit_abort(worktree, fileindex,
7693 repo, branch, base_commit_id,
7694 update_progress, &did_something);
7695 goto done;
7697 } else {
7698 const char *branch_name;
7699 branch_name = got_ref_get_symref_target(branch);
7700 if (strncmp(branch_name, "refs/heads/", 11) == 0)
7701 branch_name += 11;
7702 error = histedit_edit_script(&histedit_cmds, &commits,
7703 branch_name, edit_logmsg_only, repo);
7704 if (error) {
7705 got_worktree_histedit_abort(worktree, fileindex,
7706 repo, branch, base_commit_id,
7707 update_progress, &did_something);
7708 goto done;
7713 error = histedit_save_list(&histedit_cmds, worktree,
7714 repo);
7715 if (error) {
7716 got_worktree_histedit_abort(worktree, fileindex,
7717 repo, branch, base_commit_id,
7718 update_progress, &did_something);
7719 goto done;
7724 error = histedit_check_script(&histedit_cmds, &commits, repo);
7725 if (error)
7726 goto done;
7728 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
7729 if (resume_commit_id) {
7730 if (got_object_id_cmp(hle->commit_id,
7731 resume_commit_id) != 0)
7732 continue;
7734 resume_commit_id = NULL;
7735 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
7736 hle->cmd->code == GOT_HISTEDIT_FOLD) {
7737 error = histedit_skip_commit(hle, worktree,
7738 repo);
7739 if (error)
7740 goto done;
7741 } else {
7742 struct got_pathlist_head paths;
7743 int have_changes = 0;
7745 TAILQ_INIT(&paths);
7746 error = got_pathlist_append(&paths, "", NULL);
7747 if (error)
7748 goto done;
7749 error = got_worktree_status(worktree, &paths,
7750 repo, check_local_changes, &have_changes,
7751 check_cancelled, NULL);
7752 got_pathlist_free(&paths);
7753 if (error) {
7754 if (error->code != GOT_ERR_CANCELLED)
7755 goto done;
7756 if (sigint_received || sigpipe_received)
7757 goto done;
7759 if (have_changes) {
7760 error = histedit_commit(NULL, worktree,
7761 fileindex, tmp_branch, hle, repo);
7762 if (error)
7763 goto done;
7764 } else {
7765 error = got_object_open_as_commit(
7766 &commit, repo, hle->commit_id);
7767 if (error)
7768 goto done;
7769 error = show_histedit_progress(commit,
7770 hle, NULL);
7771 got_object_commit_close(commit);
7772 commit = NULL;
7773 if (error)
7774 goto done;
7777 continue;
7780 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
7781 error = histedit_skip_commit(hle, worktree, repo);
7782 if (error)
7783 goto done;
7784 continue;
7787 error = got_object_open_as_commit(&commit, repo,
7788 hle->commit_id);
7789 if (error)
7790 goto done;
7791 parent_ids = got_object_commit_get_parent_ids(commit);
7792 pid = SIMPLEQ_FIRST(parent_ids);
7794 error = got_worktree_histedit_merge_files(&merged_paths,
7795 worktree, fileindex, pid->id, hle->commit_id, repo,
7796 rebase_progress, &rebase_status, check_cancelled, NULL);
7797 if (error)
7798 goto done;
7799 got_object_commit_close(commit);
7800 commit = NULL;
7802 if (rebase_status == GOT_STATUS_CONFLICT) {
7803 error = show_rebase_merge_conflict(hle->commit_id,
7804 repo);
7805 if (error)
7806 goto done;
7807 got_worktree_rebase_pathlist_free(&merged_paths);
7808 break;
7811 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
7812 char *id_str;
7813 error = got_object_id_str(&id_str, hle->commit_id);
7814 if (error)
7815 goto done;
7816 printf("Stopping histedit for amending commit %s\n",
7817 id_str);
7818 free(id_str);
7819 got_worktree_rebase_pathlist_free(&merged_paths);
7820 error = got_worktree_histedit_postpone(worktree,
7821 fileindex);
7822 goto done;
7825 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
7826 error = histedit_skip_commit(hle, worktree, repo);
7827 if (error)
7828 goto done;
7829 continue;
7832 error = histedit_commit(&merged_paths, worktree, fileindex,
7833 tmp_branch, hle, repo);
7834 got_worktree_rebase_pathlist_free(&merged_paths);
7835 if (error)
7836 goto done;
7839 if (rebase_status == GOT_STATUS_CONFLICT) {
7840 error = got_worktree_histedit_postpone(worktree, fileindex);
7841 if (error)
7842 goto done;
7843 error = got_error_msg(GOT_ERR_CONFLICTS,
7844 "conflicts must be resolved before histedit can continue");
7845 } else
7846 error = histedit_complete(worktree, fileindex, tmp_branch,
7847 branch, repo);
7848 done:
7849 got_object_id_queue_free(&commits);
7850 histedit_free_list(&histedit_cmds);
7851 free(head_commit_id);
7852 free(base_commit_id);
7853 free(resume_commit_id);
7854 if (commit)
7855 got_object_commit_close(commit);
7856 if (branch)
7857 got_ref_close(branch);
7858 if (tmp_branch)
7859 got_ref_close(tmp_branch);
7860 if (worktree)
7861 got_worktree_close(worktree);
7862 if (repo)
7863 got_repo_close(repo);
7864 return error;
7867 __dead static void
7868 usage_integrate(void)
7870 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
7871 exit(1);
7874 static const struct got_error *
7875 cmd_integrate(int argc, char *argv[])
7877 const struct got_error *error = NULL;
7878 struct got_repository *repo = NULL;
7879 struct got_worktree *worktree = NULL;
7880 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
7881 const char *branch_arg = NULL;
7882 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
7883 struct got_fileindex *fileindex = NULL;
7884 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
7885 int ch, did_something = 0;
7887 while ((ch = getopt(argc, argv, "")) != -1) {
7888 switch (ch) {
7889 default:
7890 usage_integrate();
7891 /* NOTREACHED */
7895 argc -= optind;
7896 argv += optind;
7898 if (argc != 1)
7899 usage_integrate();
7900 branch_arg = argv[0];
7902 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7903 "unveil", NULL) == -1)
7904 err(1, "pledge");
7906 cwd = getcwd(NULL, 0);
7907 if (cwd == NULL) {
7908 error = got_error_from_errno("getcwd");
7909 goto done;
7912 error = got_worktree_open(&worktree, cwd);
7913 if (error)
7914 goto done;
7916 error = check_rebase_or_histedit_in_progress(worktree);
7917 if (error)
7918 goto done;
7920 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7921 NULL);
7922 if (error != NULL)
7923 goto done;
7925 error = apply_unveil(got_repo_get_path(repo), 0,
7926 got_worktree_get_root_path(worktree));
7927 if (error)
7928 goto done;
7930 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
7931 error = got_error_from_errno("asprintf");
7932 goto done;
7935 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
7936 &base_branch_ref, worktree, refname, repo);
7937 if (error)
7938 goto done;
7940 refname = strdup(got_ref_get_name(branch_ref));
7941 if (refname == NULL) {
7942 error = got_error_from_errno("strdup");
7943 got_worktree_integrate_abort(worktree, fileindex, repo,
7944 branch_ref, base_branch_ref);
7945 goto done;
7947 base_refname = strdup(got_ref_get_name(base_branch_ref));
7948 if (base_refname == NULL) {
7949 error = got_error_from_errno("strdup");
7950 got_worktree_integrate_abort(worktree, fileindex, repo,
7951 branch_ref, base_branch_ref);
7952 goto done;
7955 error = got_ref_resolve(&commit_id, repo, branch_ref);
7956 if (error)
7957 goto done;
7959 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
7960 if (error)
7961 goto done;
7963 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
7964 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7965 "specified branch has already been integrated");
7966 got_worktree_integrate_abort(worktree, fileindex, repo,
7967 branch_ref, base_branch_ref);
7968 goto done;
7971 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
7972 if (error) {
7973 if (error->code == GOT_ERR_ANCESTRY)
7974 error = got_error(GOT_ERR_REBASE_REQUIRED);
7975 got_worktree_integrate_abort(worktree, fileindex, repo,
7976 branch_ref, base_branch_ref);
7977 goto done;
7980 error = got_worktree_integrate_continue(worktree, fileindex, repo,
7981 branch_ref, base_branch_ref, update_progress, &did_something,
7982 check_cancelled, NULL);
7983 if (error)
7984 goto done;
7986 printf("Integrated %s into %s\n", refname, base_refname);
7987 done:
7988 if (repo)
7989 got_repo_close(repo);
7990 if (worktree)
7991 got_worktree_close(worktree);
7992 free(cwd);
7993 free(base_commit_id);
7994 free(commit_id);
7995 free(refname);
7996 free(base_refname);
7997 return error;
8000 __dead static void
8001 usage_stage(void)
8003 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
8004 "[file-path ...]\n",
8005 getprogname());
8006 exit(1);
8009 static const struct got_error *
8010 print_stage(void *arg, unsigned char status, unsigned char staged_status,
8011 const char *path, struct got_object_id *blob_id,
8012 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
8013 int dirfd, const char *de_name)
8015 const struct got_error *err = NULL;
8016 char *id_str = NULL;
8018 if (staged_status != GOT_STATUS_ADD &&
8019 staged_status != GOT_STATUS_MODIFY &&
8020 staged_status != GOT_STATUS_DELETE)
8021 return NULL;
8023 if (staged_status == GOT_STATUS_ADD ||
8024 staged_status == GOT_STATUS_MODIFY)
8025 err = got_object_id_str(&id_str, staged_blob_id);
8026 else
8027 err = got_object_id_str(&id_str, blob_id);
8028 if (err)
8029 return err;
8031 printf("%s %c %s\n", id_str, staged_status, path);
8032 free(id_str);
8033 return NULL;
8036 static const struct got_error *
8037 cmd_stage(int argc, char *argv[])
8039 const struct got_error *error = NULL;
8040 struct got_repository *repo = NULL;
8041 struct got_worktree *worktree = NULL;
8042 char *cwd = NULL;
8043 struct got_pathlist_head paths;
8044 struct got_pathlist_entry *pe;
8045 int ch, list_stage = 0, pflag = 0;
8046 FILE *patch_script_file = NULL;
8047 const char *patch_script_path = NULL;
8048 struct choose_patch_arg cpa;
8050 TAILQ_INIT(&paths);
8052 while ((ch = getopt(argc, argv, "lpF:")) != -1) {
8053 switch (ch) {
8054 case 'l':
8055 list_stage = 1;
8056 break;
8057 case 'p':
8058 pflag = 1;
8059 break;
8060 case 'F':
8061 patch_script_path = optarg;
8062 break;
8063 default:
8064 usage_stage();
8065 /* NOTREACHED */
8069 argc -= optind;
8070 argv += optind;
8072 #ifndef PROFILE
8073 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8074 "unveil", NULL) == -1)
8075 err(1, "pledge");
8076 #endif
8077 if (list_stage && (pflag || patch_script_path))
8078 errx(1, "-l option cannot be used with other options");
8079 if (patch_script_path && !pflag)
8080 errx(1, "-F option can only be used together with -p option");
8082 cwd = getcwd(NULL, 0);
8083 if (cwd == NULL) {
8084 error = got_error_from_errno("getcwd");
8085 goto done;
8088 error = got_worktree_open(&worktree, cwd);
8089 if (error)
8090 goto done;
8092 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8093 NULL);
8094 if (error != NULL)
8095 goto done;
8097 if (patch_script_path) {
8098 patch_script_file = fopen(patch_script_path, "r");
8099 if (patch_script_file == NULL) {
8100 error = got_error_from_errno2("fopen",
8101 patch_script_path);
8102 goto done;
8105 error = apply_unveil(got_repo_get_path(repo), 0,
8106 got_worktree_get_root_path(worktree));
8107 if (error)
8108 goto done;
8110 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8111 if (error)
8112 goto done;
8114 if (list_stage)
8115 error = got_worktree_status(worktree, &paths, repo,
8116 print_stage, NULL, check_cancelled, NULL);
8117 else {
8118 cpa.patch_script_file = patch_script_file;
8119 cpa.action = "stage";
8120 error = got_worktree_stage(worktree, &paths,
8121 pflag ? NULL : print_status, NULL,
8122 pflag ? choose_patch : NULL, &cpa, repo);
8124 done:
8125 if (patch_script_file && fclose(patch_script_file) == EOF &&
8126 error == NULL)
8127 error = got_error_from_errno2("fclose", patch_script_path);
8128 if (repo)
8129 got_repo_close(repo);
8130 if (worktree)
8131 got_worktree_close(worktree);
8132 TAILQ_FOREACH(pe, &paths, entry)
8133 free((char *)pe->path);
8134 got_pathlist_free(&paths);
8135 free(cwd);
8136 return error;
8139 __dead static void
8140 usage_unstage(void)
8142 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
8143 "[file-path ...]\n",
8144 getprogname());
8145 exit(1);
8149 static const struct got_error *
8150 cmd_unstage(int argc, char *argv[])
8152 const struct got_error *error = NULL;
8153 struct got_repository *repo = NULL;
8154 struct got_worktree *worktree = NULL;
8155 char *cwd = NULL;
8156 struct got_pathlist_head paths;
8157 struct got_pathlist_entry *pe;
8158 int ch, did_something = 0, pflag = 0;
8159 FILE *patch_script_file = NULL;
8160 const char *patch_script_path = NULL;
8161 struct choose_patch_arg cpa;
8163 TAILQ_INIT(&paths);
8165 while ((ch = getopt(argc, argv, "pF:")) != -1) {
8166 switch (ch) {
8167 case 'p':
8168 pflag = 1;
8169 break;
8170 case 'F':
8171 patch_script_path = optarg;
8172 break;
8173 default:
8174 usage_unstage();
8175 /* NOTREACHED */
8179 argc -= optind;
8180 argv += optind;
8182 #ifndef PROFILE
8183 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8184 "unveil", NULL) == -1)
8185 err(1, "pledge");
8186 #endif
8187 if (patch_script_path && !pflag)
8188 errx(1, "-F option can only be used together with -p option");
8190 cwd = getcwd(NULL, 0);
8191 if (cwd == NULL) {
8192 error = got_error_from_errno("getcwd");
8193 goto done;
8196 error = got_worktree_open(&worktree, cwd);
8197 if (error)
8198 goto done;
8200 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8201 NULL);
8202 if (error != NULL)
8203 goto done;
8205 if (patch_script_path) {
8206 patch_script_file = fopen(patch_script_path, "r");
8207 if (patch_script_file == NULL) {
8208 error = got_error_from_errno2("fopen",
8209 patch_script_path);
8210 goto done;
8214 error = apply_unveil(got_repo_get_path(repo), 0,
8215 got_worktree_get_root_path(worktree));
8216 if (error)
8217 goto done;
8219 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8220 if (error)
8221 goto done;
8223 cpa.patch_script_file = patch_script_file;
8224 cpa.action = "unstage";
8225 error = got_worktree_unstage(worktree, &paths, update_progress,
8226 &did_something, pflag ? choose_patch : NULL, &cpa, repo);
8227 done:
8228 if (patch_script_file && fclose(patch_script_file) == EOF &&
8229 error == NULL)
8230 error = got_error_from_errno2("fclose", patch_script_path);
8231 if (repo)
8232 got_repo_close(repo);
8233 if (worktree)
8234 got_worktree_close(worktree);
8235 TAILQ_FOREACH(pe, &paths, entry)
8236 free((char *)pe->path);
8237 got_pathlist_free(&paths);
8238 free(cwd);
8239 return error;
8242 __dead static void
8243 usage_cat(void)
8245 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
8246 "arg1 [arg2 ...]\n", getprogname());
8247 exit(1);
8250 static const struct got_error *
8251 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8253 const struct got_error *err;
8254 struct got_blob_object *blob;
8256 err = got_object_open_as_blob(&blob, repo, id, 8192);
8257 if (err)
8258 return err;
8260 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
8261 got_object_blob_close(blob);
8262 return err;
8265 static const struct got_error *
8266 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8268 const struct got_error *err;
8269 struct got_tree_object *tree;
8270 int nentries, i;
8272 err = got_object_open_as_tree(&tree, repo, id);
8273 if (err)
8274 return err;
8276 nentries = got_object_tree_get_nentries(tree);
8277 for (i = 0; i < nentries; i++) {
8278 struct got_tree_entry *te;
8279 char *id_str;
8280 if (sigint_received || sigpipe_received)
8281 break;
8282 te = got_object_tree_get_entry(tree, i);
8283 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
8284 if (err)
8285 break;
8286 fprintf(outfile, "%s %.7o %s\n", id_str,
8287 got_tree_entry_get_mode(te),
8288 got_tree_entry_get_name(te));
8289 free(id_str);
8292 got_object_tree_close(tree);
8293 return err;
8296 static const struct got_error *
8297 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8299 const struct got_error *err;
8300 struct got_commit_object *commit;
8301 const struct got_object_id_queue *parent_ids;
8302 struct got_object_qid *pid;
8303 char *id_str = NULL;
8304 const char *logmsg = NULL;
8306 err = got_object_open_as_commit(&commit, repo, id);
8307 if (err)
8308 return err;
8310 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
8311 if (err)
8312 goto done;
8314 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
8315 parent_ids = got_object_commit_get_parent_ids(commit);
8316 fprintf(outfile, "numparents %d\n",
8317 got_object_commit_get_nparents(commit));
8318 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
8319 char *pid_str;
8320 err = got_object_id_str(&pid_str, pid->id);
8321 if (err)
8322 goto done;
8323 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
8324 free(pid_str);
8326 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
8327 got_object_commit_get_author(commit),
8328 got_object_commit_get_author_time(commit));
8330 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
8331 got_object_commit_get_author(commit),
8332 got_object_commit_get_committer_time(commit));
8334 logmsg = got_object_commit_get_logmsg_raw(commit);
8335 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
8336 fprintf(outfile, "%s", logmsg);
8337 done:
8338 free(id_str);
8339 got_object_commit_close(commit);
8340 return err;
8343 static const struct got_error *
8344 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8346 const struct got_error *err;
8347 struct got_tag_object *tag;
8348 char *id_str = NULL;
8349 const char *tagmsg = NULL;
8351 err = got_object_open_as_tag(&tag, repo, id);
8352 if (err)
8353 return err;
8355 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
8356 if (err)
8357 goto done;
8359 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
8361 switch (got_object_tag_get_object_type(tag)) {
8362 case GOT_OBJ_TYPE_BLOB:
8363 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8364 GOT_OBJ_LABEL_BLOB);
8365 break;
8366 case GOT_OBJ_TYPE_TREE:
8367 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8368 GOT_OBJ_LABEL_TREE);
8369 break;
8370 case GOT_OBJ_TYPE_COMMIT:
8371 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8372 GOT_OBJ_LABEL_COMMIT);
8373 break;
8374 case GOT_OBJ_TYPE_TAG:
8375 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8376 GOT_OBJ_LABEL_TAG);
8377 break;
8378 default:
8379 break;
8382 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
8383 got_object_tag_get_name(tag));
8385 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
8386 got_object_tag_get_tagger(tag),
8387 got_object_tag_get_tagger_time(tag));
8389 tagmsg = got_object_tag_get_message(tag);
8390 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
8391 fprintf(outfile, "%s", tagmsg);
8392 done:
8393 free(id_str);
8394 got_object_tag_close(tag);
8395 return err;
8398 static const struct got_error *
8399 cmd_cat(int argc, char *argv[])
8401 const struct got_error *error;
8402 struct got_repository *repo = NULL;
8403 struct got_worktree *worktree = NULL;
8404 char *cwd = NULL, *repo_path = NULL, *label = NULL;
8405 const char *commit_id_str = NULL;
8406 struct got_object_id *id = NULL, *commit_id = NULL;
8407 int ch, obj_type, i, force_path = 0;
8409 #ifndef PROFILE
8410 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8411 NULL) == -1)
8412 err(1, "pledge");
8413 #endif
8415 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
8416 switch (ch) {
8417 case 'c':
8418 commit_id_str = optarg;
8419 break;
8420 case 'r':
8421 repo_path = realpath(optarg, NULL);
8422 if (repo_path == NULL)
8423 return got_error_from_errno2("realpath",
8424 optarg);
8425 got_path_strip_trailing_slashes(repo_path);
8426 break;
8427 case 'P':
8428 force_path = 1;
8429 break;
8430 default:
8431 usage_cat();
8432 /* NOTREACHED */
8436 argc -= optind;
8437 argv += optind;
8439 cwd = getcwd(NULL, 0);
8440 if (cwd == NULL) {
8441 error = got_error_from_errno("getcwd");
8442 goto done;
8444 error = got_worktree_open(&worktree, cwd);
8445 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8446 goto done;
8447 if (worktree) {
8448 if (repo_path == NULL) {
8449 repo_path = strdup(
8450 got_worktree_get_repo_path(worktree));
8451 if (repo_path == NULL) {
8452 error = got_error_from_errno("strdup");
8453 goto done;
8458 if (repo_path == NULL) {
8459 repo_path = getcwd(NULL, 0);
8460 if (repo_path == NULL)
8461 return got_error_from_errno("getcwd");
8464 error = got_repo_open(&repo, repo_path, NULL);
8465 free(repo_path);
8466 if (error != NULL)
8467 goto done;
8469 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
8470 if (error)
8471 goto done;
8473 if (commit_id_str == NULL)
8474 commit_id_str = GOT_REF_HEAD;
8475 error = got_repo_match_object_id(&commit_id, NULL,
8476 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
8477 if (error)
8478 goto done;
8480 for (i = 0; i < argc; i++) {
8481 if (force_path) {
8482 error = got_object_id_by_path(&id, repo, commit_id,
8483 argv[i]);
8484 if (error)
8485 break;
8486 } else {
8487 error = got_repo_match_object_id(&id, &label, argv[i],
8488 GOT_OBJ_TYPE_ANY, 0, repo);
8489 if (error) {
8490 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
8491 error->code != GOT_ERR_NOT_REF)
8492 break;
8493 error = got_object_id_by_path(&id, repo,
8494 commit_id, argv[i]);
8495 if (error)
8496 break;
8500 error = got_object_get_type(&obj_type, repo, id);
8501 if (error)
8502 break;
8504 switch (obj_type) {
8505 case GOT_OBJ_TYPE_BLOB:
8506 error = cat_blob(id, repo, stdout);
8507 break;
8508 case GOT_OBJ_TYPE_TREE:
8509 error = cat_tree(id, repo, stdout);
8510 break;
8511 case GOT_OBJ_TYPE_COMMIT:
8512 error = cat_commit(id, repo, stdout);
8513 break;
8514 case GOT_OBJ_TYPE_TAG:
8515 error = cat_tag(id, repo, stdout);
8516 break;
8517 default:
8518 error = got_error(GOT_ERR_OBJ_TYPE);
8519 break;
8521 if (error)
8522 break;
8523 free(label);
8524 label = NULL;
8525 free(id);
8526 id = NULL;
8528 done:
8529 free(label);
8530 free(id);
8531 free(commit_id);
8532 if (worktree)
8533 got_worktree_close(worktree);
8534 if (repo) {
8535 const struct got_error *repo_error;
8536 repo_error = got_repo_close(repo);
8537 if (error == NULL)
8538 error = repo_error;
8540 return error;