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 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1181 server_path, verbosity);
1182 if (error)
1183 goto done;
1185 if (verbosity >= 0)
1186 printf("Connected to %s%s%s\n", host,
1187 port ? ":" : "", port ? port : "");
1189 fpa.last_scaled_size[0] = '\0';
1190 fpa.last_p_indexed = -1;
1191 fpa.last_p_resolved = -1;
1192 fpa.verbosity = verbosity;
1193 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1194 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1195 fetch_all_branches, &wanted_branches, &wanted_refs,
1196 list_refs_only, verbosity, fetchfd, repo,
1197 fetch_progress, &fpa);
1198 if (error)
1199 goto done;
1201 if (list_refs_only) {
1202 error = list_remote_refs(&symrefs, &refs);
1203 goto done;
1206 error = got_object_id_str(&id_str, pack_hash);
1207 if (error)
1208 goto done;
1209 if (verbosity >= 0)
1210 printf("\nFetched %s.pack\n", id_str);
1211 free(id_str);
1213 /* Set up references provided with the pack file. */
1214 TAILQ_FOREACH(pe, &refs, entry) {
1215 const char *refname = pe->path;
1216 struct got_object_id *id = pe->data;
1217 char *remote_refname;
1219 if (is_wanted_ref(&wanted_refs, refname) &&
1220 !mirror_references) {
1221 error = create_wanted_ref(refname, id,
1222 GOT_FETCH_DEFAULT_REMOTE_NAME,
1223 verbosity - 1, repo);
1224 if (error)
1225 goto done;
1226 continue;
1229 error = create_ref(refname, id, verbosity - 1, repo);
1230 if (error)
1231 goto done;
1233 if (mirror_references)
1234 continue;
1236 if (strncmp("refs/heads/", refname, 11) != 0)
1237 continue;
1239 if (asprintf(&remote_refname,
1240 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1241 refname + 11) == -1) {
1242 error = got_error_from_errno("asprintf");
1243 goto done;
1245 error = create_ref(remote_refname, id, verbosity - 1, repo);
1246 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 reference %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 reference %s: %s\n",
1547 got_ref_get_name(symref),
1548 got_ref_get_symref_target(symref));
1551 done:
1552 if (symref_is_locked) {
1553 unlock_err = got_ref_unlock(symref);
1554 if (unlock_err && err == NULL)
1555 err = unlock_err;
1557 got_ref_close(symref);
1558 return err;
1561 __dead static void
1562 usage_fetch(void)
1564 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1565 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1566 "[remote-repository-name]\n",
1567 getprogname());
1568 exit(1);
1571 static const struct got_error *
1572 delete_missing_ref(struct got_reference *ref,
1573 int verbosity, struct got_repository *repo)
1575 const struct got_error *err = NULL;
1576 struct got_object_id *id = NULL;
1577 char *id_str = NULL;
1579 if (got_ref_is_symbolic(ref)) {
1580 err = got_ref_delete(ref, repo);
1581 if (err)
1582 return err;
1583 if (verbosity >= 0) {
1584 printf("Deleted reference %s: %s\n",
1585 got_ref_get_name(ref),
1586 got_ref_get_symref_target(ref));
1588 } else {
1589 err = got_ref_resolve(&id, repo, ref);
1590 if (err)
1591 return err;
1592 err = got_object_id_str(&id_str, id);
1593 if (err)
1594 goto done;
1596 err = got_ref_delete(ref, repo);
1597 if (err)
1598 goto done;
1599 if (verbosity >= 0) {
1600 printf("Deleted reference %s: %s\n",
1601 got_ref_get_name(ref), id_str);
1604 done:
1605 free(id);
1606 free(id_str);
1607 return NULL;
1610 static const struct got_error *
1611 delete_missing_refs(struct got_pathlist_head *their_refs,
1612 struct got_pathlist_head *their_symrefs, struct got_remote_repo *remote,
1613 int verbosity, struct got_repository *repo)
1615 const struct got_error *err = NULL, *unlock_err;
1616 struct got_reflist_head my_refs;
1617 struct got_reflist_entry *re;
1618 struct got_pathlist_entry *pe;
1619 char *remote_namespace = NULL;
1620 char *local_refname = NULL;
1622 SIMPLEQ_INIT(&my_refs);
1624 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
1625 == -1)
1626 return got_error_from_errno("asprintf");
1628 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1629 if (err)
1630 goto done;
1632 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1633 const char *refname = got_ref_get_name(re->ref);
1635 if (!remote->mirror_references) {
1636 if (strncmp(refname, remote_namespace,
1637 strlen(remote_namespace)) == 0) {
1638 if (strcmp(refname + strlen(remote_namespace),
1639 GOT_REF_HEAD) == 0)
1640 continue;
1641 if (asprintf(&local_refname, "refs/heads/%s",
1642 refname + strlen(remote_namespace)) == -1) {
1643 err = got_error_from_errno("asprintf");
1644 goto done;
1646 } else if (strncmp(refname, "refs/tags/", 10) != 0)
1647 continue;
1650 TAILQ_FOREACH(pe, their_refs, entry) {
1651 if (strcmp(local_refname, pe->path) == 0)
1652 break;
1654 if (pe != NULL)
1655 continue;
1657 TAILQ_FOREACH(pe, their_symrefs, entry) {
1658 if (strcmp(local_refname, pe->path) == 0)
1659 break;
1661 if (pe != NULL)
1662 continue;
1664 err = delete_missing_ref(re->ref, verbosity, repo);
1665 if (err)
1666 break;
1668 if (local_refname) {
1669 struct got_reference *ref;
1670 err = got_ref_open(&ref, repo, local_refname, 1);
1671 if (err) {
1672 if (err->code != GOT_ERR_NOT_REF)
1673 break;
1674 free(local_refname);
1675 local_refname = NULL;
1676 continue;
1678 err = delete_missing_ref(ref, verbosity, repo);
1679 if (err)
1680 break;
1681 unlock_err = got_ref_unlock(ref);
1682 got_ref_close(ref);
1683 if (unlock_err && err == NULL) {
1684 err = unlock_err;
1685 break;
1688 free(local_refname);
1689 local_refname = NULL;
1692 done:
1693 free(remote_namespace);
1694 free(local_refname);
1695 return err;
1698 static const struct got_error *
1699 update_wanted_ref(const char *refname, struct got_object_id *id,
1700 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1702 const struct got_error *err, *unlock_err;
1703 char *remote_refname;
1704 struct got_reference *ref;
1706 if (strncmp("refs/", refname, 5) == 0)
1707 refname += 5;
1709 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1710 remote_repo_name, refname) == -1)
1711 return got_error_from_errno("asprintf");
1713 err = got_ref_open(&ref, repo, remote_refname, 1);
1714 if (err) {
1715 if (err->code != GOT_ERR_NOT_REF)
1716 goto done;
1717 err = create_ref(remote_refname, id, verbosity, repo);
1718 } else {
1719 err = update_ref(ref, id, 0, verbosity, repo);
1720 unlock_err = got_ref_unlock(ref);
1721 if (unlock_err && err == NULL)
1722 err = unlock_err;
1723 got_ref_close(ref);
1725 done:
1726 free(remote_refname);
1727 return err;
1730 static const struct got_error *
1731 cmd_fetch(int argc, char *argv[])
1733 const struct got_error *error = NULL, *unlock_err;
1734 char *cwd = NULL, *repo_path = NULL;
1735 const char *remote_name;
1736 char *proto = NULL, *host = NULL, *port = NULL;
1737 char *repo_name = NULL, *server_path = NULL;
1738 struct got_remote_repo *remotes, *remote = NULL;
1739 int nremotes;
1740 char *id_str = NULL;
1741 struct got_repository *repo = NULL;
1742 struct got_worktree *worktree = NULL;
1743 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1744 struct got_pathlist_entry *pe;
1745 struct got_object_id *pack_hash = NULL;
1746 int i, ch, fetchfd = -1, fetchstatus;
1747 pid_t fetchpid = -1;
1748 struct got_fetch_progress_arg fpa;
1749 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
1750 int delete_refs = 0, replace_tags = 0;
1752 TAILQ_INIT(&refs);
1753 TAILQ_INIT(&symrefs);
1754 TAILQ_INIT(&wanted_branches);
1755 TAILQ_INIT(&wanted_refs);
1757 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
1758 switch (ch) {
1759 case 'a':
1760 fetch_all_branches = 1;
1761 break;
1762 case 'b':
1763 error = got_pathlist_append(&wanted_branches,
1764 optarg, NULL);
1765 if (error)
1766 return error;
1767 break;
1768 case 'd':
1769 delete_refs = 1;
1770 break;
1771 case 'l':
1772 list_refs_only = 1;
1773 break;
1774 case 'r':
1775 repo_path = realpath(optarg, NULL);
1776 if (repo_path == NULL)
1777 return got_error_from_errno2("realpath",
1778 optarg);
1779 got_path_strip_trailing_slashes(repo_path);
1780 break;
1781 case 't':
1782 replace_tags = 1;
1783 break;
1784 case 'v':
1785 if (verbosity < 0)
1786 verbosity = 0;
1787 else if (verbosity < 3)
1788 verbosity++;
1789 break;
1790 case 'q':
1791 verbosity = -1;
1792 break;
1793 case 'R':
1794 error = got_pathlist_append(&wanted_refs,
1795 optarg, NULL);
1796 if (error)
1797 return error;
1798 break;
1799 default:
1800 usage_fetch();
1801 break;
1804 argc -= optind;
1805 argv += optind;
1807 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1808 errx(1, "-a and -b options are mutually exclusive");
1809 if (list_refs_only) {
1810 if (!TAILQ_EMPTY(&wanted_branches))
1811 errx(1, "-l and -b options are mutually exclusive");
1812 if (fetch_all_branches)
1813 errx(1, "-l and -a options are mutually exclusive");
1814 if (delete_refs)
1815 errx(1, "-l and -d options are mutually exclusive");
1816 if (verbosity == -1)
1817 errx(1, "-l and -q options are mutually exclusive");
1820 if (argc == 0)
1821 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
1822 else if (argc == 1)
1823 remote_name = argv[0];
1824 else
1825 usage_fetch();
1827 cwd = getcwd(NULL, 0);
1828 if (cwd == NULL) {
1829 error = got_error_from_errno("getcwd");
1830 goto done;
1833 if (repo_path == NULL) {
1834 error = got_worktree_open(&worktree, cwd);
1835 if (error && error->code != GOT_ERR_NOT_WORKTREE)
1836 goto done;
1837 else
1838 error = NULL;
1839 if (worktree) {
1840 repo_path =
1841 strdup(got_worktree_get_repo_path(worktree));
1842 if (repo_path == NULL)
1843 error = got_error_from_errno("strdup");
1844 if (error)
1845 goto done;
1846 } else {
1847 repo_path = strdup(cwd);
1848 if (repo_path == NULL) {
1849 error = got_error_from_errno("strdup");
1850 goto done;
1855 error = got_repo_open(&repo, repo_path, NULL);
1856 if (error)
1857 goto done;
1859 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
1860 for (i = 0; i < nremotes; i++) {
1861 remote = &remotes[i];
1862 if (strcmp(remote->name, remote_name) == 0)
1863 break;
1865 if (i == nremotes) {
1866 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
1867 goto done;
1870 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1871 &repo_name, remote->url);
1872 if (error)
1873 goto done;
1875 if (strcmp(proto, "git") == 0) {
1876 #ifndef PROFILE
1877 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1878 "sendfd dns inet unveil", NULL) == -1)
1879 err(1, "pledge");
1880 #endif
1881 } else if (strcmp(proto, "git+ssh") == 0 ||
1882 strcmp(proto, "ssh") == 0) {
1883 #ifndef PROFILE
1884 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1885 "sendfd unveil", NULL) == -1)
1886 err(1, "pledge");
1887 #endif
1888 } else if (strcmp(proto, "http") == 0 ||
1889 strcmp(proto, "git+http") == 0) {
1890 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1891 goto done;
1892 } else {
1893 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1894 goto done;
1897 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1898 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1899 error = got_error_from_errno2("unveil",
1900 GOT_FETCH_PATH_SSH);
1901 goto done;
1904 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
1905 if (error)
1906 goto done;
1908 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1909 server_path, verbosity);
1910 if (error)
1911 goto done;
1913 if (verbosity >= 0)
1914 printf("Connected to \"%s\" %s%s%s\n", remote->name, host,
1915 port ? ":" : "", port ? port : "");
1917 fpa.last_scaled_size[0] = '\0';
1918 fpa.last_p_indexed = -1;
1919 fpa.last_p_resolved = -1;
1920 fpa.verbosity = verbosity;
1921 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
1922 remote->mirror_references, fetch_all_branches, &wanted_branches,
1923 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
1924 fetch_progress, &fpa);
1925 if (error)
1926 goto done;
1928 if (list_refs_only) {
1929 error = list_remote_refs(&symrefs, &refs);
1930 goto done;
1933 if (pack_hash == NULL) {
1934 if (verbosity >= 0)
1935 printf("Already up-to-date\n");
1936 } else if (verbosity >= 0) {
1937 error = got_object_id_str(&id_str, pack_hash);
1938 if (error)
1939 goto done;
1940 printf("\nFetched %s.pack\n", id_str);
1941 free(id_str);
1942 id_str = NULL;
1945 /* Update references provided with the pack file. */
1946 TAILQ_FOREACH(pe, &refs, entry) {
1947 const char *refname = pe->path;
1948 struct got_object_id *id = pe->data;
1949 struct got_reference *ref;
1950 char *remote_refname;
1952 if (is_wanted_ref(&wanted_refs, refname) &&
1953 !remote->mirror_references) {
1954 error = update_wanted_ref(refname, id,
1955 remote->name, verbosity, repo);
1956 if (error)
1957 goto done;
1958 continue;
1961 if (remote->mirror_references ||
1962 strncmp("refs/tags/", refname, 10) == 0) {
1963 error = got_ref_open(&ref, repo, refname, 1);
1964 if (error) {
1965 if (error->code != GOT_ERR_NOT_REF)
1966 goto done;
1967 error = create_ref(refname, id, verbosity,
1968 repo);
1969 if (error)
1970 goto done;
1971 } else {
1972 error = update_ref(ref, id, replace_tags,
1973 verbosity, repo);
1974 unlock_err = got_ref_unlock(ref);
1975 if (unlock_err && error == NULL)
1976 error = unlock_err;
1977 got_ref_close(ref);
1978 if (error)
1979 goto done;
1981 } else if (strncmp("refs/heads/", refname, 11) == 0) {
1982 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1983 remote_name, refname + 11) == -1) {
1984 error = got_error_from_errno("asprintf");
1985 goto done;
1988 error = got_ref_open(&ref, repo, remote_refname, 1);
1989 if (error) {
1990 if (error->code != GOT_ERR_NOT_REF)
1991 goto done;
1992 error = create_ref(remote_refname, id,
1993 verbosity, repo);
1994 if (error)
1995 goto done;
1996 } else {
1997 error = update_ref(ref, id, replace_tags,
1998 verbosity, repo);
1999 unlock_err = got_ref_unlock(ref);
2000 if (unlock_err && error == NULL)
2001 error = unlock_err;
2002 got_ref_close(ref);
2003 if (error)
2004 goto done;
2007 /* Also create a local branch if none exists yet. */
2008 error = got_ref_open(&ref, repo, refname, 1);
2009 if (error) {
2010 if (error->code != GOT_ERR_NOT_REF)
2011 goto done;
2012 error = create_ref(refname, id, verbosity,
2013 repo);
2014 if (error)
2015 goto done;
2016 } else {
2017 unlock_err = got_ref_unlock(ref);
2018 if (unlock_err && error == NULL)
2019 error = unlock_err;
2020 got_ref_close(ref);
2024 if (delete_refs) {
2025 error = delete_missing_refs(&refs, &symrefs, remote,
2026 verbosity, repo);
2027 if (error)
2028 goto done;
2031 if (!remote->mirror_references) {
2032 /* Update remote HEAD reference if the server provided one. */
2033 TAILQ_FOREACH(pe, &symrefs, entry) {
2034 struct got_reference *target_ref;
2035 const char *refname = pe->path;
2036 const char *target = pe->data;
2037 char *remote_refname = NULL, *remote_target = NULL;
2039 if (strcmp(refname, GOT_REF_HEAD) != 0)
2040 continue;
2042 if (strncmp("refs/heads/", target, 11) != 0)
2043 continue;
2045 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2046 remote->name, refname) == -1) {
2047 error = got_error_from_errno("asprintf");
2048 goto done;
2050 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2051 remote->name, target + 11) == -1) {
2052 error = got_error_from_errno("asprintf");
2053 free(remote_refname);
2054 goto done;
2057 error = got_ref_open(&target_ref, repo, remote_target,
2058 0);
2059 if (error) {
2060 free(remote_refname);
2061 free(remote_target);
2062 if (error->code == GOT_ERR_NOT_REF) {
2063 error = NULL;
2064 continue;
2066 goto done;
2068 error = update_symref(remote_refname, target_ref,
2069 verbosity, repo);
2070 free(remote_refname);
2071 free(remote_target);
2072 got_ref_close(target_ref);
2073 if (error)
2074 goto done;
2077 done:
2078 if (fetchpid > 0) {
2079 if (kill(fetchpid, SIGTERM) == -1)
2080 error = got_error_from_errno("kill");
2081 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2082 error = got_error_from_errno("waitpid");
2084 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2085 error = got_error_from_errno("close");
2086 if (repo)
2087 got_repo_close(repo);
2088 if (worktree)
2089 got_worktree_close(worktree);
2090 TAILQ_FOREACH(pe, &refs, entry) {
2091 free((void *)pe->path);
2092 free(pe->data);
2094 got_pathlist_free(&refs);
2095 TAILQ_FOREACH(pe, &symrefs, entry) {
2096 free((void *)pe->path);
2097 free(pe->data);
2099 got_pathlist_free(&symrefs);
2100 got_pathlist_free(&wanted_branches);
2101 got_pathlist_free(&wanted_refs);
2102 free(id_str);
2103 free(cwd);
2104 free(repo_path);
2105 free(pack_hash);
2106 free(proto);
2107 free(host);
2108 free(port);
2109 free(server_path);
2110 free(repo_name);
2111 return error;
2115 __dead static void
2116 usage_checkout(void)
2118 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2119 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2120 exit(1);
2123 static void
2124 show_worktree_base_ref_warning(void)
2126 fprintf(stderr, "%s: warning: could not create a reference "
2127 "to the work tree's base commit; the commit could be "
2128 "garbage-collected by Git; making the repository "
2129 "writable and running 'got update' will prevent this\n",
2130 getprogname());
2133 struct got_checkout_progress_arg {
2134 const char *worktree_path;
2135 int had_base_commit_ref_error;
2138 static const struct got_error *
2139 checkout_progress(void *arg, unsigned char status, const char *path)
2141 struct got_checkout_progress_arg *a = arg;
2143 /* Base commit bump happens silently. */
2144 if (status == GOT_STATUS_BUMP_BASE)
2145 return NULL;
2147 if (status == GOT_STATUS_BASE_REF_ERR) {
2148 a->had_base_commit_ref_error = 1;
2149 return NULL;
2152 while (path[0] == '/')
2153 path++;
2155 printf("%c %s/%s\n", status, a->worktree_path, path);
2156 return NULL;
2159 static const struct got_error *
2160 check_cancelled(void *arg)
2162 if (sigint_received || sigpipe_received)
2163 return got_error(GOT_ERR_CANCELLED);
2164 return NULL;
2167 static const struct got_error *
2168 check_linear_ancestry(struct got_object_id *commit_id,
2169 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2170 struct got_repository *repo)
2172 const struct got_error *err = NULL;
2173 struct got_object_id *yca_id;
2175 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2176 commit_id, base_commit_id, repo, check_cancelled, NULL);
2177 if (err)
2178 return err;
2180 if (yca_id == NULL)
2181 return got_error(GOT_ERR_ANCESTRY);
2184 * Require a straight line of history between the target commit
2185 * and the work tree's base commit.
2187 * Non-linear situations such as this require a rebase:
2189 * (commit) D F (base_commit)
2190 * \ /
2191 * C E
2192 * \ /
2193 * B (yca)
2194 * |
2195 * A
2197 * 'got update' only handles linear cases:
2198 * Update forwards in time: A (base/yca) - B - C - D (commit)
2199 * Update backwards in time: D (base) - C - B - A (commit/yca)
2201 if (allow_forwards_in_time_only) {
2202 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2203 return got_error(GOT_ERR_ANCESTRY);
2204 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2205 got_object_id_cmp(base_commit_id, yca_id) != 0)
2206 return got_error(GOT_ERR_ANCESTRY);
2208 free(yca_id);
2209 return NULL;
2212 static const struct got_error *
2213 check_same_branch(struct got_object_id *commit_id,
2214 struct got_reference *head_ref, struct got_object_id *yca_id,
2215 struct got_repository *repo)
2217 const struct got_error *err = NULL;
2218 struct got_commit_graph *graph = NULL;
2219 struct got_object_id *head_commit_id = NULL;
2220 int is_same_branch = 0;
2222 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2223 if (err)
2224 goto done;
2226 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2227 is_same_branch = 1;
2228 goto done;
2230 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2231 is_same_branch = 1;
2232 goto done;
2235 err = got_commit_graph_open(&graph, "/", 1);
2236 if (err)
2237 goto done;
2239 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2240 check_cancelled, NULL);
2241 if (err)
2242 goto done;
2244 for (;;) {
2245 struct got_object_id *id;
2246 err = got_commit_graph_iter_next(&id, graph, repo,
2247 check_cancelled, NULL);
2248 if (err) {
2249 if (err->code == GOT_ERR_ITER_COMPLETED)
2250 err = NULL;
2251 break;
2254 if (id) {
2255 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2256 break;
2257 if (got_object_id_cmp(id, commit_id) == 0) {
2258 is_same_branch = 1;
2259 break;
2263 done:
2264 if (graph)
2265 got_commit_graph_close(graph);
2266 free(head_commit_id);
2267 if (!err && !is_same_branch)
2268 err = got_error(GOT_ERR_ANCESTRY);
2269 return err;
2272 static const struct got_error *
2273 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2275 static char msg[512];
2276 const char *branch_name;
2278 if (got_ref_is_symbolic(ref))
2279 branch_name = got_ref_get_symref_target(ref);
2280 else
2281 branch_name = got_ref_get_name(ref);
2283 if (strncmp("refs/heads/", branch_name, 11) == 0)
2284 branch_name += 11;
2286 snprintf(msg, sizeof(msg),
2287 "target commit is not contained in branch '%s'; "
2288 "the branch to use must be specified with -b; "
2289 "if necessary a new branch can be created for "
2290 "this commit with 'got branch -c %s BRANCH_NAME'",
2291 branch_name, commit_id_str);
2293 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2296 static const struct got_error *
2297 cmd_checkout(int argc, char *argv[])
2299 const struct got_error *error = NULL;
2300 struct got_repository *repo = NULL;
2301 struct got_reference *head_ref = NULL;
2302 struct got_worktree *worktree = NULL;
2303 char *repo_path = NULL;
2304 char *worktree_path = NULL;
2305 const char *path_prefix = "";
2306 const char *branch_name = GOT_REF_HEAD;
2307 char *commit_id_str = NULL;
2308 int ch, same_path_prefix, allow_nonempty = 0;
2309 struct got_pathlist_head paths;
2310 struct got_checkout_progress_arg cpa;
2312 TAILQ_INIT(&paths);
2314 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2315 switch (ch) {
2316 case 'b':
2317 branch_name = optarg;
2318 break;
2319 case 'c':
2320 commit_id_str = strdup(optarg);
2321 if (commit_id_str == NULL)
2322 return got_error_from_errno("strdup");
2323 break;
2324 case 'E':
2325 allow_nonempty = 1;
2326 break;
2327 case 'p':
2328 path_prefix = optarg;
2329 break;
2330 default:
2331 usage_checkout();
2332 /* NOTREACHED */
2336 argc -= optind;
2337 argv += optind;
2339 #ifndef PROFILE
2340 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2341 "unveil", NULL) == -1)
2342 err(1, "pledge");
2343 #endif
2344 if (argc == 1) {
2345 char *cwd, *base, *dotgit;
2346 repo_path = realpath(argv[0], NULL);
2347 if (repo_path == NULL)
2348 return got_error_from_errno2("realpath", argv[0]);
2349 cwd = getcwd(NULL, 0);
2350 if (cwd == NULL) {
2351 error = got_error_from_errno("getcwd");
2352 goto done;
2354 if (path_prefix[0]) {
2355 base = basename(path_prefix);
2356 if (base == NULL) {
2357 error = got_error_from_errno2("basename",
2358 path_prefix);
2359 goto done;
2361 } else {
2362 base = basename(repo_path);
2363 if (base == NULL) {
2364 error = got_error_from_errno2("basename",
2365 repo_path);
2366 goto done;
2369 dotgit = strstr(base, ".git");
2370 if (dotgit)
2371 *dotgit = '\0';
2372 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2373 error = got_error_from_errno("asprintf");
2374 free(cwd);
2375 goto done;
2377 free(cwd);
2378 } else if (argc == 2) {
2379 repo_path = realpath(argv[0], NULL);
2380 if (repo_path == NULL) {
2381 error = got_error_from_errno2("realpath", argv[0]);
2382 goto done;
2384 worktree_path = realpath(argv[1], NULL);
2385 if (worktree_path == NULL) {
2386 if (errno != ENOENT) {
2387 error = got_error_from_errno2("realpath",
2388 argv[1]);
2389 goto done;
2391 worktree_path = strdup(argv[1]);
2392 if (worktree_path == NULL) {
2393 error = got_error_from_errno("strdup");
2394 goto done;
2397 } else
2398 usage_checkout();
2400 got_path_strip_trailing_slashes(repo_path);
2401 got_path_strip_trailing_slashes(worktree_path);
2403 error = got_repo_open(&repo, repo_path, NULL);
2404 if (error != NULL)
2405 goto done;
2407 /* Pre-create work tree path for unveil(2) */
2408 error = got_path_mkdir(worktree_path);
2409 if (error) {
2410 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2411 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2412 goto done;
2413 if (!allow_nonempty &&
2414 !got_path_dir_is_empty(worktree_path)) {
2415 error = got_error_path(worktree_path,
2416 GOT_ERR_DIR_NOT_EMPTY);
2417 goto done;
2421 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2422 if (error)
2423 goto done;
2425 error = got_ref_open(&head_ref, repo, branch_name, 0);
2426 if (error != NULL)
2427 goto done;
2429 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2430 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2431 goto done;
2433 error = got_worktree_open(&worktree, worktree_path);
2434 if (error != NULL)
2435 goto done;
2437 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2438 path_prefix);
2439 if (error != NULL)
2440 goto done;
2441 if (!same_path_prefix) {
2442 error = got_error(GOT_ERR_PATH_PREFIX);
2443 goto done;
2446 if (commit_id_str) {
2447 struct got_object_id *commit_id;
2448 error = got_repo_match_object_id(&commit_id, NULL,
2449 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2450 if (error)
2451 goto done;
2452 error = check_linear_ancestry(commit_id,
2453 got_worktree_get_base_commit_id(worktree), 0, repo);
2454 if (error != NULL) {
2455 free(commit_id);
2456 if (error->code == GOT_ERR_ANCESTRY) {
2457 error = checkout_ancestry_error(
2458 head_ref, commit_id_str);
2460 goto done;
2462 error = check_same_branch(commit_id, head_ref, NULL, repo);
2463 if (error) {
2464 if (error->code == GOT_ERR_ANCESTRY) {
2465 error = checkout_ancestry_error(
2466 head_ref, commit_id_str);
2468 goto done;
2470 error = got_worktree_set_base_commit_id(worktree, repo,
2471 commit_id);
2472 free(commit_id);
2473 if (error)
2474 goto done;
2477 error = got_pathlist_append(&paths, "", NULL);
2478 if (error)
2479 goto done;
2480 cpa.worktree_path = worktree_path;
2481 cpa.had_base_commit_ref_error = 0;
2482 error = got_worktree_checkout_files(worktree, &paths, repo,
2483 checkout_progress, &cpa, check_cancelled, NULL);
2484 if (error != NULL)
2485 goto done;
2487 printf("Now shut up and hack\n");
2488 if (cpa.had_base_commit_ref_error)
2489 show_worktree_base_ref_warning();
2490 done:
2491 got_pathlist_free(&paths);
2492 free(commit_id_str);
2493 free(repo_path);
2494 free(worktree_path);
2495 return error;
2498 __dead static void
2499 usage_update(void)
2501 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2502 getprogname());
2503 exit(1);
2506 static const struct got_error *
2507 update_progress(void *arg, unsigned char status, const char *path)
2509 int *did_something = arg;
2511 if (status == GOT_STATUS_EXISTS ||
2512 status == GOT_STATUS_BASE_REF_ERR)
2513 return NULL;
2515 *did_something = 1;
2517 /* Base commit bump happens silently. */
2518 if (status == GOT_STATUS_BUMP_BASE)
2519 return NULL;
2521 while (path[0] == '/')
2522 path++;
2523 printf("%c %s\n", status, path);
2524 return NULL;
2527 static const struct got_error *
2528 switch_head_ref(struct got_reference *head_ref,
2529 struct got_object_id *commit_id, struct got_worktree *worktree,
2530 struct got_repository *repo)
2532 const struct got_error *err = NULL;
2533 char *base_id_str;
2534 int ref_has_moved = 0;
2536 /* Trivial case: switching between two different references. */
2537 if (strcmp(got_ref_get_name(head_ref),
2538 got_worktree_get_head_ref_name(worktree)) != 0) {
2539 printf("Switching work tree from %s to %s\n",
2540 got_worktree_get_head_ref_name(worktree),
2541 got_ref_get_name(head_ref));
2542 return got_worktree_set_head_ref(worktree, head_ref);
2545 err = check_linear_ancestry(commit_id,
2546 got_worktree_get_base_commit_id(worktree), 0, repo);
2547 if (err) {
2548 if (err->code != GOT_ERR_ANCESTRY)
2549 return err;
2550 ref_has_moved = 1;
2552 if (!ref_has_moved)
2553 return NULL;
2555 /* Switching to a rebased branch with the same reference name. */
2556 err = got_object_id_str(&base_id_str,
2557 got_worktree_get_base_commit_id(worktree));
2558 if (err)
2559 return err;
2560 printf("Reference %s now points at a different branch\n",
2561 got_worktree_get_head_ref_name(worktree));
2562 printf("Switching work tree from %s to %s\n", base_id_str,
2563 got_worktree_get_head_ref_name(worktree));
2564 return NULL;
2567 static const struct got_error *
2568 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2570 const struct got_error *err;
2571 int in_progress;
2573 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2574 if (err)
2575 return err;
2576 if (in_progress)
2577 return got_error(GOT_ERR_REBASING);
2579 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2580 if (err)
2581 return err;
2582 if (in_progress)
2583 return got_error(GOT_ERR_HISTEDIT_BUSY);
2585 return NULL;
2588 static const struct got_error *
2589 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2590 char *argv[], struct got_worktree *worktree)
2592 const struct got_error *err = NULL;
2593 char *path;
2594 int i;
2596 if (argc == 0) {
2597 path = strdup("");
2598 if (path == NULL)
2599 return got_error_from_errno("strdup");
2600 return got_pathlist_append(paths, path, NULL);
2603 for (i = 0; i < argc; i++) {
2604 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2605 if (err)
2606 break;
2607 err = got_pathlist_append(paths, path, NULL);
2608 if (err) {
2609 free(path);
2610 break;
2614 return err;
2617 static const struct got_error *
2618 wrap_not_worktree_error(const struct got_error *orig_err,
2619 const char *cmdname, const char *path)
2621 const struct got_error *err;
2622 struct got_repository *repo;
2623 static char msg[512];
2625 err = got_repo_open(&repo, path, NULL);
2626 if (err)
2627 return orig_err;
2629 snprintf(msg, sizeof(msg),
2630 "'got %s' needs a work tree in addition to a git repository\n"
2631 "Work trees can be checked out from this Git repository with "
2632 "'got checkout'.\n"
2633 "The got(1) manual page contains more information.", cmdname);
2634 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2635 got_repo_close(repo);
2636 return err;
2639 static const struct got_error *
2640 cmd_update(int argc, char *argv[])
2642 const struct got_error *error = NULL;
2643 struct got_repository *repo = NULL;
2644 struct got_worktree *worktree = NULL;
2645 char *worktree_path = NULL;
2646 struct got_object_id *commit_id = NULL;
2647 char *commit_id_str = NULL;
2648 const char *branch_name = NULL;
2649 struct got_reference *head_ref = NULL;
2650 struct got_pathlist_head paths;
2651 struct got_pathlist_entry *pe;
2652 int ch, did_something = 0;
2654 TAILQ_INIT(&paths);
2656 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2657 switch (ch) {
2658 case 'b':
2659 branch_name = optarg;
2660 break;
2661 case 'c':
2662 commit_id_str = strdup(optarg);
2663 if (commit_id_str == NULL)
2664 return got_error_from_errno("strdup");
2665 break;
2666 default:
2667 usage_update();
2668 /* NOTREACHED */
2672 argc -= optind;
2673 argv += optind;
2675 #ifndef PROFILE
2676 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2677 "unveil", NULL) == -1)
2678 err(1, "pledge");
2679 #endif
2680 worktree_path = getcwd(NULL, 0);
2681 if (worktree_path == NULL) {
2682 error = got_error_from_errno("getcwd");
2683 goto done;
2685 error = got_worktree_open(&worktree, worktree_path);
2686 if (error) {
2687 if (error->code == GOT_ERR_NOT_WORKTREE)
2688 error = wrap_not_worktree_error(error, "update",
2689 worktree_path);
2690 goto done;
2693 error = check_rebase_or_histedit_in_progress(worktree);
2694 if (error)
2695 goto done;
2697 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
2698 NULL);
2699 if (error != NULL)
2700 goto done;
2702 error = apply_unveil(got_repo_get_path(repo), 0,
2703 got_worktree_get_root_path(worktree));
2704 if (error)
2705 goto done;
2707 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2708 if (error)
2709 goto done;
2711 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
2712 got_worktree_get_head_ref_name(worktree), 0);
2713 if (error != NULL)
2714 goto done;
2715 if (commit_id_str == NULL) {
2716 error = got_ref_resolve(&commit_id, repo, head_ref);
2717 if (error != NULL)
2718 goto done;
2719 error = got_object_id_str(&commit_id_str, commit_id);
2720 if (error != NULL)
2721 goto done;
2722 } else {
2723 error = got_repo_match_object_id(&commit_id, NULL,
2724 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2725 free(commit_id_str);
2726 commit_id_str = NULL;
2727 if (error)
2728 goto done;
2729 error = got_object_id_str(&commit_id_str, commit_id);
2730 if (error)
2731 goto done;
2734 if (branch_name) {
2735 struct got_object_id *head_commit_id;
2736 TAILQ_FOREACH(pe, &paths, entry) {
2737 if (pe->path_len == 0)
2738 continue;
2739 error = got_error_msg(GOT_ERR_BAD_PATH,
2740 "switching between branches requires that "
2741 "the entire work tree gets updated");
2742 goto done;
2744 error = got_ref_resolve(&head_commit_id, repo, head_ref);
2745 if (error)
2746 goto done;
2747 error = check_linear_ancestry(commit_id, head_commit_id, 0,
2748 repo);
2749 free(head_commit_id);
2750 if (error != NULL)
2751 goto done;
2752 error = check_same_branch(commit_id, head_ref, NULL, repo);
2753 if (error)
2754 goto done;
2755 error = switch_head_ref(head_ref, commit_id, worktree, repo);
2756 if (error)
2757 goto done;
2758 } else {
2759 error = check_linear_ancestry(commit_id,
2760 got_worktree_get_base_commit_id(worktree), 0, repo);
2761 if (error != NULL) {
2762 if (error->code == GOT_ERR_ANCESTRY)
2763 error = got_error(GOT_ERR_BRANCH_MOVED);
2764 goto done;
2766 error = check_same_branch(commit_id, head_ref, NULL, repo);
2767 if (error)
2768 goto done;
2771 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
2772 commit_id) != 0) {
2773 error = got_worktree_set_base_commit_id(worktree, repo,
2774 commit_id);
2775 if (error)
2776 goto done;
2779 error = got_worktree_checkout_files(worktree, &paths, repo,
2780 update_progress, &did_something, check_cancelled, NULL);
2781 if (error != NULL)
2782 goto done;
2784 if (did_something)
2785 printf("Updated to commit %s\n", commit_id_str);
2786 else
2787 printf("Already up-to-date\n");
2788 done:
2789 free(worktree_path);
2790 TAILQ_FOREACH(pe, &paths, entry)
2791 free((char *)pe->path);
2792 got_pathlist_free(&paths);
2793 free(commit_id);
2794 free(commit_id_str);
2795 return error;
2798 static const struct got_error *
2799 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
2800 const char *path, int diff_context, int ignore_whitespace,
2801 struct got_repository *repo)
2803 const struct got_error *err = NULL;
2804 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
2806 if (blob_id1) {
2807 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
2808 if (err)
2809 goto done;
2812 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
2813 if (err)
2814 goto done;
2816 while (path[0] == '/')
2817 path++;
2818 err = got_diff_blob(blob1, blob2, path, path, diff_context,
2819 ignore_whitespace, stdout);
2820 done:
2821 if (blob1)
2822 got_object_blob_close(blob1);
2823 got_object_blob_close(blob2);
2824 return err;
2827 static const struct got_error *
2828 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
2829 const char *path, int diff_context, int ignore_whitespace,
2830 struct got_repository *repo)
2832 const struct got_error *err = NULL;
2833 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
2834 struct got_diff_blob_output_unidiff_arg arg;
2836 if (tree_id1) {
2837 err = got_object_open_as_tree(&tree1, repo, tree_id1);
2838 if (err)
2839 goto done;
2842 err = got_object_open_as_tree(&tree2, repo, tree_id2);
2843 if (err)
2844 goto done;
2846 arg.diff_context = diff_context;
2847 arg.ignore_whitespace = ignore_whitespace;
2848 arg.outfile = stdout;
2849 while (path[0] == '/')
2850 path++;
2851 err = got_diff_tree(tree1, tree2, path, path, repo,
2852 got_diff_blob_output_unidiff, &arg, 1);
2853 done:
2854 if (tree1)
2855 got_object_tree_close(tree1);
2856 if (tree2)
2857 got_object_tree_close(tree2);
2858 return err;
2861 static const struct got_error *
2862 print_patch(struct got_commit_object *commit, struct got_object_id *id,
2863 const char *path, int diff_context, struct got_repository *repo)
2865 const struct got_error *err = NULL;
2866 struct got_commit_object *pcommit = NULL;
2867 char *id_str1 = NULL, *id_str2 = NULL;
2868 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
2869 struct got_object_qid *qid;
2871 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
2872 if (qid != NULL) {
2873 err = got_object_open_as_commit(&pcommit, repo,
2874 qid->id);
2875 if (err)
2876 return err;
2879 if (path && path[0] != '\0') {
2880 int obj_type;
2881 err = got_object_id_by_path(&obj_id2, repo, id, path);
2882 if (err)
2883 goto done;
2884 err = got_object_id_str(&id_str2, obj_id2);
2885 if (err) {
2886 free(obj_id2);
2887 goto done;
2889 if (pcommit) {
2890 err = got_object_id_by_path(&obj_id1, repo,
2891 qid->id, path);
2892 if (err) {
2893 free(obj_id2);
2894 goto done;
2896 err = got_object_id_str(&id_str1, obj_id1);
2897 if (err) {
2898 free(obj_id2);
2899 goto done;
2902 err = got_object_get_type(&obj_type, repo, obj_id2);
2903 if (err) {
2904 free(obj_id2);
2905 goto done;
2907 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2908 switch (obj_type) {
2909 case GOT_OBJ_TYPE_BLOB:
2910 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
2911 0, repo);
2912 break;
2913 case GOT_OBJ_TYPE_TREE:
2914 err = diff_trees(obj_id1, obj_id2, path, diff_context,
2915 0, repo);
2916 break;
2917 default:
2918 err = got_error(GOT_ERR_OBJ_TYPE);
2919 break;
2921 free(obj_id1);
2922 free(obj_id2);
2923 } else {
2924 obj_id2 = got_object_commit_get_tree_id(commit);
2925 err = got_object_id_str(&id_str2, obj_id2);
2926 if (err)
2927 goto done;
2928 obj_id1 = got_object_commit_get_tree_id(pcommit);
2929 err = got_object_id_str(&id_str1, obj_id1);
2930 if (err)
2931 goto done;
2932 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2933 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
2935 done:
2936 free(id_str1);
2937 free(id_str2);
2938 if (pcommit)
2939 got_object_commit_close(pcommit);
2940 return err;
2943 static char *
2944 get_datestr(time_t *time, char *datebuf)
2946 struct tm mytm, *tm;
2947 char *p, *s;
2949 tm = gmtime_r(time, &mytm);
2950 if (tm == NULL)
2951 return NULL;
2952 s = asctime_r(tm, datebuf);
2953 if (s == NULL)
2954 return NULL;
2955 p = strchr(s, '\n');
2956 if (p)
2957 *p = '\0';
2958 return s;
2961 static const struct got_error *
2962 match_logmsg(int *have_match, struct got_object_id *id,
2963 struct got_commit_object *commit, regex_t *regex)
2965 const struct got_error *err = NULL;
2966 regmatch_t regmatch;
2967 char *id_str = NULL, *logmsg = NULL;
2969 *have_match = 0;
2971 err = got_object_id_str(&id_str, id);
2972 if (err)
2973 return err;
2975 err = got_object_commit_get_logmsg(&logmsg, commit);
2976 if (err)
2977 goto done;
2979 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2980 *have_match = 1;
2981 done:
2982 free(id_str);
2983 free(logmsg);
2984 return err;
2987 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
2989 static const struct got_error *
2990 print_commit(struct got_commit_object *commit, struct got_object_id *id,
2991 struct got_repository *repo, const char *path, int show_patch,
2992 int diff_context, struct got_reflist_head *refs)
2994 const struct got_error *err = NULL;
2995 char *id_str, *datestr, *logmsg0, *logmsg, *line;
2996 char datebuf[26];
2997 time_t committer_time;
2998 const char *author, *committer;
2999 char *refs_str = NULL;
3000 struct got_reflist_entry *re;
3002 SIMPLEQ_FOREACH(re, refs, entry) {
3003 char *s;
3004 const char *name;
3005 struct got_tag_object *tag = NULL;
3006 int cmp;
3008 name = got_ref_get_name(re->ref);
3009 if (strcmp(name, GOT_REF_HEAD) == 0)
3010 continue;
3011 if (strncmp(name, "refs/", 5) == 0)
3012 name += 5;
3013 if (strncmp(name, "got/", 4) == 0)
3014 continue;
3015 if (strncmp(name, "heads/", 6) == 0)
3016 name += 6;
3017 if (strncmp(name, "remotes/", 8) == 0)
3018 name += 8;
3019 if (strncmp(name, "tags/", 5) == 0) {
3020 err = got_object_open_as_tag(&tag, repo, re->id);
3021 if (err) {
3022 if (err->code != GOT_ERR_OBJ_TYPE)
3023 return err;
3024 /* Ref points at something other than a tag. */
3025 err = NULL;
3026 tag = NULL;
3029 cmp = got_object_id_cmp(tag ?
3030 got_object_tag_get_object_id(tag) : re->id, id);
3031 if (tag)
3032 got_object_tag_close(tag);
3033 if (cmp != 0)
3034 continue;
3035 s = refs_str;
3036 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3037 name) == -1) {
3038 err = got_error_from_errno("asprintf");
3039 free(s);
3040 return err;
3042 free(s);
3044 err = got_object_id_str(&id_str, id);
3045 if (err)
3046 return err;
3048 printf(GOT_COMMIT_SEP_STR);
3049 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3050 refs_str ? refs_str : "", refs_str ? ")" : "");
3051 free(id_str);
3052 id_str = NULL;
3053 free(refs_str);
3054 refs_str = NULL;
3055 printf("from: %s\n", got_object_commit_get_author(commit));
3056 committer_time = got_object_commit_get_committer_time(commit);
3057 datestr = get_datestr(&committer_time, datebuf);
3058 if (datestr)
3059 printf("date: %s UTC\n", datestr);
3060 author = got_object_commit_get_author(commit);
3061 committer = got_object_commit_get_committer(commit);
3062 if (strcmp(author, committer) != 0)
3063 printf("via: %s\n", committer);
3064 if (got_object_commit_get_nparents(commit) > 1) {
3065 const struct got_object_id_queue *parent_ids;
3066 struct got_object_qid *qid;
3067 int n = 1;
3068 parent_ids = got_object_commit_get_parent_ids(commit);
3069 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3070 err = got_object_id_str(&id_str, qid->id);
3071 if (err)
3072 return err;
3073 printf("parent %d: %s\n", n++, id_str);
3074 free(id_str);
3078 err = got_object_commit_get_logmsg(&logmsg0, commit);
3079 if (err)
3080 return err;
3082 logmsg = logmsg0;
3083 do {
3084 line = strsep(&logmsg, "\n");
3085 if (line)
3086 printf(" %s\n", line);
3087 } while (line);
3088 free(logmsg0);
3090 if (show_patch) {
3091 err = print_patch(commit, id, path, diff_context, repo);
3092 if (err == 0)
3093 printf("\n");
3096 if (fflush(stdout) != 0 && err == NULL)
3097 err = got_error_from_errno("fflush");
3098 return err;
3101 static const struct got_error *
3102 print_commits(struct got_object_id *root_id, struct got_repository *repo,
3103 const char *path, int show_patch, const char *search_pattern,
3104 int diff_context, int limit, int log_branches,
3105 struct got_reflist_head *refs)
3107 const struct got_error *err;
3108 struct got_commit_graph *graph;
3109 regex_t regex;
3110 int have_match;
3112 if (search_pattern &&
3113 regcomp(&regex, search_pattern, REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3114 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3116 err = got_commit_graph_open(&graph, path, !log_branches);
3117 if (err)
3118 return err;
3119 err = got_commit_graph_iter_start(graph, root_id, repo,
3120 check_cancelled, NULL);
3121 if (err)
3122 goto done;
3123 for (;;) {
3124 struct got_commit_object *commit;
3125 struct got_object_id *id;
3127 if (sigint_received || sigpipe_received)
3128 break;
3130 err = got_commit_graph_iter_next(&id, graph, repo,
3131 check_cancelled, NULL);
3132 if (err) {
3133 if (err->code == GOT_ERR_ITER_COMPLETED)
3134 err = NULL;
3135 break;
3137 if (id == NULL)
3138 break;
3140 err = got_object_open_as_commit(&commit, repo, id);
3141 if (err)
3142 break;
3144 if (search_pattern) {
3145 err = match_logmsg(&have_match, id, commit, &regex);
3146 if (err) {
3147 got_object_commit_close(commit);
3148 break;
3150 if (have_match == 0) {
3151 got_object_commit_close(commit);
3152 continue;
3156 err = print_commit(commit, id, repo, path, show_patch,
3157 diff_context, refs);
3158 got_object_commit_close(commit);
3159 if (err || (limit && --limit == 0))
3160 break;
3162 done:
3163 if (search_pattern)
3164 regfree(&regex);
3165 got_commit_graph_close(graph);
3166 return err;
3169 __dead static void
3170 usage_log(void)
3172 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] [-p] "
3173 "[-s search-pattern] [-r repository-path] [path]\n", getprogname());
3174 exit(1);
3177 static int
3178 get_default_log_limit(void)
3180 const char *got_default_log_limit;
3181 long long n;
3182 const char *errstr;
3184 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3185 if (got_default_log_limit == NULL)
3186 return 0;
3187 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3188 if (errstr != NULL)
3189 return 0;
3190 return n;
3193 static const struct got_error *
3194 cmd_log(int argc, char *argv[])
3196 const struct got_error *error;
3197 struct got_repository *repo = NULL;
3198 struct got_worktree *worktree = NULL;
3199 struct got_commit_object *commit = NULL;
3200 struct got_object_id *id = NULL;
3201 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3202 const char *start_commit = NULL, *search_pattern = NULL;
3203 int diff_context = -1, ch;
3204 int show_patch = 0, limit = 0, log_branches = 0;
3205 const char *errstr;
3206 struct got_reflist_head refs;
3208 SIMPLEQ_INIT(&refs);
3210 #ifndef PROFILE
3211 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3212 NULL)
3213 == -1)
3214 err(1, "pledge");
3215 #endif
3217 limit = get_default_log_limit();
3219 while ((ch = getopt(argc, argv, "bpc:C:l:r:s:")) != -1) {
3220 switch (ch) {
3221 case 'p':
3222 show_patch = 1;
3223 break;
3224 case 'c':
3225 start_commit = optarg;
3226 break;
3227 case 'C':
3228 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3229 &errstr);
3230 if (errstr != NULL)
3231 err(1, "-C option %s", errstr);
3232 break;
3233 case 'l':
3234 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3235 if (errstr != NULL)
3236 err(1, "-l option %s", errstr);
3237 break;
3238 case 'b':
3239 log_branches = 1;
3240 break;
3241 case 'r':
3242 repo_path = realpath(optarg, NULL);
3243 if (repo_path == NULL)
3244 return got_error_from_errno2("realpath",
3245 optarg);
3246 got_path_strip_trailing_slashes(repo_path);
3247 break;
3248 case 's':
3249 search_pattern = optarg;
3250 break;
3251 default:
3252 usage_log();
3253 /* NOTREACHED */
3257 argc -= optind;
3258 argv += optind;
3260 if (diff_context == -1)
3261 diff_context = 3;
3262 else if (!show_patch)
3263 errx(1, "-C reguires -p");
3265 cwd = getcwd(NULL, 0);
3266 if (cwd == NULL) {
3267 error = got_error_from_errno("getcwd");
3268 goto done;
3271 error = got_worktree_open(&worktree, cwd);
3272 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3273 goto done;
3274 error = NULL;
3276 if (argc == 0) {
3277 path = strdup("");
3278 if (path == NULL) {
3279 error = got_error_from_errno("strdup");
3280 goto done;
3282 } else if (argc == 1) {
3283 if (worktree) {
3284 error = got_worktree_resolve_path(&path, worktree,
3285 argv[0]);
3286 if (error)
3287 goto done;
3288 } else {
3289 path = strdup(argv[0]);
3290 if (path == NULL) {
3291 error = got_error_from_errno("strdup");
3292 goto done;
3295 } else
3296 usage_log();
3298 if (repo_path == NULL) {
3299 repo_path = worktree ?
3300 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3302 if (repo_path == NULL) {
3303 error = got_error_from_errno("strdup");
3304 goto done;
3307 error = got_repo_open(&repo, repo_path, NULL);
3308 if (error != NULL)
3309 goto done;
3311 error = apply_unveil(got_repo_get_path(repo), 1,
3312 worktree ? got_worktree_get_root_path(worktree) : NULL);
3313 if (error)
3314 goto done;
3316 if (start_commit == NULL) {
3317 struct got_reference *head_ref;
3318 error = got_ref_open(&head_ref, repo,
3319 worktree ? got_worktree_get_head_ref_name(worktree)
3320 : GOT_REF_HEAD, 0);
3321 if (error != NULL)
3322 return error;
3323 error = got_ref_resolve(&id, repo, head_ref);
3324 got_ref_close(head_ref);
3325 if (error != NULL)
3326 return error;
3327 error = got_object_open_as_commit(&commit, repo, id);
3328 } else {
3329 struct got_reference *ref;
3330 error = got_ref_open(&ref, repo, start_commit, 0);
3331 if (error == NULL) {
3332 int obj_type;
3333 error = got_ref_resolve(&id, repo, ref);
3334 got_ref_close(ref);
3335 if (error != NULL)
3336 goto done;
3337 error = got_object_get_type(&obj_type, repo, id);
3338 if (error != NULL)
3339 goto done;
3340 if (obj_type == GOT_OBJ_TYPE_TAG) {
3341 struct got_tag_object *tag;
3342 error = got_object_open_as_tag(&tag, repo, id);
3343 if (error != NULL)
3344 goto done;
3345 if (got_object_tag_get_object_type(tag) !=
3346 GOT_OBJ_TYPE_COMMIT) {
3347 got_object_tag_close(tag);
3348 error = got_error(GOT_ERR_OBJ_TYPE);
3349 goto done;
3351 free(id);
3352 id = got_object_id_dup(
3353 got_object_tag_get_object_id(tag));
3354 if (id == NULL)
3355 error = got_error_from_errno(
3356 "got_object_id_dup");
3357 got_object_tag_close(tag);
3358 if (error)
3359 goto done;
3360 } else if (obj_type != GOT_OBJ_TYPE_COMMIT) {
3361 error = got_error(GOT_ERR_OBJ_TYPE);
3362 goto done;
3364 error = got_object_open_as_commit(&commit, repo, id);
3365 if (error != NULL)
3366 goto done;
3368 if (commit == NULL) {
3369 error = got_repo_match_object_id_prefix(&id,
3370 start_commit, GOT_OBJ_TYPE_COMMIT, repo);
3371 if (error != NULL)
3372 return error;
3375 if (error != NULL)
3376 goto done;
3378 if (worktree) {
3379 const char *prefix = got_worktree_get_path_prefix(worktree);
3380 char *p;
3381 if (asprintf(&p, "%s%s%s", prefix,
3382 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3383 error = got_error_from_errno("asprintf");
3384 goto done;
3386 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3387 free(p);
3388 } else
3389 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3390 if (error != NULL)
3391 goto done;
3392 if (in_repo_path) {
3393 free(path);
3394 path = in_repo_path;
3397 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3398 if (error)
3399 goto done;
3401 error = print_commits(id, repo, path, show_patch, search_pattern,
3402 diff_context, limit, log_branches, &refs);
3403 done:
3404 free(path);
3405 free(repo_path);
3406 free(cwd);
3407 free(id);
3408 if (worktree)
3409 got_worktree_close(worktree);
3410 if (repo) {
3411 const struct got_error *repo_error;
3412 repo_error = got_repo_close(repo);
3413 if (error == NULL)
3414 error = repo_error;
3416 got_ref_list_free(&refs);
3417 return error;
3420 __dead static void
3421 usage_diff(void)
3423 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3424 "[-w] [object1 object2 | path]\n", getprogname());
3425 exit(1);
3428 struct print_diff_arg {
3429 struct got_repository *repo;
3430 struct got_worktree *worktree;
3431 int diff_context;
3432 const char *id_str;
3433 int header_shown;
3434 int diff_staged;
3435 int ignore_whitespace;
3438 static const struct got_error *
3439 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3440 const char *path, struct got_object_id *blob_id,
3441 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3442 int dirfd, const char *de_name)
3444 struct print_diff_arg *a = arg;
3445 const struct got_error *err = NULL;
3446 struct got_blob_object *blob1 = NULL;
3447 int fd = -1;
3448 FILE *f2 = NULL;
3449 char *abspath = NULL, *label1 = NULL;
3450 struct stat sb;
3452 if (a->diff_staged) {
3453 if (staged_status != GOT_STATUS_MODIFY &&
3454 staged_status != GOT_STATUS_ADD &&
3455 staged_status != GOT_STATUS_DELETE)
3456 return NULL;
3457 } else {
3458 if (staged_status == GOT_STATUS_DELETE)
3459 return NULL;
3460 if (status == GOT_STATUS_NONEXISTENT)
3461 return got_error_set_errno(ENOENT, path);
3462 if (status != GOT_STATUS_MODIFY &&
3463 status != GOT_STATUS_ADD &&
3464 status != GOT_STATUS_DELETE &&
3465 status != GOT_STATUS_CONFLICT)
3466 return NULL;
3469 if (!a->header_shown) {
3470 printf("diff %s %s%s\n", a->id_str,
3471 got_worktree_get_root_path(a->worktree),
3472 a->diff_staged ? " (staged changes)" : "");
3473 a->header_shown = 1;
3476 if (a->diff_staged) {
3477 const char *label1 = NULL, *label2 = NULL;
3478 switch (staged_status) {
3479 case GOT_STATUS_MODIFY:
3480 label1 = path;
3481 label2 = path;
3482 break;
3483 case GOT_STATUS_ADD:
3484 label2 = path;
3485 break;
3486 case GOT_STATUS_DELETE:
3487 label1 = path;
3488 break;
3489 default:
3490 return got_error(GOT_ERR_FILE_STATUS);
3492 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
3493 label1, label2, a->diff_context, a->ignore_whitespace,
3494 a->repo, stdout);
3497 if (staged_status == GOT_STATUS_ADD ||
3498 staged_status == GOT_STATUS_MODIFY) {
3499 char *id_str;
3500 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
3501 8192);
3502 if (err)
3503 goto done;
3504 err = got_object_id_str(&id_str, staged_blob_id);
3505 if (err)
3506 goto done;
3507 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
3508 err = got_error_from_errno("asprintf");
3509 free(id_str);
3510 goto done;
3512 free(id_str);
3513 } else if (status != GOT_STATUS_ADD) {
3514 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
3515 if (err)
3516 goto done;
3519 if (status != GOT_STATUS_DELETE) {
3520 if (asprintf(&abspath, "%s/%s",
3521 got_worktree_get_root_path(a->worktree), path) == -1) {
3522 err = got_error_from_errno("asprintf");
3523 goto done;
3526 if (dirfd != -1) {
3527 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
3528 if (fd == -1) {
3529 err = got_error_from_errno2("openat", abspath);
3530 goto done;
3532 } else {
3533 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
3534 if (fd == -1) {
3535 err = got_error_from_errno2("open", abspath);
3536 goto done;
3539 if (fstat(fd, &sb) == -1) {
3540 err = got_error_from_errno2("fstat", abspath);
3541 goto done;
3543 f2 = fdopen(fd, "r");
3544 if (f2 == NULL) {
3545 err = got_error_from_errno2("fdopen", abspath);
3546 goto done;
3548 fd = -1;
3549 } else
3550 sb.st_size = 0;
3552 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
3553 a->diff_context, a->ignore_whitespace, stdout);
3554 done:
3555 if (blob1)
3556 got_object_blob_close(blob1);
3557 if (f2 && fclose(f2) == EOF && err == NULL)
3558 err = got_error_from_errno("fclose");
3559 if (fd != -1 && close(fd) == -1 && err == NULL)
3560 err = got_error_from_errno("close");
3561 free(abspath);
3562 return err;
3565 static const struct got_error *
3566 cmd_diff(int argc, char *argv[])
3568 const struct got_error *error;
3569 struct got_repository *repo = NULL;
3570 struct got_worktree *worktree = NULL;
3571 char *cwd = NULL, *repo_path = NULL;
3572 struct got_object_id *id1 = NULL, *id2 = NULL;
3573 const char *id_str1 = NULL, *id_str2 = NULL;
3574 char *label1 = NULL, *label2 = NULL;
3575 int type1, type2;
3576 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
3577 const char *errstr;
3578 char *path = NULL;
3580 #ifndef PROFILE
3581 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3582 NULL) == -1)
3583 err(1, "pledge");
3584 #endif
3586 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
3587 switch (ch) {
3588 case 'C':
3589 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3590 &errstr);
3591 if (errstr != NULL)
3592 err(1, "-C option %s", errstr);
3593 break;
3594 case 'r':
3595 repo_path = realpath(optarg, NULL);
3596 if (repo_path == NULL)
3597 return got_error_from_errno2("realpath",
3598 optarg);
3599 got_path_strip_trailing_slashes(repo_path);
3600 break;
3601 case 's':
3602 diff_staged = 1;
3603 break;
3604 case 'w':
3605 ignore_whitespace = 1;
3606 break;
3607 default:
3608 usage_diff();
3609 /* NOTREACHED */
3613 argc -= optind;
3614 argv += optind;
3616 cwd = getcwd(NULL, 0);
3617 if (cwd == NULL) {
3618 error = got_error_from_errno("getcwd");
3619 goto done;
3621 if (argc <= 1) {
3622 if (repo_path)
3623 errx(1,
3624 "-r option can't be used when diffing a work tree");
3625 error = got_worktree_open(&worktree, cwd);
3626 if (error) {
3627 if (error->code == GOT_ERR_NOT_WORKTREE)
3628 error = wrap_not_worktree_error(error, "diff",
3629 cwd);
3630 goto done;
3632 repo_path = strdup(got_worktree_get_repo_path(worktree));
3633 if (repo_path == NULL) {
3634 error = got_error_from_errno("strdup");
3635 goto done;
3637 if (argc == 1) {
3638 error = got_worktree_resolve_path(&path, worktree,
3639 argv[0]);
3640 if (error)
3641 goto done;
3642 } else {
3643 path = strdup("");
3644 if (path == NULL) {
3645 error = got_error_from_errno("strdup");
3646 goto done;
3649 } else if (argc == 2) {
3650 if (diff_staged)
3651 errx(1, "-s option can't be used when diffing "
3652 "objects in repository");
3653 id_str1 = argv[0];
3654 id_str2 = argv[1];
3655 if (repo_path == NULL) {
3656 error = got_worktree_open(&worktree, cwd);
3657 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3658 goto done;
3659 if (worktree) {
3660 repo_path = strdup(
3661 got_worktree_get_repo_path(worktree));
3662 if (repo_path == NULL) {
3663 error = got_error_from_errno("strdup");
3664 goto done;
3666 } else {
3667 repo_path = strdup(cwd);
3668 if (repo_path == NULL) {
3669 error = got_error_from_errno("strdup");
3670 goto done;
3674 } else
3675 usage_diff();
3677 error = got_repo_open(&repo, repo_path, NULL);
3678 free(repo_path);
3679 if (error != NULL)
3680 goto done;
3682 error = apply_unveil(got_repo_get_path(repo), 1,
3683 worktree ? got_worktree_get_root_path(worktree) : NULL);
3684 if (error)
3685 goto done;
3687 if (argc <= 1) {
3688 struct print_diff_arg arg;
3689 struct got_pathlist_head paths;
3690 char *id_str;
3692 TAILQ_INIT(&paths);
3694 error = got_object_id_str(&id_str,
3695 got_worktree_get_base_commit_id(worktree));
3696 if (error)
3697 goto done;
3698 arg.repo = repo;
3699 arg.worktree = worktree;
3700 arg.diff_context = diff_context;
3701 arg.id_str = id_str;
3702 arg.header_shown = 0;
3703 arg.diff_staged = diff_staged;
3704 arg.ignore_whitespace = ignore_whitespace;
3706 error = got_pathlist_append(&paths, path, NULL);
3707 if (error)
3708 goto done;
3710 error = got_worktree_status(worktree, &paths, repo, print_diff,
3711 &arg, check_cancelled, NULL);
3712 free(id_str);
3713 got_pathlist_free(&paths);
3714 goto done;
3717 error = got_repo_match_object_id(&id1, &label1, id_str1,
3718 GOT_OBJ_TYPE_ANY, 1, repo);
3719 if (error)
3720 goto done;
3722 error = got_repo_match_object_id(&id2, &label2, id_str2,
3723 GOT_OBJ_TYPE_ANY, 1, repo);
3724 if (error)
3725 goto done;
3727 error = got_object_get_type(&type1, repo, id1);
3728 if (error)
3729 goto done;
3731 error = got_object_get_type(&type2, repo, id2);
3732 if (error)
3733 goto done;
3735 if (type1 != type2) {
3736 error = got_error(GOT_ERR_OBJ_TYPE);
3737 goto done;
3740 switch (type1) {
3741 case GOT_OBJ_TYPE_BLOB:
3742 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
3743 diff_context, ignore_whitespace, repo, stdout);
3744 break;
3745 case GOT_OBJ_TYPE_TREE:
3746 error = got_diff_objects_as_trees(id1, id2, "", "",
3747 diff_context, ignore_whitespace, repo, stdout);
3748 break;
3749 case GOT_OBJ_TYPE_COMMIT:
3750 printf("diff %s %s\n", label1, label2);
3751 error = got_diff_objects_as_commits(id1, id2, diff_context,
3752 ignore_whitespace, repo, stdout);
3753 break;
3754 default:
3755 error = got_error(GOT_ERR_OBJ_TYPE);
3757 done:
3758 free(label1);
3759 free(label2);
3760 free(id1);
3761 free(id2);
3762 free(path);
3763 if (worktree)
3764 got_worktree_close(worktree);
3765 if (repo) {
3766 const struct got_error *repo_error;
3767 repo_error = got_repo_close(repo);
3768 if (error == NULL)
3769 error = repo_error;
3771 return error;
3774 __dead static void
3775 usage_blame(void)
3777 fprintf(stderr,
3778 "usage: %s blame [-c commit] [-r repository-path] path\n",
3779 getprogname());
3780 exit(1);
3783 struct blame_line {
3784 int annotated;
3785 char *id_str;
3786 char *committer;
3787 char datebuf[11]; /* YYYY-MM-DD + NUL */
3790 struct blame_cb_args {
3791 struct blame_line *lines;
3792 int nlines;
3793 int nlines_prec;
3794 int lineno_cur;
3795 off_t *line_offsets;
3796 FILE *f;
3797 struct got_repository *repo;
3800 static const struct got_error *
3801 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
3803 const struct got_error *err = NULL;
3804 struct blame_cb_args *a = arg;
3805 struct blame_line *bline;
3806 char *line = NULL;
3807 size_t linesize = 0;
3808 struct got_commit_object *commit = NULL;
3809 off_t offset;
3810 struct tm tm;
3811 time_t committer_time;
3813 if (nlines != a->nlines ||
3814 (lineno != -1 && lineno < 1) || lineno > a->nlines)
3815 return got_error(GOT_ERR_RANGE);
3817 if (sigint_received)
3818 return got_error(GOT_ERR_ITER_COMPLETED);
3820 if (lineno == -1)
3821 return NULL; /* no change in this commit */
3823 /* Annotate this line. */
3824 bline = &a->lines[lineno - 1];
3825 if (bline->annotated)
3826 return NULL;
3827 err = got_object_id_str(&bline->id_str, id);
3828 if (err)
3829 return err;
3831 err = got_object_open_as_commit(&commit, a->repo, id);
3832 if (err)
3833 goto done;
3835 bline->committer = strdup(got_object_commit_get_committer(commit));
3836 if (bline->committer == NULL) {
3837 err = got_error_from_errno("strdup");
3838 goto done;
3841 committer_time = got_object_commit_get_committer_time(commit);
3842 if (localtime_r(&committer_time, &tm) == NULL)
3843 return got_error_from_errno("localtime_r");
3844 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
3845 &tm) >= sizeof(bline->datebuf)) {
3846 err = got_error(GOT_ERR_NO_SPACE);
3847 goto done;
3849 bline->annotated = 1;
3851 /* Print lines annotated so far. */
3852 bline = &a->lines[a->lineno_cur - 1];
3853 if (!bline->annotated)
3854 goto done;
3856 offset = a->line_offsets[a->lineno_cur - 1];
3857 if (fseeko(a->f, offset, SEEK_SET) == -1) {
3858 err = got_error_from_errno("fseeko");
3859 goto done;
3862 while (bline->annotated) {
3863 char *smallerthan, *at, *nl, *committer;
3864 size_t len;
3866 if (getline(&line, &linesize, a->f) == -1) {
3867 if (ferror(a->f))
3868 err = got_error_from_errno("getline");
3869 break;
3872 committer = bline->committer;
3873 smallerthan = strchr(committer, '<');
3874 if (smallerthan && smallerthan[1] != '\0')
3875 committer = smallerthan + 1;
3876 at = strchr(committer, '@');
3877 if (at)
3878 *at = '\0';
3879 len = strlen(committer);
3880 if (len >= 9)
3881 committer[8] = '\0';
3883 nl = strchr(line, '\n');
3884 if (nl)
3885 *nl = '\0';
3886 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
3887 bline->id_str, bline->datebuf, committer, line);
3889 a->lineno_cur++;
3890 bline = &a->lines[a->lineno_cur - 1];
3892 done:
3893 if (commit)
3894 got_object_commit_close(commit);
3895 free(line);
3896 return err;
3899 static const struct got_error *
3900 cmd_blame(int argc, char *argv[])
3902 const struct got_error *error;
3903 struct got_repository *repo = NULL;
3904 struct got_worktree *worktree = NULL;
3905 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
3906 struct got_object_id *obj_id = NULL;
3907 struct got_object_id *commit_id = NULL;
3908 struct got_blob_object *blob = NULL;
3909 char *commit_id_str = NULL;
3910 struct blame_cb_args bca;
3911 int ch, obj_type, i;
3912 size_t filesize;
3914 memset(&bca, 0, sizeof(bca));
3916 #ifndef PROFILE
3917 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3918 NULL) == -1)
3919 err(1, "pledge");
3920 #endif
3922 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
3923 switch (ch) {
3924 case 'c':
3925 commit_id_str = optarg;
3926 break;
3927 case 'r':
3928 repo_path = realpath(optarg, NULL);
3929 if (repo_path == NULL)
3930 return got_error_from_errno2("realpath",
3931 optarg);
3932 got_path_strip_trailing_slashes(repo_path);
3933 break;
3934 default:
3935 usage_blame();
3936 /* NOTREACHED */
3940 argc -= optind;
3941 argv += optind;
3943 if (argc == 1)
3944 path = argv[0];
3945 else
3946 usage_blame();
3948 cwd = getcwd(NULL, 0);
3949 if (cwd == NULL) {
3950 error = got_error_from_errno("getcwd");
3951 goto done;
3953 if (repo_path == NULL) {
3954 error = got_worktree_open(&worktree, cwd);
3955 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3956 goto done;
3957 else
3958 error = NULL;
3959 if (worktree) {
3960 repo_path =
3961 strdup(got_worktree_get_repo_path(worktree));
3962 if (repo_path == NULL) {
3963 error = got_error_from_errno("strdup");
3964 if (error)
3965 goto done;
3967 } else {
3968 repo_path = strdup(cwd);
3969 if (repo_path == NULL) {
3970 error = got_error_from_errno("strdup");
3971 goto done;
3976 error = got_repo_open(&repo, repo_path, NULL);
3977 if (error != NULL)
3978 goto done;
3980 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
3981 if (error)
3982 goto done;
3984 if (worktree) {
3985 const char *prefix = got_worktree_get_path_prefix(worktree);
3986 char *p, *worktree_subdir = cwd +
3987 strlen(got_worktree_get_root_path(worktree));
3988 if (asprintf(&p, "%s%s%s%s%s",
3989 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
3990 worktree_subdir, worktree_subdir[0] ? "/" : "",
3991 path) == -1) {
3992 error = got_error_from_errno("asprintf");
3993 goto done;
3995 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3996 free(p);
3997 } else {
3998 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4000 if (error)
4001 goto done;
4003 if (commit_id_str == NULL) {
4004 struct got_reference *head_ref;
4005 error = got_ref_open(&head_ref, repo, worktree ?
4006 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4007 if (error != NULL)
4008 goto done;
4009 error = got_ref_resolve(&commit_id, repo, head_ref);
4010 got_ref_close(head_ref);
4011 if (error != NULL)
4012 goto done;
4013 } else {
4014 error = got_repo_match_object_id(&commit_id, NULL,
4015 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4016 if (error)
4017 goto done;
4020 error = got_object_id_by_path(&obj_id, repo, commit_id, in_repo_path);
4021 if (error)
4022 goto done;
4024 error = got_object_get_type(&obj_type, repo, obj_id);
4025 if (error)
4026 goto done;
4028 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4029 error = got_error(GOT_ERR_OBJ_TYPE);
4030 goto done;
4033 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4034 if (error)
4035 goto done;
4036 bca.f = got_opentemp();
4037 if (bca.f == NULL) {
4038 error = got_error_from_errno("got_opentemp");
4039 goto done;
4041 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4042 &bca.line_offsets, bca.f, blob);
4043 if (error || bca.nlines == 0)
4044 goto done;
4046 /* Don't include \n at EOF in the blame line count. */
4047 if (bca.line_offsets[bca.nlines - 1] == filesize)
4048 bca.nlines--;
4050 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4051 if (bca.lines == NULL) {
4052 error = got_error_from_errno("calloc");
4053 goto done;
4055 bca.lineno_cur = 1;
4056 bca.nlines_prec = 0;
4057 i = bca.nlines;
4058 while (i > 0) {
4059 i /= 10;
4060 bca.nlines_prec++;
4062 bca.repo = repo;
4064 error = got_blame(in_repo_path, commit_id, repo, blame_cb, &bca,
4065 check_cancelled, NULL);
4066 done:
4067 free(in_repo_path);
4068 free(repo_path);
4069 free(cwd);
4070 free(commit_id);
4071 free(obj_id);
4072 if (blob)
4073 got_object_blob_close(blob);
4074 if (worktree)
4075 got_worktree_close(worktree);
4076 if (repo) {
4077 const struct got_error *repo_error;
4078 repo_error = got_repo_close(repo);
4079 if (error == NULL)
4080 error = repo_error;
4082 if (bca.lines) {
4083 for (i = 0; i < bca.nlines; i++) {
4084 struct blame_line *bline = &bca.lines[i];
4085 free(bline->id_str);
4086 free(bline->committer);
4088 free(bca.lines);
4090 free(bca.line_offsets);
4091 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4092 error = got_error_from_errno("fclose");
4093 return error;
4096 __dead static void
4097 usage_tree(void)
4099 fprintf(stderr,
4100 "usage: %s tree [-c commit] [-r repository-path] [-iR] path\n",
4101 getprogname());
4102 exit(1);
4105 static void
4106 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4107 const char *root_path)
4109 int is_root_path = (strcmp(path, root_path) == 0);
4110 const char *modestr = "";
4111 mode_t mode = got_tree_entry_get_mode(te);
4113 path += strlen(root_path);
4114 while (path[0] == '/')
4115 path++;
4117 if (got_object_tree_entry_is_submodule(te))
4118 modestr = "$";
4119 else if (S_ISLNK(mode))
4120 modestr = "@";
4121 else if (S_ISDIR(mode))
4122 modestr = "/";
4123 else if (mode & S_IXUSR)
4124 modestr = "*";
4126 printf("%s%s%s%s%s\n", id ? id : "", path,
4127 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr);
4130 static const struct got_error *
4131 print_tree(const char *path, struct got_object_id *commit_id,
4132 int show_ids, int recurse, const char *root_path,
4133 struct got_repository *repo)
4135 const struct got_error *err = NULL;
4136 struct got_object_id *tree_id = NULL;
4137 struct got_tree_object *tree = NULL;
4138 int nentries, i;
4140 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4141 if (err)
4142 goto done;
4144 err = got_object_open_as_tree(&tree, repo, tree_id);
4145 if (err)
4146 goto done;
4147 nentries = got_object_tree_get_nentries(tree);
4148 for (i = 0; i < nentries; i++) {
4149 struct got_tree_entry *te;
4150 char *id = NULL;
4152 if (sigint_received || sigpipe_received)
4153 break;
4155 te = got_object_tree_get_entry(tree, i);
4156 if (show_ids) {
4157 char *id_str;
4158 err = got_object_id_str(&id_str,
4159 got_tree_entry_get_id(te));
4160 if (err)
4161 goto done;
4162 if (asprintf(&id, "%s ", id_str) == -1) {
4163 err = got_error_from_errno("asprintf");
4164 free(id_str);
4165 goto done;
4167 free(id_str);
4169 print_entry(te, id, path, root_path);
4170 free(id);
4172 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4173 char *child_path;
4174 if (asprintf(&child_path, "%s%s%s", path,
4175 path[0] == '/' && path[1] == '\0' ? "" : "/",
4176 got_tree_entry_get_name(te)) == -1) {
4177 err = got_error_from_errno("asprintf");
4178 goto done;
4180 err = print_tree(child_path, commit_id, show_ids, 1,
4181 root_path, repo);
4182 free(child_path);
4183 if (err)
4184 goto done;
4187 done:
4188 if (tree)
4189 got_object_tree_close(tree);
4190 free(tree_id);
4191 return err;
4194 static const struct got_error *
4195 cmd_tree(int argc, char *argv[])
4197 const struct got_error *error;
4198 struct got_repository *repo = NULL;
4199 struct got_worktree *worktree = NULL;
4200 const char *path, *refname = NULL;
4201 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4202 struct got_object_id *commit_id = NULL;
4203 char *commit_id_str = NULL;
4204 int show_ids = 0, recurse = 0;
4205 int ch;
4207 #ifndef PROFILE
4208 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4209 NULL) == -1)
4210 err(1, "pledge");
4211 #endif
4213 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4214 switch (ch) {
4215 case 'c':
4216 commit_id_str = optarg;
4217 break;
4218 case 'r':
4219 repo_path = realpath(optarg, NULL);
4220 if (repo_path == NULL)
4221 return got_error_from_errno2("realpath",
4222 optarg);
4223 got_path_strip_trailing_slashes(repo_path);
4224 break;
4225 case 'i':
4226 show_ids = 1;
4227 break;
4228 case 'R':
4229 recurse = 1;
4230 break;
4231 default:
4232 usage_tree();
4233 /* NOTREACHED */
4237 argc -= optind;
4238 argv += optind;
4240 if (argc == 1)
4241 path = argv[0];
4242 else if (argc > 1)
4243 usage_tree();
4244 else
4245 path = NULL;
4247 cwd = getcwd(NULL, 0);
4248 if (cwd == NULL) {
4249 error = got_error_from_errno("getcwd");
4250 goto done;
4252 if (repo_path == NULL) {
4253 error = got_worktree_open(&worktree, cwd);
4254 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4255 goto done;
4256 else
4257 error = NULL;
4258 if (worktree) {
4259 repo_path =
4260 strdup(got_worktree_get_repo_path(worktree));
4261 if (repo_path == NULL)
4262 error = got_error_from_errno("strdup");
4263 if (error)
4264 goto done;
4265 } else {
4266 repo_path = strdup(cwd);
4267 if (repo_path == NULL) {
4268 error = got_error_from_errno("strdup");
4269 goto done;
4274 error = got_repo_open(&repo, repo_path, NULL);
4275 if (error != NULL)
4276 goto done;
4278 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4279 if (error)
4280 goto done;
4282 if (path == NULL) {
4283 if (worktree) {
4284 char *p, *worktree_subdir = cwd +
4285 strlen(got_worktree_get_root_path(worktree));
4286 if (asprintf(&p, "%s/%s",
4287 got_worktree_get_path_prefix(worktree),
4288 worktree_subdir) == -1) {
4289 error = got_error_from_errno("asprintf");
4290 goto done;
4292 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4293 free(p);
4294 if (error)
4295 goto done;
4296 } else
4297 path = "/";
4299 if (in_repo_path == NULL) {
4300 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4301 if (error != NULL)
4302 goto done;
4305 if (commit_id_str == NULL) {
4306 struct got_reference *head_ref;
4307 if (worktree)
4308 refname = got_worktree_get_head_ref_name(worktree);
4309 else
4310 refname = GOT_REF_HEAD;
4311 error = got_ref_open(&head_ref, repo, refname, 0);
4312 if (error != NULL)
4313 goto done;
4314 error = got_ref_resolve(&commit_id, repo, head_ref);
4315 got_ref_close(head_ref);
4316 if (error != NULL)
4317 goto done;
4318 } else {
4319 error = got_repo_match_object_id(&commit_id, NULL,
4320 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4321 if (error)
4322 goto done;
4325 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4326 in_repo_path, repo);
4327 done:
4328 free(in_repo_path);
4329 free(repo_path);
4330 free(cwd);
4331 free(commit_id);
4332 if (worktree)
4333 got_worktree_close(worktree);
4334 if (repo) {
4335 const struct got_error *repo_error;
4336 repo_error = got_repo_close(repo);
4337 if (error == NULL)
4338 error = repo_error;
4340 return error;
4343 __dead static void
4344 usage_status(void)
4346 fprintf(stderr, "usage: %s status [path ...]\n", getprogname());
4347 exit(1);
4350 static const struct got_error *
4351 print_status(void *arg, unsigned char status, unsigned char staged_status,
4352 const char *path, struct got_object_id *blob_id,
4353 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4354 int dirfd, const char *de_name)
4356 if (status == staged_status && (status == GOT_STATUS_DELETE))
4357 status = GOT_STATUS_NO_CHANGE;
4358 printf("%c%c %s\n", status, staged_status, path);
4359 return NULL;
4362 static const struct got_error *
4363 cmd_status(int argc, char *argv[])
4365 const struct got_error *error = NULL;
4366 struct got_repository *repo = NULL;
4367 struct got_worktree *worktree = NULL;
4368 char *cwd = NULL;
4369 struct got_pathlist_head paths;
4370 struct got_pathlist_entry *pe;
4371 int ch;
4373 TAILQ_INIT(&paths);
4375 while ((ch = getopt(argc, argv, "")) != -1) {
4376 switch (ch) {
4377 default:
4378 usage_status();
4379 /* NOTREACHED */
4383 argc -= optind;
4384 argv += optind;
4386 #ifndef PROFILE
4387 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4388 NULL) == -1)
4389 err(1, "pledge");
4390 #endif
4391 cwd = getcwd(NULL, 0);
4392 if (cwd == NULL) {
4393 error = got_error_from_errno("getcwd");
4394 goto done;
4397 error = got_worktree_open(&worktree, cwd);
4398 if (error) {
4399 if (error->code == GOT_ERR_NOT_WORKTREE)
4400 error = wrap_not_worktree_error(error, "status", cwd);
4401 goto done;
4404 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4405 NULL);
4406 if (error != NULL)
4407 goto done;
4409 error = apply_unveil(got_repo_get_path(repo), 1,
4410 got_worktree_get_root_path(worktree));
4411 if (error)
4412 goto done;
4414 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
4415 if (error)
4416 goto done;
4418 error = got_worktree_status(worktree, &paths, repo, print_status, NULL,
4419 check_cancelled, NULL);
4420 done:
4421 TAILQ_FOREACH(pe, &paths, entry)
4422 free((char *)pe->path);
4423 got_pathlist_free(&paths);
4424 free(cwd);
4425 return error;
4428 __dead static void
4429 usage_ref(void)
4431 fprintf(stderr,
4432 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
4433 "[-d] [name]\n",
4434 getprogname());
4435 exit(1);
4438 static const struct got_error *
4439 list_refs(struct got_repository *repo, const char *refname)
4441 static const struct got_error *err = NULL;
4442 struct got_reflist_head refs;
4443 struct got_reflist_entry *re;
4445 SIMPLEQ_INIT(&refs);
4446 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
4447 if (err)
4448 return err;
4450 SIMPLEQ_FOREACH(re, &refs, entry) {
4451 char *refstr;
4452 refstr = got_ref_to_str(re->ref);
4453 if (refstr == NULL)
4454 return got_error_from_errno("got_ref_to_str");
4455 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
4456 free(refstr);
4459 got_ref_list_free(&refs);
4460 return NULL;
4463 static const struct got_error *
4464 delete_ref(struct got_repository *repo, const char *refname)
4466 const struct got_error *err = NULL;
4467 struct got_reference *ref;
4469 err = got_ref_open(&ref, repo, refname, 0);
4470 if (err)
4471 return err;
4473 err = got_ref_delete(ref, repo);
4474 got_ref_close(ref);
4475 return err;
4478 static const struct got_error *
4479 add_ref(struct got_repository *repo, const char *refname, const char *target)
4481 const struct got_error *err = NULL;
4482 struct got_object_id *id;
4483 struct got_reference *ref = NULL;
4486 * Don't let the user create a reference name with a leading '-'.
4487 * While technically a valid reference name, this case is usually
4488 * an unintended typo.
4490 if (refname[0] == '-')
4491 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4493 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
4494 repo);
4495 if (err) {
4496 struct got_reference *target_ref;
4498 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
4499 return err;
4500 err = got_ref_open(&target_ref, repo, target, 0);
4501 if (err)
4502 return err;
4503 err = got_ref_resolve(&id, repo, target_ref);
4504 got_ref_close(target_ref);
4505 if (err)
4506 return err;
4509 err = got_ref_alloc(&ref, refname, id);
4510 if (err)
4511 goto done;
4513 err = got_ref_write(ref, repo);
4514 done:
4515 if (ref)
4516 got_ref_close(ref);
4517 free(id);
4518 return err;
4521 static const struct got_error *
4522 add_symref(struct got_repository *repo, const char *refname, const char *target)
4524 const struct got_error *err = NULL;
4525 struct got_reference *ref = NULL;
4526 struct got_reference *target_ref = NULL;
4529 * Don't let the user create a reference name with a leading '-'.
4530 * While technically a valid reference name, this case is usually
4531 * an unintended typo.
4533 if (refname[0] == '-')
4534 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4536 err = got_ref_open(&target_ref, repo, target, 0);
4537 if (err)
4538 return err;
4540 err = got_ref_alloc_symref(&ref, refname, target_ref);
4541 if (err)
4542 goto done;
4544 err = got_ref_write(ref, repo);
4545 done:
4546 if (target_ref)
4547 got_ref_close(target_ref);
4548 if (ref)
4549 got_ref_close(ref);
4550 return err;
4553 static const struct got_error *
4554 cmd_ref(int argc, char *argv[])
4556 const struct got_error *error = NULL;
4557 struct got_repository *repo = NULL;
4558 struct got_worktree *worktree = NULL;
4559 char *cwd = NULL, *repo_path = NULL;
4560 int ch, do_list = 0, do_delete = 0;
4561 const char *obj_arg = NULL, *symref_target= NULL;
4562 char *refname = NULL;
4564 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
4565 switch (ch) {
4566 case 'c':
4567 obj_arg = optarg;
4568 break;
4569 case 'd':
4570 do_delete = 1;
4571 break;
4572 case 'r':
4573 repo_path = realpath(optarg, NULL);
4574 if (repo_path == NULL)
4575 return got_error_from_errno2("realpath",
4576 optarg);
4577 got_path_strip_trailing_slashes(repo_path);
4578 break;
4579 case 'l':
4580 do_list = 1;
4581 break;
4582 case 's':
4583 symref_target = optarg;
4584 break;
4585 default:
4586 usage_ref();
4587 /* NOTREACHED */
4591 if (obj_arg && do_list)
4592 errx(1, "-c and -l options are mutually exclusive");
4593 if (obj_arg && do_delete)
4594 errx(1, "-c and -d options are mutually exclusive");
4595 if (obj_arg && symref_target)
4596 errx(1, "-c and -s options are mutually exclusive");
4597 if (symref_target && do_delete)
4598 errx(1, "-s and -d options are mutually exclusive");
4599 if (symref_target && do_list)
4600 errx(1, "-s and -l options are mutually exclusive");
4601 if (do_delete && do_list)
4602 errx(1, "-d and -l options are mutually exclusive");
4604 argc -= optind;
4605 argv += optind;
4607 if (do_list) {
4608 if (argc != 0 && argc != 1)
4609 usage_ref();
4610 if (argc == 1) {
4611 refname = strdup(argv[0]);
4612 if (refname == NULL) {
4613 error = got_error_from_errno("strdup");
4614 goto done;
4617 } else {
4618 if (argc != 1)
4619 usage_ref();
4620 refname = strdup(argv[0]);
4621 if (refname == NULL) {
4622 error = got_error_from_errno("strdup");
4623 goto done;
4627 if (refname)
4628 got_path_strip_trailing_slashes(refname);
4630 #ifndef PROFILE
4631 if (do_list) {
4632 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4633 NULL) == -1)
4634 err(1, "pledge");
4635 } else {
4636 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4637 "sendfd unveil", NULL) == -1)
4638 err(1, "pledge");
4640 #endif
4641 cwd = getcwd(NULL, 0);
4642 if (cwd == NULL) {
4643 error = got_error_from_errno("getcwd");
4644 goto done;
4647 if (repo_path == NULL) {
4648 error = got_worktree_open(&worktree, cwd);
4649 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4650 goto done;
4651 else
4652 error = NULL;
4653 if (worktree) {
4654 repo_path =
4655 strdup(got_worktree_get_repo_path(worktree));
4656 if (repo_path == NULL)
4657 error = got_error_from_errno("strdup");
4658 if (error)
4659 goto done;
4660 } else {
4661 repo_path = strdup(cwd);
4662 if (repo_path == NULL) {
4663 error = got_error_from_errno("strdup");
4664 goto done;
4669 error = got_repo_open(&repo, repo_path, NULL);
4670 if (error != NULL)
4671 goto done;
4673 error = apply_unveil(got_repo_get_path(repo), do_list,
4674 worktree ? got_worktree_get_root_path(worktree) : NULL);
4675 if (error)
4676 goto done;
4678 if (do_list)
4679 error = list_refs(repo, refname);
4680 else if (do_delete)
4681 error = delete_ref(repo, refname);
4682 else if (symref_target)
4683 error = add_symref(repo, refname, symref_target);
4684 else {
4685 if (obj_arg == NULL)
4686 usage_ref();
4687 error = add_ref(repo, refname, obj_arg);
4689 done:
4690 free(refname);
4691 if (repo)
4692 got_repo_close(repo);
4693 if (worktree)
4694 got_worktree_close(worktree);
4695 free(cwd);
4696 free(repo_path);
4697 return error;
4700 __dead static void
4701 usage_branch(void)
4703 fprintf(stderr,
4704 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
4705 "[name]\n", getprogname());
4706 exit(1);
4709 static const struct got_error *
4710 list_branch(struct got_repository *repo, struct got_worktree *worktree,
4711 struct got_reference *ref)
4713 const struct got_error *err = NULL;
4714 const char *refname, *marker = " ";
4715 char *refstr;
4717 refname = got_ref_get_name(ref);
4718 if (worktree && strcmp(refname,
4719 got_worktree_get_head_ref_name(worktree)) == 0) {
4720 struct got_object_id *id = NULL;
4722 err = got_ref_resolve(&id, repo, ref);
4723 if (err)
4724 return err;
4725 if (got_object_id_cmp(id,
4726 got_worktree_get_base_commit_id(worktree)) == 0)
4727 marker = "* ";
4728 else
4729 marker = "~ ";
4730 free(id);
4733 if (strncmp(refname, "refs/heads/", 11) == 0)
4734 refname += 11;
4735 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4736 refname += 18;
4738 refstr = got_ref_to_str(ref);
4739 if (refstr == NULL)
4740 return got_error_from_errno("got_ref_to_str");
4742 printf("%s%s: %s\n", marker, refname, refstr);
4743 free(refstr);
4744 return NULL;
4747 static const struct got_error *
4748 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
4750 const char *refname;
4752 if (worktree == NULL)
4753 return got_error(GOT_ERR_NOT_WORKTREE);
4755 refname = got_worktree_get_head_ref_name(worktree);
4757 if (strncmp(refname, "refs/heads/", 11) == 0)
4758 refname += 11;
4759 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4760 refname += 18;
4762 printf("%s\n", refname);
4764 return NULL;
4767 static const struct got_error *
4768 list_branches(struct got_repository *repo, struct got_worktree *worktree)
4770 static const struct got_error *err = NULL;
4771 struct got_reflist_head refs;
4772 struct got_reflist_entry *re;
4773 struct got_reference *temp_ref = NULL;
4774 int rebase_in_progress, histedit_in_progress;
4776 SIMPLEQ_INIT(&refs);
4778 if (worktree) {
4779 err = got_worktree_rebase_in_progress(&rebase_in_progress,
4780 worktree);
4781 if (err)
4782 return err;
4784 err = got_worktree_histedit_in_progress(&histedit_in_progress,
4785 worktree);
4786 if (err)
4787 return err;
4789 if (rebase_in_progress || histedit_in_progress) {
4790 err = got_ref_open(&temp_ref, repo,
4791 got_worktree_get_head_ref_name(worktree), 0);
4792 if (err)
4793 return err;
4794 list_branch(repo, worktree, temp_ref);
4795 got_ref_close(temp_ref);
4799 err = got_ref_list(&refs, repo, "refs/heads",
4800 got_ref_cmp_by_name, NULL);
4801 if (err)
4802 return err;
4804 SIMPLEQ_FOREACH(re, &refs, entry)
4805 list_branch(repo, worktree, re->ref);
4807 got_ref_list_free(&refs);
4808 return NULL;
4811 static const struct got_error *
4812 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
4813 const char *branch_name)
4815 const struct got_error *err = NULL;
4816 struct got_reference *ref = NULL;
4817 char *refname;
4819 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
4820 return got_error_from_errno("asprintf");
4822 err = got_ref_open(&ref, repo, refname, 0);
4823 if (err)
4824 goto done;
4826 if (worktree &&
4827 strcmp(got_worktree_get_head_ref_name(worktree),
4828 got_ref_get_name(ref)) == 0) {
4829 err = got_error_msg(GOT_ERR_SAME_BRANCH,
4830 "will not delete this work tree's current branch");
4831 goto done;
4834 err = got_ref_delete(ref, repo);
4835 done:
4836 if (ref)
4837 got_ref_close(ref);
4838 free(refname);
4839 return err;
4842 static const struct got_error *
4843 add_branch(struct got_repository *repo, const char *branch_name,
4844 struct got_object_id *base_commit_id)
4846 const struct got_error *err = NULL;
4847 struct got_reference *ref = NULL;
4848 char *base_refname = NULL, *refname = NULL;
4851 * Don't let the user create a branch name with a leading '-'.
4852 * While technically a valid reference name, this case is usually
4853 * an unintended typo.
4855 if (branch_name[0] == '-')
4856 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
4858 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
4859 err = got_error_from_errno("asprintf");
4860 goto done;
4863 err = got_ref_open(&ref, repo, refname, 0);
4864 if (err == NULL) {
4865 err = got_error(GOT_ERR_BRANCH_EXISTS);
4866 goto done;
4867 } else if (err->code != GOT_ERR_NOT_REF)
4868 goto done;
4870 err = got_ref_alloc(&ref, refname, base_commit_id);
4871 if (err)
4872 goto done;
4874 err = got_ref_write(ref, repo);
4875 done:
4876 if (ref)
4877 got_ref_close(ref);
4878 free(base_refname);
4879 free(refname);
4880 return err;
4883 static const struct got_error *
4884 cmd_branch(int argc, char *argv[])
4886 const struct got_error *error = NULL;
4887 struct got_repository *repo = NULL;
4888 struct got_worktree *worktree = NULL;
4889 char *cwd = NULL, *repo_path = NULL;
4890 int ch, do_list = 0, do_show = 0, do_update = 1;
4891 const char *delref = NULL, *commit_id_arg = NULL;
4892 struct got_reference *ref = NULL;
4893 struct got_pathlist_head paths;
4894 struct got_pathlist_entry *pe;
4895 struct got_object_id *commit_id = NULL;
4896 char *commit_id_str = NULL;
4898 TAILQ_INIT(&paths);
4900 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
4901 switch (ch) {
4902 case 'c':
4903 commit_id_arg = optarg;
4904 break;
4905 case 'd':
4906 delref = optarg;
4907 break;
4908 case 'r':
4909 repo_path = realpath(optarg, NULL);
4910 if (repo_path == NULL)
4911 return got_error_from_errno2("realpath",
4912 optarg);
4913 got_path_strip_trailing_slashes(repo_path);
4914 break;
4915 case 'l':
4916 do_list = 1;
4917 break;
4918 case 'n':
4919 do_update = 0;
4920 break;
4921 default:
4922 usage_branch();
4923 /* NOTREACHED */
4927 if (do_list && delref)
4928 errx(1, "-l and -d options are mutually exclusive");
4930 argc -= optind;
4931 argv += optind;
4933 if (!do_list && !delref && argc == 0)
4934 do_show = 1;
4936 if ((do_list || delref || do_show) && commit_id_arg != NULL)
4937 errx(1, "-c option can only be used when creating a branch");
4939 if (do_list || delref) {
4940 if (argc > 0)
4941 usage_branch();
4942 } else if (!do_show && argc != 1)
4943 usage_branch();
4945 #ifndef PROFILE
4946 if (do_list || do_show) {
4947 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4948 NULL) == -1)
4949 err(1, "pledge");
4950 } else {
4951 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4952 "sendfd unveil", NULL) == -1)
4953 err(1, "pledge");
4955 #endif
4956 cwd = getcwd(NULL, 0);
4957 if (cwd == NULL) {
4958 error = got_error_from_errno("getcwd");
4959 goto done;
4962 if (repo_path == NULL) {
4963 error = got_worktree_open(&worktree, cwd);
4964 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4965 goto done;
4966 else
4967 error = NULL;
4968 if (worktree) {
4969 repo_path =
4970 strdup(got_worktree_get_repo_path(worktree));
4971 if (repo_path == NULL)
4972 error = got_error_from_errno("strdup");
4973 if (error)
4974 goto done;
4975 } else {
4976 repo_path = strdup(cwd);
4977 if (repo_path == NULL) {
4978 error = got_error_from_errno("strdup");
4979 goto done;
4984 error = got_repo_open(&repo, repo_path, NULL);
4985 if (error != NULL)
4986 goto done;
4988 error = apply_unveil(got_repo_get_path(repo), do_list,
4989 worktree ? got_worktree_get_root_path(worktree) : NULL);
4990 if (error)
4991 goto done;
4993 if (do_show)
4994 error = show_current_branch(repo, worktree);
4995 else if (do_list)
4996 error = list_branches(repo, worktree);
4997 else if (delref)
4998 error = delete_branch(repo, worktree, delref);
4999 else {
5000 if (commit_id_arg == NULL)
5001 commit_id_arg = worktree ?
5002 got_worktree_get_head_ref_name(worktree) :
5003 GOT_REF_HEAD;
5004 error = got_repo_match_object_id(&commit_id, NULL,
5005 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5006 if (error)
5007 goto done;
5008 error = add_branch(repo, argv[0], commit_id);
5009 if (error)
5010 goto done;
5011 if (worktree && do_update) {
5012 int did_something = 0;
5013 char *branch_refname = NULL;
5015 error = got_object_id_str(&commit_id_str, commit_id);
5016 if (error)
5017 goto done;
5018 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5019 worktree);
5020 if (error)
5021 goto done;
5022 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5023 == -1) {
5024 error = got_error_from_errno("asprintf");
5025 goto done;
5027 error = got_ref_open(&ref, repo, branch_refname, 0);
5028 free(branch_refname);
5029 if (error)
5030 goto done;
5031 error = switch_head_ref(ref, commit_id, worktree,
5032 repo);
5033 if (error)
5034 goto done;
5035 error = got_worktree_set_base_commit_id(worktree, repo,
5036 commit_id);
5037 if (error)
5038 goto done;
5039 error = got_worktree_checkout_files(worktree, &paths,
5040 repo, update_progress, &did_something,
5041 check_cancelled, NULL);
5042 if (error)
5043 goto done;
5044 if (did_something)
5045 printf("Updated to commit %s\n", commit_id_str);
5048 done:
5049 if (ref)
5050 got_ref_close(ref);
5051 if (repo)
5052 got_repo_close(repo);
5053 if (worktree)
5054 got_worktree_close(worktree);
5055 free(cwd);
5056 free(repo_path);
5057 free(commit_id);
5058 free(commit_id_str);
5059 TAILQ_FOREACH(pe, &paths, entry)
5060 free((char *)pe->path);
5061 got_pathlist_free(&paths);
5062 return error;
5066 __dead static void
5067 usage_tag(void)
5069 fprintf(stderr,
5070 "usage: %s tag [-c commit] [-r repository] [-l] "
5071 "[-m message] name\n", getprogname());
5072 exit(1);
5075 #if 0
5076 static const struct got_error *
5077 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5079 const struct got_error *err = NULL;
5080 struct got_reflist_entry *re, *se, *new;
5081 struct got_object_id *re_id, *se_id;
5082 struct got_tag_object *re_tag, *se_tag;
5083 time_t re_time, se_time;
5085 SIMPLEQ_FOREACH(re, tags, entry) {
5086 se = SIMPLEQ_FIRST(sorted);
5087 if (se == NULL) {
5088 err = got_reflist_entry_dup(&new, re);
5089 if (err)
5090 return err;
5091 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5092 continue;
5093 } else {
5094 err = got_ref_resolve(&re_id, repo, re->ref);
5095 if (err)
5096 break;
5097 err = got_object_open_as_tag(&re_tag, repo, re_id);
5098 free(re_id);
5099 if (err)
5100 break;
5101 re_time = got_object_tag_get_tagger_time(re_tag);
5102 got_object_tag_close(re_tag);
5105 while (se) {
5106 err = got_ref_resolve(&se_id, repo, re->ref);
5107 if (err)
5108 break;
5109 err = got_object_open_as_tag(&se_tag, repo, se_id);
5110 free(se_id);
5111 if (err)
5112 break;
5113 se_time = got_object_tag_get_tagger_time(se_tag);
5114 got_object_tag_close(se_tag);
5116 if (se_time > re_time) {
5117 err = got_reflist_entry_dup(&new, re);
5118 if (err)
5119 return err;
5120 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5121 break;
5123 se = SIMPLEQ_NEXT(se, entry);
5124 continue;
5127 done:
5128 return err;
5130 #endif
5132 static const struct got_error *
5133 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5135 static const struct got_error *err = NULL;
5136 struct got_reflist_head refs;
5137 struct got_reflist_entry *re;
5139 SIMPLEQ_INIT(&refs);
5141 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5142 if (err)
5143 return err;
5145 SIMPLEQ_FOREACH(re, &refs, entry) {
5146 const char *refname;
5147 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5148 char datebuf[26];
5149 const char *tagger;
5150 time_t tagger_time;
5151 struct got_object_id *id;
5152 struct got_tag_object *tag;
5153 struct got_commit_object *commit = NULL;
5155 refname = got_ref_get_name(re->ref);
5156 if (strncmp(refname, "refs/tags/", 10) != 0)
5157 continue;
5158 refname += 10;
5159 refstr = got_ref_to_str(re->ref);
5160 if (refstr == NULL) {
5161 err = got_error_from_errno("got_ref_to_str");
5162 break;
5164 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5165 free(refstr);
5167 err = got_ref_resolve(&id, repo, re->ref);
5168 if (err)
5169 break;
5170 err = got_object_open_as_tag(&tag, repo, id);
5171 if (err) {
5172 if (err->code != GOT_ERR_OBJ_TYPE) {
5173 free(id);
5174 break;
5176 /* "lightweight" tag */
5177 err = got_object_open_as_commit(&commit, repo, id);
5178 if (err) {
5179 free(id);
5180 break;
5182 tagger = got_object_commit_get_committer(commit);
5183 tagger_time =
5184 got_object_commit_get_committer_time(commit);
5185 err = got_object_id_str(&id_str, id);
5186 free(id);
5187 if (err)
5188 break;
5189 } else {
5190 free(id);
5191 tagger = got_object_tag_get_tagger(tag);
5192 tagger_time = got_object_tag_get_tagger_time(tag);
5193 err = got_object_id_str(&id_str,
5194 got_object_tag_get_object_id(tag));
5195 if (err)
5196 break;
5198 printf("from: %s\n", tagger);
5199 datestr = get_datestr(&tagger_time, datebuf);
5200 if (datestr)
5201 printf("date: %s UTC\n", datestr);
5202 if (commit)
5203 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5204 else {
5205 switch (got_object_tag_get_object_type(tag)) {
5206 case GOT_OBJ_TYPE_BLOB:
5207 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5208 id_str);
5209 break;
5210 case GOT_OBJ_TYPE_TREE:
5211 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5212 id_str);
5213 break;
5214 case GOT_OBJ_TYPE_COMMIT:
5215 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5216 id_str);
5217 break;
5218 case GOT_OBJ_TYPE_TAG:
5219 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5220 id_str);
5221 break;
5222 default:
5223 break;
5226 free(id_str);
5227 if (commit) {
5228 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5229 if (err)
5230 break;
5231 got_object_commit_close(commit);
5232 } else {
5233 tagmsg0 = strdup(got_object_tag_get_message(tag));
5234 got_object_tag_close(tag);
5235 if (tagmsg0 == NULL) {
5236 err = got_error_from_errno("strdup");
5237 break;
5241 tagmsg = tagmsg0;
5242 do {
5243 line = strsep(&tagmsg, "\n");
5244 if (line)
5245 printf(" %s\n", line);
5246 } while (line);
5247 free(tagmsg0);
5250 got_ref_list_free(&refs);
5251 return NULL;
5254 static const struct got_error *
5255 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5256 const char *tag_name, const char *repo_path)
5258 const struct got_error *err = NULL;
5259 char *template = NULL, *initial_content = NULL;
5260 char *editor = NULL;
5261 int fd = -1;
5263 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5264 err = got_error_from_errno("asprintf");
5265 goto done;
5268 if (asprintf(&initial_content, "\n# tagging commit %s as %s\n",
5269 commit_id_str, tag_name) == -1) {
5270 err = got_error_from_errno("asprintf");
5271 goto done;
5274 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5275 if (err)
5276 goto done;
5278 dprintf(fd, initial_content);
5279 close(fd);
5281 err = get_editor(&editor);
5282 if (err)
5283 goto done;
5284 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
5285 done:
5286 free(initial_content);
5287 free(template);
5288 free(editor);
5290 /* Editor is done; we can now apply unveil(2) */
5291 if (err == NULL) {
5292 err = apply_unveil(repo_path, 0, NULL);
5293 if (err) {
5294 free(*tagmsg);
5295 *tagmsg = NULL;
5298 return err;
5301 static const struct got_error *
5302 add_tag(struct got_repository *repo, const char *tag_name,
5303 const char *commit_arg, const char *tagmsg_arg)
5305 const struct got_error *err = NULL;
5306 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5307 char *label = NULL, *commit_id_str = NULL;
5308 struct got_reference *ref = NULL;
5309 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5310 char *tagmsg_path = NULL, *tag_id_str = NULL;
5311 int preserve_tagmsg = 0;
5314 * Don't let the user create a tag name with a leading '-'.
5315 * While technically a valid reference name, this case is usually
5316 * an unintended typo.
5318 if (tag_name[0] == '-')
5319 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5321 err = get_author(&tagger, repo);
5322 if (err)
5323 return err;
5325 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5326 GOT_OBJ_TYPE_COMMIT, 1, repo);
5327 if (err)
5328 goto done;
5330 err = got_object_id_str(&commit_id_str, commit_id);
5331 if (err)
5332 goto done;
5334 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5335 refname = strdup(tag_name);
5336 if (refname == NULL) {
5337 err = got_error_from_errno("strdup");
5338 goto done;
5340 tag_name += 10;
5341 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5342 err = got_error_from_errno("asprintf");
5343 goto done;
5346 err = got_ref_open(&ref, repo, refname, 0);
5347 if (err == NULL) {
5348 err = got_error(GOT_ERR_TAG_EXISTS);
5349 goto done;
5350 } else if (err->code != GOT_ERR_NOT_REF)
5351 goto done;
5353 if (tagmsg_arg == NULL) {
5354 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5355 tag_name, got_repo_get_path(repo));
5356 if (err) {
5357 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5358 tagmsg_path != NULL)
5359 preserve_tagmsg = 1;
5360 goto done;
5364 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5365 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5366 if (err) {
5367 if (tagmsg_path)
5368 preserve_tagmsg = 1;
5369 goto done;
5372 err = got_ref_alloc(&ref, refname, tag_id);
5373 if (err) {
5374 if (tagmsg_path)
5375 preserve_tagmsg = 1;
5376 goto done;
5379 err = got_ref_write(ref, repo);
5380 if (err) {
5381 if (tagmsg_path)
5382 preserve_tagmsg = 1;
5383 goto done;
5386 err = got_object_id_str(&tag_id_str, tag_id);
5387 if (err) {
5388 if (tagmsg_path)
5389 preserve_tagmsg = 1;
5390 goto done;
5392 printf("Created tag %s\n", tag_id_str);
5393 done:
5394 if (preserve_tagmsg) {
5395 fprintf(stderr, "%s: tag message preserved in %s\n",
5396 getprogname(), tagmsg_path);
5397 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
5398 err = got_error_from_errno2("unlink", tagmsg_path);
5399 free(tag_id_str);
5400 if (ref)
5401 got_ref_close(ref);
5402 free(commit_id);
5403 free(commit_id_str);
5404 free(refname);
5405 free(tagmsg);
5406 free(tagmsg_path);
5407 free(tagger);
5408 return err;
5411 static const struct got_error *
5412 cmd_tag(int argc, char *argv[])
5414 const struct got_error *error = NULL;
5415 struct got_repository *repo = NULL;
5416 struct got_worktree *worktree = NULL;
5417 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
5418 char *gitconfig_path = NULL;
5419 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
5420 int ch, do_list = 0;
5422 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
5423 switch (ch) {
5424 case 'c':
5425 commit_id_arg = optarg;
5426 break;
5427 case 'm':
5428 tagmsg = optarg;
5429 break;
5430 case 'r':
5431 repo_path = realpath(optarg, NULL);
5432 if (repo_path == NULL)
5433 return got_error_from_errno2("realpath",
5434 optarg);
5435 got_path_strip_trailing_slashes(repo_path);
5436 break;
5437 case 'l':
5438 do_list = 1;
5439 break;
5440 default:
5441 usage_tag();
5442 /* NOTREACHED */
5446 argc -= optind;
5447 argv += optind;
5449 if (do_list) {
5450 if (commit_id_arg != NULL)
5451 errx(1,
5452 "-c option can only be used when creating a tag");
5453 if (tagmsg)
5454 errx(1, "-l and -m options are mutually exclusive");
5455 if (argc > 0)
5456 usage_tag();
5457 } else if (argc != 1)
5458 usage_tag();
5460 tag_name = argv[0];
5462 #ifndef PROFILE
5463 if (do_list) {
5464 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5465 NULL) == -1)
5466 err(1, "pledge");
5467 } else {
5468 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5469 "sendfd unveil", NULL) == -1)
5470 err(1, "pledge");
5472 #endif
5473 cwd = getcwd(NULL, 0);
5474 if (cwd == NULL) {
5475 error = got_error_from_errno("getcwd");
5476 goto done;
5479 if (repo_path == NULL) {
5480 error = got_worktree_open(&worktree, cwd);
5481 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5482 goto done;
5483 else
5484 error = NULL;
5485 if (worktree) {
5486 repo_path =
5487 strdup(got_worktree_get_repo_path(worktree));
5488 if (repo_path == NULL)
5489 error = got_error_from_errno("strdup");
5490 if (error)
5491 goto done;
5492 } else {
5493 repo_path = strdup(cwd);
5494 if (repo_path == NULL) {
5495 error = got_error_from_errno("strdup");
5496 goto done;
5501 if (do_list) {
5502 error = got_repo_open(&repo, repo_path, NULL);
5503 if (error != NULL)
5504 goto done;
5505 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5506 if (error)
5507 goto done;
5508 error = list_tags(repo, worktree);
5509 } else {
5510 error = get_gitconfig_path(&gitconfig_path);
5511 if (error)
5512 goto done;
5513 error = got_repo_open(&repo, repo_path, gitconfig_path);
5514 if (error != NULL)
5515 goto done;
5517 if (tagmsg) {
5518 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5519 if (error)
5520 goto done;
5523 if (commit_id_arg == NULL) {
5524 struct got_reference *head_ref;
5525 struct got_object_id *commit_id;
5526 error = got_ref_open(&head_ref, repo,
5527 worktree ? got_worktree_get_head_ref_name(worktree)
5528 : GOT_REF_HEAD, 0);
5529 if (error)
5530 goto done;
5531 error = got_ref_resolve(&commit_id, repo, head_ref);
5532 got_ref_close(head_ref);
5533 if (error)
5534 goto done;
5535 error = got_object_id_str(&commit_id_str, commit_id);
5536 free(commit_id);
5537 if (error)
5538 goto done;
5541 error = add_tag(repo, tag_name,
5542 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
5544 done:
5545 if (repo)
5546 got_repo_close(repo);
5547 if (worktree)
5548 got_worktree_close(worktree);
5549 free(cwd);
5550 free(repo_path);
5551 free(gitconfig_path);
5552 free(commit_id_str);
5553 return error;
5556 __dead static void
5557 usage_add(void)
5559 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
5560 getprogname());
5561 exit(1);
5564 static const struct got_error *
5565 add_progress(void *arg, unsigned char status, const char *path)
5567 while (path[0] == '/')
5568 path++;
5569 printf("%c %s\n", status, path);
5570 return NULL;
5573 static const struct got_error *
5574 cmd_add(int argc, char *argv[])
5576 const struct got_error *error = NULL;
5577 struct got_repository *repo = NULL;
5578 struct got_worktree *worktree = NULL;
5579 char *cwd = NULL;
5580 struct got_pathlist_head paths;
5581 struct got_pathlist_entry *pe;
5582 int ch, can_recurse = 0, no_ignores = 0;
5584 TAILQ_INIT(&paths);
5586 while ((ch = getopt(argc, argv, "IR")) != -1) {
5587 switch (ch) {
5588 case 'I':
5589 no_ignores = 1;
5590 break;
5591 case 'R':
5592 can_recurse = 1;
5593 break;
5594 default:
5595 usage_add();
5596 /* NOTREACHED */
5600 argc -= optind;
5601 argv += optind;
5603 #ifndef PROFILE
5604 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5605 NULL) == -1)
5606 err(1, "pledge");
5607 #endif
5608 if (argc < 1)
5609 usage_add();
5611 cwd = getcwd(NULL, 0);
5612 if (cwd == NULL) {
5613 error = got_error_from_errno("getcwd");
5614 goto done;
5617 error = got_worktree_open(&worktree, cwd);
5618 if (error) {
5619 if (error->code == GOT_ERR_NOT_WORKTREE)
5620 error = wrap_not_worktree_error(error, "add", cwd);
5621 goto done;
5624 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5625 NULL);
5626 if (error != NULL)
5627 goto done;
5629 error = apply_unveil(got_repo_get_path(repo), 1,
5630 got_worktree_get_root_path(worktree));
5631 if (error)
5632 goto done;
5634 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5635 if (error)
5636 goto done;
5638 if (!can_recurse && no_ignores) {
5639 error = got_error_msg(GOT_ERR_BAD_PATH,
5640 "disregarding ignores requires -R option");
5641 goto done;
5645 if (!can_recurse) {
5646 char *ondisk_path;
5647 struct stat sb;
5648 TAILQ_FOREACH(pe, &paths, entry) {
5649 if (asprintf(&ondisk_path, "%s/%s",
5650 got_worktree_get_root_path(worktree),
5651 pe->path) == -1) {
5652 error = got_error_from_errno("asprintf");
5653 goto done;
5655 if (lstat(ondisk_path, &sb) == -1) {
5656 if (errno == ENOENT) {
5657 free(ondisk_path);
5658 continue;
5660 error = got_error_from_errno2("lstat",
5661 ondisk_path);
5662 free(ondisk_path);
5663 goto done;
5665 free(ondisk_path);
5666 if (S_ISDIR(sb.st_mode)) {
5667 error = got_error_msg(GOT_ERR_BAD_PATH,
5668 "adding directories requires -R option");
5669 goto done;
5674 error = got_worktree_schedule_add(worktree, &paths, add_progress,
5675 NULL, repo, no_ignores);
5676 done:
5677 if (repo)
5678 got_repo_close(repo);
5679 if (worktree)
5680 got_worktree_close(worktree);
5681 TAILQ_FOREACH(pe, &paths, entry)
5682 free((char *)pe->path);
5683 got_pathlist_free(&paths);
5684 free(cwd);
5685 return error;
5688 __dead static void
5689 usage_remove(void)
5691 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] path ...\n",
5692 getprogname());
5693 exit(1);
5696 static const struct got_error *
5697 print_remove_status(void *arg, unsigned char status,
5698 unsigned char staged_status, const char *path)
5700 while (path[0] == '/')
5701 path++;
5702 if (status == GOT_STATUS_NONEXISTENT)
5703 return NULL;
5704 if (status == staged_status && (status == GOT_STATUS_DELETE))
5705 status = GOT_STATUS_NO_CHANGE;
5706 printf("%c%c %s\n", status, staged_status, path);
5707 return NULL;
5710 static const struct got_error *
5711 cmd_remove(int argc, char *argv[])
5713 const struct got_error *error = NULL;
5714 struct got_worktree *worktree = NULL;
5715 struct got_repository *repo = NULL;
5716 char *cwd = NULL;
5717 struct got_pathlist_head paths;
5718 struct got_pathlist_entry *pe;
5719 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0;
5721 TAILQ_INIT(&paths);
5723 while ((ch = getopt(argc, argv, "fkR")) != -1) {
5724 switch (ch) {
5725 case 'f':
5726 delete_local_mods = 1;
5727 break;
5728 case 'k':
5729 keep_on_disk = 1;
5730 break;
5731 case 'R':
5732 can_recurse = 1;
5733 break;
5734 default:
5735 usage_remove();
5736 /* NOTREACHED */
5740 argc -= optind;
5741 argv += optind;
5743 #ifndef PROFILE
5744 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5745 NULL) == -1)
5746 err(1, "pledge");
5747 #endif
5748 if (argc < 1)
5749 usage_remove();
5751 cwd = getcwd(NULL, 0);
5752 if (cwd == NULL) {
5753 error = got_error_from_errno("getcwd");
5754 goto done;
5756 error = got_worktree_open(&worktree, cwd);
5757 if (error) {
5758 if (error->code == GOT_ERR_NOT_WORKTREE)
5759 error = wrap_not_worktree_error(error, "remove", cwd);
5760 goto done;
5763 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5764 NULL);
5765 if (error)
5766 goto done;
5768 error = apply_unveil(got_repo_get_path(repo), 1,
5769 got_worktree_get_root_path(worktree));
5770 if (error)
5771 goto done;
5773 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5774 if (error)
5775 goto done;
5777 if (!can_recurse) {
5778 char *ondisk_path;
5779 struct stat sb;
5780 TAILQ_FOREACH(pe, &paths, entry) {
5781 if (asprintf(&ondisk_path, "%s/%s",
5782 got_worktree_get_root_path(worktree),
5783 pe->path) == -1) {
5784 error = got_error_from_errno("asprintf");
5785 goto done;
5787 if (lstat(ondisk_path, &sb) == -1) {
5788 if (errno == ENOENT) {
5789 free(ondisk_path);
5790 continue;
5792 error = got_error_from_errno2("lstat",
5793 ondisk_path);
5794 free(ondisk_path);
5795 goto done;
5797 free(ondisk_path);
5798 if (S_ISDIR(sb.st_mode)) {
5799 error = got_error_msg(GOT_ERR_BAD_PATH,
5800 "removing directories requires -R option");
5801 goto done;
5806 error = got_worktree_schedule_delete(worktree, &paths,
5807 delete_local_mods, print_remove_status, NULL, repo, keep_on_disk);
5808 done:
5809 if (repo)
5810 got_repo_close(repo);
5811 if (worktree)
5812 got_worktree_close(worktree);
5813 TAILQ_FOREACH(pe, &paths, entry)
5814 free((char *)pe->path);
5815 got_pathlist_free(&paths);
5816 free(cwd);
5817 return error;
5820 __dead static void
5821 usage_revert(void)
5823 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
5824 "path ...\n", getprogname());
5825 exit(1);
5828 static const struct got_error *
5829 revert_progress(void *arg, unsigned char status, const char *path)
5831 if (status == GOT_STATUS_UNVERSIONED)
5832 return NULL;
5834 while (path[0] == '/')
5835 path++;
5836 printf("%c %s\n", status, path);
5837 return NULL;
5840 struct choose_patch_arg {
5841 FILE *patch_script_file;
5842 const char *action;
5845 static const struct got_error *
5846 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
5847 int nchanges, const char *action)
5849 char *line = NULL;
5850 size_t linesize = 0;
5851 ssize_t linelen;
5853 switch (status) {
5854 case GOT_STATUS_ADD:
5855 printf("A %s\n%s this addition? [y/n] ", path, action);
5856 break;
5857 case GOT_STATUS_DELETE:
5858 printf("D %s\n%s this deletion? [y/n] ", path, action);
5859 break;
5860 case GOT_STATUS_MODIFY:
5861 if (fseek(patch_file, 0L, SEEK_SET) == -1)
5862 return got_error_from_errno("fseek");
5863 printf(GOT_COMMIT_SEP_STR);
5864 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
5865 printf("%s", line);
5866 if (ferror(patch_file))
5867 return got_error_from_errno("getline");
5868 printf(GOT_COMMIT_SEP_STR);
5869 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
5870 path, n, nchanges, action);
5871 break;
5872 default:
5873 return got_error_path(path, GOT_ERR_FILE_STATUS);
5876 return NULL;
5879 static const struct got_error *
5880 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
5881 FILE *patch_file, int n, int nchanges)
5883 const struct got_error *err = NULL;
5884 char *line = NULL;
5885 size_t linesize = 0;
5886 ssize_t linelen;
5887 int resp = ' ';
5888 struct choose_patch_arg *a = arg;
5890 *choice = GOT_PATCH_CHOICE_NONE;
5892 if (a->patch_script_file) {
5893 char *nl;
5894 err = show_change(status, path, patch_file, n, nchanges,
5895 a->action);
5896 if (err)
5897 return err;
5898 linelen = getline(&line, &linesize, a->patch_script_file);
5899 if (linelen == -1) {
5900 if (ferror(a->patch_script_file))
5901 return got_error_from_errno("getline");
5902 return NULL;
5904 nl = strchr(line, '\n');
5905 if (nl)
5906 *nl = '\0';
5907 if (strcmp(line, "y") == 0) {
5908 *choice = GOT_PATCH_CHOICE_YES;
5909 printf("y\n");
5910 } else if (strcmp(line, "n") == 0) {
5911 *choice = GOT_PATCH_CHOICE_NO;
5912 printf("n\n");
5913 } else if (strcmp(line, "q") == 0 &&
5914 status == GOT_STATUS_MODIFY) {
5915 *choice = GOT_PATCH_CHOICE_QUIT;
5916 printf("q\n");
5917 } else
5918 printf("invalid response '%s'\n", line);
5919 free(line);
5920 return NULL;
5923 while (resp != 'y' && resp != 'n' && resp != 'q') {
5924 err = show_change(status, path, patch_file, n, nchanges,
5925 a->action);
5926 if (err)
5927 return err;
5928 resp = getchar();
5929 if (resp == '\n')
5930 resp = getchar();
5931 if (status == GOT_STATUS_MODIFY) {
5932 if (resp != 'y' && resp != 'n' && resp != 'q') {
5933 printf("invalid response '%c'\n", resp);
5934 resp = ' ';
5936 } else if (resp != 'y' && resp != 'n') {
5937 printf("invalid response '%c'\n", resp);
5938 resp = ' ';
5942 if (resp == 'y')
5943 *choice = GOT_PATCH_CHOICE_YES;
5944 else if (resp == 'n')
5945 *choice = GOT_PATCH_CHOICE_NO;
5946 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
5947 *choice = GOT_PATCH_CHOICE_QUIT;
5949 return NULL;
5953 static const struct got_error *
5954 cmd_revert(int argc, char *argv[])
5956 const struct got_error *error = NULL;
5957 struct got_worktree *worktree = NULL;
5958 struct got_repository *repo = NULL;
5959 char *cwd = NULL, *path = NULL;
5960 struct got_pathlist_head paths;
5961 struct got_pathlist_entry *pe;
5962 int ch, can_recurse = 0, pflag = 0;
5963 FILE *patch_script_file = NULL;
5964 const char *patch_script_path = NULL;
5965 struct choose_patch_arg cpa;
5967 TAILQ_INIT(&paths);
5969 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
5970 switch (ch) {
5971 case 'p':
5972 pflag = 1;
5973 break;
5974 case 'F':
5975 patch_script_path = optarg;
5976 break;
5977 case 'R':
5978 can_recurse = 1;
5979 break;
5980 default:
5981 usage_revert();
5982 /* NOTREACHED */
5986 argc -= optind;
5987 argv += optind;
5989 #ifndef PROFILE
5990 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
5991 "unveil", NULL) == -1)
5992 err(1, "pledge");
5993 #endif
5994 if (argc < 1)
5995 usage_revert();
5996 if (patch_script_path && !pflag)
5997 errx(1, "-F option can only be used together with -p option");
5999 cwd = getcwd(NULL, 0);
6000 if (cwd == NULL) {
6001 error = got_error_from_errno("getcwd");
6002 goto done;
6004 error = got_worktree_open(&worktree, cwd);
6005 if (error) {
6006 if (error->code == GOT_ERR_NOT_WORKTREE)
6007 error = wrap_not_worktree_error(error, "revert", cwd);
6008 goto done;
6011 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6012 NULL);
6013 if (error != NULL)
6014 goto done;
6016 if (patch_script_path) {
6017 patch_script_file = fopen(patch_script_path, "r");
6018 if (patch_script_file == NULL) {
6019 error = got_error_from_errno2("fopen",
6020 patch_script_path);
6021 goto done;
6024 error = apply_unveil(got_repo_get_path(repo), 1,
6025 got_worktree_get_root_path(worktree));
6026 if (error)
6027 goto done;
6029 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6030 if (error)
6031 goto done;
6033 if (!can_recurse) {
6034 char *ondisk_path;
6035 struct stat sb;
6036 TAILQ_FOREACH(pe, &paths, entry) {
6037 if (asprintf(&ondisk_path, "%s/%s",
6038 got_worktree_get_root_path(worktree),
6039 pe->path) == -1) {
6040 error = got_error_from_errno("asprintf");
6041 goto done;
6043 if (lstat(ondisk_path, &sb) == -1) {
6044 if (errno == ENOENT) {
6045 free(ondisk_path);
6046 continue;
6048 error = got_error_from_errno2("lstat",
6049 ondisk_path);
6050 free(ondisk_path);
6051 goto done;
6053 free(ondisk_path);
6054 if (S_ISDIR(sb.st_mode)) {
6055 error = got_error_msg(GOT_ERR_BAD_PATH,
6056 "reverting directories requires -R option");
6057 goto done;
6062 cpa.patch_script_file = patch_script_file;
6063 cpa.action = "revert";
6064 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6065 pflag ? choose_patch : NULL, &cpa, repo);
6066 done:
6067 if (patch_script_file && fclose(patch_script_file) == EOF &&
6068 error == NULL)
6069 error = got_error_from_errno2("fclose", patch_script_path);
6070 if (repo)
6071 got_repo_close(repo);
6072 if (worktree)
6073 got_worktree_close(worktree);
6074 free(path);
6075 free(cwd);
6076 return error;
6079 __dead static void
6080 usage_commit(void)
6082 fprintf(stderr, "usage: %s commit [-m msg] [path ...]\n",
6083 getprogname());
6084 exit(1);
6087 struct collect_commit_logmsg_arg {
6088 const char *cmdline_log;
6089 const char *editor;
6090 const char *worktree_path;
6091 const char *branch_name;
6092 const char *repo_path;
6093 char *logmsg_path;
6097 static const struct got_error *
6098 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6099 void *arg)
6101 char *initial_content = NULL;
6102 struct got_pathlist_entry *pe;
6103 const struct got_error *err = NULL;
6104 char *template = NULL;
6105 struct collect_commit_logmsg_arg *a = arg;
6106 int fd;
6107 size_t len;
6109 /* if a message was specified on the command line, just use it */
6110 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6111 len = strlen(a->cmdline_log) + 1;
6112 *logmsg = malloc(len + 1);
6113 if (*logmsg == NULL)
6114 return got_error_from_errno("malloc");
6115 strlcpy(*logmsg, a->cmdline_log, len);
6116 return NULL;
6119 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6120 return got_error_from_errno("asprintf");
6122 if (asprintf(&initial_content,
6123 "\n# changes to be committed on branch %s:\n",
6124 a->branch_name) == -1)
6125 return got_error_from_errno("asprintf");
6127 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6128 if (err)
6129 goto done;
6131 dprintf(fd, initial_content);
6133 TAILQ_FOREACH(pe, commitable_paths, entry) {
6134 struct got_commitable *ct = pe->data;
6135 dprintf(fd, "# %c %s\n",
6136 got_commitable_get_status(ct),
6137 got_commitable_get_path(ct));
6139 close(fd);
6141 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
6142 done:
6143 free(initial_content);
6144 free(template);
6146 /* Editor is done; we can now apply unveil(2) */
6147 if (err == NULL) {
6148 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6149 if (err) {
6150 free(*logmsg);
6151 *logmsg = NULL;
6154 return err;
6157 static const struct got_error *
6158 cmd_commit(int argc, char *argv[])
6160 const struct got_error *error = NULL;
6161 struct got_worktree *worktree = NULL;
6162 struct got_repository *repo = NULL;
6163 char *cwd = NULL, *id_str = NULL;
6164 struct got_object_id *id = NULL;
6165 const char *logmsg = NULL;
6166 struct collect_commit_logmsg_arg cl_arg;
6167 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6168 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6169 struct got_pathlist_head paths;
6171 TAILQ_INIT(&paths);
6172 cl_arg.logmsg_path = NULL;
6174 while ((ch = getopt(argc, argv, "m:")) != -1) {
6175 switch (ch) {
6176 case 'm':
6177 logmsg = optarg;
6178 break;
6179 default:
6180 usage_commit();
6181 /* NOTREACHED */
6185 argc -= optind;
6186 argv += optind;
6188 #ifndef PROFILE
6189 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6190 "unveil", NULL) == -1)
6191 err(1, "pledge");
6192 #endif
6193 cwd = getcwd(NULL, 0);
6194 if (cwd == NULL) {
6195 error = got_error_from_errno("getcwd");
6196 goto done;
6198 error = got_worktree_open(&worktree, cwd);
6199 if (error) {
6200 if (error->code == GOT_ERR_NOT_WORKTREE)
6201 error = wrap_not_worktree_error(error, "commit", cwd);
6202 goto done;
6205 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6206 if (error)
6207 goto done;
6208 if (rebase_in_progress) {
6209 error = got_error(GOT_ERR_REBASING);
6210 goto done;
6213 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6214 worktree);
6215 if (error)
6216 goto done;
6218 error = get_gitconfig_path(&gitconfig_path);
6219 if (error)
6220 goto done;
6221 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6222 gitconfig_path);
6223 if (error != NULL)
6224 goto done;
6226 error = get_author(&author, repo);
6227 if (error)
6228 return error;
6231 * unveil(2) traverses exec(2); if an editor is used we have
6232 * to apply unveil after the log message has been written.
6234 if (logmsg == NULL || strlen(logmsg) == 0)
6235 error = get_editor(&editor);
6236 else
6237 error = apply_unveil(got_repo_get_path(repo), 0,
6238 got_worktree_get_root_path(worktree));
6239 if (error)
6240 goto done;
6242 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6243 if (error)
6244 goto done;
6246 cl_arg.editor = editor;
6247 cl_arg.cmdline_log = logmsg;
6248 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6249 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6250 if (!histedit_in_progress) {
6251 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6252 error = got_error(GOT_ERR_COMMIT_BRANCH);
6253 goto done;
6255 cl_arg.branch_name += 11;
6257 cl_arg.repo_path = got_repo_get_path(repo);
6258 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6259 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
6260 if (error) {
6261 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6262 cl_arg.logmsg_path != NULL)
6263 preserve_logmsg = 1;
6264 goto done;
6267 error = got_object_id_str(&id_str, id);
6268 if (error)
6269 goto done;
6270 printf("Created commit %s\n", id_str);
6271 done:
6272 if (preserve_logmsg) {
6273 fprintf(stderr, "%s: log message preserved in %s\n",
6274 getprogname(), cl_arg.logmsg_path);
6275 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6276 error == NULL)
6277 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6278 free(cl_arg.logmsg_path);
6279 if (repo)
6280 got_repo_close(repo);
6281 if (worktree)
6282 got_worktree_close(worktree);
6283 free(cwd);
6284 free(id_str);
6285 free(gitconfig_path);
6286 free(editor);
6287 free(author);
6288 return error;
6291 __dead static void
6292 usage_cherrypick(void)
6294 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6295 exit(1);
6298 static const struct got_error *
6299 cmd_cherrypick(int argc, char *argv[])
6301 const struct got_error *error = NULL;
6302 struct got_worktree *worktree = NULL;
6303 struct got_repository *repo = NULL;
6304 char *cwd = NULL, *commit_id_str = NULL;
6305 struct got_object_id *commit_id = NULL;
6306 struct got_commit_object *commit = NULL;
6307 struct got_object_qid *pid;
6308 struct got_reference *head_ref = NULL;
6309 int ch, did_something = 0;
6311 while ((ch = getopt(argc, argv, "")) != -1) {
6312 switch (ch) {
6313 default:
6314 usage_cherrypick();
6315 /* NOTREACHED */
6319 argc -= optind;
6320 argv += optind;
6322 #ifndef PROFILE
6323 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6324 "unveil", NULL) == -1)
6325 err(1, "pledge");
6326 #endif
6327 if (argc != 1)
6328 usage_cherrypick();
6330 cwd = getcwd(NULL, 0);
6331 if (cwd == NULL) {
6332 error = got_error_from_errno("getcwd");
6333 goto done;
6335 error = got_worktree_open(&worktree, cwd);
6336 if (error) {
6337 if (error->code == GOT_ERR_NOT_WORKTREE)
6338 error = wrap_not_worktree_error(error, "cherrypick",
6339 cwd);
6340 goto done;
6343 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6344 NULL);
6345 if (error != NULL)
6346 goto done;
6348 error = apply_unveil(got_repo_get_path(repo), 0,
6349 got_worktree_get_root_path(worktree));
6350 if (error)
6351 goto done;
6353 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6354 GOT_OBJ_TYPE_COMMIT, repo);
6355 if (error != NULL) {
6356 struct got_reference *ref;
6357 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6358 goto done;
6359 error = got_ref_open(&ref, repo, argv[0], 0);
6360 if (error != NULL)
6361 goto done;
6362 error = got_ref_resolve(&commit_id, repo, ref);
6363 got_ref_close(ref);
6364 if (error != NULL)
6365 goto done;
6367 error = got_object_id_str(&commit_id_str, commit_id);
6368 if (error)
6369 goto done;
6371 error = got_ref_open(&head_ref, repo,
6372 got_worktree_get_head_ref_name(worktree), 0);
6373 if (error != NULL)
6374 goto done;
6376 error = check_same_branch(commit_id, head_ref, NULL, repo);
6377 if (error) {
6378 if (error->code != GOT_ERR_ANCESTRY)
6379 goto done;
6380 error = NULL;
6381 } else {
6382 error = got_error(GOT_ERR_SAME_BRANCH);
6383 goto done;
6386 error = got_object_open_as_commit(&commit, repo, commit_id);
6387 if (error)
6388 goto done;
6389 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6390 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
6391 commit_id, repo, update_progress, &did_something, check_cancelled,
6392 NULL);
6393 if (error != NULL)
6394 goto done;
6396 if (did_something)
6397 printf("Merged commit %s\n", commit_id_str);
6398 done:
6399 if (commit)
6400 got_object_commit_close(commit);
6401 free(commit_id_str);
6402 if (head_ref)
6403 got_ref_close(head_ref);
6404 if (worktree)
6405 got_worktree_close(worktree);
6406 if (repo)
6407 got_repo_close(repo);
6408 return error;
6411 __dead static void
6412 usage_backout(void)
6414 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
6415 exit(1);
6418 static const struct got_error *
6419 cmd_backout(int argc, char *argv[])
6421 const struct got_error *error = NULL;
6422 struct got_worktree *worktree = NULL;
6423 struct got_repository *repo = NULL;
6424 char *cwd = NULL, *commit_id_str = NULL;
6425 struct got_object_id *commit_id = NULL;
6426 struct got_commit_object *commit = NULL;
6427 struct got_object_qid *pid;
6428 struct got_reference *head_ref = NULL;
6429 int ch, did_something = 0;
6431 while ((ch = getopt(argc, argv, "")) != -1) {
6432 switch (ch) {
6433 default:
6434 usage_backout();
6435 /* NOTREACHED */
6439 argc -= optind;
6440 argv += optind;
6442 #ifndef PROFILE
6443 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6444 "unveil", NULL) == -1)
6445 err(1, "pledge");
6446 #endif
6447 if (argc != 1)
6448 usage_backout();
6450 cwd = getcwd(NULL, 0);
6451 if (cwd == NULL) {
6452 error = got_error_from_errno("getcwd");
6453 goto done;
6455 error = got_worktree_open(&worktree, cwd);
6456 if (error) {
6457 if (error->code == GOT_ERR_NOT_WORKTREE)
6458 error = wrap_not_worktree_error(error, "backout", cwd);
6459 goto done;
6462 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6463 NULL);
6464 if (error != NULL)
6465 goto done;
6467 error = apply_unveil(got_repo_get_path(repo), 0,
6468 got_worktree_get_root_path(worktree));
6469 if (error)
6470 goto done;
6472 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6473 GOT_OBJ_TYPE_COMMIT, repo);
6474 if (error != NULL) {
6475 struct got_reference *ref;
6476 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6477 goto done;
6478 error = got_ref_open(&ref, repo, argv[0], 0);
6479 if (error != NULL)
6480 goto done;
6481 error = got_ref_resolve(&commit_id, repo, ref);
6482 got_ref_close(ref);
6483 if (error != NULL)
6484 goto done;
6486 error = got_object_id_str(&commit_id_str, commit_id);
6487 if (error)
6488 goto done;
6490 error = got_ref_open(&head_ref, repo,
6491 got_worktree_get_head_ref_name(worktree), 0);
6492 if (error != NULL)
6493 goto done;
6495 error = check_same_branch(commit_id, head_ref, NULL, repo);
6496 if (error)
6497 goto done;
6499 error = got_object_open_as_commit(&commit, repo, commit_id);
6500 if (error)
6501 goto done;
6502 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6503 if (pid == NULL) {
6504 error = got_error(GOT_ERR_ROOT_COMMIT);
6505 goto done;
6508 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
6509 update_progress, &did_something, check_cancelled, NULL);
6510 if (error != NULL)
6511 goto done;
6513 if (did_something)
6514 printf("Backed out commit %s\n", commit_id_str);
6515 done:
6516 if (commit)
6517 got_object_commit_close(commit);
6518 free(commit_id_str);
6519 if (head_ref)
6520 got_ref_close(head_ref);
6521 if (worktree)
6522 got_worktree_close(worktree);
6523 if (repo)
6524 got_repo_close(repo);
6525 return error;
6528 __dead static void
6529 usage_rebase(void)
6531 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
6532 getprogname());
6533 exit(1);
6536 void
6537 trim_logmsg(char *logmsg, int limit)
6539 char *nl;
6540 size_t len;
6542 len = strlen(logmsg);
6543 if (len > limit)
6544 len = limit;
6545 logmsg[len] = '\0';
6546 nl = strchr(logmsg, '\n');
6547 if (nl)
6548 *nl = '\0';
6551 static const struct got_error *
6552 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
6554 const struct got_error *err;
6555 char *logmsg0 = NULL;
6556 const char *s;
6558 err = got_object_commit_get_logmsg(&logmsg0, commit);
6559 if (err)
6560 return err;
6562 s = logmsg0;
6563 while (isspace((unsigned char)s[0]))
6564 s++;
6566 *logmsg = strdup(s);
6567 if (*logmsg == NULL) {
6568 err = got_error_from_errno("strdup");
6569 goto done;
6572 trim_logmsg(*logmsg, limit);
6573 done:
6574 free(logmsg0);
6575 return err;
6578 static const struct got_error *
6579 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
6581 const struct got_error *err;
6582 struct got_commit_object *commit = NULL;
6583 char *id_str = NULL, *logmsg = NULL;
6585 err = got_object_open_as_commit(&commit, repo, id);
6586 if (err)
6587 return err;
6589 err = got_object_id_str(&id_str, id);
6590 if (err)
6591 goto done;
6593 id_str[12] = '\0';
6595 err = get_short_logmsg(&logmsg, 42, commit);
6596 if (err)
6597 goto done;
6599 printf("%s -> merge conflict: %s\n", id_str, logmsg);
6600 done:
6601 free(id_str);
6602 got_object_commit_close(commit);
6603 free(logmsg);
6604 return err;
6607 static const struct got_error *
6608 show_rebase_progress(struct got_commit_object *commit,
6609 struct got_object_id *old_id, struct got_object_id *new_id)
6611 const struct got_error *err;
6612 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
6614 err = got_object_id_str(&old_id_str, old_id);
6615 if (err)
6616 goto done;
6618 if (new_id) {
6619 err = got_object_id_str(&new_id_str, new_id);
6620 if (err)
6621 goto done;
6624 old_id_str[12] = '\0';
6625 if (new_id_str)
6626 new_id_str[12] = '\0';
6628 err = get_short_logmsg(&logmsg, 42, commit);
6629 if (err)
6630 goto done;
6632 printf("%s -> %s: %s\n", old_id_str,
6633 new_id_str ? new_id_str : "no-op change", logmsg);
6634 done:
6635 free(old_id_str);
6636 free(new_id_str);
6637 free(logmsg);
6638 return err;
6641 static const struct got_error *
6642 rebase_progress(void *arg, unsigned char status, const char *path)
6644 unsigned char *rebase_status = arg;
6646 while (path[0] == '/')
6647 path++;
6648 printf("%c %s\n", status, path);
6650 if (*rebase_status == GOT_STATUS_CONFLICT)
6651 return NULL;
6652 if (status == GOT_STATUS_CONFLICT || status == GOT_STATUS_MERGE)
6653 *rebase_status = status;
6654 return NULL;
6657 static const struct got_error *
6658 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
6659 struct got_reference *branch, struct got_reference *new_base_branch,
6660 struct got_reference *tmp_branch, struct got_repository *repo)
6662 printf("Switching work tree to %s\n", got_ref_get_name(branch));
6663 return got_worktree_rebase_complete(worktree, fileindex,
6664 new_base_branch, tmp_branch, branch, repo);
6667 static const struct got_error *
6668 rebase_commit(struct got_pathlist_head *merged_paths,
6669 struct got_worktree *worktree, struct got_fileindex *fileindex,
6670 struct got_reference *tmp_branch,
6671 struct got_object_id *commit_id, struct got_repository *repo)
6673 const struct got_error *error;
6674 struct got_commit_object *commit;
6675 struct got_object_id *new_commit_id;
6677 error = got_object_open_as_commit(&commit, repo, commit_id);
6678 if (error)
6679 return error;
6681 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
6682 worktree, fileindex, tmp_branch, commit, commit_id, repo);
6683 if (error) {
6684 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
6685 goto done;
6686 error = show_rebase_progress(commit, commit_id, NULL);
6687 } else {
6688 error = show_rebase_progress(commit, commit_id, new_commit_id);
6689 free(new_commit_id);
6691 done:
6692 got_object_commit_close(commit);
6693 return error;
6696 struct check_path_prefix_arg {
6697 const char *path_prefix;
6698 size_t len;
6699 int errcode;
6702 static const struct got_error *
6703 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
6704 struct got_blob_object *blob2, struct got_object_id *id1,
6705 struct got_object_id *id2, const char *path1, const char *path2,
6706 mode_t mode1, mode_t mode2, struct got_repository *repo)
6708 struct check_path_prefix_arg *a = arg;
6710 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
6711 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
6712 return got_error(a->errcode);
6714 return NULL;
6717 static const struct got_error *
6718 check_path_prefix(struct got_object_id *parent_id,
6719 struct got_object_id *commit_id, const char *path_prefix,
6720 int errcode, struct got_repository *repo)
6722 const struct got_error *err;
6723 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
6724 struct got_commit_object *commit = NULL, *parent_commit = NULL;
6725 struct check_path_prefix_arg cpp_arg;
6727 if (got_path_is_root_dir(path_prefix))
6728 return NULL;
6730 err = got_object_open_as_commit(&commit, repo, commit_id);
6731 if (err)
6732 goto done;
6734 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
6735 if (err)
6736 goto done;
6738 err = got_object_open_as_tree(&tree1, repo,
6739 got_object_commit_get_tree_id(parent_commit));
6740 if (err)
6741 goto done;
6743 err = got_object_open_as_tree(&tree2, repo,
6744 got_object_commit_get_tree_id(commit));
6745 if (err)
6746 goto done;
6748 cpp_arg.path_prefix = path_prefix;
6749 while (cpp_arg.path_prefix[0] == '/')
6750 cpp_arg.path_prefix++;
6751 cpp_arg.len = strlen(cpp_arg.path_prefix);
6752 cpp_arg.errcode = errcode;
6753 err = got_diff_tree(tree1, tree2, "", "", repo,
6754 check_path_prefix_in_diff, &cpp_arg, 0);
6755 done:
6756 if (tree1)
6757 got_object_tree_close(tree1);
6758 if (tree2)
6759 got_object_tree_close(tree2);
6760 if (commit)
6761 got_object_commit_close(commit);
6762 if (parent_commit)
6763 got_object_commit_close(parent_commit);
6764 return err;
6767 static const struct got_error *
6768 collect_commits(struct got_object_id_queue *commits,
6769 struct got_object_id *initial_commit_id,
6770 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
6771 const char *path_prefix, int path_prefix_errcode,
6772 struct got_repository *repo)
6774 const struct got_error *err = NULL;
6775 struct got_commit_graph *graph = NULL;
6776 struct got_object_id *parent_id = NULL;
6777 struct got_object_qid *qid;
6778 struct got_object_id *commit_id = initial_commit_id;
6780 err = got_commit_graph_open(&graph, "/", 1);
6781 if (err)
6782 return err;
6784 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
6785 check_cancelled, NULL);
6786 if (err)
6787 goto done;
6788 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
6789 err = got_commit_graph_iter_next(&parent_id, graph, repo,
6790 check_cancelled, NULL);
6791 if (err) {
6792 if (err->code == GOT_ERR_ITER_COMPLETED) {
6793 err = got_error_msg(GOT_ERR_ANCESTRY,
6794 "ran out of commits to rebase before "
6795 "youngest common ancestor commit has "
6796 "been reached?!?");
6798 goto done;
6799 } else {
6800 err = check_path_prefix(parent_id, commit_id,
6801 path_prefix, path_prefix_errcode, repo);
6802 if (err)
6803 goto done;
6805 err = got_object_qid_alloc(&qid, commit_id);
6806 if (err)
6807 goto done;
6808 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
6809 commit_id = parent_id;
6812 done:
6813 got_commit_graph_close(graph);
6814 return err;
6817 static const struct got_error *
6818 cmd_rebase(int argc, char *argv[])
6820 const struct got_error *error = NULL;
6821 struct got_worktree *worktree = NULL;
6822 struct got_repository *repo = NULL;
6823 struct got_fileindex *fileindex = NULL;
6824 char *cwd = NULL;
6825 struct got_reference *branch = NULL;
6826 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
6827 struct got_object_id *commit_id = NULL, *parent_id = NULL;
6828 struct got_object_id *resume_commit_id = NULL;
6829 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
6830 struct got_commit_object *commit = NULL;
6831 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
6832 int histedit_in_progress = 0;
6833 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
6834 struct got_object_id_queue commits;
6835 struct got_pathlist_head merged_paths;
6836 const struct got_object_id_queue *parent_ids;
6837 struct got_object_qid *qid, *pid;
6839 SIMPLEQ_INIT(&commits);
6840 TAILQ_INIT(&merged_paths);
6842 while ((ch = getopt(argc, argv, "ac")) != -1) {
6843 switch (ch) {
6844 case 'a':
6845 abort_rebase = 1;
6846 break;
6847 case 'c':
6848 continue_rebase = 1;
6849 break;
6850 default:
6851 usage_rebase();
6852 /* NOTREACHED */
6856 argc -= optind;
6857 argv += optind;
6859 #ifndef PROFILE
6860 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6861 "unveil", NULL) == -1)
6862 err(1, "pledge");
6863 #endif
6864 if (abort_rebase && continue_rebase)
6865 usage_rebase();
6866 else if (abort_rebase || continue_rebase) {
6867 if (argc != 0)
6868 usage_rebase();
6869 } else if (argc != 1)
6870 usage_rebase();
6872 cwd = getcwd(NULL, 0);
6873 if (cwd == NULL) {
6874 error = got_error_from_errno("getcwd");
6875 goto done;
6877 error = got_worktree_open(&worktree, cwd);
6878 if (error) {
6879 if (error->code == GOT_ERR_NOT_WORKTREE)
6880 error = wrap_not_worktree_error(error, "rebase", cwd);
6881 goto done;
6884 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6885 NULL);
6886 if (error != NULL)
6887 goto done;
6889 error = apply_unveil(got_repo_get_path(repo), 0,
6890 got_worktree_get_root_path(worktree));
6891 if (error)
6892 goto done;
6894 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6895 worktree);
6896 if (error)
6897 goto done;
6898 if (histedit_in_progress) {
6899 error = got_error(GOT_ERR_HISTEDIT_BUSY);
6900 goto done;
6903 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6904 if (error)
6905 goto done;
6907 if (abort_rebase) {
6908 int did_something;
6909 if (!rebase_in_progress) {
6910 error = got_error(GOT_ERR_NOT_REBASING);
6911 goto done;
6913 error = got_worktree_rebase_continue(&resume_commit_id,
6914 &new_base_branch, &tmp_branch, &branch, &fileindex,
6915 worktree, repo);
6916 if (error)
6917 goto done;
6918 printf("Switching work tree to %s\n",
6919 got_ref_get_symref_target(new_base_branch));
6920 error = got_worktree_rebase_abort(worktree, fileindex, repo,
6921 new_base_branch, update_progress, &did_something);
6922 if (error)
6923 goto done;
6924 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
6925 goto done; /* nothing else to do */
6928 if (continue_rebase) {
6929 if (!rebase_in_progress) {
6930 error = got_error(GOT_ERR_NOT_REBASING);
6931 goto done;
6933 error = got_worktree_rebase_continue(&resume_commit_id,
6934 &new_base_branch, &tmp_branch, &branch, &fileindex,
6935 worktree, repo);
6936 if (error)
6937 goto done;
6939 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
6940 resume_commit_id, repo);
6941 if (error)
6942 goto done;
6944 yca_id = got_object_id_dup(resume_commit_id);
6945 if (yca_id == NULL) {
6946 error = got_error_from_errno("got_object_id_dup");
6947 goto done;
6949 } else {
6950 error = got_ref_open(&branch, repo, argv[0], 0);
6951 if (error != NULL)
6952 goto done;
6955 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
6956 if (error)
6957 goto done;
6959 if (!continue_rebase) {
6960 struct got_object_id *base_commit_id;
6962 base_commit_id = got_worktree_get_base_commit_id(worktree);
6963 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
6964 base_commit_id, branch_head_commit_id, repo,
6965 check_cancelled, NULL);
6966 if (error)
6967 goto done;
6968 if (yca_id == NULL) {
6969 error = got_error_msg(GOT_ERR_ANCESTRY,
6970 "specified branch shares no common ancestry "
6971 "with work tree's branch");
6972 goto done;
6975 error = check_same_branch(base_commit_id, branch, yca_id, repo);
6976 if (error) {
6977 if (error->code != GOT_ERR_ANCESTRY)
6978 goto done;
6979 error = NULL;
6980 } else {
6981 error = got_error_msg(GOT_ERR_SAME_BRANCH,
6982 "specified branch resolves to a commit which "
6983 "is already contained in work tree's branch");
6984 goto done;
6986 error = got_worktree_rebase_prepare(&new_base_branch,
6987 &tmp_branch, &fileindex, worktree, branch, repo);
6988 if (error)
6989 goto done;
6992 commit_id = branch_head_commit_id;
6993 error = got_object_open_as_commit(&commit, repo, commit_id);
6994 if (error)
6995 goto done;
6997 parent_ids = got_object_commit_get_parent_ids(commit);
6998 pid = SIMPLEQ_FIRST(parent_ids);
6999 if (pid == NULL) {
7000 if (!continue_rebase) {
7001 int did_something;
7002 error = got_worktree_rebase_abort(worktree, fileindex,
7003 repo, new_base_branch, update_progress,
7004 &did_something);
7005 if (error)
7006 goto done;
7007 printf("Rebase of %s aborted\n",
7008 got_ref_get_name(branch));
7010 error = got_error(GOT_ERR_EMPTY_REBASE);
7011 goto done;
7013 error = collect_commits(&commits, commit_id, pid->id,
7014 yca_id, got_worktree_get_path_prefix(worktree),
7015 GOT_ERR_REBASE_PATH, repo);
7016 got_object_commit_close(commit);
7017 commit = NULL;
7018 if (error)
7019 goto done;
7021 if (SIMPLEQ_EMPTY(&commits)) {
7022 if (continue_rebase) {
7023 error = rebase_complete(worktree, fileindex,
7024 branch, new_base_branch, tmp_branch, repo);
7025 goto done;
7026 } else {
7027 /* Fast-forward the reference of the branch. */
7028 struct got_object_id *new_head_commit_id;
7029 char *id_str;
7030 error = got_ref_resolve(&new_head_commit_id, repo,
7031 new_base_branch);
7032 if (error)
7033 goto done;
7034 error = got_object_id_str(&id_str, new_head_commit_id);
7035 printf("Forwarding %s to commit %s\n",
7036 got_ref_get_name(branch), id_str);
7037 free(id_str);
7038 error = got_ref_change_ref(branch,
7039 new_head_commit_id);
7040 if (error)
7041 goto done;
7045 pid = NULL;
7046 SIMPLEQ_FOREACH(qid, &commits, entry) {
7047 commit_id = qid->id;
7048 parent_id = pid ? pid->id : yca_id;
7049 pid = qid;
7051 error = got_worktree_rebase_merge_files(&merged_paths,
7052 worktree, fileindex, parent_id, commit_id, repo,
7053 rebase_progress, &rebase_status, check_cancelled, NULL);
7054 if (error)
7055 goto done;
7057 if (rebase_status == GOT_STATUS_CONFLICT) {
7058 error = show_rebase_merge_conflict(qid->id, repo);
7059 if (error)
7060 goto done;
7061 got_worktree_rebase_pathlist_free(&merged_paths);
7062 break;
7065 error = rebase_commit(&merged_paths, worktree, fileindex,
7066 tmp_branch, commit_id, repo);
7067 got_worktree_rebase_pathlist_free(&merged_paths);
7068 if (error)
7069 goto done;
7072 if (rebase_status == GOT_STATUS_CONFLICT) {
7073 error = got_worktree_rebase_postpone(worktree, fileindex);
7074 if (error)
7075 goto done;
7076 error = got_error_msg(GOT_ERR_CONFLICTS,
7077 "conflicts must be resolved before rebasing can continue");
7078 } else
7079 error = rebase_complete(worktree, fileindex, branch,
7080 new_base_branch, tmp_branch, repo);
7081 done:
7082 got_object_id_queue_free(&commits);
7083 free(branch_head_commit_id);
7084 free(resume_commit_id);
7085 free(yca_id);
7086 if (commit)
7087 got_object_commit_close(commit);
7088 if (branch)
7089 got_ref_close(branch);
7090 if (new_base_branch)
7091 got_ref_close(new_base_branch);
7092 if (tmp_branch)
7093 got_ref_close(tmp_branch);
7094 if (worktree)
7095 got_worktree_close(worktree);
7096 if (repo)
7097 got_repo_close(repo);
7098 return error;
7101 __dead static void
7102 usage_histedit(void)
7104 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
7105 getprogname());
7106 exit(1);
7109 #define GOT_HISTEDIT_PICK 'p'
7110 #define GOT_HISTEDIT_EDIT 'e'
7111 #define GOT_HISTEDIT_FOLD 'f'
7112 #define GOT_HISTEDIT_DROP 'd'
7113 #define GOT_HISTEDIT_MESG 'm'
7115 static struct got_histedit_cmd {
7116 unsigned char code;
7117 const char *name;
7118 const char *desc;
7119 } got_histedit_cmds[] = {
7120 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7121 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7122 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7123 "be used" },
7124 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7125 { GOT_HISTEDIT_MESG, "mesg",
7126 "single-line log message for commit above (open editor if empty)" },
7129 struct got_histedit_list_entry {
7130 TAILQ_ENTRY(got_histedit_list_entry) entry;
7131 struct got_object_id *commit_id;
7132 const struct got_histedit_cmd *cmd;
7133 char *logmsg;
7135 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7137 static const struct got_error *
7138 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7139 FILE *f, struct got_repository *repo)
7141 const struct got_error *err = NULL;
7142 char *logmsg = NULL, *id_str = NULL;
7143 struct got_commit_object *commit = NULL;
7144 int n;
7146 err = got_object_open_as_commit(&commit, repo, commit_id);
7147 if (err)
7148 goto done;
7150 err = get_short_logmsg(&logmsg, 34, commit);
7151 if (err)
7152 goto done;
7154 err = got_object_id_str(&id_str, commit_id);
7155 if (err)
7156 goto done;
7158 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7159 if (n < 0)
7160 err = got_ferror(f, GOT_ERR_IO);
7161 done:
7162 if (commit)
7163 got_object_commit_close(commit);
7164 free(id_str);
7165 free(logmsg);
7166 return err;
7169 static const struct got_error *
7170 histedit_write_commit_list(struct got_object_id_queue *commits,
7171 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7173 const struct got_error *err = NULL;
7174 struct got_object_qid *qid;
7176 if (SIMPLEQ_EMPTY(commits))
7177 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7179 SIMPLEQ_FOREACH(qid, commits, entry) {
7180 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7181 f, repo);
7182 if (err)
7183 break;
7184 if (edit_logmsg_only) {
7185 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7186 if (n < 0) {
7187 err = got_ferror(f, GOT_ERR_IO);
7188 break;
7193 return err;
7196 static const struct got_error *
7197 write_cmd_list(FILE *f, const char *branch_name,
7198 struct got_object_id_queue *commits)
7200 const struct got_error *err = NULL;
7201 int n, i;
7202 char *id_str;
7203 struct got_object_qid *qid;
7205 qid = SIMPLEQ_FIRST(commits);
7206 err = got_object_id_str(&id_str, qid->id);
7207 if (err)
7208 return err;
7210 n = fprintf(f,
7211 "# Editing the history of branch '%s' starting at\n"
7212 "# commit %s\n"
7213 "# Commits will be processed in order from top to "
7214 "bottom of this file.\n", branch_name, id_str);
7215 if (n < 0) {
7216 err = got_ferror(f, GOT_ERR_IO);
7217 goto done;
7220 n = fprintf(f, "# Available histedit commands:\n");
7221 if (n < 0) {
7222 err = got_ferror(f, GOT_ERR_IO);
7223 goto done;
7226 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7227 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7228 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7229 cmd->desc);
7230 if (n < 0) {
7231 err = got_ferror(f, GOT_ERR_IO);
7232 break;
7235 done:
7236 free(id_str);
7237 return err;
7240 static const struct got_error *
7241 histedit_syntax_error(int lineno)
7243 static char msg[42];
7244 int ret;
7246 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7247 lineno);
7248 if (ret == -1 || ret >= sizeof(msg))
7249 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7251 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7254 static const struct got_error *
7255 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7256 char *logmsg, struct got_repository *repo)
7258 const struct got_error *err;
7259 struct got_commit_object *folded_commit = NULL;
7260 char *id_str, *folded_logmsg = NULL;
7262 err = got_object_id_str(&id_str, hle->commit_id);
7263 if (err)
7264 return err;
7266 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7267 if (err)
7268 goto done;
7270 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7271 if (err)
7272 goto done;
7273 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7274 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7275 folded_logmsg) == -1) {
7276 err = got_error_from_errno("asprintf");
7278 done:
7279 if (folded_commit)
7280 got_object_commit_close(folded_commit);
7281 free(id_str);
7282 free(folded_logmsg);
7283 return err;
7286 static struct got_histedit_list_entry *
7287 get_folded_commits(struct got_histedit_list_entry *hle)
7289 struct got_histedit_list_entry *prev, *folded = NULL;
7291 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7292 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7293 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7294 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7295 folded = prev;
7296 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7299 return folded;
7302 static const struct got_error *
7303 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7304 struct got_repository *repo)
7306 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7307 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7308 const struct got_error *err = NULL;
7309 struct got_commit_object *commit = NULL;
7310 int fd;
7311 struct got_histedit_list_entry *folded = NULL;
7313 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7314 if (err)
7315 return err;
7317 folded = get_folded_commits(hle);
7318 if (folded) {
7319 while (folded != hle) {
7320 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7321 folded = TAILQ_NEXT(folded, entry);
7322 continue;
7324 err = append_folded_commit_msg(&new_msg, folded,
7325 logmsg, repo);
7326 if (err)
7327 goto done;
7328 free(logmsg);
7329 logmsg = new_msg;
7330 folded = TAILQ_NEXT(folded, entry);
7334 err = got_object_id_str(&id_str, hle->commit_id);
7335 if (err)
7336 goto done;
7337 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7338 if (err)
7339 goto done;
7340 if (asprintf(&new_msg,
7341 "%s\n# original log message of commit %s: %s",
7342 logmsg ? logmsg : "", id_str, orig_logmsg) == -1) {
7343 err = got_error_from_errno("asprintf");
7344 goto done;
7346 free(logmsg);
7347 logmsg = new_msg;
7349 err = got_object_id_str(&id_str, hle->commit_id);
7350 if (err)
7351 goto done;
7353 err = got_opentemp_named_fd(&logmsg_path, &fd,
7354 GOT_TMPDIR_STR "/got-logmsg");
7355 if (err)
7356 goto done;
7358 dprintf(fd, logmsg);
7359 close(fd);
7361 err = get_editor(&editor);
7362 if (err)
7363 goto done;
7365 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
7366 if (err) {
7367 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
7368 goto done;
7369 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
7371 done:
7372 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
7373 err = got_error_from_errno2("unlink", logmsg_path);
7374 free(logmsg_path);
7375 free(logmsg);
7376 free(orig_logmsg);
7377 free(editor);
7378 if (commit)
7379 got_object_commit_close(commit);
7380 return err;
7383 static const struct got_error *
7384 histedit_parse_list(struct got_histedit_list *histedit_cmds,
7385 FILE *f, struct got_repository *repo)
7387 const struct got_error *err = NULL;
7388 char *line = NULL, *p, *end;
7389 size_t size;
7390 ssize_t len;
7391 int lineno = 0, i;
7392 const struct got_histedit_cmd *cmd;
7393 struct got_object_id *commit_id = NULL;
7394 struct got_histedit_list_entry *hle = NULL;
7396 for (;;) {
7397 len = getline(&line, &size, f);
7398 if (len == -1) {
7399 const struct got_error *getline_err;
7400 if (feof(f))
7401 break;
7402 getline_err = got_error_from_errno("getline");
7403 err = got_ferror(f, getline_err->code);
7404 break;
7406 lineno++;
7407 p = line;
7408 while (isspace((unsigned char)p[0]))
7409 p++;
7410 if (p[0] == '#' || p[0] == '\0') {
7411 free(line);
7412 line = NULL;
7413 continue;
7415 cmd = NULL;
7416 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7417 cmd = &got_histedit_cmds[i];
7418 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
7419 isspace((unsigned char)p[strlen(cmd->name)])) {
7420 p += strlen(cmd->name);
7421 break;
7423 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
7424 p++;
7425 break;
7428 if (i == nitems(got_histedit_cmds)) {
7429 err = histedit_syntax_error(lineno);
7430 break;
7432 while (isspace((unsigned char)p[0]))
7433 p++;
7434 if (cmd->code == GOT_HISTEDIT_MESG) {
7435 if (hle == NULL || hle->logmsg != NULL) {
7436 err = got_error(GOT_ERR_HISTEDIT_CMD);
7437 break;
7439 if (p[0] == '\0') {
7440 err = histedit_edit_logmsg(hle, repo);
7441 if (err)
7442 break;
7443 } else {
7444 hle->logmsg = strdup(p);
7445 if (hle->logmsg == NULL) {
7446 err = got_error_from_errno("strdup");
7447 break;
7450 free(line);
7451 line = NULL;
7452 continue;
7453 } else {
7454 end = p;
7455 while (end[0] && !isspace((unsigned char)end[0]))
7456 end++;
7457 *end = '\0';
7459 err = got_object_resolve_id_str(&commit_id, repo, p);
7460 if (err) {
7461 /* override error code */
7462 err = histedit_syntax_error(lineno);
7463 break;
7466 hle = malloc(sizeof(*hle));
7467 if (hle == NULL) {
7468 err = got_error_from_errno("malloc");
7469 break;
7471 hle->cmd = cmd;
7472 hle->commit_id = commit_id;
7473 hle->logmsg = NULL;
7474 commit_id = NULL;
7475 free(line);
7476 line = NULL;
7477 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
7480 free(line);
7481 free(commit_id);
7482 return err;
7485 static const struct got_error *
7486 histedit_check_script(struct got_histedit_list *histedit_cmds,
7487 struct got_object_id_queue *commits, struct got_repository *repo)
7489 const struct got_error *err = NULL;
7490 struct got_object_qid *qid;
7491 struct got_histedit_list_entry *hle;
7492 static char msg[92];
7493 char *id_str;
7495 if (TAILQ_EMPTY(histedit_cmds))
7496 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
7497 "histedit script contains no commands");
7498 if (SIMPLEQ_EMPTY(commits))
7499 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7501 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7502 struct got_histedit_list_entry *hle2;
7503 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
7504 if (hle == hle2)
7505 continue;
7506 if (got_object_id_cmp(hle->commit_id,
7507 hle2->commit_id) != 0)
7508 continue;
7509 err = got_object_id_str(&id_str, hle->commit_id);
7510 if (err)
7511 return err;
7512 snprintf(msg, sizeof(msg), "commit %s is listed "
7513 "more than once in histedit script", id_str);
7514 free(id_str);
7515 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7519 SIMPLEQ_FOREACH(qid, commits, entry) {
7520 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7521 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
7522 break;
7524 if (hle == NULL) {
7525 err = got_object_id_str(&id_str, qid->id);
7526 if (err)
7527 return err;
7528 snprintf(msg, sizeof(msg),
7529 "commit %s missing from histedit script", id_str);
7530 free(id_str);
7531 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7535 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
7536 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
7537 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
7538 "last commit in histedit script cannot be folded");
7540 return NULL;
7543 static const struct got_error *
7544 histedit_run_editor(struct got_histedit_list *histedit_cmds,
7545 const char *path, struct got_object_id_queue *commits,
7546 struct got_repository *repo)
7548 const struct got_error *err = NULL;
7549 char *editor;
7550 FILE *f = NULL;
7552 err = get_editor(&editor);
7553 if (err)
7554 return err;
7556 if (spawn_editor(editor, path) == -1) {
7557 err = got_error_from_errno("failed spawning editor");
7558 goto done;
7561 f = fopen(path, "r");
7562 if (f == NULL) {
7563 err = got_error_from_errno("fopen");
7564 goto done;
7566 err = histedit_parse_list(histedit_cmds, f, repo);
7567 if (err)
7568 goto done;
7570 err = histedit_check_script(histedit_cmds, commits, repo);
7571 done:
7572 if (f && fclose(f) != 0 && err == NULL)
7573 err = got_error_from_errno("fclose");
7574 free(editor);
7575 return err;
7578 static const struct got_error *
7579 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
7580 struct got_object_id_queue *, const char *, const char *,
7581 struct got_repository *);
7583 static const struct got_error *
7584 histedit_edit_script(struct got_histedit_list *histedit_cmds,
7585 struct got_object_id_queue *commits, const char *branch_name,
7586 int edit_logmsg_only, struct got_repository *repo)
7588 const struct got_error *err;
7589 FILE *f = NULL;
7590 char *path = NULL;
7592 err = got_opentemp_named(&path, &f, "got-histedit");
7593 if (err)
7594 return err;
7596 err = write_cmd_list(f, branch_name, commits);
7597 if (err)
7598 goto done;
7600 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
7601 if (err)
7602 goto done;
7604 if (edit_logmsg_only) {
7605 rewind(f);
7606 err = histedit_parse_list(histedit_cmds, f, repo);
7607 } else {
7608 if (fclose(f) != 0) {
7609 err = got_error_from_errno("fclose");
7610 goto done;
7612 f = NULL;
7613 err = histedit_run_editor(histedit_cmds, path, commits, repo);
7614 if (err) {
7615 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7616 err->code != GOT_ERR_HISTEDIT_CMD)
7617 goto done;
7618 err = histedit_edit_list_retry(histedit_cmds, err,
7619 commits, path, branch_name, repo);
7622 done:
7623 if (f && fclose(f) != 0 && err == NULL)
7624 err = got_error_from_errno("fclose");
7625 if (path && unlink(path) != 0 && err == NULL)
7626 err = got_error_from_errno2("unlink", path);
7627 free(path);
7628 return err;
7631 static const struct got_error *
7632 histedit_save_list(struct got_histedit_list *histedit_cmds,
7633 struct got_worktree *worktree, struct got_repository *repo)
7635 const struct got_error *err = NULL;
7636 char *path = NULL;
7637 FILE *f = NULL;
7638 struct got_histedit_list_entry *hle;
7639 struct got_commit_object *commit = NULL;
7641 err = got_worktree_get_histedit_script_path(&path, worktree);
7642 if (err)
7643 return err;
7645 f = fopen(path, "w");
7646 if (f == NULL) {
7647 err = got_error_from_errno2("fopen", path);
7648 goto done;
7650 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7651 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
7652 repo);
7653 if (err)
7654 break;
7656 if (hle->logmsg) {
7657 int n = fprintf(f, "%c %s\n",
7658 GOT_HISTEDIT_MESG, hle->logmsg);
7659 if (n < 0) {
7660 err = got_ferror(f, GOT_ERR_IO);
7661 break;
7665 done:
7666 if (f && fclose(f) != 0 && err == NULL)
7667 err = got_error_from_errno("fclose");
7668 free(path);
7669 if (commit)
7670 got_object_commit_close(commit);
7671 return err;
7674 void
7675 histedit_free_list(struct got_histedit_list *histedit_cmds)
7677 struct got_histedit_list_entry *hle;
7679 while ((hle = TAILQ_FIRST(histedit_cmds))) {
7680 TAILQ_REMOVE(histedit_cmds, hle, entry);
7681 free(hle);
7685 static const struct got_error *
7686 histedit_load_list(struct got_histedit_list *histedit_cmds,
7687 const char *path, struct got_repository *repo)
7689 const struct got_error *err = NULL;
7690 FILE *f = NULL;
7692 f = fopen(path, "r");
7693 if (f == NULL) {
7694 err = got_error_from_errno2("fopen", path);
7695 goto done;
7698 err = histedit_parse_list(histedit_cmds, f, repo);
7699 done:
7700 if (f && fclose(f) != 0 && err == NULL)
7701 err = got_error_from_errno("fclose");
7702 return err;
7705 static const struct got_error *
7706 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
7707 const struct got_error *edit_err, struct got_object_id_queue *commits,
7708 const char *path, const char *branch_name, struct got_repository *repo)
7710 const struct got_error *err = NULL, *prev_err = edit_err;
7711 int resp = ' ';
7713 while (resp != 'c' && resp != 'r' && resp != 'a') {
7714 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
7715 "or (a)bort: ", getprogname(), prev_err->msg);
7716 resp = getchar();
7717 if (resp == '\n')
7718 resp = getchar();
7719 if (resp == 'c') {
7720 histedit_free_list(histedit_cmds);
7721 err = histedit_run_editor(histedit_cmds, path, commits,
7722 repo);
7723 if (err) {
7724 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7725 err->code != GOT_ERR_HISTEDIT_CMD)
7726 break;
7727 prev_err = err;
7728 resp = ' ';
7729 continue;
7731 break;
7732 } else if (resp == 'r') {
7733 histedit_free_list(histedit_cmds);
7734 err = histedit_edit_script(histedit_cmds,
7735 commits, branch_name, 0, repo);
7736 if (err) {
7737 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7738 err->code != GOT_ERR_HISTEDIT_CMD)
7739 break;
7740 prev_err = err;
7741 resp = ' ';
7742 continue;
7744 break;
7745 } else if (resp == 'a') {
7746 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
7747 break;
7748 } else
7749 printf("invalid response '%c'\n", resp);
7752 return err;
7755 static const struct got_error *
7756 histedit_complete(struct got_worktree *worktree,
7757 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
7758 struct got_reference *branch, struct got_repository *repo)
7760 printf("Switching work tree to %s\n",
7761 got_ref_get_symref_target(branch));
7762 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
7763 branch, repo);
7766 static const struct got_error *
7767 show_histedit_progress(struct got_commit_object *commit,
7768 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
7770 const struct got_error *err;
7771 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7773 err = got_object_id_str(&old_id_str, hle->commit_id);
7774 if (err)
7775 goto done;
7777 if (new_id) {
7778 err = got_object_id_str(&new_id_str, new_id);
7779 if (err)
7780 goto done;
7783 old_id_str[12] = '\0';
7784 if (new_id_str)
7785 new_id_str[12] = '\0';
7787 if (hle->logmsg) {
7788 logmsg = strdup(hle->logmsg);
7789 if (logmsg == NULL) {
7790 err = got_error_from_errno("strdup");
7791 goto done;
7793 trim_logmsg(logmsg, 42);
7794 } else {
7795 err = get_short_logmsg(&logmsg, 42, commit);
7796 if (err)
7797 goto done;
7800 switch (hle->cmd->code) {
7801 case GOT_HISTEDIT_PICK:
7802 case GOT_HISTEDIT_EDIT:
7803 printf("%s -> %s: %s\n", old_id_str,
7804 new_id_str ? new_id_str : "no-op change", logmsg);
7805 break;
7806 case GOT_HISTEDIT_DROP:
7807 case GOT_HISTEDIT_FOLD:
7808 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
7809 logmsg);
7810 break;
7811 default:
7812 break;
7814 done:
7815 free(old_id_str);
7816 free(new_id_str);
7817 return err;
7820 static const struct got_error *
7821 histedit_commit(struct got_pathlist_head *merged_paths,
7822 struct got_worktree *worktree, struct got_fileindex *fileindex,
7823 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
7824 struct got_repository *repo)
7826 const struct got_error *err;
7827 struct got_commit_object *commit;
7828 struct got_object_id *new_commit_id;
7830 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
7831 && hle->logmsg == NULL) {
7832 err = histedit_edit_logmsg(hle, repo);
7833 if (err)
7834 return err;
7837 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7838 if (err)
7839 return err;
7841 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
7842 worktree, fileindex, tmp_branch, commit, hle->commit_id,
7843 hle->logmsg, repo);
7844 if (err) {
7845 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
7846 goto done;
7847 err = show_histedit_progress(commit, hle, NULL);
7848 } else {
7849 err = show_histedit_progress(commit, hle, new_commit_id);
7850 free(new_commit_id);
7852 done:
7853 got_object_commit_close(commit);
7854 return err;
7857 static const struct got_error *
7858 histedit_skip_commit(struct got_histedit_list_entry *hle,
7859 struct got_worktree *worktree, struct got_repository *repo)
7861 const struct got_error *error;
7862 struct got_commit_object *commit;
7864 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
7865 repo);
7866 if (error)
7867 return error;
7869 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
7870 if (error)
7871 return error;
7873 error = show_histedit_progress(commit, hle, NULL);
7874 got_object_commit_close(commit);
7875 return error;
7878 static const struct got_error *
7879 check_local_changes(void *arg, unsigned char status,
7880 unsigned char staged_status, const char *path,
7881 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
7882 struct got_object_id *commit_id, int dirfd, const char *de_name)
7884 int *have_local_changes = arg;
7886 switch (status) {
7887 case GOT_STATUS_ADD:
7888 case GOT_STATUS_DELETE:
7889 case GOT_STATUS_MODIFY:
7890 case GOT_STATUS_CONFLICT:
7891 *have_local_changes = 1;
7892 return got_error(GOT_ERR_CANCELLED);
7893 default:
7894 break;
7897 switch (staged_status) {
7898 case GOT_STATUS_ADD:
7899 case GOT_STATUS_DELETE:
7900 case GOT_STATUS_MODIFY:
7901 *have_local_changes = 1;
7902 return got_error(GOT_ERR_CANCELLED);
7903 default:
7904 break;
7907 return NULL;
7910 static const struct got_error *
7911 cmd_histedit(int argc, char *argv[])
7913 const struct got_error *error = NULL;
7914 struct got_worktree *worktree = NULL;
7915 struct got_fileindex *fileindex = NULL;
7916 struct got_repository *repo = NULL;
7917 char *cwd = NULL;
7918 struct got_reference *branch = NULL;
7919 struct got_reference *tmp_branch = NULL;
7920 struct got_object_id *resume_commit_id = NULL;
7921 struct got_object_id *base_commit_id = NULL;
7922 struct got_object_id *head_commit_id = NULL;
7923 struct got_commit_object *commit = NULL;
7924 int ch, rebase_in_progress = 0, did_something;
7925 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
7926 int edit_logmsg_only = 0;
7927 const char *edit_script_path = NULL;
7928 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7929 struct got_object_id_queue commits;
7930 struct got_pathlist_head merged_paths;
7931 const struct got_object_id_queue *parent_ids;
7932 struct got_object_qid *pid;
7933 struct got_histedit_list histedit_cmds;
7934 struct got_histedit_list_entry *hle;
7936 SIMPLEQ_INIT(&commits);
7937 TAILQ_INIT(&histedit_cmds);
7938 TAILQ_INIT(&merged_paths);
7940 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
7941 switch (ch) {
7942 case 'a':
7943 abort_edit = 1;
7944 break;
7945 case 'c':
7946 continue_edit = 1;
7947 break;
7948 case 'F':
7949 edit_script_path = optarg;
7950 break;
7951 case 'm':
7952 edit_logmsg_only = 1;
7953 break;
7954 default:
7955 usage_histedit();
7956 /* NOTREACHED */
7960 argc -= optind;
7961 argv += optind;
7963 #ifndef PROFILE
7964 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7965 "unveil", NULL) == -1)
7966 err(1, "pledge");
7967 #endif
7968 if (abort_edit && continue_edit)
7969 errx(1, "histedit's -a and -c options are mutually exclusive");
7970 if (edit_script_path && edit_logmsg_only)
7971 errx(1, "histedit's -F and -m options are mutually exclusive");
7972 if (abort_edit && edit_logmsg_only)
7973 errx(1, "histedit's -a and -m options are mutually exclusive");
7974 if (continue_edit && edit_logmsg_only)
7975 errx(1, "histedit's -c and -m options are mutually exclusive");
7976 if (argc != 0)
7977 usage_histedit();
7980 * This command cannot apply unveil(2) in all cases because the
7981 * user may choose to run an editor to edit the histedit script
7982 * and to edit individual commit log messages.
7983 * unveil(2) traverses exec(2); if an editor is used we have to
7984 * apply unveil after edit script and log messages have been written.
7985 * XXX TODO: Make use of unveil(2) where possible.
7988 cwd = getcwd(NULL, 0);
7989 if (cwd == NULL) {
7990 error = got_error_from_errno("getcwd");
7991 goto done;
7993 error = got_worktree_open(&worktree, cwd);
7994 if (error) {
7995 if (error->code == GOT_ERR_NOT_WORKTREE)
7996 error = wrap_not_worktree_error(error, "histedit", cwd);
7997 goto done;
8000 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8001 NULL);
8002 if (error != NULL)
8003 goto done;
8005 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8006 if (error)
8007 goto done;
8008 if (rebase_in_progress) {
8009 error = got_error(GOT_ERR_REBASING);
8010 goto done;
8013 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8014 if (error)
8015 goto done;
8017 if (edit_in_progress && edit_logmsg_only) {
8018 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8019 "histedit operation is in progress in this "
8020 "work tree and must be continued or aborted "
8021 "before the -m option can be used");
8022 goto done;
8025 if (edit_in_progress && abort_edit) {
8026 error = got_worktree_histedit_continue(&resume_commit_id,
8027 &tmp_branch, &branch, &base_commit_id, &fileindex,
8028 worktree, repo);
8029 if (error)
8030 goto done;
8031 printf("Switching work tree to %s\n",
8032 got_ref_get_symref_target(branch));
8033 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8034 branch, base_commit_id, update_progress, &did_something);
8035 if (error)
8036 goto done;
8037 printf("Histedit of %s aborted\n",
8038 got_ref_get_symref_target(branch));
8039 goto done; /* nothing else to do */
8040 } else if (abort_edit) {
8041 error = got_error(GOT_ERR_NOT_HISTEDIT);
8042 goto done;
8045 if (continue_edit) {
8046 char *path;
8048 if (!edit_in_progress) {
8049 error = got_error(GOT_ERR_NOT_HISTEDIT);
8050 goto done;
8053 error = got_worktree_get_histedit_script_path(&path, worktree);
8054 if (error)
8055 goto done;
8057 error = histedit_load_list(&histedit_cmds, path, repo);
8058 free(path);
8059 if (error)
8060 goto done;
8062 error = got_worktree_histedit_continue(&resume_commit_id,
8063 &tmp_branch, &branch, &base_commit_id, &fileindex,
8064 worktree, repo);
8065 if (error)
8066 goto done;
8068 error = got_ref_resolve(&head_commit_id, repo, branch);
8069 if (error)
8070 goto done;
8072 error = got_object_open_as_commit(&commit, repo,
8073 head_commit_id);
8074 if (error)
8075 goto done;
8076 parent_ids = got_object_commit_get_parent_ids(commit);
8077 pid = SIMPLEQ_FIRST(parent_ids);
8078 if (pid == NULL) {
8079 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8080 goto done;
8082 error = collect_commits(&commits, head_commit_id, pid->id,
8083 base_commit_id, got_worktree_get_path_prefix(worktree),
8084 GOT_ERR_HISTEDIT_PATH, repo);
8085 got_object_commit_close(commit);
8086 commit = NULL;
8087 if (error)
8088 goto done;
8089 } else {
8090 if (edit_in_progress) {
8091 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8092 goto done;
8095 error = got_ref_open(&branch, repo,
8096 got_worktree_get_head_ref_name(worktree), 0);
8097 if (error != NULL)
8098 goto done;
8100 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8101 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8102 "will not edit commit history of a branch outside "
8103 "the \"refs/heads/\" reference namespace");
8104 goto done;
8107 error = got_ref_resolve(&head_commit_id, repo, branch);
8108 got_ref_close(branch);
8109 branch = NULL;
8110 if (error)
8111 goto done;
8113 error = got_object_open_as_commit(&commit, repo,
8114 head_commit_id);
8115 if (error)
8116 goto done;
8117 parent_ids = got_object_commit_get_parent_ids(commit);
8118 pid = SIMPLEQ_FIRST(parent_ids);
8119 if (pid == NULL) {
8120 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8121 goto done;
8123 error = collect_commits(&commits, head_commit_id, pid->id,
8124 got_worktree_get_base_commit_id(worktree),
8125 got_worktree_get_path_prefix(worktree),
8126 GOT_ERR_HISTEDIT_PATH, repo);
8127 got_object_commit_close(commit);
8128 commit = NULL;
8129 if (error)
8130 goto done;
8132 if (SIMPLEQ_EMPTY(&commits)) {
8133 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8134 goto done;
8137 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8138 &base_commit_id, &fileindex, worktree, repo);
8139 if (error)
8140 goto done;
8142 if (edit_script_path) {
8143 error = histedit_load_list(&histedit_cmds,
8144 edit_script_path, repo);
8145 if (error) {
8146 got_worktree_histedit_abort(worktree, fileindex,
8147 repo, branch, base_commit_id,
8148 update_progress, &did_something);
8149 goto done;
8151 } else {
8152 const char *branch_name;
8153 branch_name = got_ref_get_symref_target(branch);
8154 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8155 branch_name += 11;
8156 error = histedit_edit_script(&histedit_cmds, &commits,
8157 branch_name, edit_logmsg_only, repo);
8158 if (error) {
8159 got_worktree_histedit_abort(worktree, fileindex,
8160 repo, branch, base_commit_id,
8161 update_progress, &did_something);
8162 goto done;
8167 error = histedit_save_list(&histedit_cmds, worktree,
8168 repo);
8169 if (error) {
8170 got_worktree_histedit_abort(worktree, fileindex,
8171 repo, branch, base_commit_id,
8172 update_progress, &did_something);
8173 goto done;
8178 error = histedit_check_script(&histedit_cmds, &commits, repo);
8179 if (error)
8180 goto done;
8182 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8183 if (resume_commit_id) {
8184 if (got_object_id_cmp(hle->commit_id,
8185 resume_commit_id) != 0)
8186 continue;
8188 resume_commit_id = NULL;
8189 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8190 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8191 error = histedit_skip_commit(hle, worktree,
8192 repo);
8193 if (error)
8194 goto done;
8195 } else {
8196 struct got_pathlist_head paths;
8197 int have_changes = 0;
8199 TAILQ_INIT(&paths);
8200 error = got_pathlist_append(&paths, "", NULL);
8201 if (error)
8202 goto done;
8203 error = got_worktree_status(worktree, &paths,
8204 repo, check_local_changes, &have_changes,
8205 check_cancelled, NULL);
8206 got_pathlist_free(&paths);
8207 if (error) {
8208 if (error->code != GOT_ERR_CANCELLED)
8209 goto done;
8210 if (sigint_received || sigpipe_received)
8211 goto done;
8213 if (have_changes) {
8214 error = histedit_commit(NULL, worktree,
8215 fileindex, tmp_branch, hle, repo);
8216 if (error)
8217 goto done;
8218 } else {
8219 error = got_object_open_as_commit(
8220 &commit, repo, hle->commit_id);
8221 if (error)
8222 goto done;
8223 error = show_histedit_progress(commit,
8224 hle, NULL);
8225 got_object_commit_close(commit);
8226 commit = NULL;
8227 if (error)
8228 goto done;
8231 continue;
8234 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8235 error = histedit_skip_commit(hle, worktree, repo);
8236 if (error)
8237 goto done;
8238 continue;
8241 error = got_object_open_as_commit(&commit, repo,
8242 hle->commit_id);
8243 if (error)
8244 goto done;
8245 parent_ids = got_object_commit_get_parent_ids(commit);
8246 pid = SIMPLEQ_FIRST(parent_ids);
8248 error = got_worktree_histedit_merge_files(&merged_paths,
8249 worktree, fileindex, pid->id, hle->commit_id, repo,
8250 rebase_progress, &rebase_status, check_cancelled, NULL);
8251 if (error)
8252 goto done;
8253 got_object_commit_close(commit);
8254 commit = NULL;
8256 if (rebase_status == GOT_STATUS_CONFLICT) {
8257 error = show_rebase_merge_conflict(hle->commit_id,
8258 repo);
8259 if (error)
8260 goto done;
8261 got_worktree_rebase_pathlist_free(&merged_paths);
8262 break;
8265 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8266 char *id_str;
8267 error = got_object_id_str(&id_str, hle->commit_id);
8268 if (error)
8269 goto done;
8270 printf("Stopping histedit for amending commit %s\n",
8271 id_str);
8272 free(id_str);
8273 got_worktree_rebase_pathlist_free(&merged_paths);
8274 error = got_worktree_histedit_postpone(worktree,
8275 fileindex);
8276 goto done;
8279 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8280 error = histedit_skip_commit(hle, worktree, repo);
8281 if (error)
8282 goto done;
8283 continue;
8286 error = histedit_commit(&merged_paths, worktree, fileindex,
8287 tmp_branch, hle, repo);
8288 got_worktree_rebase_pathlist_free(&merged_paths);
8289 if (error)
8290 goto done;
8293 if (rebase_status == GOT_STATUS_CONFLICT) {
8294 error = got_worktree_histedit_postpone(worktree, fileindex);
8295 if (error)
8296 goto done;
8297 error = got_error_msg(GOT_ERR_CONFLICTS,
8298 "conflicts must be resolved before histedit can continue");
8299 } else
8300 error = histedit_complete(worktree, fileindex, tmp_branch,
8301 branch, repo);
8302 done:
8303 got_object_id_queue_free(&commits);
8304 histedit_free_list(&histedit_cmds);
8305 free(head_commit_id);
8306 free(base_commit_id);
8307 free(resume_commit_id);
8308 if (commit)
8309 got_object_commit_close(commit);
8310 if (branch)
8311 got_ref_close(branch);
8312 if (tmp_branch)
8313 got_ref_close(tmp_branch);
8314 if (worktree)
8315 got_worktree_close(worktree);
8316 if (repo)
8317 got_repo_close(repo);
8318 return error;
8321 __dead static void
8322 usage_integrate(void)
8324 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
8325 exit(1);
8328 static const struct got_error *
8329 cmd_integrate(int argc, char *argv[])
8331 const struct got_error *error = NULL;
8332 struct got_repository *repo = NULL;
8333 struct got_worktree *worktree = NULL;
8334 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
8335 const char *branch_arg = NULL;
8336 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
8337 struct got_fileindex *fileindex = NULL;
8338 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
8339 int ch, did_something = 0;
8341 while ((ch = getopt(argc, argv, "")) != -1) {
8342 switch (ch) {
8343 default:
8344 usage_integrate();
8345 /* NOTREACHED */
8349 argc -= optind;
8350 argv += optind;
8352 if (argc != 1)
8353 usage_integrate();
8354 branch_arg = argv[0];
8356 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8357 "unveil", NULL) == -1)
8358 err(1, "pledge");
8360 cwd = getcwd(NULL, 0);
8361 if (cwd == NULL) {
8362 error = got_error_from_errno("getcwd");
8363 goto done;
8366 error = got_worktree_open(&worktree, cwd);
8367 if (error) {
8368 if (error->code == GOT_ERR_NOT_WORKTREE)
8369 error = wrap_not_worktree_error(error, "integrate",
8370 cwd);
8371 goto done;
8374 error = check_rebase_or_histedit_in_progress(worktree);
8375 if (error)
8376 goto done;
8378 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8379 NULL);
8380 if (error != NULL)
8381 goto done;
8383 error = apply_unveil(got_repo_get_path(repo), 0,
8384 got_worktree_get_root_path(worktree));
8385 if (error)
8386 goto done;
8388 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
8389 error = got_error_from_errno("asprintf");
8390 goto done;
8393 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
8394 &base_branch_ref, worktree, refname, repo);
8395 if (error)
8396 goto done;
8398 refname = strdup(got_ref_get_name(branch_ref));
8399 if (refname == NULL) {
8400 error = got_error_from_errno("strdup");
8401 got_worktree_integrate_abort(worktree, fileindex, repo,
8402 branch_ref, base_branch_ref);
8403 goto done;
8405 base_refname = strdup(got_ref_get_name(base_branch_ref));
8406 if (base_refname == NULL) {
8407 error = got_error_from_errno("strdup");
8408 got_worktree_integrate_abort(worktree, fileindex, repo,
8409 branch_ref, base_branch_ref);
8410 goto done;
8413 error = got_ref_resolve(&commit_id, repo, branch_ref);
8414 if (error)
8415 goto done;
8417 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
8418 if (error)
8419 goto done;
8421 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
8422 error = got_error_msg(GOT_ERR_SAME_BRANCH,
8423 "specified branch has already been integrated");
8424 got_worktree_integrate_abort(worktree, fileindex, repo,
8425 branch_ref, base_branch_ref);
8426 goto done;
8429 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
8430 if (error) {
8431 if (error->code == GOT_ERR_ANCESTRY)
8432 error = got_error(GOT_ERR_REBASE_REQUIRED);
8433 got_worktree_integrate_abort(worktree, fileindex, repo,
8434 branch_ref, base_branch_ref);
8435 goto done;
8438 error = got_worktree_integrate_continue(worktree, fileindex, repo,
8439 branch_ref, base_branch_ref, update_progress, &did_something,
8440 check_cancelled, NULL);
8441 if (error)
8442 goto done;
8444 printf("Integrated %s into %s\n", refname, base_refname);
8445 done:
8446 if (repo)
8447 got_repo_close(repo);
8448 if (worktree)
8449 got_worktree_close(worktree);
8450 free(cwd);
8451 free(base_commit_id);
8452 free(commit_id);
8453 free(refname);
8454 free(base_refname);
8455 return error;
8458 __dead static void
8459 usage_stage(void)
8461 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
8462 "[file-path ...]\n",
8463 getprogname());
8464 exit(1);
8467 static const struct got_error *
8468 print_stage(void *arg, unsigned char status, unsigned char staged_status,
8469 const char *path, struct got_object_id *blob_id,
8470 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
8471 int dirfd, const char *de_name)
8473 const struct got_error *err = NULL;
8474 char *id_str = NULL;
8476 if (staged_status != GOT_STATUS_ADD &&
8477 staged_status != GOT_STATUS_MODIFY &&
8478 staged_status != GOT_STATUS_DELETE)
8479 return NULL;
8481 if (staged_status == GOT_STATUS_ADD ||
8482 staged_status == GOT_STATUS_MODIFY)
8483 err = got_object_id_str(&id_str, staged_blob_id);
8484 else
8485 err = got_object_id_str(&id_str, blob_id);
8486 if (err)
8487 return err;
8489 printf("%s %c %s\n", id_str, staged_status, path);
8490 free(id_str);
8491 return NULL;
8494 static const struct got_error *
8495 cmd_stage(int argc, char *argv[])
8497 const struct got_error *error = NULL;
8498 struct got_repository *repo = NULL;
8499 struct got_worktree *worktree = NULL;
8500 char *cwd = NULL;
8501 struct got_pathlist_head paths;
8502 struct got_pathlist_entry *pe;
8503 int ch, list_stage = 0, pflag = 0;
8504 FILE *patch_script_file = NULL;
8505 const char *patch_script_path = NULL;
8506 struct choose_patch_arg cpa;
8508 TAILQ_INIT(&paths);
8510 while ((ch = getopt(argc, argv, "lpF:")) != -1) {
8511 switch (ch) {
8512 case 'l':
8513 list_stage = 1;
8514 break;
8515 case 'p':
8516 pflag = 1;
8517 break;
8518 case 'F':
8519 patch_script_path = optarg;
8520 break;
8521 default:
8522 usage_stage();
8523 /* NOTREACHED */
8527 argc -= optind;
8528 argv += optind;
8530 #ifndef PROFILE
8531 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8532 "unveil", NULL) == -1)
8533 err(1, "pledge");
8534 #endif
8535 if (list_stage && (pflag || patch_script_path))
8536 errx(1, "-l option cannot be used with other options");
8537 if (patch_script_path && !pflag)
8538 errx(1, "-F option can only be used together with -p option");
8540 cwd = getcwd(NULL, 0);
8541 if (cwd == NULL) {
8542 error = got_error_from_errno("getcwd");
8543 goto done;
8546 error = got_worktree_open(&worktree, cwd);
8547 if (error) {
8548 if (error->code == GOT_ERR_NOT_WORKTREE)
8549 error = wrap_not_worktree_error(error, "stage", cwd);
8550 goto done;
8553 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8554 NULL);
8555 if (error != NULL)
8556 goto done;
8558 if (patch_script_path) {
8559 patch_script_file = fopen(patch_script_path, "r");
8560 if (patch_script_file == NULL) {
8561 error = got_error_from_errno2("fopen",
8562 patch_script_path);
8563 goto done;
8566 error = apply_unveil(got_repo_get_path(repo), 0,
8567 got_worktree_get_root_path(worktree));
8568 if (error)
8569 goto done;
8571 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8572 if (error)
8573 goto done;
8575 if (list_stage)
8576 error = got_worktree_status(worktree, &paths, repo,
8577 print_stage, NULL, check_cancelled, NULL);
8578 else {
8579 cpa.patch_script_file = patch_script_file;
8580 cpa.action = "stage";
8581 error = got_worktree_stage(worktree, &paths,
8582 pflag ? NULL : print_status, NULL,
8583 pflag ? choose_patch : NULL, &cpa, repo);
8585 done:
8586 if (patch_script_file && fclose(patch_script_file) == EOF &&
8587 error == NULL)
8588 error = got_error_from_errno2("fclose", patch_script_path);
8589 if (repo)
8590 got_repo_close(repo);
8591 if (worktree)
8592 got_worktree_close(worktree);
8593 TAILQ_FOREACH(pe, &paths, entry)
8594 free((char *)pe->path);
8595 got_pathlist_free(&paths);
8596 free(cwd);
8597 return error;
8600 __dead static void
8601 usage_unstage(void)
8603 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
8604 "[file-path ...]\n",
8605 getprogname());
8606 exit(1);
8610 static const struct got_error *
8611 cmd_unstage(int argc, char *argv[])
8613 const struct got_error *error = NULL;
8614 struct got_repository *repo = NULL;
8615 struct got_worktree *worktree = NULL;
8616 char *cwd = NULL;
8617 struct got_pathlist_head paths;
8618 struct got_pathlist_entry *pe;
8619 int ch, did_something = 0, pflag = 0;
8620 FILE *patch_script_file = NULL;
8621 const char *patch_script_path = NULL;
8622 struct choose_patch_arg cpa;
8624 TAILQ_INIT(&paths);
8626 while ((ch = getopt(argc, argv, "pF:")) != -1) {
8627 switch (ch) {
8628 case 'p':
8629 pflag = 1;
8630 break;
8631 case 'F':
8632 patch_script_path = optarg;
8633 break;
8634 default:
8635 usage_unstage();
8636 /* NOTREACHED */
8640 argc -= optind;
8641 argv += optind;
8643 #ifndef PROFILE
8644 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8645 "unveil", NULL) == -1)
8646 err(1, "pledge");
8647 #endif
8648 if (patch_script_path && !pflag)
8649 errx(1, "-F option can only be used together with -p option");
8651 cwd = getcwd(NULL, 0);
8652 if (cwd == NULL) {
8653 error = got_error_from_errno("getcwd");
8654 goto done;
8657 error = got_worktree_open(&worktree, cwd);
8658 if (error) {
8659 if (error->code == GOT_ERR_NOT_WORKTREE)
8660 error = wrap_not_worktree_error(error, "unstage", cwd);
8661 goto done;
8664 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8665 NULL);
8666 if (error != NULL)
8667 goto done;
8669 if (patch_script_path) {
8670 patch_script_file = fopen(patch_script_path, "r");
8671 if (patch_script_file == NULL) {
8672 error = got_error_from_errno2("fopen",
8673 patch_script_path);
8674 goto done;
8678 error = apply_unveil(got_repo_get_path(repo), 0,
8679 got_worktree_get_root_path(worktree));
8680 if (error)
8681 goto done;
8683 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8684 if (error)
8685 goto done;
8687 cpa.patch_script_file = patch_script_file;
8688 cpa.action = "unstage";
8689 error = got_worktree_unstage(worktree, &paths, update_progress,
8690 &did_something, pflag ? choose_patch : NULL, &cpa, repo);
8691 done:
8692 if (patch_script_file && fclose(patch_script_file) == EOF &&
8693 error == NULL)
8694 error = got_error_from_errno2("fclose", patch_script_path);
8695 if (repo)
8696 got_repo_close(repo);
8697 if (worktree)
8698 got_worktree_close(worktree);
8699 TAILQ_FOREACH(pe, &paths, entry)
8700 free((char *)pe->path);
8701 got_pathlist_free(&paths);
8702 free(cwd);
8703 return error;
8706 __dead static void
8707 usage_cat(void)
8709 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
8710 "arg1 [arg2 ...]\n", getprogname());
8711 exit(1);
8714 static const struct got_error *
8715 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8717 const struct got_error *err;
8718 struct got_blob_object *blob;
8720 err = got_object_open_as_blob(&blob, repo, id, 8192);
8721 if (err)
8722 return err;
8724 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
8725 got_object_blob_close(blob);
8726 return err;
8729 static const struct got_error *
8730 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8732 const struct got_error *err;
8733 struct got_tree_object *tree;
8734 int nentries, i;
8736 err = got_object_open_as_tree(&tree, repo, id);
8737 if (err)
8738 return err;
8740 nentries = got_object_tree_get_nentries(tree);
8741 for (i = 0; i < nentries; i++) {
8742 struct got_tree_entry *te;
8743 char *id_str;
8744 if (sigint_received || sigpipe_received)
8745 break;
8746 te = got_object_tree_get_entry(tree, i);
8747 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
8748 if (err)
8749 break;
8750 fprintf(outfile, "%s %.7o %s\n", id_str,
8751 got_tree_entry_get_mode(te),
8752 got_tree_entry_get_name(te));
8753 free(id_str);
8756 got_object_tree_close(tree);
8757 return err;
8760 static const struct got_error *
8761 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8763 const struct got_error *err;
8764 struct got_commit_object *commit;
8765 const struct got_object_id_queue *parent_ids;
8766 struct got_object_qid *pid;
8767 char *id_str = NULL;
8768 const char *logmsg = NULL;
8770 err = got_object_open_as_commit(&commit, repo, id);
8771 if (err)
8772 return err;
8774 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
8775 if (err)
8776 goto done;
8778 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
8779 parent_ids = got_object_commit_get_parent_ids(commit);
8780 fprintf(outfile, "numparents %d\n",
8781 got_object_commit_get_nparents(commit));
8782 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
8783 char *pid_str;
8784 err = got_object_id_str(&pid_str, pid->id);
8785 if (err)
8786 goto done;
8787 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
8788 free(pid_str);
8790 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
8791 got_object_commit_get_author(commit),
8792 got_object_commit_get_author_time(commit));
8794 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
8795 got_object_commit_get_author(commit),
8796 got_object_commit_get_committer_time(commit));
8798 logmsg = got_object_commit_get_logmsg_raw(commit);
8799 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
8800 fprintf(outfile, "%s", logmsg);
8801 done:
8802 free(id_str);
8803 got_object_commit_close(commit);
8804 return err;
8807 static const struct got_error *
8808 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8810 const struct got_error *err;
8811 struct got_tag_object *tag;
8812 char *id_str = NULL;
8813 const char *tagmsg = NULL;
8815 err = got_object_open_as_tag(&tag, repo, id);
8816 if (err)
8817 return err;
8819 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
8820 if (err)
8821 goto done;
8823 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
8825 switch (got_object_tag_get_object_type(tag)) {
8826 case GOT_OBJ_TYPE_BLOB:
8827 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8828 GOT_OBJ_LABEL_BLOB);
8829 break;
8830 case GOT_OBJ_TYPE_TREE:
8831 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8832 GOT_OBJ_LABEL_TREE);
8833 break;
8834 case GOT_OBJ_TYPE_COMMIT:
8835 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8836 GOT_OBJ_LABEL_COMMIT);
8837 break;
8838 case GOT_OBJ_TYPE_TAG:
8839 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8840 GOT_OBJ_LABEL_TAG);
8841 break;
8842 default:
8843 break;
8846 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
8847 got_object_tag_get_name(tag));
8849 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
8850 got_object_tag_get_tagger(tag),
8851 got_object_tag_get_tagger_time(tag));
8853 tagmsg = got_object_tag_get_message(tag);
8854 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
8855 fprintf(outfile, "%s", tagmsg);
8856 done:
8857 free(id_str);
8858 got_object_tag_close(tag);
8859 return err;
8862 static const struct got_error *
8863 cmd_cat(int argc, char *argv[])
8865 const struct got_error *error;
8866 struct got_repository *repo = NULL;
8867 struct got_worktree *worktree = NULL;
8868 char *cwd = NULL, *repo_path = NULL, *label = NULL;
8869 const char *commit_id_str = NULL;
8870 struct got_object_id *id = NULL, *commit_id = NULL;
8871 int ch, obj_type, i, force_path = 0;
8873 #ifndef PROFILE
8874 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8875 NULL) == -1)
8876 err(1, "pledge");
8877 #endif
8879 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
8880 switch (ch) {
8881 case 'c':
8882 commit_id_str = optarg;
8883 break;
8884 case 'r':
8885 repo_path = realpath(optarg, NULL);
8886 if (repo_path == NULL)
8887 return got_error_from_errno2("realpath",
8888 optarg);
8889 got_path_strip_trailing_slashes(repo_path);
8890 break;
8891 case 'P':
8892 force_path = 1;
8893 break;
8894 default:
8895 usage_cat();
8896 /* NOTREACHED */
8900 argc -= optind;
8901 argv += optind;
8903 cwd = getcwd(NULL, 0);
8904 if (cwd == NULL) {
8905 error = got_error_from_errno("getcwd");
8906 goto done;
8908 error = got_worktree_open(&worktree, cwd);
8909 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8910 goto done;
8911 if (worktree) {
8912 if (repo_path == NULL) {
8913 repo_path = strdup(
8914 got_worktree_get_repo_path(worktree));
8915 if (repo_path == NULL) {
8916 error = got_error_from_errno("strdup");
8917 goto done;
8922 if (repo_path == NULL) {
8923 repo_path = getcwd(NULL, 0);
8924 if (repo_path == NULL)
8925 return got_error_from_errno("getcwd");
8928 error = got_repo_open(&repo, repo_path, NULL);
8929 free(repo_path);
8930 if (error != NULL)
8931 goto done;
8933 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
8934 if (error)
8935 goto done;
8937 if (commit_id_str == NULL)
8938 commit_id_str = GOT_REF_HEAD;
8939 error = got_repo_match_object_id(&commit_id, NULL,
8940 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
8941 if (error)
8942 goto done;
8944 for (i = 0; i < argc; i++) {
8945 if (force_path) {
8946 error = got_object_id_by_path(&id, repo, commit_id,
8947 argv[i]);
8948 if (error)
8949 break;
8950 } else {
8951 error = got_repo_match_object_id(&id, &label, argv[i],
8952 GOT_OBJ_TYPE_ANY, 0, repo);
8953 if (error) {
8954 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
8955 error->code != GOT_ERR_NOT_REF)
8956 break;
8957 error = got_object_id_by_path(&id, repo,
8958 commit_id, argv[i]);
8959 if (error)
8960 break;
8964 error = got_object_get_type(&obj_type, repo, id);
8965 if (error)
8966 break;
8968 switch (obj_type) {
8969 case GOT_OBJ_TYPE_BLOB:
8970 error = cat_blob(id, repo, stdout);
8971 break;
8972 case GOT_OBJ_TYPE_TREE:
8973 error = cat_tree(id, repo, stdout);
8974 break;
8975 case GOT_OBJ_TYPE_COMMIT:
8976 error = cat_commit(id, repo, stdout);
8977 break;
8978 case GOT_OBJ_TYPE_TAG:
8979 error = cat_tag(id, repo, stdout);
8980 break;
8981 default:
8982 error = got_error(GOT_ERR_OBJ_TYPE);
8983 break;
8985 if (error)
8986 break;
8987 free(label);
8988 label = NULL;
8989 free(id);
8990 id = NULL;
8992 done:
8993 free(label);
8994 free(id);
8995 free(commit_id);
8996 if (worktree)
8997 got_worktree_close(worktree);
8998 if (repo) {
8999 const struct got_error *repo_error;
9000 repo_error = got_repo_close(repo);
9001 if (error == NULL)
9002 error = repo_error;
9004 return error;