Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/param.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
41 #include <util.h>
43 #include "got_version.h"
44 #include "got_error.h"
45 #include "got_object.h"
46 #include "got_reference.h"
47 #include "got_repository.h"
48 #include "got_path.h"
49 #include "got_cancel.h"
50 #include "got_worktree.h"
51 #include "got_diff.h"
52 #include "got_commit_graph.h"
53 #include "got_fetch.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_opentemp.h"
58 #ifndef nitems
59 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
60 #endif
62 static volatile sig_atomic_t sigint_received;
63 static volatile sig_atomic_t sigpipe_received;
65 static void
66 catch_sigint(int signo)
67 {
68 sigint_received = 1;
69 }
71 static void
72 catch_sigpipe(int signo)
73 {
74 sigpipe_received = 1;
75 }
78 struct got_cmd {
79 const char *cmd_name;
80 const struct got_error *(*cmd_main)(int, char *[]);
81 void (*cmd_usage)(void);
82 const char *cmd_alias;
83 };
85 __dead static void usage(int);
86 __dead static void usage_init(void);
87 __dead static void usage_import(void);
88 __dead static void usage_clone(void);
89 __dead static void usage_fetch(void);
90 __dead static void usage_checkout(void);
91 __dead static void usage_update(void);
92 __dead static void usage_log(void);
93 __dead static void usage_diff(void);
94 __dead static void usage_blame(void);
95 __dead static void usage_tree(void);
96 __dead static void usage_status(void);
97 __dead static void usage_ref(void);
98 __dead static void usage_branch(void);
99 __dead static void usage_tag(void);
100 __dead static void usage_add(void);
101 __dead static void usage_remove(void);
102 __dead static void usage_revert(void);
103 __dead static void usage_commit(void);
104 __dead static void usage_cherrypick(void);
105 __dead static void usage_backout(void);
106 __dead static void usage_rebase(void);
107 __dead static void usage_histedit(void);
108 __dead static void usage_integrate(void);
109 __dead static void usage_stage(void);
110 __dead static void usage_unstage(void);
111 __dead static void usage_cat(void);
113 static const struct got_error* cmd_init(int, char *[]);
114 static const struct got_error* cmd_import(int, char *[]);
115 static const struct got_error* cmd_clone(int, char *[]);
116 static const struct got_error* cmd_fetch(int, char *[]);
117 static const struct got_error* cmd_checkout(int, char *[]);
118 static const struct got_error* cmd_update(int, char *[]);
119 static const struct got_error* cmd_log(int, char *[]);
120 static const struct got_error* cmd_diff(int, char *[]);
121 static const struct got_error* cmd_blame(int, char *[]);
122 static const struct got_error* cmd_tree(int, char *[]);
123 static const struct got_error* cmd_status(int, char *[]);
124 static const struct got_error* cmd_ref(int, char *[]);
125 static const struct got_error* cmd_branch(int, char *[]);
126 static const struct got_error* cmd_tag(int, char *[]);
127 static const struct got_error* cmd_add(int, char *[]);
128 static const struct got_error* cmd_remove(int, char *[]);
129 static const struct got_error* cmd_revert(int, char *[]);
130 static const struct got_error* cmd_commit(int, char *[]);
131 static const struct got_error* cmd_cherrypick(int, char *[]);
132 static const struct got_error* cmd_backout(int, char *[]);
133 static const struct got_error* cmd_rebase(int, char *[]);
134 static const struct got_error* cmd_histedit(int, char *[]);
135 static const struct got_error* cmd_integrate(int, char *[]);
136 static const struct got_error* cmd_stage(int, char *[]);
137 static const struct got_error* cmd_unstage(int, char *[]);
138 static const struct got_error* cmd_cat(int, char *[]);
140 static struct got_cmd got_commands[] = {
141 { "init", cmd_init, usage_init, "in" },
142 { "import", cmd_import, usage_import, "im" },
143 { "clone", cmd_clone, usage_clone, "cl" },
144 { "fetch", cmd_fetch, usage_fetch, "fe" },
145 { "checkout", cmd_checkout, usage_checkout, "co" },
146 { "update", cmd_update, usage_update, "up" },
147 { "log", cmd_log, usage_log, "" },
148 { "diff", cmd_diff, usage_diff, "di" },
149 { "blame", cmd_blame, usage_blame, "bl" },
150 { "tree", cmd_tree, usage_tree, "tr" },
151 { "status", cmd_status, usage_status, "st" },
152 { "ref", cmd_ref, usage_ref, "" },
153 { "branch", cmd_branch, usage_branch, "br" },
154 { "tag", cmd_tag, usage_tag, "" },
155 { "add", cmd_add, usage_add, "" },
156 { "remove", cmd_remove, usage_remove, "rm" },
157 { "revert", cmd_revert, usage_revert, "rv" },
158 { "commit", cmd_commit, usage_commit, "ci" },
159 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
160 { "backout", cmd_backout, usage_backout, "bo" },
161 { "rebase", cmd_rebase, usage_rebase, "rb" },
162 { "histedit", cmd_histedit, usage_histedit, "he" },
163 { "integrate", cmd_integrate, usage_integrate,"ig" },
164 { "stage", cmd_stage, usage_stage, "sg" },
165 { "unstage", cmd_unstage, usage_unstage, "ug" },
166 { "cat", cmd_cat, usage_cat, "" },
167 };
169 static void
170 list_commands(void)
172 int i;
174 fprintf(stderr, "commands:");
175 for (i = 0; i < nitems(got_commands); i++) {
176 struct got_cmd *cmd = &got_commands[i];
177 fprintf(stderr, " %s", cmd->cmd_name);
179 fputc('\n', stderr);
182 int
183 main(int argc, char *argv[])
185 struct got_cmd *cmd;
186 unsigned int i;
187 int ch;
188 int hflag = 0, Vflag = 0;
189 static struct option longopts[] = {
190 { "version", no_argument, NULL, 'V' },
191 { NULL, 0, NULL, 0}
192 };
194 setlocale(LC_CTYPE, "");
196 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
197 switch (ch) {
198 case 'h':
199 hflag = 1;
200 break;
201 case 'V':
202 Vflag = 1;
203 break;
204 default:
205 usage(hflag);
206 /* NOTREACHED */
210 argc -= optind;
211 argv += optind;
212 optind = 0;
214 if (Vflag) {
215 got_version_print_str();
216 return 1;
219 if (argc <= 0)
220 usage(hflag);
222 signal(SIGINT, catch_sigint);
223 signal(SIGPIPE, catch_sigpipe);
225 for (i = 0; i < nitems(got_commands); i++) {
226 const struct got_error *error;
228 cmd = &got_commands[i];
230 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
231 strcmp(cmd->cmd_alias, argv[0]) != 0)
232 continue;
234 if (hflag)
235 got_commands[i].cmd_usage();
237 error = got_commands[i].cmd_main(argc, argv);
238 if (error && error->code != GOT_ERR_CANCELLED &&
239 error->code != GOT_ERR_PRIVSEP_EXIT &&
240 !(sigpipe_received &&
241 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
242 !(sigint_received &&
243 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
244 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
245 return 1;
248 return 0;
251 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
252 list_commands();
253 return 1;
256 __dead static void
257 usage(int hflag)
259 fprintf(stderr, "usage: %s [-h] [-V | --version] command [arg ...]\n",
260 getprogname());
261 if (hflag)
262 list_commands();
263 exit(1);
266 static const struct got_error *
267 get_editor(char **abspath)
269 const struct got_error *err = NULL;
270 const char *editor;
272 *abspath = NULL;
274 editor = getenv("VISUAL");
275 if (editor == NULL)
276 editor = getenv("EDITOR");
278 if (editor) {
279 err = got_path_find_prog(abspath, editor);
280 if (err)
281 return err;
284 if (*abspath == NULL) {
285 *abspath = strdup("/bin/ed");
286 if (*abspath == NULL)
287 return got_error_from_errno("strdup");
290 return NULL;
293 static const struct got_error *
294 apply_unveil(const char *repo_path, int repo_read_only,
295 const char *worktree_path)
297 const struct got_error *err;
299 #ifdef PROFILE
300 if (unveil("gmon.out", "rwc") != 0)
301 return got_error_from_errno2("unveil", "gmon.out");
302 #endif
303 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
304 return got_error_from_errno2("unveil", repo_path);
306 if (worktree_path && unveil(worktree_path, "rwc") != 0)
307 return got_error_from_errno2("unveil", worktree_path);
309 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
310 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
312 err = got_privsep_unveil_exec_helpers();
313 if (err != NULL)
314 return err;
316 if (unveil(NULL, NULL) != 0)
317 return got_error_from_errno("unveil");
319 return NULL;
322 __dead static void
323 usage_init(void)
325 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
326 exit(1);
329 static const struct got_error *
330 cmd_init(int argc, char *argv[])
332 const struct got_error *error = NULL;
333 char *repo_path = NULL;
334 int ch;
336 while ((ch = getopt(argc, argv, "")) != -1) {
337 switch (ch) {
338 default:
339 usage_init();
340 /* NOTREACHED */
344 argc -= optind;
345 argv += optind;
347 #ifndef PROFILE
348 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
349 err(1, "pledge");
350 #endif
351 if (argc != 1)
352 usage_init();
354 repo_path = strdup(argv[0]);
355 if (repo_path == NULL)
356 return got_error_from_errno("strdup");
358 got_path_strip_trailing_slashes(repo_path);
360 error = got_path_mkdir(repo_path);
361 if (error &&
362 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
363 goto done;
365 error = apply_unveil(repo_path, 0, NULL);
366 if (error)
367 goto done;
369 error = got_repo_init(repo_path);
370 done:
371 free(repo_path);
372 return error;
375 __dead static void
376 usage_import(void)
378 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
379 "[-r repository-path] [-I pattern] path\n", getprogname());
380 exit(1);
383 int
384 spawn_editor(const char *editor, const char *file)
386 pid_t pid;
387 sig_t sighup, sigint, sigquit;
388 int st = -1;
390 sighup = signal(SIGHUP, SIG_IGN);
391 sigint = signal(SIGINT, SIG_IGN);
392 sigquit = signal(SIGQUIT, SIG_IGN);
394 switch (pid = fork()) {
395 case -1:
396 goto doneediting;
397 case 0:
398 execl(editor, editor, file, (char *)NULL);
399 _exit(127);
402 while (waitpid(pid, &st, 0) == -1)
403 if (errno != EINTR)
404 break;
406 doneediting:
407 (void)signal(SIGHUP, sighup);
408 (void)signal(SIGINT, sigint);
409 (void)signal(SIGQUIT, sigquit);
411 if (!WIFEXITED(st)) {
412 errno = EINTR;
413 return -1;
416 return WEXITSTATUS(st);
419 static const struct got_error *
420 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
421 const char *initial_content)
423 const struct got_error *err = NULL;
424 char buf[1024];
425 struct stat st, st2;
426 FILE *fp;
427 int content_changed = 0;
428 size_t len;
430 *logmsg = NULL;
432 if (stat(logmsg_path, &st) == -1)
433 return got_error_from_errno2("stat", logmsg_path);
435 if (spawn_editor(editor, logmsg_path) == -1)
436 return got_error_from_errno("failed spawning editor");
438 if (stat(logmsg_path, &st2) == -1)
439 return got_error_from_errno("stat");
441 if (st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
442 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
443 "no changes made to commit message, aborting");
445 *logmsg = malloc(st2.st_size + 1);
446 if (*logmsg == NULL)
447 return got_error_from_errno("malloc");
448 (*logmsg)[0] = '\0';
449 len = 0;
451 fp = fopen(logmsg_path, "r");
452 if (fp == NULL) {
453 err = got_error_from_errno("fopen");
454 goto done;
456 while (fgets(buf, sizeof(buf), fp) != NULL) {
457 if (!content_changed && strcmp(buf, initial_content) != 0)
458 content_changed = 1;
459 if (buf[0] == '#' || (len == 0 && buf[0] == '\n'))
460 continue; /* remove comments and leading empty lines */
461 len = strlcat(*logmsg, buf, st2.st_size);
463 fclose(fp);
465 while (len > 0 && (*logmsg)[len - 1] == '\n') {
466 (*logmsg)[len - 1] = '\0';
467 len--;
470 if (len == 0 || !content_changed)
471 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
472 "commit message cannot be empty, aborting");
473 done:
474 if (err) {
475 free(*logmsg);
476 *logmsg = NULL;
478 return err;
481 static const struct got_error *
482 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
483 const char *path_dir, const char *branch_name)
485 char *initial_content = NULL;
486 const struct got_error *err = NULL;
487 int fd;
489 if (asprintf(&initial_content,
490 "\n# %s to be imported to branch %s\n", path_dir,
491 branch_name) == -1)
492 return got_error_from_errno("asprintf");
494 err = got_opentemp_named_fd(logmsg_path, &fd,
495 GOT_TMPDIR_STR "/got-importmsg");
496 if (err)
497 goto done;
499 dprintf(fd, initial_content);
500 close(fd);
502 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content);
503 done:
504 free(initial_content);
505 return err;
508 static const struct got_error *
509 import_progress(void *arg, const char *path)
511 printf("A %s\n", path);
512 return NULL;
515 static const struct got_error *
516 get_author(char **author, struct got_repository *repo)
518 const struct got_error *err = NULL;
519 const char *got_author, *name, *email;
521 *author = NULL;
523 name = got_repo_get_gitconfig_author_name(repo);
524 email = got_repo_get_gitconfig_author_email(repo);
525 if (name && email) {
526 if (asprintf(author, "%s <%s>", name, email) == -1)
527 return got_error_from_errno("asprintf");
528 return NULL;
531 got_author = getenv("GOT_AUTHOR");
532 if (got_author == NULL) {
533 name = got_repo_get_global_gitconfig_author_name(repo);
534 email = got_repo_get_global_gitconfig_author_email(repo);
535 if (name && email) {
536 if (asprintf(author, "%s <%s>", name, email) == -1)
537 return got_error_from_errno("asprintf");
538 return NULL;
540 /* TODO: Look up user in password database? */
541 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
544 *author = strdup(got_author);
545 if (*author == NULL)
546 return got_error_from_errno("strdup");
548 /*
549 * Really dumb email address check; we're only doing this to
550 * avoid git's object parser breaking on commits we create.
551 */
552 while (*got_author && *got_author != '<')
553 got_author++;
554 if (*got_author != '<') {
555 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
556 goto done;
558 while (*got_author && *got_author != '@')
559 got_author++;
560 if (*got_author != '@') {
561 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
562 goto done;
564 while (*got_author && *got_author != '>')
565 got_author++;
566 if (*got_author != '>')
567 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
568 done:
569 if (err) {
570 free(*author);
571 *author = NULL;
573 return err;
576 static const struct got_error *
577 get_gitconfig_path(char **gitconfig_path)
579 const char *homedir = getenv("HOME");
581 *gitconfig_path = NULL;
582 if (homedir) {
583 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
584 return got_error_from_errno("asprintf");
587 return NULL;
590 static const struct got_error *
591 cmd_import(int argc, char *argv[])
593 const struct got_error *error = NULL;
594 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
595 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
596 const char *branch_name = "main";
597 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
598 struct got_repository *repo = NULL;
599 struct got_reference *branch_ref = NULL, *head_ref = NULL;
600 struct got_object_id *new_commit_id = NULL;
601 int ch;
602 struct got_pathlist_head ignores;
603 struct got_pathlist_entry *pe;
604 int preserve_logmsg = 0;
606 TAILQ_INIT(&ignores);
608 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
609 switch (ch) {
610 case 'b':
611 branch_name = optarg;
612 break;
613 case 'm':
614 logmsg = strdup(optarg);
615 if (logmsg == NULL) {
616 error = got_error_from_errno("strdup");
617 goto done;
619 break;
620 case 'r':
621 repo_path = realpath(optarg, NULL);
622 if (repo_path == NULL) {
623 error = got_error_from_errno2("realpath",
624 optarg);
625 goto done;
627 break;
628 case 'I':
629 if (optarg[0] == '\0')
630 break;
631 error = got_pathlist_insert(&pe, &ignores, optarg,
632 NULL);
633 if (error)
634 goto done;
635 break;
636 default:
637 usage_import();
638 /* NOTREACHED */
642 argc -= optind;
643 argv += optind;
645 #ifndef PROFILE
646 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
647 "unveil",
648 NULL) == -1)
649 err(1, "pledge");
650 #endif
651 if (argc != 1)
652 usage_import();
654 if (repo_path == NULL) {
655 repo_path = getcwd(NULL, 0);
656 if (repo_path == NULL)
657 return got_error_from_errno("getcwd");
659 got_path_strip_trailing_slashes(repo_path);
660 error = get_gitconfig_path(&gitconfig_path);
661 if (error)
662 goto done;
663 error = got_repo_open(&repo, repo_path, gitconfig_path);
664 if (error)
665 goto done;
667 error = get_author(&author, repo);
668 if (error)
669 return error;
671 /*
672 * Don't let the user create a branch name with a leading '-'.
673 * While technically a valid reference name, this case is usually
674 * an unintended typo.
675 */
676 if (branch_name[0] == '-')
677 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
679 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
680 error = got_error_from_errno("asprintf");
681 goto done;
684 error = got_ref_open(&branch_ref, repo, refname, 0);
685 if (error) {
686 if (error->code != GOT_ERR_NOT_REF)
687 goto done;
688 } else {
689 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
690 "import target branch already exists");
691 goto done;
694 path_dir = realpath(argv[0], NULL);
695 if (path_dir == NULL) {
696 error = got_error_from_errno2("realpath", argv[0]);
697 goto done;
699 got_path_strip_trailing_slashes(path_dir);
701 /*
702 * unveil(2) traverses exec(2); if an editor is used we have
703 * to apply unveil after the log message has been written.
704 */
705 if (logmsg == NULL || strlen(logmsg) == 0) {
706 error = get_editor(&editor);
707 if (error)
708 goto done;
709 free(logmsg);
710 error = collect_import_msg(&logmsg, &logmsg_path, editor,
711 path_dir, refname);
712 if (error) {
713 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
714 logmsg_path != NULL)
715 preserve_logmsg = 1;
716 goto done;
720 if (unveil(path_dir, "r") != 0) {
721 error = got_error_from_errno2("unveil", path_dir);
722 if (logmsg_path)
723 preserve_logmsg = 1;
724 goto done;
727 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
728 if (error) {
729 if (logmsg_path)
730 preserve_logmsg = 1;
731 goto done;
734 error = got_repo_import(&new_commit_id, path_dir, logmsg,
735 author, &ignores, repo, import_progress, NULL);
736 if (error) {
737 if (logmsg_path)
738 preserve_logmsg = 1;
739 goto done;
742 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
743 if (error) {
744 if (logmsg_path)
745 preserve_logmsg = 1;
746 goto done;
749 error = got_ref_write(branch_ref, repo);
750 if (error) {
751 if (logmsg_path)
752 preserve_logmsg = 1;
753 goto done;
756 error = got_object_id_str(&id_str, new_commit_id);
757 if (error) {
758 if (logmsg_path)
759 preserve_logmsg = 1;
760 goto done;
763 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
764 if (error) {
765 if (error->code != GOT_ERR_NOT_REF) {
766 if (logmsg_path)
767 preserve_logmsg = 1;
768 goto done;
771 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
772 branch_ref);
773 if (error) {
774 if (logmsg_path)
775 preserve_logmsg = 1;
776 goto done;
779 error = got_ref_write(head_ref, repo);
780 if (error) {
781 if (logmsg_path)
782 preserve_logmsg = 1;
783 goto done;
787 printf("Created branch %s with commit %s\n",
788 got_ref_get_name(branch_ref), id_str);
789 done:
790 if (preserve_logmsg) {
791 fprintf(stderr, "%s: log message preserved in %s\n",
792 getprogname(), logmsg_path);
793 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
794 error = got_error_from_errno2("unlink", logmsg_path);
795 free(logmsg);
796 free(logmsg_path);
797 free(repo_path);
798 free(editor);
799 free(refname);
800 free(new_commit_id);
801 free(id_str);
802 free(author);
803 free(gitconfig_path);
804 if (branch_ref)
805 got_ref_close(branch_ref);
806 if (head_ref)
807 got_ref_close(head_ref);
808 return error;
811 __dead static void
812 usage_clone(void)
814 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
815 "[-R reference] repository-url [directory]\n", getprogname());
816 exit(1);
819 struct got_fetch_progress_arg {
820 char last_scaled_size[FMT_SCALED_STRSIZE];
821 int last_p_indexed;
822 int last_p_resolved;
823 int verbosity;
824 };
826 static const struct got_error *
827 fetch_progress(void *arg, const char *message, off_t packfile_size,
828 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
830 struct got_fetch_progress_arg *a = arg;
831 char scaled_size[FMT_SCALED_STRSIZE];
832 int p_indexed, p_resolved;
833 int print_size = 0, print_indexed = 0, print_resolved = 0;
835 if (a->verbosity < 0)
836 return NULL;
838 if (message && message[0] != '\0') {
839 printf("\rserver: %s", message);
840 fflush(stdout);
841 return NULL;
844 if (packfile_size > 0 || nobj_indexed > 0) {
845 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
846 (a->last_scaled_size[0] == '\0' ||
847 strcmp(scaled_size, a->last_scaled_size)) != 0) {
848 print_size = 1;
849 if (strlcpy(a->last_scaled_size, scaled_size,
850 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
851 return got_error(GOT_ERR_NO_SPACE);
853 if (nobj_indexed > 0) {
854 p_indexed = (nobj_indexed * 100) / nobj_total;
855 if (p_indexed != a->last_p_indexed) {
856 a->last_p_indexed = p_indexed;
857 print_indexed = 1;
858 print_size = 1;
861 if (nobj_resolved > 0) {
862 p_resolved = (nobj_resolved * 100) /
863 (nobj_total - nobj_loose);
864 if (p_resolved != a->last_p_resolved) {
865 a->last_p_resolved = p_resolved;
866 print_resolved = 1;
867 print_indexed = 1;
868 print_size = 1;
873 if (print_size || print_indexed || print_resolved)
874 printf("\r");
875 if (print_size)
876 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
877 if (print_indexed)
878 printf("; indexing %d%%", p_indexed);
879 if (print_resolved)
880 printf("; resolving deltas %d%%", p_resolved);
881 if (print_size || print_indexed || print_resolved)
882 fflush(stdout);
884 return NULL;
887 static const struct got_error *
888 create_symref(const char *refname, struct got_reference *target_ref,
889 int verbosity, struct got_repository *repo)
891 const struct got_error *err;
892 struct got_reference *head_symref;
894 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
895 if (err)
896 return err;
898 err = got_ref_write(head_symref, repo);
899 got_ref_close(head_symref);
900 if (err == NULL && verbosity > 0) {
901 printf("Created reference %s: %s\n", GOT_REF_HEAD,
902 got_ref_get_name(target_ref));
904 return err;
907 static const struct got_error *
908 list_remote_refs(struct got_pathlist_head *symrefs,
909 struct got_pathlist_head *refs)
911 const struct got_error *err;
912 struct got_pathlist_entry *pe;
914 TAILQ_FOREACH(pe, symrefs, entry) {
915 const char *refname = pe->path;
916 const char *targetref = pe->data;
918 printf("%s: %s\n", refname, targetref);
921 TAILQ_FOREACH(pe, refs, entry) {
922 const char *refname = pe->path;
923 struct got_object_id *id = pe->data;
924 char *id_str;
926 err = got_object_id_str(&id_str, id);
927 if (err)
928 return err;
929 printf("%s: %s\n", refname, id_str);
930 free(id_str);
933 return NULL;
936 static const struct got_error *
937 create_ref(const char *refname, struct got_object_id *id,
938 int verbosity, struct got_repository *repo)
940 const struct got_error *err = NULL;
941 struct got_reference *ref;
942 char *id_str;
944 err = got_object_id_str(&id_str, id);
945 if (err)
946 return err;
948 err = got_ref_alloc(&ref, refname, id);
949 if (err)
950 goto done;
952 err = got_ref_write(ref, repo);
953 got_ref_close(ref);
955 if (err == NULL && verbosity >= 0)
956 printf("Created reference %s: %s\n", refname, id_str);
957 done:
958 free(id_str);
959 return err;
962 static int
963 match_wanted_ref(const char *refname, const char *wanted_ref)
965 if (strncmp(refname, "refs/", 5) != 0)
966 return 0;
967 refname += 5;
969 /*
970 * Prevent fetching of references that won't make any
971 * sense outside of the remote repository's context.
972 */
973 if (strncmp(refname, "got/", 4) == 0)
974 return 0;
975 if (strncmp(refname, "remotes/", 8) == 0)
976 return 0;
978 if (strncmp(wanted_ref, "refs/", 5) == 0)
979 wanted_ref += 5;
981 /* Allow prefix match. */
982 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
983 return 1;
985 /* Allow exact match. */
986 return (strcmp(refname, wanted_ref) == 0);
989 static int
990 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
992 struct got_pathlist_entry *pe;
994 TAILQ_FOREACH(pe, wanted_refs, entry) {
995 if (match_wanted_ref(refname, pe->path))
996 return 1;
999 return 0;
1002 static const struct got_error *
1003 create_wanted_ref(const char *refname, struct got_object_id *id,
1004 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1006 const struct got_error *err;
1007 char *remote_refname;
1009 if (strncmp("refs/", refname, 5) == 0)
1010 refname += 5;
1012 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1013 remote_repo_name, refname) == -1)
1014 return got_error_from_errno("asprintf");
1016 err = create_ref(remote_refname, id, verbosity, repo);
1017 free(remote_refname);
1018 return err;
1021 static const struct got_error *
1022 cmd_clone(int argc, char *argv[])
1024 const struct got_error *error = NULL;
1025 const char *uri, *dirname;
1026 char *proto, *host, *port, *repo_name, *server_path;
1027 char *default_destdir = NULL, *id_str = NULL;
1028 const char *repo_path;
1029 struct got_repository *repo = NULL;
1030 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1031 struct got_pathlist_entry *pe;
1032 struct got_object_id *pack_hash = NULL;
1033 int ch, fetchfd = -1, fetchstatus;
1034 pid_t fetchpid = -1;
1035 struct got_fetch_progress_arg fpa;
1036 char *git_url = NULL;
1037 char *gitconfig_path = NULL;
1038 char *gitconfig = NULL;
1039 FILE *gitconfig_file = NULL;
1040 ssize_t n;
1041 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1042 int list_refs_only = 0;
1043 struct got_reference *head_symref = NULL;
1045 TAILQ_INIT(&refs);
1046 TAILQ_INIT(&symrefs);
1047 TAILQ_INIT(&wanted_branches);
1048 TAILQ_INIT(&wanted_refs);
1050 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1051 switch (ch) {
1052 case 'a':
1053 fetch_all_branches = 1;
1054 break;
1055 case 'b':
1056 error = got_pathlist_append(&wanted_branches,
1057 optarg, NULL);
1058 if (error)
1059 return error;
1060 break;
1061 case 'l':
1062 list_refs_only = 1;
1063 break;
1064 case 'm':
1065 mirror_references = 1;
1066 break;
1067 case 'v':
1068 if (verbosity < 0)
1069 verbosity = 0;
1070 else if (verbosity < 3)
1071 verbosity++;
1072 break;
1073 case 'q':
1074 verbosity = -1;
1075 break;
1076 case 'R':
1077 error = got_pathlist_append(&wanted_refs,
1078 optarg, NULL);
1079 if (error)
1080 return error;
1081 break;
1082 default:
1083 usage_clone();
1084 break;
1087 argc -= optind;
1088 argv += optind;
1090 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1091 errx(1, "-a and -b options are mutually exclusive");
1092 if (list_refs_only) {
1093 if (!TAILQ_EMPTY(&wanted_branches))
1094 errx(1, "-l and -b options are mutually exclusive");
1095 if (fetch_all_branches)
1096 errx(1, "-l and -a options are mutually exclusive");
1097 if (mirror_references)
1098 errx(1, "-l and -m options are mutually exclusive");
1099 if (verbosity == -1)
1100 errx(1, "-l and -q options are mutually exclusive");
1101 if (!TAILQ_EMPTY(&wanted_refs))
1102 errx(1, "-l and -R options are mutually exclusive");
1105 uri = argv[0];
1107 if (argc == 1)
1108 dirname = NULL;
1109 else if (argc == 2)
1110 dirname = argv[1];
1111 else
1112 usage_clone();
1114 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1115 &repo_name, argv[0]);
1116 if (error)
1117 goto done;
1119 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1120 host, port ? ":" : "", port ? port : "",
1121 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1122 error = got_error_from_errno("asprintf");
1123 goto done;
1126 if (strcmp(proto, "git") == 0) {
1127 #ifndef PROFILE
1128 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1129 "sendfd dns inet unveil", NULL) == -1)
1130 err(1, "pledge");
1131 #endif
1132 } else if (strcmp(proto, "git+ssh") == 0 ||
1133 strcmp(proto, "ssh") == 0) {
1134 #ifndef PROFILE
1135 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1136 "sendfd unveil", NULL) == -1)
1137 err(1, "pledge");
1138 #endif
1139 } else if (strcmp(proto, "http") == 0 ||
1140 strcmp(proto, "git+http") == 0) {
1141 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1142 goto done;
1143 } else {
1144 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1145 goto done;
1147 if (dirname == NULL) {
1148 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1149 error = got_error_from_errno("asprintf");
1150 goto done;
1152 repo_path = default_destdir;
1153 } else
1154 repo_path = dirname;
1156 if (!list_refs_only) {
1157 error = got_path_mkdir(repo_path);
1158 if (error)
1159 goto done;
1161 error = got_repo_init(repo_path);
1162 if (error)
1163 goto done;
1164 error = got_repo_open(&repo, repo_path, NULL);
1165 if (error)
1166 goto done;
1169 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1170 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1171 error = got_error_from_errno2("unveil",
1172 GOT_FETCH_PATH_SSH);
1173 goto done;
1176 error = apply_unveil(repo ? got_repo_get_path(repo) : NULL, 0, NULL);
1177 if (error)
1178 goto done;
1180 if (verbosity >= 0)
1181 printf("Connecting to %s%s%s\n", host,
1182 port ? ":" : "", port ? port : "");
1184 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1185 server_path, verbosity);
1186 if (error)
1187 goto done;
1189 fpa.last_scaled_size[0] = '\0';
1190 fpa.last_p_indexed = -1;
1191 fpa.last_p_resolved = -1;
1192 fpa.verbosity = verbosity;
1193 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1194 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1195 fetch_all_branches, &wanted_branches, &wanted_refs,
1196 list_refs_only, verbosity, fetchfd, repo,
1197 fetch_progress, &fpa);
1198 if (error)
1199 goto done;
1201 if (list_refs_only) {
1202 error = list_remote_refs(&symrefs, &refs);
1203 goto done;
1206 error = got_object_id_str(&id_str, pack_hash);
1207 if (error)
1208 goto done;
1209 if (verbosity >= 0)
1210 printf("\nFetched %s.pack\n", id_str);
1211 free(id_str);
1213 /* Set up references provided with the pack file. */
1214 TAILQ_FOREACH(pe, &refs, entry) {
1215 const char *refname = pe->path;
1216 struct got_object_id *id = pe->data;
1217 char *remote_refname;
1219 if (is_wanted_ref(&wanted_refs, refname) &&
1220 !mirror_references) {
1221 error = create_wanted_ref(refname, id,
1222 GOT_FETCH_DEFAULT_REMOTE_NAME,
1223 verbosity - 1, repo);
1224 if (error)
1225 goto done;
1226 continue;
1229 error = create_ref(refname, id, verbosity - 1, repo);
1230 if (error)
1231 goto done;
1233 if (mirror_references)
1234 continue;
1236 if (strncmp("refs/heads/", refname, 11) != 0)
1237 continue;
1239 if (asprintf(&remote_refname,
1240 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1241 refname + 11) == -1) {
1242 error = got_error_from_errno("asprintf");
1243 goto done;
1245 error = create_ref(remote_refname, id, verbosity - 1, repo);
1246 free(remote_refname);
1247 if (error)
1248 goto done;
1251 /* Set the HEAD reference if the server provided one. */
1252 TAILQ_FOREACH(pe, &symrefs, entry) {
1253 struct got_reference *target_ref;
1254 const char *refname = pe->path;
1255 const char *target = pe->data;
1256 char *remote_refname = NULL, *remote_target = NULL;
1258 if (strcmp(refname, GOT_REF_HEAD) != 0)
1259 continue;
1261 error = got_ref_open(&target_ref, repo, target, 0);
1262 if (error) {
1263 if (error->code == GOT_ERR_NOT_REF) {
1264 error = NULL;
1265 continue;
1267 goto done;
1270 error = create_symref(refname, target_ref, verbosity, repo);
1271 got_ref_close(target_ref);
1272 if (error)
1273 goto done;
1275 if (mirror_references)
1276 continue;
1278 if (strncmp("refs/heads/", target, 11) != 0)
1279 continue;
1281 if (asprintf(&remote_refname,
1282 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1283 refname) == -1) {
1284 error = got_error_from_errno("asprintf");
1285 goto done;
1287 if (asprintf(&remote_target,
1288 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1289 target + 11) == -1) {
1290 error = got_error_from_errno("asprintf");
1291 free(remote_refname);
1292 goto done;
1294 error = got_ref_open(&target_ref, repo, remote_target, 0);
1295 if (error) {
1296 free(remote_refname);
1297 free(remote_target);
1298 if (error->code == GOT_ERR_NOT_REF) {
1299 error = NULL;
1300 continue;
1302 goto done;
1304 error = create_symref(remote_refname, target_ref,
1305 verbosity - 1, repo);
1306 free(remote_refname);
1307 free(remote_target);
1308 got_ref_close(target_ref);
1309 if (error)
1310 goto done;
1312 if (pe == NULL) {
1314 * We failed to set the HEAD reference. If we asked for
1315 * a set of wanted branches use the first of one of those
1316 * which could be fetched instead.
1318 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1319 const char *target = pe->path;
1320 struct got_reference *target_ref;
1322 error = got_ref_open(&target_ref, repo, target, 0);
1323 if (error) {
1324 if (error->code == GOT_ERR_NOT_REF) {
1325 error = NULL;
1326 continue;
1328 goto done;
1331 error = create_symref(GOT_REF_HEAD, target_ref,
1332 verbosity, repo);
1333 got_ref_close(target_ref);
1334 if (error)
1335 goto done;
1336 break;
1340 /* Create a config file git-fetch(1) can understand. */
1341 gitconfig_path = got_repo_get_path_gitconfig(repo);
1342 if (gitconfig_path == NULL) {
1343 error = got_error_from_errno("got_repo_get_path_gitconfig");
1344 goto done;
1346 gitconfig_file = fopen(gitconfig_path, "a");
1347 if (gitconfig_file == NULL) {
1348 error = got_error_from_errno2("fopen", gitconfig_path);
1349 goto done;
1351 if (mirror_references) {
1352 if (asprintf(&gitconfig,
1353 "[remote \"%s\"]\n"
1354 "\turl = %s\n"
1355 "\tfetch = +refs/*:refs/*\n"
1356 "\tmirror = true\n",
1357 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1358 error = got_error_from_errno("asprintf");
1359 goto done;
1361 } else if (fetch_all_branches) {
1362 if (asprintf(&gitconfig,
1363 "[remote \"%s\"]\n"
1364 "\turl = %s\n"
1365 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1366 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1367 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1368 error = got_error_from_errno("asprintf");
1369 goto done;
1371 } else {
1372 const char *branchname;
1375 * If the server specified a default branch, use just that one.
1376 * Otherwise fall back to fetching all branches on next fetch.
1378 if (head_symref) {
1379 branchname = got_ref_get_symref_target(head_symref);
1380 if (strncmp(branchname, "refs/heads/", 11) == 0)
1381 branchname += 11;
1382 } else
1383 branchname = "*"; /* fall back to all branches */
1384 if (asprintf(&gitconfig,
1385 "[remote \"%s\"]\n"
1386 "\turl = %s\n"
1387 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1388 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1389 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1390 branchname) == -1) {
1391 error = got_error_from_errno("asprintf");
1392 goto done;
1395 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1396 if (n != strlen(gitconfig)) {
1397 error = got_ferror(gitconfig_file, GOT_ERR_IO);
1398 goto done;
1401 if (verbosity >= 0)
1402 printf("Created %s repository '%s'\n",
1403 mirror_references ? "mirrored" : "cloned", repo_path);
1404 done:
1405 if (fetchpid > 0) {
1406 if (kill(fetchpid, SIGTERM) == -1)
1407 error = got_error_from_errno("kill");
1408 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1409 error = got_error_from_errno("waitpid");
1411 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1412 error = got_error_from_errno("close");
1413 if (gitconfig_file && fclose(gitconfig_file) == EOF && error == NULL)
1414 error = got_error_from_errno("fclose");
1415 if (repo)
1416 got_repo_close(repo);
1417 if (head_symref)
1418 got_ref_close(head_symref);
1419 TAILQ_FOREACH(pe, &refs, entry) {
1420 free((void *)pe->path);
1421 free(pe->data);
1423 got_pathlist_free(&refs);
1424 TAILQ_FOREACH(pe, &symrefs, entry) {
1425 free((void *)pe->path);
1426 free(pe->data);
1428 got_pathlist_free(&symrefs);
1429 got_pathlist_free(&wanted_branches);
1430 got_pathlist_free(&wanted_refs);
1431 free(pack_hash);
1432 free(proto);
1433 free(host);
1434 free(port);
1435 free(server_path);
1436 free(repo_name);
1437 free(default_destdir);
1438 free(gitconfig_path);
1439 free(git_url);
1440 return error;
1443 static const struct got_error *
1444 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1445 int replace_tags, int verbosity, struct got_repository *repo)
1447 const struct got_error *err = NULL;
1448 char *new_id_str = NULL;
1449 struct got_object_id *old_id = NULL;
1451 err = got_object_id_str(&new_id_str, new_id);
1452 if (err)
1453 goto done;
1455 if (!replace_tags &&
1456 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1457 err = got_ref_resolve(&old_id, repo, ref);
1458 if (err)
1459 goto done;
1460 if (got_object_id_cmp(old_id, new_id) == 0)
1461 goto done;
1462 if (verbosity >= 0) {
1463 printf("Rejecting update of existing tag %s: %s\n",
1464 got_ref_get_name(ref), new_id_str);
1466 goto done;
1469 if (got_ref_is_symbolic(ref)) {
1470 if (verbosity >= 0) {
1471 printf("Replacing reference %s: %s\n",
1472 got_ref_get_name(ref),
1473 got_ref_get_symref_target(ref));
1475 err = got_ref_change_symref_to_ref(ref, new_id);
1476 if (err)
1477 goto done;
1478 err = got_ref_write(ref, repo);
1479 if (err)
1480 goto done;
1481 } else {
1482 err = got_ref_resolve(&old_id, repo, ref);
1483 if (err)
1484 goto done;
1485 if (got_object_id_cmp(old_id, new_id) == 0)
1486 goto done;
1488 err = got_ref_change_ref(ref, new_id);
1489 if (err)
1490 goto done;
1491 err = got_ref_write(ref, repo);
1492 if (err)
1493 goto done;
1496 if (verbosity >= 0)
1497 printf("Updated %s: %s\n", got_ref_get_name(ref),
1498 new_id_str);
1499 done:
1500 free(old_id);
1501 free(new_id_str);
1502 return err;
1505 static const struct got_error *
1506 update_symref(const char *refname, struct got_reference *target_ref,
1507 int verbosity, struct got_repository *repo)
1509 const struct got_error *err = NULL, *unlock_err;
1510 struct got_reference *symref;
1511 int symref_is_locked = 0;
1513 err = got_ref_open(&symref, repo, refname, 1);
1514 if (err) {
1515 if (err->code != GOT_ERR_NOT_REF)
1516 return err;
1517 err = got_ref_alloc_symref(&symref, refname, target_ref);
1518 if (err)
1519 goto done;
1521 err = got_ref_write(symref, repo);
1522 if (err)
1523 goto done;
1525 if (verbosity >= 0)
1526 printf("Created reference %s: %s\n",
1527 got_ref_get_name(symref),
1528 got_ref_get_symref_target(symref));
1529 } else {
1530 symref_is_locked = 1;
1532 if (strcmp(got_ref_get_symref_target(symref),
1533 got_ref_get_name(target_ref)) == 0)
1534 goto done;
1536 err = got_ref_change_symref(symref,
1537 got_ref_get_name(target_ref));
1538 if (err)
1539 goto done;
1541 err = got_ref_write(symref, repo);
1542 if (err)
1543 goto done;
1545 if (verbosity >= 0)
1546 printf("Updated %s: %s\n", got_ref_get_name(symref),
1547 got_ref_get_symref_target(symref));
1550 done:
1551 if (symref_is_locked) {
1552 unlock_err = got_ref_unlock(symref);
1553 if (unlock_err && err == NULL)
1554 err = unlock_err;
1556 got_ref_close(symref);
1557 return err;
1560 __dead static void
1561 usage_fetch(void)
1563 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1564 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1565 "[remote-repository-name]\n",
1566 getprogname());
1567 exit(1);
1570 static const struct got_error *
1571 delete_missing_ref(struct got_reference *ref,
1572 int verbosity, struct got_repository *repo)
1574 const struct got_error *err = NULL;
1575 struct got_object_id *id = NULL;
1576 char *id_str = NULL;
1578 if (got_ref_is_symbolic(ref)) {
1579 err = got_ref_delete(ref, repo);
1580 if (err)
1581 return err;
1582 if (verbosity >= 0) {
1583 printf("Deleted reference %s: %s\n",
1584 got_ref_get_name(ref),
1585 got_ref_get_symref_target(ref));
1587 } else {
1588 err = got_ref_resolve(&id, repo, ref);
1589 if (err)
1590 return err;
1591 err = got_object_id_str(&id_str, id);
1592 if (err)
1593 goto done;
1595 err = got_ref_delete(ref, repo);
1596 if (err)
1597 goto done;
1598 if (verbosity >= 0) {
1599 printf("Deleted reference %s: %s\n",
1600 got_ref_get_name(ref), id_str);
1603 done:
1604 free(id);
1605 free(id_str);
1606 return NULL;
1609 static const struct got_error *
1610 delete_missing_refs(struct got_pathlist_head *their_refs,
1611 struct got_pathlist_head *their_symrefs, struct got_remote_repo *remote,
1612 int verbosity, struct got_repository *repo)
1614 const struct got_error *err = NULL, *unlock_err;
1615 struct got_reflist_head my_refs;
1616 struct got_reflist_entry *re;
1617 struct got_pathlist_entry *pe;
1618 char *remote_namespace = NULL;
1619 char *local_refname = NULL;
1621 SIMPLEQ_INIT(&my_refs);
1623 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
1624 == -1)
1625 return got_error_from_errno("asprintf");
1627 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1628 if (err)
1629 goto done;
1631 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1632 const char *refname = got_ref_get_name(re->ref);
1634 if (!remote->mirror_references) {
1635 if (strncmp(refname, remote_namespace,
1636 strlen(remote_namespace)) == 0) {
1637 if (strcmp(refname + strlen(remote_namespace),
1638 GOT_REF_HEAD) == 0)
1639 continue;
1640 if (asprintf(&local_refname, "refs/heads/%s",
1641 refname + strlen(remote_namespace)) == -1) {
1642 err = got_error_from_errno("asprintf");
1643 goto done;
1645 } else if (strncmp(refname, "refs/tags/", 10) != 0)
1646 continue;
1649 TAILQ_FOREACH(pe, their_refs, entry) {
1650 if (strcmp(local_refname, pe->path) == 0)
1651 break;
1653 if (pe != NULL)
1654 continue;
1656 TAILQ_FOREACH(pe, their_symrefs, entry) {
1657 if (strcmp(local_refname, pe->path) == 0)
1658 break;
1660 if (pe != NULL)
1661 continue;
1663 err = delete_missing_ref(re->ref, verbosity, repo);
1664 if (err)
1665 break;
1667 if (local_refname) {
1668 struct got_reference *ref;
1669 err = got_ref_open(&ref, repo, local_refname, 1);
1670 if (err) {
1671 if (err->code != GOT_ERR_NOT_REF)
1672 break;
1673 free(local_refname);
1674 local_refname = NULL;
1675 continue;
1677 err = delete_missing_ref(ref, verbosity, repo);
1678 if (err)
1679 break;
1680 unlock_err = got_ref_unlock(ref);
1681 got_ref_close(ref);
1682 if (unlock_err && err == NULL) {
1683 err = unlock_err;
1684 break;
1687 free(local_refname);
1688 local_refname = NULL;
1691 done:
1692 free(remote_namespace);
1693 free(local_refname);
1694 return err;
1697 static const struct got_error *
1698 update_wanted_ref(const char *refname, struct got_object_id *id,
1699 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1701 const struct got_error *err, *unlock_err;
1702 char *remote_refname;
1703 struct got_reference *ref;
1705 if (strncmp("refs/", refname, 5) == 0)
1706 refname += 5;
1708 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1709 remote_repo_name, refname) == -1)
1710 return got_error_from_errno("asprintf");
1712 err = got_ref_open(&ref, repo, remote_refname, 1);
1713 if (err) {
1714 if (err->code != GOT_ERR_NOT_REF)
1715 goto done;
1716 err = create_ref(remote_refname, id, verbosity, repo);
1717 } else {
1718 err = update_ref(ref, id, 0, verbosity, repo);
1719 unlock_err = got_ref_unlock(ref);
1720 if (unlock_err && err == NULL)
1721 err = unlock_err;
1722 got_ref_close(ref);
1724 done:
1725 free(remote_refname);
1726 return err;
1729 static const struct got_error *
1730 cmd_fetch(int argc, char *argv[])
1732 const struct got_error *error = NULL, *unlock_err;
1733 char *cwd = NULL, *repo_path = NULL;
1734 const char *remote_name;
1735 char *proto = NULL, *host = NULL, *port = NULL;
1736 char *repo_name = NULL, *server_path = NULL;
1737 struct got_remote_repo *remotes, *remote = NULL;
1738 int nremotes;
1739 char *id_str = NULL;
1740 struct got_repository *repo = NULL;
1741 struct got_worktree *worktree = NULL;
1742 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1743 struct got_pathlist_entry *pe;
1744 struct got_object_id *pack_hash = NULL;
1745 int i, ch, fetchfd = -1, fetchstatus;
1746 pid_t fetchpid = -1;
1747 struct got_fetch_progress_arg fpa;
1748 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
1749 int delete_refs = 0, replace_tags = 0;
1751 TAILQ_INIT(&refs);
1752 TAILQ_INIT(&symrefs);
1753 TAILQ_INIT(&wanted_branches);
1754 TAILQ_INIT(&wanted_refs);
1756 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
1757 switch (ch) {
1758 case 'a':
1759 fetch_all_branches = 1;
1760 break;
1761 case 'b':
1762 error = got_pathlist_append(&wanted_branches,
1763 optarg, NULL);
1764 if (error)
1765 return error;
1766 break;
1767 case 'd':
1768 delete_refs = 1;
1769 break;
1770 case 'l':
1771 list_refs_only = 1;
1772 break;
1773 case 'r':
1774 repo_path = realpath(optarg, NULL);
1775 if (repo_path == NULL)
1776 return got_error_from_errno2("realpath",
1777 optarg);
1778 got_path_strip_trailing_slashes(repo_path);
1779 break;
1780 case 't':
1781 replace_tags = 1;
1782 break;
1783 case 'v':
1784 if (verbosity < 0)
1785 verbosity = 0;
1786 else if (verbosity < 3)
1787 verbosity++;
1788 break;
1789 case 'q':
1790 verbosity = -1;
1791 break;
1792 case 'R':
1793 error = got_pathlist_append(&wanted_refs,
1794 optarg, NULL);
1795 if (error)
1796 return error;
1797 break;
1798 default:
1799 usage_fetch();
1800 break;
1803 argc -= optind;
1804 argv += optind;
1806 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1807 errx(1, "-a and -b options are mutually exclusive");
1808 if (list_refs_only) {
1809 if (!TAILQ_EMPTY(&wanted_branches))
1810 errx(1, "-l and -b options are mutually exclusive");
1811 if (fetch_all_branches)
1812 errx(1, "-l and -a options are mutually exclusive");
1813 if (delete_refs)
1814 errx(1, "-l and -d options are mutually exclusive");
1815 if (verbosity == -1)
1816 errx(1, "-l and -q options are mutually exclusive");
1819 if (argc == 0)
1820 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
1821 else if (argc == 1)
1822 remote_name = argv[0];
1823 else
1824 usage_fetch();
1826 cwd = getcwd(NULL, 0);
1827 if (cwd == NULL) {
1828 error = got_error_from_errno("getcwd");
1829 goto done;
1832 if (repo_path == NULL) {
1833 error = got_worktree_open(&worktree, cwd);
1834 if (error && error->code != GOT_ERR_NOT_WORKTREE)
1835 goto done;
1836 else
1837 error = NULL;
1838 if (worktree) {
1839 repo_path =
1840 strdup(got_worktree_get_repo_path(worktree));
1841 if (repo_path == NULL)
1842 error = got_error_from_errno("strdup");
1843 if (error)
1844 goto done;
1845 } else {
1846 repo_path = strdup(cwd);
1847 if (repo_path == NULL) {
1848 error = got_error_from_errno("strdup");
1849 goto done;
1854 error = got_repo_open(&repo, repo_path, NULL);
1855 if (error)
1856 goto done;
1858 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
1859 for (i = 0; i < nremotes; i++) {
1860 remote = &remotes[i];
1861 if (strcmp(remote->name, remote_name) == 0)
1862 break;
1864 if (i == nremotes) {
1865 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
1866 goto done;
1869 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1870 &repo_name, remote->url);
1871 if (error)
1872 goto done;
1874 if (strcmp(proto, "git") == 0) {
1875 #ifndef PROFILE
1876 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1877 "sendfd dns inet unveil", NULL) == -1)
1878 err(1, "pledge");
1879 #endif
1880 } else if (strcmp(proto, "git+ssh") == 0 ||
1881 strcmp(proto, "ssh") == 0) {
1882 #ifndef PROFILE
1883 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1884 "sendfd unveil", NULL) == -1)
1885 err(1, "pledge");
1886 #endif
1887 } else if (strcmp(proto, "http") == 0 ||
1888 strcmp(proto, "git+http") == 0) {
1889 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1890 goto done;
1891 } else {
1892 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1893 goto done;
1896 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1897 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1898 error = got_error_from_errno2("unveil",
1899 GOT_FETCH_PATH_SSH);
1900 goto done;
1903 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
1904 if (error)
1905 goto done;
1907 if (verbosity >= 0)
1908 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
1909 port ? ":" : "", port ? port : "");
1911 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1912 server_path, verbosity);
1913 if (error)
1914 goto done;
1916 fpa.last_scaled_size[0] = '\0';
1917 fpa.last_p_indexed = -1;
1918 fpa.last_p_resolved = -1;
1919 fpa.verbosity = verbosity;
1920 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
1921 remote->mirror_references, fetch_all_branches, &wanted_branches,
1922 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
1923 fetch_progress, &fpa);
1924 if (error)
1925 goto done;
1927 if (list_refs_only) {
1928 error = list_remote_refs(&symrefs, &refs);
1929 goto done;
1932 if (pack_hash == NULL) {
1933 if (verbosity >= 0)
1934 printf("Already up-to-date\n");
1935 } else if (verbosity >= 0) {
1936 error = got_object_id_str(&id_str, pack_hash);
1937 if (error)
1938 goto done;
1939 printf("\nFetched %s.pack\n", id_str);
1940 free(id_str);
1941 id_str = NULL;
1944 /* Update references provided with the pack file. */
1945 TAILQ_FOREACH(pe, &refs, entry) {
1946 const char *refname = pe->path;
1947 struct got_object_id *id = pe->data;
1948 struct got_reference *ref;
1949 char *remote_refname;
1951 if (is_wanted_ref(&wanted_refs, refname) &&
1952 !remote->mirror_references) {
1953 error = update_wanted_ref(refname, id,
1954 remote->name, verbosity, repo);
1955 if (error)
1956 goto done;
1957 continue;
1960 if (remote->mirror_references ||
1961 strncmp("refs/tags/", refname, 10) == 0) {
1962 error = got_ref_open(&ref, repo, refname, 1);
1963 if (error) {
1964 if (error->code != GOT_ERR_NOT_REF)
1965 goto done;
1966 error = create_ref(refname, id, verbosity,
1967 repo);
1968 if (error)
1969 goto done;
1970 } else {
1971 error = update_ref(ref, id, replace_tags,
1972 verbosity, repo);
1973 unlock_err = got_ref_unlock(ref);
1974 if (unlock_err && error == NULL)
1975 error = unlock_err;
1976 got_ref_close(ref);
1977 if (error)
1978 goto done;
1980 } else if (strncmp("refs/heads/", refname, 11) == 0) {
1981 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1982 remote_name, refname + 11) == -1) {
1983 error = got_error_from_errno("asprintf");
1984 goto done;
1987 error = got_ref_open(&ref, repo, remote_refname, 1);
1988 if (error) {
1989 if (error->code != GOT_ERR_NOT_REF)
1990 goto done;
1991 error = create_ref(remote_refname, id,
1992 verbosity, repo);
1993 if (error)
1994 goto done;
1995 } else {
1996 error = update_ref(ref, id, replace_tags,
1997 verbosity, repo);
1998 unlock_err = got_ref_unlock(ref);
1999 if (unlock_err && error == NULL)
2000 error = unlock_err;
2001 got_ref_close(ref);
2002 if (error)
2003 goto done;
2006 /* Also create a local branch if none exists yet. */
2007 error = got_ref_open(&ref, repo, refname, 1);
2008 if (error) {
2009 if (error->code != GOT_ERR_NOT_REF)
2010 goto done;
2011 error = create_ref(refname, id, verbosity,
2012 repo);
2013 if (error)
2014 goto done;
2015 } else {
2016 unlock_err = got_ref_unlock(ref);
2017 if (unlock_err && error == NULL)
2018 error = unlock_err;
2019 got_ref_close(ref);
2023 if (delete_refs) {
2024 error = delete_missing_refs(&refs, &symrefs, remote,
2025 verbosity, repo);
2026 if (error)
2027 goto done;
2030 if (!remote->mirror_references) {
2031 /* Update remote HEAD reference if the server provided one. */
2032 TAILQ_FOREACH(pe, &symrefs, entry) {
2033 struct got_reference *target_ref;
2034 const char *refname = pe->path;
2035 const char *target = pe->data;
2036 char *remote_refname = NULL, *remote_target = NULL;
2038 if (strcmp(refname, GOT_REF_HEAD) != 0)
2039 continue;
2041 if (strncmp("refs/heads/", target, 11) != 0)
2042 continue;
2044 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2045 remote->name, refname) == -1) {
2046 error = got_error_from_errno("asprintf");
2047 goto done;
2049 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2050 remote->name, target + 11) == -1) {
2051 error = got_error_from_errno("asprintf");
2052 free(remote_refname);
2053 goto done;
2056 error = got_ref_open(&target_ref, repo, remote_target,
2057 0);
2058 if (error) {
2059 free(remote_refname);
2060 free(remote_target);
2061 if (error->code == GOT_ERR_NOT_REF) {
2062 error = NULL;
2063 continue;
2065 goto done;
2067 error = update_symref(remote_refname, target_ref,
2068 verbosity, repo);
2069 free(remote_refname);
2070 free(remote_target);
2071 got_ref_close(target_ref);
2072 if (error)
2073 goto done;
2076 done:
2077 if (fetchpid > 0) {
2078 if (kill(fetchpid, SIGTERM) == -1)
2079 error = got_error_from_errno("kill");
2080 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2081 error = got_error_from_errno("waitpid");
2083 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2084 error = got_error_from_errno("close");
2085 if (repo)
2086 got_repo_close(repo);
2087 if (worktree)
2088 got_worktree_close(worktree);
2089 TAILQ_FOREACH(pe, &refs, entry) {
2090 free((void *)pe->path);
2091 free(pe->data);
2093 got_pathlist_free(&refs);
2094 TAILQ_FOREACH(pe, &symrefs, entry) {
2095 free((void *)pe->path);
2096 free(pe->data);
2098 got_pathlist_free(&symrefs);
2099 got_pathlist_free(&wanted_branches);
2100 got_pathlist_free(&wanted_refs);
2101 free(id_str);
2102 free(cwd);
2103 free(repo_path);
2104 free(pack_hash);
2105 free(proto);
2106 free(host);
2107 free(port);
2108 free(server_path);
2109 free(repo_name);
2110 return error;
2114 __dead static void
2115 usage_checkout(void)
2117 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2118 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2119 exit(1);
2122 static void
2123 show_worktree_base_ref_warning(void)
2125 fprintf(stderr, "%s: warning: could not create a reference "
2126 "to the work tree's base commit; the commit could be "
2127 "garbage-collected by Git; making the repository "
2128 "writable and running 'got update' will prevent this\n",
2129 getprogname());
2132 struct got_checkout_progress_arg {
2133 const char *worktree_path;
2134 int had_base_commit_ref_error;
2137 static const struct got_error *
2138 checkout_progress(void *arg, unsigned char status, const char *path)
2140 struct got_checkout_progress_arg *a = arg;
2142 /* Base commit bump happens silently. */
2143 if (status == GOT_STATUS_BUMP_BASE)
2144 return NULL;
2146 if (status == GOT_STATUS_BASE_REF_ERR) {
2147 a->had_base_commit_ref_error = 1;
2148 return NULL;
2151 while (path[0] == '/')
2152 path++;
2154 printf("%c %s/%s\n", status, a->worktree_path, path);
2155 return NULL;
2158 static const struct got_error *
2159 check_cancelled(void *arg)
2161 if (sigint_received || sigpipe_received)
2162 return got_error(GOT_ERR_CANCELLED);
2163 return NULL;
2166 static const struct got_error *
2167 check_linear_ancestry(struct got_object_id *commit_id,
2168 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2169 struct got_repository *repo)
2171 const struct got_error *err = NULL;
2172 struct got_object_id *yca_id;
2174 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2175 commit_id, base_commit_id, repo, check_cancelled, NULL);
2176 if (err)
2177 return err;
2179 if (yca_id == NULL)
2180 return got_error(GOT_ERR_ANCESTRY);
2183 * Require a straight line of history between the target commit
2184 * and the work tree's base commit.
2186 * Non-linear situations such as this require a rebase:
2188 * (commit) D F (base_commit)
2189 * \ /
2190 * C E
2191 * \ /
2192 * B (yca)
2193 * |
2194 * A
2196 * 'got update' only handles linear cases:
2197 * Update forwards in time: A (base/yca) - B - C - D (commit)
2198 * Update backwards in time: D (base) - C - B - A (commit/yca)
2200 if (allow_forwards_in_time_only) {
2201 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2202 return got_error(GOT_ERR_ANCESTRY);
2203 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2204 got_object_id_cmp(base_commit_id, yca_id) != 0)
2205 return got_error(GOT_ERR_ANCESTRY);
2207 free(yca_id);
2208 return NULL;
2211 static const struct got_error *
2212 check_same_branch(struct got_object_id *commit_id,
2213 struct got_reference *head_ref, struct got_object_id *yca_id,
2214 struct got_repository *repo)
2216 const struct got_error *err = NULL;
2217 struct got_commit_graph *graph = NULL;
2218 struct got_object_id *head_commit_id = NULL;
2219 int is_same_branch = 0;
2221 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2222 if (err)
2223 goto done;
2225 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2226 is_same_branch = 1;
2227 goto done;
2229 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2230 is_same_branch = 1;
2231 goto done;
2234 err = got_commit_graph_open(&graph, "/", 1);
2235 if (err)
2236 goto done;
2238 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2239 check_cancelled, NULL);
2240 if (err)
2241 goto done;
2243 for (;;) {
2244 struct got_object_id *id;
2245 err = got_commit_graph_iter_next(&id, graph, repo,
2246 check_cancelled, NULL);
2247 if (err) {
2248 if (err->code == GOT_ERR_ITER_COMPLETED)
2249 err = NULL;
2250 break;
2253 if (id) {
2254 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2255 break;
2256 if (got_object_id_cmp(id, commit_id) == 0) {
2257 is_same_branch = 1;
2258 break;
2262 done:
2263 if (graph)
2264 got_commit_graph_close(graph);
2265 free(head_commit_id);
2266 if (!err && !is_same_branch)
2267 err = got_error(GOT_ERR_ANCESTRY);
2268 return err;
2271 static const struct got_error *
2272 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2274 static char msg[512];
2275 const char *branch_name;
2277 if (got_ref_is_symbolic(ref))
2278 branch_name = got_ref_get_symref_target(ref);
2279 else
2280 branch_name = got_ref_get_name(ref);
2282 if (strncmp("refs/heads/", branch_name, 11) == 0)
2283 branch_name += 11;
2285 snprintf(msg, sizeof(msg),
2286 "target commit is not contained in branch '%s'; "
2287 "the branch to use must be specified with -b; "
2288 "if necessary a new branch can be created for "
2289 "this commit with 'got branch -c %s BRANCH_NAME'",
2290 branch_name, commit_id_str);
2292 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2295 static const struct got_error *
2296 cmd_checkout(int argc, char *argv[])
2298 const struct got_error *error = NULL;
2299 struct got_repository *repo = NULL;
2300 struct got_reference *head_ref = NULL;
2301 struct got_worktree *worktree = NULL;
2302 char *repo_path = NULL;
2303 char *worktree_path = NULL;
2304 const char *path_prefix = "";
2305 const char *branch_name = GOT_REF_HEAD;
2306 char *commit_id_str = NULL;
2307 int ch, same_path_prefix, allow_nonempty = 0;
2308 struct got_pathlist_head paths;
2309 struct got_checkout_progress_arg cpa;
2311 TAILQ_INIT(&paths);
2313 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2314 switch (ch) {
2315 case 'b':
2316 branch_name = optarg;
2317 break;
2318 case 'c':
2319 commit_id_str = strdup(optarg);
2320 if (commit_id_str == NULL)
2321 return got_error_from_errno("strdup");
2322 break;
2323 case 'E':
2324 allow_nonempty = 1;
2325 break;
2326 case 'p':
2327 path_prefix = optarg;
2328 break;
2329 default:
2330 usage_checkout();
2331 /* NOTREACHED */
2335 argc -= optind;
2336 argv += optind;
2338 #ifndef PROFILE
2339 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2340 "unveil", NULL) == -1)
2341 err(1, "pledge");
2342 #endif
2343 if (argc == 1) {
2344 char *cwd, *base, *dotgit;
2345 repo_path = realpath(argv[0], NULL);
2346 if (repo_path == NULL)
2347 return got_error_from_errno2("realpath", argv[0]);
2348 cwd = getcwd(NULL, 0);
2349 if (cwd == NULL) {
2350 error = got_error_from_errno("getcwd");
2351 goto done;
2353 if (path_prefix[0]) {
2354 base = basename(path_prefix);
2355 if (base == NULL) {
2356 error = got_error_from_errno2("basename",
2357 path_prefix);
2358 goto done;
2360 } else {
2361 base = basename(repo_path);
2362 if (base == NULL) {
2363 error = got_error_from_errno2("basename",
2364 repo_path);
2365 goto done;
2368 dotgit = strstr(base, ".git");
2369 if (dotgit)
2370 *dotgit = '\0';
2371 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2372 error = got_error_from_errno("asprintf");
2373 free(cwd);
2374 goto done;
2376 free(cwd);
2377 } else if (argc == 2) {
2378 repo_path = realpath(argv[0], NULL);
2379 if (repo_path == NULL) {
2380 error = got_error_from_errno2("realpath", argv[0]);
2381 goto done;
2383 worktree_path = realpath(argv[1], NULL);
2384 if (worktree_path == NULL) {
2385 if (errno != ENOENT) {
2386 error = got_error_from_errno2("realpath",
2387 argv[1]);
2388 goto done;
2390 worktree_path = strdup(argv[1]);
2391 if (worktree_path == NULL) {
2392 error = got_error_from_errno("strdup");
2393 goto done;
2396 } else
2397 usage_checkout();
2399 got_path_strip_trailing_slashes(repo_path);
2400 got_path_strip_trailing_slashes(worktree_path);
2402 error = got_repo_open(&repo, repo_path, NULL);
2403 if (error != NULL)
2404 goto done;
2406 /* Pre-create work tree path for unveil(2) */
2407 error = got_path_mkdir(worktree_path);
2408 if (error) {
2409 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2410 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2411 goto done;
2412 if (!allow_nonempty &&
2413 !got_path_dir_is_empty(worktree_path)) {
2414 error = got_error_path(worktree_path,
2415 GOT_ERR_DIR_NOT_EMPTY);
2416 goto done;
2420 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2421 if (error)
2422 goto done;
2424 error = got_ref_open(&head_ref, repo, branch_name, 0);
2425 if (error != NULL)
2426 goto done;
2428 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2429 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2430 goto done;
2432 error = got_worktree_open(&worktree, worktree_path);
2433 if (error != NULL)
2434 goto done;
2436 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2437 path_prefix);
2438 if (error != NULL)
2439 goto done;
2440 if (!same_path_prefix) {
2441 error = got_error(GOT_ERR_PATH_PREFIX);
2442 goto done;
2445 if (commit_id_str) {
2446 struct got_object_id *commit_id;
2447 error = got_repo_match_object_id(&commit_id, NULL,
2448 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2449 if (error)
2450 goto done;
2451 error = check_linear_ancestry(commit_id,
2452 got_worktree_get_base_commit_id(worktree), 0, repo);
2453 if (error != NULL) {
2454 free(commit_id);
2455 if (error->code == GOT_ERR_ANCESTRY) {
2456 error = checkout_ancestry_error(
2457 head_ref, commit_id_str);
2459 goto done;
2461 error = check_same_branch(commit_id, head_ref, NULL, repo);
2462 if (error) {
2463 if (error->code == GOT_ERR_ANCESTRY) {
2464 error = checkout_ancestry_error(
2465 head_ref, commit_id_str);
2467 goto done;
2469 error = got_worktree_set_base_commit_id(worktree, repo,
2470 commit_id);
2471 free(commit_id);
2472 if (error)
2473 goto done;
2476 error = got_pathlist_append(&paths, "", NULL);
2477 if (error)
2478 goto done;
2479 cpa.worktree_path = worktree_path;
2480 cpa.had_base_commit_ref_error = 0;
2481 error = got_worktree_checkout_files(worktree, &paths, repo,
2482 checkout_progress, &cpa, check_cancelled, NULL);
2483 if (error != NULL)
2484 goto done;
2486 printf("Now shut up and hack\n");
2487 if (cpa.had_base_commit_ref_error)
2488 show_worktree_base_ref_warning();
2489 done:
2490 got_pathlist_free(&paths);
2491 free(commit_id_str);
2492 free(repo_path);
2493 free(worktree_path);
2494 return error;
2497 struct got_update_progress_arg {
2498 int did_something;
2499 int conflicts;
2500 int obstructed;
2501 int not_updated;
2504 void
2505 print_update_progress_stats(struct got_update_progress_arg *upa)
2507 if (!upa->did_something)
2508 return;
2510 if (upa->conflicts > 0)
2511 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2512 if (upa->obstructed > 0)
2513 printf("File paths obstructed by a non-regular file: %d\n",
2514 upa->obstructed);
2515 if (upa->not_updated > 0)
2516 printf("Files not updated because of existing merge "
2517 "conflicts: %d\n", upa->not_updated);
2520 __dead static void
2521 usage_update(void)
2523 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2524 getprogname());
2525 exit(1);
2528 static const struct got_error *
2529 update_progress(void *arg, unsigned char status, const char *path)
2531 struct got_update_progress_arg *upa = arg;
2533 if (status == GOT_STATUS_EXISTS ||
2534 status == GOT_STATUS_BASE_REF_ERR)
2535 return NULL;
2537 upa->did_something = 1;
2539 /* Base commit bump happens silently. */
2540 if (status == GOT_STATUS_BUMP_BASE)
2541 return NULL;
2543 if (status == GOT_STATUS_CONFLICT)
2544 upa->conflicts++;
2545 if (status == GOT_STATUS_OBSTRUCTED)
2546 upa->obstructed++;
2547 if (status == GOT_STATUS_CANNOT_UPDATE)
2548 upa->not_updated++;
2550 while (path[0] == '/')
2551 path++;
2552 printf("%c %s\n", status, path);
2553 return NULL;
2556 static const struct got_error *
2557 switch_head_ref(struct got_reference *head_ref,
2558 struct got_object_id *commit_id, struct got_worktree *worktree,
2559 struct got_repository *repo)
2561 const struct got_error *err = NULL;
2562 char *base_id_str;
2563 int ref_has_moved = 0;
2565 /* Trivial case: switching between two different references. */
2566 if (strcmp(got_ref_get_name(head_ref),
2567 got_worktree_get_head_ref_name(worktree)) != 0) {
2568 printf("Switching work tree from %s to %s\n",
2569 got_worktree_get_head_ref_name(worktree),
2570 got_ref_get_name(head_ref));
2571 return got_worktree_set_head_ref(worktree, head_ref);
2574 err = check_linear_ancestry(commit_id,
2575 got_worktree_get_base_commit_id(worktree), 0, repo);
2576 if (err) {
2577 if (err->code != GOT_ERR_ANCESTRY)
2578 return err;
2579 ref_has_moved = 1;
2581 if (!ref_has_moved)
2582 return NULL;
2584 /* Switching to a rebased branch with the same reference name. */
2585 err = got_object_id_str(&base_id_str,
2586 got_worktree_get_base_commit_id(worktree));
2587 if (err)
2588 return err;
2589 printf("Reference %s now points at a different branch\n",
2590 got_worktree_get_head_ref_name(worktree));
2591 printf("Switching work tree from %s to %s\n", base_id_str,
2592 got_worktree_get_head_ref_name(worktree));
2593 return NULL;
2596 static const struct got_error *
2597 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2599 const struct got_error *err;
2600 int in_progress;
2602 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2603 if (err)
2604 return err;
2605 if (in_progress)
2606 return got_error(GOT_ERR_REBASING);
2608 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2609 if (err)
2610 return err;
2611 if (in_progress)
2612 return got_error(GOT_ERR_HISTEDIT_BUSY);
2614 return NULL;
2617 static const struct got_error *
2618 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2619 char *argv[], struct got_worktree *worktree)
2621 const struct got_error *err = NULL;
2622 char *path;
2623 int i;
2625 if (argc == 0) {
2626 path = strdup("");
2627 if (path == NULL)
2628 return got_error_from_errno("strdup");
2629 return got_pathlist_append(paths, path, NULL);
2632 for (i = 0; i < argc; i++) {
2633 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2634 if (err)
2635 break;
2636 err = got_pathlist_append(paths, path, NULL);
2637 if (err) {
2638 free(path);
2639 break;
2643 return err;
2646 static const struct got_error *
2647 wrap_not_worktree_error(const struct got_error *orig_err,
2648 const char *cmdname, const char *path)
2650 const struct got_error *err;
2651 struct got_repository *repo;
2652 static char msg[512];
2654 err = got_repo_open(&repo, path, NULL);
2655 if (err)
2656 return orig_err;
2658 snprintf(msg, sizeof(msg),
2659 "'got %s' needs a work tree in addition to a git repository\n"
2660 "Work trees can be checked out from this Git repository with "
2661 "'got checkout'.\n"
2662 "The got(1) manual page contains more information.", cmdname);
2663 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2664 got_repo_close(repo);
2665 return err;
2668 static const struct got_error *
2669 cmd_update(int argc, char *argv[])
2671 const struct got_error *error = NULL;
2672 struct got_repository *repo = NULL;
2673 struct got_worktree *worktree = NULL;
2674 char *worktree_path = NULL;
2675 struct got_object_id *commit_id = NULL;
2676 char *commit_id_str = NULL;
2677 const char *branch_name = NULL;
2678 struct got_reference *head_ref = NULL;
2679 struct got_pathlist_head paths;
2680 struct got_pathlist_entry *pe;
2681 int ch;
2682 struct got_update_progress_arg upa;
2684 TAILQ_INIT(&paths);
2686 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2687 switch (ch) {
2688 case 'b':
2689 branch_name = optarg;
2690 break;
2691 case 'c':
2692 commit_id_str = strdup(optarg);
2693 if (commit_id_str == NULL)
2694 return got_error_from_errno("strdup");
2695 break;
2696 default:
2697 usage_update();
2698 /* NOTREACHED */
2702 argc -= optind;
2703 argv += optind;
2705 #ifndef PROFILE
2706 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2707 "unveil", NULL) == -1)
2708 err(1, "pledge");
2709 #endif
2710 worktree_path = getcwd(NULL, 0);
2711 if (worktree_path == NULL) {
2712 error = got_error_from_errno("getcwd");
2713 goto done;
2715 error = got_worktree_open(&worktree, worktree_path);
2716 if (error) {
2717 if (error->code == GOT_ERR_NOT_WORKTREE)
2718 error = wrap_not_worktree_error(error, "update",
2719 worktree_path);
2720 goto done;
2723 error = check_rebase_or_histedit_in_progress(worktree);
2724 if (error)
2725 goto done;
2727 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
2728 NULL);
2729 if (error != NULL)
2730 goto done;
2732 error = apply_unveil(got_repo_get_path(repo), 0,
2733 got_worktree_get_root_path(worktree));
2734 if (error)
2735 goto done;
2737 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2738 if (error)
2739 goto done;
2741 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
2742 got_worktree_get_head_ref_name(worktree), 0);
2743 if (error != NULL)
2744 goto done;
2745 if (commit_id_str == NULL) {
2746 error = got_ref_resolve(&commit_id, repo, head_ref);
2747 if (error != NULL)
2748 goto done;
2749 error = got_object_id_str(&commit_id_str, commit_id);
2750 if (error != NULL)
2751 goto done;
2752 } else {
2753 error = got_repo_match_object_id(&commit_id, NULL,
2754 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2755 free(commit_id_str);
2756 commit_id_str = NULL;
2757 if (error)
2758 goto done;
2759 error = got_object_id_str(&commit_id_str, commit_id);
2760 if (error)
2761 goto done;
2764 if (branch_name) {
2765 struct got_object_id *head_commit_id;
2766 TAILQ_FOREACH(pe, &paths, entry) {
2767 if (pe->path_len == 0)
2768 continue;
2769 error = got_error_msg(GOT_ERR_BAD_PATH,
2770 "switching between branches requires that "
2771 "the entire work tree gets updated");
2772 goto done;
2774 error = got_ref_resolve(&head_commit_id, repo, head_ref);
2775 if (error)
2776 goto done;
2777 error = check_linear_ancestry(commit_id, head_commit_id, 0,
2778 repo);
2779 free(head_commit_id);
2780 if (error != NULL)
2781 goto done;
2782 error = check_same_branch(commit_id, head_ref, NULL, repo);
2783 if (error)
2784 goto done;
2785 error = switch_head_ref(head_ref, commit_id, worktree, repo);
2786 if (error)
2787 goto done;
2788 } else {
2789 error = check_linear_ancestry(commit_id,
2790 got_worktree_get_base_commit_id(worktree), 0, repo);
2791 if (error != NULL) {
2792 if (error->code == GOT_ERR_ANCESTRY)
2793 error = got_error(GOT_ERR_BRANCH_MOVED);
2794 goto done;
2796 error = check_same_branch(commit_id, head_ref, NULL, repo);
2797 if (error)
2798 goto done;
2801 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
2802 commit_id) != 0) {
2803 error = got_worktree_set_base_commit_id(worktree, repo,
2804 commit_id);
2805 if (error)
2806 goto done;
2809 memset(&upa, 0, sizeof(upa));
2810 error = got_worktree_checkout_files(worktree, &paths, repo,
2811 update_progress, &upa, check_cancelled, NULL);
2812 if (error != NULL)
2813 goto done;
2815 if (upa.did_something)
2816 printf("Updated to commit %s\n", commit_id_str);
2817 else
2818 printf("Already up-to-date\n");
2819 print_update_progress_stats(&upa);
2820 done:
2821 free(worktree_path);
2822 TAILQ_FOREACH(pe, &paths, entry)
2823 free((char *)pe->path);
2824 got_pathlist_free(&paths);
2825 free(commit_id);
2826 free(commit_id_str);
2827 return error;
2830 static const struct got_error *
2831 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
2832 const char *path, int diff_context, int ignore_whitespace,
2833 struct got_repository *repo)
2835 const struct got_error *err = NULL;
2836 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
2838 if (blob_id1) {
2839 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
2840 if (err)
2841 goto done;
2844 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
2845 if (err)
2846 goto done;
2848 while (path[0] == '/')
2849 path++;
2850 err = got_diff_blob(blob1, blob2, path, path, diff_context,
2851 ignore_whitespace, stdout);
2852 done:
2853 if (blob1)
2854 got_object_blob_close(blob1);
2855 got_object_blob_close(blob2);
2856 return err;
2859 static const struct got_error *
2860 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
2861 const char *path, int diff_context, int ignore_whitespace,
2862 struct got_repository *repo)
2864 const struct got_error *err = NULL;
2865 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
2866 struct got_diff_blob_output_unidiff_arg arg;
2868 if (tree_id1) {
2869 err = got_object_open_as_tree(&tree1, repo, tree_id1);
2870 if (err)
2871 goto done;
2874 err = got_object_open_as_tree(&tree2, repo, tree_id2);
2875 if (err)
2876 goto done;
2878 arg.diff_context = diff_context;
2879 arg.ignore_whitespace = ignore_whitespace;
2880 arg.outfile = stdout;
2881 while (path[0] == '/')
2882 path++;
2883 err = got_diff_tree(tree1, tree2, path, path, repo,
2884 got_diff_blob_output_unidiff, &arg, 1);
2885 done:
2886 if (tree1)
2887 got_object_tree_close(tree1);
2888 if (tree2)
2889 got_object_tree_close(tree2);
2890 return err;
2893 static const struct got_error *
2894 get_changed_paths(struct got_pathlist_head *paths,
2895 struct got_commit_object *commit, struct got_repository *repo)
2897 const struct got_error *err = NULL;
2898 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
2899 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
2900 struct got_object_qid *qid;
2902 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
2903 if (qid != NULL) {
2904 struct got_commit_object *pcommit;
2905 err = got_object_open_as_commit(&pcommit, repo,
2906 qid->id);
2907 if (err)
2908 return err;
2910 tree_id1 = got_object_commit_get_tree_id(pcommit);
2911 got_object_commit_close(pcommit);
2915 if (tree_id1) {
2916 err = got_object_open_as_tree(&tree1, repo, tree_id1);
2917 if (err)
2918 goto done;
2921 tree_id2 = got_object_commit_get_tree_id(commit);
2922 err = got_object_open_as_tree(&tree2, repo, tree_id2);
2923 if (err)
2924 goto done;
2926 err = got_diff_tree(tree1, tree2, "", "", repo,
2927 got_diff_tree_collect_changed_paths, paths, 0);
2928 done:
2929 if (tree1)
2930 got_object_tree_close(tree1);
2931 if (tree2)
2932 got_object_tree_close(tree2);
2933 return err;
2936 static const struct got_error *
2937 print_patch(struct got_commit_object *commit, struct got_object_id *id,
2938 const char *path, int diff_context, struct got_repository *repo)
2940 const struct got_error *err = NULL;
2941 struct got_commit_object *pcommit = NULL;
2942 char *id_str1 = NULL, *id_str2 = NULL;
2943 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
2944 struct got_object_qid *qid;
2946 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
2947 if (qid != NULL) {
2948 err = got_object_open_as_commit(&pcommit, repo,
2949 qid->id);
2950 if (err)
2951 return err;
2954 if (path && path[0] != '\0') {
2955 int obj_type;
2956 err = got_object_id_by_path(&obj_id2, repo, id, path);
2957 if (err)
2958 goto done;
2959 err = got_object_id_str(&id_str2, obj_id2);
2960 if (err) {
2961 free(obj_id2);
2962 goto done;
2964 if (pcommit) {
2965 err = got_object_id_by_path(&obj_id1, repo,
2966 qid->id, path);
2967 if (err) {
2968 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
2969 free(obj_id2);
2970 goto done;
2972 } else {
2973 err = got_object_id_str(&id_str1, obj_id1);
2974 if (err) {
2975 free(obj_id2);
2976 goto done;
2980 err = got_object_get_type(&obj_type, repo, obj_id2);
2981 if (err) {
2982 free(obj_id2);
2983 goto done;
2985 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2986 switch (obj_type) {
2987 case GOT_OBJ_TYPE_BLOB:
2988 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
2989 0, repo);
2990 break;
2991 case GOT_OBJ_TYPE_TREE:
2992 err = diff_trees(obj_id1, obj_id2, path, diff_context,
2993 0, repo);
2994 break;
2995 default:
2996 err = got_error(GOT_ERR_OBJ_TYPE);
2997 break;
2999 free(obj_id1);
3000 free(obj_id2);
3001 } else {
3002 obj_id2 = got_object_commit_get_tree_id(commit);
3003 err = got_object_id_str(&id_str2, obj_id2);
3004 if (err)
3005 goto done;
3006 obj_id1 = got_object_commit_get_tree_id(pcommit);
3007 err = got_object_id_str(&id_str1, obj_id1);
3008 if (err)
3009 goto done;
3010 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3011 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
3013 done:
3014 free(id_str1);
3015 free(id_str2);
3016 if (pcommit)
3017 got_object_commit_close(pcommit);
3018 return err;
3021 static char *
3022 get_datestr(time_t *time, char *datebuf)
3024 struct tm mytm, *tm;
3025 char *p, *s;
3027 tm = gmtime_r(time, &mytm);
3028 if (tm == NULL)
3029 return NULL;
3030 s = asctime_r(tm, datebuf);
3031 if (s == NULL)
3032 return NULL;
3033 p = strchr(s, '\n');
3034 if (p)
3035 *p = '\0';
3036 return s;
3039 static const struct got_error *
3040 match_logmsg(int *have_match, struct got_object_id *id,
3041 struct got_commit_object *commit, regex_t *regex)
3043 const struct got_error *err = NULL;
3044 regmatch_t regmatch;
3045 char *id_str = NULL, *logmsg = NULL;
3047 *have_match = 0;
3049 err = got_object_id_str(&id_str, id);
3050 if (err)
3051 return err;
3053 err = got_object_commit_get_logmsg(&logmsg, commit);
3054 if (err)
3055 goto done;
3057 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3058 *have_match = 1;
3059 done:
3060 free(id_str);
3061 free(logmsg);
3062 return err;
3065 static void
3066 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3067 regex_t *regex)
3069 regmatch_t regmatch;
3070 struct got_pathlist_entry *pe;
3072 *have_match = 0;
3074 TAILQ_FOREACH(pe, changed_paths, entry) {
3075 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3076 *have_match = 1;
3077 break;
3082 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3084 static const struct got_error *
3085 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3086 struct got_repository *repo, const char *path,
3087 struct got_pathlist_head *changed_paths, int show_patch,
3088 int diff_context, struct got_reflist_head *refs)
3090 const struct got_error *err = NULL;
3091 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3092 char datebuf[26];
3093 time_t committer_time;
3094 const char *author, *committer;
3095 char *refs_str = NULL;
3096 struct got_reflist_entry *re;
3098 SIMPLEQ_FOREACH(re, refs, entry) {
3099 char *s;
3100 const char *name;
3101 struct got_tag_object *tag = NULL;
3102 int cmp;
3104 name = got_ref_get_name(re->ref);
3105 if (strcmp(name, GOT_REF_HEAD) == 0)
3106 continue;
3107 if (strncmp(name, "refs/", 5) == 0)
3108 name += 5;
3109 if (strncmp(name, "got/", 4) == 0)
3110 continue;
3111 if (strncmp(name, "heads/", 6) == 0)
3112 name += 6;
3113 if (strncmp(name, "remotes/", 8) == 0) {
3114 name += 8;
3115 s = strstr(name, "/" GOT_REF_HEAD);
3116 if (s != NULL && s[strlen(s)] == '\0')
3117 continue;
3119 if (strncmp(name, "tags/", 5) == 0) {
3120 err = got_object_open_as_tag(&tag, repo, re->id);
3121 if (err) {
3122 if (err->code != GOT_ERR_OBJ_TYPE)
3123 return err;
3124 /* Ref points at something other than a tag. */
3125 err = NULL;
3126 tag = NULL;
3129 cmp = got_object_id_cmp(tag ?
3130 got_object_tag_get_object_id(tag) : re->id, id);
3131 if (tag)
3132 got_object_tag_close(tag);
3133 if (cmp != 0)
3134 continue;
3135 s = refs_str;
3136 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3137 name) == -1) {
3138 err = got_error_from_errno("asprintf");
3139 free(s);
3140 return err;
3142 free(s);
3144 err = got_object_id_str(&id_str, id);
3145 if (err)
3146 return err;
3148 printf(GOT_COMMIT_SEP_STR);
3149 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3150 refs_str ? refs_str : "", refs_str ? ")" : "");
3151 free(id_str);
3152 id_str = NULL;
3153 free(refs_str);
3154 refs_str = NULL;
3155 printf("from: %s\n", got_object_commit_get_author(commit));
3156 committer_time = got_object_commit_get_committer_time(commit);
3157 datestr = get_datestr(&committer_time, datebuf);
3158 if (datestr)
3159 printf("date: %s UTC\n", datestr);
3160 author = got_object_commit_get_author(commit);
3161 committer = got_object_commit_get_committer(commit);
3162 if (strcmp(author, committer) != 0)
3163 printf("via: %s\n", committer);
3164 if (got_object_commit_get_nparents(commit) > 1) {
3165 const struct got_object_id_queue *parent_ids;
3166 struct got_object_qid *qid;
3167 int n = 1;
3168 parent_ids = got_object_commit_get_parent_ids(commit);
3169 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3170 err = got_object_id_str(&id_str, qid->id);
3171 if (err)
3172 return err;
3173 printf("parent %d: %s\n", n++, id_str);
3174 free(id_str);
3178 err = got_object_commit_get_logmsg(&logmsg0, commit);
3179 if (err)
3180 return err;
3182 logmsg = logmsg0;
3183 do {
3184 line = strsep(&logmsg, "\n");
3185 if (line)
3186 printf(" %s\n", line);
3187 } while (line);
3188 free(logmsg0);
3190 if (changed_paths) {
3191 struct got_pathlist_entry *pe;
3192 TAILQ_FOREACH(pe, changed_paths, entry) {
3193 struct got_diff_changed_path *cp = pe->data;
3194 printf(" %c %s\n", cp->status, pe->path);
3196 printf("\n");
3198 if (show_patch) {
3199 err = print_patch(commit, id, path, diff_context, repo);
3200 if (err == 0)
3201 printf("\n");
3204 if (fflush(stdout) != 0 && err == NULL)
3205 err = got_error_from_errno("fflush");
3206 return err;
3209 static const struct got_error *
3210 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3211 struct got_repository *repo, const char *path, int show_changed_paths,
3212 int show_patch, const char *search_pattern, int diff_context, int limit,
3213 int log_branches, int reverse_display_order, struct got_reflist_head *refs)
3215 const struct got_error *err;
3216 struct got_commit_graph *graph;
3217 regex_t regex;
3218 int have_match;
3219 struct got_object_id_queue reversed_commits;
3220 struct got_object_qid *qid;
3221 struct got_commit_object *commit;
3222 struct got_pathlist_head changed_paths;
3223 struct got_pathlist_entry *pe;
3225 SIMPLEQ_INIT(&reversed_commits);
3226 TAILQ_INIT(&changed_paths);
3228 if (search_pattern && regcomp(&regex, search_pattern,
3229 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3230 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3232 err = got_commit_graph_open(&graph, path, !log_branches);
3233 if (err)
3234 return err;
3235 err = got_commit_graph_iter_start(graph, root_id, repo,
3236 check_cancelled, NULL);
3237 if (err)
3238 goto done;
3239 for (;;) {
3240 struct got_object_id *id;
3242 if (sigint_received || sigpipe_received)
3243 break;
3245 err = got_commit_graph_iter_next(&id, graph, repo,
3246 check_cancelled, NULL);
3247 if (err) {
3248 if (err->code == GOT_ERR_ITER_COMPLETED)
3249 err = NULL;
3250 break;
3252 if (id == NULL)
3253 break;
3255 err = got_object_open_as_commit(&commit, repo, id);
3256 if (err)
3257 break;
3259 if (show_changed_paths) {
3260 err = get_changed_paths(&changed_paths, commit, repo);
3261 if (err)
3262 break;
3265 if (search_pattern) {
3266 err = match_logmsg(&have_match, id, commit, &regex);
3267 if (err) {
3268 got_object_commit_close(commit);
3269 break;
3271 if (have_match == 0 && show_changed_paths)
3272 match_changed_paths(&have_match,
3273 &changed_paths, &regex);
3274 if (have_match == 0) {
3275 got_object_commit_close(commit);
3276 TAILQ_FOREACH(pe, &changed_paths, entry) {
3277 free((char *)pe->path);
3278 free(pe->data);
3280 got_pathlist_free(&changed_paths);
3281 continue;
3285 if (reverse_display_order) {
3286 err = got_object_qid_alloc(&qid, id);
3287 if (err)
3288 break;
3289 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3290 got_object_commit_close(commit);
3291 } else {
3292 err = print_commit(commit, id, repo, path,
3293 show_changed_paths ? &changed_paths : NULL,
3294 show_patch, diff_context, refs);
3295 got_object_commit_close(commit);
3296 if (err)
3297 break;
3299 if ((limit && --limit == 0) ||
3300 (end_id && got_object_id_cmp(id, end_id) == 0))
3301 break;
3303 TAILQ_FOREACH(pe, &changed_paths, entry) {
3304 free((char *)pe->path);
3305 free(pe->data);
3307 got_pathlist_free(&changed_paths);
3309 if (reverse_display_order) {
3310 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3311 err = got_object_open_as_commit(&commit, repo, qid->id);
3312 if (err)
3313 break;
3314 err = print_commit(commit, qid->id, repo, path,
3315 show_changed_paths ? &changed_paths : NULL,
3316 show_patch, diff_context, refs);
3317 got_object_commit_close(commit);
3318 if (err)
3319 break;
3322 done:
3323 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3324 qid = SIMPLEQ_FIRST(&reversed_commits);
3325 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3326 got_object_qid_free(qid);
3328 TAILQ_FOREACH(pe, &changed_paths, entry) {
3329 free((char *)pe->path);
3330 free(pe->data);
3332 got_pathlist_free(&changed_paths);
3333 if (search_pattern)
3334 regfree(&regex);
3335 got_commit_graph_close(graph);
3336 return err;
3339 __dead static void
3340 usage_log(void)
3342 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3343 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3344 "[-R] [path]\n", getprogname());
3345 exit(1);
3348 static int
3349 get_default_log_limit(void)
3351 const char *got_default_log_limit;
3352 long long n;
3353 const char *errstr;
3355 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3356 if (got_default_log_limit == NULL)
3357 return 0;
3358 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3359 if (errstr != NULL)
3360 return 0;
3361 return n;
3364 static const struct got_error *
3365 resolve_commit_arg(struct got_object_id **id, const char *commit_arg,
3366 struct got_repository *repo)
3368 const struct got_error *err = NULL;
3369 struct got_reference *ref;
3371 *id = NULL;
3373 err = got_ref_open(&ref, repo, commit_arg, 0);
3374 if (err == NULL) {
3375 int obj_type;
3376 err = got_ref_resolve(id, repo, ref);
3377 got_ref_close(ref);
3378 if (err)
3379 return err;
3380 err = got_object_get_type(&obj_type, repo, *id);
3381 if (err)
3382 return err;
3383 if (obj_type == GOT_OBJ_TYPE_TAG) {
3384 struct got_tag_object *tag;
3385 err = got_object_open_as_tag(&tag, repo, *id);
3386 if (err)
3387 return err;
3388 if (got_object_tag_get_object_type(tag) !=
3389 GOT_OBJ_TYPE_COMMIT) {
3390 got_object_tag_close(tag);
3391 return got_error(GOT_ERR_OBJ_TYPE);
3393 free(*id);
3394 *id = got_object_id_dup(
3395 got_object_tag_get_object_id(tag));
3396 if (*id == NULL)
3397 err = got_error_from_errno(
3398 "got_object_id_dup");
3399 got_object_tag_close(tag);
3400 if (err)
3401 return err;
3402 } else if (obj_type != GOT_OBJ_TYPE_COMMIT)
3403 return got_error(GOT_ERR_OBJ_TYPE);
3404 } else {
3405 err = got_repo_match_object_id_prefix(id, commit_arg,
3406 GOT_OBJ_TYPE_COMMIT, repo);
3409 return err;
3412 static const struct got_error *
3413 cmd_log(int argc, char *argv[])
3415 const struct got_error *error;
3416 struct got_repository *repo = NULL;
3417 struct got_worktree *worktree = NULL;
3418 struct got_object_id *start_id = NULL, *end_id = NULL;
3419 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3420 const char *start_commit = NULL, *end_commit = NULL;
3421 const char *search_pattern = NULL;
3422 int diff_context = -1, ch;
3423 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3424 int reverse_display_order = 0;
3425 const char *errstr;
3426 struct got_reflist_head refs;
3428 SIMPLEQ_INIT(&refs);
3430 #ifndef PROFILE
3431 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3432 NULL)
3433 == -1)
3434 err(1, "pledge");
3435 #endif
3437 limit = get_default_log_limit();
3439 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3440 switch (ch) {
3441 case 'p':
3442 show_patch = 1;
3443 break;
3444 case 'P':
3445 show_changed_paths = 1;
3446 break;
3447 case 'c':
3448 start_commit = optarg;
3449 break;
3450 case 'C':
3451 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3452 &errstr);
3453 if (errstr != NULL)
3454 err(1, "-C option %s", errstr);
3455 break;
3456 case 'l':
3457 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3458 if (errstr != NULL)
3459 err(1, "-l option %s", errstr);
3460 break;
3461 case 'b':
3462 log_branches = 1;
3463 break;
3464 case 'r':
3465 repo_path = realpath(optarg, NULL);
3466 if (repo_path == NULL)
3467 return got_error_from_errno2("realpath",
3468 optarg);
3469 got_path_strip_trailing_slashes(repo_path);
3470 break;
3471 case 'R':
3472 reverse_display_order = 1;
3473 break;
3474 case 's':
3475 search_pattern = optarg;
3476 break;
3477 case 'x':
3478 end_commit = optarg;
3479 break;
3480 default:
3481 usage_log();
3482 /* NOTREACHED */
3486 argc -= optind;
3487 argv += optind;
3489 if (diff_context == -1)
3490 diff_context = 3;
3491 else if (!show_patch)
3492 errx(1, "-C reguires -p");
3494 cwd = getcwd(NULL, 0);
3495 if (cwd == NULL) {
3496 error = got_error_from_errno("getcwd");
3497 goto done;
3500 if (repo_path == NULL) {
3501 error = got_worktree_open(&worktree, cwd);
3502 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3503 goto done;
3504 error = NULL;
3507 if (argc == 0) {
3508 path = strdup("");
3509 if (path == NULL) {
3510 error = got_error_from_errno("strdup");
3511 goto done;
3513 } else if (argc == 1) {
3514 if (worktree) {
3515 error = got_worktree_resolve_path(&path, worktree,
3516 argv[0]);
3517 if (error)
3518 goto done;
3519 } else {
3520 path = strdup(argv[0]);
3521 if (path == NULL) {
3522 error = got_error_from_errno("strdup");
3523 goto done;
3526 } else
3527 usage_log();
3529 if (repo_path == NULL) {
3530 repo_path = worktree ?
3531 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3533 if (repo_path == NULL) {
3534 error = got_error_from_errno("strdup");
3535 goto done;
3538 error = got_repo_open(&repo, repo_path, NULL);
3539 if (error != NULL)
3540 goto done;
3542 error = apply_unveil(got_repo_get_path(repo), 1,
3543 worktree ? got_worktree_get_root_path(worktree) : NULL);
3544 if (error)
3545 goto done;
3547 if (start_commit == NULL) {
3548 struct got_reference *head_ref;
3549 struct got_commit_object *commit = NULL;
3550 error = got_ref_open(&head_ref, repo,
3551 worktree ? got_worktree_get_head_ref_name(worktree)
3552 : GOT_REF_HEAD, 0);
3553 if (error != NULL)
3554 goto done;
3555 error = got_ref_resolve(&start_id, repo, head_ref);
3556 got_ref_close(head_ref);
3557 if (error != NULL)
3558 goto done;
3559 error = got_object_open_as_commit(&commit, repo,
3560 start_id);
3561 if (error != NULL)
3562 goto done;
3563 got_object_commit_close(commit);
3564 } else {
3565 error = resolve_commit_arg(&start_id, start_commit, repo);
3566 if (error != NULL)
3567 goto done;
3569 if (end_commit != NULL) {
3570 error = resolve_commit_arg(&end_id, end_commit, repo);
3571 if (error != NULL)
3572 goto done;
3575 if (worktree) {
3576 const char *prefix = got_worktree_get_path_prefix(worktree);
3577 char *p;
3578 if (asprintf(&p, "%s%s%s", prefix,
3579 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3580 error = got_error_from_errno("asprintf");
3581 goto done;
3583 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3584 free(p);
3585 } else
3586 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3587 if (error != NULL)
3588 goto done;
3589 if (in_repo_path) {
3590 free(path);
3591 path = in_repo_path;
3594 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3595 if (error)
3596 goto done;
3598 error = print_commits(start_id, end_id, repo, path, show_changed_paths,
3599 show_patch, search_pattern, diff_context, limit, log_branches,
3600 reverse_display_order, &refs);
3601 done:
3602 free(path);
3603 free(repo_path);
3604 free(cwd);
3605 if (worktree)
3606 got_worktree_close(worktree);
3607 if (repo) {
3608 const struct got_error *repo_error;
3609 repo_error = got_repo_close(repo);
3610 if (error == NULL)
3611 error = repo_error;
3613 got_ref_list_free(&refs);
3614 return error;
3617 __dead static void
3618 usage_diff(void)
3620 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3621 "[-w] [object1 object2 | path]\n", getprogname());
3622 exit(1);
3625 struct print_diff_arg {
3626 struct got_repository *repo;
3627 struct got_worktree *worktree;
3628 int diff_context;
3629 const char *id_str;
3630 int header_shown;
3631 int diff_staged;
3632 int ignore_whitespace;
3636 * Create a file which contains the target path of a symlink so we can feed
3637 * it as content to the diff engine.
3639 static const struct got_error *
3640 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
3641 const char *abspath)
3643 const struct got_error *err = NULL;
3644 char target_path[PATH_MAX];
3645 ssize_t target_len, outlen;
3647 *fd = -1;
3649 if (dirfd != -1) {
3650 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
3651 if (target_len == -1)
3652 return got_error_from_errno2("readlinkat", abspath);
3653 } else {
3654 target_len = readlink(abspath, target_path, PATH_MAX);
3655 if (target_len == -1)
3656 return got_error_from_errno2("readlink", abspath);
3659 *fd = got_opentempfd();
3660 if (*fd == -1)
3661 return got_error_from_errno("got_opentempfd");
3663 outlen = write(*fd, target_path, target_len);
3664 if (outlen == -1) {
3665 err = got_error_from_errno("got_opentempfd");
3666 goto done;
3669 if (lseek(*fd, 0, SEEK_SET) == -1) {
3670 err = got_error_from_errno2("lseek", abspath);
3671 goto done;
3673 done:
3674 if (err) {
3675 close(*fd);
3676 *fd = -1;
3678 return err;
3681 static const struct got_error *
3682 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3683 const char *path, struct got_object_id *blob_id,
3684 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3685 int dirfd, const char *de_name)
3687 struct print_diff_arg *a = arg;
3688 const struct got_error *err = NULL;
3689 struct got_blob_object *blob1 = NULL;
3690 int fd = -1;
3691 FILE *f2 = NULL;
3692 char *abspath = NULL, *label1 = NULL;
3693 struct stat sb;
3695 if (a->diff_staged) {
3696 if (staged_status != GOT_STATUS_MODIFY &&
3697 staged_status != GOT_STATUS_ADD &&
3698 staged_status != GOT_STATUS_DELETE)
3699 return NULL;
3700 } else {
3701 if (staged_status == GOT_STATUS_DELETE)
3702 return NULL;
3703 if (status == GOT_STATUS_NONEXISTENT)
3704 return got_error_set_errno(ENOENT, path);
3705 if (status != GOT_STATUS_MODIFY &&
3706 status != GOT_STATUS_ADD &&
3707 status != GOT_STATUS_DELETE &&
3708 status != GOT_STATUS_CONFLICT)
3709 return NULL;
3712 if (!a->header_shown) {
3713 printf("diff %s %s%s\n", a->id_str,
3714 got_worktree_get_root_path(a->worktree),
3715 a->diff_staged ? " (staged changes)" : "");
3716 a->header_shown = 1;
3719 if (a->diff_staged) {
3720 const char *label1 = NULL, *label2 = NULL;
3721 switch (staged_status) {
3722 case GOT_STATUS_MODIFY:
3723 label1 = path;
3724 label2 = path;
3725 break;
3726 case GOT_STATUS_ADD:
3727 label2 = path;
3728 break;
3729 case GOT_STATUS_DELETE:
3730 label1 = path;
3731 break;
3732 default:
3733 return got_error(GOT_ERR_FILE_STATUS);
3735 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
3736 label1, label2, a->diff_context, a->ignore_whitespace,
3737 a->repo, stdout);
3740 if (staged_status == GOT_STATUS_ADD ||
3741 staged_status == GOT_STATUS_MODIFY) {
3742 char *id_str;
3743 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
3744 8192);
3745 if (err)
3746 goto done;
3747 err = got_object_id_str(&id_str, staged_blob_id);
3748 if (err)
3749 goto done;
3750 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
3751 err = got_error_from_errno("asprintf");
3752 free(id_str);
3753 goto done;
3755 free(id_str);
3756 } else if (status != GOT_STATUS_ADD) {
3757 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
3758 if (err)
3759 goto done;
3762 if (status != GOT_STATUS_DELETE) {
3763 if (asprintf(&abspath, "%s/%s",
3764 got_worktree_get_root_path(a->worktree), path) == -1) {
3765 err = got_error_from_errno("asprintf");
3766 goto done;
3769 if (dirfd != -1) {
3770 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
3771 if (fd == -1) {
3772 if (errno != ELOOP) {
3773 err = got_error_from_errno2("openat",
3774 abspath);
3775 goto done;
3777 err = get_symlink_target_file(&fd, dirfd,
3778 de_name, abspath);
3779 if (err)
3780 goto done;
3782 } else {
3783 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
3784 if (fd == -1) {
3785 if (errno != ELOOP) {
3786 err = got_error_from_errno2("open",
3787 abspath);
3788 goto done;
3790 err = get_symlink_target_file(&fd, dirfd,
3791 de_name, abspath);
3792 if (err)
3793 goto done;
3796 if (fstat(fd, &sb) == -1) {
3797 err = got_error_from_errno2("fstat", abspath);
3798 goto done;
3800 f2 = fdopen(fd, "r");
3801 if (f2 == NULL) {
3802 err = got_error_from_errno2("fdopen", abspath);
3803 goto done;
3805 fd = -1;
3806 } else
3807 sb.st_size = 0;
3809 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
3810 a->diff_context, a->ignore_whitespace, stdout);
3811 done:
3812 if (blob1)
3813 got_object_blob_close(blob1);
3814 if (f2 && fclose(f2) == EOF && err == NULL)
3815 err = got_error_from_errno("fclose");
3816 if (fd != -1 && close(fd) == -1 && err == NULL)
3817 err = got_error_from_errno("close");
3818 free(abspath);
3819 return err;
3822 static const struct got_error *
3823 cmd_diff(int argc, char *argv[])
3825 const struct got_error *error;
3826 struct got_repository *repo = NULL;
3827 struct got_worktree *worktree = NULL;
3828 char *cwd = NULL, *repo_path = NULL;
3829 struct got_object_id *id1 = NULL, *id2 = NULL;
3830 const char *id_str1 = NULL, *id_str2 = NULL;
3831 char *label1 = NULL, *label2 = NULL;
3832 int type1, type2;
3833 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
3834 const char *errstr;
3835 char *path = NULL;
3837 #ifndef PROFILE
3838 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3839 NULL) == -1)
3840 err(1, "pledge");
3841 #endif
3843 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
3844 switch (ch) {
3845 case 'C':
3846 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3847 &errstr);
3848 if (errstr != NULL)
3849 err(1, "-C option %s", errstr);
3850 break;
3851 case 'r':
3852 repo_path = realpath(optarg, NULL);
3853 if (repo_path == NULL)
3854 return got_error_from_errno2("realpath",
3855 optarg);
3856 got_path_strip_trailing_slashes(repo_path);
3857 break;
3858 case 's':
3859 diff_staged = 1;
3860 break;
3861 case 'w':
3862 ignore_whitespace = 1;
3863 break;
3864 default:
3865 usage_diff();
3866 /* NOTREACHED */
3870 argc -= optind;
3871 argv += optind;
3873 cwd = getcwd(NULL, 0);
3874 if (cwd == NULL) {
3875 error = got_error_from_errno("getcwd");
3876 goto done;
3878 if (argc <= 1) {
3879 if (repo_path)
3880 errx(1,
3881 "-r option can't be used when diffing a work tree");
3882 error = got_worktree_open(&worktree, cwd);
3883 if (error) {
3884 if (error->code == GOT_ERR_NOT_WORKTREE)
3885 error = wrap_not_worktree_error(error, "diff",
3886 cwd);
3887 goto done;
3889 repo_path = strdup(got_worktree_get_repo_path(worktree));
3890 if (repo_path == NULL) {
3891 error = got_error_from_errno("strdup");
3892 goto done;
3894 if (argc == 1) {
3895 error = got_worktree_resolve_path(&path, worktree,
3896 argv[0]);
3897 if (error)
3898 goto done;
3899 } else {
3900 path = strdup("");
3901 if (path == NULL) {
3902 error = got_error_from_errno("strdup");
3903 goto done;
3906 } else if (argc == 2) {
3907 if (diff_staged)
3908 errx(1, "-s option can't be used when diffing "
3909 "objects in repository");
3910 id_str1 = argv[0];
3911 id_str2 = argv[1];
3912 if (repo_path == NULL) {
3913 error = got_worktree_open(&worktree, cwd);
3914 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3915 goto done;
3916 if (worktree) {
3917 repo_path = strdup(
3918 got_worktree_get_repo_path(worktree));
3919 if (repo_path == NULL) {
3920 error = got_error_from_errno("strdup");
3921 goto done;
3923 } else {
3924 repo_path = strdup(cwd);
3925 if (repo_path == NULL) {
3926 error = got_error_from_errno("strdup");
3927 goto done;
3931 } else
3932 usage_diff();
3934 error = got_repo_open(&repo, repo_path, NULL);
3935 free(repo_path);
3936 if (error != NULL)
3937 goto done;
3939 error = apply_unveil(got_repo_get_path(repo), 1,
3940 worktree ? got_worktree_get_root_path(worktree) : NULL);
3941 if (error)
3942 goto done;
3944 if (argc <= 1) {
3945 struct print_diff_arg arg;
3946 struct got_pathlist_head paths;
3947 char *id_str;
3949 TAILQ_INIT(&paths);
3951 error = got_object_id_str(&id_str,
3952 got_worktree_get_base_commit_id(worktree));
3953 if (error)
3954 goto done;
3955 arg.repo = repo;
3956 arg.worktree = worktree;
3957 arg.diff_context = diff_context;
3958 arg.id_str = id_str;
3959 arg.header_shown = 0;
3960 arg.diff_staged = diff_staged;
3961 arg.ignore_whitespace = ignore_whitespace;
3963 error = got_pathlist_append(&paths, path, NULL);
3964 if (error)
3965 goto done;
3967 error = got_worktree_status(worktree, &paths, repo, print_diff,
3968 &arg, check_cancelled, NULL);
3969 free(id_str);
3970 got_pathlist_free(&paths);
3971 goto done;
3974 error = got_repo_match_object_id(&id1, &label1, id_str1,
3975 GOT_OBJ_TYPE_ANY, 1, repo);
3976 if (error)
3977 goto done;
3979 error = got_repo_match_object_id(&id2, &label2, id_str2,
3980 GOT_OBJ_TYPE_ANY, 1, repo);
3981 if (error)
3982 goto done;
3984 error = got_object_get_type(&type1, repo, id1);
3985 if (error)
3986 goto done;
3988 error = got_object_get_type(&type2, repo, id2);
3989 if (error)
3990 goto done;
3992 if (type1 != type2) {
3993 error = got_error(GOT_ERR_OBJ_TYPE);
3994 goto done;
3997 switch (type1) {
3998 case GOT_OBJ_TYPE_BLOB:
3999 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
4000 diff_context, ignore_whitespace, repo, stdout);
4001 break;
4002 case GOT_OBJ_TYPE_TREE:
4003 error = got_diff_objects_as_trees(id1, id2, "", "",
4004 diff_context, ignore_whitespace, repo, stdout);
4005 break;
4006 case GOT_OBJ_TYPE_COMMIT:
4007 printf("diff %s %s\n", label1, label2);
4008 error = got_diff_objects_as_commits(id1, id2, diff_context,
4009 ignore_whitespace, repo, stdout);
4010 break;
4011 default:
4012 error = got_error(GOT_ERR_OBJ_TYPE);
4014 done:
4015 free(label1);
4016 free(label2);
4017 free(id1);
4018 free(id2);
4019 free(path);
4020 if (worktree)
4021 got_worktree_close(worktree);
4022 if (repo) {
4023 const struct got_error *repo_error;
4024 repo_error = got_repo_close(repo);
4025 if (error == NULL)
4026 error = repo_error;
4028 return error;
4031 __dead static void
4032 usage_blame(void)
4034 fprintf(stderr,
4035 "usage: %s blame [-c commit] [-r repository-path] path\n",
4036 getprogname());
4037 exit(1);
4040 struct blame_line {
4041 int annotated;
4042 char *id_str;
4043 char *committer;
4044 char datebuf[11]; /* YYYY-MM-DD + NUL */
4047 struct blame_cb_args {
4048 struct blame_line *lines;
4049 int nlines;
4050 int nlines_prec;
4051 int lineno_cur;
4052 off_t *line_offsets;
4053 FILE *f;
4054 struct got_repository *repo;
4057 static const struct got_error *
4058 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4060 const struct got_error *err = NULL;
4061 struct blame_cb_args *a = arg;
4062 struct blame_line *bline;
4063 char *line = NULL;
4064 size_t linesize = 0;
4065 struct got_commit_object *commit = NULL;
4066 off_t offset;
4067 struct tm tm;
4068 time_t committer_time;
4070 if (nlines != a->nlines ||
4071 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4072 return got_error(GOT_ERR_RANGE);
4074 if (sigint_received)
4075 return got_error(GOT_ERR_ITER_COMPLETED);
4077 if (lineno == -1)
4078 return NULL; /* no change in this commit */
4080 /* Annotate this line. */
4081 bline = &a->lines[lineno - 1];
4082 if (bline->annotated)
4083 return NULL;
4084 err = got_object_id_str(&bline->id_str, id);
4085 if (err)
4086 return err;
4088 err = got_object_open_as_commit(&commit, a->repo, id);
4089 if (err)
4090 goto done;
4092 bline->committer = strdup(got_object_commit_get_committer(commit));
4093 if (bline->committer == NULL) {
4094 err = got_error_from_errno("strdup");
4095 goto done;
4098 committer_time = got_object_commit_get_committer_time(commit);
4099 if (localtime_r(&committer_time, &tm) == NULL)
4100 return got_error_from_errno("localtime_r");
4101 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4102 &tm) >= sizeof(bline->datebuf)) {
4103 err = got_error(GOT_ERR_NO_SPACE);
4104 goto done;
4106 bline->annotated = 1;
4108 /* Print lines annotated so far. */
4109 bline = &a->lines[a->lineno_cur - 1];
4110 if (!bline->annotated)
4111 goto done;
4113 offset = a->line_offsets[a->lineno_cur - 1];
4114 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4115 err = got_error_from_errno("fseeko");
4116 goto done;
4119 while (bline->annotated) {
4120 char *smallerthan, *at, *nl, *committer;
4121 size_t len;
4123 if (getline(&line, &linesize, a->f) == -1) {
4124 if (ferror(a->f))
4125 err = got_error_from_errno("getline");
4126 break;
4129 committer = bline->committer;
4130 smallerthan = strchr(committer, '<');
4131 if (smallerthan && smallerthan[1] != '\0')
4132 committer = smallerthan + 1;
4133 at = strchr(committer, '@');
4134 if (at)
4135 *at = '\0';
4136 len = strlen(committer);
4137 if (len >= 9)
4138 committer[8] = '\0';
4140 nl = strchr(line, '\n');
4141 if (nl)
4142 *nl = '\0';
4143 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4144 bline->id_str, bline->datebuf, committer, line);
4146 a->lineno_cur++;
4147 bline = &a->lines[a->lineno_cur - 1];
4149 done:
4150 if (commit)
4151 got_object_commit_close(commit);
4152 free(line);
4153 return err;
4156 static const struct got_error *
4157 cmd_blame(int argc, char *argv[])
4159 const struct got_error *error;
4160 struct got_repository *repo = NULL;
4161 struct got_worktree *worktree = NULL;
4162 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4163 char *link_target = NULL;
4164 struct got_object_id *obj_id = NULL;
4165 struct got_object_id *commit_id = NULL;
4166 struct got_blob_object *blob = NULL;
4167 char *commit_id_str = NULL;
4168 struct blame_cb_args bca;
4169 int ch, obj_type, i;
4170 size_t filesize;
4172 memset(&bca, 0, sizeof(bca));
4174 #ifndef PROFILE
4175 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4176 NULL) == -1)
4177 err(1, "pledge");
4178 #endif
4180 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4181 switch (ch) {
4182 case 'c':
4183 commit_id_str = optarg;
4184 break;
4185 case 'r':
4186 repo_path = realpath(optarg, NULL);
4187 if (repo_path == NULL)
4188 return got_error_from_errno2("realpath",
4189 optarg);
4190 got_path_strip_trailing_slashes(repo_path);
4191 break;
4192 default:
4193 usage_blame();
4194 /* NOTREACHED */
4198 argc -= optind;
4199 argv += optind;
4201 if (argc == 1)
4202 path = argv[0];
4203 else
4204 usage_blame();
4206 cwd = getcwd(NULL, 0);
4207 if (cwd == NULL) {
4208 error = got_error_from_errno("getcwd");
4209 goto done;
4211 if (repo_path == NULL) {
4212 error = got_worktree_open(&worktree, cwd);
4213 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4214 goto done;
4215 else
4216 error = NULL;
4217 if (worktree) {
4218 repo_path =
4219 strdup(got_worktree_get_repo_path(worktree));
4220 if (repo_path == NULL) {
4221 error = got_error_from_errno("strdup");
4222 if (error)
4223 goto done;
4225 } else {
4226 repo_path = strdup(cwd);
4227 if (repo_path == NULL) {
4228 error = got_error_from_errno("strdup");
4229 goto done;
4234 error = got_repo_open(&repo, repo_path, NULL);
4235 if (error != NULL)
4236 goto done;
4238 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4239 if (error)
4240 goto done;
4242 if (worktree) {
4243 const char *prefix = got_worktree_get_path_prefix(worktree);
4244 char *p, *worktree_subdir = cwd +
4245 strlen(got_worktree_get_root_path(worktree));
4246 if (asprintf(&p, "%s%s%s%s%s",
4247 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
4248 worktree_subdir, worktree_subdir[0] ? "/" : "",
4249 path) == -1) {
4250 error = got_error_from_errno("asprintf");
4251 goto done;
4253 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4254 free(p);
4255 } else {
4256 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4258 if (error)
4259 goto done;
4261 if (commit_id_str == NULL) {
4262 struct got_reference *head_ref;
4263 error = got_ref_open(&head_ref, repo, worktree ?
4264 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4265 if (error != NULL)
4266 goto done;
4267 error = got_ref_resolve(&commit_id, repo, head_ref);
4268 got_ref_close(head_ref);
4269 if (error != NULL)
4270 goto done;
4271 } else {
4272 error = got_repo_match_object_id(&commit_id, NULL,
4273 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4274 if (error)
4275 goto done;
4278 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4279 commit_id, repo);
4280 if (error)
4281 goto done;
4283 error = got_object_id_by_path(&obj_id, repo, commit_id,
4284 link_target ? link_target : in_repo_path);
4285 if (error)
4286 goto done;
4288 error = got_object_get_type(&obj_type, repo, obj_id);
4289 if (error)
4290 goto done;
4292 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4293 error = got_error_path(link_target ? link_target : in_repo_path,
4294 GOT_ERR_OBJ_TYPE);
4295 goto done;
4298 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4299 if (error)
4300 goto done;
4301 bca.f = got_opentemp();
4302 if (bca.f == NULL) {
4303 error = got_error_from_errno("got_opentemp");
4304 goto done;
4306 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4307 &bca.line_offsets, bca.f, blob);
4308 if (error || bca.nlines == 0)
4309 goto done;
4311 /* Don't include \n at EOF in the blame line count. */
4312 if (bca.line_offsets[bca.nlines - 1] == filesize)
4313 bca.nlines--;
4315 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4316 if (bca.lines == NULL) {
4317 error = got_error_from_errno("calloc");
4318 goto done;
4320 bca.lineno_cur = 1;
4321 bca.nlines_prec = 0;
4322 i = bca.nlines;
4323 while (i > 0) {
4324 i /= 10;
4325 bca.nlines_prec++;
4327 bca.repo = repo;
4329 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4330 repo, blame_cb, &bca, check_cancelled, NULL);
4331 done:
4332 free(in_repo_path);
4333 free(link_target);
4334 free(repo_path);
4335 free(cwd);
4336 free(commit_id);
4337 free(obj_id);
4338 if (blob)
4339 got_object_blob_close(blob);
4340 if (worktree)
4341 got_worktree_close(worktree);
4342 if (repo) {
4343 const struct got_error *repo_error;
4344 repo_error = got_repo_close(repo);
4345 if (error == NULL)
4346 error = repo_error;
4348 if (bca.lines) {
4349 for (i = 0; i < bca.nlines; i++) {
4350 struct blame_line *bline = &bca.lines[i];
4351 free(bline->id_str);
4352 free(bline->committer);
4354 free(bca.lines);
4356 free(bca.line_offsets);
4357 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4358 error = got_error_from_errno("fclose");
4359 return error;
4362 __dead static void
4363 usage_tree(void)
4365 fprintf(stderr,
4366 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4367 getprogname());
4368 exit(1);
4371 static const struct got_error *
4372 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4373 const char *root_path, struct got_repository *repo)
4375 const struct got_error *err = NULL;
4376 int is_root_path = (strcmp(path, root_path) == 0);
4377 const char *modestr = "";
4378 mode_t mode = got_tree_entry_get_mode(te);
4379 char *link_target = NULL;
4381 path += strlen(root_path);
4382 while (path[0] == '/')
4383 path++;
4385 if (got_object_tree_entry_is_submodule(te))
4386 modestr = "$";
4387 else if (S_ISLNK(mode)) {
4388 int i;
4390 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4391 if (err)
4392 return err;
4393 for (i = 0; i < strlen(link_target); i++) {
4394 if (!isprint((unsigned char)link_target[i]))
4395 link_target[i] = '?';
4398 modestr = "@";
4400 else if (S_ISDIR(mode))
4401 modestr = "/";
4402 else if (mode & S_IXUSR)
4403 modestr = "*";
4405 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4406 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4407 link_target ? " -> ": "", link_target ? link_target : "");
4409 free(link_target);
4410 return NULL;
4413 static const struct got_error *
4414 print_tree(const char *path, struct got_object_id *commit_id,
4415 int show_ids, int recurse, const char *root_path,
4416 struct got_repository *repo)
4418 const struct got_error *err = NULL;
4419 struct got_object_id *tree_id = NULL;
4420 struct got_tree_object *tree = NULL;
4421 int nentries, i;
4423 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4424 if (err)
4425 goto done;
4427 err = got_object_open_as_tree(&tree, repo, tree_id);
4428 if (err)
4429 goto done;
4430 nentries = got_object_tree_get_nentries(tree);
4431 for (i = 0; i < nentries; i++) {
4432 struct got_tree_entry *te;
4433 char *id = NULL;
4435 if (sigint_received || sigpipe_received)
4436 break;
4438 te = got_object_tree_get_entry(tree, i);
4439 if (show_ids) {
4440 char *id_str;
4441 err = got_object_id_str(&id_str,
4442 got_tree_entry_get_id(te));
4443 if (err)
4444 goto done;
4445 if (asprintf(&id, "%s ", id_str) == -1) {
4446 err = got_error_from_errno("asprintf");
4447 free(id_str);
4448 goto done;
4450 free(id_str);
4452 err = print_entry(te, id, path, root_path, repo);
4453 free(id);
4454 if (err)
4455 goto done;
4457 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4458 char *child_path;
4459 if (asprintf(&child_path, "%s%s%s", path,
4460 path[0] == '/' && path[1] == '\0' ? "" : "/",
4461 got_tree_entry_get_name(te)) == -1) {
4462 err = got_error_from_errno("asprintf");
4463 goto done;
4465 err = print_tree(child_path, commit_id, show_ids, 1,
4466 root_path, repo);
4467 free(child_path);
4468 if (err)
4469 goto done;
4472 done:
4473 if (tree)
4474 got_object_tree_close(tree);
4475 free(tree_id);
4476 return err;
4479 static const struct got_error *
4480 cmd_tree(int argc, char *argv[])
4482 const struct got_error *error;
4483 struct got_repository *repo = NULL;
4484 struct got_worktree *worktree = NULL;
4485 const char *path, *refname = NULL;
4486 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4487 struct got_object_id *commit_id = NULL;
4488 char *commit_id_str = NULL;
4489 int show_ids = 0, recurse = 0;
4490 int ch;
4492 #ifndef PROFILE
4493 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4494 NULL) == -1)
4495 err(1, "pledge");
4496 #endif
4498 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4499 switch (ch) {
4500 case 'c':
4501 commit_id_str = optarg;
4502 break;
4503 case 'r':
4504 repo_path = realpath(optarg, NULL);
4505 if (repo_path == NULL)
4506 return got_error_from_errno2("realpath",
4507 optarg);
4508 got_path_strip_trailing_slashes(repo_path);
4509 break;
4510 case 'i':
4511 show_ids = 1;
4512 break;
4513 case 'R':
4514 recurse = 1;
4515 break;
4516 default:
4517 usage_tree();
4518 /* NOTREACHED */
4522 argc -= optind;
4523 argv += optind;
4525 if (argc == 1)
4526 path = argv[0];
4527 else if (argc > 1)
4528 usage_tree();
4529 else
4530 path = NULL;
4532 cwd = getcwd(NULL, 0);
4533 if (cwd == NULL) {
4534 error = got_error_from_errno("getcwd");
4535 goto done;
4537 if (repo_path == NULL) {
4538 error = got_worktree_open(&worktree, cwd);
4539 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4540 goto done;
4541 else
4542 error = NULL;
4543 if (worktree) {
4544 repo_path =
4545 strdup(got_worktree_get_repo_path(worktree));
4546 if (repo_path == NULL)
4547 error = got_error_from_errno("strdup");
4548 if (error)
4549 goto done;
4550 } else {
4551 repo_path = strdup(cwd);
4552 if (repo_path == NULL) {
4553 error = got_error_from_errno("strdup");
4554 goto done;
4559 error = got_repo_open(&repo, repo_path, NULL);
4560 if (error != NULL)
4561 goto done;
4563 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4564 if (error)
4565 goto done;
4567 if (path == NULL) {
4568 if (worktree) {
4569 char *p, *worktree_subdir = cwd +
4570 strlen(got_worktree_get_root_path(worktree));
4571 if (asprintf(&p, "%s/%s",
4572 got_worktree_get_path_prefix(worktree),
4573 worktree_subdir) == -1) {
4574 error = got_error_from_errno("asprintf");
4575 goto done;
4577 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4578 free(p);
4579 if (error)
4580 goto done;
4581 } else
4582 path = "/";
4584 if (in_repo_path == NULL) {
4585 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4586 if (error != NULL)
4587 goto done;
4590 if (commit_id_str == NULL) {
4591 struct got_reference *head_ref;
4592 if (worktree)
4593 refname = got_worktree_get_head_ref_name(worktree);
4594 else
4595 refname = GOT_REF_HEAD;
4596 error = got_ref_open(&head_ref, repo, refname, 0);
4597 if (error != NULL)
4598 goto done;
4599 error = got_ref_resolve(&commit_id, repo, head_ref);
4600 got_ref_close(head_ref);
4601 if (error != NULL)
4602 goto done;
4603 } else {
4604 error = got_repo_match_object_id(&commit_id, NULL,
4605 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4606 if (error)
4607 goto done;
4610 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4611 in_repo_path, repo);
4612 done:
4613 free(in_repo_path);
4614 free(repo_path);
4615 free(cwd);
4616 free(commit_id);
4617 if (worktree)
4618 got_worktree_close(worktree);
4619 if (repo) {
4620 const struct got_error *repo_error;
4621 repo_error = got_repo_close(repo);
4622 if (error == NULL)
4623 error = repo_error;
4625 return error;
4628 __dead static void
4629 usage_status(void)
4631 fprintf(stderr, "usage: %s status [path ...]\n", getprogname());
4632 exit(1);
4635 static const struct got_error *
4636 print_status(void *arg, unsigned char status, unsigned char staged_status,
4637 const char *path, struct got_object_id *blob_id,
4638 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4639 int dirfd, const char *de_name)
4641 if (status == staged_status && (status == GOT_STATUS_DELETE))
4642 status = GOT_STATUS_NO_CHANGE;
4643 printf("%c%c %s\n", status, staged_status, path);
4644 return NULL;
4647 static const struct got_error *
4648 cmd_status(int argc, char *argv[])
4650 const struct got_error *error = NULL;
4651 struct got_repository *repo = NULL;
4652 struct got_worktree *worktree = NULL;
4653 char *cwd = NULL;
4654 struct got_pathlist_head paths;
4655 struct got_pathlist_entry *pe;
4656 int ch;
4658 TAILQ_INIT(&paths);
4660 while ((ch = getopt(argc, argv, "")) != -1) {
4661 switch (ch) {
4662 default:
4663 usage_status();
4664 /* NOTREACHED */
4668 argc -= optind;
4669 argv += optind;
4671 #ifndef PROFILE
4672 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4673 NULL) == -1)
4674 err(1, "pledge");
4675 #endif
4676 cwd = getcwd(NULL, 0);
4677 if (cwd == NULL) {
4678 error = got_error_from_errno("getcwd");
4679 goto done;
4682 error = got_worktree_open(&worktree, cwd);
4683 if (error) {
4684 if (error->code == GOT_ERR_NOT_WORKTREE)
4685 error = wrap_not_worktree_error(error, "status", cwd);
4686 goto done;
4689 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4690 NULL);
4691 if (error != NULL)
4692 goto done;
4694 error = apply_unveil(got_repo_get_path(repo), 1,
4695 got_worktree_get_root_path(worktree));
4696 if (error)
4697 goto done;
4699 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
4700 if (error)
4701 goto done;
4703 error = got_worktree_status(worktree, &paths, repo, print_status, NULL,
4704 check_cancelled, NULL);
4705 done:
4706 TAILQ_FOREACH(pe, &paths, entry)
4707 free((char *)pe->path);
4708 got_pathlist_free(&paths);
4709 free(cwd);
4710 return error;
4713 __dead static void
4714 usage_ref(void)
4716 fprintf(stderr,
4717 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
4718 "[-d] [name]\n",
4719 getprogname());
4720 exit(1);
4723 static const struct got_error *
4724 list_refs(struct got_repository *repo, const char *refname)
4726 static const struct got_error *err = NULL;
4727 struct got_reflist_head refs;
4728 struct got_reflist_entry *re;
4730 SIMPLEQ_INIT(&refs);
4731 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
4732 if (err)
4733 return err;
4735 SIMPLEQ_FOREACH(re, &refs, entry) {
4736 char *refstr;
4737 refstr = got_ref_to_str(re->ref);
4738 if (refstr == NULL)
4739 return got_error_from_errno("got_ref_to_str");
4740 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
4741 free(refstr);
4744 got_ref_list_free(&refs);
4745 return NULL;
4748 static const struct got_error *
4749 delete_ref(struct got_repository *repo, const char *refname)
4751 const struct got_error *err = NULL;
4752 struct got_reference *ref;
4754 err = got_ref_open(&ref, repo, refname, 0);
4755 if (err)
4756 return err;
4758 err = got_ref_delete(ref, repo);
4759 got_ref_close(ref);
4760 return err;
4763 static const struct got_error *
4764 add_ref(struct got_repository *repo, const char *refname, const char *target)
4766 const struct got_error *err = NULL;
4767 struct got_object_id *id;
4768 struct got_reference *ref = NULL;
4771 * Don't let the user create a reference name with a leading '-'.
4772 * While technically a valid reference name, this case is usually
4773 * an unintended typo.
4775 if (refname[0] == '-')
4776 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4778 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
4779 repo);
4780 if (err) {
4781 struct got_reference *target_ref;
4783 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
4784 return err;
4785 err = got_ref_open(&target_ref, repo, target, 0);
4786 if (err)
4787 return err;
4788 err = got_ref_resolve(&id, repo, target_ref);
4789 got_ref_close(target_ref);
4790 if (err)
4791 return err;
4794 err = got_ref_alloc(&ref, refname, id);
4795 if (err)
4796 goto done;
4798 err = got_ref_write(ref, repo);
4799 done:
4800 if (ref)
4801 got_ref_close(ref);
4802 free(id);
4803 return err;
4806 static const struct got_error *
4807 add_symref(struct got_repository *repo, const char *refname, const char *target)
4809 const struct got_error *err = NULL;
4810 struct got_reference *ref = NULL;
4811 struct got_reference *target_ref = NULL;
4814 * Don't let the user create a reference name with a leading '-'.
4815 * While technically a valid reference name, this case is usually
4816 * an unintended typo.
4818 if (refname[0] == '-')
4819 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4821 err = got_ref_open(&target_ref, repo, target, 0);
4822 if (err)
4823 return err;
4825 err = got_ref_alloc_symref(&ref, refname, target_ref);
4826 if (err)
4827 goto done;
4829 err = got_ref_write(ref, repo);
4830 done:
4831 if (target_ref)
4832 got_ref_close(target_ref);
4833 if (ref)
4834 got_ref_close(ref);
4835 return err;
4838 static const struct got_error *
4839 cmd_ref(int argc, char *argv[])
4841 const struct got_error *error = NULL;
4842 struct got_repository *repo = NULL;
4843 struct got_worktree *worktree = NULL;
4844 char *cwd = NULL, *repo_path = NULL;
4845 int ch, do_list = 0, do_delete = 0;
4846 const char *obj_arg = NULL, *symref_target= NULL;
4847 char *refname = NULL;
4849 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
4850 switch (ch) {
4851 case 'c':
4852 obj_arg = optarg;
4853 break;
4854 case 'd':
4855 do_delete = 1;
4856 break;
4857 case 'r':
4858 repo_path = realpath(optarg, NULL);
4859 if (repo_path == NULL)
4860 return got_error_from_errno2("realpath",
4861 optarg);
4862 got_path_strip_trailing_slashes(repo_path);
4863 break;
4864 case 'l':
4865 do_list = 1;
4866 break;
4867 case 's':
4868 symref_target = optarg;
4869 break;
4870 default:
4871 usage_ref();
4872 /* NOTREACHED */
4876 if (obj_arg && do_list)
4877 errx(1, "-c and -l options are mutually exclusive");
4878 if (obj_arg && do_delete)
4879 errx(1, "-c and -d options are mutually exclusive");
4880 if (obj_arg && symref_target)
4881 errx(1, "-c and -s options are mutually exclusive");
4882 if (symref_target && do_delete)
4883 errx(1, "-s and -d options are mutually exclusive");
4884 if (symref_target && do_list)
4885 errx(1, "-s and -l options are mutually exclusive");
4886 if (do_delete && do_list)
4887 errx(1, "-d and -l options are mutually exclusive");
4889 argc -= optind;
4890 argv += optind;
4892 if (do_list) {
4893 if (argc != 0 && argc != 1)
4894 usage_ref();
4895 if (argc == 1) {
4896 refname = strdup(argv[0]);
4897 if (refname == NULL) {
4898 error = got_error_from_errno("strdup");
4899 goto done;
4902 } else {
4903 if (argc != 1)
4904 usage_ref();
4905 refname = strdup(argv[0]);
4906 if (refname == NULL) {
4907 error = got_error_from_errno("strdup");
4908 goto done;
4912 if (refname)
4913 got_path_strip_trailing_slashes(refname);
4915 #ifndef PROFILE
4916 if (do_list) {
4917 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4918 NULL) == -1)
4919 err(1, "pledge");
4920 } else {
4921 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4922 "sendfd unveil", NULL) == -1)
4923 err(1, "pledge");
4925 #endif
4926 cwd = getcwd(NULL, 0);
4927 if (cwd == NULL) {
4928 error = got_error_from_errno("getcwd");
4929 goto done;
4932 if (repo_path == NULL) {
4933 error = got_worktree_open(&worktree, cwd);
4934 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4935 goto done;
4936 else
4937 error = NULL;
4938 if (worktree) {
4939 repo_path =
4940 strdup(got_worktree_get_repo_path(worktree));
4941 if (repo_path == NULL)
4942 error = got_error_from_errno("strdup");
4943 if (error)
4944 goto done;
4945 } else {
4946 repo_path = strdup(cwd);
4947 if (repo_path == NULL) {
4948 error = got_error_from_errno("strdup");
4949 goto done;
4954 error = got_repo_open(&repo, repo_path, NULL);
4955 if (error != NULL)
4956 goto done;
4958 error = apply_unveil(got_repo_get_path(repo), do_list,
4959 worktree ? got_worktree_get_root_path(worktree) : NULL);
4960 if (error)
4961 goto done;
4963 if (do_list)
4964 error = list_refs(repo, refname);
4965 else if (do_delete)
4966 error = delete_ref(repo, refname);
4967 else if (symref_target)
4968 error = add_symref(repo, refname, symref_target);
4969 else {
4970 if (obj_arg == NULL)
4971 usage_ref();
4972 error = add_ref(repo, refname, obj_arg);
4974 done:
4975 free(refname);
4976 if (repo)
4977 got_repo_close(repo);
4978 if (worktree)
4979 got_worktree_close(worktree);
4980 free(cwd);
4981 free(repo_path);
4982 return error;
4985 __dead static void
4986 usage_branch(void)
4988 fprintf(stderr,
4989 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
4990 "[name]\n", getprogname());
4991 exit(1);
4994 static const struct got_error *
4995 list_branch(struct got_repository *repo, struct got_worktree *worktree,
4996 struct got_reference *ref)
4998 const struct got_error *err = NULL;
4999 const char *refname, *marker = " ";
5000 char *refstr;
5002 refname = got_ref_get_name(ref);
5003 if (worktree && strcmp(refname,
5004 got_worktree_get_head_ref_name(worktree)) == 0) {
5005 struct got_object_id *id = NULL;
5007 err = got_ref_resolve(&id, repo, ref);
5008 if (err)
5009 return err;
5010 if (got_object_id_cmp(id,
5011 got_worktree_get_base_commit_id(worktree)) == 0)
5012 marker = "* ";
5013 else
5014 marker = "~ ";
5015 free(id);
5018 if (strncmp(refname, "refs/heads/", 11) == 0)
5019 refname += 11;
5020 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5021 refname += 18;
5023 refstr = got_ref_to_str(ref);
5024 if (refstr == NULL)
5025 return got_error_from_errno("got_ref_to_str");
5027 printf("%s%s: %s\n", marker, refname, refstr);
5028 free(refstr);
5029 return NULL;
5032 static const struct got_error *
5033 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5035 const char *refname;
5037 if (worktree == NULL)
5038 return got_error(GOT_ERR_NOT_WORKTREE);
5040 refname = got_worktree_get_head_ref_name(worktree);
5042 if (strncmp(refname, "refs/heads/", 11) == 0)
5043 refname += 11;
5044 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5045 refname += 18;
5047 printf("%s\n", refname);
5049 return NULL;
5052 static const struct got_error *
5053 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5055 static const struct got_error *err = NULL;
5056 struct got_reflist_head refs;
5057 struct got_reflist_entry *re;
5058 struct got_reference *temp_ref = NULL;
5059 int rebase_in_progress, histedit_in_progress;
5061 SIMPLEQ_INIT(&refs);
5063 if (worktree) {
5064 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5065 worktree);
5066 if (err)
5067 return err;
5069 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5070 worktree);
5071 if (err)
5072 return err;
5074 if (rebase_in_progress || histedit_in_progress) {
5075 err = got_ref_open(&temp_ref, repo,
5076 got_worktree_get_head_ref_name(worktree), 0);
5077 if (err)
5078 return err;
5079 list_branch(repo, worktree, temp_ref);
5080 got_ref_close(temp_ref);
5084 err = got_ref_list(&refs, repo, "refs/heads",
5085 got_ref_cmp_by_name, NULL);
5086 if (err)
5087 return err;
5089 SIMPLEQ_FOREACH(re, &refs, entry)
5090 list_branch(repo, worktree, re->ref);
5092 got_ref_list_free(&refs);
5093 return NULL;
5096 static const struct got_error *
5097 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5098 const char *branch_name)
5100 const struct got_error *err = NULL;
5101 struct got_reference *ref = NULL;
5102 char *refname;
5104 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5105 return got_error_from_errno("asprintf");
5107 err = got_ref_open(&ref, repo, refname, 0);
5108 if (err)
5109 goto done;
5111 if (worktree &&
5112 strcmp(got_worktree_get_head_ref_name(worktree),
5113 got_ref_get_name(ref)) == 0) {
5114 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5115 "will not delete this work tree's current branch");
5116 goto done;
5119 err = got_ref_delete(ref, repo);
5120 done:
5121 if (ref)
5122 got_ref_close(ref);
5123 free(refname);
5124 return err;
5127 static const struct got_error *
5128 add_branch(struct got_repository *repo, const char *branch_name,
5129 struct got_object_id *base_commit_id)
5131 const struct got_error *err = NULL;
5132 struct got_reference *ref = NULL;
5133 char *base_refname = NULL, *refname = NULL;
5136 * Don't let the user create a branch name with a leading '-'.
5137 * While technically a valid reference name, this case is usually
5138 * an unintended typo.
5140 if (branch_name[0] == '-')
5141 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5143 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5144 err = got_error_from_errno("asprintf");
5145 goto done;
5148 err = got_ref_open(&ref, repo, refname, 0);
5149 if (err == NULL) {
5150 err = got_error(GOT_ERR_BRANCH_EXISTS);
5151 goto done;
5152 } else if (err->code != GOT_ERR_NOT_REF)
5153 goto done;
5155 err = got_ref_alloc(&ref, refname, base_commit_id);
5156 if (err)
5157 goto done;
5159 err = got_ref_write(ref, repo);
5160 done:
5161 if (ref)
5162 got_ref_close(ref);
5163 free(base_refname);
5164 free(refname);
5165 return err;
5168 static const struct got_error *
5169 cmd_branch(int argc, char *argv[])
5171 const struct got_error *error = NULL;
5172 struct got_repository *repo = NULL;
5173 struct got_worktree *worktree = NULL;
5174 char *cwd = NULL, *repo_path = NULL;
5175 int ch, do_list = 0, do_show = 0, do_update = 1;
5176 const char *delref = NULL, *commit_id_arg = NULL;
5177 struct got_reference *ref = NULL;
5178 struct got_pathlist_head paths;
5179 struct got_pathlist_entry *pe;
5180 struct got_object_id *commit_id = NULL;
5181 char *commit_id_str = NULL;
5183 TAILQ_INIT(&paths);
5185 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5186 switch (ch) {
5187 case 'c':
5188 commit_id_arg = optarg;
5189 break;
5190 case 'd':
5191 delref = optarg;
5192 break;
5193 case 'r':
5194 repo_path = realpath(optarg, NULL);
5195 if (repo_path == NULL)
5196 return got_error_from_errno2("realpath",
5197 optarg);
5198 got_path_strip_trailing_slashes(repo_path);
5199 break;
5200 case 'l':
5201 do_list = 1;
5202 break;
5203 case 'n':
5204 do_update = 0;
5205 break;
5206 default:
5207 usage_branch();
5208 /* NOTREACHED */
5212 if (do_list && delref)
5213 errx(1, "-l and -d options are mutually exclusive");
5215 argc -= optind;
5216 argv += optind;
5218 if (!do_list && !delref && argc == 0)
5219 do_show = 1;
5221 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5222 errx(1, "-c option can only be used when creating a branch");
5224 if (do_list || delref) {
5225 if (argc > 0)
5226 usage_branch();
5227 } else if (!do_show && argc != 1)
5228 usage_branch();
5230 #ifndef PROFILE
5231 if (do_list || do_show) {
5232 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5233 NULL) == -1)
5234 err(1, "pledge");
5235 } else {
5236 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5237 "sendfd unveil", NULL) == -1)
5238 err(1, "pledge");
5240 #endif
5241 cwd = getcwd(NULL, 0);
5242 if (cwd == NULL) {
5243 error = got_error_from_errno("getcwd");
5244 goto done;
5247 if (repo_path == NULL) {
5248 error = got_worktree_open(&worktree, cwd);
5249 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5250 goto done;
5251 else
5252 error = NULL;
5253 if (worktree) {
5254 repo_path =
5255 strdup(got_worktree_get_repo_path(worktree));
5256 if (repo_path == NULL)
5257 error = got_error_from_errno("strdup");
5258 if (error)
5259 goto done;
5260 } else {
5261 repo_path = strdup(cwd);
5262 if (repo_path == NULL) {
5263 error = got_error_from_errno("strdup");
5264 goto done;
5269 error = got_repo_open(&repo, repo_path, NULL);
5270 if (error != NULL)
5271 goto done;
5273 error = apply_unveil(got_repo_get_path(repo), do_list,
5274 worktree ? got_worktree_get_root_path(worktree) : NULL);
5275 if (error)
5276 goto done;
5278 if (do_show)
5279 error = show_current_branch(repo, worktree);
5280 else if (do_list)
5281 error = list_branches(repo, worktree);
5282 else if (delref)
5283 error = delete_branch(repo, worktree, delref);
5284 else {
5285 if (commit_id_arg == NULL)
5286 commit_id_arg = worktree ?
5287 got_worktree_get_head_ref_name(worktree) :
5288 GOT_REF_HEAD;
5289 error = got_repo_match_object_id(&commit_id, NULL,
5290 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5291 if (error)
5292 goto done;
5293 error = add_branch(repo, argv[0], commit_id);
5294 if (error)
5295 goto done;
5296 if (worktree && do_update) {
5297 struct got_update_progress_arg upa;
5298 char *branch_refname = NULL;
5300 error = got_object_id_str(&commit_id_str, commit_id);
5301 if (error)
5302 goto done;
5303 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5304 worktree);
5305 if (error)
5306 goto done;
5307 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5308 == -1) {
5309 error = got_error_from_errno("asprintf");
5310 goto done;
5312 error = got_ref_open(&ref, repo, branch_refname, 0);
5313 free(branch_refname);
5314 if (error)
5315 goto done;
5316 error = switch_head_ref(ref, commit_id, worktree,
5317 repo);
5318 if (error)
5319 goto done;
5320 error = got_worktree_set_base_commit_id(worktree, repo,
5321 commit_id);
5322 if (error)
5323 goto done;
5324 memset(&upa, 0, sizeof(upa));
5325 error = got_worktree_checkout_files(worktree, &paths,
5326 repo, update_progress, &upa, check_cancelled,
5327 NULL);
5328 if (error)
5329 goto done;
5330 if (upa.did_something)
5331 printf("Updated to commit %s\n", commit_id_str);
5332 print_update_progress_stats(&upa);
5335 done:
5336 if (ref)
5337 got_ref_close(ref);
5338 if (repo)
5339 got_repo_close(repo);
5340 if (worktree)
5341 got_worktree_close(worktree);
5342 free(cwd);
5343 free(repo_path);
5344 free(commit_id);
5345 free(commit_id_str);
5346 TAILQ_FOREACH(pe, &paths, entry)
5347 free((char *)pe->path);
5348 got_pathlist_free(&paths);
5349 return error;
5353 __dead static void
5354 usage_tag(void)
5356 fprintf(stderr,
5357 "usage: %s tag [-c commit] [-r repository] [-l] "
5358 "[-m message] name\n", getprogname());
5359 exit(1);
5362 #if 0
5363 static const struct got_error *
5364 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5366 const struct got_error *err = NULL;
5367 struct got_reflist_entry *re, *se, *new;
5368 struct got_object_id *re_id, *se_id;
5369 struct got_tag_object *re_tag, *se_tag;
5370 time_t re_time, se_time;
5372 SIMPLEQ_FOREACH(re, tags, entry) {
5373 se = SIMPLEQ_FIRST(sorted);
5374 if (se == NULL) {
5375 err = got_reflist_entry_dup(&new, re);
5376 if (err)
5377 return err;
5378 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5379 continue;
5380 } else {
5381 err = got_ref_resolve(&re_id, repo, re->ref);
5382 if (err)
5383 break;
5384 err = got_object_open_as_tag(&re_tag, repo, re_id);
5385 free(re_id);
5386 if (err)
5387 break;
5388 re_time = got_object_tag_get_tagger_time(re_tag);
5389 got_object_tag_close(re_tag);
5392 while (se) {
5393 err = got_ref_resolve(&se_id, repo, re->ref);
5394 if (err)
5395 break;
5396 err = got_object_open_as_tag(&se_tag, repo, se_id);
5397 free(se_id);
5398 if (err)
5399 break;
5400 se_time = got_object_tag_get_tagger_time(se_tag);
5401 got_object_tag_close(se_tag);
5403 if (se_time > re_time) {
5404 err = got_reflist_entry_dup(&new, re);
5405 if (err)
5406 return err;
5407 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5408 break;
5410 se = SIMPLEQ_NEXT(se, entry);
5411 continue;
5414 done:
5415 return err;
5417 #endif
5419 static const struct got_error *
5420 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5422 static const struct got_error *err = NULL;
5423 struct got_reflist_head refs;
5424 struct got_reflist_entry *re;
5426 SIMPLEQ_INIT(&refs);
5428 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5429 if (err)
5430 return err;
5432 SIMPLEQ_FOREACH(re, &refs, entry) {
5433 const char *refname;
5434 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5435 char datebuf[26];
5436 const char *tagger;
5437 time_t tagger_time;
5438 struct got_object_id *id;
5439 struct got_tag_object *tag;
5440 struct got_commit_object *commit = NULL;
5442 refname = got_ref_get_name(re->ref);
5443 if (strncmp(refname, "refs/tags/", 10) != 0)
5444 continue;
5445 refname += 10;
5446 refstr = got_ref_to_str(re->ref);
5447 if (refstr == NULL) {
5448 err = got_error_from_errno("got_ref_to_str");
5449 break;
5451 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5452 free(refstr);
5454 err = got_ref_resolve(&id, repo, re->ref);
5455 if (err)
5456 break;
5457 err = got_object_open_as_tag(&tag, repo, id);
5458 if (err) {
5459 if (err->code != GOT_ERR_OBJ_TYPE) {
5460 free(id);
5461 break;
5463 /* "lightweight" tag */
5464 err = got_object_open_as_commit(&commit, repo, id);
5465 if (err) {
5466 free(id);
5467 break;
5469 tagger = got_object_commit_get_committer(commit);
5470 tagger_time =
5471 got_object_commit_get_committer_time(commit);
5472 err = got_object_id_str(&id_str, id);
5473 free(id);
5474 if (err)
5475 break;
5476 } else {
5477 free(id);
5478 tagger = got_object_tag_get_tagger(tag);
5479 tagger_time = got_object_tag_get_tagger_time(tag);
5480 err = got_object_id_str(&id_str,
5481 got_object_tag_get_object_id(tag));
5482 if (err)
5483 break;
5485 printf("from: %s\n", tagger);
5486 datestr = get_datestr(&tagger_time, datebuf);
5487 if (datestr)
5488 printf("date: %s UTC\n", datestr);
5489 if (commit)
5490 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5491 else {
5492 switch (got_object_tag_get_object_type(tag)) {
5493 case GOT_OBJ_TYPE_BLOB:
5494 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5495 id_str);
5496 break;
5497 case GOT_OBJ_TYPE_TREE:
5498 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5499 id_str);
5500 break;
5501 case GOT_OBJ_TYPE_COMMIT:
5502 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5503 id_str);
5504 break;
5505 case GOT_OBJ_TYPE_TAG:
5506 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5507 id_str);
5508 break;
5509 default:
5510 break;
5513 free(id_str);
5514 if (commit) {
5515 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5516 if (err)
5517 break;
5518 got_object_commit_close(commit);
5519 } else {
5520 tagmsg0 = strdup(got_object_tag_get_message(tag));
5521 got_object_tag_close(tag);
5522 if (tagmsg0 == NULL) {
5523 err = got_error_from_errno("strdup");
5524 break;
5528 tagmsg = tagmsg0;
5529 do {
5530 line = strsep(&tagmsg, "\n");
5531 if (line)
5532 printf(" %s\n", line);
5533 } while (line);
5534 free(tagmsg0);
5537 got_ref_list_free(&refs);
5538 return NULL;
5541 static const struct got_error *
5542 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5543 const char *tag_name, const char *repo_path)
5545 const struct got_error *err = NULL;
5546 char *template = NULL, *initial_content = NULL;
5547 char *editor = NULL;
5548 int fd = -1;
5550 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5551 err = got_error_from_errno("asprintf");
5552 goto done;
5555 if (asprintf(&initial_content, "\n# tagging commit %s as %s\n",
5556 commit_id_str, tag_name) == -1) {
5557 err = got_error_from_errno("asprintf");
5558 goto done;
5561 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5562 if (err)
5563 goto done;
5565 dprintf(fd, initial_content);
5566 close(fd);
5568 err = get_editor(&editor);
5569 if (err)
5570 goto done;
5571 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
5572 done:
5573 free(initial_content);
5574 free(template);
5575 free(editor);
5577 /* Editor is done; we can now apply unveil(2) */
5578 if (err == NULL) {
5579 err = apply_unveil(repo_path, 0, NULL);
5580 if (err) {
5581 free(*tagmsg);
5582 *tagmsg = NULL;
5585 return err;
5588 static const struct got_error *
5589 add_tag(struct got_repository *repo, const char *tag_name,
5590 const char *commit_arg, const char *tagmsg_arg)
5592 const struct got_error *err = NULL;
5593 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5594 char *label = NULL, *commit_id_str = NULL;
5595 struct got_reference *ref = NULL;
5596 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5597 char *tagmsg_path = NULL, *tag_id_str = NULL;
5598 int preserve_tagmsg = 0;
5601 * Don't let the user create a tag name with a leading '-'.
5602 * While technically a valid reference name, this case is usually
5603 * an unintended typo.
5605 if (tag_name[0] == '-')
5606 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5608 err = get_author(&tagger, repo);
5609 if (err)
5610 return err;
5612 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5613 GOT_OBJ_TYPE_COMMIT, 1, repo);
5614 if (err)
5615 goto done;
5617 err = got_object_id_str(&commit_id_str, commit_id);
5618 if (err)
5619 goto done;
5621 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5622 refname = strdup(tag_name);
5623 if (refname == NULL) {
5624 err = got_error_from_errno("strdup");
5625 goto done;
5627 tag_name += 10;
5628 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5629 err = got_error_from_errno("asprintf");
5630 goto done;
5633 err = got_ref_open(&ref, repo, refname, 0);
5634 if (err == NULL) {
5635 err = got_error(GOT_ERR_TAG_EXISTS);
5636 goto done;
5637 } else if (err->code != GOT_ERR_NOT_REF)
5638 goto done;
5640 if (tagmsg_arg == NULL) {
5641 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5642 tag_name, got_repo_get_path(repo));
5643 if (err) {
5644 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5645 tagmsg_path != NULL)
5646 preserve_tagmsg = 1;
5647 goto done;
5651 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5652 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5653 if (err) {
5654 if (tagmsg_path)
5655 preserve_tagmsg = 1;
5656 goto done;
5659 err = got_ref_alloc(&ref, refname, tag_id);
5660 if (err) {
5661 if (tagmsg_path)
5662 preserve_tagmsg = 1;
5663 goto done;
5666 err = got_ref_write(ref, repo);
5667 if (err) {
5668 if (tagmsg_path)
5669 preserve_tagmsg = 1;
5670 goto done;
5673 err = got_object_id_str(&tag_id_str, tag_id);
5674 if (err) {
5675 if (tagmsg_path)
5676 preserve_tagmsg = 1;
5677 goto done;
5679 printf("Created tag %s\n", tag_id_str);
5680 done:
5681 if (preserve_tagmsg) {
5682 fprintf(stderr, "%s: tag message preserved in %s\n",
5683 getprogname(), tagmsg_path);
5684 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
5685 err = got_error_from_errno2("unlink", tagmsg_path);
5686 free(tag_id_str);
5687 if (ref)
5688 got_ref_close(ref);
5689 free(commit_id);
5690 free(commit_id_str);
5691 free(refname);
5692 free(tagmsg);
5693 free(tagmsg_path);
5694 free(tagger);
5695 return err;
5698 static const struct got_error *
5699 cmd_tag(int argc, char *argv[])
5701 const struct got_error *error = NULL;
5702 struct got_repository *repo = NULL;
5703 struct got_worktree *worktree = NULL;
5704 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
5705 char *gitconfig_path = NULL;
5706 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
5707 int ch, do_list = 0;
5709 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
5710 switch (ch) {
5711 case 'c':
5712 commit_id_arg = optarg;
5713 break;
5714 case 'm':
5715 tagmsg = optarg;
5716 break;
5717 case 'r':
5718 repo_path = realpath(optarg, NULL);
5719 if (repo_path == NULL)
5720 return got_error_from_errno2("realpath",
5721 optarg);
5722 got_path_strip_trailing_slashes(repo_path);
5723 break;
5724 case 'l':
5725 do_list = 1;
5726 break;
5727 default:
5728 usage_tag();
5729 /* NOTREACHED */
5733 argc -= optind;
5734 argv += optind;
5736 if (do_list) {
5737 if (commit_id_arg != NULL)
5738 errx(1,
5739 "-c option can only be used when creating a tag");
5740 if (tagmsg)
5741 errx(1, "-l and -m options are mutually exclusive");
5742 if (argc > 0)
5743 usage_tag();
5744 } else if (argc != 1)
5745 usage_tag();
5747 tag_name = argv[0];
5749 #ifndef PROFILE
5750 if (do_list) {
5751 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5752 NULL) == -1)
5753 err(1, "pledge");
5754 } else {
5755 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5756 "sendfd unveil", NULL) == -1)
5757 err(1, "pledge");
5759 #endif
5760 cwd = getcwd(NULL, 0);
5761 if (cwd == NULL) {
5762 error = got_error_from_errno("getcwd");
5763 goto done;
5766 if (repo_path == NULL) {
5767 error = got_worktree_open(&worktree, cwd);
5768 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5769 goto done;
5770 else
5771 error = NULL;
5772 if (worktree) {
5773 repo_path =
5774 strdup(got_worktree_get_repo_path(worktree));
5775 if (repo_path == NULL)
5776 error = got_error_from_errno("strdup");
5777 if (error)
5778 goto done;
5779 } else {
5780 repo_path = strdup(cwd);
5781 if (repo_path == NULL) {
5782 error = got_error_from_errno("strdup");
5783 goto done;
5788 if (do_list) {
5789 error = got_repo_open(&repo, repo_path, NULL);
5790 if (error != NULL)
5791 goto done;
5792 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5793 if (error)
5794 goto done;
5795 error = list_tags(repo, worktree);
5796 } else {
5797 error = get_gitconfig_path(&gitconfig_path);
5798 if (error)
5799 goto done;
5800 error = got_repo_open(&repo, repo_path, gitconfig_path);
5801 if (error != NULL)
5802 goto done;
5804 if (tagmsg) {
5805 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5806 if (error)
5807 goto done;
5810 if (commit_id_arg == NULL) {
5811 struct got_reference *head_ref;
5812 struct got_object_id *commit_id;
5813 error = got_ref_open(&head_ref, repo,
5814 worktree ? got_worktree_get_head_ref_name(worktree)
5815 : GOT_REF_HEAD, 0);
5816 if (error)
5817 goto done;
5818 error = got_ref_resolve(&commit_id, repo, head_ref);
5819 got_ref_close(head_ref);
5820 if (error)
5821 goto done;
5822 error = got_object_id_str(&commit_id_str, commit_id);
5823 free(commit_id);
5824 if (error)
5825 goto done;
5828 error = add_tag(repo, tag_name,
5829 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
5831 done:
5832 if (repo)
5833 got_repo_close(repo);
5834 if (worktree)
5835 got_worktree_close(worktree);
5836 free(cwd);
5837 free(repo_path);
5838 free(gitconfig_path);
5839 free(commit_id_str);
5840 return error;
5843 __dead static void
5844 usage_add(void)
5846 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
5847 getprogname());
5848 exit(1);
5851 static const struct got_error *
5852 add_progress(void *arg, unsigned char status, const char *path)
5854 while (path[0] == '/')
5855 path++;
5856 printf("%c %s\n", status, path);
5857 return NULL;
5860 static const struct got_error *
5861 cmd_add(int argc, char *argv[])
5863 const struct got_error *error = NULL;
5864 struct got_repository *repo = NULL;
5865 struct got_worktree *worktree = NULL;
5866 char *cwd = NULL;
5867 struct got_pathlist_head paths;
5868 struct got_pathlist_entry *pe;
5869 int ch, can_recurse = 0, no_ignores = 0;
5871 TAILQ_INIT(&paths);
5873 while ((ch = getopt(argc, argv, "IR")) != -1) {
5874 switch (ch) {
5875 case 'I':
5876 no_ignores = 1;
5877 break;
5878 case 'R':
5879 can_recurse = 1;
5880 break;
5881 default:
5882 usage_add();
5883 /* NOTREACHED */
5887 argc -= optind;
5888 argv += optind;
5890 #ifndef PROFILE
5891 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5892 NULL) == -1)
5893 err(1, "pledge");
5894 #endif
5895 if (argc < 1)
5896 usage_add();
5898 cwd = getcwd(NULL, 0);
5899 if (cwd == NULL) {
5900 error = got_error_from_errno("getcwd");
5901 goto done;
5904 error = got_worktree_open(&worktree, cwd);
5905 if (error) {
5906 if (error->code == GOT_ERR_NOT_WORKTREE)
5907 error = wrap_not_worktree_error(error, "add", cwd);
5908 goto done;
5911 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5912 NULL);
5913 if (error != NULL)
5914 goto done;
5916 error = apply_unveil(got_repo_get_path(repo), 1,
5917 got_worktree_get_root_path(worktree));
5918 if (error)
5919 goto done;
5921 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5922 if (error)
5923 goto done;
5925 if (!can_recurse && no_ignores) {
5926 error = got_error_msg(GOT_ERR_BAD_PATH,
5927 "disregarding ignores requires -R option");
5928 goto done;
5932 if (!can_recurse) {
5933 char *ondisk_path;
5934 struct stat sb;
5935 TAILQ_FOREACH(pe, &paths, entry) {
5936 if (asprintf(&ondisk_path, "%s/%s",
5937 got_worktree_get_root_path(worktree),
5938 pe->path) == -1) {
5939 error = got_error_from_errno("asprintf");
5940 goto done;
5942 if (lstat(ondisk_path, &sb) == -1) {
5943 if (errno == ENOENT) {
5944 free(ondisk_path);
5945 continue;
5947 error = got_error_from_errno2("lstat",
5948 ondisk_path);
5949 free(ondisk_path);
5950 goto done;
5952 free(ondisk_path);
5953 if (S_ISDIR(sb.st_mode)) {
5954 error = got_error_msg(GOT_ERR_BAD_PATH,
5955 "adding directories requires -R option");
5956 goto done;
5961 error = got_worktree_schedule_add(worktree, &paths, add_progress,
5962 NULL, repo, no_ignores);
5963 done:
5964 if (repo)
5965 got_repo_close(repo);
5966 if (worktree)
5967 got_worktree_close(worktree);
5968 TAILQ_FOREACH(pe, &paths, entry)
5969 free((char *)pe->path);
5970 got_pathlist_free(&paths);
5971 free(cwd);
5972 return error;
5975 __dead static void
5976 usage_remove(void)
5978 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] path ...\n",
5979 getprogname());
5980 exit(1);
5983 static const struct got_error *
5984 print_remove_status(void *arg, unsigned char status,
5985 unsigned char staged_status, const char *path)
5987 while (path[0] == '/')
5988 path++;
5989 if (status == GOT_STATUS_NONEXISTENT)
5990 return NULL;
5991 if (status == staged_status && (status == GOT_STATUS_DELETE))
5992 status = GOT_STATUS_NO_CHANGE;
5993 printf("%c%c %s\n", status, staged_status, path);
5994 return NULL;
5997 static const struct got_error *
5998 cmd_remove(int argc, char *argv[])
6000 const struct got_error *error = NULL;
6001 struct got_worktree *worktree = NULL;
6002 struct got_repository *repo = NULL;
6003 char *cwd = NULL;
6004 struct got_pathlist_head paths;
6005 struct got_pathlist_entry *pe;
6006 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0;
6008 TAILQ_INIT(&paths);
6010 while ((ch = getopt(argc, argv, "fkR")) != -1) {
6011 switch (ch) {
6012 case 'f':
6013 delete_local_mods = 1;
6014 break;
6015 case 'k':
6016 keep_on_disk = 1;
6017 break;
6018 case 'R':
6019 can_recurse = 1;
6020 break;
6021 default:
6022 usage_remove();
6023 /* NOTREACHED */
6027 argc -= optind;
6028 argv += optind;
6030 #ifndef PROFILE
6031 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6032 NULL) == -1)
6033 err(1, "pledge");
6034 #endif
6035 if (argc < 1)
6036 usage_remove();
6038 cwd = getcwd(NULL, 0);
6039 if (cwd == NULL) {
6040 error = got_error_from_errno("getcwd");
6041 goto done;
6043 error = got_worktree_open(&worktree, cwd);
6044 if (error) {
6045 if (error->code == GOT_ERR_NOT_WORKTREE)
6046 error = wrap_not_worktree_error(error, "remove", cwd);
6047 goto done;
6050 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6051 NULL);
6052 if (error)
6053 goto done;
6055 error = apply_unveil(got_repo_get_path(repo), 1,
6056 got_worktree_get_root_path(worktree));
6057 if (error)
6058 goto done;
6060 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6061 if (error)
6062 goto done;
6064 if (!can_recurse) {
6065 char *ondisk_path;
6066 struct stat sb;
6067 TAILQ_FOREACH(pe, &paths, entry) {
6068 if (asprintf(&ondisk_path, "%s/%s",
6069 got_worktree_get_root_path(worktree),
6070 pe->path) == -1) {
6071 error = got_error_from_errno("asprintf");
6072 goto done;
6074 if (lstat(ondisk_path, &sb) == -1) {
6075 if (errno == ENOENT) {
6076 free(ondisk_path);
6077 continue;
6079 error = got_error_from_errno2("lstat",
6080 ondisk_path);
6081 free(ondisk_path);
6082 goto done;
6084 free(ondisk_path);
6085 if (S_ISDIR(sb.st_mode)) {
6086 error = got_error_msg(GOT_ERR_BAD_PATH,
6087 "removing directories requires -R option");
6088 goto done;
6093 error = got_worktree_schedule_delete(worktree, &paths,
6094 delete_local_mods, print_remove_status, NULL, repo, keep_on_disk);
6095 done:
6096 if (repo)
6097 got_repo_close(repo);
6098 if (worktree)
6099 got_worktree_close(worktree);
6100 TAILQ_FOREACH(pe, &paths, entry)
6101 free((char *)pe->path);
6102 got_pathlist_free(&paths);
6103 free(cwd);
6104 return error;
6107 __dead static void
6108 usage_revert(void)
6110 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6111 "path ...\n", getprogname());
6112 exit(1);
6115 static const struct got_error *
6116 revert_progress(void *arg, unsigned char status, const char *path)
6118 if (status == GOT_STATUS_UNVERSIONED)
6119 return NULL;
6121 while (path[0] == '/')
6122 path++;
6123 printf("%c %s\n", status, path);
6124 return NULL;
6127 struct choose_patch_arg {
6128 FILE *patch_script_file;
6129 const char *action;
6132 static const struct got_error *
6133 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6134 int nchanges, const char *action)
6136 char *line = NULL;
6137 size_t linesize = 0;
6138 ssize_t linelen;
6140 switch (status) {
6141 case GOT_STATUS_ADD:
6142 printf("A %s\n%s this addition? [y/n] ", path, action);
6143 break;
6144 case GOT_STATUS_DELETE:
6145 printf("D %s\n%s this deletion? [y/n] ", path, action);
6146 break;
6147 case GOT_STATUS_MODIFY:
6148 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6149 return got_error_from_errno("fseek");
6150 printf(GOT_COMMIT_SEP_STR);
6151 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6152 printf("%s", line);
6153 if (ferror(patch_file))
6154 return got_error_from_errno("getline");
6155 printf(GOT_COMMIT_SEP_STR);
6156 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6157 path, n, nchanges, action);
6158 break;
6159 default:
6160 return got_error_path(path, GOT_ERR_FILE_STATUS);
6163 return NULL;
6166 static const struct got_error *
6167 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6168 FILE *patch_file, int n, int nchanges)
6170 const struct got_error *err = NULL;
6171 char *line = NULL;
6172 size_t linesize = 0;
6173 ssize_t linelen;
6174 int resp = ' ';
6175 struct choose_patch_arg *a = arg;
6177 *choice = GOT_PATCH_CHOICE_NONE;
6179 if (a->patch_script_file) {
6180 char *nl;
6181 err = show_change(status, path, patch_file, n, nchanges,
6182 a->action);
6183 if (err)
6184 return err;
6185 linelen = getline(&line, &linesize, a->patch_script_file);
6186 if (linelen == -1) {
6187 if (ferror(a->patch_script_file))
6188 return got_error_from_errno("getline");
6189 return NULL;
6191 nl = strchr(line, '\n');
6192 if (nl)
6193 *nl = '\0';
6194 if (strcmp(line, "y") == 0) {
6195 *choice = GOT_PATCH_CHOICE_YES;
6196 printf("y\n");
6197 } else if (strcmp(line, "n") == 0) {
6198 *choice = GOT_PATCH_CHOICE_NO;
6199 printf("n\n");
6200 } else if (strcmp(line, "q") == 0 &&
6201 status == GOT_STATUS_MODIFY) {
6202 *choice = GOT_PATCH_CHOICE_QUIT;
6203 printf("q\n");
6204 } else
6205 printf("invalid response '%s'\n", line);
6206 free(line);
6207 return NULL;
6210 while (resp != 'y' && resp != 'n' && resp != 'q') {
6211 err = show_change(status, path, patch_file, n, nchanges,
6212 a->action);
6213 if (err)
6214 return err;
6215 resp = getchar();
6216 if (resp == '\n')
6217 resp = getchar();
6218 if (status == GOT_STATUS_MODIFY) {
6219 if (resp != 'y' && resp != 'n' && resp != 'q') {
6220 printf("invalid response '%c'\n", resp);
6221 resp = ' ';
6223 } else if (resp != 'y' && resp != 'n') {
6224 printf("invalid response '%c'\n", resp);
6225 resp = ' ';
6229 if (resp == 'y')
6230 *choice = GOT_PATCH_CHOICE_YES;
6231 else if (resp == 'n')
6232 *choice = GOT_PATCH_CHOICE_NO;
6233 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6234 *choice = GOT_PATCH_CHOICE_QUIT;
6236 return NULL;
6240 static const struct got_error *
6241 cmd_revert(int argc, char *argv[])
6243 const struct got_error *error = NULL;
6244 struct got_worktree *worktree = NULL;
6245 struct got_repository *repo = NULL;
6246 char *cwd = NULL, *path = NULL;
6247 struct got_pathlist_head paths;
6248 struct got_pathlist_entry *pe;
6249 int ch, can_recurse = 0, pflag = 0;
6250 FILE *patch_script_file = NULL;
6251 const char *patch_script_path = NULL;
6252 struct choose_patch_arg cpa;
6254 TAILQ_INIT(&paths);
6256 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6257 switch (ch) {
6258 case 'p':
6259 pflag = 1;
6260 break;
6261 case 'F':
6262 patch_script_path = optarg;
6263 break;
6264 case 'R':
6265 can_recurse = 1;
6266 break;
6267 default:
6268 usage_revert();
6269 /* NOTREACHED */
6273 argc -= optind;
6274 argv += optind;
6276 #ifndef PROFILE
6277 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6278 "unveil", NULL) == -1)
6279 err(1, "pledge");
6280 #endif
6281 if (argc < 1)
6282 usage_revert();
6283 if (patch_script_path && !pflag)
6284 errx(1, "-F option can only be used together with -p option");
6286 cwd = getcwd(NULL, 0);
6287 if (cwd == NULL) {
6288 error = got_error_from_errno("getcwd");
6289 goto done;
6291 error = got_worktree_open(&worktree, cwd);
6292 if (error) {
6293 if (error->code == GOT_ERR_NOT_WORKTREE)
6294 error = wrap_not_worktree_error(error, "revert", cwd);
6295 goto done;
6298 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6299 NULL);
6300 if (error != NULL)
6301 goto done;
6303 if (patch_script_path) {
6304 patch_script_file = fopen(patch_script_path, "r");
6305 if (patch_script_file == NULL) {
6306 error = got_error_from_errno2("fopen",
6307 patch_script_path);
6308 goto done;
6311 error = apply_unveil(got_repo_get_path(repo), 1,
6312 got_worktree_get_root_path(worktree));
6313 if (error)
6314 goto done;
6316 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6317 if (error)
6318 goto done;
6320 if (!can_recurse) {
6321 char *ondisk_path;
6322 struct stat sb;
6323 TAILQ_FOREACH(pe, &paths, entry) {
6324 if (asprintf(&ondisk_path, "%s/%s",
6325 got_worktree_get_root_path(worktree),
6326 pe->path) == -1) {
6327 error = got_error_from_errno("asprintf");
6328 goto done;
6330 if (lstat(ondisk_path, &sb) == -1) {
6331 if (errno == ENOENT) {
6332 free(ondisk_path);
6333 continue;
6335 error = got_error_from_errno2("lstat",
6336 ondisk_path);
6337 free(ondisk_path);
6338 goto done;
6340 free(ondisk_path);
6341 if (S_ISDIR(sb.st_mode)) {
6342 error = got_error_msg(GOT_ERR_BAD_PATH,
6343 "reverting directories requires -R option");
6344 goto done;
6349 cpa.patch_script_file = patch_script_file;
6350 cpa.action = "revert";
6351 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6352 pflag ? choose_patch : NULL, &cpa, repo);
6353 done:
6354 if (patch_script_file && fclose(patch_script_file) == EOF &&
6355 error == NULL)
6356 error = got_error_from_errno2("fclose", patch_script_path);
6357 if (repo)
6358 got_repo_close(repo);
6359 if (worktree)
6360 got_worktree_close(worktree);
6361 free(path);
6362 free(cwd);
6363 return error;
6366 __dead static void
6367 usage_commit(void)
6369 fprintf(stderr, "usage: %s commit [-m msg] [-S] [path ...]\n",
6370 getprogname());
6371 exit(1);
6374 struct collect_commit_logmsg_arg {
6375 const char *cmdline_log;
6376 const char *editor;
6377 const char *worktree_path;
6378 const char *branch_name;
6379 const char *repo_path;
6380 char *logmsg_path;
6384 static const struct got_error *
6385 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6386 void *arg)
6388 char *initial_content = NULL;
6389 struct got_pathlist_entry *pe;
6390 const struct got_error *err = NULL;
6391 char *template = NULL;
6392 struct collect_commit_logmsg_arg *a = arg;
6393 int fd;
6394 size_t len;
6396 /* if a message was specified on the command line, just use it */
6397 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6398 len = strlen(a->cmdline_log) + 1;
6399 *logmsg = malloc(len + 1);
6400 if (*logmsg == NULL)
6401 return got_error_from_errno("malloc");
6402 strlcpy(*logmsg, a->cmdline_log, len);
6403 return NULL;
6406 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6407 return got_error_from_errno("asprintf");
6409 if (asprintf(&initial_content,
6410 "\n# changes to be committed on branch %s:\n",
6411 a->branch_name) == -1)
6412 return got_error_from_errno("asprintf");
6414 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6415 if (err)
6416 goto done;
6418 dprintf(fd, initial_content);
6420 TAILQ_FOREACH(pe, commitable_paths, entry) {
6421 struct got_commitable *ct = pe->data;
6422 dprintf(fd, "# %c %s\n",
6423 got_commitable_get_status(ct),
6424 got_commitable_get_path(ct));
6426 close(fd);
6428 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
6429 done:
6430 free(initial_content);
6431 free(template);
6433 /* Editor is done; we can now apply unveil(2) */
6434 if (err == NULL) {
6435 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6436 if (err) {
6437 free(*logmsg);
6438 *logmsg = NULL;
6441 return err;
6444 static const struct got_error *
6445 cmd_commit(int argc, char *argv[])
6447 const struct got_error *error = NULL;
6448 struct got_worktree *worktree = NULL;
6449 struct got_repository *repo = NULL;
6450 char *cwd = NULL, *id_str = NULL;
6451 struct got_object_id *id = NULL;
6452 const char *logmsg = NULL;
6453 struct collect_commit_logmsg_arg cl_arg;
6454 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6455 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6456 int allow_bad_symlinks = 0;
6457 struct got_pathlist_head paths;
6459 TAILQ_INIT(&paths);
6460 cl_arg.logmsg_path = NULL;
6462 while ((ch = getopt(argc, argv, "m:S")) != -1) {
6463 switch (ch) {
6464 case 'm':
6465 logmsg = optarg;
6466 break;
6467 case 'S':
6468 allow_bad_symlinks = 1;
6469 break;
6470 default:
6471 usage_commit();
6472 /* NOTREACHED */
6476 argc -= optind;
6477 argv += optind;
6479 #ifndef PROFILE
6480 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6481 "unveil", NULL) == -1)
6482 err(1, "pledge");
6483 #endif
6484 cwd = getcwd(NULL, 0);
6485 if (cwd == NULL) {
6486 error = got_error_from_errno("getcwd");
6487 goto done;
6489 error = got_worktree_open(&worktree, cwd);
6490 if (error) {
6491 if (error->code == GOT_ERR_NOT_WORKTREE)
6492 error = wrap_not_worktree_error(error, "commit", cwd);
6493 goto done;
6496 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6497 if (error)
6498 goto done;
6499 if (rebase_in_progress) {
6500 error = got_error(GOT_ERR_REBASING);
6501 goto done;
6504 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6505 worktree);
6506 if (error)
6507 goto done;
6509 error = get_gitconfig_path(&gitconfig_path);
6510 if (error)
6511 goto done;
6512 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6513 gitconfig_path);
6514 if (error != NULL)
6515 goto done;
6517 error = get_author(&author, repo);
6518 if (error)
6519 return error;
6522 * unveil(2) traverses exec(2); if an editor is used we have
6523 * to apply unveil after the log message has been written.
6525 if (logmsg == NULL || strlen(logmsg) == 0)
6526 error = get_editor(&editor);
6527 else
6528 error = apply_unveil(got_repo_get_path(repo), 0,
6529 got_worktree_get_root_path(worktree));
6530 if (error)
6531 goto done;
6533 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6534 if (error)
6535 goto done;
6537 cl_arg.editor = editor;
6538 cl_arg.cmdline_log = logmsg;
6539 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6540 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6541 if (!histedit_in_progress) {
6542 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6543 error = got_error(GOT_ERR_COMMIT_BRANCH);
6544 goto done;
6546 cl_arg.branch_name += 11;
6548 cl_arg.repo_path = got_repo_get_path(repo);
6549 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6550 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
6551 print_status, NULL, repo);
6552 if (error) {
6553 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6554 cl_arg.logmsg_path != NULL)
6555 preserve_logmsg = 1;
6556 goto done;
6559 error = got_object_id_str(&id_str, id);
6560 if (error)
6561 goto done;
6562 printf("Created commit %s\n", id_str);
6563 done:
6564 if (preserve_logmsg) {
6565 fprintf(stderr, "%s: log message preserved in %s\n",
6566 getprogname(), cl_arg.logmsg_path);
6567 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6568 error == NULL)
6569 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6570 free(cl_arg.logmsg_path);
6571 if (repo)
6572 got_repo_close(repo);
6573 if (worktree)
6574 got_worktree_close(worktree);
6575 free(cwd);
6576 free(id_str);
6577 free(gitconfig_path);
6578 free(editor);
6579 free(author);
6580 return error;
6583 __dead static void
6584 usage_cherrypick(void)
6586 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6587 exit(1);
6590 static const struct got_error *
6591 cmd_cherrypick(int argc, char *argv[])
6593 const struct got_error *error = NULL;
6594 struct got_worktree *worktree = NULL;
6595 struct got_repository *repo = NULL;
6596 char *cwd = NULL, *commit_id_str = NULL;
6597 struct got_object_id *commit_id = NULL;
6598 struct got_commit_object *commit = NULL;
6599 struct got_object_qid *pid;
6600 struct got_reference *head_ref = NULL;
6601 int ch;
6602 struct got_update_progress_arg upa;
6604 while ((ch = getopt(argc, argv, "")) != -1) {
6605 switch (ch) {
6606 default:
6607 usage_cherrypick();
6608 /* NOTREACHED */
6612 argc -= optind;
6613 argv += optind;
6615 #ifndef PROFILE
6616 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6617 "unveil", NULL) == -1)
6618 err(1, "pledge");
6619 #endif
6620 if (argc != 1)
6621 usage_cherrypick();
6623 cwd = getcwd(NULL, 0);
6624 if (cwd == NULL) {
6625 error = got_error_from_errno("getcwd");
6626 goto done;
6628 error = got_worktree_open(&worktree, cwd);
6629 if (error) {
6630 if (error->code == GOT_ERR_NOT_WORKTREE)
6631 error = wrap_not_worktree_error(error, "cherrypick",
6632 cwd);
6633 goto done;
6636 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6637 NULL);
6638 if (error != NULL)
6639 goto done;
6641 error = apply_unveil(got_repo_get_path(repo), 0,
6642 got_worktree_get_root_path(worktree));
6643 if (error)
6644 goto done;
6646 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6647 GOT_OBJ_TYPE_COMMIT, repo);
6648 if (error != NULL) {
6649 struct got_reference *ref;
6650 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6651 goto done;
6652 error = got_ref_open(&ref, repo, argv[0], 0);
6653 if (error != NULL)
6654 goto done;
6655 error = got_ref_resolve(&commit_id, repo, ref);
6656 got_ref_close(ref);
6657 if (error != NULL)
6658 goto done;
6660 error = got_object_id_str(&commit_id_str, commit_id);
6661 if (error)
6662 goto done;
6664 error = got_ref_open(&head_ref, repo,
6665 got_worktree_get_head_ref_name(worktree), 0);
6666 if (error != NULL)
6667 goto done;
6669 error = check_same_branch(commit_id, head_ref, NULL, repo);
6670 if (error) {
6671 if (error->code != GOT_ERR_ANCESTRY)
6672 goto done;
6673 error = NULL;
6674 } else {
6675 error = got_error(GOT_ERR_SAME_BRANCH);
6676 goto done;
6679 error = got_object_open_as_commit(&commit, repo, commit_id);
6680 if (error)
6681 goto done;
6682 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6683 memset(&upa, 0, sizeof(upa));
6684 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
6685 commit_id, repo, update_progress, &upa, check_cancelled,
6686 NULL);
6687 if (error != NULL)
6688 goto done;
6690 if (upa.did_something)
6691 printf("Merged commit %s\n", commit_id_str);
6692 print_update_progress_stats(&upa);
6693 done:
6694 if (commit)
6695 got_object_commit_close(commit);
6696 free(commit_id_str);
6697 if (head_ref)
6698 got_ref_close(head_ref);
6699 if (worktree)
6700 got_worktree_close(worktree);
6701 if (repo)
6702 got_repo_close(repo);
6703 return error;
6706 __dead static void
6707 usage_backout(void)
6709 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
6710 exit(1);
6713 static const struct got_error *
6714 cmd_backout(int argc, char *argv[])
6716 const struct got_error *error = NULL;
6717 struct got_worktree *worktree = NULL;
6718 struct got_repository *repo = NULL;
6719 char *cwd = NULL, *commit_id_str = NULL;
6720 struct got_object_id *commit_id = NULL;
6721 struct got_commit_object *commit = NULL;
6722 struct got_object_qid *pid;
6723 struct got_reference *head_ref = NULL;
6724 int ch;
6725 struct got_update_progress_arg upa;
6727 while ((ch = getopt(argc, argv, "")) != -1) {
6728 switch (ch) {
6729 default:
6730 usage_backout();
6731 /* NOTREACHED */
6735 argc -= optind;
6736 argv += optind;
6738 #ifndef PROFILE
6739 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6740 "unveil", NULL) == -1)
6741 err(1, "pledge");
6742 #endif
6743 if (argc != 1)
6744 usage_backout();
6746 cwd = getcwd(NULL, 0);
6747 if (cwd == NULL) {
6748 error = got_error_from_errno("getcwd");
6749 goto done;
6751 error = got_worktree_open(&worktree, cwd);
6752 if (error) {
6753 if (error->code == GOT_ERR_NOT_WORKTREE)
6754 error = wrap_not_worktree_error(error, "backout", cwd);
6755 goto done;
6758 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6759 NULL);
6760 if (error != NULL)
6761 goto done;
6763 error = apply_unveil(got_repo_get_path(repo), 0,
6764 got_worktree_get_root_path(worktree));
6765 if (error)
6766 goto done;
6768 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6769 GOT_OBJ_TYPE_COMMIT, repo);
6770 if (error != NULL) {
6771 struct got_reference *ref;
6772 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6773 goto done;
6774 error = got_ref_open(&ref, repo, argv[0], 0);
6775 if (error != NULL)
6776 goto done;
6777 error = got_ref_resolve(&commit_id, repo, ref);
6778 got_ref_close(ref);
6779 if (error != NULL)
6780 goto done;
6782 error = got_object_id_str(&commit_id_str, commit_id);
6783 if (error)
6784 goto done;
6786 error = got_ref_open(&head_ref, repo,
6787 got_worktree_get_head_ref_name(worktree), 0);
6788 if (error != NULL)
6789 goto done;
6791 error = check_same_branch(commit_id, head_ref, NULL, repo);
6792 if (error)
6793 goto done;
6795 error = got_object_open_as_commit(&commit, repo, commit_id);
6796 if (error)
6797 goto done;
6798 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6799 if (pid == NULL) {
6800 error = got_error(GOT_ERR_ROOT_COMMIT);
6801 goto done;
6804 memset(&upa, 0, sizeof(upa));
6805 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
6806 update_progress, &upa, check_cancelled, NULL);
6807 if (error != NULL)
6808 goto done;
6810 if (upa.did_something)
6811 printf("Backed out commit %s\n", commit_id_str);
6812 print_update_progress_stats(&upa);
6813 done:
6814 if (commit)
6815 got_object_commit_close(commit);
6816 free(commit_id_str);
6817 if (head_ref)
6818 got_ref_close(head_ref);
6819 if (worktree)
6820 got_worktree_close(worktree);
6821 if (repo)
6822 got_repo_close(repo);
6823 return error;
6826 __dead static void
6827 usage_rebase(void)
6829 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
6830 getprogname());
6831 exit(1);
6834 void
6835 trim_logmsg(char *logmsg, int limit)
6837 char *nl;
6838 size_t len;
6840 len = strlen(logmsg);
6841 if (len > limit)
6842 len = limit;
6843 logmsg[len] = '\0';
6844 nl = strchr(logmsg, '\n');
6845 if (nl)
6846 *nl = '\0';
6849 static const struct got_error *
6850 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
6852 const struct got_error *err;
6853 char *logmsg0 = NULL;
6854 const char *s;
6856 err = got_object_commit_get_logmsg(&logmsg0, commit);
6857 if (err)
6858 return err;
6860 s = logmsg0;
6861 while (isspace((unsigned char)s[0]))
6862 s++;
6864 *logmsg = strdup(s);
6865 if (*logmsg == NULL) {
6866 err = got_error_from_errno("strdup");
6867 goto done;
6870 trim_logmsg(*logmsg, limit);
6871 done:
6872 free(logmsg0);
6873 return err;
6876 static const struct got_error *
6877 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
6879 const struct got_error *err;
6880 struct got_commit_object *commit = NULL;
6881 char *id_str = NULL, *logmsg = NULL;
6883 err = got_object_open_as_commit(&commit, repo, id);
6884 if (err)
6885 return err;
6887 err = got_object_id_str(&id_str, id);
6888 if (err)
6889 goto done;
6891 id_str[12] = '\0';
6893 err = get_short_logmsg(&logmsg, 42, commit);
6894 if (err)
6895 goto done;
6897 printf("%s -> merge conflict: %s\n", id_str, logmsg);
6898 done:
6899 free(id_str);
6900 got_object_commit_close(commit);
6901 free(logmsg);
6902 return err;
6905 static const struct got_error *
6906 show_rebase_progress(struct got_commit_object *commit,
6907 struct got_object_id *old_id, struct got_object_id *new_id)
6909 const struct got_error *err;
6910 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
6912 err = got_object_id_str(&old_id_str, old_id);
6913 if (err)
6914 goto done;
6916 if (new_id) {
6917 err = got_object_id_str(&new_id_str, new_id);
6918 if (err)
6919 goto done;
6922 old_id_str[12] = '\0';
6923 if (new_id_str)
6924 new_id_str[12] = '\0';
6926 err = get_short_logmsg(&logmsg, 42, commit);
6927 if (err)
6928 goto done;
6930 printf("%s -> %s: %s\n", old_id_str,
6931 new_id_str ? new_id_str : "no-op change", logmsg);
6932 done:
6933 free(old_id_str);
6934 free(new_id_str);
6935 free(logmsg);
6936 return err;
6939 static const struct got_error *
6940 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
6941 struct got_reference *branch, struct got_reference *new_base_branch,
6942 struct got_reference *tmp_branch, struct got_repository *repo)
6944 printf("Switching work tree to %s\n", got_ref_get_name(branch));
6945 return got_worktree_rebase_complete(worktree, fileindex,
6946 new_base_branch, tmp_branch, branch, repo);
6949 static const struct got_error *
6950 rebase_commit(struct got_pathlist_head *merged_paths,
6951 struct got_worktree *worktree, struct got_fileindex *fileindex,
6952 struct got_reference *tmp_branch,
6953 struct got_object_id *commit_id, struct got_repository *repo)
6955 const struct got_error *error;
6956 struct got_commit_object *commit;
6957 struct got_object_id *new_commit_id;
6959 error = got_object_open_as_commit(&commit, repo, commit_id);
6960 if (error)
6961 return error;
6963 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
6964 worktree, fileindex, tmp_branch, commit, commit_id, repo);
6965 if (error) {
6966 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
6967 goto done;
6968 error = show_rebase_progress(commit, commit_id, NULL);
6969 } else {
6970 error = show_rebase_progress(commit, commit_id, new_commit_id);
6971 free(new_commit_id);
6973 done:
6974 got_object_commit_close(commit);
6975 return error;
6978 struct check_path_prefix_arg {
6979 const char *path_prefix;
6980 size_t len;
6981 int errcode;
6984 static const struct got_error *
6985 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
6986 struct got_blob_object *blob2, struct got_object_id *id1,
6987 struct got_object_id *id2, const char *path1, const char *path2,
6988 mode_t mode1, mode_t mode2, struct got_repository *repo)
6990 struct check_path_prefix_arg *a = arg;
6992 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
6993 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
6994 return got_error(a->errcode);
6996 return NULL;
6999 static const struct got_error *
7000 check_path_prefix(struct got_object_id *parent_id,
7001 struct got_object_id *commit_id, const char *path_prefix,
7002 int errcode, struct got_repository *repo)
7004 const struct got_error *err;
7005 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7006 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7007 struct check_path_prefix_arg cpp_arg;
7009 if (got_path_is_root_dir(path_prefix))
7010 return NULL;
7012 err = got_object_open_as_commit(&commit, repo, commit_id);
7013 if (err)
7014 goto done;
7016 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7017 if (err)
7018 goto done;
7020 err = got_object_open_as_tree(&tree1, repo,
7021 got_object_commit_get_tree_id(parent_commit));
7022 if (err)
7023 goto done;
7025 err = got_object_open_as_tree(&tree2, repo,
7026 got_object_commit_get_tree_id(commit));
7027 if (err)
7028 goto done;
7030 cpp_arg.path_prefix = path_prefix;
7031 while (cpp_arg.path_prefix[0] == '/')
7032 cpp_arg.path_prefix++;
7033 cpp_arg.len = strlen(cpp_arg.path_prefix);
7034 cpp_arg.errcode = errcode;
7035 err = got_diff_tree(tree1, tree2, "", "", repo,
7036 check_path_prefix_in_diff, &cpp_arg, 0);
7037 done:
7038 if (tree1)
7039 got_object_tree_close(tree1);
7040 if (tree2)
7041 got_object_tree_close(tree2);
7042 if (commit)
7043 got_object_commit_close(commit);
7044 if (parent_commit)
7045 got_object_commit_close(parent_commit);
7046 return err;
7049 static const struct got_error *
7050 collect_commits(struct got_object_id_queue *commits,
7051 struct got_object_id *initial_commit_id,
7052 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7053 const char *path_prefix, int path_prefix_errcode,
7054 struct got_repository *repo)
7056 const struct got_error *err = NULL;
7057 struct got_commit_graph *graph = NULL;
7058 struct got_object_id *parent_id = NULL;
7059 struct got_object_qid *qid;
7060 struct got_object_id *commit_id = initial_commit_id;
7062 err = got_commit_graph_open(&graph, "/", 1);
7063 if (err)
7064 return err;
7066 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7067 check_cancelled, NULL);
7068 if (err)
7069 goto done;
7070 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7071 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7072 check_cancelled, NULL);
7073 if (err) {
7074 if (err->code == GOT_ERR_ITER_COMPLETED) {
7075 err = got_error_msg(GOT_ERR_ANCESTRY,
7076 "ran out of commits to rebase before "
7077 "youngest common ancestor commit has "
7078 "been reached?!?");
7080 goto done;
7081 } else {
7082 err = check_path_prefix(parent_id, commit_id,
7083 path_prefix, path_prefix_errcode, repo);
7084 if (err)
7085 goto done;
7087 err = got_object_qid_alloc(&qid, commit_id);
7088 if (err)
7089 goto done;
7090 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
7091 commit_id = parent_id;
7094 done:
7095 got_commit_graph_close(graph);
7096 return err;
7099 static const struct got_error *
7100 cmd_rebase(int argc, char *argv[])
7102 const struct got_error *error = NULL;
7103 struct got_worktree *worktree = NULL;
7104 struct got_repository *repo = NULL;
7105 struct got_fileindex *fileindex = NULL;
7106 char *cwd = NULL;
7107 struct got_reference *branch = NULL;
7108 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
7109 struct got_object_id *commit_id = NULL, *parent_id = NULL;
7110 struct got_object_id *resume_commit_id = NULL;
7111 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
7112 struct got_commit_object *commit = NULL;
7113 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
7114 int histedit_in_progress = 0;
7115 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7116 struct got_object_id_queue commits;
7117 struct got_pathlist_head merged_paths;
7118 const struct got_object_id_queue *parent_ids;
7119 struct got_object_qid *qid, *pid;
7121 SIMPLEQ_INIT(&commits);
7122 TAILQ_INIT(&merged_paths);
7124 while ((ch = getopt(argc, argv, "ac")) != -1) {
7125 switch (ch) {
7126 case 'a':
7127 abort_rebase = 1;
7128 break;
7129 case 'c':
7130 continue_rebase = 1;
7131 break;
7132 default:
7133 usage_rebase();
7134 /* NOTREACHED */
7138 argc -= optind;
7139 argv += optind;
7141 #ifndef PROFILE
7142 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7143 "unveil", NULL) == -1)
7144 err(1, "pledge");
7145 #endif
7146 if (abort_rebase && continue_rebase)
7147 usage_rebase();
7148 else if (abort_rebase || continue_rebase) {
7149 if (argc != 0)
7150 usage_rebase();
7151 } else if (argc != 1)
7152 usage_rebase();
7154 cwd = getcwd(NULL, 0);
7155 if (cwd == NULL) {
7156 error = got_error_from_errno("getcwd");
7157 goto done;
7159 error = got_worktree_open(&worktree, cwd);
7160 if (error) {
7161 if (error->code == GOT_ERR_NOT_WORKTREE)
7162 error = wrap_not_worktree_error(error, "rebase", cwd);
7163 goto done;
7166 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7167 NULL);
7168 if (error != NULL)
7169 goto done;
7171 error = apply_unveil(got_repo_get_path(repo), 0,
7172 got_worktree_get_root_path(worktree));
7173 if (error)
7174 goto done;
7176 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7177 worktree);
7178 if (error)
7179 goto done;
7180 if (histedit_in_progress) {
7181 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7182 goto done;
7185 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7186 if (error)
7187 goto done;
7189 if (abort_rebase) {
7190 struct got_update_progress_arg upa;
7191 if (!rebase_in_progress) {
7192 error = got_error(GOT_ERR_NOT_REBASING);
7193 goto done;
7195 error = got_worktree_rebase_continue(&resume_commit_id,
7196 &new_base_branch, &tmp_branch, &branch, &fileindex,
7197 worktree, repo);
7198 if (error)
7199 goto done;
7200 printf("Switching work tree to %s\n",
7201 got_ref_get_symref_target(new_base_branch));
7202 memset(&upa, 0, sizeof(upa));
7203 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7204 new_base_branch, update_progress, &upa);
7205 if (error)
7206 goto done;
7207 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7208 print_update_progress_stats(&upa);
7209 goto done; /* nothing else to do */
7212 if (continue_rebase) {
7213 if (!rebase_in_progress) {
7214 error = got_error(GOT_ERR_NOT_REBASING);
7215 goto done;
7217 error = got_worktree_rebase_continue(&resume_commit_id,
7218 &new_base_branch, &tmp_branch, &branch, &fileindex,
7219 worktree, repo);
7220 if (error)
7221 goto done;
7223 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7224 resume_commit_id, repo);
7225 if (error)
7226 goto done;
7228 yca_id = got_object_id_dup(resume_commit_id);
7229 if (yca_id == NULL) {
7230 error = got_error_from_errno("got_object_id_dup");
7231 goto done;
7233 } else {
7234 error = got_ref_open(&branch, repo, argv[0], 0);
7235 if (error != NULL)
7236 goto done;
7239 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7240 if (error)
7241 goto done;
7243 if (!continue_rebase) {
7244 struct got_object_id *base_commit_id;
7246 base_commit_id = got_worktree_get_base_commit_id(worktree);
7247 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7248 base_commit_id, branch_head_commit_id, repo,
7249 check_cancelled, NULL);
7250 if (error)
7251 goto done;
7252 if (yca_id == NULL) {
7253 error = got_error_msg(GOT_ERR_ANCESTRY,
7254 "specified branch shares no common ancestry "
7255 "with work tree's branch");
7256 goto done;
7259 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7260 if (error) {
7261 if (error->code != GOT_ERR_ANCESTRY)
7262 goto done;
7263 error = NULL;
7264 } else {
7265 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7266 "specified branch resolves to a commit which "
7267 "is already contained in work tree's branch");
7268 goto done;
7270 error = got_worktree_rebase_prepare(&new_base_branch,
7271 &tmp_branch, &fileindex, worktree, branch, repo);
7272 if (error)
7273 goto done;
7276 commit_id = branch_head_commit_id;
7277 error = got_object_open_as_commit(&commit, repo, commit_id);
7278 if (error)
7279 goto done;
7281 parent_ids = got_object_commit_get_parent_ids(commit);
7282 pid = SIMPLEQ_FIRST(parent_ids);
7283 if (pid == NULL) {
7284 if (!continue_rebase) {
7285 struct got_update_progress_arg upa;
7286 memset(&upa, 0, sizeof(upa));
7287 error = got_worktree_rebase_abort(worktree, fileindex,
7288 repo, new_base_branch, update_progress, &upa);
7289 if (error)
7290 goto done;
7291 printf("Rebase of %s aborted\n",
7292 got_ref_get_name(branch));
7293 print_update_progress_stats(&upa);
7296 error = got_error(GOT_ERR_EMPTY_REBASE);
7297 goto done;
7299 error = collect_commits(&commits, commit_id, pid->id,
7300 yca_id, got_worktree_get_path_prefix(worktree),
7301 GOT_ERR_REBASE_PATH, repo);
7302 got_object_commit_close(commit);
7303 commit = NULL;
7304 if (error)
7305 goto done;
7307 if (SIMPLEQ_EMPTY(&commits)) {
7308 if (continue_rebase) {
7309 error = rebase_complete(worktree, fileindex,
7310 branch, new_base_branch, tmp_branch, repo);
7311 goto done;
7312 } else {
7313 /* Fast-forward the reference of the branch. */
7314 struct got_object_id *new_head_commit_id;
7315 char *id_str;
7316 error = got_ref_resolve(&new_head_commit_id, repo,
7317 new_base_branch);
7318 if (error)
7319 goto done;
7320 error = got_object_id_str(&id_str, new_head_commit_id);
7321 printf("Forwarding %s to commit %s\n",
7322 got_ref_get_name(branch), id_str);
7323 free(id_str);
7324 error = got_ref_change_ref(branch,
7325 new_head_commit_id);
7326 if (error)
7327 goto done;
7331 pid = NULL;
7332 SIMPLEQ_FOREACH(qid, &commits, entry) {
7333 struct got_update_progress_arg upa;
7335 commit_id = qid->id;
7336 parent_id = pid ? pid->id : yca_id;
7337 pid = qid;
7339 memset(&upa, 0, sizeof(upa));
7340 error = got_worktree_rebase_merge_files(&merged_paths,
7341 worktree, fileindex, parent_id, commit_id, repo,
7342 update_progress, &upa, check_cancelled, NULL);
7343 if (error)
7344 goto done;
7346 print_update_progress_stats(&upa);
7347 if (upa.conflicts > 0)
7348 rebase_status = GOT_STATUS_CONFLICT;
7350 if (rebase_status == GOT_STATUS_CONFLICT) {
7351 error = show_rebase_merge_conflict(qid->id, repo);
7352 if (error)
7353 goto done;
7354 got_worktree_rebase_pathlist_free(&merged_paths);
7355 break;
7358 error = rebase_commit(&merged_paths, worktree, fileindex,
7359 tmp_branch, commit_id, repo);
7360 got_worktree_rebase_pathlist_free(&merged_paths);
7361 if (error)
7362 goto done;
7365 if (rebase_status == GOT_STATUS_CONFLICT) {
7366 error = got_worktree_rebase_postpone(worktree, fileindex);
7367 if (error)
7368 goto done;
7369 error = got_error_msg(GOT_ERR_CONFLICTS,
7370 "conflicts must be resolved before rebasing can continue");
7371 } else
7372 error = rebase_complete(worktree, fileindex, branch,
7373 new_base_branch, tmp_branch, repo);
7374 done:
7375 got_object_id_queue_free(&commits);
7376 free(branch_head_commit_id);
7377 free(resume_commit_id);
7378 free(yca_id);
7379 if (commit)
7380 got_object_commit_close(commit);
7381 if (branch)
7382 got_ref_close(branch);
7383 if (new_base_branch)
7384 got_ref_close(new_base_branch);
7385 if (tmp_branch)
7386 got_ref_close(tmp_branch);
7387 if (worktree)
7388 got_worktree_close(worktree);
7389 if (repo)
7390 got_repo_close(repo);
7391 return error;
7394 __dead static void
7395 usage_histedit(void)
7397 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
7398 getprogname());
7399 exit(1);
7402 #define GOT_HISTEDIT_PICK 'p'
7403 #define GOT_HISTEDIT_EDIT 'e'
7404 #define GOT_HISTEDIT_FOLD 'f'
7405 #define GOT_HISTEDIT_DROP 'd'
7406 #define GOT_HISTEDIT_MESG 'm'
7408 static struct got_histedit_cmd {
7409 unsigned char code;
7410 const char *name;
7411 const char *desc;
7412 } got_histedit_cmds[] = {
7413 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7414 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7415 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7416 "be used" },
7417 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7418 { GOT_HISTEDIT_MESG, "mesg",
7419 "single-line log message for commit above (open editor if empty)" },
7422 struct got_histedit_list_entry {
7423 TAILQ_ENTRY(got_histedit_list_entry) entry;
7424 struct got_object_id *commit_id;
7425 const struct got_histedit_cmd *cmd;
7426 char *logmsg;
7428 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7430 static const struct got_error *
7431 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7432 FILE *f, struct got_repository *repo)
7434 const struct got_error *err = NULL;
7435 char *logmsg = NULL, *id_str = NULL;
7436 struct got_commit_object *commit = NULL;
7437 int n;
7439 err = got_object_open_as_commit(&commit, repo, commit_id);
7440 if (err)
7441 goto done;
7443 err = get_short_logmsg(&logmsg, 34, commit);
7444 if (err)
7445 goto done;
7447 err = got_object_id_str(&id_str, commit_id);
7448 if (err)
7449 goto done;
7451 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7452 if (n < 0)
7453 err = got_ferror(f, GOT_ERR_IO);
7454 done:
7455 if (commit)
7456 got_object_commit_close(commit);
7457 free(id_str);
7458 free(logmsg);
7459 return err;
7462 static const struct got_error *
7463 histedit_write_commit_list(struct got_object_id_queue *commits,
7464 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7466 const struct got_error *err = NULL;
7467 struct got_object_qid *qid;
7469 if (SIMPLEQ_EMPTY(commits))
7470 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7472 SIMPLEQ_FOREACH(qid, commits, entry) {
7473 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7474 f, repo);
7475 if (err)
7476 break;
7477 if (edit_logmsg_only) {
7478 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7479 if (n < 0) {
7480 err = got_ferror(f, GOT_ERR_IO);
7481 break;
7486 return err;
7489 static const struct got_error *
7490 write_cmd_list(FILE *f, const char *branch_name,
7491 struct got_object_id_queue *commits)
7493 const struct got_error *err = NULL;
7494 int n, i;
7495 char *id_str;
7496 struct got_object_qid *qid;
7498 qid = SIMPLEQ_FIRST(commits);
7499 err = got_object_id_str(&id_str, qid->id);
7500 if (err)
7501 return err;
7503 n = fprintf(f,
7504 "# Editing the history of branch '%s' starting at\n"
7505 "# commit %s\n"
7506 "# Commits will be processed in order from top to "
7507 "bottom of this file.\n", branch_name, id_str);
7508 if (n < 0) {
7509 err = got_ferror(f, GOT_ERR_IO);
7510 goto done;
7513 n = fprintf(f, "# Available histedit commands:\n");
7514 if (n < 0) {
7515 err = got_ferror(f, GOT_ERR_IO);
7516 goto done;
7519 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7520 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7521 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7522 cmd->desc);
7523 if (n < 0) {
7524 err = got_ferror(f, GOT_ERR_IO);
7525 break;
7528 done:
7529 free(id_str);
7530 return err;
7533 static const struct got_error *
7534 histedit_syntax_error(int lineno)
7536 static char msg[42];
7537 int ret;
7539 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7540 lineno);
7541 if (ret == -1 || ret >= sizeof(msg))
7542 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7544 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7547 static const struct got_error *
7548 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7549 char *logmsg, struct got_repository *repo)
7551 const struct got_error *err;
7552 struct got_commit_object *folded_commit = NULL;
7553 char *id_str, *folded_logmsg = NULL;
7555 err = got_object_id_str(&id_str, hle->commit_id);
7556 if (err)
7557 return err;
7559 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7560 if (err)
7561 goto done;
7563 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7564 if (err)
7565 goto done;
7566 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7567 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7568 folded_logmsg) == -1) {
7569 err = got_error_from_errno("asprintf");
7571 done:
7572 if (folded_commit)
7573 got_object_commit_close(folded_commit);
7574 free(id_str);
7575 free(folded_logmsg);
7576 return err;
7579 static struct got_histedit_list_entry *
7580 get_folded_commits(struct got_histedit_list_entry *hle)
7582 struct got_histedit_list_entry *prev, *folded = NULL;
7584 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7585 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7586 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7587 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7588 folded = prev;
7589 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7592 return folded;
7595 static const struct got_error *
7596 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7597 struct got_repository *repo)
7599 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7600 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7601 const struct got_error *err = NULL;
7602 struct got_commit_object *commit = NULL;
7603 int fd;
7604 struct got_histedit_list_entry *folded = NULL;
7606 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7607 if (err)
7608 return err;
7610 folded = get_folded_commits(hle);
7611 if (folded) {
7612 while (folded != hle) {
7613 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7614 folded = TAILQ_NEXT(folded, entry);
7615 continue;
7617 err = append_folded_commit_msg(&new_msg, folded,
7618 logmsg, repo);
7619 if (err)
7620 goto done;
7621 free(logmsg);
7622 logmsg = new_msg;
7623 folded = TAILQ_NEXT(folded, entry);
7627 err = got_object_id_str(&id_str, hle->commit_id);
7628 if (err)
7629 goto done;
7630 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7631 if (err)
7632 goto done;
7633 if (asprintf(&new_msg,
7634 "%s\n# original log message of commit %s: %s",
7635 logmsg ? logmsg : "", id_str, orig_logmsg) == -1) {
7636 err = got_error_from_errno("asprintf");
7637 goto done;
7639 free(logmsg);
7640 logmsg = new_msg;
7642 err = got_object_id_str(&id_str, hle->commit_id);
7643 if (err)
7644 goto done;
7646 err = got_opentemp_named_fd(&logmsg_path, &fd,
7647 GOT_TMPDIR_STR "/got-logmsg");
7648 if (err)
7649 goto done;
7651 dprintf(fd, logmsg);
7652 close(fd);
7654 err = get_editor(&editor);
7655 if (err)
7656 goto done;
7658 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
7659 if (err) {
7660 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
7661 goto done;
7662 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
7664 done:
7665 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
7666 err = got_error_from_errno2("unlink", logmsg_path);
7667 free(logmsg_path);
7668 free(logmsg);
7669 free(orig_logmsg);
7670 free(editor);
7671 if (commit)
7672 got_object_commit_close(commit);
7673 return err;
7676 static const struct got_error *
7677 histedit_parse_list(struct got_histedit_list *histedit_cmds,
7678 FILE *f, struct got_repository *repo)
7680 const struct got_error *err = NULL;
7681 char *line = NULL, *p, *end;
7682 size_t size;
7683 ssize_t len;
7684 int lineno = 0, i;
7685 const struct got_histedit_cmd *cmd;
7686 struct got_object_id *commit_id = NULL;
7687 struct got_histedit_list_entry *hle = NULL;
7689 for (;;) {
7690 len = getline(&line, &size, f);
7691 if (len == -1) {
7692 const struct got_error *getline_err;
7693 if (feof(f))
7694 break;
7695 getline_err = got_error_from_errno("getline");
7696 err = got_ferror(f, getline_err->code);
7697 break;
7699 lineno++;
7700 p = line;
7701 while (isspace((unsigned char)p[0]))
7702 p++;
7703 if (p[0] == '#' || p[0] == '\0') {
7704 free(line);
7705 line = NULL;
7706 continue;
7708 cmd = NULL;
7709 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7710 cmd = &got_histedit_cmds[i];
7711 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
7712 isspace((unsigned char)p[strlen(cmd->name)])) {
7713 p += strlen(cmd->name);
7714 break;
7716 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
7717 p++;
7718 break;
7721 if (i == nitems(got_histedit_cmds)) {
7722 err = histedit_syntax_error(lineno);
7723 break;
7725 while (isspace((unsigned char)p[0]))
7726 p++;
7727 if (cmd->code == GOT_HISTEDIT_MESG) {
7728 if (hle == NULL || hle->logmsg != NULL) {
7729 err = got_error(GOT_ERR_HISTEDIT_CMD);
7730 break;
7732 if (p[0] == '\0') {
7733 err = histedit_edit_logmsg(hle, repo);
7734 if (err)
7735 break;
7736 } else {
7737 hle->logmsg = strdup(p);
7738 if (hle->logmsg == NULL) {
7739 err = got_error_from_errno("strdup");
7740 break;
7743 free(line);
7744 line = NULL;
7745 continue;
7746 } else {
7747 end = p;
7748 while (end[0] && !isspace((unsigned char)end[0]))
7749 end++;
7750 *end = '\0';
7752 err = got_object_resolve_id_str(&commit_id, repo, p);
7753 if (err) {
7754 /* override error code */
7755 err = histedit_syntax_error(lineno);
7756 break;
7759 hle = malloc(sizeof(*hle));
7760 if (hle == NULL) {
7761 err = got_error_from_errno("malloc");
7762 break;
7764 hle->cmd = cmd;
7765 hle->commit_id = commit_id;
7766 hle->logmsg = NULL;
7767 commit_id = NULL;
7768 free(line);
7769 line = NULL;
7770 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
7773 free(line);
7774 free(commit_id);
7775 return err;
7778 static const struct got_error *
7779 histedit_check_script(struct got_histedit_list *histedit_cmds,
7780 struct got_object_id_queue *commits, struct got_repository *repo)
7782 const struct got_error *err = NULL;
7783 struct got_object_qid *qid;
7784 struct got_histedit_list_entry *hle;
7785 static char msg[92];
7786 char *id_str;
7788 if (TAILQ_EMPTY(histedit_cmds))
7789 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
7790 "histedit script contains no commands");
7791 if (SIMPLEQ_EMPTY(commits))
7792 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7794 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7795 struct got_histedit_list_entry *hle2;
7796 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
7797 if (hle == hle2)
7798 continue;
7799 if (got_object_id_cmp(hle->commit_id,
7800 hle2->commit_id) != 0)
7801 continue;
7802 err = got_object_id_str(&id_str, hle->commit_id);
7803 if (err)
7804 return err;
7805 snprintf(msg, sizeof(msg), "commit %s is listed "
7806 "more than once in histedit script", id_str);
7807 free(id_str);
7808 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7812 SIMPLEQ_FOREACH(qid, commits, entry) {
7813 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7814 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
7815 break;
7817 if (hle == NULL) {
7818 err = got_object_id_str(&id_str, qid->id);
7819 if (err)
7820 return err;
7821 snprintf(msg, sizeof(msg),
7822 "commit %s missing from histedit script", id_str);
7823 free(id_str);
7824 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7828 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
7829 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
7830 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
7831 "last commit in histedit script cannot be folded");
7833 return NULL;
7836 static const struct got_error *
7837 histedit_run_editor(struct got_histedit_list *histedit_cmds,
7838 const char *path, struct got_object_id_queue *commits,
7839 struct got_repository *repo)
7841 const struct got_error *err = NULL;
7842 char *editor;
7843 FILE *f = NULL;
7845 err = get_editor(&editor);
7846 if (err)
7847 return err;
7849 if (spawn_editor(editor, path) == -1) {
7850 err = got_error_from_errno("failed spawning editor");
7851 goto done;
7854 f = fopen(path, "r");
7855 if (f == NULL) {
7856 err = got_error_from_errno("fopen");
7857 goto done;
7859 err = histedit_parse_list(histedit_cmds, f, repo);
7860 if (err)
7861 goto done;
7863 err = histedit_check_script(histedit_cmds, commits, repo);
7864 done:
7865 if (f && fclose(f) != 0 && err == NULL)
7866 err = got_error_from_errno("fclose");
7867 free(editor);
7868 return err;
7871 static const struct got_error *
7872 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
7873 struct got_object_id_queue *, const char *, const char *,
7874 struct got_repository *);
7876 static const struct got_error *
7877 histedit_edit_script(struct got_histedit_list *histedit_cmds,
7878 struct got_object_id_queue *commits, const char *branch_name,
7879 int edit_logmsg_only, struct got_repository *repo)
7881 const struct got_error *err;
7882 FILE *f = NULL;
7883 char *path = NULL;
7885 err = got_opentemp_named(&path, &f, "got-histedit");
7886 if (err)
7887 return err;
7889 err = write_cmd_list(f, branch_name, commits);
7890 if (err)
7891 goto done;
7893 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
7894 if (err)
7895 goto done;
7897 if (edit_logmsg_only) {
7898 rewind(f);
7899 err = histedit_parse_list(histedit_cmds, f, repo);
7900 } else {
7901 if (fclose(f) != 0) {
7902 err = got_error_from_errno("fclose");
7903 goto done;
7905 f = NULL;
7906 err = histedit_run_editor(histedit_cmds, path, commits, repo);
7907 if (err) {
7908 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7909 err->code != GOT_ERR_HISTEDIT_CMD)
7910 goto done;
7911 err = histedit_edit_list_retry(histedit_cmds, err,
7912 commits, path, branch_name, repo);
7915 done:
7916 if (f && fclose(f) != 0 && err == NULL)
7917 err = got_error_from_errno("fclose");
7918 if (path && unlink(path) != 0 && err == NULL)
7919 err = got_error_from_errno2("unlink", path);
7920 free(path);
7921 return err;
7924 static const struct got_error *
7925 histedit_save_list(struct got_histedit_list *histedit_cmds,
7926 struct got_worktree *worktree, struct got_repository *repo)
7928 const struct got_error *err = NULL;
7929 char *path = NULL;
7930 FILE *f = NULL;
7931 struct got_histedit_list_entry *hle;
7932 struct got_commit_object *commit = NULL;
7934 err = got_worktree_get_histedit_script_path(&path, worktree);
7935 if (err)
7936 return err;
7938 f = fopen(path, "w");
7939 if (f == NULL) {
7940 err = got_error_from_errno2("fopen", path);
7941 goto done;
7943 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7944 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
7945 repo);
7946 if (err)
7947 break;
7949 if (hle->logmsg) {
7950 int n = fprintf(f, "%c %s\n",
7951 GOT_HISTEDIT_MESG, hle->logmsg);
7952 if (n < 0) {
7953 err = got_ferror(f, GOT_ERR_IO);
7954 break;
7958 done:
7959 if (f && fclose(f) != 0 && err == NULL)
7960 err = got_error_from_errno("fclose");
7961 free(path);
7962 if (commit)
7963 got_object_commit_close(commit);
7964 return err;
7967 void
7968 histedit_free_list(struct got_histedit_list *histedit_cmds)
7970 struct got_histedit_list_entry *hle;
7972 while ((hle = TAILQ_FIRST(histedit_cmds))) {
7973 TAILQ_REMOVE(histedit_cmds, hle, entry);
7974 free(hle);
7978 static const struct got_error *
7979 histedit_load_list(struct got_histedit_list *histedit_cmds,
7980 const char *path, struct got_repository *repo)
7982 const struct got_error *err = NULL;
7983 FILE *f = NULL;
7985 f = fopen(path, "r");
7986 if (f == NULL) {
7987 err = got_error_from_errno2("fopen", path);
7988 goto done;
7991 err = histedit_parse_list(histedit_cmds, f, repo);
7992 done:
7993 if (f && fclose(f) != 0 && err == NULL)
7994 err = got_error_from_errno("fclose");
7995 return err;
7998 static const struct got_error *
7999 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
8000 const struct got_error *edit_err, struct got_object_id_queue *commits,
8001 const char *path, const char *branch_name, struct got_repository *repo)
8003 const struct got_error *err = NULL, *prev_err = edit_err;
8004 int resp = ' ';
8006 while (resp != 'c' && resp != 'r' && resp != 'a') {
8007 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
8008 "or (a)bort: ", getprogname(), prev_err->msg);
8009 resp = getchar();
8010 if (resp == '\n')
8011 resp = getchar();
8012 if (resp == 'c') {
8013 histedit_free_list(histedit_cmds);
8014 err = histedit_run_editor(histedit_cmds, path, commits,
8015 repo);
8016 if (err) {
8017 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8018 err->code != GOT_ERR_HISTEDIT_CMD)
8019 break;
8020 prev_err = err;
8021 resp = ' ';
8022 continue;
8024 break;
8025 } else if (resp == 'r') {
8026 histedit_free_list(histedit_cmds);
8027 err = histedit_edit_script(histedit_cmds,
8028 commits, branch_name, 0, repo);
8029 if (err) {
8030 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8031 err->code != GOT_ERR_HISTEDIT_CMD)
8032 break;
8033 prev_err = err;
8034 resp = ' ';
8035 continue;
8037 break;
8038 } else if (resp == 'a') {
8039 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
8040 break;
8041 } else
8042 printf("invalid response '%c'\n", resp);
8045 return err;
8048 static const struct got_error *
8049 histedit_complete(struct got_worktree *worktree,
8050 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
8051 struct got_reference *branch, struct got_repository *repo)
8053 printf("Switching work tree to %s\n",
8054 got_ref_get_symref_target(branch));
8055 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
8056 branch, repo);
8059 static const struct got_error *
8060 show_histedit_progress(struct got_commit_object *commit,
8061 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
8063 const struct got_error *err;
8064 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8066 err = got_object_id_str(&old_id_str, hle->commit_id);
8067 if (err)
8068 goto done;
8070 if (new_id) {
8071 err = got_object_id_str(&new_id_str, new_id);
8072 if (err)
8073 goto done;
8076 old_id_str[12] = '\0';
8077 if (new_id_str)
8078 new_id_str[12] = '\0';
8080 if (hle->logmsg) {
8081 logmsg = strdup(hle->logmsg);
8082 if (logmsg == NULL) {
8083 err = got_error_from_errno("strdup");
8084 goto done;
8086 trim_logmsg(logmsg, 42);
8087 } else {
8088 err = get_short_logmsg(&logmsg, 42, commit);
8089 if (err)
8090 goto done;
8093 switch (hle->cmd->code) {
8094 case GOT_HISTEDIT_PICK:
8095 case GOT_HISTEDIT_EDIT:
8096 printf("%s -> %s: %s\n", old_id_str,
8097 new_id_str ? new_id_str : "no-op change", logmsg);
8098 break;
8099 case GOT_HISTEDIT_DROP:
8100 case GOT_HISTEDIT_FOLD:
8101 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
8102 logmsg);
8103 break;
8104 default:
8105 break;
8107 done:
8108 free(old_id_str);
8109 free(new_id_str);
8110 return err;
8113 static const struct got_error *
8114 histedit_commit(struct got_pathlist_head *merged_paths,
8115 struct got_worktree *worktree, struct got_fileindex *fileindex,
8116 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
8117 struct got_repository *repo)
8119 const struct got_error *err;
8120 struct got_commit_object *commit;
8121 struct got_object_id *new_commit_id;
8123 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
8124 && hle->logmsg == NULL) {
8125 err = histedit_edit_logmsg(hle, repo);
8126 if (err)
8127 return err;
8130 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8131 if (err)
8132 return err;
8134 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
8135 worktree, fileindex, tmp_branch, commit, hle->commit_id,
8136 hle->logmsg, repo);
8137 if (err) {
8138 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
8139 goto done;
8140 err = show_histedit_progress(commit, hle, NULL);
8141 } else {
8142 err = show_histedit_progress(commit, hle, new_commit_id);
8143 free(new_commit_id);
8145 done:
8146 got_object_commit_close(commit);
8147 return err;
8150 static const struct got_error *
8151 histedit_skip_commit(struct got_histedit_list_entry *hle,
8152 struct got_worktree *worktree, struct got_repository *repo)
8154 const struct got_error *error;
8155 struct got_commit_object *commit;
8157 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
8158 repo);
8159 if (error)
8160 return error;
8162 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
8163 if (error)
8164 return error;
8166 error = show_histedit_progress(commit, hle, NULL);
8167 got_object_commit_close(commit);
8168 return error;
8171 static const struct got_error *
8172 check_local_changes(void *arg, unsigned char status,
8173 unsigned char staged_status, const char *path,
8174 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8175 struct got_object_id *commit_id, int dirfd, const char *de_name)
8177 int *have_local_changes = arg;
8179 switch (status) {
8180 case GOT_STATUS_ADD:
8181 case GOT_STATUS_DELETE:
8182 case GOT_STATUS_MODIFY:
8183 case GOT_STATUS_CONFLICT:
8184 *have_local_changes = 1;
8185 return got_error(GOT_ERR_CANCELLED);
8186 default:
8187 break;
8190 switch (staged_status) {
8191 case GOT_STATUS_ADD:
8192 case GOT_STATUS_DELETE:
8193 case GOT_STATUS_MODIFY:
8194 *have_local_changes = 1;
8195 return got_error(GOT_ERR_CANCELLED);
8196 default:
8197 break;
8200 return NULL;
8203 static const struct got_error *
8204 cmd_histedit(int argc, char *argv[])
8206 const struct got_error *error = NULL;
8207 struct got_worktree *worktree = NULL;
8208 struct got_fileindex *fileindex = NULL;
8209 struct got_repository *repo = NULL;
8210 char *cwd = NULL;
8211 struct got_reference *branch = NULL;
8212 struct got_reference *tmp_branch = NULL;
8213 struct got_object_id *resume_commit_id = NULL;
8214 struct got_object_id *base_commit_id = NULL;
8215 struct got_object_id *head_commit_id = NULL;
8216 struct got_commit_object *commit = NULL;
8217 int ch, rebase_in_progress = 0;
8218 struct got_update_progress_arg upa;
8219 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8220 int edit_logmsg_only = 0;
8221 const char *edit_script_path = NULL;
8222 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8223 struct got_object_id_queue commits;
8224 struct got_pathlist_head merged_paths;
8225 const struct got_object_id_queue *parent_ids;
8226 struct got_object_qid *pid;
8227 struct got_histedit_list histedit_cmds;
8228 struct got_histedit_list_entry *hle;
8230 SIMPLEQ_INIT(&commits);
8231 TAILQ_INIT(&histedit_cmds);
8232 TAILQ_INIT(&merged_paths);
8233 memset(&upa, 0, sizeof(upa));
8235 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
8236 switch (ch) {
8237 case 'a':
8238 abort_edit = 1;
8239 break;
8240 case 'c':
8241 continue_edit = 1;
8242 break;
8243 case 'F':
8244 edit_script_path = optarg;
8245 break;
8246 case 'm':
8247 edit_logmsg_only = 1;
8248 break;
8249 default:
8250 usage_histedit();
8251 /* NOTREACHED */
8255 argc -= optind;
8256 argv += optind;
8258 #ifndef PROFILE
8259 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8260 "unveil", NULL) == -1)
8261 err(1, "pledge");
8262 #endif
8263 if (abort_edit && continue_edit)
8264 errx(1, "histedit's -a and -c options are mutually exclusive");
8265 if (edit_script_path && edit_logmsg_only)
8266 errx(1, "histedit's -F and -m options are mutually exclusive");
8267 if (abort_edit && edit_logmsg_only)
8268 errx(1, "histedit's -a and -m options are mutually exclusive");
8269 if (continue_edit && edit_logmsg_only)
8270 errx(1, "histedit's -c and -m options are mutually exclusive");
8271 if (argc != 0)
8272 usage_histedit();
8275 * This command cannot apply unveil(2) in all cases because the
8276 * user may choose to run an editor to edit the histedit script
8277 * and to edit individual commit log messages.
8278 * unveil(2) traverses exec(2); if an editor is used we have to
8279 * apply unveil after edit script and log messages have been written.
8280 * XXX TODO: Make use of unveil(2) where possible.
8283 cwd = getcwd(NULL, 0);
8284 if (cwd == NULL) {
8285 error = got_error_from_errno("getcwd");
8286 goto done;
8288 error = got_worktree_open(&worktree, cwd);
8289 if (error) {
8290 if (error->code == GOT_ERR_NOT_WORKTREE)
8291 error = wrap_not_worktree_error(error, "histedit", cwd);
8292 goto done;
8295 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8296 NULL);
8297 if (error != NULL)
8298 goto done;
8300 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8301 if (error)
8302 goto done;
8303 if (rebase_in_progress) {
8304 error = got_error(GOT_ERR_REBASING);
8305 goto done;
8308 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8309 if (error)
8310 goto done;
8312 if (edit_in_progress && edit_logmsg_only) {
8313 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8314 "histedit operation is in progress in this "
8315 "work tree and must be continued or aborted "
8316 "before the -m option can be used");
8317 goto done;
8320 if (edit_in_progress && abort_edit) {
8321 error = got_worktree_histedit_continue(&resume_commit_id,
8322 &tmp_branch, &branch, &base_commit_id, &fileindex,
8323 worktree, repo);
8324 if (error)
8325 goto done;
8326 printf("Switching work tree to %s\n",
8327 got_ref_get_symref_target(branch));
8328 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8329 branch, base_commit_id, update_progress, &upa);
8330 if (error)
8331 goto done;
8332 printf("Histedit of %s aborted\n",
8333 got_ref_get_symref_target(branch));
8334 print_update_progress_stats(&upa);
8335 goto done; /* nothing else to do */
8336 } else if (abort_edit) {
8337 error = got_error(GOT_ERR_NOT_HISTEDIT);
8338 goto done;
8341 if (continue_edit) {
8342 char *path;
8344 if (!edit_in_progress) {
8345 error = got_error(GOT_ERR_NOT_HISTEDIT);
8346 goto done;
8349 error = got_worktree_get_histedit_script_path(&path, worktree);
8350 if (error)
8351 goto done;
8353 error = histedit_load_list(&histedit_cmds, path, repo);
8354 free(path);
8355 if (error)
8356 goto done;
8358 error = got_worktree_histedit_continue(&resume_commit_id,
8359 &tmp_branch, &branch, &base_commit_id, &fileindex,
8360 worktree, repo);
8361 if (error)
8362 goto done;
8364 error = got_ref_resolve(&head_commit_id, repo, branch);
8365 if (error)
8366 goto done;
8368 error = got_object_open_as_commit(&commit, repo,
8369 head_commit_id);
8370 if (error)
8371 goto done;
8372 parent_ids = got_object_commit_get_parent_ids(commit);
8373 pid = SIMPLEQ_FIRST(parent_ids);
8374 if (pid == NULL) {
8375 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8376 goto done;
8378 error = collect_commits(&commits, head_commit_id, pid->id,
8379 base_commit_id, got_worktree_get_path_prefix(worktree),
8380 GOT_ERR_HISTEDIT_PATH, repo);
8381 got_object_commit_close(commit);
8382 commit = NULL;
8383 if (error)
8384 goto done;
8385 } else {
8386 if (edit_in_progress) {
8387 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8388 goto done;
8391 error = got_ref_open(&branch, repo,
8392 got_worktree_get_head_ref_name(worktree), 0);
8393 if (error != NULL)
8394 goto done;
8396 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8397 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8398 "will not edit commit history of a branch outside "
8399 "the \"refs/heads/\" reference namespace");
8400 goto done;
8403 error = got_ref_resolve(&head_commit_id, repo, branch);
8404 got_ref_close(branch);
8405 branch = NULL;
8406 if (error)
8407 goto done;
8409 error = got_object_open_as_commit(&commit, repo,
8410 head_commit_id);
8411 if (error)
8412 goto done;
8413 parent_ids = got_object_commit_get_parent_ids(commit);
8414 pid = SIMPLEQ_FIRST(parent_ids);
8415 if (pid == NULL) {
8416 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8417 goto done;
8419 error = collect_commits(&commits, head_commit_id, pid->id,
8420 got_worktree_get_base_commit_id(worktree),
8421 got_worktree_get_path_prefix(worktree),
8422 GOT_ERR_HISTEDIT_PATH, repo);
8423 got_object_commit_close(commit);
8424 commit = NULL;
8425 if (error)
8426 goto done;
8428 if (SIMPLEQ_EMPTY(&commits)) {
8429 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8430 goto done;
8433 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8434 &base_commit_id, &fileindex, worktree, repo);
8435 if (error)
8436 goto done;
8438 if (edit_script_path) {
8439 error = histedit_load_list(&histedit_cmds,
8440 edit_script_path, repo);
8441 if (error) {
8442 got_worktree_histedit_abort(worktree, fileindex,
8443 repo, branch, base_commit_id,
8444 update_progress, &upa);
8445 print_update_progress_stats(&upa);
8446 goto done;
8448 } else {
8449 const char *branch_name;
8450 branch_name = got_ref_get_symref_target(branch);
8451 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8452 branch_name += 11;
8453 error = histedit_edit_script(&histedit_cmds, &commits,
8454 branch_name, edit_logmsg_only, repo);
8455 if (error) {
8456 got_worktree_histedit_abort(worktree, fileindex,
8457 repo, branch, base_commit_id,
8458 update_progress, &upa);
8459 print_update_progress_stats(&upa);
8460 goto done;
8465 error = histedit_save_list(&histedit_cmds, worktree,
8466 repo);
8467 if (error) {
8468 got_worktree_histedit_abort(worktree, fileindex,
8469 repo, branch, base_commit_id,
8470 update_progress, &upa);
8471 print_update_progress_stats(&upa);
8472 goto done;
8477 error = histedit_check_script(&histedit_cmds, &commits, repo);
8478 if (error)
8479 goto done;
8481 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8482 if (resume_commit_id) {
8483 if (got_object_id_cmp(hle->commit_id,
8484 resume_commit_id) != 0)
8485 continue;
8487 resume_commit_id = NULL;
8488 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8489 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8490 error = histedit_skip_commit(hle, worktree,
8491 repo);
8492 if (error)
8493 goto done;
8494 } else {
8495 struct got_pathlist_head paths;
8496 int have_changes = 0;
8498 TAILQ_INIT(&paths);
8499 error = got_pathlist_append(&paths, "", NULL);
8500 if (error)
8501 goto done;
8502 error = got_worktree_status(worktree, &paths,
8503 repo, check_local_changes, &have_changes,
8504 check_cancelled, NULL);
8505 got_pathlist_free(&paths);
8506 if (error) {
8507 if (error->code != GOT_ERR_CANCELLED)
8508 goto done;
8509 if (sigint_received || sigpipe_received)
8510 goto done;
8512 if (have_changes) {
8513 error = histedit_commit(NULL, worktree,
8514 fileindex, tmp_branch, hle, repo);
8515 if (error)
8516 goto done;
8517 } else {
8518 error = got_object_open_as_commit(
8519 &commit, repo, hle->commit_id);
8520 if (error)
8521 goto done;
8522 error = show_histedit_progress(commit,
8523 hle, NULL);
8524 got_object_commit_close(commit);
8525 commit = NULL;
8526 if (error)
8527 goto done;
8530 continue;
8533 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8534 error = histedit_skip_commit(hle, worktree, repo);
8535 if (error)
8536 goto done;
8537 continue;
8540 error = got_object_open_as_commit(&commit, repo,
8541 hle->commit_id);
8542 if (error)
8543 goto done;
8544 parent_ids = got_object_commit_get_parent_ids(commit);
8545 pid = SIMPLEQ_FIRST(parent_ids);
8547 error = got_worktree_histedit_merge_files(&merged_paths,
8548 worktree, fileindex, pid->id, hle->commit_id, repo,
8549 update_progress, &upa, check_cancelled, NULL);
8550 if (error)
8551 goto done;
8552 got_object_commit_close(commit);
8553 commit = NULL;
8555 print_update_progress_stats(&upa);
8556 if (upa.conflicts > 0)
8557 rebase_status = GOT_STATUS_CONFLICT;
8559 if (rebase_status == GOT_STATUS_CONFLICT) {
8560 error = show_rebase_merge_conflict(hle->commit_id,
8561 repo);
8562 if (error)
8563 goto done;
8564 got_worktree_rebase_pathlist_free(&merged_paths);
8565 break;
8568 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8569 char *id_str;
8570 error = got_object_id_str(&id_str, hle->commit_id);
8571 if (error)
8572 goto done;
8573 printf("Stopping histedit for amending commit %s\n",
8574 id_str);
8575 free(id_str);
8576 got_worktree_rebase_pathlist_free(&merged_paths);
8577 error = got_worktree_histedit_postpone(worktree,
8578 fileindex);
8579 goto done;
8582 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8583 error = histedit_skip_commit(hle, worktree, repo);
8584 if (error)
8585 goto done;
8586 continue;
8589 error = histedit_commit(&merged_paths, worktree, fileindex,
8590 tmp_branch, hle, repo);
8591 got_worktree_rebase_pathlist_free(&merged_paths);
8592 if (error)
8593 goto done;
8596 if (rebase_status == GOT_STATUS_CONFLICT) {
8597 error = got_worktree_histedit_postpone(worktree, fileindex);
8598 if (error)
8599 goto done;
8600 error = got_error_msg(GOT_ERR_CONFLICTS,
8601 "conflicts must be resolved before histedit can continue");
8602 } else
8603 error = histedit_complete(worktree, fileindex, tmp_branch,
8604 branch, repo);
8605 done:
8606 got_object_id_queue_free(&commits);
8607 histedit_free_list(&histedit_cmds);
8608 free(head_commit_id);
8609 free(base_commit_id);
8610 free(resume_commit_id);
8611 if (commit)
8612 got_object_commit_close(commit);
8613 if (branch)
8614 got_ref_close(branch);
8615 if (tmp_branch)
8616 got_ref_close(tmp_branch);
8617 if (worktree)
8618 got_worktree_close(worktree);
8619 if (repo)
8620 got_repo_close(repo);
8621 return error;
8624 __dead static void
8625 usage_integrate(void)
8627 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
8628 exit(1);
8631 static const struct got_error *
8632 cmd_integrate(int argc, char *argv[])
8634 const struct got_error *error = NULL;
8635 struct got_repository *repo = NULL;
8636 struct got_worktree *worktree = NULL;
8637 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
8638 const char *branch_arg = NULL;
8639 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
8640 struct got_fileindex *fileindex = NULL;
8641 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
8642 int ch;
8643 struct got_update_progress_arg upa;
8645 while ((ch = getopt(argc, argv, "")) != -1) {
8646 switch (ch) {
8647 default:
8648 usage_integrate();
8649 /* NOTREACHED */
8653 argc -= optind;
8654 argv += optind;
8656 if (argc != 1)
8657 usage_integrate();
8658 branch_arg = argv[0];
8660 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8661 "unveil", NULL) == -1)
8662 err(1, "pledge");
8664 cwd = getcwd(NULL, 0);
8665 if (cwd == NULL) {
8666 error = got_error_from_errno("getcwd");
8667 goto done;
8670 error = got_worktree_open(&worktree, cwd);
8671 if (error) {
8672 if (error->code == GOT_ERR_NOT_WORKTREE)
8673 error = wrap_not_worktree_error(error, "integrate",
8674 cwd);
8675 goto done;
8678 error = check_rebase_or_histedit_in_progress(worktree);
8679 if (error)
8680 goto done;
8682 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8683 NULL);
8684 if (error != NULL)
8685 goto done;
8687 error = apply_unveil(got_repo_get_path(repo), 0,
8688 got_worktree_get_root_path(worktree));
8689 if (error)
8690 goto done;
8692 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
8693 error = got_error_from_errno("asprintf");
8694 goto done;
8697 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
8698 &base_branch_ref, worktree, refname, repo);
8699 if (error)
8700 goto done;
8702 refname = strdup(got_ref_get_name(branch_ref));
8703 if (refname == NULL) {
8704 error = got_error_from_errno("strdup");
8705 got_worktree_integrate_abort(worktree, fileindex, repo,
8706 branch_ref, base_branch_ref);
8707 goto done;
8709 base_refname = strdup(got_ref_get_name(base_branch_ref));
8710 if (base_refname == NULL) {
8711 error = got_error_from_errno("strdup");
8712 got_worktree_integrate_abort(worktree, fileindex, repo,
8713 branch_ref, base_branch_ref);
8714 goto done;
8717 error = got_ref_resolve(&commit_id, repo, branch_ref);
8718 if (error)
8719 goto done;
8721 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
8722 if (error)
8723 goto done;
8725 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
8726 error = got_error_msg(GOT_ERR_SAME_BRANCH,
8727 "specified branch has already been integrated");
8728 got_worktree_integrate_abort(worktree, fileindex, repo,
8729 branch_ref, base_branch_ref);
8730 goto done;
8733 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
8734 if (error) {
8735 if (error->code == GOT_ERR_ANCESTRY)
8736 error = got_error(GOT_ERR_REBASE_REQUIRED);
8737 got_worktree_integrate_abort(worktree, fileindex, repo,
8738 branch_ref, base_branch_ref);
8739 goto done;
8742 memset(&upa, 0, sizeof(upa));
8743 error = got_worktree_integrate_continue(worktree, fileindex, repo,
8744 branch_ref, base_branch_ref, update_progress, &upa,
8745 check_cancelled, NULL);
8746 if (error)
8747 goto done;
8749 printf("Integrated %s into %s\n", refname, base_refname);
8750 print_update_progress_stats(&upa);
8751 done:
8752 if (repo)
8753 got_repo_close(repo);
8754 if (worktree)
8755 got_worktree_close(worktree);
8756 free(cwd);
8757 free(base_commit_id);
8758 free(commit_id);
8759 free(refname);
8760 free(base_refname);
8761 return error;
8764 __dead static void
8765 usage_stage(void)
8767 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
8768 "[-S] [file-path ...]\n",
8769 getprogname());
8770 exit(1);
8773 static const struct got_error *
8774 print_stage(void *arg, unsigned char status, unsigned char staged_status,
8775 const char *path, struct got_object_id *blob_id,
8776 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
8777 int dirfd, const char *de_name)
8779 const struct got_error *err = NULL;
8780 char *id_str = NULL;
8782 if (staged_status != GOT_STATUS_ADD &&
8783 staged_status != GOT_STATUS_MODIFY &&
8784 staged_status != GOT_STATUS_DELETE)
8785 return NULL;
8787 if (staged_status == GOT_STATUS_ADD ||
8788 staged_status == GOT_STATUS_MODIFY)
8789 err = got_object_id_str(&id_str, staged_blob_id);
8790 else
8791 err = got_object_id_str(&id_str, blob_id);
8792 if (err)
8793 return err;
8795 printf("%s %c %s\n", id_str, staged_status, path);
8796 free(id_str);
8797 return NULL;
8800 static const struct got_error *
8801 cmd_stage(int argc, char *argv[])
8803 const struct got_error *error = NULL;
8804 struct got_repository *repo = NULL;
8805 struct got_worktree *worktree = NULL;
8806 char *cwd = NULL;
8807 struct got_pathlist_head paths;
8808 struct got_pathlist_entry *pe;
8809 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
8810 FILE *patch_script_file = NULL;
8811 const char *patch_script_path = NULL;
8812 struct choose_patch_arg cpa;
8814 TAILQ_INIT(&paths);
8816 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
8817 switch (ch) {
8818 case 'l':
8819 list_stage = 1;
8820 break;
8821 case 'p':
8822 pflag = 1;
8823 break;
8824 case 'F':
8825 patch_script_path = optarg;
8826 break;
8827 case 'S':
8828 allow_bad_symlinks = 1;
8829 break;
8830 default:
8831 usage_stage();
8832 /* NOTREACHED */
8836 argc -= optind;
8837 argv += optind;
8839 #ifndef PROFILE
8840 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8841 "unveil", NULL) == -1)
8842 err(1, "pledge");
8843 #endif
8844 if (list_stage && (pflag || patch_script_path))
8845 errx(1, "-l option cannot be used with other options");
8846 if (patch_script_path && !pflag)
8847 errx(1, "-F option can only be used together with -p option");
8849 cwd = getcwd(NULL, 0);
8850 if (cwd == NULL) {
8851 error = got_error_from_errno("getcwd");
8852 goto done;
8855 error = got_worktree_open(&worktree, cwd);
8856 if (error) {
8857 if (error->code == GOT_ERR_NOT_WORKTREE)
8858 error = wrap_not_worktree_error(error, "stage", cwd);
8859 goto done;
8862 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8863 NULL);
8864 if (error != NULL)
8865 goto done;
8867 if (patch_script_path) {
8868 patch_script_file = fopen(patch_script_path, "r");
8869 if (patch_script_file == NULL) {
8870 error = got_error_from_errno2("fopen",
8871 patch_script_path);
8872 goto done;
8875 error = apply_unveil(got_repo_get_path(repo), 0,
8876 got_worktree_get_root_path(worktree));
8877 if (error)
8878 goto done;
8880 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8881 if (error)
8882 goto done;
8884 if (list_stage)
8885 error = got_worktree_status(worktree, &paths, repo,
8886 print_stage, NULL, check_cancelled, NULL);
8887 else {
8888 cpa.patch_script_file = patch_script_file;
8889 cpa.action = "stage";
8890 error = got_worktree_stage(worktree, &paths,
8891 pflag ? NULL : print_status, NULL,
8892 pflag ? choose_patch : NULL, &cpa,
8893 allow_bad_symlinks, repo);
8895 done:
8896 if (patch_script_file && fclose(patch_script_file) == EOF &&
8897 error == NULL)
8898 error = got_error_from_errno2("fclose", patch_script_path);
8899 if (repo)
8900 got_repo_close(repo);
8901 if (worktree)
8902 got_worktree_close(worktree);
8903 TAILQ_FOREACH(pe, &paths, entry)
8904 free((char *)pe->path);
8905 got_pathlist_free(&paths);
8906 free(cwd);
8907 return error;
8910 __dead static void
8911 usage_unstage(void)
8913 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
8914 "[file-path ...]\n",
8915 getprogname());
8916 exit(1);
8920 static const struct got_error *
8921 cmd_unstage(int argc, char *argv[])
8923 const struct got_error *error = NULL;
8924 struct got_repository *repo = NULL;
8925 struct got_worktree *worktree = NULL;
8926 char *cwd = NULL;
8927 struct got_pathlist_head paths;
8928 struct got_pathlist_entry *pe;
8929 int ch, pflag = 0;
8930 struct got_update_progress_arg upa;
8931 FILE *patch_script_file = NULL;
8932 const char *patch_script_path = NULL;
8933 struct choose_patch_arg cpa;
8935 TAILQ_INIT(&paths);
8937 while ((ch = getopt(argc, argv, "pF:")) != -1) {
8938 switch (ch) {
8939 case 'p':
8940 pflag = 1;
8941 break;
8942 case 'F':
8943 patch_script_path = optarg;
8944 break;
8945 default:
8946 usage_unstage();
8947 /* NOTREACHED */
8951 argc -= optind;
8952 argv += optind;
8954 #ifndef PROFILE
8955 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8956 "unveil", NULL) == -1)
8957 err(1, "pledge");
8958 #endif
8959 if (patch_script_path && !pflag)
8960 errx(1, "-F option can only be used together with -p option");
8962 cwd = getcwd(NULL, 0);
8963 if (cwd == NULL) {
8964 error = got_error_from_errno("getcwd");
8965 goto done;
8968 error = got_worktree_open(&worktree, cwd);
8969 if (error) {
8970 if (error->code == GOT_ERR_NOT_WORKTREE)
8971 error = wrap_not_worktree_error(error, "unstage", cwd);
8972 goto done;
8975 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8976 NULL);
8977 if (error != NULL)
8978 goto done;
8980 if (patch_script_path) {
8981 patch_script_file = fopen(patch_script_path, "r");
8982 if (patch_script_file == NULL) {
8983 error = got_error_from_errno2("fopen",
8984 patch_script_path);
8985 goto done;
8989 error = apply_unveil(got_repo_get_path(repo), 0,
8990 got_worktree_get_root_path(worktree));
8991 if (error)
8992 goto done;
8994 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8995 if (error)
8996 goto done;
8998 cpa.patch_script_file = patch_script_file;
8999 cpa.action = "unstage";
9000 memset(&upa, 0, sizeof(upa));
9001 error = got_worktree_unstage(worktree, &paths, update_progress,
9002 &upa, pflag ? choose_patch : NULL, &cpa, repo);
9003 if (!error)
9004 print_update_progress_stats(&upa);
9005 done:
9006 if (patch_script_file && fclose(patch_script_file) == EOF &&
9007 error == NULL)
9008 error = got_error_from_errno2("fclose", patch_script_path);
9009 if (repo)
9010 got_repo_close(repo);
9011 if (worktree)
9012 got_worktree_close(worktree);
9013 TAILQ_FOREACH(pe, &paths, entry)
9014 free((char *)pe->path);
9015 got_pathlist_free(&paths);
9016 free(cwd);
9017 return error;
9020 __dead static void
9021 usage_cat(void)
9023 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
9024 "arg1 [arg2 ...]\n", getprogname());
9025 exit(1);
9028 static const struct got_error *
9029 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9031 const struct got_error *err;
9032 struct got_blob_object *blob;
9034 err = got_object_open_as_blob(&blob, repo, id, 8192);
9035 if (err)
9036 return err;
9038 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
9039 got_object_blob_close(blob);
9040 return err;
9043 static const struct got_error *
9044 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9046 const struct got_error *err;
9047 struct got_tree_object *tree;
9048 int nentries, i;
9050 err = got_object_open_as_tree(&tree, repo, id);
9051 if (err)
9052 return err;
9054 nentries = got_object_tree_get_nentries(tree);
9055 for (i = 0; i < nentries; i++) {
9056 struct got_tree_entry *te;
9057 char *id_str;
9058 if (sigint_received || sigpipe_received)
9059 break;
9060 te = got_object_tree_get_entry(tree, i);
9061 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
9062 if (err)
9063 break;
9064 fprintf(outfile, "%s %.7o %s\n", id_str,
9065 got_tree_entry_get_mode(te),
9066 got_tree_entry_get_name(te));
9067 free(id_str);
9070 got_object_tree_close(tree);
9071 return err;
9074 static const struct got_error *
9075 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9077 const struct got_error *err;
9078 struct got_commit_object *commit;
9079 const struct got_object_id_queue *parent_ids;
9080 struct got_object_qid *pid;
9081 char *id_str = NULL;
9082 const char *logmsg = NULL;
9084 err = got_object_open_as_commit(&commit, repo, id);
9085 if (err)
9086 return err;
9088 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
9089 if (err)
9090 goto done;
9092 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
9093 parent_ids = got_object_commit_get_parent_ids(commit);
9094 fprintf(outfile, "numparents %d\n",
9095 got_object_commit_get_nparents(commit));
9096 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
9097 char *pid_str;
9098 err = got_object_id_str(&pid_str, pid->id);
9099 if (err)
9100 goto done;
9101 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
9102 free(pid_str);
9104 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
9105 got_object_commit_get_author(commit),
9106 got_object_commit_get_author_time(commit));
9108 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
9109 got_object_commit_get_author(commit),
9110 got_object_commit_get_committer_time(commit));
9112 logmsg = got_object_commit_get_logmsg_raw(commit);
9113 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
9114 fprintf(outfile, "%s", logmsg);
9115 done:
9116 free(id_str);
9117 got_object_commit_close(commit);
9118 return err;
9121 static const struct got_error *
9122 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9124 const struct got_error *err;
9125 struct got_tag_object *tag;
9126 char *id_str = NULL;
9127 const char *tagmsg = NULL;
9129 err = got_object_open_as_tag(&tag, repo, id);
9130 if (err)
9131 return err;
9133 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
9134 if (err)
9135 goto done;
9137 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
9139 switch (got_object_tag_get_object_type(tag)) {
9140 case GOT_OBJ_TYPE_BLOB:
9141 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9142 GOT_OBJ_LABEL_BLOB);
9143 break;
9144 case GOT_OBJ_TYPE_TREE:
9145 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9146 GOT_OBJ_LABEL_TREE);
9147 break;
9148 case GOT_OBJ_TYPE_COMMIT:
9149 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9150 GOT_OBJ_LABEL_COMMIT);
9151 break;
9152 case GOT_OBJ_TYPE_TAG:
9153 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9154 GOT_OBJ_LABEL_TAG);
9155 break;
9156 default:
9157 break;
9160 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
9161 got_object_tag_get_name(tag));
9163 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
9164 got_object_tag_get_tagger(tag),
9165 got_object_tag_get_tagger_time(tag));
9167 tagmsg = got_object_tag_get_message(tag);
9168 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
9169 fprintf(outfile, "%s", tagmsg);
9170 done:
9171 free(id_str);
9172 got_object_tag_close(tag);
9173 return err;
9176 static const struct got_error *
9177 cmd_cat(int argc, char *argv[])
9179 const struct got_error *error;
9180 struct got_repository *repo = NULL;
9181 struct got_worktree *worktree = NULL;
9182 char *cwd = NULL, *repo_path = NULL, *label = NULL;
9183 const char *commit_id_str = NULL;
9184 struct got_object_id *id = NULL, *commit_id = NULL;
9185 int ch, obj_type, i, force_path = 0;
9187 #ifndef PROFILE
9188 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9189 NULL) == -1)
9190 err(1, "pledge");
9191 #endif
9193 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
9194 switch (ch) {
9195 case 'c':
9196 commit_id_str = optarg;
9197 break;
9198 case 'r':
9199 repo_path = realpath(optarg, NULL);
9200 if (repo_path == NULL)
9201 return got_error_from_errno2("realpath",
9202 optarg);
9203 got_path_strip_trailing_slashes(repo_path);
9204 break;
9205 case 'P':
9206 force_path = 1;
9207 break;
9208 default:
9209 usage_cat();
9210 /* NOTREACHED */
9214 argc -= optind;
9215 argv += optind;
9217 cwd = getcwd(NULL, 0);
9218 if (cwd == NULL) {
9219 error = got_error_from_errno("getcwd");
9220 goto done;
9222 error = got_worktree_open(&worktree, cwd);
9223 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9224 goto done;
9225 if (worktree) {
9226 if (repo_path == NULL) {
9227 repo_path = strdup(
9228 got_worktree_get_repo_path(worktree));
9229 if (repo_path == NULL) {
9230 error = got_error_from_errno("strdup");
9231 goto done;
9236 if (repo_path == NULL) {
9237 repo_path = getcwd(NULL, 0);
9238 if (repo_path == NULL)
9239 return got_error_from_errno("getcwd");
9242 error = got_repo_open(&repo, repo_path, NULL);
9243 free(repo_path);
9244 if (error != NULL)
9245 goto done;
9247 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9248 if (error)
9249 goto done;
9251 if (commit_id_str == NULL)
9252 commit_id_str = GOT_REF_HEAD;
9253 error = got_repo_match_object_id(&commit_id, NULL,
9254 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
9255 if (error)
9256 goto done;
9258 for (i = 0; i < argc; i++) {
9259 if (force_path) {
9260 error = got_object_id_by_path(&id, repo, commit_id,
9261 argv[i]);
9262 if (error)
9263 break;
9264 } else {
9265 error = got_repo_match_object_id(&id, &label, argv[i],
9266 GOT_OBJ_TYPE_ANY, 0, repo);
9267 if (error) {
9268 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9269 error->code != GOT_ERR_NOT_REF)
9270 break;
9271 error = got_object_id_by_path(&id, repo,
9272 commit_id, argv[i]);
9273 if (error)
9274 break;
9278 error = got_object_get_type(&obj_type, repo, id);
9279 if (error)
9280 break;
9282 switch (obj_type) {
9283 case GOT_OBJ_TYPE_BLOB:
9284 error = cat_blob(id, repo, stdout);
9285 break;
9286 case GOT_OBJ_TYPE_TREE:
9287 error = cat_tree(id, repo, stdout);
9288 break;
9289 case GOT_OBJ_TYPE_COMMIT:
9290 error = cat_commit(id, repo, stdout);
9291 break;
9292 case GOT_OBJ_TYPE_TAG:
9293 error = cat_tag(id, repo, stdout);
9294 break;
9295 default:
9296 error = got_error(GOT_ERR_OBJ_TYPE);
9297 break;
9299 if (error)
9300 break;
9301 free(label);
9302 label = NULL;
9303 free(id);
9304 id = NULL;
9306 done:
9307 free(label);
9308 free(id);
9309 free(commit_id);
9310 if (worktree)
9311 got_worktree_close(worktree);
9312 if (repo) {
9313 const struct got_error *repo_error;
9314 repo_error = got_repo_close(repo);
9315 if (error == NULL)
9316 error = repo_error;
9318 return error;