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_object_id *end_id,
3103 struct got_repository *repo, const char *path, int show_patch,
3104 const char *search_pattern, 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 && regcomp(&regex, search_pattern,
3113 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 (end_id != NULL && got_object_id_cmp(id, end_id) == 0))
3161 break;
3163 done:
3164 if (search_pattern)
3165 regfree(&regex);
3166 got_commit_graph_close(graph);
3167 return err;
3170 __dead static void
3171 usage_log(void)
3173 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3174 "[-p] [-x commit] [-s search-pattern] [-r repository-path] "
3175 "[path]\n", getprogname());
3176 exit(1);
3179 static int
3180 get_default_log_limit(void)
3182 const char *got_default_log_limit;
3183 long long n;
3184 const char *errstr;
3186 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3187 if (got_default_log_limit == NULL)
3188 return 0;
3189 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3190 if (errstr != NULL)
3191 return 0;
3192 return n;
3195 static const struct got_error *
3196 resolve_commit_arg(struct got_object_id **id, const char *commit_arg,
3197 struct got_repository *repo)
3199 const struct got_error *err = NULL;
3200 struct got_reference *ref;
3202 *id = NULL;
3204 err = got_ref_open(&ref, repo, commit_arg, 0);
3205 if (err == NULL) {
3206 int obj_type;
3207 err = got_ref_resolve(id, repo, ref);
3208 got_ref_close(ref);
3209 if (err)
3210 return err;
3211 err = got_object_get_type(&obj_type, repo, *id);
3212 if (err)
3213 return err;
3214 if (obj_type == GOT_OBJ_TYPE_TAG) {
3215 struct got_tag_object *tag;
3216 err = got_object_open_as_tag(&tag, repo, *id);
3217 if (err)
3218 return err;
3219 if (got_object_tag_get_object_type(tag) !=
3220 GOT_OBJ_TYPE_COMMIT) {
3221 got_object_tag_close(tag);
3222 return got_error(GOT_ERR_OBJ_TYPE);
3224 free(*id);
3225 *id = got_object_id_dup(
3226 got_object_tag_get_object_id(tag));
3227 if (*id == NULL)
3228 err = got_error_from_errno(
3229 "got_object_id_dup");
3230 got_object_tag_close(tag);
3231 if (err)
3232 return err;
3233 } else if (obj_type != GOT_OBJ_TYPE_COMMIT)
3234 return got_error(GOT_ERR_OBJ_TYPE);
3235 } else {
3236 err = got_repo_match_object_id_prefix(id, commit_arg,
3237 GOT_OBJ_TYPE_COMMIT, repo);
3240 return err;
3243 static const struct got_error *
3244 cmd_log(int argc, char *argv[])
3246 const struct got_error *error;
3247 struct got_repository *repo = NULL;
3248 struct got_worktree *worktree = NULL;
3249 struct got_object_id *start_id = NULL, *end_id = NULL;
3250 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3251 const char *start_commit = NULL, *end_commit = NULL;
3252 const char *search_pattern = NULL;
3253 int diff_context = -1, ch;
3254 int show_patch = 0, limit = 0, log_branches = 0;
3255 const char *errstr;
3256 struct got_reflist_head refs;
3258 SIMPLEQ_INIT(&refs);
3260 #ifndef PROFILE
3261 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3262 NULL)
3263 == -1)
3264 err(1, "pledge");
3265 #endif
3267 limit = get_default_log_limit();
3269 while ((ch = getopt(argc, argv, "bpc:C:l:r:s:x:")) != -1) {
3270 switch (ch) {
3271 case 'p':
3272 show_patch = 1;
3273 break;
3274 case 'c':
3275 start_commit = optarg;
3276 break;
3277 case 'C':
3278 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3279 &errstr);
3280 if (errstr != NULL)
3281 err(1, "-C option %s", errstr);
3282 break;
3283 case 'l':
3284 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3285 if (errstr != NULL)
3286 err(1, "-l option %s", errstr);
3287 break;
3288 case 'b':
3289 log_branches = 1;
3290 break;
3291 case 'r':
3292 repo_path = realpath(optarg, NULL);
3293 if (repo_path == NULL)
3294 return got_error_from_errno2("realpath",
3295 optarg);
3296 got_path_strip_trailing_slashes(repo_path);
3297 break;
3298 case 's':
3299 search_pattern = optarg;
3300 break;
3301 case 'x':
3302 end_commit = optarg;
3303 break;
3304 default:
3305 usage_log();
3306 /* NOTREACHED */
3310 argc -= optind;
3311 argv += optind;
3313 if (diff_context == -1)
3314 diff_context = 3;
3315 else if (!show_patch)
3316 errx(1, "-C reguires -p");
3318 cwd = getcwd(NULL, 0);
3319 if (cwd == NULL) {
3320 error = got_error_from_errno("getcwd");
3321 goto done;
3324 error = got_worktree_open(&worktree, cwd);
3325 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3326 goto done;
3327 error = NULL;
3329 if (argc == 0) {
3330 path = strdup("");
3331 if (path == NULL) {
3332 error = got_error_from_errno("strdup");
3333 goto done;
3335 } else if (argc == 1) {
3336 if (worktree) {
3337 error = got_worktree_resolve_path(&path, worktree,
3338 argv[0]);
3339 if (error)
3340 goto done;
3341 } else {
3342 path = strdup(argv[0]);
3343 if (path == NULL) {
3344 error = got_error_from_errno("strdup");
3345 goto done;
3348 } else
3349 usage_log();
3351 if (repo_path == NULL) {
3352 repo_path = worktree ?
3353 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3355 if (repo_path == NULL) {
3356 error = got_error_from_errno("strdup");
3357 goto done;
3360 error = got_repo_open(&repo, repo_path, NULL);
3361 if (error != NULL)
3362 goto done;
3364 error = apply_unveil(got_repo_get_path(repo), 1,
3365 worktree ? got_worktree_get_root_path(worktree) : NULL);
3366 if (error)
3367 goto done;
3369 if (start_commit == NULL) {
3370 struct got_reference *head_ref;
3371 struct got_commit_object *commit = NULL;
3372 error = got_ref_open(&head_ref, repo,
3373 worktree ? got_worktree_get_head_ref_name(worktree)
3374 : GOT_REF_HEAD, 0);
3375 if (error != NULL)
3376 goto done;
3377 error = got_ref_resolve(&start_id, repo, head_ref);
3378 got_ref_close(head_ref);
3379 if (error != NULL)
3380 goto done;
3381 error = got_object_open_as_commit(&commit, repo,
3382 start_id);
3383 if (error != NULL)
3384 goto done;
3385 got_object_commit_close(commit);
3386 } else {
3387 error = resolve_commit_arg(&start_id, start_commit, repo);
3388 if (error != NULL)
3389 goto done;
3391 if (end_commit != NULL) {
3392 error = resolve_commit_arg(&end_id, end_commit, repo);
3393 if (error != NULL)
3394 goto done;
3397 if (worktree) {
3398 const char *prefix = got_worktree_get_path_prefix(worktree);
3399 char *p;
3400 if (asprintf(&p, "%s%s%s", prefix,
3401 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3402 error = got_error_from_errno("asprintf");
3403 goto done;
3405 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3406 free(p);
3407 } else
3408 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3409 if (error != NULL)
3410 goto done;
3411 if (in_repo_path) {
3412 free(path);
3413 path = in_repo_path;
3416 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3417 if (error)
3418 goto done;
3420 error = print_commits(start_id, end_id, repo, path, show_patch,
3421 search_pattern, diff_context, limit, log_branches, &refs);
3422 done:
3423 free(path);
3424 free(repo_path);
3425 free(cwd);
3426 if (worktree)
3427 got_worktree_close(worktree);
3428 if (repo) {
3429 const struct got_error *repo_error;
3430 repo_error = got_repo_close(repo);
3431 if (error == NULL)
3432 error = repo_error;
3434 got_ref_list_free(&refs);
3435 return error;
3438 __dead static void
3439 usage_diff(void)
3441 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3442 "[-w] [object1 object2 | path]\n", getprogname());
3443 exit(1);
3446 struct print_diff_arg {
3447 struct got_repository *repo;
3448 struct got_worktree *worktree;
3449 int diff_context;
3450 const char *id_str;
3451 int header_shown;
3452 int diff_staged;
3453 int ignore_whitespace;
3456 static const struct got_error *
3457 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3458 const char *path, struct got_object_id *blob_id,
3459 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3460 int dirfd, const char *de_name)
3462 struct print_diff_arg *a = arg;
3463 const struct got_error *err = NULL;
3464 struct got_blob_object *blob1 = NULL;
3465 int fd = -1;
3466 FILE *f2 = NULL;
3467 char *abspath = NULL, *label1 = NULL;
3468 struct stat sb;
3470 if (a->diff_staged) {
3471 if (staged_status != GOT_STATUS_MODIFY &&
3472 staged_status != GOT_STATUS_ADD &&
3473 staged_status != GOT_STATUS_DELETE)
3474 return NULL;
3475 } else {
3476 if (staged_status == GOT_STATUS_DELETE)
3477 return NULL;
3478 if (status == GOT_STATUS_NONEXISTENT)
3479 return got_error_set_errno(ENOENT, path);
3480 if (status != GOT_STATUS_MODIFY &&
3481 status != GOT_STATUS_ADD &&
3482 status != GOT_STATUS_DELETE &&
3483 status != GOT_STATUS_CONFLICT)
3484 return NULL;
3487 if (!a->header_shown) {
3488 printf("diff %s %s%s\n", a->id_str,
3489 got_worktree_get_root_path(a->worktree),
3490 a->diff_staged ? " (staged changes)" : "");
3491 a->header_shown = 1;
3494 if (a->diff_staged) {
3495 const char *label1 = NULL, *label2 = NULL;
3496 switch (staged_status) {
3497 case GOT_STATUS_MODIFY:
3498 label1 = path;
3499 label2 = path;
3500 break;
3501 case GOT_STATUS_ADD:
3502 label2 = path;
3503 break;
3504 case GOT_STATUS_DELETE:
3505 label1 = path;
3506 break;
3507 default:
3508 return got_error(GOT_ERR_FILE_STATUS);
3510 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
3511 label1, label2, a->diff_context, a->ignore_whitespace,
3512 a->repo, stdout);
3515 if (staged_status == GOT_STATUS_ADD ||
3516 staged_status == GOT_STATUS_MODIFY) {
3517 char *id_str;
3518 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
3519 8192);
3520 if (err)
3521 goto done;
3522 err = got_object_id_str(&id_str, staged_blob_id);
3523 if (err)
3524 goto done;
3525 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
3526 err = got_error_from_errno("asprintf");
3527 free(id_str);
3528 goto done;
3530 free(id_str);
3531 } else if (status != GOT_STATUS_ADD) {
3532 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
3533 if (err)
3534 goto done;
3537 if (status != GOT_STATUS_DELETE) {
3538 if (asprintf(&abspath, "%s/%s",
3539 got_worktree_get_root_path(a->worktree), path) == -1) {
3540 err = got_error_from_errno("asprintf");
3541 goto done;
3544 if (dirfd != -1) {
3545 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
3546 if (fd == -1) {
3547 err = got_error_from_errno2("openat", abspath);
3548 goto done;
3550 } else {
3551 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
3552 if (fd == -1) {
3553 err = got_error_from_errno2("open", abspath);
3554 goto done;
3557 if (fstat(fd, &sb) == -1) {
3558 err = got_error_from_errno2("fstat", abspath);
3559 goto done;
3561 f2 = fdopen(fd, "r");
3562 if (f2 == NULL) {
3563 err = got_error_from_errno2("fdopen", abspath);
3564 goto done;
3566 fd = -1;
3567 } else
3568 sb.st_size = 0;
3570 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
3571 a->diff_context, a->ignore_whitespace, stdout);
3572 done:
3573 if (blob1)
3574 got_object_blob_close(blob1);
3575 if (f2 && fclose(f2) == EOF && err == NULL)
3576 err = got_error_from_errno("fclose");
3577 if (fd != -1 && close(fd) == -1 && err == NULL)
3578 err = got_error_from_errno("close");
3579 free(abspath);
3580 return err;
3583 static const struct got_error *
3584 cmd_diff(int argc, char *argv[])
3586 const struct got_error *error;
3587 struct got_repository *repo = NULL;
3588 struct got_worktree *worktree = NULL;
3589 char *cwd = NULL, *repo_path = NULL;
3590 struct got_object_id *id1 = NULL, *id2 = NULL;
3591 const char *id_str1 = NULL, *id_str2 = NULL;
3592 char *label1 = NULL, *label2 = NULL;
3593 int type1, type2;
3594 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
3595 const char *errstr;
3596 char *path = NULL;
3598 #ifndef PROFILE
3599 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3600 NULL) == -1)
3601 err(1, "pledge");
3602 #endif
3604 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
3605 switch (ch) {
3606 case 'C':
3607 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3608 &errstr);
3609 if (errstr != NULL)
3610 err(1, "-C option %s", errstr);
3611 break;
3612 case 'r':
3613 repo_path = realpath(optarg, NULL);
3614 if (repo_path == NULL)
3615 return got_error_from_errno2("realpath",
3616 optarg);
3617 got_path_strip_trailing_slashes(repo_path);
3618 break;
3619 case 's':
3620 diff_staged = 1;
3621 break;
3622 case 'w':
3623 ignore_whitespace = 1;
3624 break;
3625 default:
3626 usage_diff();
3627 /* NOTREACHED */
3631 argc -= optind;
3632 argv += optind;
3634 cwd = getcwd(NULL, 0);
3635 if (cwd == NULL) {
3636 error = got_error_from_errno("getcwd");
3637 goto done;
3639 if (argc <= 1) {
3640 if (repo_path)
3641 errx(1,
3642 "-r option can't be used when diffing a work tree");
3643 error = got_worktree_open(&worktree, cwd);
3644 if (error) {
3645 if (error->code == GOT_ERR_NOT_WORKTREE)
3646 error = wrap_not_worktree_error(error, "diff",
3647 cwd);
3648 goto done;
3650 repo_path = strdup(got_worktree_get_repo_path(worktree));
3651 if (repo_path == NULL) {
3652 error = got_error_from_errno("strdup");
3653 goto done;
3655 if (argc == 1) {
3656 error = got_worktree_resolve_path(&path, worktree,
3657 argv[0]);
3658 if (error)
3659 goto done;
3660 } else {
3661 path = strdup("");
3662 if (path == NULL) {
3663 error = got_error_from_errno("strdup");
3664 goto done;
3667 } else if (argc == 2) {
3668 if (diff_staged)
3669 errx(1, "-s option can't be used when diffing "
3670 "objects in repository");
3671 id_str1 = argv[0];
3672 id_str2 = argv[1];
3673 if (repo_path == NULL) {
3674 error = got_worktree_open(&worktree, cwd);
3675 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3676 goto done;
3677 if (worktree) {
3678 repo_path = strdup(
3679 got_worktree_get_repo_path(worktree));
3680 if (repo_path == NULL) {
3681 error = got_error_from_errno("strdup");
3682 goto done;
3684 } else {
3685 repo_path = strdup(cwd);
3686 if (repo_path == NULL) {
3687 error = got_error_from_errno("strdup");
3688 goto done;
3692 } else
3693 usage_diff();
3695 error = got_repo_open(&repo, repo_path, NULL);
3696 free(repo_path);
3697 if (error != NULL)
3698 goto done;
3700 error = apply_unveil(got_repo_get_path(repo), 1,
3701 worktree ? got_worktree_get_root_path(worktree) : NULL);
3702 if (error)
3703 goto done;
3705 if (argc <= 1) {
3706 struct print_diff_arg arg;
3707 struct got_pathlist_head paths;
3708 char *id_str;
3710 TAILQ_INIT(&paths);
3712 error = got_object_id_str(&id_str,
3713 got_worktree_get_base_commit_id(worktree));
3714 if (error)
3715 goto done;
3716 arg.repo = repo;
3717 arg.worktree = worktree;
3718 arg.diff_context = diff_context;
3719 arg.id_str = id_str;
3720 arg.header_shown = 0;
3721 arg.diff_staged = diff_staged;
3722 arg.ignore_whitespace = ignore_whitespace;
3724 error = got_pathlist_append(&paths, path, NULL);
3725 if (error)
3726 goto done;
3728 error = got_worktree_status(worktree, &paths, repo, print_diff,
3729 &arg, check_cancelled, NULL);
3730 free(id_str);
3731 got_pathlist_free(&paths);
3732 goto done;
3735 error = got_repo_match_object_id(&id1, &label1, id_str1,
3736 GOT_OBJ_TYPE_ANY, 1, repo);
3737 if (error)
3738 goto done;
3740 error = got_repo_match_object_id(&id2, &label2, id_str2,
3741 GOT_OBJ_TYPE_ANY, 1, repo);
3742 if (error)
3743 goto done;
3745 error = got_object_get_type(&type1, repo, id1);
3746 if (error)
3747 goto done;
3749 error = got_object_get_type(&type2, repo, id2);
3750 if (error)
3751 goto done;
3753 if (type1 != type2) {
3754 error = got_error(GOT_ERR_OBJ_TYPE);
3755 goto done;
3758 switch (type1) {
3759 case GOT_OBJ_TYPE_BLOB:
3760 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
3761 diff_context, ignore_whitespace, repo, stdout);
3762 break;
3763 case GOT_OBJ_TYPE_TREE:
3764 error = got_diff_objects_as_trees(id1, id2, "", "",
3765 diff_context, ignore_whitespace, repo, stdout);
3766 break;
3767 case GOT_OBJ_TYPE_COMMIT:
3768 printf("diff %s %s\n", label1, label2);
3769 error = got_diff_objects_as_commits(id1, id2, diff_context,
3770 ignore_whitespace, repo, stdout);
3771 break;
3772 default:
3773 error = got_error(GOT_ERR_OBJ_TYPE);
3775 done:
3776 free(label1);
3777 free(label2);
3778 free(id1);
3779 free(id2);
3780 free(path);
3781 if (worktree)
3782 got_worktree_close(worktree);
3783 if (repo) {
3784 const struct got_error *repo_error;
3785 repo_error = got_repo_close(repo);
3786 if (error == NULL)
3787 error = repo_error;
3789 return error;
3792 __dead static void
3793 usage_blame(void)
3795 fprintf(stderr,
3796 "usage: %s blame [-c commit] [-r repository-path] path\n",
3797 getprogname());
3798 exit(1);
3801 struct blame_line {
3802 int annotated;
3803 char *id_str;
3804 char *committer;
3805 char datebuf[11]; /* YYYY-MM-DD + NUL */
3808 struct blame_cb_args {
3809 struct blame_line *lines;
3810 int nlines;
3811 int nlines_prec;
3812 int lineno_cur;
3813 off_t *line_offsets;
3814 FILE *f;
3815 struct got_repository *repo;
3818 static const struct got_error *
3819 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
3821 const struct got_error *err = NULL;
3822 struct blame_cb_args *a = arg;
3823 struct blame_line *bline;
3824 char *line = NULL;
3825 size_t linesize = 0;
3826 struct got_commit_object *commit = NULL;
3827 off_t offset;
3828 struct tm tm;
3829 time_t committer_time;
3831 if (nlines != a->nlines ||
3832 (lineno != -1 && lineno < 1) || lineno > a->nlines)
3833 return got_error(GOT_ERR_RANGE);
3835 if (sigint_received)
3836 return got_error(GOT_ERR_ITER_COMPLETED);
3838 if (lineno == -1)
3839 return NULL; /* no change in this commit */
3841 /* Annotate this line. */
3842 bline = &a->lines[lineno - 1];
3843 if (bline->annotated)
3844 return NULL;
3845 err = got_object_id_str(&bline->id_str, id);
3846 if (err)
3847 return err;
3849 err = got_object_open_as_commit(&commit, a->repo, id);
3850 if (err)
3851 goto done;
3853 bline->committer = strdup(got_object_commit_get_committer(commit));
3854 if (bline->committer == NULL) {
3855 err = got_error_from_errno("strdup");
3856 goto done;
3859 committer_time = got_object_commit_get_committer_time(commit);
3860 if (localtime_r(&committer_time, &tm) == NULL)
3861 return got_error_from_errno("localtime_r");
3862 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
3863 &tm) >= sizeof(bline->datebuf)) {
3864 err = got_error(GOT_ERR_NO_SPACE);
3865 goto done;
3867 bline->annotated = 1;
3869 /* Print lines annotated so far. */
3870 bline = &a->lines[a->lineno_cur - 1];
3871 if (!bline->annotated)
3872 goto done;
3874 offset = a->line_offsets[a->lineno_cur - 1];
3875 if (fseeko(a->f, offset, SEEK_SET) == -1) {
3876 err = got_error_from_errno("fseeko");
3877 goto done;
3880 while (bline->annotated) {
3881 char *smallerthan, *at, *nl, *committer;
3882 size_t len;
3884 if (getline(&line, &linesize, a->f) == -1) {
3885 if (ferror(a->f))
3886 err = got_error_from_errno("getline");
3887 break;
3890 committer = bline->committer;
3891 smallerthan = strchr(committer, '<');
3892 if (smallerthan && smallerthan[1] != '\0')
3893 committer = smallerthan + 1;
3894 at = strchr(committer, '@');
3895 if (at)
3896 *at = '\0';
3897 len = strlen(committer);
3898 if (len >= 9)
3899 committer[8] = '\0';
3901 nl = strchr(line, '\n');
3902 if (nl)
3903 *nl = '\0';
3904 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
3905 bline->id_str, bline->datebuf, committer, line);
3907 a->lineno_cur++;
3908 bline = &a->lines[a->lineno_cur - 1];
3910 done:
3911 if (commit)
3912 got_object_commit_close(commit);
3913 free(line);
3914 return err;
3917 static const struct got_error *
3918 cmd_blame(int argc, char *argv[])
3920 const struct got_error *error;
3921 struct got_repository *repo = NULL;
3922 struct got_worktree *worktree = NULL;
3923 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
3924 struct got_object_id *obj_id = NULL;
3925 struct got_object_id *commit_id = NULL;
3926 struct got_blob_object *blob = NULL;
3927 char *commit_id_str = NULL;
3928 struct blame_cb_args bca;
3929 int ch, obj_type, i;
3930 size_t filesize;
3932 memset(&bca, 0, sizeof(bca));
3934 #ifndef PROFILE
3935 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3936 NULL) == -1)
3937 err(1, "pledge");
3938 #endif
3940 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
3941 switch (ch) {
3942 case 'c':
3943 commit_id_str = optarg;
3944 break;
3945 case 'r':
3946 repo_path = realpath(optarg, NULL);
3947 if (repo_path == NULL)
3948 return got_error_from_errno2("realpath",
3949 optarg);
3950 got_path_strip_trailing_slashes(repo_path);
3951 break;
3952 default:
3953 usage_blame();
3954 /* NOTREACHED */
3958 argc -= optind;
3959 argv += optind;
3961 if (argc == 1)
3962 path = argv[0];
3963 else
3964 usage_blame();
3966 cwd = getcwd(NULL, 0);
3967 if (cwd == NULL) {
3968 error = got_error_from_errno("getcwd");
3969 goto done;
3971 if (repo_path == NULL) {
3972 error = got_worktree_open(&worktree, cwd);
3973 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3974 goto done;
3975 else
3976 error = NULL;
3977 if (worktree) {
3978 repo_path =
3979 strdup(got_worktree_get_repo_path(worktree));
3980 if (repo_path == NULL) {
3981 error = got_error_from_errno("strdup");
3982 if (error)
3983 goto done;
3985 } else {
3986 repo_path = strdup(cwd);
3987 if (repo_path == NULL) {
3988 error = got_error_from_errno("strdup");
3989 goto done;
3994 error = got_repo_open(&repo, repo_path, NULL);
3995 if (error != NULL)
3996 goto done;
3998 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
3999 if (error)
4000 goto done;
4002 if (worktree) {
4003 const char *prefix = got_worktree_get_path_prefix(worktree);
4004 char *p, *worktree_subdir = cwd +
4005 strlen(got_worktree_get_root_path(worktree));
4006 if (asprintf(&p, "%s%s%s%s%s",
4007 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
4008 worktree_subdir, worktree_subdir[0] ? "/" : "",
4009 path) == -1) {
4010 error = got_error_from_errno("asprintf");
4011 goto done;
4013 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4014 free(p);
4015 } else {
4016 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4018 if (error)
4019 goto done;
4021 if (commit_id_str == NULL) {
4022 struct got_reference *head_ref;
4023 error = got_ref_open(&head_ref, repo, worktree ?
4024 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4025 if (error != NULL)
4026 goto done;
4027 error = got_ref_resolve(&commit_id, repo, head_ref);
4028 got_ref_close(head_ref);
4029 if (error != NULL)
4030 goto done;
4031 } else {
4032 error = got_repo_match_object_id(&commit_id, NULL,
4033 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4034 if (error)
4035 goto done;
4038 error = got_object_id_by_path(&obj_id, repo, commit_id, in_repo_path);
4039 if (error)
4040 goto done;
4042 error = got_object_get_type(&obj_type, repo, obj_id);
4043 if (error)
4044 goto done;
4046 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4047 error = got_error(GOT_ERR_OBJ_TYPE);
4048 goto done;
4051 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4052 if (error)
4053 goto done;
4054 bca.f = got_opentemp();
4055 if (bca.f == NULL) {
4056 error = got_error_from_errno("got_opentemp");
4057 goto done;
4059 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4060 &bca.line_offsets, bca.f, blob);
4061 if (error || bca.nlines == 0)
4062 goto done;
4064 /* Don't include \n at EOF in the blame line count. */
4065 if (bca.line_offsets[bca.nlines - 1] == filesize)
4066 bca.nlines--;
4068 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4069 if (bca.lines == NULL) {
4070 error = got_error_from_errno("calloc");
4071 goto done;
4073 bca.lineno_cur = 1;
4074 bca.nlines_prec = 0;
4075 i = bca.nlines;
4076 while (i > 0) {
4077 i /= 10;
4078 bca.nlines_prec++;
4080 bca.repo = repo;
4082 error = got_blame(in_repo_path, commit_id, repo, blame_cb, &bca,
4083 check_cancelled, NULL);
4084 done:
4085 free(in_repo_path);
4086 free(repo_path);
4087 free(cwd);
4088 free(commit_id);
4089 free(obj_id);
4090 if (blob)
4091 got_object_blob_close(blob);
4092 if (worktree)
4093 got_worktree_close(worktree);
4094 if (repo) {
4095 const struct got_error *repo_error;
4096 repo_error = got_repo_close(repo);
4097 if (error == NULL)
4098 error = repo_error;
4100 if (bca.lines) {
4101 for (i = 0; i < bca.nlines; i++) {
4102 struct blame_line *bline = &bca.lines[i];
4103 free(bline->id_str);
4104 free(bline->committer);
4106 free(bca.lines);
4108 free(bca.line_offsets);
4109 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4110 error = got_error_from_errno("fclose");
4111 return error;
4114 __dead static void
4115 usage_tree(void)
4117 fprintf(stderr,
4118 "usage: %s tree [-c commit] [-r repository-path] [-iR] path\n",
4119 getprogname());
4120 exit(1);
4123 static void
4124 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4125 const char *root_path)
4127 int is_root_path = (strcmp(path, root_path) == 0);
4128 const char *modestr = "";
4129 mode_t mode = got_tree_entry_get_mode(te);
4131 path += strlen(root_path);
4132 while (path[0] == '/')
4133 path++;
4135 if (got_object_tree_entry_is_submodule(te))
4136 modestr = "$";
4137 else if (S_ISLNK(mode))
4138 modestr = "@";
4139 else if (S_ISDIR(mode))
4140 modestr = "/";
4141 else if (mode & S_IXUSR)
4142 modestr = "*";
4144 printf("%s%s%s%s%s\n", id ? id : "", path,
4145 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr);
4148 static const struct got_error *
4149 print_tree(const char *path, struct got_object_id *commit_id,
4150 int show_ids, int recurse, const char *root_path,
4151 struct got_repository *repo)
4153 const struct got_error *err = NULL;
4154 struct got_object_id *tree_id = NULL;
4155 struct got_tree_object *tree = NULL;
4156 int nentries, i;
4158 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4159 if (err)
4160 goto done;
4162 err = got_object_open_as_tree(&tree, repo, tree_id);
4163 if (err)
4164 goto done;
4165 nentries = got_object_tree_get_nentries(tree);
4166 for (i = 0; i < nentries; i++) {
4167 struct got_tree_entry *te;
4168 char *id = NULL;
4170 if (sigint_received || sigpipe_received)
4171 break;
4173 te = got_object_tree_get_entry(tree, i);
4174 if (show_ids) {
4175 char *id_str;
4176 err = got_object_id_str(&id_str,
4177 got_tree_entry_get_id(te));
4178 if (err)
4179 goto done;
4180 if (asprintf(&id, "%s ", id_str) == -1) {
4181 err = got_error_from_errno("asprintf");
4182 free(id_str);
4183 goto done;
4185 free(id_str);
4187 print_entry(te, id, path, root_path);
4188 free(id);
4190 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4191 char *child_path;
4192 if (asprintf(&child_path, "%s%s%s", path,
4193 path[0] == '/' && path[1] == '\0' ? "" : "/",
4194 got_tree_entry_get_name(te)) == -1) {
4195 err = got_error_from_errno("asprintf");
4196 goto done;
4198 err = print_tree(child_path, commit_id, show_ids, 1,
4199 root_path, repo);
4200 free(child_path);
4201 if (err)
4202 goto done;
4205 done:
4206 if (tree)
4207 got_object_tree_close(tree);
4208 free(tree_id);
4209 return err;
4212 static const struct got_error *
4213 cmd_tree(int argc, char *argv[])
4215 const struct got_error *error;
4216 struct got_repository *repo = NULL;
4217 struct got_worktree *worktree = NULL;
4218 const char *path, *refname = NULL;
4219 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4220 struct got_object_id *commit_id = NULL;
4221 char *commit_id_str = NULL;
4222 int show_ids = 0, recurse = 0;
4223 int ch;
4225 #ifndef PROFILE
4226 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4227 NULL) == -1)
4228 err(1, "pledge");
4229 #endif
4231 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4232 switch (ch) {
4233 case 'c':
4234 commit_id_str = optarg;
4235 break;
4236 case 'r':
4237 repo_path = realpath(optarg, NULL);
4238 if (repo_path == NULL)
4239 return got_error_from_errno2("realpath",
4240 optarg);
4241 got_path_strip_trailing_slashes(repo_path);
4242 break;
4243 case 'i':
4244 show_ids = 1;
4245 break;
4246 case 'R':
4247 recurse = 1;
4248 break;
4249 default:
4250 usage_tree();
4251 /* NOTREACHED */
4255 argc -= optind;
4256 argv += optind;
4258 if (argc == 1)
4259 path = argv[0];
4260 else if (argc > 1)
4261 usage_tree();
4262 else
4263 path = NULL;
4265 cwd = getcwd(NULL, 0);
4266 if (cwd == NULL) {
4267 error = got_error_from_errno("getcwd");
4268 goto done;
4270 if (repo_path == NULL) {
4271 error = got_worktree_open(&worktree, cwd);
4272 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4273 goto done;
4274 else
4275 error = NULL;
4276 if (worktree) {
4277 repo_path =
4278 strdup(got_worktree_get_repo_path(worktree));
4279 if (repo_path == NULL)
4280 error = got_error_from_errno("strdup");
4281 if (error)
4282 goto done;
4283 } else {
4284 repo_path = strdup(cwd);
4285 if (repo_path == NULL) {
4286 error = got_error_from_errno("strdup");
4287 goto done;
4292 error = got_repo_open(&repo, repo_path, NULL);
4293 if (error != NULL)
4294 goto done;
4296 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4297 if (error)
4298 goto done;
4300 if (path == NULL) {
4301 if (worktree) {
4302 char *p, *worktree_subdir = cwd +
4303 strlen(got_worktree_get_root_path(worktree));
4304 if (asprintf(&p, "%s/%s",
4305 got_worktree_get_path_prefix(worktree),
4306 worktree_subdir) == -1) {
4307 error = got_error_from_errno("asprintf");
4308 goto done;
4310 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4311 free(p);
4312 if (error)
4313 goto done;
4314 } else
4315 path = "/";
4317 if (in_repo_path == NULL) {
4318 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4319 if (error != NULL)
4320 goto done;
4323 if (commit_id_str == NULL) {
4324 struct got_reference *head_ref;
4325 if (worktree)
4326 refname = got_worktree_get_head_ref_name(worktree);
4327 else
4328 refname = GOT_REF_HEAD;
4329 error = got_ref_open(&head_ref, repo, refname, 0);
4330 if (error != NULL)
4331 goto done;
4332 error = got_ref_resolve(&commit_id, repo, head_ref);
4333 got_ref_close(head_ref);
4334 if (error != NULL)
4335 goto done;
4336 } else {
4337 error = got_repo_match_object_id(&commit_id, NULL,
4338 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4339 if (error)
4340 goto done;
4343 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4344 in_repo_path, repo);
4345 done:
4346 free(in_repo_path);
4347 free(repo_path);
4348 free(cwd);
4349 free(commit_id);
4350 if (worktree)
4351 got_worktree_close(worktree);
4352 if (repo) {
4353 const struct got_error *repo_error;
4354 repo_error = got_repo_close(repo);
4355 if (error == NULL)
4356 error = repo_error;
4358 return error;
4361 __dead static void
4362 usage_status(void)
4364 fprintf(stderr, "usage: %s status [path ...]\n", getprogname());
4365 exit(1);
4368 static const struct got_error *
4369 print_status(void *arg, unsigned char status, unsigned char staged_status,
4370 const char *path, struct got_object_id *blob_id,
4371 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4372 int dirfd, const char *de_name)
4374 if (status == staged_status && (status == GOT_STATUS_DELETE))
4375 status = GOT_STATUS_NO_CHANGE;
4376 printf("%c%c %s\n", status, staged_status, path);
4377 return NULL;
4380 static const struct got_error *
4381 cmd_status(int argc, char *argv[])
4383 const struct got_error *error = NULL;
4384 struct got_repository *repo = NULL;
4385 struct got_worktree *worktree = NULL;
4386 char *cwd = NULL;
4387 struct got_pathlist_head paths;
4388 struct got_pathlist_entry *pe;
4389 int ch;
4391 TAILQ_INIT(&paths);
4393 while ((ch = getopt(argc, argv, "")) != -1) {
4394 switch (ch) {
4395 default:
4396 usage_status();
4397 /* NOTREACHED */
4401 argc -= optind;
4402 argv += optind;
4404 #ifndef PROFILE
4405 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4406 NULL) == -1)
4407 err(1, "pledge");
4408 #endif
4409 cwd = getcwd(NULL, 0);
4410 if (cwd == NULL) {
4411 error = got_error_from_errno("getcwd");
4412 goto done;
4415 error = got_worktree_open(&worktree, cwd);
4416 if (error) {
4417 if (error->code == GOT_ERR_NOT_WORKTREE)
4418 error = wrap_not_worktree_error(error, "status", cwd);
4419 goto done;
4422 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4423 NULL);
4424 if (error != NULL)
4425 goto done;
4427 error = apply_unveil(got_repo_get_path(repo), 1,
4428 got_worktree_get_root_path(worktree));
4429 if (error)
4430 goto done;
4432 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
4433 if (error)
4434 goto done;
4436 error = got_worktree_status(worktree, &paths, repo, print_status, NULL,
4437 check_cancelled, NULL);
4438 done:
4439 TAILQ_FOREACH(pe, &paths, entry)
4440 free((char *)pe->path);
4441 got_pathlist_free(&paths);
4442 free(cwd);
4443 return error;
4446 __dead static void
4447 usage_ref(void)
4449 fprintf(stderr,
4450 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
4451 "[-d] [name]\n",
4452 getprogname());
4453 exit(1);
4456 static const struct got_error *
4457 list_refs(struct got_repository *repo, const char *refname)
4459 static const struct got_error *err = NULL;
4460 struct got_reflist_head refs;
4461 struct got_reflist_entry *re;
4463 SIMPLEQ_INIT(&refs);
4464 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
4465 if (err)
4466 return err;
4468 SIMPLEQ_FOREACH(re, &refs, entry) {
4469 char *refstr;
4470 refstr = got_ref_to_str(re->ref);
4471 if (refstr == NULL)
4472 return got_error_from_errno("got_ref_to_str");
4473 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
4474 free(refstr);
4477 got_ref_list_free(&refs);
4478 return NULL;
4481 static const struct got_error *
4482 delete_ref(struct got_repository *repo, const char *refname)
4484 const struct got_error *err = NULL;
4485 struct got_reference *ref;
4487 err = got_ref_open(&ref, repo, refname, 0);
4488 if (err)
4489 return err;
4491 err = got_ref_delete(ref, repo);
4492 got_ref_close(ref);
4493 return err;
4496 static const struct got_error *
4497 add_ref(struct got_repository *repo, const char *refname, const char *target)
4499 const struct got_error *err = NULL;
4500 struct got_object_id *id;
4501 struct got_reference *ref = NULL;
4504 * Don't let the user create a reference name with a leading '-'.
4505 * While technically a valid reference name, this case is usually
4506 * an unintended typo.
4508 if (refname[0] == '-')
4509 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4511 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
4512 repo);
4513 if (err) {
4514 struct got_reference *target_ref;
4516 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
4517 return err;
4518 err = got_ref_open(&target_ref, repo, target, 0);
4519 if (err)
4520 return err;
4521 err = got_ref_resolve(&id, repo, target_ref);
4522 got_ref_close(target_ref);
4523 if (err)
4524 return err;
4527 err = got_ref_alloc(&ref, refname, id);
4528 if (err)
4529 goto done;
4531 err = got_ref_write(ref, repo);
4532 done:
4533 if (ref)
4534 got_ref_close(ref);
4535 free(id);
4536 return err;
4539 static const struct got_error *
4540 add_symref(struct got_repository *repo, const char *refname, const char *target)
4542 const struct got_error *err = NULL;
4543 struct got_reference *ref = NULL;
4544 struct got_reference *target_ref = NULL;
4547 * Don't let the user create a reference name with a leading '-'.
4548 * While technically a valid reference name, this case is usually
4549 * an unintended typo.
4551 if (refname[0] == '-')
4552 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4554 err = got_ref_open(&target_ref, repo, target, 0);
4555 if (err)
4556 return err;
4558 err = got_ref_alloc_symref(&ref, refname, target_ref);
4559 if (err)
4560 goto done;
4562 err = got_ref_write(ref, repo);
4563 done:
4564 if (target_ref)
4565 got_ref_close(target_ref);
4566 if (ref)
4567 got_ref_close(ref);
4568 return err;
4571 static const struct got_error *
4572 cmd_ref(int argc, char *argv[])
4574 const struct got_error *error = NULL;
4575 struct got_repository *repo = NULL;
4576 struct got_worktree *worktree = NULL;
4577 char *cwd = NULL, *repo_path = NULL;
4578 int ch, do_list = 0, do_delete = 0;
4579 const char *obj_arg = NULL, *symref_target= NULL;
4580 char *refname = NULL;
4582 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
4583 switch (ch) {
4584 case 'c':
4585 obj_arg = optarg;
4586 break;
4587 case 'd':
4588 do_delete = 1;
4589 break;
4590 case 'r':
4591 repo_path = realpath(optarg, NULL);
4592 if (repo_path == NULL)
4593 return got_error_from_errno2("realpath",
4594 optarg);
4595 got_path_strip_trailing_slashes(repo_path);
4596 break;
4597 case 'l':
4598 do_list = 1;
4599 break;
4600 case 's':
4601 symref_target = optarg;
4602 break;
4603 default:
4604 usage_ref();
4605 /* NOTREACHED */
4609 if (obj_arg && do_list)
4610 errx(1, "-c and -l options are mutually exclusive");
4611 if (obj_arg && do_delete)
4612 errx(1, "-c and -d options are mutually exclusive");
4613 if (obj_arg && symref_target)
4614 errx(1, "-c and -s options are mutually exclusive");
4615 if (symref_target && do_delete)
4616 errx(1, "-s and -d options are mutually exclusive");
4617 if (symref_target && do_list)
4618 errx(1, "-s and -l options are mutually exclusive");
4619 if (do_delete && do_list)
4620 errx(1, "-d and -l options are mutually exclusive");
4622 argc -= optind;
4623 argv += optind;
4625 if (do_list) {
4626 if (argc != 0 && argc != 1)
4627 usage_ref();
4628 if (argc == 1) {
4629 refname = strdup(argv[0]);
4630 if (refname == NULL) {
4631 error = got_error_from_errno("strdup");
4632 goto done;
4635 } else {
4636 if (argc != 1)
4637 usage_ref();
4638 refname = strdup(argv[0]);
4639 if (refname == NULL) {
4640 error = got_error_from_errno("strdup");
4641 goto done;
4645 if (refname)
4646 got_path_strip_trailing_slashes(refname);
4648 #ifndef PROFILE
4649 if (do_list) {
4650 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4651 NULL) == -1)
4652 err(1, "pledge");
4653 } else {
4654 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4655 "sendfd unveil", NULL) == -1)
4656 err(1, "pledge");
4658 #endif
4659 cwd = getcwd(NULL, 0);
4660 if (cwd == NULL) {
4661 error = got_error_from_errno("getcwd");
4662 goto done;
4665 if (repo_path == NULL) {
4666 error = got_worktree_open(&worktree, cwd);
4667 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4668 goto done;
4669 else
4670 error = NULL;
4671 if (worktree) {
4672 repo_path =
4673 strdup(got_worktree_get_repo_path(worktree));
4674 if (repo_path == NULL)
4675 error = got_error_from_errno("strdup");
4676 if (error)
4677 goto done;
4678 } else {
4679 repo_path = strdup(cwd);
4680 if (repo_path == NULL) {
4681 error = got_error_from_errno("strdup");
4682 goto done;
4687 error = got_repo_open(&repo, repo_path, NULL);
4688 if (error != NULL)
4689 goto done;
4691 error = apply_unveil(got_repo_get_path(repo), do_list,
4692 worktree ? got_worktree_get_root_path(worktree) : NULL);
4693 if (error)
4694 goto done;
4696 if (do_list)
4697 error = list_refs(repo, refname);
4698 else if (do_delete)
4699 error = delete_ref(repo, refname);
4700 else if (symref_target)
4701 error = add_symref(repo, refname, symref_target);
4702 else {
4703 if (obj_arg == NULL)
4704 usage_ref();
4705 error = add_ref(repo, refname, obj_arg);
4707 done:
4708 free(refname);
4709 if (repo)
4710 got_repo_close(repo);
4711 if (worktree)
4712 got_worktree_close(worktree);
4713 free(cwd);
4714 free(repo_path);
4715 return error;
4718 __dead static void
4719 usage_branch(void)
4721 fprintf(stderr,
4722 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
4723 "[name]\n", getprogname());
4724 exit(1);
4727 static const struct got_error *
4728 list_branch(struct got_repository *repo, struct got_worktree *worktree,
4729 struct got_reference *ref)
4731 const struct got_error *err = NULL;
4732 const char *refname, *marker = " ";
4733 char *refstr;
4735 refname = got_ref_get_name(ref);
4736 if (worktree && strcmp(refname,
4737 got_worktree_get_head_ref_name(worktree)) == 0) {
4738 struct got_object_id *id = NULL;
4740 err = got_ref_resolve(&id, repo, ref);
4741 if (err)
4742 return err;
4743 if (got_object_id_cmp(id,
4744 got_worktree_get_base_commit_id(worktree)) == 0)
4745 marker = "* ";
4746 else
4747 marker = "~ ";
4748 free(id);
4751 if (strncmp(refname, "refs/heads/", 11) == 0)
4752 refname += 11;
4753 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4754 refname += 18;
4756 refstr = got_ref_to_str(ref);
4757 if (refstr == NULL)
4758 return got_error_from_errno("got_ref_to_str");
4760 printf("%s%s: %s\n", marker, refname, refstr);
4761 free(refstr);
4762 return NULL;
4765 static const struct got_error *
4766 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
4768 const char *refname;
4770 if (worktree == NULL)
4771 return got_error(GOT_ERR_NOT_WORKTREE);
4773 refname = got_worktree_get_head_ref_name(worktree);
4775 if (strncmp(refname, "refs/heads/", 11) == 0)
4776 refname += 11;
4777 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4778 refname += 18;
4780 printf("%s\n", refname);
4782 return NULL;
4785 static const struct got_error *
4786 list_branches(struct got_repository *repo, struct got_worktree *worktree)
4788 static const struct got_error *err = NULL;
4789 struct got_reflist_head refs;
4790 struct got_reflist_entry *re;
4791 struct got_reference *temp_ref = NULL;
4792 int rebase_in_progress, histedit_in_progress;
4794 SIMPLEQ_INIT(&refs);
4796 if (worktree) {
4797 err = got_worktree_rebase_in_progress(&rebase_in_progress,
4798 worktree);
4799 if (err)
4800 return err;
4802 err = got_worktree_histedit_in_progress(&histedit_in_progress,
4803 worktree);
4804 if (err)
4805 return err;
4807 if (rebase_in_progress || histedit_in_progress) {
4808 err = got_ref_open(&temp_ref, repo,
4809 got_worktree_get_head_ref_name(worktree), 0);
4810 if (err)
4811 return err;
4812 list_branch(repo, worktree, temp_ref);
4813 got_ref_close(temp_ref);
4817 err = got_ref_list(&refs, repo, "refs/heads",
4818 got_ref_cmp_by_name, NULL);
4819 if (err)
4820 return err;
4822 SIMPLEQ_FOREACH(re, &refs, entry)
4823 list_branch(repo, worktree, re->ref);
4825 got_ref_list_free(&refs);
4826 return NULL;
4829 static const struct got_error *
4830 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
4831 const char *branch_name)
4833 const struct got_error *err = NULL;
4834 struct got_reference *ref = NULL;
4835 char *refname;
4837 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
4838 return got_error_from_errno("asprintf");
4840 err = got_ref_open(&ref, repo, refname, 0);
4841 if (err)
4842 goto done;
4844 if (worktree &&
4845 strcmp(got_worktree_get_head_ref_name(worktree),
4846 got_ref_get_name(ref)) == 0) {
4847 err = got_error_msg(GOT_ERR_SAME_BRANCH,
4848 "will not delete this work tree's current branch");
4849 goto done;
4852 err = got_ref_delete(ref, repo);
4853 done:
4854 if (ref)
4855 got_ref_close(ref);
4856 free(refname);
4857 return err;
4860 static const struct got_error *
4861 add_branch(struct got_repository *repo, const char *branch_name,
4862 struct got_object_id *base_commit_id)
4864 const struct got_error *err = NULL;
4865 struct got_reference *ref = NULL;
4866 char *base_refname = NULL, *refname = NULL;
4869 * Don't let the user create a branch name with a leading '-'.
4870 * While technically a valid reference name, this case is usually
4871 * an unintended typo.
4873 if (branch_name[0] == '-')
4874 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
4876 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
4877 err = got_error_from_errno("asprintf");
4878 goto done;
4881 err = got_ref_open(&ref, repo, refname, 0);
4882 if (err == NULL) {
4883 err = got_error(GOT_ERR_BRANCH_EXISTS);
4884 goto done;
4885 } else if (err->code != GOT_ERR_NOT_REF)
4886 goto done;
4888 err = got_ref_alloc(&ref, refname, base_commit_id);
4889 if (err)
4890 goto done;
4892 err = got_ref_write(ref, repo);
4893 done:
4894 if (ref)
4895 got_ref_close(ref);
4896 free(base_refname);
4897 free(refname);
4898 return err;
4901 static const struct got_error *
4902 cmd_branch(int argc, char *argv[])
4904 const struct got_error *error = NULL;
4905 struct got_repository *repo = NULL;
4906 struct got_worktree *worktree = NULL;
4907 char *cwd = NULL, *repo_path = NULL;
4908 int ch, do_list = 0, do_show = 0, do_update = 1;
4909 const char *delref = NULL, *commit_id_arg = NULL;
4910 struct got_reference *ref = NULL;
4911 struct got_pathlist_head paths;
4912 struct got_pathlist_entry *pe;
4913 struct got_object_id *commit_id = NULL;
4914 char *commit_id_str = NULL;
4916 TAILQ_INIT(&paths);
4918 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
4919 switch (ch) {
4920 case 'c':
4921 commit_id_arg = optarg;
4922 break;
4923 case 'd':
4924 delref = optarg;
4925 break;
4926 case 'r':
4927 repo_path = realpath(optarg, NULL);
4928 if (repo_path == NULL)
4929 return got_error_from_errno2("realpath",
4930 optarg);
4931 got_path_strip_trailing_slashes(repo_path);
4932 break;
4933 case 'l':
4934 do_list = 1;
4935 break;
4936 case 'n':
4937 do_update = 0;
4938 break;
4939 default:
4940 usage_branch();
4941 /* NOTREACHED */
4945 if (do_list && delref)
4946 errx(1, "-l and -d options are mutually exclusive");
4948 argc -= optind;
4949 argv += optind;
4951 if (!do_list && !delref && argc == 0)
4952 do_show = 1;
4954 if ((do_list || delref || do_show) && commit_id_arg != NULL)
4955 errx(1, "-c option can only be used when creating a branch");
4957 if (do_list || delref) {
4958 if (argc > 0)
4959 usage_branch();
4960 } else if (!do_show && argc != 1)
4961 usage_branch();
4963 #ifndef PROFILE
4964 if (do_list || do_show) {
4965 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4966 NULL) == -1)
4967 err(1, "pledge");
4968 } else {
4969 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4970 "sendfd unveil", NULL) == -1)
4971 err(1, "pledge");
4973 #endif
4974 cwd = getcwd(NULL, 0);
4975 if (cwd == NULL) {
4976 error = got_error_from_errno("getcwd");
4977 goto done;
4980 if (repo_path == NULL) {
4981 error = got_worktree_open(&worktree, cwd);
4982 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4983 goto done;
4984 else
4985 error = NULL;
4986 if (worktree) {
4987 repo_path =
4988 strdup(got_worktree_get_repo_path(worktree));
4989 if (repo_path == NULL)
4990 error = got_error_from_errno("strdup");
4991 if (error)
4992 goto done;
4993 } else {
4994 repo_path = strdup(cwd);
4995 if (repo_path == NULL) {
4996 error = got_error_from_errno("strdup");
4997 goto done;
5002 error = got_repo_open(&repo, repo_path, NULL);
5003 if (error != NULL)
5004 goto done;
5006 error = apply_unveil(got_repo_get_path(repo), do_list,
5007 worktree ? got_worktree_get_root_path(worktree) : NULL);
5008 if (error)
5009 goto done;
5011 if (do_show)
5012 error = show_current_branch(repo, worktree);
5013 else if (do_list)
5014 error = list_branches(repo, worktree);
5015 else if (delref)
5016 error = delete_branch(repo, worktree, delref);
5017 else {
5018 if (commit_id_arg == NULL)
5019 commit_id_arg = worktree ?
5020 got_worktree_get_head_ref_name(worktree) :
5021 GOT_REF_HEAD;
5022 error = got_repo_match_object_id(&commit_id, NULL,
5023 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5024 if (error)
5025 goto done;
5026 error = add_branch(repo, argv[0], commit_id);
5027 if (error)
5028 goto done;
5029 if (worktree && do_update) {
5030 int did_something = 0;
5031 char *branch_refname = NULL;
5033 error = got_object_id_str(&commit_id_str, commit_id);
5034 if (error)
5035 goto done;
5036 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5037 worktree);
5038 if (error)
5039 goto done;
5040 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5041 == -1) {
5042 error = got_error_from_errno("asprintf");
5043 goto done;
5045 error = got_ref_open(&ref, repo, branch_refname, 0);
5046 free(branch_refname);
5047 if (error)
5048 goto done;
5049 error = switch_head_ref(ref, commit_id, worktree,
5050 repo);
5051 if (error)
5052 goto done;
5053 error = got_worktree_set_base_commit_id(worktree, repo,
5054 commit_id);
5055 if (error)
5056 goto done;
5057 error = got_worktree_checkout_files(worktree, &paths,
5058 repo, update_progress, &did_something,
5059 check_cancelled, NULL);
5060 if (error)
5061 goto done;
5062 if (did_something)
5063 printf("Updated to commit %s\n", commit_id_str);
5066 done:
5067 if (ref)
5068 got_ref_close(ref);
5069 if (repo)
5070 got_repo_close(repo);
5071 if (worktree)
5072 got_worktree_close(worktree);
5073 free(cwd);
5074 free(repo_path);
5075 free(commit_id);
5076 free(commit_id_str);
5077 TAILQ_FOREACH(pe, &paths, entry)
5078 free((char *)pe->path);
5079 got_pathlist_free(&paths);
5080 return error;
5084 __dead static void
5085 usage_tag(void)
5087 fprintf(stderr,
5088 "usage: %s tag [-c commit] [-r repository] [-l] "
5089 "[-m message] name\n", getprogname());
5090 exit(1);
5093 #if 0
5094 static const struct got_error *
5095 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5097 const struct got_error *err = NULL;
5098 struct got_reflist_entry *re, *se, *new;
5099 struct got_object_id *re_id, *se_id;
5100 struct got_tag_object *re_tag, *se_tag;
5101 time_t re_time, se_time;
5103 SIMPLEQ_FOREACH(re, tags, entry) {
5104 se = SIMPLEQ_FIRST(sorted);
5105 if (se == NULL) {
5106 err = got_reflist_entry_dup(&new, re);
5107 if (err)
5108 return err;
5109 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5110 continue;
5111 } else {
5112 err = got_ref_resolve(&re_id, repo, re->ref);
5113 if (err)
5114 break;
5115 err = got_object_open_as_tag(&re_tag, repo, re_id);
5116 free(re_id);
5117 if (err)
5118 break;
5119 re_time = got_object_tag_get_tagger_time(re_tag);
5120 got_object_tag_close(re_tag);
5123 while (se) {
5124 err = got_ref_resolve(&se_id, repo, re->ref);
5125 if (err)
5126 break;
5127 err = got_object_open_as_tag(&se_tag, repo, se_id);
5128 free(se_id);
5129 if (err)
5130 break;
5131 se_time = got_object_tag_get_tagger_time(se_tag);
5132 got_object_tag_close(se_tag);
5134 if (se_time > re_time) {
5135 err = got_reflist_entry_dup(&new, re);
5136 if (err)
5137 return err;
5138 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5139 break;
5141 se = SIMPLEQ_NEXT(se, entry);
5142 continue;
5145 done:
5146 return err;
5148 #endif
5150 static const struct got_error *
5151 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5153 static const struct got_error *err = NULL;
5154 struct got_reflist_head refs;
5155 struct got_reflist_entry *re;
5157 SIMPLEQ_INIT(&refs);
5159 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5160 if (err)
5161 return err;
5163 SIMPLEQ_FOREACH(re, &refs, entry) {
5164 const char *refname;
5165 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5166 char datebuf[26];
5167 const char *tagger;
5168 time_t tagger_time;
5169 struct got_object_id *id;
5170 struct got_tag_object *tag;
5171 struct got_commit_object *commit = NULL;
5173 refname = got_ref_get_name(re->ref);
5174 if (strncmp(refname, "refs/tags/", 10) != 0)
5175 continue;
5176 refname += 10;
5177 refstr = got_ref_to_str(re->ref);
5178 if (refstr == NULL) {
5179 err = got_error_from_errno("got_ref_to_str");
5180 break;
5182 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5183 free(refstr);
5185 err = got_ref_resolve(&id, repo, re->ref);
5186 if (err)
5187 break;
5188 err = got_object_open_as_tag(&tag, repo, id);
5189 if (err) {
5190 if (err->code != GOT_ERR_OBJ_TYPE) {
5191 free(id);
5192 break;
5194 /* "lightweight" tag */
5195 err = got_object_open_as_commit(&commit, repo, id);
5196 if (err) {
5197 free(id);
5198 break;
5200 tagger = got_object_commit_get_committer(commit);
5201 tagger_time =
5202 got_object_commit_get_committer_time(commit);
5203 err = got_object_id_str(&id_str, id);
5204 free(id);
5205 if (err)
5206 break;
5207 } else {
5208 free(id);
5209 tagger = got_object_tag_get_tagger(tag);
5210 tagger_time = got_object_tag_get_tagger_time(tag);
5211 err = got_object_id_str(&id_str,
5212 got_object_tag_get_object_id(tag));
5213 if (err)
5214 break;
5216 printf("from: %s\n", tagger);
5217 datestr = get_datestr(&tagger_time, datebuf);
5218 if (datestr)
5219 printf("date: %s UTC\n", datestr);
5220 if (commit)
5221 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5222 else {
5223 switch (got_object_tag_get_object_type(tag)) {
5224 case GOT_OBJ_TYPE_BLOB:
5225 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5226 id_str);
5227 break;
5228 case GOT_OBJ_TYPE_TREE:
5229 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5230 id_str);
5231 break;
5232 case GOT_OBJ_TYPE_COMMIT:
5233 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5234 id_str);
5235 break;
5236 case GOT_OBJ_TYPE_TAG:
5237 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5238 id_str);
5239 break;
5240 default:
5241 break;
5244 free(id_str);
5245 if (commit) {
5246 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5247 if (err)
5248 break;
5249 got_object_commit_close(commit);
5250 } else {
5251 tagmsg0 = strdup(got_object_tag_get_message(tag));
5252 got_object_tag_close(tag);
5253 if (tagmsg0 == NULL) {
5254 err = got_error_from_errno("strdup");
5255 break;
5259 tagmsg = tagmsg0;
5260 do {
5261 line = strsep(&tagmsg, "\n");
5262 if (line)
5263 printf(" %s\n", line);
5264 } while (line);
5265 free(tagmsg0);
5268 got_ref_list_free(&refs);
5269 return NULL;
5272 static const struct got_error *
5273 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5274 const char *tag_name, const char *repo_path)
5276 const struct got_error *err = NULL;
5277 char *template = NULL, *initial_content = NULL;
5278 char *editor = NULL;
5279 int fd = -1;
5281 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5282 err = got_error_from_errno("asprintf");
5283 goto done;
5286 if (asprintf(&initial_content, "\n# tagging commit %s as %s\n",
5287 commit_id_str, tag_name) == -1) {
5288 err = got_error_from_errno("asprintf");
5289 goto done;
5292 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5293 if (err)
5294 goto done;
5296 dprintf(fd, initial_content);
5297 close(fd);
5299 err = get_editor(&editor);
5300 if (err)
5301 goto done;
5302 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
5303 done:
5304 free(initial_content);
5305 free(template);
5306 free(editor);
5308 /* Editor is done; we can now apply unveil(2) */
5309 if (err == NULL) {
5310 err = apply_unveil(repo_path, 0, NULL);
5311 if (err) {
5312 free(*tagmsg);
5313 *tagmsg = NULL;
5316 return err;
5319 static const struct got_error *
5320 add_tag(struct got_repository *repo, const char *tag_name,
5321 const char *commit_arg, const char *tagmsg_arg)
5323 const struct got_error *err = NULL;
5324 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5325 char *label = NULL, *commit_id_str = NULL;
5326 struct got_reference *ref = NULL;
5327 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5328 char *tagmsg_path = NULL, *tag_id_str = NULL;
5329 int preserve_tagmsg = 0;
5332 * Don't let the user create a tag name with a leading '-'.
5333 * While technically a valid reference name, this case is usually
5334 * an unintended typo.
5336 if (tag_name[0] == '-')
5337 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5339 err = get_author(&tagger, repo);
5340 if (err)
5341 return err;
5343 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5344 GOT_OBJ_TYPE_COMMIT, 1, repo);
5345 if (err)
5346 goto done;
5348 err = got_object_id_str(&commit_id_str, commit_id);
5349 if (err)
5350 goto done;
5352 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5353 refname = strdup(tag_name);
5354 if (refname == NULL) {
5355 err = got_error_from_errno("strdup");
5356 goto done;
5358 tag_name += 10;
5359 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5360 err = got_error_from_errno("asprintf");
5361 goto done;
5364 err = got_ref_open(&ref, repo, refname, 0);
5365 if (err == NULL) {
5366 err = got_error(GOT_ERR_TAG_EXISTS);
5367 goto done;
5368 } else if (err->code != GOT_ERR_NOT_REF)
5369 goto done;
5371 if (tagmsg_arg == NULL) {
5372 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5373 tag_name, got_repo_get_path(repo));
5374 if (err) {
5375 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5376 tagmsg_path != NULL)
5377 preserve_tagmsg = 1;
5378 goto done;
5382 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5383 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5384 if (err) {
5385 if (tagmsg_path)
5386 preserve_tagmsg = 1;
5387 goto done;
5390 err = got_ref_alloc(&ref, refname, tag_id);
5391 if (err) {
5392 if (tagmsg_path)
5393 preserve_tagmsg = 1;
5394 goto done;
5397 err = got_ref_write(ref, repo);
5398 if (err) {
5399 if (tagmsg_path)
5400 preserve_tagmsg = 1;
5401 goto done;
5404 err = got_object_id_str(&tag_id_str, tag_id);
5405 if (err) {
5406 if (tagmsg_path)
5407 preserve_tagmsg = 1;
5408 goto done;
5410 printf("Created tag %s\n", tag_id_str);
5411 done:
5412 if (preserve_tagmsg) {
5413 fprintf(stderr, "%s: tag message preserved in %s\n",
5414 getprogname(), tagmsg_path);
5415 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
5416 err = got_error_from_errno2("unlink", tagmsg_path);
5417 free(tag_id_str);
5418 if (ref)
5419 got_ref_close(ref);
5420 free(commit_id);
5421 free(commit_id_str);
5422 free(refname);
5423 free(tagmsg);
5424 free(tagmsg_path);
5425 free(tagger);
5426 return err;
5429 static const struct got_error *
5430 cmd_tag(int argc, char *argv[])
5432 const struct got_error *error = NULL;
5433 struct got_repository *repo = NULL;
5434 struct got_worktree *worktree = NULL;
5435 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
5436 char *gitconfig_path = NULL;
5437 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
5438 int ch, do_list = 0;
5440 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
5441 switch (ch) {
5442 case 'c':
5443 commit_id_arg = optarg;
5444 break;
5445 case 'm':
5446 tagmsg = optarg;
5447 break;
5448 case 'r':
5449 repo_path = realpath(optarg, NULL);
5450 if (repo_path == NULL)
5451 return got_error_from_errno2("realpath",
5452 optarg);
5453 got_path_strip_trailing_slashes(repo_path);
5454 break;
5455 case 'l':
5456 do_list = 1;
5457 break;
5458 default:
5459 usage_tag();
5460 /* NOTREACHED */
5464 argc -= optind;
5465 argv += optind;
5467 if (do_list) {
5468 if (commit_id_arg != NULL)
5469 errx(1,
5470 "-c option can only be used when creating a tag");
5471 if (tagmsg)
5472 errx(1, "-l and -m options are mutually exclusive");
5473 if (argc > 0)
5474 usage_tag();
5475 } else if (argc != 1)
5476 usage_tag();
5478 tag_name = argv[0];
5480 #ifndef PROFILE
5481 if (do_list) {
5482 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5483 NULL) == -1)
5484 err(1, "pledge");
5485 } else {
5486 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5487 "sendfd unveil", NULL) == -1)
5488 err(1, "pledge");
5490 #endif
5491 cwd = getcwd(NULL, 0);
5492 if (cwd == NULL) {
5493 error = got_error_from_errno("getcwd");
5494 goto done;
5497 if (repo_path == NULL) {
5498 error = got_worktree_open(&worktree, cwd);
5499 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5500 goto done;
5501 else
5502 error = NULL;
5503 if (worktree) {
5504 repo_path =
5505 strdup(got_worktree_get_repo_path(worktree));
5506 if (repo_path == NULL)
5507 error = got_error_from_errno("strdup");
5508 if (error)
5509 goto done;
5510 } else {
5511 repo_path = strdup(cwd);
5512 if (repo_path == NULL) {
5513 error = got_error_from_errno("strdup");
5514 goto done;
5519 if (do_list) {
5520 error = got_repo_open(&repo, repo_path, NULL);
5521 if (error != NULL)
5522 goto done;
5523 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5524 if (error)
5525 goto done;
5526 error = list_tags(repo, worktree);
5527 } else {
5528 error = get_gitconfig_path(&gitconfig_path);
5529 if (error)
5530 goto done;
5531 error = got_repo_open(&repo, repo_path, gitconfig_path);
5532 if (error != NULL)
5533 goto done;
5535 if (tagmsg) {
5536 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5537 if (error)
5538 goto done;
5541 if (commit_id_arg == NULL) {
5542 struct got_reference *head_ref;
5543 struct got_object_id *commit_id;
5544 error = got_ref_open(&head_ref, repo,
5545 worktree ? got_worktree_get_head_ref_name(worktree)
5546 : GOT_REF_HEAD, 0);
5547 if (error)
5548 goto done;
5549 error = got_ref_resolve(&commit_id, repo, head_ref);
5550 got_ref_close(head_ref);
5551 if (error)
5552 goto done;
5553 error = got_object_id_str(&commit_id_str, commit_id);
5554 free(commit_id);
5555 if (error)
5556 goto done;
5559 error = add_tag(repo, tag_name,
5560 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
5562 done:
5563 if (repo)
5564 got_repo_close(repo);
5565 if (worktree)
5566 got_worktree_close(worktree);
5567 free(cwd);
5568 free(repo_path);
5569 free(gitconfig_path);
5570 free(commit_id_str);
5571 return error;
5574 __dead static void
5575 usage_add(void)
5577 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
5578 getprogname());
5579 exit(1);
5582 static const struct got_error *
5583 add_progress(void *arg, unsigned char status, const char *path)
5585 while (path[0] == '/')
5586 path++;
5587 printf("%c %s\n", status, path);
5588 return NULL;
5591 static const struct got_error *
5592 cmd_add(int argc, char *argv[])
5594 const struct got_error *error = NULL;
5595 struct got_repository *repo = NULL;
5596 struct got_worktree *worktree = NULL;
5597 char *cwd = NULL;
5598 struct got_pathlist_head paths;
5599 struct got_pathlist_entry *pe;
5600 int ch, can_recurse = 0, no_ignores = 0;
5602 TAILQ_INIT(&paths);
5604 while ((ch = getopt(argc, argv, "IR")) != -1) {
5605 switch (ch) {
5606 case 'I':
5607 no_ignores = 1;
5608 break;
5609 case 'R':
5610 can_recurse = 1;
5611 break;
5612 default:
5613 usage_add();
5614 /* NOTREACHED */
5618 argc -= optind;
5619 argv += optind;
5621 #ifndef PROFILE
5622 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5623 NULL) == -1)
5624 err(1, "pledge");
5625 #endif
5626 if (argc < 1)
5627 usage_add();
5629 cwd = getcwd(NULL, 0);
5630 if (cwd == NULL) {
5631 error = got_error_from_errno("getcwd");
5632 goto done;
5635 error = got_worktree_open(&worktree, cwd);
5636 if (error) {
5637 if (error->code == GOT_ERR_NOT_WORKTREE)
5638 error = wrap_not_worktree_error(error, "add", cwd);
5639 goto done;
5642 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5643 NULL);
5644 if (error != NULL)
5645 goto done;
5647 error = apply_unveil(got_repo_get_path(repo), 1,
5648 got_worktree_get_root_path(worktree));
5649 if (error)
5650 goto done;
5652 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5653 if (error)
5654 goto done;
5656 if (!can_recurse && no_ignores) {
5657 error = got_error_msg(GOT_ERR_BAD_PATH,
5658 "disregarding ignores requires -R option");
5659 goto done;
5663 if (!can_recurse) {
5664 char *ondisk_path;
5665 struct stat sb;
5666 TAILQ_FOREACH(pe, &paths, entry) {
5667 if (asprintf(&ondisk_path, "%s/%s",
5668 got_worktree_get_root_path(worktree),
5669 pe->path) == -1) {
5670 error = got_error_from_errno("asprintf");
5671 goto done;
5673 if (lstat(ondisk_path, &sb) == -1) {
5674 if (errno == ENOENT) {
5675 free(ondisk_path);
5676 continue;
5678 error = got_error_from_errno2("lstat",
5679 ondisk_path);
5680 free(ondisk_path);
5681 goto done;
5683 free(ondisk_path);
5684 if (S_ISDIR(sb.st_mode)) {
5685 error = got_error_msg(GOT_ERR_BAD_PATH,
5686 "adding directories requires -R option");
5687 goto done;
5692 error = got_worktree_schedule_add(worktree, &paths, add_progress,
5693 NULL, repo, no_ignores);
5694 done:
5695 if (repo)
5696 got_repo_close(repo);
5697 if (worktree)
5698 got_worktree_close(worktree);
5699 TAILQ_FOREACH(pe, &paths, entry)
5700 free((char *)pe->path);
5701 got_pathlist_free(&paths);
5702 free(cwd);
5703 return error;
5706 __dead static void
5707 usage_remove(void)
5709 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] path ...\n",
5710 getprogname());
5711 exit(1);
5714 static const struct got_error *
5715 print_remove_status(void *arg, unsigned char status,
5716 unsigned char staged_status, const char *path)
5718 while (path[0] == '/')
5719 path++;
5720 if (status == GOT_STATUS_NONEXISTENT)
5721 return NULL;
5722 if (status == staged_status && (status == GOT_STATUS_DELETE))
5723 status = GOT_STATUS_NO_CHANGE;
5724 printf("%c%c %s\n", status, staged_status, path);
5725 return NULL;
5728 static const struct got_error *
5729 cmd_remove(int argc, char *argv[])
5731 const struct got_error *error = NULL;
5732 struct got_worktree *worktree = NULL;
5733 struct got_repository *repo = NULL;
5734 char *cwd = NULL;
5735 struct got_pathlist_head paths;
5736 struct got_pathlist_entry *pe;
5737 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0;
5739 TAILQ_INIT(&paths);
5741 while ((ch = getopt(argc, argv, "fkR")) != -1) {
5742 switch (ch) {
5743 case 'f':
5744 delete_local_mods = 1;
5745 break;
5746 case 'k':
5747 keep_on_disk = 1;
5748 break;
5749 case 'R':
5750 can_recurse = 1;
5751 break;
5752 default:
5753 usage_remove();
5754 /* NOTREACHED */
5758 argc -= optind;
5759 argv += optind;
5761 #ifndef PROFILE
5762 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5763 NULL) == -1)
5764 err(1, "pledge");
5765 #endif
5766 if (argc < 1)
5767 usage_remove();
5769 cwd = getcwd(NULL, 0);
5770 if (cwd == NULL) {
5771 error = got_error_from_errno("getcwd");
5772 goto done;
5774 error = got_worktree_open(&worktree, cwd);
5775 if (error) {
5776 if (error->code == GOT_ERR_NOT_WORKTREE)
5777 error = wrap_not_worktree_error(error, "remove", cwd);
5778 goto done;
5781 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5782 NULL);
5783 if (error)
5784 goto done;
5786 error = apply_unveil(got_repo_get_path(repo), 1,
5787 got_worktree_get_root_path(worktree));
5788 if (error)
5789 goto done;
5791 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5792 if (error)
5793 goto done;
5795 if (!can_recurse) {
5796 char *ondisk_path;
5797 struct stat sb;
5798 TAILQ_FOREACH(pe, &paths, entry) {
5799 if (asprintf(&ondisk_path, "%s/%s",
5800 got_worktree_get_root_path(worktree),
5801 pe->path) == -1) {
5802 error = got_error_from_errno("asprintf");
5803 goto done;
5805 if (lstat(ondisk_path, &sb) == -1) {
5806 if (errno == ENOENT) {
5807 free(ondisk_path);
5808 continue;
5810 error = got_error_from_errno2("lstat",
5811 ondisk_path);
5812 free(ondisk_path);
5813 goto done;
5815 free(ondisk_path);
5816 if (S_ISDIR(sb.st_mode)) {
5817 error = got_error_msg(GOT_ERR_BAD_PATH,
5818 "removing directories requires -R option");
5819 goto done;
5824 error = got_worktree_schedule_delete(worktree, &paths,
5825 delete_local_mods, print_remove_status, NULL, repo, keep_on_disk);
5826 done:
5827 if (repo)
5828 got_repo_close(repo);
5829 if (worktree)
5830 got_worktree_close(worktree);
5831 TAILQ_FOREACH(pe, &paths, entry)
5832 free((char *)pe->path);
5833 got_pathlist_free(&paths);
5834 free(cwd);
5835 return error;
5838 __dead static void
5839 usage_revert(void)
5841 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
5842 "path ...\n", getprogname());
5843 exit(1);
5846 static const struct got_error *
5847 revert_progress(void *arg, unsigned char status, const char *path)
5849 if (status == GOT_STATUS_UNVERSIONED)
5850 return NULL;
5852 while (path[0] == '/')
5853 path++;
5854 printf("%c %s\n", status, path);
5855 return NULL;
5858 struct choose_patch_arg {
5859 FILE *patch_script_file;
5860 const char *action;
5863 static const struct got_error *
5864 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
5865 int nchanges, const char *action)
5867 char *line = NULL;
5868 size_t linesize = 0;
5869 ssize_t linelen;
5871 switch (status) {
5872 case GOT_STATUS_ADD:
5873 printf("A %s\n%s this addition? [y/n] ", path, action);
5874 break;
5875 case GOT_STATUS_DELETE:
5876 printf("D %s\n%s this deletion? [y/n] ", path, action);
5877 break;
5878 case GOT_STATUS_MODIFY:
5879 if (fseek(patch_file, 0L, SEEK_SET) == -1)
5880 return got_error_from_errno("fseek");
5881 printf(GOT_COMMIT_SEP_STR);
5882 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
5883 printf("%s", line);
5884 if (ferror(patch_file))
5885 return got_error_from_errno("getline");
5886 printf(GOT_COMMIT_SEP_STR);
5887 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
5888 path, n, nchanges, action);
5889 break;
5890 default:
5891 return got_error_path(path, GOT_ERR_FILE_STATUS);
5894 return NULL;
5897 static const struct got_error *
5898 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
5899 FILE *patch_file, int n, int nchanges)
5901 const struct got_error *err = NULL;
5902 char *line = NULL;
5903 size_t linesize = 0;
5904 ssize_t linelen;
5905 int resp = ' ';
5906 struct choose_patch_arg *a = arg;
5908 *choice = GOT_PATCH_CHOICE_NONE;
5910 if (a->patch_script_file) {
5911 char *nl;
5912 err = show_change(status, path, patch_file, n, nchanges,
5913 a->action);
5914 if (err)
5915 return err;
5916 linelen = getline(&line, &linesize, a->patch_script_file);
5917 if (linelen == -1) {
5918 if (ferror(a->patch_script_file))
5919 return got_error_from_errno("getline");
5920 return NULL;
5922 nl = strchr(line, '\n');
5923 if (nl)
5924 *nl = '\0';
5925 if (strcmp(line, "y") == 0) {
5926 *choice = GOT_PATCH_CHOICE_YES;
5927 printf("y\n");
5928 } else if (strcmp(line, "n") == 0) {
5929 *choice = GOT_PATCH_CHOICE_NO;
5930 printf("n\n");
5931 } else if (strcmp(line, "q") == 0 &&
5932 status == GOT_STATUS_MODIFY) {
5933 *choice = GOT_PATCH_CHOICE_QUIT;
5934 printf("q\n");
5935 } else
5936 printf("invalid response '%s'\n", line);
5937 free(line);
5938 return NULL;
5941 while (resp != 'y' && resp != 'n' && resp != 'q') {
5942 err = show_change(status, path, patch_file, n, nchanges,
5943 a->action);
5944 if (err)
5945 return err;
5946 resp = getchar();
5947 if (resp == '\n')
5948 resp = getchar();
5949 if (status == GOT_STATUS_MODIFY) {
5950 if (resp != 'y' && resp != 'n' && resp != 'q') {
5951 printf("invalid response '%c'\n", resp);
5952 resp = ' ';
5954 } else if (resp != 'y' && resp != 'n') {
5955 printf("invalid response '%c'\n", resp);
5956 resp = ' ';
5960 if (resp == 'y')
5961 *choice = GOT_PATCH_CHOICE_YES;
5962 else if (resp == 'n')
5963 *choice = GOT_PATCH_CHOICE_NO;
5964 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
5965 *choice = GOT_PATCH_CHOICE_QUIT;
5967 return NULL;
5971 static const struct got_error *
5972 cmd_revert(int argc, char *argv[])
5974 const struct got_error *error = NULL;
5975 struct got_worktree *worktree = NULL;
5976 struct got_repository *repo = NULL;
5977 char *cwd = NULL, *path = NULL;
5978 struct got_pathlist_head paths;
5979 struct got_pathlist_entry *pe;
5980 int ch, can_recurse = 0, pflag = 0;
5981 FILE *patch_script_file = NULL;
5982 const char *patch_script_path = NULL;
5983 struct choose_patch_arg cpa;
5985 TAILQ_INIT(&paths);
5987 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
5988 switch (ch) {
5989 case 'p':
5990 pflag = 1;
5991 break;
5992 case 'F':
5993 patch_script_path = optarg;
5994 break;
5995 case 'R':
5996 can_recurse = 1;
5997 break;
5998 default:
5999 usage_revert();
6000 /* NOTREACHED */
6004 argc -= optind;
6005 argv += optind;
6007 #ifndef PROFILE
6008 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6009 "unveil", NULL) == -1)
6010 err(1, "pledge");
6011 #endif
6012 if (argc < 1)
6013 usage_revert();
6014 if (patch_script_path && !pflag)
6015 errx(1, "-F option can only be used together with -p option");
6017 cwd = getcwd(NULL, 0);
6018 if (cwd == NULL) {
6019 error = got_error_from_errno("getcwd");
6020 goto done;
6022 error = got_worktree_open(&worktree, cwd);
6023 if (error) {
6024 if (error->code == GOT_ERR_NOT_WORKTREE)
6025 error = wrap_not_worktree_error(error, "revert", cwd);
6026 goto done;
6029 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6030 NULL);
6031 if (error != NULL)
6032 goto done;
6034 if (patch_script_path) {
6035 patch_script_file = fopen(patch_script_path, "r");
6036 if (patch_script_file == NULL) {
6037 error = got_error_from_errno2("fopen",
6038 patch_script_path);
6039 goto done;
6042 error = apply_unveil(got_repo_get_path(repo), 1,
6043 got_worktree_get_root_path(worktree));
6044 if (error)
6045 goto done;
6047 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6048 if (error)
6049 goto done;
6051 if (!can_recurse) {
6052 char *ondisk_path;
6053 struct stat sb;
6054 TAILQ_FOREACH(pe, &paths, entry) {
6055 if (asprintf(&ondisk_path, "%s/%s",
6056 got_worktree_get_root_path(worktree),
6057 pe->path) == -1) {
6058 error = got_error_from_errno("asprintf");
6059 goto done;
6061 if (lstat(ondisk_path, &sb) == -1) {
6062 if (errno == ENOENT) {
6063 free(ondisk_path);
6064 continue;
6066 error = got_error_from_errno2("lstat",
6067 ondisk_path);
6068 free(ondisk_path);
6069 goto done;
6071 free(ondisk_path);
6072 if (S_ISDIR(sb.st_mode)) {
6073 error = got_error_msg(GOT_ERR_BAD_PATH,
6074 "reverting directories requires -R option");
6075 goto done;
6080 cpa.patch_script_file = patch_script_file;
6081 cpa.action = "revert";
6082 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6083 pflag ? choose_patch : NULL, &cpa, repo);
6084 done:
6085 if (patch_script_file && fclose(patch_script_file) == EOF &&
6086 error == NULL)
6087 error = got_error_from_errno2("fclose", patch_script_path);
6088 if (repo)
6089 got_repo_close(repo);
6090 if (worktree)
6091 got_worktree_close(worktree);
6092 free(path);
6093 free(cwd);
6094 return error;
6097 __dead static void
6098 usage_commit(void)
6100 fprintf(stderr, "usage: %s commit [-m msg] [path ...]\n",
6101 getprogname());
6102 exit(1);
6105 struct collect_commit_logmsg_arg {
6106 const char *cmdline_log;
6107 const char *editor;
6108 const char *worktree_path;
6109 const char *branch_name;
6110 const char *repo_path;
6111 char *logmsg_path;
6115 static const struct got_error *
6116 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6117 void *arg)
6119 char *initial_content = NULL;
6120 struct got_pathlist_entry *pe;
6121 const struct got_error *err = NULL;
6122 char *template = NULL;
6123 struct collect_commit_logmsg_arg *a = arg;
6124 int fd;
6125 size_t len;
6127 /* if a message was specified on the command line, just use it */
6128 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6129 len = strlen(a->cmdline_log) + 1;
6130 *logmsg = malloc(len + 1);
6131 if (*logmsg == NULL)
6132 return got_error_from_errno("malloc");
6133 strlcpy(*logmsg, a->cmdline_log, len);
6134 return NULL;
6137 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6138 return got_error_from_errno("asprintf");
6140 if (asprintf(&initial_content,
6141 "\n# changes to be committed on branch %s:\n",
6142 a->branch_name) == -1)
6143 return got_error_from_errno("asprintf");
6145 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6146 if (err)
6147 goto done;
6149 dprintf(fd, initial_content);
6151 TAILQ_FOREACH(pe, commitable_paths, entry) {
6152 struct got_commitable *ct = pe->data;
6153 dprintf(fd, "# %c %s\n",
6154 got_commitable_get_status(ct),
6155 got_commitable_get_path(ct));
6157 close(fd);
6159 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
6160 done:
6161 free(initial_content);
6162 free(template);
6164 /* Editor is done; we can now apply unveil(2) */
6165 if (err == NULL) {
6166 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6167 if (err) {
6168 free(*logmsg);
6169 *logmsg = NULL;
6172 return err;
6175 static const struct got_error *
6176 cmd_commit(int argc, char *argv[])
6178 const struct got_error *error = NULL;
6179 struct got_worktree *worktree = NULL;
6180 struct got_repository *repo = NULL;
6181 char *cwd = NULL, *id_str = NULL;
6182 struct got_object_id *id = NULL;
6183 const char *logmsg = NULL;
6184 struct collect_commit_logmsg_arg cl_arg;
6185 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6186 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6187 struct got_pathlist_head paths;
6189 TAILQ_INIT(&paths);
6190 cl_arg.logmsg_path = NULL;
6192 while ((ch = getopt(argc, argv, "m:")) != -1) {
6193 switch (ch) {
6194 case 'm':
6195 logmsg = optarg;
6196 break;
6197 default:
6198 usage_commit();
6199 /* NOTREACHED */
6203 argc -= optind;
6204 argv += optind;
6206 #ifndef PROFILE
6207 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6208 "unveil", NULL) == -1)
6209 err(1, "pledge");
6210 #endif
6211 cwd = getcwd(NULL, 0);
6212 if (cwd == NULL) {
6213 error = got_error_from_errno("getcwd");
6214 goto done;
6216 error = got_worktree_open(&worktree, cwd);
6217 if (error) {
6218 if (error->code == GOT_ERR_NOT_WORKTREE)
6219 error = wrap_not_worktree_error(error, "commit", cwd);
6220 goto done;
6223 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6224 if (error)
6225 goto done;
6226 if (rebase_in_progress) {
6227 error = got_error(GOT_ERR_REBASING);
6228 goto done;
6231 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6232 worktree);
6233 if (error)
6234 goto done;
6236 error = get_gitconfig_path(&gitconfig_path);
6237 if (error)
6238 goto done;
6239 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6240 gitconfig_path);
6241 if (error != NULL)
6242 goto done;
6244 error = get_author(&author, repo);
6245 if (error)
6246 return error;
6249 * unveil(2) traverses exec(2); if an editor is used we have
6250 * to apply unveil after the log message has been written.
6252 if (logmsg == NULL || strlen(logmsg) == 0)
6253 error = get_editor(&editor);
6254 else
6255 error = apply_unveil(got_repo_get_path(repo), 0,
6256 got_worktree_get_root_path(worktree));
6257 if (error)
6258 goto done;
6260 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6261 if (error)
6262 goto done;
6264 cl_arg.editor = editor;
6265 cl_arg.cmdline_log = logmsg;
6266 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6267 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6268 if (!histedit_in_progress) {
6269 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6270 error = got_error(GOT_ERR_COMMIT_BRANCH);
6271 goto done;
6273 cl_arg.branch_name += 11;
6275 cl_arg.repo_path = got_repo_get_path(repo);
6276 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6277 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
6278 if (error) {
6279 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6280 cl_arg.logmsg_path != NULL)
6281 preserve_logmsg = 1;
6282 goto done;
6285 error = got_object_id_str(&id_str, id);
6286 if (error)
6287 goto done;
6288 printf("Created commit %s\n", id_str);
6289 done:
6290 if (preserve_logmsg) {
6291 fprintf(stderr, "%s: log message preserved in %s\n",
6292 getprogname(), cl_arg.logmsg_path);
6293 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6294 error == NULL)
6295 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6296 free(cl_arg.logmsg_path);
6297 if (repo)
6298 got_repo_close(repo);
6299 if (worktree)
6300 got_worktree_close(worktree);
6301 free(cwd);
6302 free(id_str);
6303 free(gitconfig_path);
6304 free(editor);
6305 free(author);
6306 return error;
6309 __dead static void
6310 usage_cherrypick(void)
6312 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6313 exit(1);
6316 static const struct got_error *
6317 cmd_cherrypick(int argc, char *argv[])
6319 const struct got_error *error = NULL;
6320 struct got_worktree *worktree = NULL;
6321 struct got_repository *repo = NULL;
6322 char *cwd = NULL, *commit_id_str = NULL;
6323 struct got_object_id *commit_id = NULL;
6324 struct got_commit_object *commit = NULL;
6325 struct got_object_qid *pid;
6326 struct got_reference *head_ref = NULL;
6327 int ch, did_something = 0;
6329 while ((ch = getopt(argc, argv, "")) != -1) {
6330 switch (ch) {
6331 default:
6332 usage_cherrypick();
6333 /* NOTREACHED */
6337 argc -= optind;
6338 argv += optind;
6340 #ifndef PROFILE
6341 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6342 "unveil", NULL) == -1)
6343 err(1, "pledge");
6344 #endif
6345 if (argc != 1)
6346 usage_cherrypick();
6348 cwd = getcwd(NULL, 0);
6349 if (cwd == NULL) {
6350 error = got_error_from_errno("getcwd");
6351 goto done;
6353 error = got_worktree_open(&worktree, cwd);
6354 if (error) {
6355 if (error->code == GOT_ERR_NOT_WORKTREE)
6356 error = wrap_not_worktree_error(error, "cherrypick",
6357 cwd);
6358 goto done;
6361 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6362 NULL);
6363 if (error != NULL)
6364 goto done;
6366 error = apply_unveil(got_repo_get_path(repo), 0,
6367 got_worktree_get_root_path(worktree));
6368 if (error)
6369 goto done;
6371 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6372 GOT_OBJ_TYPE_COMMIT, repo);
6373 if (error != NULL) {
6374 struct got_reference *ref;
6375 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6376 goto done;
6377 error = got_ref_open(&ref, repo, argv[0], 0);
6378 if (error != NULL)
6379 goto done;
6380 error = got_ref_resolve(&commit_id, repo, ref);
6381 got_ref_close(ref);
6382 if (error != NULL)
6383 goto done;
6385 error = got_object_id_str(&commit_id_str, commit_id);
6386 if (error)
6387 goto done;
6389 error = got_ref_open(&head_ref, repo,
6390 got_worktree_get_head_ref_name(worktree), 0);
6391 if (error != NULL)
6392 goto done;
6394 error = check_same_branch(commit_id, head_ref, NULL, repo);
6395 if (error) {
6396 if (error->code != GOT_ERR_ANCESTRY)
6397 goto done;
6398 error = NULL;
6399 } else {
6400 error = got_error(GOT_ERR_SAME_BRANCH);
6401 goto done;
6404 error = got_object_open_as_commit(&commit, repo, commit_id);
6405 if (error)
6406 goto done;
6407 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6408 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
6409 commit_id, repo, update_progress, &did_something, check_cancelled,
6410 NULL);
6411 if (error != NULL)
6412 goto done;
6414 if (did_something)
6415 printf("Merged commit %s\n", commit_id_str);
6416 done:
6417 if (commit)
6418 got_object_commit_close(commit);
6419 free(commit_id_str);
6420 if (head_ref)
6421 got_ref_close(head_ref);
6422 if (worktree)
6423 got_worktree_close(worktree);
6424 if (repo)
6425 got_repo_close(repo);
6426 return error;
6429 __dead static void
6430 usage_backout(void)
6432 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
6433 exit(1);
6436 static const struct got_error *
6437 cmd_backout(int argc, char *argv[])
6439 const struct got_error *error = NULL;
6440 struct got_worktree *worktree = NULL;
6441 struct got_repository *repo = NULL;
6442 char *cwd = NULL, *commit_id_str = NULL;
6443 struct got_object_id *commit_id = NULL;
6444 struct got_commit_object *commit = NULL;
6445 struct got_object_qid *pid;
6446 struct got_reference *head_ref = NULL;
6447 int ch, did_something = 0;
6449 while ((ch = getopt(argc, argv, "")) != -1) {
6450 switch (ch) {
6451 default:
6452 usage_backout();
6453 /* NOTREACHED */
6457 argc -= optind;
6458 argv += optind;
6460 #ifndef PROFILE
6461 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6462 "unveil", NULL) == -1)
6463 err(1, "pledge");
6464 #endif
6465 if (argc != 1)
6466 usage_backout();
6468 cwd = getcwd(NULL, 0);
6469 if (cwd == NULL) {
6470 error = got_error_from_errno("getcwd");
6471 goto done;
6473 error = got_worktree_open(&worktree, cwd);
6474 if (error) {
6475 if (error->code == GOT_ERR_NOT_WORKTREE)
6476 error = wrap_not_worktree_error(error, "backout", cwd);
6477 goto done;
6480 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6481 NULL);
6482 if (error != NULL)
6483 goto done;
6485 error = apply_unveil(got_repo_get_path(repo), 0,
6486 got_worktree_get_root_path(worktree));
6487 if (error)
6488 goto done;
6490 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6491 GOT_OBJ_TYPE_COMMIT, repo);
6492 if (error != NULL) {
6493 struct got_reference *ref;
6494 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6495 goto done;
6496 error = got_ref_open(&ref, repo, argv[0], 0);
6497 if (error != NULL)
6498 goto done;
6499 error = got_ref_resolve(&commit_id, repo, ref);
6500 got_ref_close(ref);
6501 if (error != NULL)
6502 goto done;
6504 error = got_object_id_str(&commit_id_str, commit_id);
6505 if (error)
6506 goto done;
6508 error = got_ref_open(&head_ref, repo,
6509 got_worktree_get_head_ref_name(worktree), 0);
6510 if (error != NULL)
6511 goto done;
6513 error = check_same_branch(commit_id, head_ref, NULL, repo);
6514 if (error)
6515 goto done;
6517 error = got_object_open_as_commit(&commit, repo, commit_id);
6518 if (error)
6519 goto done;
6520 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6521 if (pid == NULL) {
6522 error = got_error(GOT_ERR_ROOT_COMMIT);
6523 goto done;
6526 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
6527 update_progress, &did_something, check_cancelled, NULL);
6528 if (error != NULL)
6529 goto done;
6531 if (did_something)
6532 printf("Backed out commit %s\n", commit_id_str);
6533 done:
6534 if (commit)
6535 got_object_commit_close(commit);
6536 free(commit_id_str);
6537 if (head_ref)
6538 got_ref_close(head_ref);
6539 if (worktree)
6540 got_worktree_close(worktree);
6541 if (repo)
6542 got_repo_close(repo);
6543 return error;
6546 __dead static void
6547 usage_rebase(void)
6549 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
6550 getprogname());
6551 exit(1);
6554 void
6555 trim_logmsg(char *logmsg, int limit)
6557 char *nl;
6558 size_t len;
6560 len = strlen(logmsg);
6561 if (len > limit)
6562 len = limit;
6563 logmsg[len] = '\0';
6564 nl = strchr(logmsg, '\n');
6565 if (nl)
6566 *nl = '\0';
6569 static const struct got_error *
6570 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
6572 const struct got_error *err;
6573 char *logmsg0 = NULL;
6574 const char *s;
6576 err = got_object_commit_get_logmsg(&logmsg0, commit);
6577 if (err)
6578 return err;
6580 s = logmsg0;
6581 while (isspace((unsigned char)s[0]))
6582 s++;
6584 *logmsg = strdup(s);
6585 if (*logmsg == NULL) {
6586 err = got_error_from_errno("strdup");
6587 goto done;
6590 trim_logmsg(*logmsg, limit);
6591 done:
6592 free(logmsg0);
6593 return err;
6596 static const struct got_error *
6597 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
6599 const struct got_error *err;
6600 struct got_commit_object *commit = NULL;
6601 char *id_str = NULL, *logmsg = NULL;
6603 err = got_object_open_as_commit(&commit, repo, id);
6604 if (err)
6605 return err;
6607 err = got_object_id_str(&id_str, id);
6608 if (err)
6609 goto done;
6611 id_str[12] = '\0';
6613 err = get_short_logmsg(&logmsg, 42, commit);
6614 if (err)
6615 goto done;
6617 printf("%s -> merge conflict: %s\n", id_str, logmsg);
6618 done:
6619 free(id_str);
6620 got_object_commit_close(commit);
6621 free(logmsg);
6622 return err;
6625 static const struct got_error *
6626 show_rebase_progress(struct got_commit_object *commit,
6627 struct got_object_id *old_id, struct got_object_id *new_id)
6629 const struct got_error *err;
6630 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
6632 err = got_object_id_str(&old_id_str, old_id);
6633 if (err)
6634 goto done;
6636 if (new_id) {
6637 err = got_object_id_str(&new_id_str, new_id);
6638 if (err)
6639 goto done;
6642 old_id_str[12] = '\0';
6643 if (new_id_str)
6644 new_id_str[12] = '\0';
6646 err = get_short_logmsg(&logmsg, 42, commit);
6647 if (err)
6648 goto done;
6650 printf("%s -> %s: %s\n", old_id_str,
6651 new_id_str ? new_id_str : "no-op change", logmsg);
6652 done:
6653 free(old_id_str);
6654 free(new_id_str);
6655 free(logmsg);
6656 return err;
6659 static const struct got_error *
6660 rebase_progress(void *arg, unsigned char status, const char *path)
6662 unsigned char *rebase_status = arg;
6664 while (path[0] == '/')
6665 path++;
6666 printf("%c %s\n", status, path);
6668 if (*rebase_status == GOT_STATUS_CONFLICT)
6669 return NULL;
6670 if (status == GOT_STATUS_CONFLICT || status == GOT_STATUS_MERGE)
6671 *rebase_status = status;
6672 return NULL;
6675 static const struct got_error *
6676 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
6677 struct got_reference *branch, struct got_reference *new_base_branch,
6678 struct got_reference *tmp_branch, struct got_repository *repo)
6680 printf("Switching work tree to %s\n", got_ref_get_name(branch));
6681 return got_worktree_rebase_complete(worktree, fileindex,
6682 new_base_branch, tmp_branch, branch, repo);
6685 static const struct got_error *
6686 rebase_commit(struct got_pathlist_head *merged_paths,
6687 struct got_worktree *worktree, struct got_fileindex *fileindex,
6688 struct got_reference *tmp_branch,
6689 struct got_object_id *commit_id, struct got_repository *repo)
6691 const struct got_error *error;
6692 struct got_commit_object *commit;
6693 struct got_object_id *new_commit_id;
6695 error = got_object_open_as_commit(&commit, repo, commit_id);
6696 if (error)
6697 return error;
6699 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
6700 worktree, fileindex, tmp_branch, commit, commit_id, repo);
6701 if (error) {
6702 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
6703 goto done;
6704 error = show_rebase_progress(commit, commit_id, NULL);
6705 } else {
6706 error = show_rebase_progress(commit, commit_id, new_commit_id);
6707 free(new_commit_id);
6709 done:
6710 got_object_commit_close(commit);
6711 return error;
6714 struct check_path_prefix_arg {
6715 const char *path_prefix;
6716 size_t len;
6717 int errcode;
6720 static const struct got_error *
6721 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
6722 struct got_blob_object *blob2, struct got_object_id *id1,
6723 struct got_object_id *id2, const char *path1, const char *path2,
6724 mode_t mode1, mode_t mode2, struct got_repository *repo)
6726 struct check_path_prefix_arg *a = arg;
6728 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
6729 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
6730 return got_error(a->errcode);
6732 return NULL;
6735 static const struct got_error *
6736 check_path_prefix(struct got_object_id *parent_id,
6737 struct got_object_id *commit_id, const char *path_prefix,
6738 int errcode, struct got_repository *repo)
6740 const struct got_error *err;
6741 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
6742 struct got_commit_object *commit = NULL, *parent_commit = NULL;
6743 struct check_path_prefix_arg cpp_arg;
6745 if (got_path_is_root_dir(path_prefix))
6746 return NULL;
6748 err = got_object_open_as_commit(&commit, repo, commit_id);
6749 if (err)
6750 goto done;
6752 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
6753 if (err)
6754 goto done;
6756 err = got_object_open_as_tree(&tree1, repo,
6757 got_object_commit_get_tree_id(parent_commit));
6758 if (err)
6759 goto done;
6761 err = got_object_open_as_tree(&tree2, repo,
6762 got_object_commit_get_tree_id(commit));
6763 if (err)
6764 goto done;
6766 cpp_arg.path_prefix = path_prefix;
6767 while (cpp_arg.path_prefix[0] == '/')
6768 cpp_arg.path_prefix++;
6769 cpp_arg.len = strlen(cpp_arg.path_prefix);
6770 cpp_arg.errcode = errcode;
6771 err = got_diff_tree(tree1, tree2, "", "", repo,
6772 check_path_prefix_in_diff, &cpp_arg, 0);
6773 done:
6774 if (tree1)
6775 got_object_tree_close(tree1);
6776 if (tree2)
6777 got_object_tree_close(tree2);
6778 if (commit)
6779 got_object_commit_close(commit);
6780 if (parent_commit)
6781 got_object_commit_close(parent_commit);
6782 return err;
6785 static const struct got_error *
6786 collect_commits(struct got_object_id_queue *commits,
6787 struct got_object_id *initial_commit_id,
6788 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
6789 const char *path_prefix, int path_prefix_errcode,
6790 struct got_repository *repo)
6792 const struct got_error *err = NULL;
6793 struct got_commit_graph *graph = NULL;
6794 struct got_object_id *parent_id = NULL;
6795 struct got_object_qid *qid;
6796 struct got_object_id *commit_id = initial_commit_id;
6798 err = got_commit_graph_open(&graph, "/", 1);
6799 if (err)
6800 return err;
6802 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
6803 check_cancelled, NULL);
6804 if (err)
6805 goto done;
6806 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
6807 err = got_commit_graph_iter_next(&parent_id, graph, repo,
6808 check_cancelled, NULL);
6809 if (err) {
6810 if (err->code == GOT_ERR_ITER_COMPLETED) {
6811 err = got_error_msg(GOT_ERR_ANCESTRY,
6812 "ran out of commits to rebase before "
6813 "youngest common ancestor commit has "
6814 "been reached?!?");
6816 goto done;
6817 } else {
6818 err = check_path_prefix(parent_id, commit_id,
6819 path_prefix, path_prefix_errcode, repo);
6820 if (err)
6821 goto done;
6823 err = got_object_qid_alloc(&qid, commit_id);
6824 if (err)
6825 goto done;
6826 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
6827 commit_id = parent_id;
6830 done:
6831 got_commit_graph_close(graph);
6832 return err;
6835 static const struct got_error *
6836 cmd_rebase(int argc, char *argv[])
6838 const struct got_error *error = NULL;
6839 struct got_worktree *worktree = NULL;
6840 struct got_repository *repo = NULL;
6841 struct got_fileindex *fileindex = NULL;
6842 char *cwd = NULL;
6843 struct got_reference *branch = NULL;
6844 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
6845 struct got_object_id *commit_id = NULL, *parent_id = NULL;
6846 struct got_object_id *resume_commit_id = NULL;
6847 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
6848 struct got_commit_object *commit = NULL;
6849 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
6850 int histedit_in_progress = 0;
6851 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
6852 struct got_object_id_queue commits;
6853 struct got_pathlist_head merged_paths;
6854 const struct got_object_id_queue *parent_ids;
6855 struct got_object_qid *qid, *pid;
6857 SIMPLEQ_INIT(&commits);
6858 TAILQ_INIT(&merged_paths);
6860 while ((ch = getopt(argc, argv, "ac")) != -1) {
6861 switch (ch) {
6862 case 'a':
6863 abort_rebase = 1;
6864 break;
6865 case 'c':
6866 continue_rebase = 1;
6867 break;
6868 default:
6869 usage_rebase();
6870 /* NOTREACHED */
6874 argc -= optind;
6875 argv += optind;
6877 #ifndef PROFILE
6878 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6879 "unveil", NULL) == -1)
6880 err(1, "pledge");
6881 #endif
6882 if (abort_rebase && continue_rebase)
6883 usage_rebase();
6884 else if (abort_rebase || continue_rebase) {
6885 if (argc != 0)
6886 usage_rebase();
6887 } else if (argc != 1)
6888 usage_rebase();
6890 cwd = getcwd(NULL, 0);
6891 if (cwd == NULL) {
6892 error = got_error_from_errno("getcwd");
6893 goto done;
6895 error = got_worktree_open(&worktree, cwd);
6896 if (error) {
6897 if (error->code == GOT_ERR_NOT_WORKTREE)
6898 error = wrap_not_worktree_error(error, "rebase", cwd);
6899 goto done;
6902 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6903 NULL);
6904 if (error != NULL)
6905 goto done;
6907 error = apply_unveil(got_repo_get_path(repo), 0,
6908 got_worktree_get_root_path(worktree));
6909 if (error)
6910 goto done;
6912 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6913 worktree);
6914 if (error)
6915 goto done;
6916 if (histedit_in_progress) {
6917 error = got_error(GOT_ERR_HISTEDIT_BUSY);
6918 goto done;
6921 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6922 if (error)
6923 goto done;
6925 if (abort_rebase) {
6926 int did_something;
6927 if (!rebase_in_progress) {
6928 error = got_error(GOT_ERR_NOT_REBASING);
6929 goto done;
6931 error = got_worktree_rebase_continue(&resume_commit_id,
6932 &new_base_branch, &tmp_branch, &branch, &fileindex,
6933 worktree, repo);
6934 if (error)
6935 goto done;
6936 printf("Switching work tree to %s\n",
6937 got_ref_get_symref_target(new_base_branch));
6938 error = got_worktree_rebase_abort(worktree, fileindex, repo,
6939 new_base_branch, update_progress, &did_something);
6940 if (error)
6941 goto done;
6942 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
6943 goto done; /* nothing else to do */
6946 if (continue_rebase) {
6947 if (!rebase_in_progress) {
6948 error = got_error(GOT_ERR_NOT_REBASING);
6949 goto done;
6951 error = got_worktree_rebase_continue(&resume_commit_id,
6952 &new_base_branch, &tmp_branch, &branch, &fileindex,
6953 worktree, repo);
6954 if (error)
6955 goto done;
6957 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
6958 resume_commit_id, repo);
6959 if (error)
6960 goto done;
6962 yca_id = got_object_id_dup(resume_commit_id);
6963 if (yca_id == NULL) {
6964 error = got_error_from_errno("got_object_id_dup");
6965 goto done;
6967 } else {
6968 error = got_ref_open(&branch, repo, argv[0], 0);
6969 if (error != NULL)
6970 goto done;
6973 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
6974 if (error)
6975 goto done;
6977 if (!continue_rebase) {
6978 struct got_object_id *base_commit_id;
6980 base_commit_id = got_worktree_get_base_commit_id(worktree);
6981 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
6982 base_commit_id, branch_head_commit_id, repo,
6983 check_cancelled, NULL);
6984 if (error)
6985 goto done;
6986 if (yca_id == NULL) {
6987 error = got_error_msg(GOT_ERR_ANCESTRY,
6988 "specified branch shares no common ancestry "
6989 "with work tree's branch");
6990 goto done;
6993 error = check_same_branch(base_commit_id, branch, yca_id, repo);
6994 if (error) {
6995 if (error->code != GOT_ERR_ANCESTRY)
6996 goto done;
6997 error = NULL;
6998 } else {
6999 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7000 "specified branch resolves to a commit which "
7001 "is already contained in work tree's branch");
7002 goto done;
7004 error = got_worktree_rebase_prepare(&new_base_branch,
7005 &tmp_branch, &fileindex, worktree, branch, repo);
7006 if (error)
7007 goto done;
7010 commit_id = branch_head_commit_id;
7011 error = got_object_open_as_commit(&commit, repo, commit_id);
7012 if (error)
7013 goto done;
7015 parent_ids = got_object_commit_get_parent_ids(commit);
7016 pid = SIMPLEQ_FIRST(parent_ids);
7017 if (pid == NULL) {
7018 if (!continue_rebase) {
7019 int did_something;
7020 error = got_worktree_rebase_abort(worktree, fileindex,
7021 repo, new_base_branch, update_progress,
7022 &did_something);
7023 if (error)
7024 goto done;
7025 printf("Rebase of %s aborted\n",
7026 got_ref_get_name(branch));
7028 error = got_error(GOT_ERR_EMPTY_REBASE);
7029 goto done;
7031 error = collect_commits(&commits, commit_id, pid->id,
7032 yca_id, got_worktree_get_path_prefix(worktree),
7033 GOT_ERR_REBASE_PATH, repo);
7034 got_object_commit_close(commit);
7035 commit = NULL;
7036 if (error)
7037 goto done;
7039 if (SIMPLEQ_EMPTY(&commits)) {
7040 if (continue_rebase) {
7041 error = rebase_complete(worktree, fileindex,
7042 branch, new_base_branch, tmp_branch, repo);
7043 goto done;
7044 } else {
7045 /* Fast-forward the reference of the branch. */
7046 struct got_object_id *new_head_commit_id;
7047 char *id_str;
7048 error = got_ref_resolve(&new_head_commit_id, repo,
7049 new_base_branch);
7050 if (error)
7051 goto done;
7052 error = got_object_id_str(&id_str, new_head_commit_id);
7053 printf("Forwarding %s to commit %s\n",
7054 got_ref_get_name(branch), id_str);
7055 free(id_str);
7056 error = got_ref_change_ref(branch,
7057 new_head_commit_id);
7058 if (error)
7059 goto done;
7063 pid = NULL;
7064 SIMPLEQ_FOREACH(qid, &commits, entry) {
7065 commit_id = qid->id;
7066 parent_id = pid ? pid->id : yca_id;
7067 pid = qid;
7069 error = got_worktree_rebase_merge_files(&merged_paths,
7070 worktree, fileindex, parent_id, commit_id, repo,
7071 rebase_progress, &rebase_status, check_cancelled, NULL);
7072 if (error)
7073 goto done;
7075 if (rebase_status == GOT_STATUS_CONFLICT) {
7076 error = show_rebase_merge_conflict(qid->id, repo);
7077 if (error)
7078 goto done;
7079 got_worktree_rebase_pathlist_free(&merged_paths);
7080 break;
7083 error = rebase_commit(&merged_paths, worktree, fileindex,
7084 tmp_branch, commit_id, repo);
7085 got_worktree_rebase_pathlist_free(&merged_paths);
7086 if (error)
7087 goto done;
7090 if (rebase_status == GOT_STATUS_CONFLICT) {
7091 error = got_worktree_rebase_postpone(worktree, fileindex);
7092 if (error)
7093 goto done;
7094 error = got_error_msg(GOT_ERR_CONFLICTS,
7095 "conflicts must be resolved before rebasing can continue");
7096 } else
7097 error = rebase_complete(worktree, fileindex, branch,
7098 new_base_branch, tmp_branch, repo);
7099 done:
7100 got_object_id_queue_free(&commits);
7101 free(branch_head_commit_id);
7102 free(resume_commit_id);
7103 free(yca_id);
7104 if (commit)
7105 got_object_commit_close(commit);
7106 if (branch)
7107 got_ref_close(branch);
7108 if (new_base_branch)
7109 got_ref_close(new_base_branch);
7110 if (tmp_branch)
7111 got_ref_close(tmp_branch);
7112 if (worktree)
7113 got_worktree_close(worktree);
7114 if (repo)
7115 got_repo_close(repo);
7116 return error;
7119 __dead static void
7120 usage_histedit(void)
7122 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
7123 getprogname());
7124 exit(1);
7127 #define GOT_HISTEDIT_PICK 'p'
7128 #define GOT_HISTEDIT_EDIT 'e'
7129 #define GOT_HISTEDIT_FOLD 'f'
7130 #define GOT_HISTEDIT_DROP 'd'
7131 #define GOT_HISTEDIT_MESG 'm'
7133 static struct got_histedit_cmd {
7134 unsigned char code;
7135 const char *name;
7136 const char *desc;
7137 } got_histedit_cmds[] = {
7138 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7139 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7140 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7141 "be used" },
7142 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7143 { GOT_HISTEDIT_MESG, "mesg",
7144 "single-line log message for commit above (open editor if empty)" },
7147 struct got_histedit_list_entry {
7148 TAILQ_ENTRY(got_histedit_list_entry) entry;
7149 struct got_object_id *commit_id;
7150 const struct got_histedit_cmd *cmd;
7151 char *logmsg;
7153 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7155 static const struct got_error *
7156 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7157 FILE *f, struct got_repository *repo)
7159 const struct got_error *err = NULL;
7160 char *logmsg = NULL, *id_str = NULL;
7161 struct got_commit_object *commit = NULL;
7162 int n;
7164 err = got_object_open_as_commit(&commit, repo, commit_id);
7165 if (err)
7166 goto done;
7168 err = get_short_logmsg(&logmsg, 34, commit);
7169 if (err)
7170 goto done;
7172 err = got_object_id_str(&id_str, commit_id);
7173 if (err)
7174 goto done;
7176 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7177 if (n < 0)
7178 err = got_ferror(f, GOT_ERR_IO);
7179 done:
7180 if (commit)
7181 got_object_commit_close(commit);
7182 free(id_str);
7183 free(logmsg);
7184 return err;
7187 static const struct got_error *
7188 histedit_write_commit_list(struct got_object_id_queue *commits,
7189 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7191 const struct got_error *err = NULL;
7192 struct got_object_qid *qid;
7194 if (SIMPLEQ_EMPTY(commits))
7195 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7197 SIMPLEQ_FOREACH(qid, commits, entry) {
7198 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7199 f, repo);
7200 if (err)
7201 break;
7202 if (edit_logmsg_only) {
7203 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7204 if (n < 0) {
7205 err = got_ferror(f, GOT_ERR_IO);
7206 break;
7211 return err;
7214 static const struct got_error *
7215 write_cmd_list(FILE *f, const char *branch_name,
7216 struct got_object_id_queue *commits)
7218 const struct got_error *err = NULL;
7219 int n, i;
7220 char *id_str;
7221 struct got_object_qid *qid;
7223 qid = SIMPLEQ_FIRST(commits);
7224 err = got_object_id_str(&id_str, qid->id);
7225 if (err)
7226 return err;
7228 n = fprintf(f,
7229 "# Editing the history of branch '%s' starting at\n"
7230 "# commit %s\n"
7231 "# Commits will be processed in order from top to "
7232 "bottom of this file.\n", branch_name, id_str);
7233 if (n < 0) {
7234 err = got_ferror(f, GOT_ERR_IO);
7235 goto done;
7238 n = fprintf(f, "# Available histedit commands:\n");
7239 if (n < 0) {
7240 err = got_ferror(f, GOT_ERR_IO);
7241 goto done;
7244 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7245 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7246 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7247 cmd->desc);
7248 if (n < 0) {
7249 err = got_ferror(f, GOT_ERR_IO);
7250 break;
7253 done:
7254 free(id_str);
7255 return err;
7258 static const struct got_error *
7259 histedit_syntax_error(int lineno)
7261 static char msg[42];
7262 int ret;
7264 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7265 lineno);
7266 if (ret == -1 || ret >= sizeof(msg))
7267 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7269 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7272 static const struct got_error *
7273 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7274 char *logmsg, struct got_repository *repo)
7276 const struct got_error *err;
7277 struct got_commit_object *folded_commit = NULL;
7278 char *id_str, *folded_logmsg = NULL;
7280 err = got_object_id_str(&id_str, hle->commit_id);
7281 if (err)
7282 return err;
7284 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7285 if (err)
7286 goto done;
7288 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7289 if (err)
7290 goto done;
7291 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7292 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7293 folded_logmsg) == -1) {
7294 err = got_error_from_errno("asprintf");
7296 done:
7297 if (folded_commit)
7298 got_object_commit_close(folded_commit);
7299 free(id_str);
7300 free(folded_logmsg);
7301 return err;
7304 static struct got_histedit_list_entry *
7305 get_folded_commits(struct got_histedit_list_entry *hle)
7307 struct got_histedit_list_entry *prev, *folded = NULL;
7309 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7310 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7311 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7312 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7313 folded = prev;
7314 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7317 return folded;
7320 static const struct got_error *
7321 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7322 struct got_repository *repo)
7324 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7325 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7326 const struct got_error *err = NULL;
7327 struct got_commit_object *commit = NULL;
7328 int fd;
7329 struct got_histedit_list_entry *folded = NULL;
7331 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7332 if (err)
7333 return err;
7335 folded = get_folded_commits(hle);
7336 if (folded) {
7337 while (folded != hle) {
7338 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7339 folded = TAILQ_NEXT(folded, entry);
7340 continue;
7342 err = append_folded_commit_msg(&new_msg, folded,
7343 logmsg, repo);
7344 if (err)
7345 goto done;
7346 free(logmsg);
7347 logmsg = new_msg;
7348 folded = TAILQ_NEXT(folded, entry);
7352 err = got_object_id_str(&id_str, hle->commit_id);
7353 if (err)
7354 goto done;
7355 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7356 if (err)
7357 goto done;
7358 if (asprintf(&new_msg,
7359 "%s\n# original log message of commit %s: %s",
7360 logmsg ? logmsg : "", id_str, orig_logmsg) == -1) {
7361 err = got_error_from_errno("asprintf");
7362 goto done;
7364 free(logmsg);
7365 logmsg = new_msg;
7367 err = got_object_id_str(&id_str, hle->commit_id);
7368 if (err)
7369 goto done;
7371 err = got_opentemp_named_fd(&logmsg_path, &fd,
7372 GOT_TMPDIR_STR "/got-logmsg");
7373 if (err)
7374 goto done;
7376 dprintf(fd, logmsg);
7377 close(fd);
7379 err = get_editor(&editor);
7380 if (err)
7381 goto done;
7383 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
7384 if (err) {
7385 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
7386 goto done;
7387 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
7389 done:
7390 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
7391 err = got_error_from_errno2("unlink", logmsg_path);
7392 free(logmsg_path);
7393 free(logmsg);
7394 free(orig_logmsg);
7395 free(editor);
7396 if (commit)
7397 got_object_commit_close(commit);
7398 return err;
7401 static const struct got_error *
7402 histedit_parse_list(struct got_histedit_list *histedit_cmds,
7403 FILE *f, struct got_repository *repo)
7405 const struct got_error *err = NULL;
7406 char *line = NULL, *p, *end;
7407 size_t size;
7408 ssize_t len;
7409 int lineno = 0, i;
7410 const struct got_histedit_cmd *cmd;
7411 struct got_object_id *commit_id = NULL;
7412 struct got_histedit_list_entry *hle = NULL;
7414 for (;;) {
7415 len = getline(&line, &size, f);
7416 if (len == -1) {
7417 const struct got_error *getline_err;
7418 if (feof(f))
7419 break;
7420 getline_err = got_error_from_errno("getline");
7421 err = got_ferror(f, getline_err->code);
7422 break;
7424 lineno++;
7425 p = line;
7426 while (isspace((unsigned char)p[0]))
7427 p++;
7428 if (p[0] == '#' || p[0] == '\0') {
7429 free(line);
7430 line = NULL;
7431 continue;
7433 cmd = NULL;
7434 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7435 cmd = &got_histedit_cmds[i];
7436 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
7437 isspace((unsigned char)p[strlen(cmd->name)])) {
7438 p += strlen(cmd->name);
7439 break;
7441 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
7442 p++;
7443 break;
7446 if (i == nitems(got_histedit_cmds)) {
7447 err = histedit_syntax_error(lineno);
7448 break;
7450 while (isspace((unsigned char)p[0]))
7451 p++;
7452 if (cmd->code == GOT_HISTEDIT_MESG) {
7453 if (hle == NULL || hle->logmsg != NULL) {
7454 err = got_error(GOT_ERR_HISTEDIT_CMD);
7455 break;
7457 if (p[0] == '\0') {
7458 err = histedit_edit_logmsg(hle, repo);
7459 if (err)
7460 break;
7461 } else {
7462 hle->logmsg = strdup(p);
7463 if (hle->logmsg == NULL) {
7464 err = got_error_from_errno("strdup");
7465 break;
7468 free(line);
7469 line = NULL;
7470 continue;
7471 } else {
7472 end = p;
7473 while (end[0] && !isspace((unsigned char)end[0]))
7474 end++;
7475 *end = '\0';
7477 err = got_object_resolve_id_str(&commit_id, repo, p);
7478 if (err) {
7479 /* override error code */
7480 err = histedit_syntax_error(lineno);
7481 break;
7484 hle = malloc(sizeof(*hle));
7485 if (hle == NULL) {
7486 err = got_error_from_errno("malloc");
7487 break;
7489 hle->cmd = cmd;
7490 hle->commit_id = commit_id;
7491 hle->logmsg = NULL;
7492 commit_id = NULL;
7493 free(line);
7494 line = NULL;
7495 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
7498 free(line);
7499 free(commit_id);
7500 return err;
7503 static const struct got_error *
7504 histedit_check_script(struct got_histedit_list *histedit_cmds,
7505 struct got_object_id_queue *commits, struct got_repository *repo)
7507 const struct got_error *err = NULL;
7508 struct got_object_qid *qid;
7509 struct got_histedit_list_entry *hle;
7510 static char msg[92];
7511 char *id_str;
7513 if (TAILQ_EMPTY(histedit_cmds))
7514 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
7515 "histedit script contains no commands");
7516 if (SIMPLEQ_EMPTY(commits))
7517 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7519 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7520 struct got_histedit_list_entry *hle2;
7521 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
7522 if (hle == hle2)
7523 continue;
7524 if (got_object_id_cmp(hle->commit_id,
7525 hle2->commit_id) != 0)
7526 continue;
7527 err = got_object_id_str(&id_str, hle->commit_id);
7528 if (err)
7529 return err;
7530 snprintf(msg, sizeof(msg), "commit %s is listed "
7531 "more than once in histedit script", id_str);
7532 free(id_str);
7533 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7537 SIMPLEQ_FOREACH(qid, commits, entry) {
7538 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7539 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
7540 break;
7542 if (hle == NULL) {
7543 err = got_object_id_str(&id_str, qid->id);
7544 if (err)
7545 return err;
7546 snprintf(msg, sizeof(msg),
7547 "commit %s missing from histedit script", id_str);
7548 free(id_str);
7549 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7553 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
7554 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
7555 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
7556 "last commit in histedit script cannot be folded");
7558 return NULL;
7561 static const struct got_error *
7562 histedit_run_editor(struct got_histedit_list *histedit_cmds,
7563 const char *path, struct got_object_id_queue *commits,
7564 struct got_repository *repo)
7566 const struct got_error *err = NULL;
7567 char *editor;
7568 FILE *f = NULL;
7570 err = get_editor(&editor);
7571 if (err)
7572 return err;
7574 if (spawn_editor(editor, path) == -1) {
7575 err = got_error_from_errno("failed spawning editor");
7576 goto done;
7579 f = fopen(path, "r");
7580 if (f == NULL) {
7581 err = got_error_from_errno("fopen");
7582 goto done;
7584 err = histedit_parse_list(histedit_cmds, f, repo);
7585 if (err)
7586 goto done;
7588 err = histedit_check_script(histedit_cmds, commits, repo);
7589 done:
7590 if (f && fclose(f) != 0 && err == NULL)
7591 err = got_error_from_errno("fclose");
7592 free(editor);
7593 return err;
7596 static const struct got_error *
7597 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
7598 struct got_object_id_queue *, const char *, const char *,
7599 struct got_repository *);
7601 static const struct got_error *
7602 histedit_edit_script(struct got_histedit_list *histedit_cmds,
7603 struct got_object_id_queue *commits, const char *branch_name,
7604 int edit_logmsg_only, struct got_repository *repo)
7606 const struct got_error *err;
7607 FILE *f = NULL;
7608 char *path = NULL;
7610 err = got_opentemp_named(&path, &f, "got-histedit");
7611 if (err)
7612 return err;
7614 err = write_cmd_list(f, branch_name, commits);
7615 if (err)
7616 goto done;
7618 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
7619 if (err)
7620 goto done;
7622 if (edit_logmsg_only) {
7623 rewind(f);
7624 err = histedit_parse_list(histedit_cmds, f, repo);
7625 } else {
7626 if (fclose(f) != 0) {
7627 err = got_error_from_errno("fclose");
7628 goto done;
7630 f = NULL;
7631 err = histedit_run_editor(histedit_cmds, path, commits, repo);
7632 if (err) {
7633 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7634 err->code != GOT_ERR_HISTEDIT_CMD)
7635 goto done;
7636 err = histedit_edit_list_retry(histedit_cmds, err,
7637 commits, path, branch_name, repo);
7640 done:
7641 if (f && fclose(f) != 0 && err == NULL)
7642 err = got_error_from_errno("fclose");
7643 if (path && unlink(path) != 0 && err == NULL)
7644 err = got_error_from_errno2("unlink", path);
7645 free(path);
7646 return err;
7649 static const struct got_error *
7650 histedit_save_list(struct got_histedit_list *histedit_cmds,
7651 struct got_worktree *worktree, struct got_repository *repo)
7653 const struct got_error *err = NULL;
7654 char *path = NULL;
7655 FILE *f = NULL;
7656 struct got_histedit_list_entry *hle;
7657 struct got_commit_object *commit = NULL;
7659 err = got_worktree_get_histedit_script_path(&path, worktree);
7660 if (err)
7661 return err;
7663 f = fopen(path, "w");
7664 if (f == NULL) {
7665 err = got_error_from_errno2("fopen", path);
7666 goto done;
7668 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7669 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
7670 repo);
7671 if (err)
7672 break;
7674 if (hle->logmsg) {
7675 int n = fprintf(f, "%c %s\n",
7676 GOT_HISTEDIT_MESG, hle->logmsg);
7677 if (n < 0) {
7678 err = got_ferror(f, GOT_ERR_IO);
7679 break;
7683 done:
7684 if (f && fclose(f) != 0 && err == NULL)
7685 err = got_error_from_errno("fclose");
7686 free(path);
7687 if (commit)
7688 got_object_commit_close(commit);
7689 return err;
7692 void
7693 histedit_free_list(struct got_histedit_list *histedit_cmds)
7695 struct got_histedit_list_entry *hle;
7697 while ((hle = TAILQ_FIRST(histedit_cmds))) {
7698 TAILQ_REMOVE(histedit_cmds, hle, entry);
7699 free(hle);
7703 static const struct got_error *
7704 histedit_load_list(struct got_histedit_list *histedit_cmds,
7705 const char *path, struct got_repository *repo)
7707 const struct got_error *err = NULL;
7708 FILE *f = NULL;
7710 f = fopen(path, "r");
7711 if (f == NULL) {
7712 err = got_error_from_errno2("fopen", path);
7713 goto done;
7716 err = histedit_parse_list(histedit_cmds, f, repo);
7717 done:
7718 if (f && fclose(f) != 0 && err == NULL)
7719 err = got_error_from_errno("fclose");
7720 return err;
7723 static const struct got_error *
7724 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
7725 const struct got_error *edit_err, struct got_object_id_queue *commits,
7726 const char *path, const char *branch_name, struct got_repository *repo)
7728 const struct got_error *err = NULL, *prev_err = edit_err;
7729 int resp = ' ';
7731 while (resp != 'c' && resp != 'r' && resp != 'a') {
7732 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
7733 "or (a)bort: ", getprogname(), prev_err->msg);
7734 resp = getchar();
7735 if (resp == '\n')
7736 resp = getchar();
7737 if (resp == 'c') {
7738 histedit_free_list(histedit_cmds);
7739 err = histedit_run_editor(histedit_cmds, path, commits,
7740 repo);
7741 if (err) {
7742 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7743 err->code != GOT_ERR_HISTEDIT_CMD)
7744 break;
7745 prev_err = err;
7746 resp = ' ';
7747 continue;
7749 break;
7750 } else if (resp == 'r') {
7751 histedit_free_list(histedit_cmds);
7752 err = histedit_edit_script(histedit_cmds,
7753 commits, branch_name, 0, repo);
7754 if (err) {
7755 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7756 err->code != GOT_ERR_HISTEDIT_CMD)
7757 break;
7758 prev_err = err;
7759 resp = ' ';
7760 continue;
7762 break;
7763 } else if (resp == 'a') {
7764 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
7765 break;
7766 } else
7767 printf("invalid response '%c'\n", resp);
7770 return err;
7773 static const struct got_error *
7774 histedit_complete(struct got_worktree *worktree,
7775 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
7776 struct got_reference *branch, struct got_repository *repo)
7778 printf("Switching work tree to %s\n",
7779 got_ref_get_symref_target(branch));
7780 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
7781 branch, repo);
7784 static const struct got_error *
7785 show_histedit_progress(struct got_commit_object *commit,
7786 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
7788 const struct got_error *err;
7789 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7791 err = got_object_id_str(&old_id_str, hle->commit_id);
7792 if (err)
7793 goto done;
7795 if (new_id) {
7796 err = got_object_id_str(&new_id_str, new_id);
7797 if (err)
7798 goto done;
7801 old_id_str[12] = '\0';
7802 if (new_id_str)
7803 new_id_str[12] = '\0';
7805 if (hle->logmsg) {
7806 logmsg = strdup(hle->logmsg);
7807 if (logmsg == NULL) {
7808 err = got_error_from_errno("strdup");
7809 goto done;
7811 trim_logmsg(logmsg, 42);
7812 } else {
7813 err = get_short_logmsg(&logmsg, 42, commit);
7814 if (err)
7815 goto done;
7818 switch (hle->cmd->code) {
7819 case GOT_HISTEDIT_PICK:
7820 case GOT_HISTEDIT_EDIT:
7821 printf("%s -> %s: %s\n", old_id_str,
7822 new_id_str ? new_id_str : "no-op change", logmsg);
7823 break;
7824 case GOT_HISTEDIT_DROP:
7825 case GOT_HISTEDIT_FOLD:
7826 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
7827 logmsg);
7828 break;
7829 default:
7830 break;
7832 done:
7833 free(old_id_str);
7834 free(new_id_str);
7835 return err;
7838 static const struct got_error *
7839 histedit_commit(struct got_pathlist_head *merged_paths,
7840 struct got_worktree *worktree, struct got_fileindex *fileindex,
7841 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
7842 struct got_repository *repo)
7844 const struct got_error *err;
7845 struct got_commit_object *commit;
7846 struct got_object_id *new_commit_id;
7848 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
7849 && hle->logmsg == NULL) {
7850 err = histedit_edit_logmsg(hle, repo);
7851 if (err)
7852 return err;
7855 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7856 if (err)
7857 return err;
7859 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
7860 worktree, fileindex, tmp_branch, commit, hle->commit_id,
7861 hle->logmsg, repo);
7862 if (err) {
7863 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
7864 goto done;
7865 err = show_histedit_progress(commit, hle, NULL);
7866 } else {
7867 err = show_histedit_progress(commit, hle, new_commit_id);
7868 free(new_commit_id);
7870 done:
7871 got_object_commit_close(commit);
7872 return err;
7875 static const struct got_error *
7876 histedit_skip_commit(struct got_histedit_list_entry *hle,
7877 struct got_worktree *worktree, struct got_repository *repo)
7879 const struct got_error *error;
7880 struct got_commit_object *commit;
7882 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
7883 repo);
7884 if (error)
7885 return error;
7887 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
7888 if (error)
7889 return error;
7891 error = show_histedit_progress(commit, hle, NULL);
7892 got_object_commit_close(commit);
7893 return error;
7896 static const struct got_error *
7897 check_local_changes(void *arg, unsigned char status,
7898 unsigned char staged_status, const char *path,
7899 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
7900 struct got_object_id *commit_id, int dirfd, const char *de_name)
7902 int *have_local_changes = arg;
7904 switch (status) {
7905 case GOT_STATUS_ADD:
7906 case GOT_STATUS_DELETE:
7907 case GOT_STATUS_MODIFY:
7908 case GOT_STATUS_CONFLICT:
7909 *have_local_changes = 1;
7910 return got_error(GOT_ERR_CANCELLED);
7911 default:
7912 break;
7915 switch (staged_status) {
7916 case GOT_STATUS_ADD:
7917 case GOT_STATUS_DELETE:
7918 case GOT_STATUS_MODIFY:
7919 *have_local_changes = 1;
7920 return got_error(GOT_ERR_CANCELLED);
7921 default:
7922 break;
7925 return NULL;
7928 static const struct got_error *
7929 cmd_histedit(int argc, char *argv[])
7931 const struct got_error *error = NULL;
7932 struct got_worktree *worktree = NULL;
7933 struct got_fileindex *fileindex = NULL;
7934 struct got_repository *repo = NULL;
7935 char *cwd = NULL;
7936 struct got_reference *branch = NULL;
7937 struct got_reference *tmp_branch = NULL;
7938 struct got_object_id *resume_commit_id = NULL;
7939 struct got_object_id *base_commit_id = NULL;
7940 struct got_object_id *head_commit_id = NULL;
7941 struct got_commit_object *commit = NULL;
7942 int ch, rebase_in_progress = 0, did_something;
7943 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
7944 int edit_logmsg_only = 0;
7945 const char *edit_script_path = NULL;
7946 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7947 struct got_object_id_queue commits;
7948 struct got_pathlist_head merged_paths;
7949 const struct got_object_id_queue *parent_ids;
7950 struct got_object_qid *pid;
7951 struct got_histedit_list histedit_cmds;
7952 struct got_histedit_list_entry *hle;
7954 SIMPLEQ_INIT(&commits);
7955 TAILQ_INIT(&histedit_cmds);
7956 TAILQ_INIT(&merged_paths);
7958 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
7959 switch (ch) {
7960 case 'a':
7961 abort_edit = 1;
7962 break;
7963 case 'c':
7964 continue_edit = 1;
7965 break;
7966 case 'F':
7967 edit_script_path = optarg;
7968 break;
7969 case 'm':
7970 edit_logmsg_only = 1;
7971 break;
7972 default:
7973 usage_histedit();
7974 /* NOTREACHED */
7978 argc -= optind;
7979 argv += optind;
7981 #ifndef PROFILE
7982 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7983 "unveil", NULL) == -1)
7984 err(1, "pledge");
7985 #endif
7986 if (abort_edit && continue_edit)
7987 errx(1, "histedit's -a and -c options are mutually exclusive");
7988 if (edit_script_path && edit_logmsg_only)
7989 errx(1, "histedit's -F and -m options are mutually exclusive");
7990 if (abort_edit && edit_logmsg_only)
7991 errx(1, "histedit's -a and -m options are mutually exclusive");
7992 if (continue_edit && edit_logmsg_only)
7993 errx(1, "histedit's -c and -m options are mutually exclusive");
7994 if (argc != 0)
7995 usage_histedit();
7998 * This command cannot apply unveil(2) in all cases because the
7999 * user may choose to run an editor to edit the histedit script
8000 * and to edit individual commit log messages.
8001 * unveil(2) traverses exec(2); if an editor is used we have to
8002 * apply unveil after edit script and log messages have been written.
8003 * XXX TODO: Make use of unveil(2) where possible.
8006 cwd = getcwd(NULL, 0);
8007 if (cwd == NULL) {
8008 error = got_error_from_errno("getcwd");
8009 goto done;
8011 error = got_worktree_open(&worktree, cwd);
8012 if (error) {
8013 if (error->code == GOT_ERR_NOT_WORKTREE)
8014 error = wrap_not_worktree_error(error, "histedit", cwd);
8015 goto done;
8018 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8019 NULL);
8020 if (error != NULL)
8021 goto done;
8023 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8024 if (error)
8025 goto done;
8026 if (rebase_in_progress) {
8027 error = got_error(GOT_ERR_REBASING);
8028 goto done;
8031 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8032 if (error)
8033 goto done;
8035 if (edit_in_progress && edit_logmsg_only) {
8036 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8037 "histedit operation is in progress in this "
8038 "work tree and must be continued or aborted "
8039 "before the -m option can be used");
8040 goto done;
8043 if (edit_in_progress && abort_edit) {
8044 error = got_worktree_histedit_continue(&resume_commit_id,
8045 &tmp_branch, &branch, &base_commit_id, &fileindex,
8046 worktree, repo);
8047 if (error)
8048 goto done;
8049 printf("Switching work tree to %s\n",
8050 got_ref_get_symref_target(branch));
8051 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8052 branch, base_commit_id, update_progress, &did_something);
8053 if (error)
8054 goto done;
8055 printf("Histedit of %s aborted\n",
8056 got_ref_get_symref_target(branch));
8057 goto done; /* nothing else to do */
8058 } else if (abort_edit) {
8059 error = got_error(GOT_ERR_NOT_HISTEDIT);
8060 goto done;
8063 if (continue_edit) {
8064 char *path;
8066 if (!edit_in_progress) {
8067 error = got_error(GOT_ERR_NOT_HISTEDIT);
8068 goto done;
8071 error = got_worktree_get_histedit_script_path(&path, worktree);
8072 if (error)
8073 goto done;
8075 error = histedit_load_list(&histedit_cmds, path, repo);
8076 free(path);
8077 if (error)
8078 goto done;
8080 error = got_worktree_histedit_continue(&resume_commit_id,
8081 &tmp_branch, &branch, &base_commit_id, &fileindex,
8082 worktree, repo);
8083 if (error)
8084 goto done;
8086 error = got_ref_resolve(&head_commit_id, repo, branch);
8087 if (error)
8088 goto done;
8090 error = got_object_open_as_commit(&commit, repo,
8091 head_commit_id);
8092 if (error)
8093 goto done;
8094 parent_ids = got_object_commit_get_parent_ids(commit);
8095 pid = SIMPLEQ_FIRST(parent_ids);
8096 if (pid == NULL) {
8097 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8098 goto done;
8100 error = collect_commits(&commits, head_commit_id, pid->id,
8101 base_commit_id, got_worktree_get_path_prefix(worktree),
8102 GOT_ERR_HISTEDIT_PATH, repo);
8103 got_object_commit_close(commit);
8104 commit = NULL;
8105 if (error)
8106 goto done;
8107 } else {
8108 if (edit_in_progress) {
8109 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8110 goto done;
8113 error = got_ref_open(&branch, repo,
8114 got_worktree_get_head_ref_name(worktree), 0);
8115 if (error != NULL)
8116 goto done;
8118 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8119 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8120 "will not edit commit history of a branch outside "
8121 "the \"refs/heads/\" reference namespace");
8122 goto done;
8125 error = got_ref_resolve(&head_commit_id, repo, branch);
8126 got_ref_close(branch);
8127 branch = NULL;
8128 if (error)
8129 goto done;
8131 error = got_object_open_as_commit(&commit, repo,
8132 head_commit_id);
8133 if (error)
8134 goto done;
8135 parent_ids = got_object_commit_get_parent_ids(commit);
8136 pid = SIMPLEQ_FIRST(parent_ids);
8137 if (pid == NULL) {
8138 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8139 goto done;
8141 error = collect_commits(&commits, head_commit_id, pid->id,
8142 got_worktree_get_base_commit_id(worktree),
8143 got_worktree_get_path_prefix(worktree),
8144 GOT_ERR_HISTEDIT_PATH, repo);
8145 got_object_commit_close(commit);
8146 commit = NULL;
8147 if (error)
8148 goto done;
8150 if (SIMPLEQ_EMPTY(&commits)) {
8151 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8152 goto done;
8155 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8156 &base_commit_id, &fileindex, worktree, repo);
8157 if (error)
8158 goto done;
8160 if (edit_script_path) {
8161 error = histedit_load_list(&histedit_cmds,
8162 edit_script_path, repo);
8163 if (error) {
8164 got_worktree_histedit_abort(worktree, fileindex,
8165 repo, branch, base_commit_id,
8166 update_progress, &did_something);
8167 goto done;
8169 } else {
8170 const char *branch_name;
8171 branch_name = got_ref_get_symref_target(branch);
8172 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8173 branch_name += 11;
8174 error = histedit_edit_script(&histedit_cmds, &commits,
8175 branch_name, edit_logmsg_only, repo);
8176 if (error) {
8177 got_worktree_histedit_abort(worktree, fileindex,
8178 repo, branch, base_commit_id,
8179 update_progress, &did_something);
8180 goto done;
8185 error = histedit_save_list(&histedit_cmds, worktree,
8186 repo);
8187 if (error) {
8188 got_worktree_histedit_abort(worktree, fileindex,
8189 repo, branch, base_commit_id,
8190 update_progress, &did_something);
8191 goto done;
8196 error = histedit_check_script(&histedit_cmds, &commits, repo);
8197 if (error)
8198 goto done;
8200 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8201 if (resume_commit_id) {
8202 if (got_object_id_cmp(hle->commit_id,
8203 resume_commit_id) != 0)
8204 continue;
8206 resume_commit_id = NULL;
8207 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8208 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8209 error = histedit_skip_commit(hle, worktree,
8210 repo);
8211 if (error)
8212 goto done;
8213 } else {
8214 struct got_pathlist_head paths;
8215 int have_changes = 0;
8217 TAILQ_INIT(&paths);
8218 error = got_pathlist_append(&paths, "", NULL);
8219 if (error)
8220 goto done;
8221 error = got_worktree_status(worktree, &paths,
8222 repo, check_local_changes, &have_changes,
8223 check_cancelled, NULL);
8224 got_pathlist_free(&paths);
8225 if (error) {
8226 if (error->code != GOT_ERR_CANCELLED)
8227 goto done;
8228 if (sigint_received || sigpipe_received)
8229 goto done;
8231 if (have_changes) {
8232 error = histedit_commit(NULL, worktree,
8233 fileindex, tmp_branch, hle, repo);
8234 if (error)
8235 goto done;
8236 } else {
8237 error = got_object_open_as_commit(
8238 &commit, repo, hle->commit_id);
8239 if (error)
8240 goto done;
8241 error = show_histedit_progress(commit,
8242 hle, NULL);
8243 got_object_commit_close(commit);
8244 commit = NULL;
8245 if (error)
8246 goto done;
8249 continue;
8252 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8253 error = histedit_skip_commit(hle, worktree, repo);
8254 if (error)
8255 goto done;
8256 continue;
8259 error = got_object_open_as_commit(&commit, repo,
8260 hle->commit_id);
8261 if (error)
8262 goto done;
8263 parent_ids = got_object_commit_get_parent_ids(commit);
8264 pid = SIMPLEQ_FIRST(parent_ids);
8266 error = got_worktree_histedit_merge_files(&merged_paths,
8267 worktree, fileindex, pid->id, hle->commit_id, repo,
8268 rebase_progress, &rebase_status, check_cancelled, NULL);
8269 if (error)
8270 goto done;
8271 got_object_commit_close(commit);
8272 commit = NULL;
8274 if (rebase_status == GOT_STATUS_CONFLICT) {
8275 error = show_rebase_merge_conflict(hle->commit_id,
8276 repo);
8277 if (error)
8278 goto done;
8279 got_worktree_rebase_pathlist_free(&merged_paths);
8280 break;
8283 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8284 char *id_str;
8285 error = got_object_id_str(&id_str, hle->commit_id);
8286 if (error)
8287 goto done;
8288 printf("Stopping histedit for amending commit %s\n",
8289 id_str);
8290 free(id_str);
8291 got_worktree_rebase_pathlist_free(&merged_paths);
8292 error = got_worktree_histedit_postpone(worktree,
8293 fileindex);
8294 goto done;
8297 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8298 error = histedit_skip_commit(hle, worktree, repo);
8299 if (error)
8300 goto done;
8301 continue;
8304 error = histedit_commit(&merged_paths, worktree, fileindex,
8305 tmp_branch, hle, repo);
8306 got_worktree_rebase_pathlist_free(&merged_paths);
8307 if (error)
8308 goto done;
8311 if (rebase_status == GOT_STATUS_CONFLICT) {
8312 error = got_worktree_histedit_postpone(worktree, fileindex);
8313 if (error)
8314 goto done;
8315 error = got_error_msg(GOT_ERR_CONFLICTS,
8316 "conflicts must be resolved before histedit can continue");
8317 } else
8318 error = histedit_complete(worktree, fileindex, tmp_branch,
8319 branch, repo);
8320 done:
8321 got_object_id_queue_free(&commits);
8322 histedit_free_list(&histedit_cmds);
8323 free(head_commit_id);
8324 free(base_commit_id);
8325 free(resume_commit_id);
8326 if (commit)
8327 got_object_commit_close(commit);
8328 if (branch)
8329 got_ref_close(branch);
8330 if (tmp_branch)
8331 got_ref_close(tmp_branch);
8332 if (worktree)
8333 got_worktree_close(worktree);
8334 if (repo)
8335 got_repo_close(repo);
8336 return error;
8339 __dead static void
8340 usage_integrate(void)
8342 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
8343 exit(1);
8346 static const struct got_error *
8347 cmd_integrate(int argc, char *argv[])
8349 const struct got_error *error = NULL;
8350 struct got_repository *repo = NULL;
8351 struct got_worktree *worktree = NULL;
8352 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
8353 const char *branch_arg = NULL;
8354 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
8355 struct got_fileindex *fileindex = NULL;
8356 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
8357 int ch, did_something = 0;
8359 while ((ch = getopt(argc, argv, "")) != -1) {
8360 switch (ch) {
8361 default:
8362 usage_integrate();
8363 /* NOTREACHED */
8367 argc -= optind;
8368 argv += optind;
8370 if (argc != 1)
8371 usage_integrate();
8372 branch_arg = argv[0];
8374 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8375 "unveil", NULL) == -1)
8376 err(1, "pledge");
8378 cwd = getcwd(NULL, 0);
8379 if (cwd == NULL) {
8380 error = got_error_from_errno("getcwd");
8381 goto done;
8384 error = got_worktree_open(&worktree, cwd);
8385 if (error) {
8386 if (error->code == GOT_ERR_NOT_WORKTREE)
8387 error = wrap_not_worktree_error(error, "integrate",
8388 cwd);
8389 goto done;
8392 error = check_rebase_or_histedit_in_progress(worktree);
8393 if (error)
8394 goto done;
8396 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8397 NULL);
8398 if (error != NULL)
8399 goto done;
8401 error = apply_unveil(got_repo_get_path(repo), 0,
8402 got_worktree_get_root_path(worktree));
8403 if (error)
8404 goto done;
8406 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
8407 error = got_error_from_errno("asprintf");
8408 goto done;
8411 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
8412 &base_branch_ref, worktree, refname, repo);
8413 if (error)
8414 goto done;
8416 refname = strdup(got_ref_get_name(branch_ref));
8417 if (refname == NULL) {
8418 error = got_error_from_errno("strdup");
8419 got_worktree_integrate_abort(worktree, fileindex, repo,
8420 branch_ref, base_branch_ref);
8421 goto done;
8423 base_refname = strdup(got_ref_get_name(base_branch_ref));
8424 if (base_refname == NULL) {
8425 error = got_error_from_errno("strdup");
8426 got_worktree_integrate_abort(worktree, fileindex, repo,
8427 branch_ref, base_branch_ref);
8428 goto done;
8431 error = got_ref_resolve(&commit_id, repo, branch_ref);
8432 if (error)
8433 goto done;
8435 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
8436 if (error)
8437 goto done;
8439 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
8440 error = got_error_msg(GOT_ERR_SAME_BRANCH,
8441 "specified branch has already been integrated");
8442 got_worktree_integrate_abort(worktree, fileindex, repo,
8443 branch_ref, base_branch_ref);
8444 goto done;
8447 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
8448 if (error) {
8449 if (error->code == GOT_ERR_ANCESTRY)
8450 error = got_error(GOT_ERR_REBASE_REQUIRED);
8451 got_worktree_integrate_abort(worktree, fileindex, repo,
8452 branch_ref, base_branch_ref);
8453 goto done;
8456 error = got_worktree_integrate_continue(worktree, fileindex, repo,
8457 branch_ref, base_branch_ref, update_progress, &did_something,
8458 check_cancelled, NULL);
8459 if (error)
8460 goto done;
8462 printf("Integrated %s into %s\n", refname, base_refname);
8463 done:
8464 if (repo)
8465 got_repo_close(repo);
8466 if (worktree)
8467 got_worktree_close(worktree);
8468 free(cwd);
8469 free(base_commit_id);
8470 free(commit_id);
8471 free(refname);
8472 free(base_refname);
8473 return error;
8476 __dead static void
8477 usage_stage(void)
8479 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
8480 "[file-path ...]\n",
8481 getprogname());
8482 exit(1);
8485 static const struct got_error *
8486 print_stage(void *arg, unsigned char status, unsigned char staged_status,
8487 const char *path, struct got_object_id *blob_id,
8488 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
8489 int dirfd, const char *de_name)
8491 const struct got_error *err = NULL;
8492 char *id_str = NULL;
8494 if (staged_status != GOT_STATUS_ADD &&
8495 staged_status != GOT_STATUS_MODIFY &&
8496 staged_status != GOT_STATUS_DELETE)
8497 return NULL;
8499 if (staged_status == GOT_STATUS_ADD ||
8500 staged_status == GOT_STATUS_MODIFY)
8501 err = got_object_id_str(&id_str, staged_blob_id);
8502 else
8503 err = got_object_id_str(&id_str, blob_id);
8504 if (err)
8505 return err;
8507 printf("%s %c %s\n", id_str, staged_status, path);
8508 free(id_str);
8509 return NULL;
8512 static const struct got_error *
8513 cmd_stage(int argc, char *argv[])
8515 const struct got_error *error = NULL;
8516 struct got_repository *repo = NULL;
8517 struct got_worktree *worktree = NULL;
8518 char *cwd = NULL;
8519 struct got_pathlist_head paths;
8520 struct got_pathlist_entry *pe;
8521 int ch, list_stage = 0, pflag = 0;
8522 FILE *patch_script_file = NULL;
8523 const char *patch_script_path = NULL;
8524 struct choose_patch_arg cpa;
8526 TAILQ_INIT(&paths);
8528 while ((ch = getopt(argc, argv, "lpF:")) != -1) {
8529 switch (ch) {
8530 case 'l':
8531 list_stage = 1;
8532 break;
8533 case 'p':
8534 pflag = 1;
8535 break;
8536 case 'F':
8537 patch_script_path = optarg;
8538 break;
8539 default:
8540 usage_stage();
8541 /* NOTREACHED */
8545 argc -= optind;
8546 argv += optind;
8548 #ifndef PROFILE
8549 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8550 "unveil", NULL) == -1)
8551 err(1, "pledge");
8552 #endif
8553 if (list_stage && (pflag || patch_script_path))
8554 errx(1, "-l option cannot be used with other options");
8555 if (patch_script_path && !pflag)
8556 errx(1, "-F option can only be used together with -p option");
8558 cwd = getcwd(NULL, 0);
8559 if (cwd == NULL) {
8560 error = got_error_from_errno("getcwd");
8561 goto done;
8564 error = got_worktree_open(&worktree, cwd);
8565 if (error) {
8566 if (error->code == GOT_ERR_NOT_WORKTREE)
8567 error = wrap_not_worktree_error(error, "stage", cwd);
8568 goto done;
8571 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8572 NULL);
8573 if (error != NULL)
8574 goto done;
8576 if (patch_script_path) {
8577 patch_script_file = fopen(patch_script_path, "r");
8578 if (patch_script_file == NULL) {
8579 error = got_error_from_errno2("fopen",
8580 patch_script_path);
8581 goto done;
8584 error = apply_unveil(got_repo_get_path(repo), 0,
8585 got_worktree_get_root_path(worktree));
8586 if (error)
8587 goto done;
8589 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8590 if (error)
8591 goto done;
8593 if (list_stage)
8594 error = got_worktree_status(worktree, &paths, repo,
8595 print_stage, NULL, check_cancelled, NULL);
8596 else {
8597 cpa.patch_script_file = patch_script_file;
8598 cpa.action = "stage";
8599 error = got_worktree_stage(worktree, &paths,
8600 pflag ? NULL : print_status, NULL,
8601 pflag ? choose_patch : NULL, &cpa, repo);
8603 done:
8604 if (patch_script_file && fclose(patch_script_file) == EOF &&
8605 error == NULL)
8606 error = got_error_from_errno2("fclose", patch_script_path);
8607 if (repo)
8608 got_repo_close(repo);
8609 if (worktree)
8610 got_worktree_close(worktree);
8611 TAILQ_FOREACH(pe, &paths, entry)
8612 free((char *)pe->path);
8613 got_pathlist_free(&paths);
8614 free(cwd);
8615 return error;
8618 __dead static void
8619 usage_unstage(void)
8621 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
8622 "[file-path ...]\n",
8623 getprogname());
8624 exit(1);
8628 static const struct got_error *
8629 cmd_unstage(int argc, char *argv[])
8631 const struct got_error *error = NULL;
8632 struct got_repository *repo = NULL;
8633 struct got_worktree *worktree = NULL;
8634 char *cwd = NULL;
8635 struct got_pathlist_head paths;
8636 struct got_pathlist_entry *pe;
8637 int ch, did_something = 0, pflag = 0;
8638 FILE *patch_script_file = NULL;
8639 const char *patch_script_path = NULL;
8640 struct choose_patch_arg cpa;
8642 TAILQ_INIT(&paths);
8644 while ((ch = getopt(argc, argv, "pF:")) != -1) {
8645 switch (ch) {
8646 case 'p':
8647 pflag = 1;
8648 break;
8649 case 'F':
8650 patch_script_path = optarg;
8651 break;
8652 default:
8653 usage_unstage();
8654 /* NOTREACHED */
8658 argc -= optind;
8659 argv += optind;
8661 #ifndef PROFILE
8662 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8663 "unveil", NULL) == -1)
8664 err(1, "pledge");
8665 #endif
8666 if (patch_script_path && !pflag)
8667 errx(1, "-F option can only be used together with -p option");
8669 cwd = getcwd(NULL, 0);
8670 if (cwd == NULL) {
8671 error = got_error_from_errno("getcwd");
8672 goto done;
8675 error = got_worktree_open(&worktree, cwd);
8676 if (error) {
8677 if (error->code == GOT_ERR_NOT_WORKTREE)
8678 error = wrap_not_worktree_error(error, "unstage", cwd);
8679 goto done;
8682 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8683 NULL);
8684 if (error != NULL)
8685 goto done;
8687 if (patch_script_path) {
8688 patch_script_file = fopen(patch_script_path, "r");
8689 if (patch_script_file == NULL) {
8690 error = got_error_from_errno2("fopen",
8691 patch_script_path);
8692 goto done;
8696 error = apply_unveil(got_repo_get_path(repo), 0,
8697 got_worktree_get_root_path(worktree));
8698 if (error)
8699 goto done;
8701 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8702 if (error)
8703 goto done;
8705 cpa.patch_script_file = patch_script_file;
8706 cpa.action = "unstage";
8707 error = got_worktree_unstage(worktree, &paths, update_progress,
8708 &did_something, pflag ? choose_patch : NULL, &cpa, repo);
8709 done:
8710 if (patch_script_file && fclose(patch_script_file) == EOF &&
8711 error == NULL)
8712 error = got_error_from_errno2("fclose", patch_script_path);
8713 if (repo)
8714 got_repo_close(repo);
8715 if (worktree)
8716 got_worktree_close(worktree);
8717 TAILQ_FOREACH(pe, &paths, entry)
8718 free((char *)pe->path);
8719 got_pathlist_free(&paths);
8720 free(cwd);
8721 return error;
8724 __dead static void
8725 usage_cat(void)
8727 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
8728 "arg1 [arg2 ...]\n", getprogname());
8729 exit(1);
8732 static const struct got_error *
8733 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8735 const struct got_error *err;
8736 struct got_blob_object *blob;
8738 err = got_object_open_as_blob(&blob, repo, id, 8192);
8739 if (err)
8740 return err;
8742 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
8743 got_object_blob_close(blob);
8744 return err;
8747 static const struct got_error *
8748 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8750 const struct got_error *err;
8751 struct got_tree_object *tree;
8752 int nentries, i;
8754 err = got_object_open_as_tree(&tree, repo, id);
8755 if (err)
8756 return err;
8758 nentries = got_object_tree_get_nentries(tree);
8759 for (i = 0; i < nentries; i++) {
8760 struct got_tree_entry *te;
8761 char *id_str;
8762 if (sigint_received || sigpipe_received)
8763 break;
8764 te = got_object_tree_get_entry(tree, i);
8765 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
8766 if (err)
8767 break;
8768 fprintf(outfile, "%s %.7o %s\n", id_str,
8769 got_tree_entry_get_mode(te),
8770 got_tree_entry_get_name(te));
8771 free(id_str);
8774 got_object_tree_close(tree);
8775 return err;
8778 static const struct got_error *
8779 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8781 const struct got_error *err;
8782 struct got_commit_object *commit;
8783 const struct got_object_id_queue *parent_ids;
8784 struct got_object_qid *pid;
8785 char *id_str = NULL;
8786 const char *logmsg = NULL;
8788 err = got_object_open_as_commit(&commit, repo, id);
8789 if (err)
8790 return err;
8792 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
8793 if (err)
8794 goto done;
8796 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
8797 parent_ids = got_object_commit_get_parent_ids(commit);
8798 fprintf(outfile, "numparents %d\n",
8799 got_object_commit_get_nparents(commit));
8800 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
8801 char *pid_str;
8802 err = got_object_id_str(&pid_str, pid->id);
8803 if (err)
8804 goto done;
8805 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
8806 free(pid_str);
8808 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
8809 got_object_commit_get_author(commit),
8810 got_object_commit_get_author_time(commit));
8812 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
8813 got_object_commit_get_author(commit),
8814 got_object_commit_get_committer_time(commit));
8816 logmsg = got_object_commit_get_logmsg_raw(commit);
8817 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
8818 fprintf(outfile, "%s", logmsg);
8819 done:
8820 free(id_str);
8821 got_object_commit_close(commit);
8822 return err;
8825 static const struct got_error *
8826 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8828 const struct got_error *err;
8829 struct got_tag_object *tag;
8830 char *id_str = NULL;
8831 const char *tagmsg = NULL;
8833 err = got_object_open_as_tag(&tag, repo, id);
8834 if (err)
8835 return err;
8837 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
8838 if (err)
8839 goto done;
8841 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
8843 switch (got_object_tag_get_object_type(tag)) {
8844 case GOT_OBJ_TYPE_BLOB:
8845 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8846 GOT_OBJ_LABEL_BLOB);
8847 break;
8848 case GOT_OBJ_TYPE_TREE:
8849 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8850 GOT_OBJ_LABEL_TREE);
8851 break;
8852 case GOT_OBJ_TYPE_COMMIT:
8853 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8854 GOT_OBJ_LABEL_COMMIT);
8855 break;
8856 case GOT_OBJ_TYPE_TAG:
8857 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8858 GOT_OBJ_LABEL_TAG);
8859 break;
8860 default:
8861 break;
8864 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
8865 got_object_tag_get_name(tag));
8867 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
8868 got_object_tag_get_tagger(tag),
8869 got_object_tag_get_tagger_time(tag));
8871 tagmsg = got_object_tag_get_message(tag);
8872 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
8873 fprintf(outfile, "%s", tagmsg);
8874 done:
8875 free(id_str);
8876 got_object_tag_close(tag);
8877 return err;
8880 static const struct got_error *
8881 cmd_cat(int argc, char *argv[])
8883 const struct got_error *error;
8884 struct got_repository *repo = NULL;
8885 struct got_worktree *worktree = NULL;
8886 char *cwd = NULL, *repo_path = NULL, *label = NULL;
8887 const char *commit_id_str = NULL;
8888 struct got_object_id *id = NULL, *commit_id = NULL;
8889 int ch, obj_type, i, force_path = 0;
8891 #ifndef PROFILE
8892 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8893 NULL) == -1)
8894 err(1, "pledge");
8895 #endif
8897 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
8898 switch (ch) {
8899 case 'c':
8900 commit_id_str = optarg;
8901 break;
8902 case 'r':
8903 repo_path = realpath(optarg, NULL);
8904 if (repo_path == NULL)
8905 return got_error_from_errno2("realpath",
8906 optarg);
8907 got_path_strip_trailing_slashes(repo_path);
8908 break;
8909 case 'P':
8910 force_path = 1;
8911 break;
8912 default:
8913 usage_cat();
8914 /* NOTREACHED */
8918 argc -= optind;
8919 argv += optind;
8921 cwd = getcwd(NULL, 0);
8922 if (cwd == NULL) {
8923 error = got_error_from_errno("getcwd");
8924 goto done;
8926 error = got_worktree_open(&worktree, cwd);
8927 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8928 goto done;
8929 if (worktree) {
8930 if (repo_path == NULL) {
8931 repo_path = strdup(
8932 got_worktree_get_repo_path(worktree));
8933 if (repo_path == NULL) {
8934 error = got_error_from_errno("strdup");
8935 goto done;
8940 if (repo_path == NULL) {
8941 repo_path = getcwd(NULL, 0);
8942 if (repo_path == NULL)
8943 return got_error_from_errno("getcwd");
8946 error = got_repo_open(&repo, repo_path, NULL);
8947 free(repo_path);
8948 if (error != NULL)
8949 goto done;
8951 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
8952 if (error)
8953 goto done;
8955 if (commit_id_str == NULL)
8956 commit_id_str = GOT_REF_HEAD;
8957 error = got_repo_match_object_id(&commit_id, NULL,
8958 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
8959 if (error)
8960 goto done;
8962 for (i = 0; i < argc; i++) {
8963 if (force_path) {
8964 error = got_object_id_by_path(&id, repo, commit_id,
8965 argv[i]);
8966 if (error)
8967 break;
8968 } else {
8969 error = got_repo_match_object_id(&id, &label, argv[i],
8970 GOT_OBJ_TYPE_ANY, 0, repo);
8971 if (error) {
8972 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
8973 error->code != GOT_ERR_NOT_REF)
8974 break;
8975 error = got_object_id_by_path(&id, repo,
8976 commit_id, argv[i]);
8977 if (error)
8978 break;
8982 error = got_object_get_type(&obj_type, repo, id);
8983 if (error)
8984 break;
8986 switch (obj_type) {
8987 case GOT_OBJ_TYPE_BLOB:
8988 error = cat_blob(id, repo, stdout);
8989 break;
8990 case GOT_OBJ_TYPE_TREE:
8991 error = cat_tree(id, repo, stdout);
8992 break;
8993 case GOT_OBJ_TYPE_COMMIT:
8994 error = cat_commit(id, repo, stdout);
8995 break;
8996 case GOT_OBJ_TYPE_TAG:
8997 error = cat_tag(id, repo, stdout);
8998 break;
8999 default:
9000 error = got_error(GOT_ERR_OBJ_TYPE);
9001 break;
9003 if (error)
9004 break;
9005 free(label);
9006 label = NULL;
9007 free(id);
9008 id = NULL;
9010 done:
9011 free(label);
9012 free(id);
9013 free(commit_id);
9014 if (worktree)
9015 got_worktree_close(worktree);
9016 if (repo) {
9017 const struct got_error *repo_error;
9018 repo_error = got_repo_close(repo);
9019 if (error == NULL)
9020 error = repo_error;
9022 return error;