Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/param.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
41 #include <util.h>
43 #include "got_version.h"
44 #include "got_error.h"
45 #include "got_object.h"
46 #include "got_reference.h"
47 #include "got_repository.h"
48 #include "got_path.h"
49 #include "got_cancel.h"
50 #include "got_worktree.h"
51 #include "got_diff.h"
52 #include "got_commit_graph.h"
53 #include "got_fetch.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_opentemp.h"
58 #ifndef nitems
59 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
60 #endif
62 static volatile sig_atomic_t sigint_received;
63 static volatile sig_atomic_t sigpipe_received;
65 static void
66 catch_sigint(int signo)
67 {
68 sigint_received = 1;
69 }
71 static void
72 catch_sigpipe(int signo)
73 {
74 sigpipe_received = 1;
75 }
78 struct got_cmd {
79 const char *cmd_name;
80 const struct got_error *(*cmd_main)(int, char *[]);
81 void (*cmd_usage)(void);
82 const char *cmd_alias;
83 };
85 __dead static void usage(int);
86 __dead static void usage_init(void);
87 __dead static void usage_import(void);
88 __dead static void usage_clone(void);
89 __dead static void usage_fetch(void);
90 __dead static void usage_checkout(void);
91 __dead static void usage_update(void);
92 __dead static void usage_log(void);
93 __dead static void usage_diff(void);
94 __dead static void usage_blame(void);
95 __dead static void usage_tree(void);
96 __dead static void usage_status(void);
97 __dead static void usage_ref(void);
98 __dead static void usage_branch(void);
99 __dead static void usage_tag(void);
100 __dead static void usage_add(void);
101 __dead static void usage_remove(void);
102 __dead static void usage_revert(void);
103 __dead static void usage_commit(void);
104 __dead static void usage_cherrypick(void);
105 __dead static void usage_backout(void);
106 __dead static void usage_rebase(void);
107 __dead static void usage_histedit(void);
108 __dead static void usage_integrate(void);
109 __dead static void usage_stage(void);
110 __dead static void usage_unstage(void);
111 __dead static void usage_cat(void);
113 static const struct got_error* cmd_init(int, char *[]);
114 static const struct got_error* cmd_import(int, char *[]);
115 static const struct got_error* cmd_clone(int, char *[]);
116 static const struct got_error* cmd_fetch(int, char *[]);
117 static const struct got_error* cmd_checkout(int, char *[]);
118 static const struct got_error* cmd_update(int, char *[]);
119 static const struct got_error* cmd_log(int, char *[]);
120 static const struct got_error* cmd_diff(int, char *[]);
121 static const struct got_error* cmd_blame(int, char *[]);
122 static const struct got_error* cmd_tree(int, char *[]);
123 static const struct got_error* cmd_status(int, char *[]);
124 static const struct got_error* cmd_ref(int, char *[]);
125 static const struct got_error* cmd_branch(int, char *[]);
126 static const struct got_error* cmd_tag(int, char *[]);
127 static const struct got_error* cmd_add(int, char *[]);
128 static const struct got_error* cmd_remove(int, char *[]);
129 static const struct got_error* cmd_revert(int, char *[]);
130 static const struct got_error* cmd_commit(int, char *[]);
131 static const struct got_error* cmd_cherrypick(int, char *[]);
132 static const struct got_error* cmd_backout(int, char *[]);
133 static const struct got_error* cmd_rebase(int, char *[]);
134 static const struct got_error* cmd_histedit(int, char *[]);
135 static const struct got_error* cmd_integrate(int, char *[]);
136 static const struct got_error* cmd_stage(int, char *[]);
137 static const struct got_error* cmd_unstage(int, char *[]);
138 static const struct got_error* cmd_cat(int, char *[]);
140 static struct got_cmd got_commands[] = {
141 { "init", cmd_init, usage_init, "in" },
142 { "import", cmd_import, usage_import, "im" },
143 { "clone", cmd_clone, usage_clone, "cl" },
144 { "fetch", cmd_fetch, usage_fetch, "fe" },
145 { "checkout", cmd_checkout, usage_checkout, "co" },
146 { "update", cmd_update, usage_update, "up" },
147 { "log", cmd_log, usage_log, "" },
148 { "diff", cmd_diff, usage_diff, "di" },
149 { "blame", cmd_blame, usage_blame, "bl" },
150 { "tree", cmd_tree, usage_tree, "tr" },
151 { "status", cmd_status, usage_status, "st" },
152 { "ref", cmd_ref, usage_ref, "" },
153 { "branch", cmd_branch, usage_branch, "br" },
154 { "tag", cmd_tag, usage_tag, "" },
155 { "add", cmd_add, usage_add, "" },
156 { "remove", cmd_remove, usage_remove, "rm" },
157 { "revert", cmd_revert, usage_revert, "rv" },
158 { "commit", cmd_commit, usage_commit, "ci" },
159 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
160 { "backout", cmd_backout, usage_backout, "bo" },
161 { "rebase", cmd_rebase, usage_rebase, "rb" },
162 { "histedit", cmd_histedit, usage_histedit, "he" },
163 { "integrate", cmd_integrate, usage_integrate,"ig" },
164 { "stage", cmd_stage, usage_stage, "sg" },
165 { "unstage", cmd_unstage, usage_unstage, "ug" },
166 { "cat", cmd_cat, usage_cat, "" },
167 };
169 static void
170 list_commands(void)
172 int i;
174 fprintf(stderr, "commands:");
175 for (i = 0; i < nitems(got_commands); i++) {
176 struct got_cmd *cmd = &got_commands[i];
177 fprintf(stderr, " %s", cmd->cmd_name);
179 fputc('\n', stderr);
182 int
183 main(int argc, char *argv[])
185 struct got_cmd *cmd;
186 unsigned int i;
187 int ch;
188 int hflag = 0, Vflag = 0;
189 static struct option longopts[] = {
190 { "version", no_argument, NULL, 'V' },
191 { NULL, 0, NULL, 0}
192 };
194 setlocale(LC_CTYPE, "");
196 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
197 switch (ch) {
198 case 'h':
199 hflag = 1;
200 break;
201 case 'V':
202 Vflag = 1;
203 break;
204 default:
205 usage(hflag);
206 /* NOTREACHED */
210 argc -= optind;
211 argv += optind;
212 optind = 0;
214 if (Vflag) {
215 got_version_print_str();
216 return 1;
219 if (argc <= 0)
220 usage(hflag);
222 signal(SIGINT, catch_sigint);
223 signal(SIGPIPE, catch_sigpipe);
225 for (i = 0; i < nitems(got_commands); i++) {
226 const struct got_error *error;
228 cmd = &got_commands[i];
230 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
231 strcmp(cmd->cmd_alias, argv[0]) != 0)
232 continue;
234 if (hflag)
235 got_commands[i].cmd_usage();
237 error = got_commands[i].cmd_main(argc, argv);
238 if (error && error->code != GOT_ERR_CANCELLED &&
239 error->code != GOT_ERR_PRIVSEP_EXIT &&
240 !(sigpipe_received &&
241 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
242 !(sigint_received &&
243 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
244 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
245 return 1;
248 return 0;
251 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
252 list_commands();
253 return 1;
256 __dead static void
257 usage(int hflag)
259 fprintf(stderr, "usage: %s [-h] [-V | --version] command [arg ...]\n",
260 getprogname());
261 if (hflag)
262 list_commands();
263 exit(1);
266 static const struct got_error *
267 get_editor(char **abspath)
269 const struct got_error *err = NULL;
270 const char *editor;
272 *abspath = NULL;
274 editor = getenv("VISUAL");
275 if (editor == NULL)
276 editor = getenv("EDITOR");
278 if (editor) {
279 err = got_path_find_prog(abspath, editor);
280 if (err)
281 return err;
284 if (*abspath == NULL) {
285 *abspath = strdup("/bin/ed");
286 if (*abspath == NULL)
287 return got_error_from_errno("strdup");
290 return NULL;
293 static const struct got_error *
294 apply_unveil(const char *repo_path, int repo_read_only,
295 const char *worktree_path)
297 const struct got_error *err;
299 #ifdef PROFILE
300 if (unveil("gmon.out", "rwc") != 0)
301 return got_error_from_errno2("unveil", "gmon.out");
302 #endif
303 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
304 return got_error_from_errno2("unveil", repo_path);
306 if (worktree_path && unveil(worktree_path, "rwc") != 0)
307 return got_error_from_errno2("unveil", worktree_path);
309 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
310 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
312 err = got_privsep_unveil_exec_helpers();
313 if (err != NULL)
314 return err;
316 if (unveil(NULL, NULL) != 0)
317 return got_error_from_errno("unveil");
319 return NULL;
322 __dead static void
323 usage_init(void)
325 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
326 exit(1);
329 static const struct got_error *
330 cmd_init(int argc, char *argv[])
332 const struct got_error *error = NULL;
333 char *repo_path = NULL;
334 int ch;
336 while ((ch = getopt(argc, argv, "")) != -1) {
337 switch (ch) {
338 default:
339 usage_init();
340 /* NOTREACHED */
344 argc -= optind;
345 argv += optind;
347 #ifndef PROFILE
348 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
349 err(1, "pledge");
350 #endif
351 if (argc != 1)
352 usage_init();
354 repo_path = strdup(argv[0]);
355 if (repo_path == NULL)
356 return got_error_from_errno("strdup");
358 got_path_strip_trailing_slashes(repo_path);
360 error = got_path_mkdir(repo_path);
361 if (error &&
362 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
363 goto done;
365 error = apply_unveil(repo_path, 0, NULL);
366 if (error)
367 goto done;
369 error = got_repo_init(repo_path);
370 done:
371 free(repo_path);
372 return error;
375 __dead static void
376 usage_import(void)
378 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
379 "[-r repository-path] [-I pattern] path\n", getprogname());
380 exit(1);
383 int
384 spawn_editor(const char *editor, const char *file)
386 pid_t pid;
387 sig_t sighup, sigint, sigquit;
388 int st = -1;
390 sighup = signal(SIGHUP, SIG_IGN);
391 sigint = signal(SIGINT, SIG_IGN);
392 sigquit = signal(SIGQUIT, SIG_IGN);
394 switch (pid = fork()) {
395 case -1:
396 goto doneediting;
397 case 0:
398 execl(editor, editor, file, (char *)NULL);
399 _exit(127);
402 while (waitpid(pid, &st, 0) == -1)
403 if (errno != EINTR)
404 break;
406 doneediting:
407 (void)signal(SIGHUP, sighup);
408 (void)signal(SIGINT, sigint);
409 (void)signal(SIGQUIT, sigquit);
411 if (!WIFEXITED(st)) {
412 errno = EINTR;
413 return -1;
416 return WEXITSTATUS(st);
419 static const struct got_error *
420 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
421 const char *initial_content)
423 const struct got_error *err = NULL;
424 char buf[1024];
425 struct stat st, st2;
426 FILE *fp;
427 int content_changed = 0;
428 size_t len;
430 *logmsg = NULL;
432 if (stat(logmsg_path, &st) == -1)
433 return got_error_from_errno2("stat", logmsg_path);
435 if (spawn_editor(editor, logmsg_path) == -1)
436 return got_error_from_errno("failed spawning editor");
438 if (stat(logmsg_path, &st2) == -1)
439 return got_error_from_errno("stat");
441 if (st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
442 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
443 "no changes made to commit message, aborting");
445 *logmsg = malloc(st2.st_size + 1);
446 if (*logmsg == NULL)
447 return got_error_from_errno("malloc");
448 (*logmsg)[0] = '\0';
449 len = 0;
451 fp = fopen(logmsg_path, "r");
452 if (fp == NULL) {
453 err = got_error_from_errno("fopen");
454 goto done;
456 while (fgets(buf, sizeof(buf), fp) != NULL) {
457 if (!content_changed && strcmp(buf, initial_content) != 0)
458 content_changed = 1;
459 if (buf[0] == '#' || (len == 0 && buf[0] == '\n'))
460 continue; /* remove comments and leading empty lines */
461 len = strlcat(*logmsg, buf, st2.st_size);
463 fclose(fp);
465 while (len > 0 && (*logmsg)[len - 1] == '\n') {
466 (*logmsg)[len - 1] = '\0';
467 len--;
470 if (len == 0 || !content_changed)
471 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
472 "commit message cannot be empty, aborting");
473 done:
474 if (err) {
475 free(*logmsg);
476 *logmsg = NULL;
478 return err;
481 static const struct got_error *
482 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
483 const char *path_dir, const char *branch_name)
485 char *initial_content = NULL;
486 const struct got_error *err = NULL;
487 int fd;
489 if (asprintf(&initial_content,
490 "\n# %s to be imported to branch %s\n", path_dir,
491 branch_name) == -1)
492 return got_error_from_errno("asprintf");
494 err = got_opentemp_named_fd(logmsg_path, &fd,
495 GOT_TMPDIR_STR "/got-importmsg");
496 if (err)
497 goto done;
499 dprintf(fd, initial_content);
500 close(fd);
502 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content);
503 done:
504 free(initial_content);
505 return err;
508 static const struct got_error *
509 import_progress(void *arg, const char *path)
511 printf("A %s\n", path);
512 return NULL;
515 static const struct got_error *
516 get_author(char **author, struct got_repository *repo)
518 const struct got_error *err = NULL;
519 const char *got_author, *name, *email;
521 *author = NULL;
523 name = got_repo_get_gitconfig_author_name(repo);
524 email = got_repo_get_gitconfig_author_email(repo);
525 if (name && email) {
526 if (asprintf(author, "%s <%s>", name, email) == -1)
527 return got_error_from_errno("asprintf");
528 return NULL;
531 got_author = getenv("GOT_AUTHOR");
532 if (got_author == NULL) {
533 name = got_repo_get_global_gitconfig_author_name(repo);
534 email = got_repo_get_global_gitconfig_author_email(repo);
535 if (name && email) {
536 if (asprintf(author, "%s <%s>", name, email) == -1)
537 return got_error_from_errno("asprintf");
538 return NULL;
540 /* TODO: Look up user in password database? */
541 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
544 *author = strdup(got_author);
545 if (*author == NULL)
546 return got_error_from_errno("strdup");
548 /*
549 * Really dumb email address check; we're only doing this to
550 * avoid git's object parser breaking on commits we create.
551 */
552 while (*got_author && *got_author != '<')
553 got_author++;
554 if (*got_author != '<') {
555 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
556 goto done;
558 while (*got_author && *got_author != '@')
559 got_author++;
560 if (*got_author != '@') {
561 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
562 goto done;
564 while (*got_author && *got_author != '>')
565 got_author++;
566 if (*got_author != '>')
567 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
568 done:
569 if (err) {
570 free(*author);
571 *author = NULL;
573 return err;
576 static const struct got_error *
577 get_gitconfig_path(char **gitconfig_path)
579 const char *homedir = getenv("HOME");
581 *gitconfig_path = NULL;
582 if (homedir) {
583 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
584 return got_error_from_errno("asprintf");
587 return NULL;
590 static const struct got_error *
591 cmd_import(int argc, char *argv[])
593 const struct got_error *error = NULL;
594 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
595 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
596 const char *branch_name = "main";
597 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
598 struct got_repository *repo = NULL;
599 struct got_reference *branch_ref = NULL, *head_ref = NULL;
600 struct got_object_id *new_commit_id = NULL;
601 int ch;
602 struct got_pathlist_head ignores;
603 struct got_pathlist_entry *pe;
604 int preserve_logmsg = 0;
606 TAILQ_INIT(&ignores);
608 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
609 switch (ch) {
610 case 'b':
611 branch_name = optarg;
612 break;
613 case 'm':
614 logmsg = strdup(optarg);
615 if (logmsg == NULL) {
616 error = got_error_from_errno("strdup");
617 goto done;
619 break;
620 case 'r':
621 repo_path = realpath(optarg, NULL);
622 if (repo_path == NULL) {
623 error = got_error_from_errno2("realpath",
624 optarg);
625 goto done;
627 break;
628 case 'I':
629 if (optarg[0] == '\0')
630 break;
631 error = got_pathlist_insert(&pe, &ignores, optarg,
632 NULL);
633 if (error)
634 goto done;
635 break;
636 default:
637 usage_import();
638 /* NOTREACHED */
642 argc -= optind;
643 argv += optind;
645 #ifndef PROFILE
646 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
647 "unveil",
648 NULL) == -1)
649 err(1, "pledge");
650 #endif
651 if (argc != 1)
652 usage_import();
654 if (repo_path == NULL) {
655 repo_path = getcwd(NULL, 0);
656 if (repo_path == NULL)
657 return got_error_from_errno("getcwd");
659 got_path_strip_trailing_slashes(repo_path);
660 error = get_gitconfig_path(&gitconfig_path);
661 if (error)
662 goto done;
663 error = got_repo_open(&repo, repo_path, gitconfig_path);
664 if (error)
665 goto done;
667 error = get_author(&author, repo);
668 if (error)
669 return error;
671 /*
672 * Don't let the user create a branch name with a leading '-'.
673 * While technically a valid reference name, this case is usually
674 * an unintended typo.
675 */
676 if (branch_name[0] == '-')
677 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
679 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
680 error = got_error_from_errno("asprintf");
681 goto done;
684 error = got_ref_open(&branch_ref, repo, refname, 0);
685 if (error) {
686 if (error->code != GOT_ERR_NOT_REF)
687 goto done;
688 } else {
689 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
690 "import target branch already exists");
691 goto done;
694 path_dir = realpath(argv[0], NULL);
695 if (path_dir == NULL) {
696 error = got_error_from_errno2("realpath", argv[0]);
697 goto done;
699 got_path_strip_trailing_slashes(path_dir);
701 /*
702 * unveil(2) traverses exec(2); if an editor is used we have
703 * to apply unveil after the log message has been written.
704 */
705 if (logmsg == NULL || strlen(logmsg) == 0) {
706 error = get_editor(&editor);
707 if (error)
708 goto done;
709 free(logmsg);
710 error = collect_import_msg(&logmsg, &logmsg_path, editor,
711 path_dir, refname);
712 if (error) {
713 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
714 logmsg_path != NULL)
715 preserve_logmsg = 1;
716 goto done;
720 if (unveil(path_dir, "r") != 0) {
721 error = got_error_from_errno2("unveil", path_dir);
722 if (logmsg_path)
723 preserve_logmsg = 1;
724 goto done;
727 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
728 if (error) {
729 if (logmsg_path)
730 preserve_logmsg = 1;
731 goto done;
734 error = got_repo_import(&new_commit_id, path_dir, logmsg,
735 author, &ignores, repo, import_progress, NULL);
736 if (error) {
737 if (logmsg_path)
738 preserve_logmsg = 1;
739 goto done;
742 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
743 if (error) {
744 if (logmsg_path)
745 preserve_logmsg = 1;
746 goto done;
749 error = got_ref_write(branch_ref, repo);
750 if (error) {
751 if (logmsg_path)
752 preserve_logmsg = 1;
753 goto done;
756 error = got_object_id_str(&id_str, new_commit_id);
757 if (error) {
758 if (logmsg_path)
759 preserve_logmsg = 1;
760 goto done;
763 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
764 if (error) {
765 if (error->code != GOT_ERR_NOT_REF) {
766 if (logmsg_path)
767 preserve_logmsg = 1;
768 goto done;
771 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
772 branch_ref);
773 if (error) {
774 if (logmsg_path)
775 preserve_logmsg = 1;
776 goto done;
779 error = got_ref_write(head_ref, repo);
780 if (error) {
781 if (logmsg_path)
782 preserve_logmsg = 1;
783 goto done;
787 printf("Created branch %s with commit %s\n",
788 got_ref_get_name(branch_ref), id_str);
789 done:
790 if (preserve_logmsg) {
791 fprintf(stderr, "%s: log message preserved in %s\n",
792 getprogname(), logmsg_path);
793 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
794 error = got_error_from_errno2("unlink", logmsg_path);
795 free(logmsg);
796 free(logmsg_path);
797 free(repo_path);
798 free(editor);
799 free(refname);
800 free(new_commit_id);
801 free(id_str);
802 free(author);
803 free(gitconfig_path);
804 if (branch_ref)
805 got_ref_close(branch_ref);
806 if (head_ref)
807 got_ref_close(head_ref);
808 return error;
811 __dead static void
812 usage_clone(void)
814 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
815 "[-R reference] repository-url [directory]\n", getprogname());
816 exit(1);
819 struct got_fetch_progress_arg {
820 char last_scaled_size[FMT_SCALED_STRSIZE];
821 int last_p_indexed;
822 int last_p_resolved;
823 int verbosity;
824 };
826 static const struct got_error *
827 fetch_progress(void *arg, const char *message, off_t packfile_size,
828 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
830 struct got_fetch_progress_arg *a = arg;
831 char scaled_size[FMT_SCALED_STRSIZE];
832 int p_indexed, p_resolved;
833 int print_size = 0, print_indexed = 0, print_resolved = 0;
835 if (a->verbosity < 0)
836 return NULL;
838 if (message && message[0] != '\0') {
839 printf("\rserver: %s", message);
840 fflush(stdout);
841 return NULL;
844 if (packfile_size > 0 || nobj_indexed > 0) {
845 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
846 (a->last_scaled_size[0] == '\0' ||
847 strcmp(scaled_size, a->last_scaled_size)) != 0) {
848 print_size = 1;
849 if (strlcpy(a->last_scaled_size, scaled_size,
850 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
851 return got_error(GOT_ERR_NO_SPACE);
853 if (nobj_indexed > 0) {
854 p_indexed = (nobj_indexed * 100) / nobj_total;
855 if (p_indexed != a->last_p_indexed) {
856 a->last_p_indexed = p_indexed;
857 print_indexed = 1;
858 print_size = 1;
861 if (nobj_resolved > 0) {
862 p_resolved = (nobj_resolved * 100) /
863 (nobj_total - nobj_loose);
864 if (p_resolved != a->last_p_resolved) {
865 a->last_p_resolved = p_resolved;
866 print_resolved = 1;
867 print_indexed = 1;
868 print_size = 1;
873 if (print_size || print_indexed || print_resolved)
874 printf("\r");
875 if (print_size)
876 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
877 if (print_indexed)
878 printf("; indexing %d%%", p_indexed);
879 if (print_resolved)
880 printf("; resolving deltas %d%%", p_resolved);
881 if (print_size || print_indexed || print_resolved)
882 fflush(stdout);
884 return NULL;
887 static const struct got_error *
888 create_symref(const char *refname, struct got_reference *target_ref,
889 int verbosity, struct got_repository *repo)
891 const struct got_error *err;
892 struct got_reference *head_symref;
894 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
895 if (err)
896 return err;
898 err = got_ref_write(head_symref, repo);
899 got_ref_close(head_symref);
900 if (err == NULL && verbosity > 0) {
901 printf("Created reference %s: %s\n", GOT_REF_HEAD,
902 got_ref_get_name(target_ref));
904 return err;
907 static const struct got_error *
908 list_remote_refs(struct got_pathlist_head *symrefs,
909 struct got_pathlist_head *refs)
911 const struct got_error *err;
912 struct got_pathlist_entry *pe;
914 TAILQ_FOREACH(pe, symrefs, entry) {
915 const char *refname = pe->path;
916 const char *targetref = pe->data;
918 printf("%s: %s\n", refname, targetref);
921 TAILQ_FOREACH(pe, refs, entry) {
922 const char *refname = pe->path;
923 struct got_object_id *id = pe->data;
924 char *id_str;
926 err = got_object_id_str(&id_str, id);
927 if (err)
928 return err;
929 printf("%s: %s\n", refname, id_str);
930 free(id_str);
933 return NULL;
936 static const struct got_error *
937 create_ref(const char *refname, struct got_object_id *id,
938 int verbosity, struct got_repository *repo)
940 const struct got_error *err = NULL;
941 struct got_reference *ref;
942 char *id_str;
944 err = got_object_id_str(&id_str, id);
945 if (err)
946 return err;
948 err = got_ref_alloc(&ref, refname, id);
949 if (err)
950 goto done;
952 err = got_ref_write(ref, repo);
953 got_ref_close(ref);
955 if (err == NULL && verbosity >= 0)
956 printf("Created reference %s: %s\n", refname, id_str);
957 done:
958 free(id_str);
959 return err;
962 static int
963 match_wanted_ref(const char *refname, const char *wanted_ref)
965 if (strncmp(refname, "refs/", 5) != 0)
966 return 0;
967 refname += 5;
969 /*
970 * Prevent fetching of references that won't make any
971 * sense outside of the remote repository's context.
972 */
973 if (strncmp(refname, "got/", 4) == 0)
974 return 0;
975 if (strncmp(refname, "remotes/", 8) == 0)
976 return 0;
978 if (strncmp(wanted_ref, "refs/", 5) == 0)
979 wanted_ref += 5;
981 /* Allow prefix match. */
982 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
983 return 1;
985 /* Allow exact match. */
986 return (strcmp(refname, wanted_ref) == 0);
989 static int
990 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
992 struct got_pathlist_entry *pe;
994 TAILQ_FOREACH(pe, wanted_refs, entry) {
995 if (match_wanted_ref(refname, pe->path))
996 return 1;
999 return 0;
1002 static const struct got_error *
1003 create_wanted_ref(const char *refname, struct got_object_id *id,
1004 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1006 const struct got_error *err;
1007 char *remote_refname;
1009 if (strncmp("refs/", refname, 5) == 0)
1010 refname += 5;
1012 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1013 remote_repo_name, refname) == -1)
1014 return got_error_from_errno("asprintf");
1016 err = create_ref(remote_refname, id, verbosity, repo);
1017 free(remote_refname);
1018 return err;
1021 static const struct got_error *
1022 cmd_clone(int argc, char *argv[])
1024 const struct got_error *error = NULL;
1025 const char *uri, *dirname;
1026 char *proto, *host, *port, *repo_name, *server_path;
1027 char *default_destdir = NULL, *id_str = NULL;
1028 const char *repo_path;
1029 struct got_repository *repo = NULL;
1030 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1031 struct got_pathlist_entry *pe;
1032 struct got_object_id *pack_hash = NULL;
1033 int ch, fetchfd = -1, fetchstatus;
1034 pid_t fetchpid = -1;
1035 struct got_fetch_progress_arg fpa;
1036 char *git_url = NULL;
1037 char *gitconfig_path = NULL;
1038 char *gitconfig = NULL;
1039 FILE *gitconfig_file = NULL;
1040 ssize_t n;
1041 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1042 int list_refs_only = 0;
1043 struct got_reference *head_symref = NULL;
1045 TAILQ_INIT(&refs);
1046 TAILQ_INIT(&symrefs);
1047 TAILQ_INIT(&wanted_branches);
1048 TAILQ_INIT(&wanted_refs);
1050 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1051 switch (ch) {
1052 case 'a':
1053 fetch_all_branches = 1;
1054 break;
1055 case 'b':
1056 error = got_pathlist_append(&wanted_branches,
1057 optarg, NULL);
1058 if (error)
1059 return error;
1060 break;
1061 case 'l':
1062 list_refs_only = 1;
1063 break;
1064 case 'm':
1065 mirror_references = 1;
1066 break;
1067 case 'v':
1068 if (verbosity < 0)
1069 verbosity = 0;
1070 else if (verbosity < 3)
1071 verbosity++;
1072 break;
1073 case 'q':
1074 verbosity = -1;
1075 break;
1076 case 'R':
1077 error = got_pathlist_append(&wanted_refs,
1078 optarg, NULL);
1079 if (error)
1080 return error;
1081 break;
1082 default:
1083 usage_clone();
1084 break;
1087 argc -= optind;
1088 argv += optind;
1090 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1091 errx(1, "-a and -b options are mutually exclusive");
1092 if (list_refs_only) {
1093 if (!TAILQ_EMPTY(&wanted_branches))
1094 errx(1, "-l and -b options are mutually exclusive");
1095 if (fetch_all_branches)
1096 errx(1, "-l and -a options are mutually exclusive");
1097 if (mirror_references)
1098 errx(1, "-l and -m options are mutually exclusive");
1099 if (verbosity == -1)
1100 errx(1, "-l and -q options are mutually exclusive");
1101 if (!TAILQ_EMPTY(&wanted_refs))
1102 errx(1, "-l and -R options are mutually exclusive");
1105 uri = argv[0];
1107 if (argc == 1)
1108 dirname = NULL;
1109 else if (argc == 2)
1110 dirname = argv[1];
1111 else
1112 usage_clone();
1114 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1115 &repo_name, argv[0]);
1116 if (error)
1117 goto done;
1119 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1120 host, port ? ":" : "", port ? port : "",
1121 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1122 error = got_error_from_errno("asprintf");
1123 goto done;
1126 if (strcmp(proto, "git") == 0) {
1127 #ifndef PROFILE
1128 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1129 "sendfd dns inet unveil", NULL) == -1)
1130 err(1, "pledge");
1131 #endif
1132 } else if (strcmp(proto, "git+ssh") == 0 ||
1133 strcmp(proto, "ssh") == 0) {
1134 #ifndef PROFILE
1135 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1136 "sendfd unveil", NULL) == -1)
1137 err(1, "pledge");
1138 #endif
1139 } else if (strcmp(proto, "http") == 0 ||
1140 strcmp(proto, "git+http") == 0) {
1141 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1142 goto done;
1143 } else {
1144 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1145 goto done;
1147 if (dirname == NULL) {
1148 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1149 error = got_error_from_errno("asprintf");
1150 goto done;
1152 repo_path = default_destdir;
1153 } else
1154 repo_path = dirname;
1156 if (!list_refs_only) {
1157 error = got_path_mkdir(repo_path);
1158 if (error)
1159 goto done;
1161 error = got_repo_init(repo_path);
1162 if (error)
1163 goto done;
1164 error = got_repo_open(&repo, repo_path, NULL);
1165 if (error)
1166 goto done;
1169 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1170 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1171 error = got_error_from_errno2("unveil",
1172 GOT_FETCH_PATH_SSH);
1173 goto done;
1176 error = apply_unveil(repo ? got_repo_get_path(repo) : NULL, 0, NULL);
1177 if (error)
1178 goto done;
1180 if (verbosity >= 0)
1181 printf("Connecting to %s%s%s\n", host,
1182 port ? ":" : "", port ? port : "");
1184 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1185 server_path, verbosity);
1186 if (error)
1187 goto done;
1189 fpa.last_scaled_size[0] = '\0';
1190 fpa.last_p_indexed = -1;
1191 fpa.last_p_resolved = -1;
1192 fpa.verbosity = verbosity;
1193 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1194 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1195 fetch_all_branches, &wanted_branches, &wanted_refs,
1196 list_refs_only, verbosity, fetchfd, repo,
1197 fetch_progress, &fpa);
1198 if (error)
1199 goto done;
1201 if (list_refs_only) {
1202 error = list_remote_refs(&symrefs, &refs);
1203 goto done;
1206 error = got_object_id_str(&id_str, pack_hash);
1207 if (error)
1208 goto done;
1209 if (verbosity >= 0)
1210 printf("\nFetched %s.pack\n", id_str);
1211 free(id_str);
1213 /* Set up references provided with the pack file. */
1214 TAILQ_FOREACH(pe, &refs, entry) {
1215 const char *refname = pe->path;
1216 struct got_object_id *id = pe->data;
1217 char *remote_refname;
1219 if (is_wanted_ref(&wanted_refs, refname) &&
1220 !mirror_references) {
1221 error = create_wanted_ref(refname, id,
1222 GOT_FETCH_DEFAULT_REMOTE_NAME,
1223 verbosity - 1, repo);
1224 if (error)
1225 goto done;
1226 continue;
1229 error = create_ref(refname, id, verbosity - 1, repo);
1230 if (error)
1231 goto done;
1233 if (mirror_references)
1234 continue;
1236 if (strncmp("refs/heads/", refname, 11) != 0)
1237 continue;
1239 if (asprintf(&remote_refname,
1240 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1241 refname + 11) == -1) {
1242 error = got_error_from_errno("asprintf");
1243 goto done;
1245 error = create_ref(remote_refname, id, verbosity - 1, repo);
1246 free(remote_refname);
1247 if (error)
1248 goto done;
1251 /* Set the HEAD reference if the server provided one. */
1252 TAILQ_FOREACH(pe, &symrefs, entry) {
1253 struct got_reference *target_ref;
1254 const char *refname = pe->path;
1255 const char *target = pe->data;
1256 char *remote_refname = NULL, *remote_target = NULL;
1258 if (strcmp(refname, GOT_REF_HEAD) != 0)
1259 continue;
1261 error = got_ref_open(&target_ref, repo, target, 0);
1262 if (error) {
1263 if (error->code == GOT_ERR_NOT_REF) {
1264 error = NULL;
1265 continue;
1267 goto done;
1270 error = create_symref(refname, target_ref, verbosity, repo);
1271 got_ref_close(target_ref);
1272 if (error)
1273 goto done;
1275 if (mirror_references)
1276 continue;
1278 if (strncmp("refs/heads/", target, 11) != 0)
1279 continue;
1281 if (asprintf(&remote_refname,
1282 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1283 refname) == -1) {
1284 error = got_error_from_errno("asprintf");
1285 goto done;
1287 if (asprintf(&remote_target,
1288 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1289 target + 11) == -1) {
1290 error = got_error_from_errno("asprintf");
1291 free(remote_refname);
1292 goto done;
1294 error = got_ref_open(&target_ref, repo, remote_target, 0);
1295 if (error) {
1296 free(remote_refname);
1297 free(remote_target);
1298 if (error->code == GOT_ERR_NOT_REF) {
1299 error = NULL;
1300 continue;
1302 goto done;
1304 error = create_symref(remote_refname, target_ref,
1305 verbosity - 1, repo);
1306 free(remote_refname);
1307 free(remote_target);
1308 got_ref_close(target_ref);
1309 if (error)
1310 goto done;
1312 if (pe == NULL) {
1314 * We failed to set the HEAD reference. If we asked for
1315 * a set of wanted branches use the first of one of those
1316 * which could be fetched instead.
1318 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1319 const char *target = pe->path;
1320 struct got_reference *target_ref;
1322 error = got_ref_open(&target_ref, repo, target, 0);
1323 if (error) {
1324 if (error->code == GOT_ERR_NOT_REF) {
1325 error = NULL;
1326 continue;
1328 goto done;
1331 error = create_symref(GOT_REF_HEAD, target_ref,
1332 verbosity, repo);
1333 got_ref_close(target_ref);
1334 if (error)
1335 goto done;
1336 break;
1340 /* Create a config file git-fetch(1) can understand. */
1341 gitconfig_path = got_repo_get_path_gitconfig(repo);
1342 if (gitconfig_path == NULL) {
1343 error = got_error_from_errno("got_repo_get_path_gitconfig");
1344 goto done;
1346 gitconfig_file = fopen(gitconfig_path, "a");
1347 if (gitconfig_file == NULL) {
1348 error = got_error_from_errno2("fopen", gitconfig_path);
1349 goto done;
1351 if (mirror_references) {
1352 if (asprintf(&gitconfig,
1353 "[remote \"%s\"]\n"
1354 "\turl = %s\n"
1355 "\tfetch = +refs/*:refs/*\n"
1356 "\tmirror = true\n",
1357 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1358 error = got_error_from_errno("asprintf");
1359 goto done;
1361 } else if (fetch_all_branches) {
1362 if (asprintf(&gitconfig,
1363 "[remote \"%s\"]\n"
1364 "\turl = %s\n"
1365 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1366 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1367 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1368 error = got_error_from_errno("asprintf");
1369 goto done;
1371 } else {
1372 const char *branchname;
1375 * If the server specified a default branch, use just that one.
1376 * Otherwise fall back to fetching all branches on next fetch.
1378 if (head_symref) {
1379 branchname = got_ref_get_symref_target(head_symref);
1380 if (strncmp(branchname, "refs/heads/", 11) == 0)
1381 branchname += 11;
1382 } else
1383 branchname = "*"; /* fall back to all branches */
1384 if (asprintf(&gitconfig,
1385 "[remote \"%s\"]\n"
1386 "\turl = %s\n"
1387 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1388 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1389 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1390 branchname) == -1) {
1391 error = got_error_from_errno("asprintf");
1392 goto done;
1395 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1396 if (n != strlen(gitconfig)) {
1397 error = got_ferror(gitconfig_file, GOT_ERR_IO);
1398 goto done;
1401 if (verbosity >= 0)
1402 printf("Created %s repository '%s'\n",
1403 mirror_references ? "mirrored" : "cloned", repo_path);
1404 done:
1405 if (fetchpid > 0) {
1406 if (kill(fetchpid, SIGTERM) == -1)
1407 error = got_error_from_errno("kill");
1408 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1409 error = got_error_from_errno("waitpid");
1411 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1412 error = got_error_from_errno("close");
1413 if (gitconfig_file && fclose(gitconfig_file) == EOF && error == NULL)
1414 error = got_error_from_errno("fclose");
1415 if (repo)
1416 got_repo_close(repo);
1417 if (head_symref)
1418 got_ref_close(head_symref);
1419 TAILQ_FOREACH(pe, &refs, entry) {
1420 free((void *)pe->path);
1421 free(pe->data);
1423 got_pathlist_free(&refs);
1424 TAILQ_FOREACH(pe, &symrefs, entry) {
1425 free((void *)pe->path);
1426 free(pe->data);
1428 got_pathlist_free(&symrefs);
1429 got_pathlist_free(&wanted_branches);
1430 got_pathlist_free(&wanted_refs);
1431 free(pack_hash);
1432 free(proto);
1433 free(host);
1434 free(port);
1435 free(server_path);
1436 free(repo_name);
1437 free(default_destdir);
1438 free(gitconfig_path);
1439 free(git_url);
1440 return error;
1443 static const struct got_error *
1444 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1445 int replace_tags, int verbosity, struct got_repository *repo)
1447 const struct got_error *err = NULL;
1448 char *new_id_str = NULL;
1449 struct got_object_id *old_id = NULL;
1451 err = got_object_id_str(&new_id_str, new_id);
1452 if (err)
1453 goto done;
1455 if (!replace_tags &&
1456 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1457 err = got_ref_resolve(&old_id, repo, ref);
1458 if (err)
1459 goto done;
1460 if (got_object_id_cmp(old_id, new_id) == 0)
1461 goto done;
1462 if (verbosity >= 0) {
1463 printf("Rejecting update of existing tag %s: %s\n",
1464 got_ref_get_name(ref), new_id_str);
1466 goto done;
1469 if (got_ref_is_symbolic(ref)) {
1470 if (verbosity >= 0) {
1471 printf("Replacing reference %s: %s\n",
1472 got_ref_get_name(ref),
1473 got_ref_get_symref_target(ref));
1475 err = got_ref_change_symref_to_ref(ref, new_id);
1476 if (err)
1477 goto done;
1478 err = got_ref_write(ref, repo);
1479 if (err)
1480 goto done;
1481 } else {
1482 err = got_ref_resolve(&old_id, repo, ref);
1483 if (err)
1484 goto done;
1485 if (got_object_id_cmp(old_id, new_id) == 0)
1486 goto done;
1488 err = got_ref_change_ref(ref, new_id);
1489 if (err)
1490 goto done;
1491 err = got_ref_write(ref, repo);
1492 if (err)
1493 goto done;
1496 if (verbosity >= 0)
1497 printf("Updated 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 if (verbosity >= 0)
1909 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
1910 port ? ":" : "", port ? port : "");
1912 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1913 server_path, verbosity);
1914 if (error)
1915 goto done;
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 struct got_update_progress_arg {
2499 int did_something;
2500 int conflicts;
2501 int obstructed;
2502 int not_updated;
2505 void
2506 print_update_progress_stats(struct got_update_progress_arg *upa)
2508 if (!upa->did_something)
2509 return;
2511 if (upa->conflicts > 0)
2512 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2513 if (upa->obstructed > 0)
2514 printf("File paths obstructed by a non-regular file: %d\n",
2515 upa->obstructed);
2516 if (upa->not_updated > 0)
2517 printf("Files not updated because of existing merge "
2518 "conflicts: %d\n", upa->not_updated);
2521 __dead static void
2522 usage_update(void)
2524 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2525 getprogname());
2526 exit(1);
2529 static const struct got_error *
2530 update_progress(void *arg, unsigned char status, const char *path)
2532 struct got_update_progress_arg *upa = arg;
2534 if (status == GOT_STATUS_EXISTS ||
2535 status == GOT_STATUS_BASE_REF_ERR)
2536 return NULL;
2538 upa->did_something = 1;
2540 /* Base commit bump happens silently. */
2541 if (status == GOT_STATUS_BUMP_BASE)
2542 return NULL;
2544 if (status == GOT_STATUS_CONFLICT)
2545 upa->conflicts++;
2546 if (status == GOT_STATUS_OBSTRUCTED)
2547 upa->obstructed++;
2548 if (status == GOT_STATUS_CANNOT_UPDATE)
2549 upa->not_updated++;
2551 while (path[0] == '/')
2552 path++;
2553 printf("%c %s\n", status, path);
2554 return NULL;
2557 static const struct got_error *
2558 switch_head_ref(struct got_reference *head_ref,
2559 struct got_object_id *commit_id, struct got_worktree *worktree,
2560 struct got_repository *repo)
2562 const struct got_error *err = NULL;
2563 char *base_id_str;
2564 int ref_has_moved = 0;
2566 /* Trivial case: switching between two different references. */
2567 if (strcmp(got_ref_get_name(head_ref),
2568 got_worktree_get_head_ref_name(worktree)) != 0) {
2569 printf("Switching work tree from %s to %s\n",
2570 got_worktree_get_head_ref_name(worktree),
2571 got_ref_get_name(head_ref));
2572 return got_worktree_set_head_ref(worktree, head_ref);
2575 err = check_linear_ancestry(commit_id,
2576 got_worktree_get_base_commit_id(worktree), 0, repo);
2577 if (err) {
2578 if (err->code != GOT_ERR_ANCESTRY)
2579 return err;
2580 ref_has_moved = 1;
2582 if (!ref_has_moved)
2583 return NULL;
2585 /* Switching to a rebased branch with the same reference name. */
2586 err = got_object_id_str(&base_id_str,
2587 got_worktree_get_base_commit_id(worktree));
2588 if (err)
2589 return err;
2590 printf("Reference %s now points at a different branch\n",
2591 got_worktree_get_head_ref_name(worktree));
2592 printf("Switching work tree from %s to %s\n", base_id_str,
2593 got_worktree_get_head_ref_name(worktree));
2594 return NULL;
2597 static const struct got_error *
2598 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2600 const struct got_error *err;
2601 int in_progress;
2603 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2604 if (err)
2605 return err;
2606 if (in_progress)
2607 return got_error(GOT_ERR_REBASING);
2609 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2610 if (err)
2611 return err;
2612 if (in_progress)
2613 return got_error(GOT_ERR_HISTEDIT_BUSY);
2615 return NULL;
2618 static const struct got_error *
2619 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2620 char *argv[], struct got_worktree *worktree)
2622 const struct got_error *err = NULL;
2623 char *path;
2624 int i;
2626 if (argc == 0) {
2627 path = strdup("");
2628 if (path == NULL)
2629 return got_error_from_errno("strdup");
2630 return got_pathlist_append(paths, path, NULL);
2633 for (i = 0; i < argc; i++) {
2634 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2635 if (err)
2636 break;
2637 err = got_pathlist_append(paths, path, NULL);
2638 if (err) {
2639 free(path);
2640 break;
2644 return err;
2647 static const struct got_error *
2648 wrap_not_worktree_error(const struct got_error *orig_err,
2649 const char *cmdname, const char *path)
2651 const struct got_error *err;
2652 struct got_repository *repo;
2653 static char msg[512];
2655 err = got_repo_open(&repo, path, NULL);
2656 if (err)
2657 return orig_err;
2659 snprintf(msg, sizeof(msg),
2660 "'got %s' needs a work tree in addition to a git repository\n"
2661 "Work trees can be checked out from this Git repository with "
2662 "'got checkout'.\n"
2663 "The got(1) manual page contains more information.", cmdname);
2664 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2665 got_repo_close(repo);
2666 return err;
2669 static const struct got_error *
2670 cmd_update(int argc, char *argv[])
2672 const struct got_error *error = NULL;
2673 struct got_repository *repo = NULL;
2674 struct got_worktree *worktree = NULL;
2675 char *worktree_path = NULL;
2676 struct got_object_id *commit_id = NULL;
2677 char *commit_id_str = NULL;
2678 const char *branch_name = NULL;
2679 struct got_reference *head_ref = NULL;
2680 struct got_pathlist_head paths;
2681 struct got_pathlist_entry *pe;
2682 int ch;
2683 struct got_update_progress_arg upa;
2685 TAILQ_INIT(&paths);
2687 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2688 switch (ch) {
2689 case 'b':
2690 branch_name = optarg;
2691 break;
2692 case 'c':
2693 commit_id_str = strdup(optarg);
2694 if (commit_id_str == NULL)
2695 return got_error_from_errno("strdup");
2696 break;
2697 default:
2698 usage_update();
2699 /* NOTREACHED */
2703 argc -= optind;
2704 argv += optind;
2706 #ifndef PROFILE
2707 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2708 "unveil", NULL) == -1)
2709 err(1, "pledge");
2710 #endif
2711 worktree_path = getcwd(NULL, 0);
2712 if (worktree_path == NULL) {
2713 error = got_error_from_errno("getcwd");
2714 goto done;
2716 error = got_worktree_open(&worktree, worktree_path);
2717 if (error) {
2718 if (error->code == GOT_ERR_NOT_WORKTREE)
2719 error = wrap_not_worktree_error(error, "update",
2720 worktree_path);
2721 goto done;
2724 error = check_rebase_or_histedit_in_progress(worktree);
2725 if (error)
2726 goto done;
2728 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
2729 NULL);
2730 if (error != NULL)
2731 goto done;
2733 error = apply_unveil(got_repo_get_path(repo), 0,
2734 got_worktree_get_root_path(worktree));
2735 if (error)
2736 goto done;
2738 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2739 if (error)
2740 goto done;
2742 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
2743 got_worktree_get_head_ref_name(worktree), 0);
2744 if (error != NULL)
2745 goto done;
2746 if (commit_id_str == NULL) {
2747 error = got_ref_resolve(&commit_id, repo, head_ref);
2748 if (error != NULL)
2749 goto done;
2750 error = got_object_id_str(&commit_id_str, commit_id);
2751 if (error != NULL)
2752 goto done;
2753 } else {
2754 error = got_repo_match_object_id(&commit_id, NULL,
2755 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2756 free(commit_id_str);
2757 commit_id_str = NULL;
2758 if (error)
2759 goto done;
2760 error = got_object_id_str(&commit_id_str, commit_id);
2761 if (error)
2762 goto done;
2765 if (branch_name) {
2766 struct got_object_id *head_commit_id;
2767 TAILQ_FOREACH(pe, &paths, entry) {
2768 if (pe->path_len == 0)
2769 continue;
2770 error = got_error_msg(GOT_ERR_BAD_PATH,
2771 "switching between branches requires that "
2772 "the entire work tree gets updated");
2773 goto done;
2775 error = got_ref_resolve(&head_commit_id, repo, head_ref);
2776 if (error)
2777 goto done;
2778 error = check_linear_ancestry(commit_id, head_commit_id, 0,
2779 repo);
2780 free(head_commit_id);
2781 if (error != NULL)
2782 goto done;
2783 error = check_same_branch(commit_id, head_ref, NULL, repo);
2784 if (error)
2785 goto done;
2786 error = switch_head_ref(head_ref, commit_id, worktree, repo);
2787 if (error)
2788 goto done;
2789 } else {
2790 error = check_linear_ancestry(commit_id,
2791 got_worktree_get_base_commit_id(worktree), 0, repo);
2792 if (error != NULL) {
2793 if (error->code == GOT_ERR_ANCESTRY)
2794 error = got_error(GOT_ERR_BRANCH_MOVED);
2795 goto done;
2797 error = check_same_branch(commit_id, head_ref, NULL, repo);
2798 if (error)
2799 goto done;
2802 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
2803 commit_id) != 0) {
2804 error = got_worktree_set_base_commit_id(worktree, repo,
2805 commit_id);
2806 if (error)
2807 goto done;
2810 memset(&upa, 0, sizeof(upa));
2811 error = got_worktree_checkout_files(worktree, &paths, repo,
2812 update_progress, &upa, check_cancelled, NULL);
2813 if (error != NULL)
2814 goto done;
2816 if (upa.did_something)
2817 printf("Updated to commit %s\n", commit_id_str);
2818 else
2819 printf("Already up-to-date\n");
2820 print_update_progress_stats(&upa);
2821 done:
2822 free(worktree_path);
2823 TAILQ_FOREACH(pe, &paths, entry)
2824 free((char *)pe->path);
2825 got_pathlist_free(&paths);
2826 free(commit_id);
2827 free(commit_id_str);
2828 return error;
2831 static const struct got_error *
2832 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
2833 const char *path, int diff_context, int ignore_whitespace,
2834 struct got_repository *repo)
2836 const struct got_error *err = NULL;
2837 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
2839 if (blob_id1) {
2840 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
2841 if (err)
2842 goto done;
2845 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
2846 if (err)
2847 goto done;
2849 while (path[0] == '/')
2850 path++;
2851 err = got_diff_blob(blob1, blob2, path, path, diff_context,
2852 ignore_whitespace, stdout);
2853 done:
2854 if (blob1)
2855 got_object_blob_close(blob1);
2856 got_object_blob_close(blob2);
2857 return err;
2860 static const struct got_error *
2861 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
2862 const char *path, int diff_context, int ignore_whitespace,
2863 struct got_repository *repo)
2865 const struct got_error *err = NULL;
2866 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
2867 struct got_diff_blob_output_unidiff_arg arg;
2869 if (tree_id1) {
2870 err = got_object_open_as_tree(&tree1, repo, tree_id1);
2871 if (err)
2872 goto done;
2875 err = got_object_open_as_tree(&tree2, repo, tree_id2);
2876 if (err)
2877 goto done;
2879 arg.diff_context = diff_context;
2880 arg.ignore_whitespace = ignore_whitespace;
2881 arg.outfile = stdout;
2882 while (path[0] == '/')
2883 path++;
2884 err = got_diff_tree(tree1, tree2, path, path, repo,
2885 got_diff_blob_output_unidiff, &arg, 1);
2886 done:
2887 if (tree1)
2888 got_object_tree_close(tree1);
2889 if (tree2)
2890 got_object_tree_close(tree2);
2891 return err;
2894 static const struct got_error *
2895 print_patch(struct got_commit_object *commit, struct got_object_id *id,
2896 const char *path, int diff_context, struct got_repository *repo)
2898 const struct got_error *err = NULL;
2899 struct got_commit_object *pcommit = NULL;
2900 char *id_str1 = NULL, *id_str2 = NULL;
2901 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
2902 struct got_object_qid *qid;
2904 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
2905 if (qid != NULL) {
2906 err = got_object_open_as_commit(&pcommit, repo,
2907 qid->id);
2908 if (err)
2909 return err;
2912 if (path && path[0] != '\0') {
2913 int obj_type;
2914 err = got_object_id_by_path(&obj_id2, repo, id, path);
2915 if (err)
2916 goto done;
2917 err = got_object_id_str(&id_str2, obj_id2);
2918 if (err) {
2919 free(obj_id2);
2920 goto done;
2922 if (pcommit) {
2923 err = got_object_id_by_path(&obj_id1, repo,
2924 qid->id, path);
2925 if (err) {
2926 free(obj_id2);
2927 goto done;
2929 err = got_object_id_str(&id_str1, obj_id1);
2930 if (err) {
2931 free(obj_id2);
2932 goto done;
2935 err = got_object_get_type(&obj_type, repo, obj_id2);
2936 if (err) {
2937 free(obj_id2);
2938 goto done;
2940 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2941 switch (obj_type) {
2942 case GOT_OBJ_TYPE_BLOB:
2943 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
2944 0, repo);
2945 break;
2946 case GOT_OBJ_TYPE_TREE:
2947 err = diff_trees(obj_id1, obj_id2, path, diff_context,
2948 0, repo);
2949 break;
2950 default:
2951 err = got_error(GOT_ERR_OBJ_TYPE);
2952 break;
2954 free(obj_id1);
2955 free(obj_id2);
2956 } else {
2957 obj_id2 = got_object_commit_get_tree_id(commit);
2958 err = got_object_id_str(&id_str2, obj_id2);
2959 if (err)
2960 goto done;
2961 obj_id1 = got_object_commit_get_tree_id(pcommit);
2962 err = got_object_id_str(&id_str1, obj_id1);
2963 if (err)
2964 goto done;
2965 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2966 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
2968 done:
2969 free(id_str1);
2970 free(id_str2);
2971 if (pcommit)
2972 got_object_commit_close(pcommit);
2973 return err;
2976 static char *
2977 get_datestr(time_t *time, char *datebuf)
2979 struct tm mytm, *tm;
2980 char *p, *s;
2982 tm = gmtime_r(time, &mytm);
2983 if (tm == NULL)
2984 return NULL;
2985 s = asctime_r(tm, datebuf);
2986 if (s == NULL)
2987 return NULL;
2988 p = strchr(s, '\n');
2989 if (p)
2990 *p = '\0';
2991 return s;
2994 static const struct got_error *
2995 match_logmsg(int *have_match, struct got_object_id *id,
2996 struct got_commit_object *commit, regex_t *regex)
2998 const struct got_error *err = NULL;
2999 regmatch_t regmatch;
3000 char *id_str = NULL, *logmsg = NULL;
3002 *have_match = 0;
3004 err = got_object_id_str(&id_str, id);
3005 if (err)
3006 return err;
3008 err = got_object_commit_get_logmsg(&logmsg, commit);
3009 if (err)
3010 goto done;
3012 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3013 *have_match = 1;
3014 done:
3015 free(id_str);
3016 free(logmsg);
3017 return err;
3020 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3022 static const struct got_error *
3023 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3024 struct got_repository *repo, const char *path, int show_patch,
3025 int diff_context, struct got_reflist_head *refs)
3027 const struct got_error *err = NULL;
3028 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3029 char datebuf[26];
3030 time_t committer_time;
3031 const char *author, *committer;
3032 char *refs_str = NULL;
3033 struct got_reflist_entry *re;
3035 SIMPLEQ_FOREACH(re, refs, entry) {
3036 char *s;
3037 const char *name;
3038 struct got_tag_object *tag = NULL;
3039 int cmp;
3041 name = got_ref_get_name(re->ref);
3042 if (strcmp(name, GOT_REF_HEAD) == 0)
3043 continue;
3044 if (strncmp(name, "refs/", 5) == 0)
3045 name += 5;
3046 if (strncmp(name, "got/", 4) == 0)
3047 continue;
3048 if (strncmp(name, "heads/", 6) == 0)
3049 name += 6;
3050 if (strncmp(name, "remotes/", 8) == 0) {
3051 name += 8;
3052 s = strstr(name, "/" GOT_REF_HEAD);
3053 if (s != NULL && s[strlen(s)] == '\0')
3054 continue;
3056 if (strncmp(name, "tags/", 5) == 0) {
3057 err = got_object_open_as_tag(&tag, repo, re->id);
3058 if (err) {
3059 if (err->code != GOT_ERR_OBJ_TYPE)
3060 return err;
3061 /* Ref points at something other than a tag. */
3062 err = NULL;
3063 tag = NULL;
3066 cmp = got_object_id_cmp(tag ?
3067 got_object_tag_get_object_id(tag) : re->id, id);
3068 if (tag)
3069 got_object_tag_close(tag);
3070 if (cmp != 0)
3071 continue;
3072 s = refs_str;
3073 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3074 name) == -1) {
3075 err = got_error_from_errno("asprintf");
3076 free(s);
3077 return err;
3079 free(s);
3081 err = got_object_id_str(&id_str, id);
3082 if (err)
3083 return err;
3085 printf(GOT_COMMIT_SEP_STR);
3086 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3087 refs_str ? refs_str : "", refs_str ? ")" : "");
3088 free(id_str);
3089 id_str = NULL;
3090 free(refs_str);
3091 refs_str = NULL;
3092 printf("from: %s\n", got_object_commit_get_author(commit));
3093 committer_time = got_object_commit_get_committer_time(commit);
3094 datestr = get_datestr(&committer_time, datebuf);
3095 if (datestr)
3096 printf("date: %s UTC\n", datestr);
3097 author = got_object_commit_get_author(commit);
3098 committer = got_object_commit_get_committer(commit);
3099 if (strcmp(author, committer) != 0)
3100 printf("via: %s\n", committer);
3101 if (got_object_commit_get_nparents(commit) > 1) {
3102 const struct got_object_id_queue *parent_ids;
3103 struct got_object_qid *qid;
3104 int n = 1;
3105 parent_ids = got_object_commit_get_parent_ids(commit);
3106 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3107 err = got_object_id_str(&id_str, qid->id);
3108 if (err)
3109 return err;
3110 printf("parent %d: %s\n", n++, id_str);
3111 free(id_str);
3115 err = got_object_commit_get_logmsg(&logmsg0, commit);
3116 if (err)
3117 return err;
3119 logmsg = logmsg0;
3120 do {
3121 line = strsep(&logmsg, "\n");
3122 if (line)
3123 printf(" %s\n", line);
3124 } while (line);
3125 free(logmsg0);
3127 if (show_patch) {
3128 err = print_patch(commit, id, path, diff_context, repo);
3129 if (err == 0)
3130 printf("\n");
3133 if (fflush(stdout) != 0 && err == NULL)
3134 err = got_error_from_errno("fflush");
3135 return err;
3138 static const struct got_error *
3139 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3140 struct got_repository *repo, const char *path, int show_patch,
3141 const char *search_pattern, int diff_context, int limit, int log_branches,
3142 int reverse_display_order, struct got_reflist_head *refs)
3144 const struct got_error *err;
3145 struct got_commit_graph *graph;
3146 regex_t regex;
3147 int have_match;
3148 struct got_object_id_queue reversed_commits;
3149 struct got_object_qid *qid;
3150 struct got_commit_object *commit;
3152 SIMPLEQ_INIT(&reversed_commits);
3154 if (search_pattern && regcomp(&regex, search_pattern,
3155 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3156 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3158 err = got_commit_graph_open(&graph, path, !log_branches);
3159 if (err)
3160 return err;
3161 err = got_commit_graph_iter_start(graph, root_id, repo,
3162 check_cancelled, NULL);
3163 if (err)
3164 goto done;
3165 for (;;) {
3166 struct got_object_id *id;
3168 if (sigint_received || sigpipe_received)
3169 break;
3171 err = got_commit_graph_iter_next(&id, graph, repo,
3172 check_cancelled, NULL);
3173 if (err) {
3174 if (err->code == GOT_ERR_ITER_COMPLETED)
3175 err = NULL;
3176 break;
3178 if (id == NULL)
3179 break;
3181 err = got_object_open_as_commit(&commit, repo, id);
3182 if (err)
3183 break;
3185 if (search_pattern) {
3186 err = match_logmsg(&have_match, id, commit, &regex);
3187 if (err) {
3188 got_object_commit_close(commit);
3189 break;
3191 if (have_match == 0) {
3192 got_object_commit_close(commit);
3193 continue;
3197 if (reverse_display_order) {
3198 err = got_object_qid_alloc(&qid, id);
3199 if (err)
3200 break;
3201 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3202 got_object_commit_close(commit);
3203 } else {
3204 err = print_commit(commit, id, repo, path, show_patch,
3205 diff_context, refs);
3206 got_object_commit_close(commit);
3207 if (err)
3208 break;
3210 if ((limit && --limit == 0) ||
3211 (end_id && got_object_id_cmp(id, end_id) == 0))
3212 break;
3214 if (reverse_display_order) {
3215 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3216 err = got_object_open_as_commit(&commit, repo, qid->id);
3217 if (err)
3218 break;
3219 err = print_commit(commit, qid->id, repo, path,
3220 show_patch, diff_context, refs);
3221 got_object_commit_close(commit);
3222 if (err)
3223 break;
3226 done:
3227 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3228 qid = SIMPLEQ_FIRST(&reversed_commits);
3229 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3230 got_object_qid_free(qid);
3232 if (search_pattern)
3233 regfree(&regex);
3234 got_commit_graph_close(graph);
3235 return err;
3238 __dead static void
3239 usage_log(void)
3241 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3242 "[-p] [-x commit] [-s search-pattern] [-r repository-path] [-R] "
3243 "[path]\n", getprogname());
3244 exit(1);
3247 static int
3248 get_default_log_limit(void)
3250 const char *got_default_log_limit;
3251 long long n;
3252 const char *errstr;
3254 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3255 if (got_default_log_limit == NULL)
3256 return 0;
3257 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3258 if (errstr != NULL)
3259 return 0;
3260 return n;
3263 static const struct got_error *
3264 resolve_commit_arg(struct got_object_id **id, const char *commit_arg,
3265 struct got_repository *repo)
3267 const struct got_error *err = NULL;
3268 struct got_reference *ref;
3270 *id = NULL;
3272 err = got_ref_open(&ref, repo, commit_arg, 0);
3273 if (err == NULL) {
3274 int obj_type;
3275 err = got_ref_resolve(id, repo, ref);
3276 got_ref_close(ref);
3277 if (err)
3278 return err;
3279 err = got_object_get_type(&obj_type, repo, *id);
3280 if (err)
3281 return err;
3282 if (obj_type == GOT_OBJ_TYPE_TAG) {
3283 struct got_tag_object *tag;
3284 err = got_object_open_as_tag(&tag, repo, *id);
3285 if (err)
3286 return err;
3287 if (got_object_tag_get_object_type(tag) !=
3288 GOT_OBJ_TYPE_COMMIT) {
3289 got_object_tag_close(tag);
3290 return got_error(GOT_ERR_OBJ_TYPE);
3292 free(*id);
3293 *id = got_object_id_dup(
3294 got_object_tag_get_object_id(tag));
3295 if (*id == NULL)
3296 err = got_error_from_errno(
3297 "got_object_id_dup");
3298 got_object_tag_close(tag);
3299 if (err)
3300 return err;
3301 } else if (obj_type != GOT_OBJ_TYPE_COMMIT)
3302 return got_error(GOT_ERR_OBJ_TYPE);
3303 } else {
3304 err = got_repo_match_object_id_prefix(id, commit_arg,
3305 GOT_OBJ_TYPE_COMMIT, repo);
3308 return err;
3311 static const struct got_error *
3312 cmd_log(int argc, char *argv[])
3314 const struct got_error *error;
3315 struct got_repository *repo = NULL;
3316 struct got_worktree *worktree = NULL;
3317 struct got_object_id *start_id = NULL, *end_id = NULL;
3318 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3319 const char *start_commit = NULL, *end_commit = NULL;
3320 const char *search_pattern = NULL;
3321 int diff_context = -1, ch;
3322 int show_patch = 0, limit = 0, log_branches = 0;
3323 int reverse_display_order = 0;
3324 const char *errstr;
3325 struct got_reflist_head refs;
3327 SIMPLEQ_INIT(&refs);
3329 #ifndef PROFILE
3330 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3331 NULL)
3332 == -1)
3333 err(1, "pledge");
3334 #endif
3336 limit = get_default_log_limit();
3338 while ((ch = getopt(argc, argv, "bpc:C:l:r:Rs:x:")) != -1) {
3339 switch (ch) {
3340 case 'p':
3341 show_patch = 1;
3342 break;
3343 case 'c':
3344 start_commit = optarg;
3345 break;
3346 case 'C':
3347 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3348 &errstr);
3349 if (errstr != NULL)
3350 err(1, "-C option %s", errstr);
3351 break;
3352 case 'l':
3353 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3354 if (errstr != NULL)
3355 err(1, "-l option %s", errstr);
3356 break;
3357 case 'b':
3358 log_branches = 1;
3359 break;
3360 case 'r':
3361 repo_path = realpath(optarg, NULL);
3362 if (repo_path == NULL)
3363 return got_error_from_errno2("realpath",
3364 optarg);
3365 got_path_strip_trailing_slashes(repo_path);
3366 break;
3367 case 'R':
3368 reverse_display_order = 1;
3369 break;
3370 case 's':
3371 search_pattern = optarg;
3372 break;
3373 case 'x':
3374 end_commit = optarg;
3375 break;
3376 default:
3377 usage_log();
3378 /* NOTREACHED */
3382 argc -= optind;
3383 argv += optind;
3385 if (diff_context == -1)
3386 diff_context = 3;
3387 else if (!show_patch)
3388 errx(1, "-C reguires -p");
3390 cwd = getcwd(NULL, 0);
3391 if (cwd == NULL) {
3392 error = got_error_from_errno("getcwd");
3393 goto done;
3396 if (repo_path == NULL) {
3397 error = got_worktree_open(&worktree, cwd);
3398 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3399 goto done;
3400 error = NULL;
3403 if (argc == 0) {
3404 path = strdup("");
3405 if (path == NULL) {
3406 error = got_error_from_errno("strdup");
3407 goto done;
3409 } else if (argc == 1) {
3410 if (worktree) {
3411 error = got_worktree_resolve_path(&path, worktree,
3412 argv[0]);
3413 if (error)
3414 goto done;
3415 } else {
3416 path = strdup(argv[0]);
3417 if (path == NULL) {
3418 error = got_error_from_errno("strdup");
3419 goto done;
3422 } else
3423 usage_log();
3425 if (repo_path == NULL) {
3426 repo_path = worktree ?
3427 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3429 if (repo_path == NULL) {
3430 error = got_error_from_errno("strdup");
3431 goto done;
3434 error = got_repo_open(&repo, repo_path, NULL);
3435 if (error != NULL)
3436 goto done;
3438 error = apply_unveil(got_repo_get_path(repo), 1,
3439 worktree ? got_worktree_get_root_path(worktree) : NULL);
3440 if (error)
3441 goto done;
3443 if (start_commit == NULL) {
3444 struct got_reference *head_ref;
3445 struct got_commit_object *commit = NULL;
3446 error = got_ref_open(&head_ref, repo,
3447 worktree ? got_worktree_get_head_ref_name(worktree)
3448 : GOT_REF_HEAD, 0);
3449 if (error != NULL)
3450 goto done;
3451 error = got_ref_resolve(&start_id, repo, head_ref);
3452 got_ref_close(head_ref);
3453 if (error != NULL)
3454 goto done;
3455 error = got_object_open_as_commit(&commit, repo,
3456 start_id);
3457 if (error != NULL)
3458 goto done;
3459 got_object_commit_close(commit);
3460 } else {
3461 error = resolve_commit_arg(&start_id, start_commit, repo);
3462 if (error != NULL)
3463 goto done;
3465 if (end_commit != NULL) {
3466 error = resolve_commit_arg(&end_id, end_commit, repo);
3467 if (error != NULL)
3468 goto done;
3471 if (worktree) {
3472 const char *prefix = got_worktree_get_path_prefix(worktree);
3473 char *p;
3474 if (asprintf(&p, "%s%s%s", prefix,
3475 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3476 error = got_error_from_errno("asprintf");
3477 goto done;
3479 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3480 free(p);
3481 } else
3482 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3483 if (error != NULL)
3484 goto done;
3485 if (in_repo_path) {
3486 free(path);
3487 path = in_repo_path;
3490 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3491 if (error)
3492 goto done;
3494 error = print_commits(start_id, end_id, repo, path, show_patch,
3495 search_pattern, diff_context, limit, log_branches,
3496 reverse_display_order, &refs);
3497 done:
3498 free(path);
3499 free(repo_path);
3500 free(cwd);
3501 if (worktree)
3502 got_worktree_close(worktree);
3503 if (repo) {
3504 const struct got_error *repo_error;
3505 repo_error = got_repo_close(repo);
3506 if (error == NULL)
3507 error = repo_error;
3509 got_ref_list_free(&refs);
3510 return error;
3513 __dead static void
3514 usage_diff(void)
3516 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3517 "[-w] [object1 object2 | path]\n", getprogname());
3518 exit(1);
3521 struct print_diff_arg {
3522 struct got_repository *repo;
3523 struct got_worktree *worktree;
3524 int diff_context;
3525 const char *id_str;
3526 int header_shown;
3527 int diff_staged;
3528 int ignore_whitespace;
3531 static const struct got_error *
3532 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3533 const char *path, struct got_object_id *blob_id,
3534 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3535 int dirfd, const char *de_name)
3537 struct print_diff_arg *a = arg;
3538 const struct got_error *err = NULL;
3539 struct got_blob_object *blob1 = NULL;
3540 int fd = -1;
3541 FILE *f2 = NULL;
3542 char *abspath = NULL, *label1 = NULL;
3543 struct stat sb;
3545 if (a->diff_staged) {
3546 if (staged_status != GOT_STATUS_MODIFY &&
3547 staged_status != GOT_STATUS_ADD &&
3548 staged_status != GOT_STATUS_DELETE)
3549 return NULL;
3550 } else {
3551 if (staged_status == GOT_STATUS_DELETE)
3552 return NULL;
3553 if (status == GOT_STATUS_NONEXISTENT)
3554 return got_error_set_errno(ENOENT, path);
3555 if (status != GOT_STATUS_MODIFY &&
3556 status != GOT_STATUS_ADD &&
3557 status != GOT_STATUS_DELETE &&
3558 status != GOT_STATUS_CONFLICT)
3559 return NULL;
3562 if (!a->header_shown) {
3563 printf("diff %s %s%s\n", a->id_str,
3564 got_worktree_get_root_path(a->worktree),
3565 a->diff_staged ? " (staged changes)" : "");
3566 a->header_shown = 1;
3569 if (a->diff_staged) {
3570 const char *label1 = NULL, *label2 = NULL;
3571 switch (staged_status) {
3572 case GOT_STATUS_MODIFY:
3573 label1 = path;
3574 label2 = path;
3575 break;
3576 case GOT_STATUS_ADD:
3577 label2 = path;
3578 break;
3579 case GOT_STATUS_DELETE:
3580 label1 = path;
3581 break;
3582 default:
3583 return got_error(GOT_ERR_FILE_STATUS);
3585 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
3586 label1, label2, a->diff_context, a->ignore_whitespace,
3587 a->repo, stdout);
3590 if (staged_status == GOT_STATUS_ADD ||
3591 staged_status == GOT_STATUS_MODIFY) {
3592 char *id_str;
3593 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
3594 8192);
3595 if (err)
3596 goto done;
3597 err = got_object_id_str(&id_str, staged_blob_id);
3598 if (err)
3599 goto done;
3600 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
3601 err = got_error_from_errno("asprintf");
3602 free(id_str);
3603 goto done;
3605 free(id_str);
3606 } else if (status != GOT_STATUS_ADD) {
3607 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
3608 if (err)
3609 goto done;
3612 if (status != GOT_STATUS_DELETE) {
3613 if (asprintf(&abspath, "%s/%s",
3614 got_worktree_get_root_path(a->worktree), path) == -1) {
3615 err = got_error_from_errno("asprintf");
3616 goto done;
3619 if (dirfd != -1) {
3620 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
3621 if (fd == -1) {
3622 err = got_error_from_errno2("openat", abspath);
3623 goto done;
3625 } else {
3626 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
3627 if (fd == -1) {
3628 err = got_error_from_errno2("open", abspath);
3629 goto done;
3632 if (fstat(fd, &sb) == -1) {
3633 err = got_error_from_errno2("fstat", abspath);
3634 goto done;
3636 f2 = fdopen(fd, "r");
3637 if (f2 == NULL) {
3638 err = got_error_from_errno2("fdopen", abspath);
3639 goto done;
3641 fd = -1;
3642 } else
3643 sb.st_size = 0;
3645 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
3646 a->diff_context, a->ignore_whitespace, stdout);
3647 done:
3648 if (blob1)
3649 got_object_blob_close(blob1);
3650 if (f2 && fclose(f2) == EOF && err == NULL)
3651 err = got_error_from_errno("fclose");
3652 if (fd != -1 && close(fd) == -1 && err == NULL)
3653 err = got_error_from_errno("close");
3654 free(abspath);
3655 return err;
3658 static const struct got_error *
3659 cmd_diff(int argc, char *argv[])
3661 const struct got_error *error;
3662 struct got_repository *repo = NULL;
3663 struct got_worktree *worktree = NULL;
3664 char *cwd = NULL, *repo_path = NULL;
3665 struct got_object_id *id1 = NULL, *id2 = NULL;
3666 const char *id_str1 = NULL, *id_str2 = NULL;
3667 char *label1 = NULL, *label2 = NULL;
3668 int type1, type2;
3669 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
3670 const char *errstr;
3671 char *path = NULL;
3673 #ifndef PROFILE
3674 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3675 NULL) == -1)
3676 err(1, "pledge");
3677 #endif
3679 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
3680 switch (ch) {
3681 case 'C':
3682 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3683 &errstr);
3684 if (errstr != NULL)
3685 err(1, "-C option %s", errstr);
3686 break;
3687 case 'r':
3688 repo_path = realpath(optarg, NULL);
3689 if (repo_path == NULL)
3690 return got_error_from_errno2("realpath",
3691 optarg);
3692 got_path_strip_trailing_slashes(repo_path);
3693 break;
3694 case 's':
3695 diff_staged = 1;
3696 break;
3697 case 'w':
3698 ignore_whitespace = 1;
3699 break;
3700 default:
3701 usage_diff();
3702 /* NOTREACHED */
3706 argc -= optind;
3707 argv += optind;
3709 cwd = getcwd(NULL, 0);
3710 if (cwd == NULL) {
3711 error = got_error_from_errno("getcwd");
3712 goto done;
3714 if (argc <= 1) {
3715 if (repo_path)
3716 errx(1,
3717 "-r option can't be used when diffing a work tree");
3718 error = got_worktree_open(&worktree, cwd);
3719 if (error) {
3720 if (error->code == GOT_ERR_NOT_WORKTREE)
3721 error = wrap_not_worktree_error(error, "diff",
3722 cwd);
3723 goto done;
3725 repo_path = strdup(got_worktree_get_repo_path(worktree));
3726 if (repo_path == NULL) {
3727 error = got_error_from_errno("strdup");
3728 goto done;
3730 if (argc == 1) {
3731 error = got_worktree_resolve_path(&path, worktree,
3732 argv[0]);
3733 if (error)
3734 goto done;
3735 } else {
3736 path = strdup("");
3737 if (path == NULL) {
3738 error = got_error_from_errno("strdup");
3739 goto done;
3742 } else if (argc == 2) {
3743 if (diff_staged)
3744 errx(1, "-s option can't be used when diffing "
3745 "objects in repository");
3746 id_str1 = argv[0];
3747 id_str2 = argv[1];
3748 if (repo_path == NULL) {
3749 error = got_worktree_open(&worktree, cwd);
3750 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3751 goto done;
3752 if (worktree) {
3753 repo_path = strdup(
3754 got_worktree_get_repo_path(worktree));
3755 if (repo_path == NULL) {
3756 error = got_error_from_errno("strdup");
3757 goto done;
3759 } else {
3760 repo_path = strdup(cwd);
3761 if (repo_path == NULL) {
3762 error = got_error_from_errno("strdup");
3763 goto done;
3767 } else
3768 usage_diff();
3770 error = got_repo_open(&repo, repo_path, NULL);
3771 free(repo_path);
3772 if (error != NULL)
3773 goto done;
3775 error = apply_unveil(got_repo_get_path(repo), 1,
3776 worktree ? got_worktree_get_root_path(worktree) : NULL);
3777 if (error)
3778 goto done;
3780 if (argc <= 1) {
3781 struct print_diff_arg arg;
3782 struct got_pathlist_head paths;
3783 char *id_str;
3785 TAILQ_INIT(&paths);
3787 error = got_object_id_str(&id_str,
3788 got_worktree_get_base_commit_id(worktree));
3789 if (error)
3790 goto done;
3791 arg.repo = repo;
3792 arg.worktree = worktree;
3793 arg.diff_context = diff_context;
3794 arg.id_str = id_str;
3795 arg.header_shown = 0;
3796 arg.diff_staged = diff_staged;
3797 arg.ignore_whitespace = ignore_whitespace;
3799 error = got_pathlist_append(&paths, path, NULL);
3800 if (error)
3801 goto done;
3803 error = got_worktree_status(worktree, &paths, repo, print_diff,
3804 &arg, check_cancelled, NULL);
3805 free(id_str);
3806 got_pathlist_free(&paths);
3807 goto done;
3810 error = got_repo_match_object_id(&id1, &label1, id_str1,
3811 GOT_OBJ_TYPE_ANY, 1, repo);
3812 if (error)
3813 goto done;
3815 error = got_repo_match_object_id(&id2, &label2, id_str2,
3816 GOT_OBJ_TYPE_ANY, 1, repo);
3817 if (error)
3818 goto done;
3820 error = got_object_get_type(&type1, repo, id1);
3821 if (error)
3822 goto done;
3824 error = got_object_get_type(&type2, repo, id2);
3825 if (error)
3826 goto done;
3828 if (type1 != type2) {
3829 error = got_error(GOT_ERR_OBJ_TYPE);
3830 goto done;
3833 switch (type1) {
3834 case GOT_OBJ_TYPE_BLOB:
3835 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
3836 diff_context, ignore_whitespace, repo, stdout);
3837 break;
3838 case GOT_OBJ_TYPE_TREE:
3839 error = got_diff_objects_as_trees(id1, id2, "", "",
3840 diff_context, ignore_whitespace, repo, stdout);
3841 break;
3842 case GOT_OBJ_TYPE_COMMIT:
3843 printf("diff %s %s\n", label1, label2);
3844 error = got_diff_objects_as_commits(id1, id2, diff_context,
3845 ignore_whitespace, repo, stdout);
3846 break;
3847 default:
3848 error = got_error(GOT_ERR_OBJ_TYPE);
3850 done:
3851 free(label1);
3852 free(label2);
3853 free(id1);
3854 free(id2);
3855 free(path);
3856 if (worktree)
3857 got_worktree_close(worktree);
3858 if (repo) {
3859 const struct got_error *repo_error;
3860 repo_error = got_repo_close(repo);
3861 if (error == NULL)
3862 error = repo_error;
3864 return error;
3867 __dead static void
3868 usage_blame(void)
3870 fprintf(stderr,
3871 "usage: %s blame [-c commit] [-r repository-path] path\n",
3872 getprogname());
3873 exit(1);
3876 struct blame_line {
3877 int annotated;
3878 char *id_str;
3879 char *committer;
3880 char datebuf[11]; /* YYYY-MM-DD + NUL */
3883 struct blame_cb_args {
3884 struct blame_line *lines;
3885 int nlines;
3886 int nlines_prec;
3887 int lineno_cur;
3888 off_t *line_offsets;
3889 FILE *f;
3890 struct got_repository *repo;
3893 static const struct got_error *
3894 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
3896 const struct got_error *err = NULL;
3897 struct blame_cb_args *a = arg;
3898 struct blame_line *bline;
3899 char *line = NULL;
3900 size_t linesize = 0;
3901 struct got_commit_object *commit = NULL;
3902 off_t offset;
3903 struct tm tm;
3904 time_t committer_time;
3906 if (nlines != a->nlines ||
3907 (lineno != -1 && lineno < 1) || lineno > a->nlines)
3908 return got_error(GOT_ERR_RANGE);
3910 if (sigint_received)
3911 return got_error(GOT_ERR_ITER_COMPLETED);
3913 if (lineno == -1)
3914 return NULL; /* no change in this commit */
3916 /* Annotate this line. */
3917 bline = &a->lines[lineno - 1];
3918 if (bline->annotated)
3919 return NULL;
3920 err = got_object_id_str(&bline->id_str, id);
3921 if (err)
3922 return err;
3924 err = got_object_open_as_commit(&commit, a->repo, id);
3925 if (err)
3926 goto done;
3928 bline->committer = strdup(got_object_commit_get_committer(commit));
3929 if (bline->committer == NULL) {
3930 err = got_error_from_errno("strdup");
3931 goto done;
3934 committer_time = got_object_commit_get_committer_time(commit);
3935 if (localtime_r(&committer_time, &tm) == NULL)
3936 return got_error_from_errno("localtime_r");
3937 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
3938 &tm) >= sizeof(bline->datebuf)) {
3939 err = got_error(GOT_ERR_NO_SPACE);
3940 goto done;
3942 bline->annotated = 1;
3944 /* Print lines annotated so far. */
3945 bline = &a->lines[a->lineno_cur - 1];
3946 if (!bline->annotated)
3947 goto done;
3949 offset = a->line_offsets[a->lineno_cur - 1];
3950 if (fseeko(a->f, offset, SEEK_SET) == -1) {
3951 err = got_error_from_errno("fseeko");
3952 goto done;
3955 while (bline->annotated) {
3956 char *smallerthan, *at, *nl, *committer;
3957 size_t len;
3959 if (getline(&line, &linesize, a->f) == -1) {
3960 if (ferror(a->f))
3961 err = got_error_from_errno("getline");
3962 break;
3965 committer = bline->committer;
3966 smallerthan = strchr(committer, '<');
3967 if (smallerthan && smallerthan[1] != '\0')
3968 committer = smallerthan + 1;
3969 at = strchr(committer, '@');
3970 if (at)
3971 *at = '\0';
3972 len = strlen(committer);
3973 if (len >= 9)
3974 committer[8] = '\0';
3976 nl = strchr(line, '\n');
3977 if (nl)
3978 *nl = '\0';
3979 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
3980 bline->id_str, bline->datebuf, committer, line);
3982 a->lineno_cur++;
3983 bline = &a->lines[a->lineno_cur - 1];
3985 done:
3986 if (commit)
3987 got_object_commit_close(commit);
3988 free(line);
3989 return err;
3992 static const struct got_error *
3993 cmd_blame(int argc, char *argv[])
3995 const struct got_error *error;
3996 struct got_repository *repo = NULL;
3997 struct got_worktree *worktree = NULL;
3998 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
3999 struct got_object_id *obj_id = NULL;
4000 struct got_object_id *commit_id = NULL;
4001 struct got_blob_object *blob = NULL;
4002 char *commit_id_str = NULL;
4003 struct blame_cb_args bca;
4004 int ch, obj_type, i;
4005 size_t filesize;
4007 memset(&bca, 0, sizeof(bca));
4009 #ifndef PROFILE
4010 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4011 NULL) == -1)
4012 err(1, "pledge");
4013 #endif
4015 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4016 switch (ch) {
4017 case 'c':
4018 commit_id_str = optarg;
4019 break;
4020 case 'r':
4021 repo_path = realpath(optarg, NULL);
4022 if (repo_path == NULL)
4023 return got_error_from_errno2("realpath",
4024 optarg);
4025 got_path_strip_trailing_slashes(repo_path);
4026 break;
4027 default:
4028 usage_blame();
4029 /* NOTREACHED */
4033 argc -= optind;
4034 argv += optind;
4036 if (argc == 1)
4037 path = argv[0];
4038 else
4039 usage_blame();
4041 cwd = getcwd(NULL, 0);
4042 if (cwd == NULL) {
4043 error = got_error_from_errno("getcwd");
4044 goto done;
4046 if (repo_path == NULL) {
4047 error = got_worktree_open(&worktree, cwd);
4048 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4049 goto done;
4050 else
4051 error = NULL;
4052 if (worktree) {
4053 repo_path =
4054 strdup(got_worktree_get_repo_path(worktree));
4055 if (repo_path == NULL) {
4056 error = got_error_from_errno("strdup");
4057 if (error)
4058 goto done;
4060 } else {
4061 repo_path = strdup(cwd);
4062 if (repo_path == NULL) {
4063 error = got_error_from_errno("strdup");
4064 goto done;
4069 error = got_repo_open(&repo, repo_path, NULL);
4070 if (error != NULL)
4071 goto done;
4073 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4074 if (error)
4075 goto done;
4077 if (worktree) {
4078 const char *prefix = got_worktree_get_path_prefix(worktree);
4079 char *p, *worktree_subdir = cwd +
4080 strlen(got_worktree_get_root_path(worktree));
4081 if (asprintf(&p, "%s%s%s%s%s",
4082 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
4083 worktree_subdir, worktree_subdir[0] ? "/" : "",
4084 path) == -1) {
4085 error = got_error_from_errno("asprintf");
4086 goto done;
4088 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4089 free(p);
4090 } else {
4091 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4093 if (error)
4094 goto done;
4096 if (commit_id_str == NULL) {
4097 struct got_reference *head_ref;
4098 error = got_ref_open(&head_ref, repo, worktree ?
4099 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4100 if (error != NULL)
4101 goto done;
4102 error = got_ref_resolve(&commit_id, repo, head_ref);
4103 got_ref_close(head_ref);
4104 if (error != NULL)
4105 goto done;
4106 } else {
4107 error = got_repo_match_object_id(&commit_id, NULL,
4108 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4109 if (error)
4110 goto done;
4113 error = got_object_id_by_path(&obj_id, repo, commit_id, in_repo_path);
4114 if (error)
4115 goto done;
4117 error = got_object_get_type(&obj_type, repo, obj_id);
4118 if (error)
4119 goto done;
4121 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4122 error = got_error(GOT_ERR_OBJ_TYPE);
4123 goto done;
4126 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4127 if (error)
4128 goto done;
4129 bca.f = got_opentemp();
4130 if (bca.f == NULL) {
4131 error = got_error_from_errno("got_opentemp");
4132 goto done;
4134 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4135 &bca.line_offsets, bca.f, blob);
4136 if (error || bca.nlines == 0)
4137 goto done;
4139 /* Don't include \n at EOF in the blame line count. */
4140 if (bca.line_offsets[bca.nlines - 1] == filesize)
4141 bca.nlines--;
4143 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4144 if (bca.lines == NULL) {
4145 error = got_error_from_errno("calloc");
4146 goto done;
4148 bca.lineno_cur = 1;
4149 bca.nlines_prec = 0;
4150 i = bca.nlines;
4151 while (i > 0) {
4152 i /= 10;
4153 bca.nlines_prec++;
4155 bca.repo = repo;
4157 error = got_blame(in_repo_path, commit_id, repo, blame_cb, &bca,
4158 check_cancelled, NULL);
4159 done:
4160 free(in_repo_path);
4161 free(repo_path);
4162 free(cwd);
4163 free(commit_id);
4164 free(obj_id);
4165 if (blob)
4166 got_object_blob_close(blob);
4167 if (worktree)
4168 got_worktree_close(worktree);
4169 if (repo) {
4170 const struct got_error *repo_error;
4171 repo_error = got_repo_close(repo);
4172 if (error == NULL)
4173 error = repo_error;
4175 if (bca.lines) {
4176 for (i = 0; i < bca.nlines; i++) {
4177 struct blame_line *bline = &bca.lines[i];
4178 free(bline->id_str);
4179 free(bline->committer);
4181 free(bca.lines);
4183 free(bca.line_offsets);
4184 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4185 error = got_error_from_errno("fclose");
4186 return error;
4189 __dead static void
4190 usage_tree(void)
4192 fprintf(stderr,
4193 "usage: %s tree [-c commit] [-r repository-path] [-iR] path\n",
4194 getprogname());
4195 exit(1);
4198 static void
4199 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4200 const char *root_path)
4202 int is_root_path = (strcmp(path, root_path) == 0);
4203 const char *modestr = "";
4204 mode_t mode = got_tree_entry_get_mode(te);
4206 path += strlen(root_path);
4207 while (path[0] == '/')
4208 path++;
4210 if (got_object_tree_entry_is_submodule(te))
4211 modestr = "$";
4212 else if (S_ISLNK(mode))
4213 modestr = "@";
4214 else if (S_ISDIR(mode))
4215 modestr = "/";
4216 else if (mode & S_IXUSR)
4217 modestr = "*";
4219 printf("%s%s%s%s%s\n", id ? id : "", path,
4220 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr);
4223 static const struct got_error *
4224 print_tree(const char *path, struct got_object_id *commit_id,
4225 int show_ids, int recurse, const char *root_path,
4226 struct got_repository *repo)
4228 const struct got_error *err = NULL;
4229 struct got_object_id *tree_id = NULL;
4230 struct got_tree_object *tree = NULL;
4231 int nentries, i;
4233 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4234 if (err)
4235 goto done;
4237 err = got_object_open_as_tree(&tree, repo, tree_id);
4238 if (err)
4239 goto done;
4240 nentries = got_object_tree_get_nentries(tree);
4241 for (i = 0; i < nentries; i++) {
4242 struct got_tree_entry *te;
4243 char *id = NULL;
4245 if (sigint_received || sigpipe_received)
4246 break;
4248 te = got_object_tree_get_entry(tree, i);
4249 if (show_ids) {
4250 char *id_str;
4251 err = got_object_id_str(&id_str,
4252 got_tree_entry_get_id(te));
4253 if (err)
4254 goto done;
4255 if (asprintf(&id, "%s ", id_str) == -1) {
4256 err = got_error_from_errno("asprintf");
4257 free(id_str);
4258 goto done;
4260 free(id_str);
4262 print_entry(te, id, path, root_path);
4263 free(id);
4265 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4266 char *child_path;
4267 if (asprintf(&child_path, "%s%s%s", path,
4268 path[0] == '/' && path[1] == '\0' ? "" : "/",
4269 got_tree_entry_get_name(te)) == -1) {
4270 err = got_error_from_errno("asprintf");
4271 goto done;
4273 err = print_tree(child_path, commit_id, show_ids, 1,
4274 root_path, repo);
4275 free(child_path);
4276 if (err)
4277 goto done;
4280 done:
4281 if (tree)
4282 got_object_tree_close(tree);
4283 free(tree_id);
4284 return err;
4287 static const struct got_error *
4288 cmd_tree(int argc, char *argv[])
4290 const struct got_error *error;
4291 struct got_repository *repo = NULL;
4292 struct got_worktree *worktree = NULL;
4293 const char *path, *refname = NULL;
4294 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4295 struct got_object_id *commit_id = NULL;
4296 char *commit_id_str = NULL;
4297 int show_ids = 0, recurse = 0;
4298 int ch;
4300 #ifndef PROFILE
4301 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4302 NULL) == -1)
4303 err(1, "pledge");
4304 #endif
4306 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4307 switch (ch) {
4308 case 'c':
4309 commit_id_str = optarg;
4310 break;
4311 case 'r':
4312 repo_path = realpath(optarg, NULL);
4313 if (repo_path == NULL)
4314 return got_error_from_errno2("realpath",
4315 optarg);
4316 got_path_strip_trailing_slashes(repo_path);
4317 break;
4318 case 'i':
4319 show_ids = 1;
4320 break;
4321 case 'R':
4322 recurse = 1;
4323 break;
4324 default:
4325 usage_tree();
4326 /* NOTREACHED */
4330 argc -= optind;
4331 argv += optind;
4333 if (argc == 1)
4334 path = argv[0];
4335 else if (argc > 1)
4336 usage_tree();
4337 else
4338 path = NULL;
4340 cwd = getcwd(NULL, 0);
4341 if (cwd == NULL) {
4342 error = got_error_from_errno("getcwd");
4343 goto done;
4345 if (repo_path == NULL) {
4346 error = got_worktree_open(&worktree, cwd);
4347 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4348 goto done;
4349 else
4350 error = NULL;
4351 if (worktree) {
4352 repo_path =
4353 strdup(got_worktree_get_repo_path(worktree));
4354 if (repo_path == NULL)
4355 error = got_error_from_errno("strdup");
4356 if (error)
4357 goto done;
4358 } else {
4359 repo_path = strdup(cwd);
4360 if (repo_path == NULL) {
4361 error = got_error_from_errno("strdup");
4362 goto done;
4367 error = got_repo_open(&repo, repo_path, NULL);
4368 if (error != NULL)
4369 goto done;
4371 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4372 if (error)
4373 goto done;
4375 if (path == NULL) {
4376 if (worktree) {
4377 char *p, *worktree_subdir = cwd +
4378 strlen(got_worktree_get_root_path(worktree));
4379 if (asprintf(&p, "%s/%s",
4380 got_worktree_get_path_prefix(worktree),
4381 worktree_subdir) == -1) {
4382 error = got_error_from_errno("asprintf");
4383 goto done;
4385 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4386 free(p);
4387 if (error)
4388 goto done;
4389 } else
4390 path = "/";
4392 if (in_repo_path == NULL) {
4393 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4394 if (error != NULL)
4395 goto done;
4398 if (commit_id_str == NULL) {
4399 struct got_reference *head_ref;
4400 if (worktree)
4401 refname = got_worktree_get_head_ref_name(worktree);
4402 else
4403 refname = GOT_REF_HEAD;
4404 error = got_ref_open(&head_ref, repo, refname, 0);
4405 if (error != NULL)
4406 goto done;
4407 error = got_ref_resolve(&commit_id, repo, head_ref);
4408 got_ref_close(head_ref);
4409 if (error != NULL)
4410 goto done;
4411 } else {
4412 error = got_repo_match_object_id(&commit_id, NULL,
4413 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4414 if (error)
4415 goto done;
4418 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4419 in_repo_path, repo);
4420 done:
4421 free(in_repo_path);
4422 free(repo_path);
4423 free(cwd);
4424 free(commit_id);
4425 if (worktree)
4426 got_worktree_close(worktree);
4427 if (repo) {
4428 const struct got_error *repo_error;
4429 repo_error = got_repo_close(repo);
4430 if (error == NULL)
4431 error = repo_error;
4433 return error;
4436 __dead static void
4437 usage_status(void)
4439 fprintf(stderr, "usage: %s status [path ...]\n", getprogname());
4440 exit(1);
4443 static const struct got_error *
4444 print_status(void *arg, unsigned char status, unsigned char staged_status,
4445 const char *path, struct got_object_id *blob_id,
4446 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4447 int dirfd, const char *de_name)
4449 if (status == staged_status && (status == GOT_STATUS_DELETE))
4450 status = GOT_STATUS_NO_CHANGE;
4451 printf("%c%c %s\n", status, staged_status, path);
4452 return NULL;
4455 static const struct got_error *
4456 cmd_status(int argc, char *argv[])
4458 const struct got_error *error = NULL;
4459 struct got_repository *repo = NULL;
4460 struct got_worktree *worktree = NULL;
4461 char *cwd = NULL;
4462 struct got_pathlist_head paths;
4463 struct got_pathlist_entry *pe;
4464 int ch;
4466 TAILQ_INIT(&paths);
4468 while ((ch = getopt(argc, argv, "")) != -1) {
4469 switch (ch) {
4470 default:
4471 usage_status();
4472 /* NOTREACHED */
4476 argc -= optind;
4477 argv += optind;
4479 #ifndef PROFILE
4480 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4481 NULL) == -1)
4482 err(1, "pledge");
4483 #endif
4484 cwd = getcwd(NULL, 0);
4485 if (cwd == NULL) {
4486 error = got_error_from_errno("getcwd");
4487 goto done;
4490 error = got_worktree_open(&worktree, cwd);
4491 if (error) {
4492 if (error->code == GOT_ERR_NOT_WORKTREE)
4493 error = wrap_not_worktree_error(error, "status", cwd);
4494 goto done;
4497 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4498 NULL);
4499 if (error != NULL)
4500 goto done;
4502 error = apply_unveil(got_repo_get_path(repo), 1,
4503 got_worktree_get_root_path(worktree));
4504 if (error)
4505 goto done;
4507 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
4508 if (error)
4509 goto done;
4511 error = got_worktree_status(worktree, &paths, repo, print_status, NULL,
4512 check_cancelled, NULL);
4513 done:
4514 TAILQ_FOREACH(pe, &paths, entry)
4515 free((char *)pe->path);
4516 got_pathlist_free(&paths);
4517 free(cwd);
4518 return error;
4521 __dead static void
4522 usage_ref(void)
4524 fprintf(stderr,
4525 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
4526 "[-d] [name]\n",
4527 getprogname());
4528 exit(1);
4531 static const struct got_error *
4532 list_refs(struct got_repository *repo, const char *refname)
4534 static const struct got_error *err = NULL;
4535 struct got_reflist_head refs;
4536 struct got_reflist_entry *re;
4538 SIMPLEQ_INIT(&refs);
4539 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
4540 if (err)
4541 return err;
4543 SIMPLEQ_FOREACH(re, &refs, entry) {
4544 char *refstr;
4545 refstr = got_ref_to_str(re->ref);
4546 if (refstr == NULL)
4547 return got_error_from_errno("got_ref_to_str");
4548 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
4549 free(refstr);
4552 got_ref_list_free(&refs);
4553 return NULL;
4556 static const struct got_error *
4557 delete_ref(struct got_repository *repo, const char *refname)
4559 const struct got_error *err = NULL;
4560 struct got_reference *ref;
4562 err = got_ref_open(&ref, repo, refname, 0);
4563 if (err)
4564 return err;
4566 err = got_ref_delete(ref, repo);
4567 got_ref_close(ref);
4568 return err;
4571 static const struct got_error *
4572 add_ref(struct got_repository *repo, const char *refname, const char *target)
4574 const struct got_error *err = NULL;
4575 struct got_object_id *id;
4576 struct got_reference *ref = NULL;
4579 * Don't let the user create a reference name with a leading '-'.
4580 * While technically a valid reference name, this case is usually
4581 * an unintended typo.
4583 if (refname[0] == '-')
4584 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4586 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
4587 repo);
4588 if (err) {
4589 struct got_reference *target_ref;
4591 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
4592 return err;
4593 err = got_ref_open(&target_ref, repo, target, 0);
4594 if (err)
4595 return err;
4596 err = got_ref_resolve(&id, repo, target_ref);
4597 got_ref_close(target_ref);
4598 if (err)
4599 return err;
4602 err = got_ref_alloc(&ref, refname, id);
4603 if (err)
4604 goto done;
4606 err = got_ref_write(ref, repo);
4607 done:
4608 if (ref)
4609 got_ref_close(ref);
4610 free(id);
4611 return err;
4614 static const struct got_error *
4615 add_symref(struct got_repository *repo, const char *refname, const char *target)
4617 const struct got_error *err = NULL;
4618 struct got_reference *ref = NULL;
4619 struct got_reference *target_ref = NULL;
4622 * Don't let the user create a reference name with a leading '-'.
4623 * While technically a valid reference name, this case is usually
4624 * an unintended typo.
4626 if (refname[0] == '-')
4627 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4629 err = got_ref_open(&target_ref, repo, target, 0);
4630 if (err)
4631 return err;
4633 err = got_ref_alloc_symref(&ref, refname, target_ref);
4634 if (err)
4635 goto done;
4637 err = got_ref_write(ref, repo);
4638 done:
4639 if (target_ref)
4640 got_ref_close(target_ref);
4641 if (ref)
4642 got_ref_close(ref);
4643 return err;
4646 static const struct got_error *
4647 cmd_ref(int argc, char *argv[])
4649 const struct got_error *error = NULL;
4650 struct got_repository *repo = NULL;
4651 struct got_worktree *worktree = NULL;
4652 char *cwd = NULL, *repo_path = NULL;
4653 int ch, do_list = 0, do_delete = 0;
4654 const char *obj_arg = NULL, *symref_target= NULL;
4655 char *refname = NULL;
4657 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
4658 switch (ch) {
4659 case 'c':
4660 obj_arg = optarg;
4661 break;
4662 case 'd':
4663 do_delete = 1;
4664 break;
4665 case 'r':
4666 repo_path = realpath(optarg, NULL);
4667 if (repo_path == NULL)
4668 return got_error_from_errno2("realpath",
4669 optarg);
4670 got_path_strip_trailing_slashes(repo_path);
4671 break;
4672 case 'l':
4673 do_list = 1;
4674 break;
4675 case 's':
4676 symref_target = optarg;
4677 break;
4678 default:
4679 usage_ref();
4680 /* NOTREACHED */
4684 if (obj_arg && do_list)
4685 errx(1, "-c and -l options are mutually exclusive");
4686 if (obj_arg && do_delete)
4687 errx(1, "-c and -d options are mutually exclusive");
4688 if (obj_arg && symref_target)
4689 errx(1, "-c and -s options are mutually exclusive");
4690 if (symref_target && do_delete)
4691 errx(1, "-s and -d options are mutually exclusive");
4692 if (symref_target && do_list)
4693 errx(1, "-s and -l options are mutually exclusive");
4694 if (do_delete && do_list)
4695 errx(1, "-d and -l options are mutually exclusive");
4697 argc -= optind;
4698 argv += optind;
4700 if (do_list) {
4701 if (argc != 0 && argc != 1)
4702 usage_ref();
4703 if (argc == 1) {
4704 refname = strdup(argv[0]);
4705 if (refname == NULL) {
4706 error = got_error_from_errno("strdup");
4707 goto done;
4710 } else {
4711 if (argc != 1)
4712 usage_ref();
4713 refname = strdup(argv[0]);
4714 if (refname == NULL) {
4715 error = got_error_from_errno("strdup");
4716 goto done;
4720 if (refname)
4721 got_path_strip_trailing_slashes(refname);
4723 #ifndef PROFILE
4724 if (do_list) {
4725 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4726 NULL) == -1)
4727 err(1, "pledge");
4728 } else {
4729 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4730 "sendfd unveil", NULL) == -1)
4731 err(1, "pledge");
4733 #endif
4734 cwd = getcwd(NULL, 0);
4735 if (cwd == NULL) {
4736 error = got_error_from_errno("getcwd");
4737 goto done;
4740 if (repo_path == NULL) {
4741 error = got_worktree_open(&worktree, cwd);
4742 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4743 goto done;
4744 else
4745 error = NULL;
4746 if (worktree) {
4747 repo_path =
4748 strdup(got_worktree_get_repo_path(worktree));
4749 if (repo_path == NULL)
4750 error = got_error_from_errno("strdup");
4751 if (error)
4752 goto done;
4753 } else {
4754 repo_path = strdup(cwd);
4755 if (repo_path == NULL) {
4756 error = got_error_from_errno("strdup");
4757 goto done;
4762 error = got_repo_open(&repo, repo_path, NULL);
4763 if (error != NULL)
4764 goto done;
4766 error = apply_unveil(got_repo_get_path(repo), do_list,
4767 worktree ? got_worktree_get_root_path(worktree) : NULL);
4768 if (error)
4769 goto done;
4771 if (do_list)
4772 error = list_refs(repo, refname);
4773 else if (do_delete)
4774 error = delete_ref(repo, refname);
4775 else if (symref_target)
4776 error = add_symref(repo, refname, symref_target);
4777 else {
4778 if (obj_arg == NULL)
4779 usage_ref();
4780 error = add_ref(repo, refname, obj_arg);
4782 done:
4783 free(refname);
4784 if (repo)
4785 got_repo_close(repo);
4786 if (worktree)
4787 got_worktree_close(worktree);
4788 free(cwd);
4789 free(repo_path);
4790 return error;
4793 __dead static void
4794 usage_branch(void)
4796 fprintf(stderr,
4797 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
4798 "[name]\n", getprogname());
4799 exit(1);
4802 static const struct got_error *
4803 list_branch(struct got_repository *repo, struct got_worktree *worktree,
4804 struct got_reference *ref)
4806 const struct got_error *err = NULL;
4807 const char *refname, *marker = " ";
4808 char *refstr;
4810 refname = got_ref_get_name(ref);
4811 if (worktree && strcmp(refname,
4812 got_worktree_get_head_ref_name(worktree)) == 0) {
4813 struct got_object_id *id = NULL;
4815 err = got_ref_resolve(&id, repo, ref);
4816 if (err)
4817 return err;
4818 if (got_object_id_cmp(id,
4819 got_worktree_get_base_commit_id(worktree)) == 0)
4820 marker = "* ";
4821 else
4822 marker = "~ ";
4823 free(id);
4826 if (strncmp(refname, "refs/heads/", 11) == 0)
4827 refname += 11;
4828 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4829 refname += 18;
4831 refstr = got_ref_to_str(ref);
4832 if (refstr == NULL)
4833 return got_error_from_errno("got_ref_to_str");
4835 printf("%s%s: %s\n", marker, refname, refstr);
4836 free(refstr);
4837 return NULL;
4840 static const struct got_error *
4841 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
4843 const char *refname;
4845 if (worktree == NULL)
4846 return got_error(GOT_ERR_NOT_WORKTREE);
4848 refname = got_worktree_get_head_ref_name(worktree);
4850 if (strncmp(refname, "refs/heads/", 11) == 0)
4851 refname += 11;
4852 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4853 refname += 18;
4855 printf("%s\n", refname);
4857 return NULL;
4860 static const struct got_error *
4861 list_branches(struct got_repository *repo, struct got_worktree *worktree)
4863 static const struct got_error *err = NULL;
4864 struct got_reflist_head refs;
4865 struct got_reflist_entry *re;
4866 struct got_reference *temp_ref = NULL;
4867 int rebase_in_progress, histedit_in_progress;
4869 SIMPLEQ_INIT(&refs);
4871 if (worktree) {
4872 err = got_worktree_rebase_in_progress(&rebase_in_progress,
4873 worktree);
4874 if (err)
4875 return err;
4877 err = got_worktree_histedit_in_progress(&histedit_in_progress,
4878 worktree);
4879 if (err)
4880 return err;
4882 if (rebase_in_progress || histedit_in_progress) {
4883 err = got_ref_open(&temp_ref, repo,
4884 got_worktree_get_head_ref_name(worktree), 0);
4885 if (err)
4886 return err;
4887 list_branch(repo, worktree, temp_ref);
4888 got_ref_close(temp_ref);
4892 err = got_ref_list(&refs, repo, "refs/heads",
4893 got_ref_cmp_by_name, NULL);
4894 if (err)
4895 return err;
4897 SIMPLEQ_FOREACH(re, &refs, entry)
4898 list_branch(repo, worktree, re->ref);
4900 got_ref_list_free(&refs);
4901 return NULL;
4904 static const struct got_error *
4905 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
4906 const char *branch_name)
4908 const struct got_error *err = NULL;
4909 struct got_reference *ref = NULL;
4910 char *refname;
4912 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
4913 return got_error_from_errno("asprintf");
4915 err = got_ref_open(&ref, repo, refname, 0);
4916 if (err)
4917 goto done;
4919 if (worktree &&
4920 strcmp(got_worktree_get_head_ref_name(worktree),
4921 got_ref_get_name(ref)) == 0) {
4922 err = got_error_msg(GOT_ERR_SAME_BRANCH,
4923 "will not delete this work tree's current branch");
4924 goto done;
4927 err = got_ref_delete(ref, repo);
4928 done:
4929 if (ref)
4930 got_ref_close(ref);
4931 free(refname);
4932 return err;
4935 static const struct got_error *
4936 add_branch(struct got_repository *repo, const char *branch_name,
4937 struct got_object_id *base_commit_id)
4939 const struct got_error *err = NULL;
4940 struct got_reference *ref = NULL;
4941 char *base_refname = NULL, *refname = NULL;
4944 * Don't let the user create a branch name with a leading '-'.
4945 * While technically a valid reference name, this case is usually
4946 * an unintended typo.
4948 if (branch_name[0] == '-')
4949 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
4951 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
4952 err = got_error_from_errno("asprintf");
4953 goto done;
4956 err = got_ref_open(&ref, repo, refname, 0);
4957 if (err == NULL) {
4958 err = got_error(GOT_ERR_BRANCH_EXISTS);
4959 goto done;
4960 } else if (err->code != GOT_ERR_NOT_REF)
4961 goto done;
4963 err = got_ref_alloc(&ref, refname, base_commit_id);
4964 if (err)
4965 goto done;
4967 err = got_ref_write(ref, repo);
4968 done:
4969 if (ref)
4970 got_ref_close(ref);
4971 free(base_refname);
4972 free(refname);
4973 return err;
4976 static const struct got_error *
4977 cmd_branch(int argc, char *argv[])
4979 const struct got_error *error = NULL;
4980 struct got_repository *repo = NULL;
4981 struct got_worktree *worktree = NULL;
4982 char *cwd = NULL, *repo_path = NULL;
4983 int ch, do_list = 0, do_show = 0, do_update = 1;
4984 const char *delref = NULL, *commit_id_arg = NULL;
4985 struct got_reference *ref = NULL;
4986 struct got_pathlist_head paths;
4987 struct got_pathlist_entry *pe;
4988 struct got_object_id *commit_id = NULL;
4989 char *commit_id_str = NULL;
4991 TAILQ_INIT(&paths);
4993 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
4994 switch (ch) {
4995 case 'c':
4996 commit_id_arg = optarg;
4997 break;
4998 case 'd':
4999 delref = optarg;
5000 break;
5001 case 'r':
5002 repo_path = realpath(optarg, NULL);
5003 if (repo_path == NULL)
5004 return got_error_from_errno2("realpath",
5005 optarg);
5006 got_path_strip_trailing_slashes(repo_path);
5007 break;
5008 case 'l':
5009 do_list = 1;
5010 break;
5011 case 'n':
5012 do_update = 0;
5013 break;
5014 default:
5015 usage_branch();
5016 /* NOTREACHED */
5020 if (do_list && delref)
5021 errx(1, "-l and -d options are mutually exclusive");
5023 argc -= optind;
5024 argv += optind;
5026 if (!do_list && !delref && argc == 0)
5027 do_show = 1;
5029 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5030 errx(1, "-c option can only be used when creating a branch");
5032 if (do_list || delref) {
5033 if (argc > 0)
5034 usage_branch();
5035 } else if (!do_show && argc != 1)
5036 usage_branch();
5038 #ifndef PROFILE
5039 if (do_list || do_show) {
5040 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5041 NULL) == -1)
5042 err(1, "pledge");
5043 } else {
5044 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5045 "sendfd unveil", NULL) == -1)
5046 err(1, "pledge");
5048 #endif
5049 cwd = getcwd(NULL, 0);
5050 if (cwd == NULL) {
5051 error = got_error_from_errno("getcwd");
5052 goto done;
5055 if (repo_path == NULL) {
5056 error = got_worktree_open(&worktree, cwd);
5057 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5058 goto done;
5059 else
5060 error = NULL;
5061 if (worktree) {
5062 repo_path =
5063 strdup(got_worktree_get_repo_path(worktree));
5064 if (repo_path == NULL)
5065 error = got_error_from_errno("strdup");
5066 if (error)
5067 goto done;
5068 } else {
5069 repo_path = strdup(cwd);
5070 if (repo_path == NULL) {
5071 error = got_error_from_errno("strdup");
5072 goto done;
5077 error = got_repo_open(&repo, repo_path, NULL);
5078 if (error != NULL)
5079 goto done;
5081 error = apply_unveil(got_repo_get_path(repo), do_list,
5082 worktree ? got_worktree_get_root_path(worktree) : NULL);
5083 if (error)
5084 goto done;
5086 if (do_show)
5087 error = show_current_branch(repo, worktree);
5088 else if (do_list)
5089 error = list_branches(repo, worktree);
5090 else if (delref)
5091 error = delete_branch(repo, worktree, delref);
5092 else {
5093 if (commit_id_arg == NULL)
5094 commit_id_arg = worktree ?
5095 got_worktree_get_head_ref_name(worktree) :
5096 GOT_REF_HEAD;
5097 error = got_repo_match_object_id(&commit_id, NULL,
5098 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5099 if (error)
5100 goto done;
5101 error = add_branch(repo, argv[0], commit_id);
5102 if (error)
5103 goto done;
5104 if (worktree && do_update) {
5105 struct got_update_progress_arg upa;
5106 char *branch_refname = NULL;
5108 error = got_object_id_str(&commit_id_str, commit_id);
5109 if (error)
5110 goto done;
5111 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5112 worktree);
5113 if (error)
5114 goto done;
5115 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5116 == -1) {
5117 error = got_error_from_errno("asprintf");
5118 goto done;
5120 error = got_ref_open(&ref, repo, branch_refname, 0);
5121 free(branch_refname);
5122 if (error)
5123 goto done;
5124 error = switch_head_ref(ref, commit_id, worktree,
5125 repo);
5126 if (error)
5127 goto done;
5128 error = got_worktree_set_base_commit_id(worktree, repo,
5129 commit_id);
5130 if (error)
5131 goto done;
5132 memset(&upa, 0, sizeof(upa));
5133 error = got_worktree_checkout_files(worktree, &paths,
5134 repo, update_progress, &upa, check_cancelled,
5135 NULL);
5136 if (error)
5137 goto done;
5138 if (upa.did_something)
5139 printf("Updated to commit %s\n", commit_id_str);
5140 print_update_progress_stats(&upa);
5143 done:
5144 if (ref)
5145 got_ref_close(ref);
5146 if (repo)
5147 got_repo_close(repo);
5148 if (worktree)
5149 got_worktree_close(worktree);
5150 free(cwd);
5151 free(repo_path);
5152 free(commit_id);
5153 free(commit_id_str);
5154 TAILQ_FOREACH(pe, &paths, entry)
5155 free((char *)pe->path);
5156 got_pathlist_free(&paths);
5157 return error;
5161 __dead static void
5162 usage_tag(void)
5164 fprintf(stderr,
5165 "usage: %s tag [-c commit] [-r repository] [-l] "
5166 "[-m message] name\n", getprogname());
5167 exit(1);
5170 #if 0
5171 static const struct got_error *
5172 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5174 const struct got_error *err = NULL;
5175 struct got_reflist_entry *re, *se, *new;
5176 struct got_object_id *re_id, *se_id;
5177 struct got_tag_object *re_tag, *se_tag;
5178 time_t re_time, se_time;
5180 SIMPLEQ_FOREACH(re, tags, entry) {
5181 se = SIMPLEQ_FIRST(sorted);
5182 if (se == NULL) {
5183 err = got_reflist_entry_dup(&new, re);
5184 if (err)
5185 return err;
5186 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5187 continue;
5188 } else {
5189 err = got_ref_resolve(&re_id, repo, re->ref);
5190 if (err)
5191 break;
5192 err = got_object_open_as_tag(&re_tag, repo, re_id);
5193 free(re_id);
5194 if (err)
5195 break;
5196 re_time = got_object_tag_get_tagger_time(re_tag);
5197 got_object_tag_close(re_tag);
5200 while (se) {
5201 err = got_ref_resolve(&se_id, repo, re->ref);
5202 if (err)
5203 break;
5204 err = got_object_open_as_tag(&se_tag, repo, se_id);
5205 free(se_id);
5206 if (err)
5207 break;
5208 se_time = got_object_tag_get_tagger_time(se_tag);
5209 got_object_tag_close(se_tag);
5211 if (se_time > re_time) {
5212 err = got_reflist_entry_dup(&new, re);
5213 if (err)
5214 return err;
5215 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5216 break;
5218 se = SIMPLEQ_NEXT(se, entry);
5219 continue;
5222 done:
5223 return err;
5225 #endif
5227 static const struct got_error *
5228 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5230 static const struct got_error *err = NULL;
5231 struct got_reflist_head refs;
5232 struct got_reflist_entry *re;
5234 SIMPLEQ_INIT(&refs);
5236 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5237 if (err)
5238 return err;
5240 SIMPLEQ_FOREACH(re, &refs, entry) {
5241 const char *refname;
5242 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5243 char datebuf[26];
5244 const char *tagger;
5245 time_t tagger_time;
5246 struct got_object_id *id;
5247 struct got_tag_object *tag;
5248 struct got_commit_object *commit = NULL;
5250 refname = got_ref_get_name(re->ref);
5251 if (strncmp(refname, "refs/tags/", 10) != 0)
5252 continue;
5253 refname += 10;
5254 refstr = got_ref_to_str(re->ref);
5255 if (refstr == NULL) {
5256 err = got_error_from_errno("got_ref_to_str");
5257 break;
5259 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5260 free(refstr);
5262 err = got_ref_resolve(&id, repo, re->ref);
5263 if (err)
5264 break;
5265 err = got_object_open_as_tag(&tag, repo, id);
5266 if (err) {
5267 if (err->code != GOT_ERR_OBJ_TYPE) {
5268 free(id);
5269 break;
5271 /* "lightweight" tag */
5272 err = got_object_open_as_commit(&commit, repo, id);
5273 if (err) {
5274 free(id);
5275 break;
5277 tagger = got_object_commit_get_committer(commit);
5278 tagger_time =
5279 got_object_commit_get_committer_time(commit);
5280 err = got_object_id_str(&id_str, id);
5281 free(id);
5282 if (err)
5283 break;
5284 } else {
5285 free(id);
5286 tagger = got_object_tag_get_tagger(tag);
5287 tagger_time = got_object_tag_get_tagger_time(tag);
5288 err = got_object_id_str(&id_str,
5289 got_object_tag_get_object_id(tag));
5290 if (err)
5291 break;
5293 printf("from: %s\n", tagger);
5294 datestr = get_datestr(&tagger_time, datebuf);
5295 if (datestr)
5296 printf("date: %s UTC\n", datestr);
5297 if (commit)
5298 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5299 else {
5300 switch (got_object_tag_get_object_type(tag)) {
5301 case GOT_OBJ_TYPE_BLOB:
5302 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5303 id_str);
5304 break;
5305 case GOT_OBJ_TYPE_TREE:
5306 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5307 id_str);
5308 break;
5309 case GOT_OBJ_TYPE_COMMIT:
5310 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5311 id_str);
5312 break;
5313 case GOT_OBJ_TYPE_TAG:
5314 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5315 id_str);
5316 break;
5317 default:
5318 break;
5321 free(id_str);
5322 if (commit) {
5323 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5324 if (err)
5325 break;
5326 got_object_commit_close(commit);
5327 } else {
5328 tagmsg0 = strdup(got_object_tag_get_message(tag));
5329 got_object_tag_close(tag);
5330 if (tagmsg0 == NULL) {
5331 err = got_error_from_errno("strdup");
5332 break;
5336 tagmsg = tagmsg0;
5337 do {
5338 line = strsep(&tagmsg, "\n");
5339 if (line)
5340 printf(" %s\n", line);
5341 } while (line);
5342 free(tagmsg0);
5345 got_ref_list_free(&refs);
5346 return NULL;
5349 static const struct got_error *
5350 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5351 const char *tag_name, const char *repo_path)
5353 const struct got_error *err = NULL;
5354 char *template = NULL, *initial_content = NULL;
5355 char *editor = NULL;
5356 int fd = -1;
5358 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5359 err = got_error_from_errno("asprintf");
5360 goto done;
5363 if (asprintf(&initial_content, "\n# tagging commit %s as %s\n",
5364 commit_id_str, tag_name) == -1) {
5365 err = got_error_from_errno("asprintf");
5366 goto done;
5369 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5370 if (err)
5371 goto done;
5373 dprintf(fd, initial_content);
5374 close(fd);
5376 err = get_editor(&editor);
5377 if (err)
5378 goto done;
5379 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
5380 done:
5381 free(initial_content);
5382 free(template);
5383 free(editor);
5385 /* Editor is done; we can now apply unveil(2) */
5386 if (err == NULL) {
5387 err = apply_unveil(repo_path, 0, NULL);
5388 if (err) {
5389 free(*tagmsg);
5390 *tagmsg = NULL;
5393 return err;
5396 static const struct got_error *
5397 add_tag(struct got_repository *repo, const char *tag_name,
5398 const char *commit_arg, const char *tagmsg_arg)
5400 const struct got_error *err = NULL;
5401 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5402 char *label = NULL, *commit_id_str = NULL;
5403 struct got_reference *ref = NULL;
5404 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5405 char *tagmsg_path = NULL, *tag_id_str = NULL;
5406 int preserve_tagmsg = 0;
5409 * Don't let the user create a tag name with a leading '-'.
5410 * While technically a valid reference name, this case is usually
5411 * an unintended typo.
5413 if (tag_name[0] == '-')
5414 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5416 err = get_author(&tagger, repo);
5417 if (err)
5418 return err;
5420 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5421 GOT_OBJ_TYPE_COMMIT, 1, repo);
5422 if (err)
5423 goto done;
5425 err = got_object_id_str(&commit_id_str, commit_id);
5426 if (err)
5427 goto done;
5429 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5430 refname = strdup(tag_name);
5431 if (refname == NULL) {
5432 err = got_error_from_errno("strdup");
5433 goto done;
5435 tag_name += 10;
5436 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5437 err = got_error_from_errno("asprintf");
5438 goto done;
5441 err = got_ref_open(&ref, repo, refname, 0);
5442 if (err == NULL) {
5443 err = got_error(GOT_ERR_TAG_EXISTS);
5444 goto done;
5445 } else if (err->code != GOT_ERR_NOT_REF)
5446 goto done;
5448 if (tagmsg_arg == NULL) {
5449 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5450 tag_name, got_repo_get_path(repo));
5451 if (err) {
5452 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5453 tagmsg_path != NULL)
5454 preserve_tagmsg = 1;
5455 goto done;
5459 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5460 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5461 if (err) {
5462 if (tagmsg_path)
5463 preserve_tagmsg = 1;
5464 goto done;
5467 err = got_ref_alloc(&ref, refname, tag_id);
5468 if (err) {
5469 if (tagmsg_path)
5470 preserve_tagmsg = 1;
5471 goto done;
5474 err = got_ref_write(ref, repo);
5475 if (err) {
5476 if (tagmsg_path)
5477 preserve_tagmsg = 1;
5478 goto done;
5481 err = got_object_id_str(&tag_id_str, tag_id);
5482 if (err) {
5483 if (tagmsg_path)
5484 preserve_tagmsg = 1;
5485 goto done;
5487 printf("Created tag %s\n", tag_id_str);
5488 done:
5489 if (preserve_tagmsg) {
5490 fprintf(stderr, "%s: tag message preserved in %s\n",
5491 getprogname(), tagmsg_path);
5492 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
5493 err = got_error_from_errno2("unlink", tagmsg_path);
5494 free(tag_id_str);
5495 if (ref)
5496 got_ref_close(ref);
5497 free(commit_id);
5498 free(commit_id_str);
5499 free(refname);
5500 free(tagmsg);
5501 free(tagmsg_path);
5502 free(tagger);
5503 return err;
5506 static const struct got_error *
5507 cmd_tag(int argc, char *argv[])
5509 const struct got_error *error = NULL;
5510 struct got_repository *repo = NULL;
5511 struct got_worktree *worktree = NULL;
5512 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
5513 char *gitconfig_path = NULL;
5514 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
5515 int ch, do_list = 0;
5517 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
5518 switch (ch) {
5519 case 'c':
5520 commit_id_arg = optarg;
5521 break;
5522 case 'm':
5523 tagmsg = optarg;
5524 break;
5525 case 'r':
5526 repo_path = realpath(optarg, NULL);
5527 if (repo_path == NULL)
5528 return got_error_from_errno2("realpath",
5529 optarg);
5530 got_path_strip_trailing_slashes(repo_path);
5531 break;
5532 case 'l':
5533 do_list = 1;
5534 break;
5535 default:
5536 usage_tag();
5537 /* NOTREACHED */
5541 argc -= optind;
5542 argv += optind;
5544 if (do_list) {
5545 if (commit_id_arg != NULL)
5546 errx(1,
5547 "-c option can only be used when creating a tag");
5548 if (tagmsg)
5549 errx(1, "-l and -m options are mutually exclusive");
5550 if (argc > 0)
5551 usage_tag();
5552 } else if (argc != 1)
5553 usage_tag();
5555 tag_name = argv[0];
5557 #ifndef PROFILE
5558 if (do_list) {
5559 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5560 NULL) == -1)
5561 err(1, "pledge");
5562 } else {
5563 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5564 "sendfd unveil", NULL) == -1)
5565 err(1, "pledge");
5567 #endif
5568 cwd = getcwd(NULL, 0);
5569 if (cwd == NULL) {
5570 error = got_error_from_errno("getcwd");
5571 goto done;
5574 if (repo_path == NULL) {
5575 error = got_worktree_open(&worktree, cwd);
5576 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5577 goto done;
5578 else
5579 error = NULL;
5580 if (worktree) {
5581 repo_path =
5582 strdup(got_worktree_get_repo_path(worktree));
5583 if (repo_path == NULL)
5584 error = got_error_from_errno("strdup");
5585 if (error)
5586 goto done;
5587 } else {
5588 repo_path = strdup(cwd);
5589 if (repo_path == NULL) {
5590 error = got_error_from_errno("strdup");
5591 goto done;
5596 if (do_list) {
5597 error = got_repo_open(&repo, repo_path, NULL);
5598 if (error != NULL)
5599 goto done;
5600 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5601 if (error)
5602 goto done;
5603 error = list_tags(repo, worktree);
5604 } else {
5605 error = get_gitconfig_path(&gitconfig_path);
5606 if (error)
5607 goto done;
5608 error = got_repo_open(&repo, repo_path, gitconfig_path);
5609 if (error != NULL)
5610 goto done;
5612 if (tagmsg) {
5613 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5614 if (error)
5615 goto done;
5618 if (commit_id_arg == NULL) {
5619 struct got_reference *head_ref;
5620 struct got_object_id *commit_id;
5621 error = got_ref_open(&head_ref, repo,
5622 worktree ? got_worktree_get_head_ref_name(worktree)
5623 : GOT_REF_HEAD, 0);
5624 if (error)
5625 goto done;
5626 error = got_ref_resolve(&commit_id, repo, head_ref);
5627 got_ref_close(head_ref);
5628 if (error)
5629 goto done;
5630 error = got_object_id_str(&commit_id_str, commit_id);
5631 free(commit_id);
5632 if (error)
5633 goto done;
5636 error = add_tag(repo, tag_name,
5637 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
5639 done:
5640 if (repo)
5641 got_repo_close(repo);
5642 if (worktree)
5643 got_worktree_close(worktree);
5644 free(cwd);
5645 free(repo_path);
5646 free(gitconfig_path);
5647 free(commit_id_str);
5648 return error;
5651 __dead static void
5652 usage_add(void)
5654 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
5655 getprogname());
5656 exit(1);
5659 static const struct got_error *
5660 add_progress(void *arg, unsigned char status, const char *path)
5662 while (path[0] == '/')
5663 path++;
5664 printf("%c %s\n", status, path);
5665 return NULL;
5668 static const struct got_error *
5669 cmd_add(int argc, char *argv[])
5671 const struct got_error *error = NULL;
5672 struct got_repository *repo = NULL;
5673 struct got_worktree *worktree = NULL;
5674 char *cwd = NULL;
5675 struct got_pathlist_head paths;
5676 struct got_pathlist_entry *pe;
5677 int ch, can_recurse = 0, no_ignores = 0;
5679 TAILQ_INIT(&paths);
5681 while ((ch = getopt(argc, argv, "IR")) != -1) {
5682 switch (ch) {
5683 case 'I':
5684 no_ignores = 1;
5685 break;
5686 case 'R':
5687 can_recurse = 1;
5688 break;
5689 default:
5690 usage_add();
5691 /* NOTREACHED */
5695 argc -= optind;
5696 argv += optind;
5698 #ifndef PROFILE
5699 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5700 NULL) == -1)
5701 err(1, "pledge");
5702 #endif
5703 if (argc < 1)
5704 usage_add();
5706 cwd = getcwd(NULL, 0);
5707 if (cwd == NULL) {
5708 error = got_error_from_errno("getcwd");
5709 goto done;
5712 error = got_worktree_open(&worktree, cwd);
5713 if (error) {
5714 if (error->code == GOT_ERR_NOT_WORKTREE)
5715 error = wrap_not_worktree_error(error, "add", cwd);
5716 goto done;
5719 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5720 NULL);
5721 if (error != NULL)
5722 goto done;
5724 error = apply_unveil(got_repo_get_path(repo), 1,
5725 got_worktree_get_root_path(worktree));
5726 if (error)
5727 goto done;
5729 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5730 if (error)
5731 goto done;
5733 if (!can_recurse && no_ignores) {
5734 error = got_error_msg(GOT_ERR_BAD_PATH,
5735 "disregarding ignores requires -R option");
5736 goto done;
5740 if (!can_recurse) {
5741 char *ondisk_path;
5742 struct stat sb;
5743 TAILQ_FOREACH(pe, &paths, entry) {
5744 if (asprintf(&ondisk_path, "%s/%s",
5745 got_worktree_get_root_path(worktree),
5746 pe->path) == -1) {
5747 error = got_error_from_errno("asprintf");
5748 goto done;
5750 if (lstat(ondisk_path, &sb) == -1) {
5751 if (errno == ENOENT) {
5752 free(ondisk_path);
5753 continue;
5755 error = got_error_from_errno2("lstat",
5756 ondisk_path);
5757 free(ondisk_path);
5758 goto done;
5760 free(ondisk_path);
5761 if (S_ISDIR(sb.st_mode)) {
5762 error = got_error_msg(GOT_ERR_BAD_PATH,
5763 "adding directories requires -R option");
5764 goto done;
5769 error = got_worktree_schedule_add(worktree, &paths, add_progress,
5770 NULL, repo, no_ignores);
5771 done:
5772 if (repo)
5773 got_repo_close(repo);
5774 if (worktree)
5775 got_worktree_close(worktree);
5776 TAILQ_FOREACH(pe, &paths, entry)
5777 free((char *)pe->path);
5778 got_pathlist_free(&paths);
5779 free(cwd);
5780 return error;
5783 __dead static void
5784 usage_remove(void)
5786 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] path ...\n",
5787 getprogname());
5788 exit(1);
5791 static const struct got_error *
5792 print_remove_status(void *arg, unsigned char status,
5793 unsigned char staged_status, const char *path)
5795 while (path[0] == '/')
5796 path++;
5797 if (status == GOT_STATUS_NONEXISTENT)
5798 return NULL;
5799 if (status == staged_status && (status == GOT_STATUS_DELETE))
5800 status = GOT_STATUS_NO_CHANGE;
5801 printf("%c%c %s\n", status, staged_status, path);
5802 return NULL;
5805 static const struct got_error *
5806 cmd_remove(int argc, char *argv[])
5808 const struct got_error *error = NULL;
5809 struct got_worktree *worktree = NULL;
5810 struct got_repository *repo = NULL;
5811 char *cwd = NULL;
5812 struct got_pathlist_head paths;
5813 struct got_pathlist_entry *pe;
5814 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0;
5816 TAILQ_INIT(&paths);
5818 while ((ch = getopt(argc, argv, "fkR")) != -1) {
5819 switch (ch) {
5820 case 'f':
5821 delete_local_mods = 1;
5822 break;
5823 case 'k':
5824 keep_on_disk = 1;
5825 break;
5826 case 'R':
5827 can_recurse = 1;
5828 break;
5829 default:
5830 usage_remove();
5831 /* NOTREACHED */
5835 argc -= optind;
5836 argv += optind;
5838 #ifndef PROFILE
5839 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5840 NULL) == -1)
5841 err(1, "pledge");
5842 #endif
5843 if (argc < 1)
5844 usage_remove();
5846 cwd = getcwd(NULL, 0);
5847 if (cwd == NULL) {
5848 error = got_error_from_errno("getcwd");
5849 goto done;
5851 error = got_worktree_open(&worktree, cwd);
5852 if (error) {
5853 if (error->code == GOT_ERR_NOT_WORKTREE)
5854 error = wrap_not_worktree_error(error, "remove", cwd);
5855 goto done;
5858 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5859 NULL);
5860 if (error)
5861 goto done;
5863 error = apply_unveil(got_repo_get_path(repo), 1,
5864 got_worktree_get_root_path(worktree));
5865 if (error)
5866 goto done;
5868 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5869 if (error)
5870 goto done;
5872 if (!can_recurse) {
5873 char *ondisk_path;
5874 struct stat sb;
5875 TAILQ_FOREACH(pe, &paths, entry) {
5876 if (asprintf(&ondisk_path, "%s/%s",
5877 got_worktree_get_root_path(worktree),
5878 pe->path) == -1) {
5879 error = got_error_from_errno("asprintf");
5880 goto done;
5882 if (lstat(ondisk_path, &sb) == -1) {
5883 if (errno == ENOENT) {
5884 free(ondisk_path);
5885 continue;
5887 error = got_error_from_errno2("lstat",
5888 ondisk_path);
5889 free(ondisk_path);
5890 goto done;
5892 free(ondisk_path);
5893 if (S_ISDIR(sb.st_mode)) {
5894 error = got_error_msg(GOT_ERR_BAD_PATH,
5895 "removing directories requires -R option");
5896 goto done;
5901 error = got_worktree_schedule_delete(worktree, &paths,
5902 delete_local_mods, print_remove_status, NULL, repo, keep_on_disk);
5903 done:
5904 if (repo)
5905 got_repo_close(repo);
5906 if (worktree)
5907 got_worktree_close(worktree);
5908 TAILQ_FOREACH(pe, &paths, entry)
5909 free((char *)pe->path);
5910 got_pathlist_free(&paths);
5911 free(cwd);
5912 return error;
5915 __dead static void
5916 usage_revert(void)
5918 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
5919 "path ...\n", getprogname());
5920 exit(1);
5923 static const struct got_error *
5924 revert_progress(void *arg, unsigned char status, const char *path)
5926 if (status == GOT_STATUS_UNVERSIONED)
5927 return NULL;
5929 while (path[0] == '/')
5930 path++;
5931 printf("%c %s\n", status, path);
5932 return NULL;
5935 struct choose_patch_arg {
5936 FILE *patch_script_file;
5937 const char *action;
5940 static const struct got_error *
5941 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
5942 int nchanges, const char *action)
5944 char *line = NULL;
5945 size_t linesize = 0;
5946 ssize_t linelen;
5948 switch (status) {
5949 case GOT_STATUS_ADD:
5950 printf("A %s\n%s this addition? [y/n] ", path, action);
5951 break;
5952 case GOT_STATUS_DELETE:
5953 printf("D %s\n%s this deletion? [y/n] ", path, action);
5954 break;
5955 case GOT_STATUS_MODIFY:
5956 if (fseek(patch_file, 0L, SEEK_SET) == -1)
5957 return got_error_from_errno("fseek");
5958 printf(GOT_COMMIT_SEP_STR);
5959 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
5960 printf("%s", line);
5961 if (ferror(patch_file))
5962 return got_error_from_errno("getline");
5963 printf(GOT_COMMIT_SEP_STR);
5964 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
5965 path, n, nchanges, action);
5966 break;
5967 default:
5968 return got_error_path(path, GOT_ERR_FILE_STATUS);
5971 return NULL;
5974 static const struct got_error *
5975 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
5976 FILE *patch_file, int n, int nchanges)
5978 const struct got_error *err = NULL;
5979 char *line = NULL;
5980 size_t linesize = 0;
5981 ssize_t linelen;
5982 int resp = ' ';
5983 struct choose_patch_arg *a = arg;
5985 *choice = GOT_PATCH_CHOICE_NONE;
5987 if (a->patch_script_file) {
5988 char *nl;
5989 err = show_change(status, path, patch_file, n, nchanges,
5990 a->action);
5991 if (err)
5992 return err;
5993 linelen = getline(&line, &linesize, a->patch_script_file);
5994 if (linelen == -1) {
5995 if (ferror(a->patch_script_file))
5996 return got_error_from_errno("getline");
5997 return NULL;
5999 nl = strchr(line, '\n');
6000 if (nl)
6001 *nl = '\0';
6002 if (strcmp(line, "y") == 0) {
6003 *choice = GOT_PATCH_CHOICE_YES;
6004 printf("y\n");
6005 } else if (strcmp(line, "n") == 0) {
6006 *choice = GOT_PATCH_CHOICE_NO;
6007 printf("n\n");
6008 } else if (strcmp(line, "q") == 0 &&
6009 status == GOT_STATUS_MODIFY) {
6010 *choice = GOT_PATCH_CHOICE_QUIT;
6011 printf("q\n");
6012 } else
6013 printf("invalid response '%s'\n", line);
6014 free(line);
6015 return NULL;
6018 while (resp != 'y' && resp != 'n' && resp != 'q') {
6019 err = show_change(status, path, patch_file, n, nchanges,
6020 a->action);
6021 if (err)
6022 return err;
6023 resp = getchar();
6024 if (resp == '\n')
6025 resp = getchar();
6026 if (status == GOT_STATUS_MODIFY) {
6027 if (resp != 'y' && resp != 'n' && resp != 'q') {
6028 printf("invalid response '%c'\n", resp);
6029 resp = ' ';
6031 } else if (resp != 'y' && resp != 'n') {
6032 printf("invalid response '%c'\n", resp);
6033 resp = ' ';
6037 if (resp == 'y')
6038 *choice = GOT_PATCH_CHOICE_YES;
6039 else if (resp == 'n')
6040 *choice = GOT_PATCH_CHOICE_NO;
6041 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6042 *choice = GOT_PATCH_CHOICE_QUIT;
6044 return NULL;
6048 static const struct got_error *
6049 cmd_revert(int argc, char *argv[])
6051 const struct got_error *error = NULL;
6052 struct got_worktree *worktree = NULL;
6053 struct got_repository *repo = NULL;
6054 char *cwd = NULL, *path = NULL;
6055 struct got_pathlist_head paths;
6056 struct got_pathlist_entry *pe;
6057 int ch, can_recurse = 0, pflag = 0;
6058 FILE *patch_script_file = NULL;
6059 const char *patch_script_path = NULL;
6060 struct choose_patch_arg cpa;
6062 TAILQ_INIT(&paths);
6064 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6065 switch (ch) {
6066 case 'p':
6067 pflag = 1;
6068 break;
6069 case 'F':
6070 patch_script_path = optarg;
6071 break;
6072 case 'R':
6073 can_recurse = 1;
6074 break;
6075 default:
6076 usage_revert();
6077 /* NOTREACHED */
6081 argc -= optind;
6082 argv += optind;
6084 #ifndef PROFILE
6085 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6086 "unveil", NULL) == -1)
6087 err(1, "pledge");
6088 #endif
6089 if (argc < 1)
6090 usage_revert();
6091 if (patch_script_path && !pflag)
6092 errx(1, "-F option can only be used together with -p option");
6094 cwd = getcwd(NULL, 0);
6095 if (cwd == NULL) {
6096 error = got_error_from_errno("getcwd");
6097 goto done;
6099 error = got_worktree_open(&worktree, cwd);
6100 if (error) {
6101 if (error->code == GOT_ERR_NOT_WORKTREE)
6102 error = wrap_not_worktree_error(error, "revert", cwd);
6103 goto done;
6106 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6107 NULL);
6108 if (error != NULL)
6109 goto done;
6111 if (patch_script_path) {
6112 patch_script_file = fopen(patch_script_path, "r");
6113 if (patch_script_file == NULL) {
6114 error = got_error_from_errno2("fopen",
6115 patch_script_path);
6116 goto done;
6119 error = apply_unveil(got_repo_get_path(repo), 1,
6120 got_worktree_get_root_path(worktree));
6121 if (error)
6122 goto done;
6124 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6125 if (error)
6126 goto done;
6128 if (!can_recurse) {
6129 char *ondisk_path;
6130 struct stat sb;
6131 TAILQ_FOREACH(pe, &paths, entry) {
6132 if (asprintf(&ondisk_path, "%s/%s",
6133 got_worktree_get_root_path(worktree),
6134 pe->path) == -1) {
6135 error = got_error_from_errno("asprintf");
6136 goto done;
6138 if (lstat(ondisk_path, &sb) == -1) {
6139 if (errno == ENOENT) {
6140 free(ondisk_path);
6141 continue;
6143 error = got_error_from_errno2("lstat",
6144 ondisk_path);
6145 free(ondisk_path);
6146 goto done;
6148 free(ondisk_path);
6149 if (S_ISDIR(sb.st_mode)) {
6150 error = got_error_msg(GOT_ERR_BAD_PATH,
6151 "reverting directories requires -R option");
6152 goto done;
6157 cpa.patch_script_file = patch_script_file;
6158 cpa.action = "revert";
6159 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6160 pflag ? choose_patch : NULL, &cpa, repo);
6161 done:
6162 if (patch_script_file && fclose(patch_script_file) == EOF &&
6163 error == NULL)
6164 error = got_error_from_errno2("fclose", patch_script_path);
6165 if (repo)
6166 got_repo_close(repo);
6167 if (worktree)
6168 got_worktree_close(worktree);
6169 free(path);
6170 free(cwd);
6171 return error;
6174 __dead static void
6175 usage_commit(void)
6177 fprintf(stderr, "usage: %s commit [-m msg] [path ...]\n",
6178 getprogname());
6179 exit(1);
6182 struct collect_commit_logmsg_arg {
6183 const char *cmdline_log;
6184 const char *editor;
6185 const char *worktree_path;
6186 const char *branch_name;
6187 const char *repo_path;
6188 char *logmsg_path;
6192 static const struct got_error *
6193 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6194 void *arg)
6196 char *initial_content = NULL;
6197 struct got_pathlist_entry *pe;
6198 const struct got_error *err = NULL;
6199 char *template = NULL;
6200 struct collect_commit_logmsg_arg *a = arg;
6201 int fd;
6202 size_t len;
6204 /* if a message was specified on the command line, just use it */
6205 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6206 len = strlen(a->cmdline_log) + 1;
6207 *logmsg = malloc(len + 1);
6208 if (*logmsg == NULL)
6209 return got_error_from_errno("malloc");
6210 strlcpy(*logmsg, a->cmdline_log, len);
6211 return NULL;
6214 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6215 return got_error_from_errno("asprintf");
6217 if (asprintf(&initial_content,
6218 "\n# changes to be committed on branch %s:\n",
6219 a->branch_name) == -1)
6220 return got_error_from_errno("asprintf");
6222 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6223 if (err)
6224 goto done;
6226 dprintf(fd, initial_content);
6228 TAILQ_FOREACH(pe, commitable_paths, entry) {
6229 struct got_commitable *ct = pe->data;
6230 dprintf(fd, "# %c %s\n",
6231 got_commitable_get_status(ct),
6232 got_commitable_get_path(ct));
6234 close(fd);
6236 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
6237 done:
6238 free(initial_content);
6239 free(template);
6241 /* Editor is done; we can now apply unveil(2) */
6242 if (err == NULL) {
6243 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6244 if (err) {
6245 free(*logmsg);
6246 *logmsg = NULL;
6249 return err;
6252 static const struct got_error *
6253 cmd_commit(int argc, char *argv[])
6255 const struct got_error *error = NULL;
6256 struct got_worktree *worktree = NULL;
6257 struct got_repository *repo = NULL;
6258 char *cwd = NULL, *id_str = NULL;
6259 struct got_object_id *id = NULL;
6260 const char *logmsg = NULL;
6261 struct collect_commit_logmsg_arg cl_arg;
6262 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6263 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6264 struct got_pathlist_head paths;
6266 TAILQ_INIT(&paths);
6267 cl_arg.logmsg_path = NULL;
6269 while ((ch = getopt(argc, argv, "m:")) != -1) {
6270 switch (ch) {
6271 case 'm':
6272 logmsg = optarg;
6273 break;
6274 default:
6275 usage_commit();
6276 /* NOTREACHED */
6280 argc -= optind;
6281 argv += optind;
6283 #ifndef PROFILE
6284 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6285 "unveil", NULL) == -1)
6286 err(1, "pledge");
6287 #endif
6288 cwd = getcwd(NULL, 0);
6289 if (cwd == NULL) {
6290 error = got_error_from_errno("getcwd");
6291 goto done;
6293 error = got_worktree_open(&worktree, cwd);
6294 if (error) {
6295 if (error->code == GOT_ERR_NOT_WORKTREE)
6296 error = wrap_not_worktree_error(error, "commit", cwd);
6297 goto done;
6300 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6301 if (error)
6302 goto done;
6303 if (rebase_in_progress) {
6304 error = got_error(GOT_ERR_REBASING);
6305 goto done;
6308 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6309 worktree);
6310 if (error)
6311 goto done;
6313 error = get_gitconfig_path(&gitconfig_path);
6314 if (error)
6315 goto done;
6316 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6317 gitconfig_path);
6318 if (error != NULL)
6319 goto done;
6321 error = get_author(&author, repo);
6322 if (error)
6323 return error;
6326 * unveil(2) traverses exec(2); if an editor is used we have
6327 * to apply unveil after the log message has been written.
6329 if (logmsg == NULL || strlen(logmsg) == 0)
6330 error = get_editor(&editor);
6331 else
6332 error = apply_unveil(got_repo_get_path(repo), 0,
6333 got_worktree_get_root_path(worktree));
6334 if (error)
6335 goto done;
6337 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6338 if (error)
6339 goto done;
6341 cl_arg.editor = editor;
6342 cl_arg.cmdline_log = logmsg;
6343 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6344 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6345 if (!histedit_in_progress) {
6346 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6347 error = got_error(GOT_ERR_COMMIT_BRANCH);
6348 goto done;
6350 cl_arg.branch_name += 11;
6352 cl_arg.repo_path = got_repo_get_path(repo);
6353 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6354 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
6355 if (error) {
6356 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6357 cl_arg.logmsg_path != NULL)
6358 preserve_logmsg = 1;
6359 goto done;
6362 error = got_object_id_str(&id_str, id);
6363 if (error)
6364 goto done;
6365 printf("Created commit %s\n", id_str);
6366 done:
6367 if (preserve_logmsg) {
6368 fprintf(stderr, "%s: log message preserved in %s\n",
6369 getprogname(), cl_arg.logmsg_path);
6370 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6371 error == NULL)
6372 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6373 free(cl_arg.logmsg_path);
6374 if (repo)
6375 got_repo_close(repo);
6376 if (worktree)
6377 got_worktree_close(worktree);
6378 free(cwd);
6379 free(id_str);
6380 free(gitconfig_path);
6381 free(editor);
6382 free(author);
6383 return error;
6386 __dead static void
6387 usage_cherrypick(void)
6389 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6390 exit(1);
6393 static const struct got_error *
6394 cmd_cherrypick(int argc, char *argv[])
6396 const struct got_error *error = NULL;
6397 struct got_worktree *worktree = NULL;
6398 struct got_repository *repo = NULL;
6399 char *cwd = NULL, *commit_id_str = NULL;
6400 struct got_object_id *commit_id = NULL;
6401 struct got_commit_object *commit = NULL;
6402 struct got_object_qid *pid;
6403 struct got_reference *head_ref = NULL;
6404 int ch;
6405 struct got_update_progress_arg upa;
6407 while ((ch = getopt(argc, argv, "")) != -1) {
6408 switch (ch) {
6409 default:
6410 usage_cherrypick();
6411 /* NOTREACHED */
6415 argc -= optind;
6416 argv += optind;
6418 #ifndef PROFILE
6419 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6420 "unveil", NULL) == -1)
6421 err(1, "pledge");
6422 #endif
6423 if (argc != 1)
6424 usage_cherrypick();
6426 cwd = getcwd(NULL, 0);
6427 if (cwd == NULL) {
6428 error = got_error_from_errno("getcwd");
6429 goto done;
6431 error = got_worktree_open(&worktree, cwd);
6432 if (error) {
6433 if (error->code == GOT_ERR_NOT_WORKTREE)
6434 error = wrap_not_worktree_error(error, "cherrypick",
6435 cwd);
6436 goto done;
6439 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6440 NULL);
6441 if (error != NULL)
6442 goto done;
6444 error = apply_unveil(got_repo_get_path(repo), 0,
6445 got_worktree_get_root_path(worktree));
6446 if (error)
6447 goto done;
6449 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6450 GOT_OBJ_TYPE_COMMIT, repo);
6451 if (error != NULL) {
6452 struct got_reference *ref;
6453 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6454 goto done;
6455 error = got_ref_open(&ref, repo, argv[0], 0);
6456 if (error != NULL)
6457 goto done;
6458 error = got_ref_resolve(&commit_id, repo, ref);
6459 got_ref_close(ref);
6460 if (error != NULL)
6461 goto done;
6463 error = got_object_id_str(&commit_id_str, commit_id);
6464 if (error)
6465 goto done;
6467 error = got_ref_open(&head_ref, repo,
6468 got_worktree_get_head_ref_name(worktree), 0);
6469 if (error != NULL)
6470 goto done;
6472 error = check_same_branch(commit_id, head_ref, NULL, repo);
6473 if (error) {
6474 if (error->code != GOT_ERR_ANCESTRY)
6475 goto done;
6476 error = NULL;
6477 } else {
6478 error = got_error(GOT_ERR_SAME_BRANCH);
6479 goto done;
6482 error = got_object_open_as_commit(&commit, repo, commit_id);
6483 if (error)
6484 goto done;
6485 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6486 memset(&upa, 0, sizeof(upa));
6487 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
6488 commit_id, repo, update_progress, &upa, check_cancelled,
6489 NULL);
6490 if (error != NULL)
6491 goto done;
6493 if (upa.did_something)
6494 printf("Merged commit %s\n", commit_id_str);
6495 print_update_progress_stats(&upa);
6496 done:
6497 if (commit)
6498 got_object_commit_close(commit);
6499 free(commit_id_str);
6500 if (head_ref)
6501 got_ref_close(head_ref);
6502 if (worktree)
6503 got_worktree_close(worktree);
6504 if (repo)
6505 got_repo_close(repo);
6506 return error;
6509 __dead static void
6510 usage_backout(void)
6512 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
6513 exit(1);
6516 static const struct got_error *
6517 cmd_backout(int argc, char *argv[])
6519 const struct got_error *error = NULL;
6520 struct got_worktree *worktree = NULL;
6521 struct got_repository *repo = NULL;
6522 char *cwd = NULL, *commit_id_str = NULL;
6523 struct got_object_id *commit_id = NULL;
6524 struct got_commit_object *commit = NULL;
6525 struct got_object_qid *pid;
6526 struct got_reference *head_ref = NULL;
6527 int ch;
6528 struct got_update_progress_arg upa;
6530 while ((ch = getopt(argc, argv, "")) != -1) {
6531 switch (ch) {
6532 default:
6533 usage_backout();
6534 /* NOTREACHED */
6538 argc -= optind;
6539 argv += optind;
6541 #ifndef PROFILE
6542 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6543 "unveil", NULL) == -1)
6544 err(1, "pledge");
6545 #endif
6546 if (argc != 1)
6547 usage_backout();
6549 cwd = getcwd(NULL, 0);
6550 if (cwd == NULL) {
6551 error = got_error_from_errno("getcwd");
6552 goto done;
6554 error = got_worktree_open(&worktree, cwd);
6555 if (error) {
6556 if (error->code == GOT_ERR_NOT_WORKTREE)
6557 error = wrap_not_worktree_error(error, "backout", cwd);
6558 goto done;
6561 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6562 NULL);
6563 if (error != NULL)
6564 goto done;
6566 error = apply_unveil(got_repo_get_path(repo), 0,
6567 got_worktree_get_root_path(worktree));
6568 if (error)
6569 goto done;
6571 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6572 GOT_OBJ_TYPE_COMMIT, repo);
6573 if (error != NULL) {
6574 struct got_reference *ref;
6575 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6576 goto done;
6577 error = got_ref_open(&ref, repo, argv[0], 0);
6578 if (error != NULL)
6579 goto done;
6580 error = got_ref_resolve(&commit_id, repo, ref);
6581 got_ref_close(ref);
6582 if (error != NULL)
6583 goto done;
6585 error = got_object_id_str(&commit_id_str, commit_id);
6586 if (error)
6587 goto done;
6589 error = got_ref_open(&head_ref, repo,
6590 got_worktree_get_head_ref_name(worktree), 0);
6591 if (error != NULL)
6592 goto done;
6594 error = check_same_branch(commit_id, head_ref, NULL, repo);
6595 if (error)
6596 goto done;
6598 error = got_object_open_as_commit(&commit, repo, commit_id);
6599 if (error)
6600 goto done;
6601 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6602 if (pid == NULL) {
6603 error = got_error(GOT_ERR_ROOT_COMMIT);
6604 goto done;
6607 memset(&upa, 0, sizeof(upa));
6608 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
6609 update_progress, &upa, check_cancelled, NULL);
6610 if (error != NULL)
6611 goto done;
6613 if (upa.did_something)
6614 printf("Backed out commit %s\n", commit_id_str);
6615 print_update_progress_stats(&upa);
6616 done:
6617 if (commit)
6618 got_object_commit_close(commit);
6619 free(commit_id_str);
6620 if (head_ref)
6621 got_ref_close(head_ref);
6622 if (worktree)
6623 got_worktree_close(worktree);
6624 if (repo)
6625 got_repo_close(repo);
6626 return error;
6629 __dead static void
6630 usage_rebase(void)
6632 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
6633 getprogname());
6634 exit(1);
6637 void
6638 trim_logmsg(char *logmsg, int limit)
6640 char *nl;
6641 size_t len;
6643 len = strlen(logmsg);
6644 if (len > limit)
6645 len = limit;
6646 logmsg[len] = '\0';
6647 nl = strchr(logmsg, '\n');
6648 if (nl)
6649 *nl = '\0';
6652 static const struct got_error *
6653 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
6655 const struct got_error *err;
6656 char *logmsg0 = NULL;
6657 const char *s;
6659 err = got_object_commit_get_logmsg(&logmsg0, commit);
6660 if (err)
6661 return err;
6663 s = logmsg0;
6664 while (isspace((unsigned char)s[0]))
6665 s++;
6667 *logmsg = strdup(s);
6668 if (*logmsg == NULL) {
6669 err = got_error_from_errno("strdup");
6670 goto done;
6673 trim_logmsg(*logmsg, limit);
6674 done:
6675 free(logmsg0);
6676 return err;
6679 static const struct got_error *
6680 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
6682 const struct got_error *err;
6683 struct got_commit_object *commit = NULL;
6684 char *id_str = NULL, *logmsg = NULL;
6686 err = got_object_open_as_commit(&commit, repo, id);
6687 if (err)
6688 return err;
6690 err = got_object_id_str(&id_str, id);
6691 if (err)
6692 goto done;
6694 id_str[12] = '\0';
6696 err = get_short_logmsg(&logmsg, 42, commit);
6697 if (err)
6698 goto done;
6700 printf("%s -> merge conflict: %s\n", id_str, logmsg);
6701 done:
6702 free(id_str);
6703 got_object_commit_close(commit);
6704 free(logmsg);
6705 return err;
6708 static const struct got_error *
6709 show_rebase_progress(struct got_commit_object *commit,
6710 struct got_object_id *old_id, struct got_object_id *new_id)
6712 const struct got_error *err;
6713 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
6715 err = got_object_id_str(&old_id_str, old_id);
6716 if (err)
6717 goto done;
6719 if (new_id) {
6720 err = got_object_id_str(&new_id_str, new_id);
6721 if (err)
6722 goto done;
6725 old_id_str[12] = '\0';
6726 if (new_id_str)
6727 new_id_str[12] = '\0';
6729 err = get_short_logmsg(&logmsg, 42, commit);
6730 if (err)
6731 goto done;
6733 printf("%s -> %s: %s\n", old_id_str,
6734 new_id_str ? new_id_str : "no-op change", logmsg);
6735 done:
6736 free(old_id_str);
6737 free(new_id_str);
6738 free(logmsg);
6739 return err;
6742 static const struct got_error *
6743 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
6744 struct got_reference *branch, struct got_reference *new_base_branch,
6745 struct got_reference *tmp_branch, struct got_repository *repo)
6747 printf("Switching work tree to %s\n", got_ref_get_name(branch));
6748 return got_worktree_rebase_complete(worktree, fileindex,
6749 new_base_branch, tmp_branch, branch, repo);
6752 static const struct got_error *
6753 rebase_commit(struct got_pathlist_head *merged_paths,
6754 struct got_worktree *worktree, struct got_fileindex *fileindex,
6755 struct got_reference *tmp_branch,
6756 struct got_object_id *commit_id, struct got_repository *repo)
6758 const struct got_error *error;
6759 struct got_commit_object *commit;
6760 struct got_object_id *new_commit_id;
6762 error = got_object_open_as_commit(&commit, repo, commit_id);
6763 if (error)
6764 return error;
6766 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
6767 worktree, fileindex, tmp_branch, commit, commit_id, repo);
6768 if (error) {
6769 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
6770 goto done;
6771 error = show_rebase_progress(commit, commit_id, NULL);
6772 } else {
6773 error = show_rebase_progress(commit, commit_id, new_commit_id);
6774 free(new_commit_id);
6776 done:
6777 got_object_commit_close(commit);
6778 return error;
6781 struct check_path_prefix_arg {
6782 const char *path_prefix;
6783 size_t len;
6784 int errcode;
6787 static const struct got_error *
6788 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
6789 struct got_blob_object *blob2, struct got_object_id *id1,
6790 struct got_object_id *id2, const char *path1, const char *path2,
6791 mode_t mode1, mode_t mode2, struct got_repository *repo)
6793 struct check_path_prefix_arg *a = arg;
6795 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
6796 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
6797 return got_error(a->errcode);
6799 return NULL;
6802 static const struct got_error *
6803 check_path_prefix(struct got_object_id *parent_id,
6804 struct got_object_id *commit_id, const char *path_prefix,
6805 int errcode, struct got_repository *repo)
6807 const struct got_error *err;
6808 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
6809 struct got_commit_object *commit = NULL, *parent_commit = NULL;
6810 struct check_path_prefix_arg cpp_arg;
6812 if (got_path_is_root_dir(path_prefix))
6813 return NULL;
6815 err = got_object_open_as_commit(&commit, repo, commit_id);
6816 if (err)
6817 goto done;
6819 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
6820 if (err)
6821 goto done;
6823 err = got_object_open_as_tree(&tree1, repo,
6824 got_object_commit_get_tree_id(parent_commit));
6825 if (err)
6826 goto done;
6828 err = got_object_open_as_tree(&tree2, repo,
6829 got_object_commit_get_tree_id(commit));
6830 if (err)
6831 goto done;
6833 cpp_arg.path_prefix = path_prefix;
6834 while (cpp_arg.path_prefix[0] == '/')
6835 cpp_arg.path_prefix++;
6836 cpp_arg.len = strlen(cpp_arg.path_prefix);
6837 cpp_arg.errcode = errcode;
6838 err = got_diff_tree(tree1, tree2, "", "", repo,
6839 check_path_prefix_in_diff, &cpp_arg, 0);
6840 done:
6841 if (tree1)
6842 got_object_tree_close(tree1);
6843 if (tree2)
6844 got_object_tree_close(tree2);
6845 if (commit)
6846 got_object_commit_close(commit);
6847 if (parent_commit)
6848 got_object_commit_close(parent_commit);
6849 return err;
6852 static const struct got_error *
6853 collect_commits(struct got_object_id_queue *commits,
6854 struct got_object_id *initial_commit_id,
6855 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
6856 const char *path_prefix, int path_prefix_errcode,
6857 struct got_repository *repo)
6859 const struct got_error *err = NULL;
6860 struct got_commit_graph *graph = NULL;
6861 struct got_object_id *parent_id = NULL;
6862 struct got_object_qid *qid;
6863 struct got_object_id *commit_id = initial_commit_id;
6865 err = got_commit_graph_open(&graph, "/", 1);
6866 if (err)
6867 return err;
6869 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
6870 check_cancelled, NULL);
6871 if (err)
6872 goto done;
6873 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
6874 err = got_commit_graph_iter_next(&parent_id, graph, repo,
6875 check_cancelled, NULL);
6876 if (err) {
6877 if (err->code == GOT_ERR_ITER_COMPLETED) {
6878 err = got_error_msg(GOT_ERR_ANCESTRY,
6879 "ran out of commits to rebase before "
6880 "youngest common ancestor commit has "
6881 "been reached?!?");
6883 goto done;
6884 } else {
6885 err = check_path_prefix(parent_id, commit_id,
6886 path_prefix, path_prefix_errcode, repo);
6887 if (err)
6888 goto done;
6890 err = got_object_qid_alloc(&qid, commit_id);
6891 if (err)
6892 goto done;
6893 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
6894 commit_id = parent_id;
6897 done:
6898 got_commit_graph_close(graph);
6899 return err;
6902 static const struct got_error *
6903 cmd_rebase(int argc, char *argv[])
6905 const struct got_error *error = NULL;
6906 struct got_worktree *worktree = NULL;
6907 struct got_repository *repo = NULL;
6908 struct got_fileindex *fileindex = NULL;
6909 char *cwd = NULL;
6910 struct got_reference *branch = NULL;
6911 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
6912 struct got_object_id *commit_id = NULL, *parent_id = NULL;
6913 struct got_object_id *resume_commit_id = NULL;
6914 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
6915 struct got_commit_object *commit = NULL;
6916 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
6917 int histedit_in_progress = 0;
6918 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
6919 struct got_object_id_queue commits;
6920 struct got_pathlist_head merged_paths;
6921 const struct got_object_id_queue *parent_ids;
6922 struct got_object_qid *qid, *pid;
6924 SIMPLEQ_INIT(&commits);
6925 TAILQ_INIT(&merged_paths);
6927 while ((ch = getopt(argc, argv, "ac")) != -1) {
6928 switch (ch) {
6929 case 'a':
6930 abort_rebase = 1;
6931 break;
6932 case 'c':
6933 continue_rebase = 1;
6934 break;
6935 default:
6936 usage_rebase();
6937 /* NOTREACHED */
6941 argc -= optind;
6942 argv += optind;
6944 #ifndef PROFILE
6945 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6946 "unveil", NULL) == -1)
6947 err(1, "pledge");
6948 #endif
6949 if (abort_rebase && continue_rebase)
6950 usage_rebase();
6951 else if (abort_rebase || continue_rebase) {
6952 if (argc != 0)
6953 usage_rebase();
6954 } else if (argc != 1)
6955 usage_rebase();
6957 cwd = getcwd(NULL, 0);
6958 if (cwd == NULL) {
6959 error = got_error_from_errno("getcwd");
6960 goto done;
6962 error = got_worktree_open(&worktree, cwd);
6963 if (error) {
6964 if (error->code == GOT_ERR_NOT_WORKTREE)
6965 error = wrap_not_worktree_error(error, "rebase", cwd);
6966 goto done;
6969 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6970 NULL);
6971 if (error != NULL)
6972 goto done;
6974 error = apply_unveil(got_repo_get_path(repo), 0,
6975 got_worktree_get_root_path(worktree));
6976 if (error)
6977 goto done;
6979 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6980 worktree);
6981 if (error)
6982 goto done;
6983 if (histedit_in_progress) {
6984 error = got_error(GOT_ERR_HISTEDIT_BUSY);
6985 goto done;
6988 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6989 if (error)
6990 goto done;
6992 if (abort_rebase) {
6993 struct got_update_progress_arg upa;
6994 if (!rebase_in_progress) {
6995 error = got_error(GOT_ERR_NOT_REBASING);
6996 goto done;
6998 error = got_worktree_rebase_continue(&resume_commit_id,
6999 &new_base_branch, &tmp_branch, &branch, &fileindex,
7000 worktree, repo);
7001 if (error)
7002 goto done;
7003 printf("Switching work tree to %s\n",
7004 got_ref_get_symref_target(new_base_branch));
7005 memset(&upa, 0, sizeof(upa));
7006 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7007 new_base_branch, update_progress, &upa);
7008 if (error)
7009 goto done;
7010 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7011 print_update_progress_stats(&upa);
7012 goto done; /* nothing else to do */
7015 if (continue_rebase) {
7016 if (!rebase_in_progress) {
7017 error = got_error(GOT_ERR_NOT_REBASING);
7018 goto done;
7020 error = got_worktree_rebase_continue(&resume_commit_id,
7021 &new_base_branch, &tmp_branch, &branch, &fileindex,
7022 worktree, repo);
7023 if (error)
7024 goto done;
7026 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7027 resume_commit_id, repo);
7028 if (error)
7029 goto done;
7031 yca_id = got_object_id_dup(resume_commit_id);
7032 if (yca_id == NULL) {
7033 error = got_error_from_errno("got_object_id_dup");
7034 goto done;
7036 } else {
7037 error = got_ref_open(&branch, repo, argv[0], 0);
7038 if (error != NULL)
7039 goto done;
7042 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7043 if (error)
7044 goto done;
7046 if (!continue_rebase) {
7047 struct got_object_id *base_commit_id;
7049 base_commit_id = got_worktree_get_base_commit_id(worktree);
7050 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7051 base_commit_id, branch_head_commit_id, repo,
7052 check_cancelled, NULL);
7053 if (error)
7054 goto done;
7055 if (yca_id == NULL) {
7056 error = got_error_msg(GOT_ERR_ANCESTRY,
7057 "specified branch shares no common ancestry "
7058 "with work tree's branch");
7059 goto done;
7062 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7063 if (error) {
7064 if (error->code != GOT_ERR_ANCESTRY)
7065 goto done;
7066 error = NULL;
7067 } else {
7068 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7069 "specified branch resolves to a commit which "
7070 "is already contained in work tree's branch");
7071 goto done;
7073 error = got_worktree_rebase_prepare(&new_base_branch,
7074 &tmp_branch, &fileindex, worktree, branch, repo);
7075 if (error)
7076 goto done;
7079 commit_id = branch_head_commit_id;
7080 error = got_object_open_as_commit(&commit, repo, commit_id);
7081 if (error)
7082 goto done;
7084 parent_ids = got_object_commit_get_parent_ids(commit);
7085 pid = SIMPLEQ_FIRST(parent_ids);
7086 if (pid == NULL) {
7087 if (!continue_rebase) {
7088 struct got_update_progress_arg upa;
7089 memset(&upa, 0, sizeof(upa));
7090 error = got_worktree_rebase_abort(worktree, fileindex,
7091 repo, new_base_branch, update_progress, &upa);
7092 if (error)
7093 goto done;
7094 printf("Rebase of %s aborted\n",
7095 got_ref_get_name(branch));
7096 print_update_progress_stats(&upa);
7099 error = got_error(GOT_ERR_EMPTY_REBASE);
7100 goto done;
7102 error = collect_commits(&commits, commit_id, pid->id,
7103 yca_id, got_worktree_get_path_prefix(worktree),
7104 GOT_ERR_REBASE_PATH, repo);
7105 got_object_commit_close(commit);
7106 commit = NULL;
7107 if (error)
7108 goto done;
7110 if (SIMPLEQ_EMPTY(&commits)) {
7111 if (continue_rebase) {
7112 error = rebase_complete(worktree, fileindex,
7113 branch, new_base_branch, tmp_branch, repo);
7114 goto done;
7115 } else {
7116 /* Fast-forward the reference of the branch. */
7117 struct got_object_id *new_head_commit_id;
7118 char *id_str;
7119 error = got_ref_resolve(&new_head_commit_id, repo,
7120 new_base_branch);
7121 if (error)
7122 goto done;
7123 error = got_object_id_str(&id_str, new_head_commit_id);
7124 printf("Forwarding %s to commit %s\n",
7125 got_ref_get_name(branch), id_str);
7126 free(id_str);
7127 error = got_ref_change_ref(branch,
7128 new_head_commit_id);
7129 if (error)
7130 goto done;
7134 pid = NULL;
7135 SIMPLEQ_FOREACH(qid, &commits, entry) {
7136 struct got_update_progress_arg upa;
7138 commit_id = qid->id;
7139 parent_id = pid ? pid->id : yca_id;
7140 pid = qid;
7142 memset(&upa, 0, sizeof(upa));
7143 error = got_worktree_rebase_merge_files(&merged_paths,
7144 worktree, fileindex, parent_id, commit_id, repo,
7145 update_progress, &upa, check_cancelled, NULL);
7146 if (error)
7147 goto done;
7149 print_update_progress_stats(&upa);
7150 if (upa.conflicts > 0)
7151 rebase_status = GOT_STATUS_CONFLICT;
7153 if (rebase_status == GOT_STATUS_CONFLICT) {
7154 error = show_rebase_merge_conflict(qid->id, repo);
7155 if (error)
7156 goto done;
7157 got_worktree_rebase_pathlist_free(&merged_paths);
7158 break;
7161 error = rebase_commit(&merged_paths, worktree, fileindex,
7162 tmp_branch, commit_id, repo);
7163 got_worktree_rebase_pathlist_free(&merged_paths);
7164 if (error)
7165 goto done;
7168 if (rebase_status == GOT_STATUS_CONFLICT) {
7169 error = got_worktree_rebase_postpone(worktree, fileindex);
7170 if (error)
7171 goto done;
7172 error = got_error_msg(GOT_ERR_CONFLICTS,
7173 "conflicts must be resolved before rebasing can continue");
7174 } else
7175 error = rebase_complete(worktree, fileindex, branch,
7176 new_base_branch, tmp_branch, repo);
7177 done:
7178 got_object_id_queue_free(&commits);
7179 free(branch_head_commit_id);
7180 free(resume_commit_id);
7181 free(yca_id);
7182 if (commit)
7183 got_object_commit_close(commit);
7184 if (branch)
7185 got_ref_close(branch);
7186 if (new_base_branch)
7187 got_ref_close(new_base_branch);
7188 if (tmp_branch)
7189 got_ref_close(tmp_branch);
7190 if (worktree)
7191 got_worktree_close(worktree);
7192 if (repo)
7193 got_repo_close(repo);
7194 return error;
7197 __dead static void
7198 usage_histedit(void)
7200 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
7201 getprogname());
7202 exit(1);
7205 #define GOT_HISTEDIT_PICK 'p'
7206 #define GOT_HISTEDIT_EDIT 'e'
7207 #define GOT_HISTEDIT_FOLD 'f'
7208 #define GOT_HISTEDIT_DROP 'd'
7209 #define GOT_HISTEDIT_MESG 'm'
7211 static struct got_histedit_cmd {
7212 unsigned char code;
7213 const char *name;
7214 const char *desc;
7215 } got_histedit_cmds[] = {
7216 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7217 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7218 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7219 "be used" },
7220 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7221 { GOT_HISTEDIT_MESG, "mesg",
7222 "single-line log message for commit above (open editor if empty)" },
7225 struct got_histedit_list_entry {
7226 TAILQ_ENTRY(got_histedit_list_entry) entry;
7227 struct got_object_id *commit_id;
7228 const struct got_histedit_cmd *cmd;
7229 char *logmsg;
7231 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7233 static const struct got_error *
7234 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7235 FILE *f, struct got_repository *repo)
7237 const struct got_error *err = NULL;
7238 char *logmsg = NULL, *id_str = NULL;
7239 struct got_commit_object *commit = NULL;
7240 int n;
7242 err = got_object_open_as_commit(&commit, repo, commit_id);
7243 if (err)
7244 goto done;
7246 err = get_short_logmsg(&logmsg, 34, commit);
7247 if (err)
7248 goto done;
7250 err = got_object_id_str(&id_str, commit_id);
7251 if (err)
7252 goto done;
7254 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7255 if (n < 0)
7256 err = got_ferror(f, GOT_ERR_IO);
7257 done:
7258 if (commit)
7259 got_object_commit_close(commit);
7260 free(id_str);
7261 free(logmsg);
7262 return err;
7265 static const struct got_error *
7266 histedit_write_commit_list(struct got_object_id_queue *commits,
7267 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7269 const struct got_error *err = NULL;
7270 struct got_object_qid *qid;
7272 if (SIMPLEQ_EMPTY(commits))
7273 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7275 SIMPLEQ_FOREACH(qid, commits, entry) {
7276 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7277 f, repo);
7278 if (err)
7279 break;
7280 if (edit_logmsg_only) {
7281 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7282 if (n < 0) {
7283 err = got_ferror(f, GOT_ERR_IO);
7284 break;
7289 return err;
7292 static const struct got_error *
7293 write_cmd_list(FILE *f, const char *branch_name,
7294 struct got_object_id_queue *commits)
7296 const struct got_error *err = NULL;
7297 int n, i;
7298 char *id_str;
7299 struct got_object_qid *qid;
7301 qid = SIMPLEQ_FIRST(commits);
7302 err = got_object_id_str(&id_str, qid->id);
7303 if (err)
7304 return err;
7306 n = fprintf(f,
7307 "# Editing the history of branch '%s' starting at\n"
7308 "# commit %s\n"
7309 "# Commits will be processed in order from top to "
7310 "bottom of this file.\n", branch_name, id_str);
7311 if (n < 0) {
7312 err = got_ferror(f, GOT_ERR_IO);
7313 goto done;
7316 n = fprintf(f, "# Available histedit commands:\n");
7317 if (n < 0) {
7318 err = got_ferror(f, GOT_ERR_IO);
7319 goto done;
7322 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7323 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7324 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7325 cmd->desc);
7326 if (n < 0) {
7327 err = got_ferror(f, GOT_ERR_IO);
7328 break;
7331 done:
7332 free(id_str);
7333 return err;
7336 static const struct got_error *
7337 histedit_syntax_error(int lineno)
7339 static char msg[42];
7340 int ret;
7342 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7343 lineno);
7344 if (ret == -1 || ret >= sizeof(msg))
7345 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7347 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7350 static const struct got_error *
7351 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7352 char *logmsg, struct got_repository *repo)
7354 const struct got_error *err;
7355 struct got_commit_object *folded_commit = NULL;
7356 char *id_str, *folded_logmsg = NULL;
7358 err = got_object_id_str(&id_str, hle->commit_id);
7359 if (err)
7360 return err;
7362 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7363 if (err)
7364 goto done;
7366 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7367 if (err)
7368 goto done;
7369 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7370 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7371 folded_logmsg) == -1) {
7372 err = got_error_from_errno("asprintf");
7374 done:
7375 if (folded_commit)
7376 got_object_commit_close(folded_commit);
7377 free(id_str);
7378 free(folded_logmsg);
7379 return err;
7382 static struct got_histedit_list_entry *
7383 get_folded_commits(struct got_histedit_list_entry *hle)
7385 struct got_histedit_list_entry *prev, *folded = NULL;
7387 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7388 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7389 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7390 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7391 folded = prev;
7392 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7395 return folded;
7398 static const struct got_error *
7399 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7400 struct got_repository *repo)
7402 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7403 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7404 const struct got_error *err = NULL;
7405 struct got_commit_object *commit = NULL;
7406 int fd;
7407 struct got_histedit_list_entry *folded = NULL;
7409 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7410 if (err)
7411 return err;
7413 folded = get_folded_commits(hle);
7414 if (folded) {
7415 while (folded != hle) {
7416 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7417 folded = TAILQ_NEXT(folded, entry);
7418 continue;
7420 err = append_folded_commit_msg(&new_msg, folded,
7421 logmsg, repo);
7422 if (err)
7423 goto done;
7424 free(logmsg);
7425 logmsg = new_msg;
7426 folded = TAILQ_NEXT(folded, entry);
7430 err = got_object_id_str(&id_str, hle->commit_id);
7431 if (err)
7432 goto done;
7433 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7434 if (err)
7435 goto done;
7436 if (asprintf(&new_msg,
7437 "%s\n# original log message of commit %s: %s",
7438 logmsg ? logmsg : "", id_str, orig_logmsg) == -1) {
7439 err = got_error_from_errno("asprintf");
7440 goto done;
7442 free(logmsg);
7443 logmsg = new_msg;
7445 err = got_object_id_str(&id_str, hle->commit_id);
7446 if (err)
7447 goto done;
7449 err = got_opentemp_named_fd(&logmsg_path, &fd,
7450 GOT_TMPDIR_STR "/got-logmsg");
7451 if (err)
7452 goto done;
7454 dprintf(fd, logmsg);
7455 close(fd);
7457 err = get_editor(&editor);
7458 if (err)
7459 goto done;
7461 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
7462 if (err) {
7463 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
7464 goto done;
7465 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
7467 done:
7468 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
7469 err = got_error_from_errno2("unlink", logmsg_path);
7470 free(logmsg_path);
7471 free(logmsg);
7472 free(orig_logmsg);
7473 free(editor);
7474 if (commit)
7475 got_object_commit_close(commit);
7476 return err;
7479 static const struct got_error *
7480 histedit_parse_list(struct got_histedit_list *histedit_cmds,
7481 FILE *f, struct got_repository *repo)
7483 const struct got_error *err = NULL;
7484 char *line = NULL, *p, *end;
7485 size_t size;
7486 ssize_t len;
7487 int lineno = 0, i;
7488 const struct got_histedit_cmd *cmd;
7489 struct got_object_id *commit_id = NULL;
7490 struct got_histedit_list_entry *hle = NULL;
7492 for (;;) {
7493 len = getline(&line, &size, f);
7494 if (len == -1) {
7495 const struct got_error *getline_err;
7496 if (feof(f))
7497 break;
7498 getline_err = got_error_from_errno("getline");
7499 err = got_ferror(f, getline_err->code);
7500 break;
7502 lineno++;
7503 p = line;
7504 while (isspace((unsigned char)p[0]))
7505 p++;
7506 if (p[0] == '#' || p[0] == '\0') {
7507 free(line);
7508 line = NULL;
7509 continue;
7511 cmd = NULL;
7512 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7513 cmd = &got_histedit_cmds[i];
7514 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
7515 isspace((unsigned char)p[strlen(cmd->name)])) {
7516 p += strlen(cmd->name);
7517 break;
7519 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
7520 p++;
7521 break;
7524 if (i == nitems(got_histedit_cmds)) {
7525 err = histedit_syntax_error(lineno);
7526 break;
7528 while (isspace((unsigned char)p[0]))
7529 p++;
7530 if (cmd->code == GOT_HISTEDIT_MESG) {
7531 if (hle == NULL || hle->logmsg != NULL) {
7532 err = got_error(GOT_ERR_HISTEDIT_CMD);
7533 break;
7535 if (p[0] == '\0') {
7536 err = histedit_edit_logmsg(hle, repo);
7537 if (err)
7538 break;
7539 } else {
7540 hle->logmsg = strdup(p);
7541 if (hle->logmsg == NULL) {
7542 err = got_error_from_errno("strdup");
7543 break;
7546 free(line);
7547 line = NULL;
7548 continue;
7549 } else {
7550 end = p;
7551 while (end[0] && !isspace((unsigned char)end[0]))
7552 end++;
7553 *end = '\0';
7555 err = got_object_resolve_id_str(&commit_id, repo, p);
7556 if (err) {
7557 /* override error code */
7558 err = histedit_syntax_error(lineno);
7559 break;
7562 hle = malloc(sizeof(*hle));
7563 if (hle == NULL) {
7564 err = got_error_from_errno("malloc");
7565 break;
7567 hle->cmd = cmd;
7568 hle->commit_id = commit_id;
7569 hle->logmsg = NULL;
7570 commit_id = NULL;
7571 free(line);
7572 line = NULL;
7573 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
7576 free(line);
7577 free(commit_id);
7578 return err;
7581 static const struct got_error *
7582 histedit_check_script(struct got_histedit_list *histedit_cmds,
7583 struct got_object_id_queue *commits, struct got_repository *repo)
7585 const struct got_error *err = NULL;
7586 struct got_object_qid *qid;
7587 struct got_histedit_list_entry *hle;
7588 static char msg[92];
7589 char *id_str;
7591 if (TAILQ_EMPTY(histedit_cmds))
7592 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
7593 "histedit script contains no commands");
7594 if (SIMPLEQ_EMPTY(commits))
7595 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7597 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7598 struct got_histedit_list_entry *hle2;
7599 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
7600 if (hle == hle2)
7601 continue;
7602 if (got_object_id_cmp(hle->commit_id,
7603 hle2->commit_id) != 0)
7604 continue;
7605 err = got_object_id_str(&id_str, hle->commit_id);
7606 if (err)
7607 return err;
7608 snprintf(msg, sizeof(msg), "commit %s is listed "
7609 "more than once in histedit script", id_str);
7610 free(id_str);
7611 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7615 SIMPLEQ_FOREACH(qid, commits, entry) {
7616 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7617 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
7618 break;
7620 if (hle == NULL) {
7621 err = got_object_id_str(&id_str, qid->id);
7622 if (err)
7623 return err;
7624 snprintf(msg, sizeof(msg),
7625 "commit %s missing from histedit script", id_str);
7626 free(id_str);
7627 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7631 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
7632 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
7633 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
7634 "last commit in histedit script cannot be folded");
7636 return NULL;
7639 static const struct got_error *
7640 histedit_run_editor(struct got_histedit_list *histedit_cmds,
7641 const char *path, struct got_object_id_queue *commits,
7642 struct got_repository *repo)
7644 const struct got_error *err = NULL;
7645 char *editor;
7646 FILE *f = NULL;
7648 err = get_editor(&editor);
7649 if (err)
7650 return err;
7652 if (spawn_editor(editor, path) == -1) {
7653 err = got_error_from_errno("failed spawning editor");
7654 goto done;
7657 f = fopen(path, "r");
7658 if (f == NULL) {
7659 err = got_error_from_errno("fopen");
7660 goto done;
7662 err = histedit_parse_list(histedit_cmds, f, repo);
7663 if (err)
7664 goto done;
7666 err = histedit_check_script(histedit_cmds, commits, repo);
7667 done:
7668 if (f && fclose(f) != 0 && err == NULL)
7669 err = got_error_from_errno("fclose");
7670 free(editor);
7671 return err;
7674 static const struct got_error *
7675 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
7676 struct got_object_id_queue *, const char *, const char *,
7677 struct got_repository *);
7679 static const struct got_error *
7680 histedit_edit_script(struct got_histedit_list *histedit_cmds,
7681 struct got_object_id_queue *commits, const char *branch_name,
7682 int edit_logmsg_only, struct got_repository *repo)
7684 const struct got_error *err;
7685 FILE *f = NULL;
7686 char *path = NULL;
7688 err = got_opentemp_named(&path, &f, "got-histedit");
7689 if (err)
7690 return err;
7692 err = write_cmd_list(f, branch_name, commits);
7693 if (err)
7694 goto done;
7696 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
7697 if (err)
7698 goto done;
7700 if (edit_logmsg_only) {
7701 rewind(f);
7702 err = histedit_parse_list(histedit_cmds, f, repo);
7703 } else {
7704 if (fclose(f) != 0) {
7705 err = got_error_from_errno("fclose");
7706 goto done;
7708 f = NULL;
7709 err = histedit_run_editor(histedit_cmds, path, commits, repo);
7710 if (err) {
7711 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7712 err->code != GOT_ERR_HISTEDIT_CMD)
7713 goto done;
7714 err = histedit_edit_list_retry(histedit_cmds, err,
7715 commits, path, branch_name, repo);
7718 done:
7719 if (f && fclose(f) != 0 && err == NULL)
7720 err = got_error_from_errno("fclose");
7721 if (path && unlink(path) != 0 && err == NULL)
7722 err = got_error_from_errno2("unlink", path);
7723 free(path);
7724 return err;
7727 static const struct got_error *
7728 histedit_save_list(struct got_histedit_list *histedit_cmds,
7729 struct got_worktree *worktree, struct got_repository *repo)
7731 const struct got_error *err = NULL;
7732 char *path = NULL;
7733 FILE *f = NULL;
7734 struct got_histedit_list_entry *hle;
7735 struct got_commit_object *commit = NULL;
7737 err = got_worktree_get_histedit_script_path(&path, worktree);
7738 if (err)
7739 return err;
7741 f = fopen(path, "w");
7742 if (f == NULL) {
7743 err = got_error_from_errno2("fopen", path);
7744 goto done;
7746 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7747 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
7748 repo);
7749 if (err)
7750 break;
7752 if (hle->logmsg) {
7753 int n = fprintf(f, "%c %s\n",
7754 GOT_HISTEDIT_MESG, hle->logmsg);
7755 if (n < 0) {
7756 err = got_ferror(f, GOT_ERR_IO);
7757 break;
7761 done:
7762 if (f && fclose(f) != 0 && err == NULL)
7763 err = got_error_from_errno("fclose");
7764 free(path);
7765 if (commit)
7766 got_object_commit_close(commit);
7767 return err;
7770 void
7771 histedit_free_list(struct got_histedit_list *histedit_cmds)
7773 struct got_histedit_list_entry *hle;
7775 while ((hle = TAILQ_FIRST(histedit_cmds))) {
7776 TAILQ_REMOVE(histedit_cmds, hle, entry);
7777 free(hle);
7781 static const struct got_error *
7782 histedit_load_list(struct got_histedit_list *histedit_cmds,
7783 const char *path, struct got_repository *repo)
7785 const struct got_error *err = NULL;
7786 FILE *f = NULL;
7788 f = fopen(path, "r");
7789 if (f == NULL) {
7790 err = got_error_from_errno2("fopen", path);
7791 goto done;
7794 err = histedit_parse_list(histedit_cmds, f, repo);
7795 done:
7796 if (f && fclose(f) != 0 && err == NULL)
7797 err = got_error_from_errno("fclose");
7798 return err;
7801 static const struct got_error *
7802 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
7803 const struct got_error *edit_err, struct got_object_id_queue *commits,
7804 const char *path, const char *branch_name, struct got_repository *repo)
7806 const struct got_error *err = NULL, *prev_err = edit_err;
7807 int resp = ' ';
7809 while (resp != 'c' && resp != 'r' && resp != 'a') {
7810 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
7811 "or (a)bort: ", getprogname(), prev_err->msg);
7812 resp = getchar();
7813 if (resp == '\n')
7814 resp = getchar();
7815 if (resp == 'c') {
7816 histedit_free_list(histedit_cmds);
7817 err = histedit_run_editor(histedit_cmds, path, commits,
7818 repo);
7819 if (err) {
7820 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7821 err->code != GOT_ERR_HISTEDIT_CMD)
7822 break;
7823 prev_err = err;
7824 resp = ' ';
7825 continue;
7827 break;
7828 } else if (resp == 'r') {
7829 histedit_free_list(histedit_cmds);
7830 err = histedit_edit_script(histedit_cmds,
7831 commits, branch_name, 0, repo);
7832 if (err) {
7833 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7834 err->code != GOT_ERR_HISTEDIT_CMD)
7835 break;
7836 prev_err = err;
7837 resp = ' ';
7838 continue;
7840 break;
7841 } else if (resp == 'a') {
7842 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
7843 break;
7844 } else
7845 printf("invalid response '%c'\n", resp);
7848 return err;
7851 static const struct got_error *
7852 histedit_complete(struct got_worktree *worktree,
7853 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
7854 struct got_reference *branch, struct got_repository *repo)
7856 printf("Switching work tree to %s\n",
7857 got_ref_get_symref_target(branch));
7858 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
7859 branch, repo);
7862 static const struct got_error *
7863 show_histedit_progress(struct got_commit_object *commit,
7864 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
7866 const struct got_error *err;
7867 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7869 err = got_object_id_str(&old_id_str, hle->commit_id);
7870 if (err)
7871 goto done;
7873 if (new_id) {
7874 err = got_object_id_str(&new_id_str, new_id);
7875 if (err)
7876 goto done;
7879 old_id_str[12] = '\0';
7880 if (new_id_str)
7881 new_id_str[12] = '\0';
7883 if (hle->logmsg) {
7884 logmsg = strdup(hle->logmsg);
7885 if (logmsg == NULL) {
7886 err = got_error_from_errno("strdup");
7887 goto done;
7889 trim_logmsg(logmsg, 42);
7890 } else {
7891 err = get_short_logmsg(&logmsg, 42, commit);
7892 if (err)
7893 goto done;
7896 switch (hle->cmd->code) {
7897 case GOT_HISTEDIT_PICK:
7898 case GOT_HISTEDIT_EDIT:
7899 printf("%s -> %s: %s\n", old_id_str,
7900 new_id_str ? new_id_str : "no-op change", logmsg);
7901 break;
7902 case GOT_HISTEDIT_DROP:
7903 case GOT_HISTEDIT_FOLD:
7904 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
7905 logmsg);
7906 break;
7907 default:
7908 break;
7910 done:
7911 free(old_id_str);
7912 free(new_id_str);
7913 return err;
7916 static const struct got_error *
7917 histedit_commit(struct got_pathlist_head *merged_paths,
7918 struct got_worktree *worktree, struct got_fileindex *fileindex,
7919 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
7920 struct got_repository *repo)
7922 const struct got_error *err;
7923 struct got_commit_object *commit;
7924 struct got_object_id *new_commit_id;
7926 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
7927 && hle->logmsg == NULL) {
7928 err = histedit_edit_logmsg(hle, repo);
7929 if (err)
7930 return err;
7933 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7934 if (err)
7935 return err;
7937 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
7938 worktree, fileindex, tmp_branch, commit, hle->commit_id,
7939 hle->logmsg, repo);
7940 if (err) {
7941 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
7942 goto done;
7943 err = show_histedit_progress(commit, hle, NULL);
7944 } else {
7945 err = show_histedit_progress(commit, hle, new_commit_id);
7946 free(new_commit_id);
7948 done:
7949 got_object_commit_close(commit);
7950 return err;
7953 static const struct got_error *
7954 histedit_skip_commit(struct got_histedit_list_entry *hle,
7955 struct got_worktree *worktree, struct got_repository *repo)
7957 const struct got_error *error;
7958 struct got_commit_object *commit;
7960 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
7961 repo);
7962 if (error)
7963 return error;
7965 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
7966 if (error)
7967 return error;
7969 error = show_histedit_progress(commit, hle, NULL);
7970 got_object_commit_close(commit);
7971 return error;
7974 static const struct got_error *
7975 check_local_changes(void *arg, unsigned char status,
7976 unsigned char staged_status, const char *path,
7977 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
7978 struct got_object_id *commit_id, int dirfd, const char *de_name)
7980 int *have_local_changes = arg;
7982 switch (status) {
7983 case GOT_STATUS_ADD:
7984 case GOT_STATUS_DELETE:
7985 case GOT_STATUS_MODIFY:
7986 case GOT_STATUS_CONFLICT:
7987 *have_local_changes = 1;
7988 return got_error(GOT_ERR_CANCELLED);
7989 default:
7990 break;
7993 switch (staged_status) {
7994 case GOT_STATUS_ADD:
7995 case GOT_STATUS_DELETE:
7996 case GOT_STATUS_MODIFY:
7997 *have_local_changes = 1;
7998 return got_error(GOT_ERR_CANCELLED);
7999 default:
8000 break;
8003 return NULL;
8006 static const struct got_error *
8007 cmd_histedit(int argc, char *argv[])
8009 const struct got_error *error = NULL;
8010 struct got_worktree *worktree = NULL;
8011 struct got_fileindex *fileindex = NULL;
8012 struct got_repository *repo = NULL;
8013 char *cwd = NULL;
8014 struct got_reference *branch = NULL;
8015 struct got_reference *tmp_branch = NULL;
8016 struct got_object_id *resume_commit_id = NULL;
8017 struct got_object_id *base_commit_id = NULL;
8018 struct got_object_id *head_commit_id = NULL;
8019 struct got_commit_object *commit = NULL;
8020 int ch, rebase_in_progress = 0;
8021 struct got_update_progress_arg upa;
8022 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8023 int edit_logmsg_only = 0;
8024 const char *edit_script_path = NULL;
8025 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8026 struct got_object_id_queue commits;
8027 struct got_pathlist_head merged_paths;
8028 const struct got_object_id_queue *parent_ids;
8029 struct got_object_qid *pid;
8030 struct got_histedit_list histedit_cmds;
8031 struct got_histedit_list_entry *hle;
8033 SIMPLEQ_INIT(&commits);
8034 TAILQ_INIT(&histedit_cmds);
8035 TAILQ_INIT(&merged_paths);
8036 memset(&upa, 0, sizeof(upa));
8038 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
8039 switch (ch) {
8040 case 'a':
8041 abort_edit = 1;
8042 break;
8043 case 'c':
8044 continue_edit = 1;
8045 break;
8046 case 'F':
8047 edit_script_path = optarg;
8048 break;
8049 case 'm':
8050 edit_logmsg_only = 1;
8051 break;
8052 default:
8053 usage_histedit();
8054 /* NOTREACHED */
8058 argc -= optind;
8059 argv += optind;
8061 #ifndef PROFILE
8062 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8063 "unveil", NULL) == -1)
8064 err(1, "pledge");
8065 #endif
8066 if (abort_edit && continue_edit)
8067 errx(1, "histedit's -a and -c options are mutually exclusive");
8068 if (edit_script_path && edit_logmsg_only)
8069 errx(1, "histedit's -F and -m options are mutually exclusive");
8070 if (abort_edit && edit_logmsg_only)
8071 errx(1, "histedit's -a and -m options are mutually exclusive");
8072 if (continue_edit && edit_logmsg_only)
8073 errx(1, "histedit's -c and -m options are mutually exclusive");
8074 if (argc != 0)
8075 usage_histedit();
8078 * This command cannot apply unveil(2) in all cases because the
8079 * user may choose to run an editor to edit the histedit script
8080 * and to edit individual commit log messages.
8081 * unveil(2) traverses exec(2); if an editor is used we have to
8082 * apply unveil after edit script and log messages have been written.
8083 * XXX TODO: Make use of unveil(2) where possible.
8086 cwd = getcwd(NULL, 0);
8087 if (cwd == NULL) {
8088 error = got_error_from_errno("getcwd");
8089 goto done;
8091 error = got_worktree_open(&worktree, cwd);
8092 if (error) {
8093 if (error->code == GOT_ERR_NOT_WORKTREE)
8094 error = wrap_not_worktree_error(error, "histedit", cwd);
8095 goto done;
8098 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8099 NULL);
8100 if (error != NULL)
8101 goto done;
8103 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8104 if (error)
8105 goto done;
8106 if (rebase_in_progress) {
8107 error = got_error(GOT_ERR_REBASING);
8108 goto done;
8111 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8112 if (error)
8113 goto done;
8115 if (edit_in_progress && edit_logmsg_only) {
8116 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8117 "histedit operation is in progress in this "
8118 "work tree and must be continued or aborted "
8119 "before the -m option can be used");
8120 goto done;
8123 if (edit_in_progress && abort_edit) {
8124 error = got_worktree_histedit_continue(&resume_commit_id,
8125 &tmp_branch, &branch, &base_commit_id, &fileindex,
8126 worktree, repo);
8127 if (error)
8128 goto done;
8129 printf("Switching work tree to %s\n",
8130 got_ref_get_symref_target(branch));
8131 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8132 branch, base_commit_id, update_progress, &upa);
8133 if (error)
8134 goto done;
8135 printf("Histedit of %s aborted\n",
8136 got_ref_get_symref_target(branch));
8137 print_update_progress_stats(&upa);
8138 goto done; /* nothing else to do */
8139 } else if (abort_edit) {
8140 error = got_error(GOT_ERR_NOT_HISTEDIT);
8141 goto done;
8144 if (continue_edit) {
8145 char *path;
8147 if (!edit_in_progress) {
8148 error = got_error(GOT_ERR_NOT_HISTEDIT);
8149 goto done;
8152 error = got_worktree_get_histedit_script_path(&path, worktree);
8153 if (error)
8154 goto done;
8156 error = histedit_load_list(&histedit_cmds, path, repo);
8157 free(path);
8158 if (error)
8159 goto done;
8161 error = got_worktree_histedit_continue(&resume_commit_id,
8162 &tmp_branch, &branch, &base_commit_id, &fileindex,
8163 worktree, repo);
8164 if (error)
8165 goto done;
8167 error = got_ref_resolve(&head_commit_id, repo, branch);
8168 if (error)
8169 goto done;
8171 error = got_object_open_as_commit(&commit, repo,
8172 head_commit_id);
8173 if (error)
8174 goto done;
8175 parent_ids = got_object_commit_get_parent_ids(commit);
8176 pid = SIMPLEQ_FIRST(parent_ids);
8177 if (pid == NULL) {
8178 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8179 goto done;
8181 error = collect_commits(&commits, head_commit_id, pid->id,
8182 base_commit_id, got_worktree_get_path_prefix(worktree),
8183 GOT_ERR_HISTEDIT_PATH, repo);
8184 got_object_commit_close(commit);
8185 commit = NULL;
8186 if (error)
8187 goto done;
8188 } else {
8189 if (edit_in_progress) {
8190 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8191 goto done;
8194 error = got_ref_open(&branch, repo,
8195 got_worktree_get_head_ref_name(worktree), 0);
8196 if (error != NULL)
8197 goto done;
8199 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8200 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8201 "will not edit commit history of a branch outside "
8202 "the \"refs/heads/\" reference namespace");
8203 goto done;
8206 error = got_ref_resolve(&head_commit_id, repo, branch);
8207 got_ref_close(branch);
8208 branch = NULL;
8209 if (error)
8210 goto done;
8212 error = got_object_open_as_commit(&commit, repo,
8213 head_commit_id);
8214 if (error)
8215 goto done;
8216 parent_ids = got_object_commit_get_parent_ids(commit);
8217 pid = SIMPLEQ_FIRST(parent_ids);
8218 if (pid == NULL) {
8219 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8220 goto done;
8222 error = collect_commits(&commits, head_commit_id, pid->id,
8223 got_worktree_get_base_commit_id(worktree),
8224 got_worktree_get_path_prefix(worktree),
8225 GOT_ERR_HISTEDIT_PATH, repo);
8226 got_object_commit_close(commit);
8227 commit = NULL;
8228 if (error)
8229 goto done;
8231 if (SIMPLEQ_EMPTY(&commits)) {
8232 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8233 goto done;
8236 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8237 &base_commit_id, &fileindex, worktree, repo);
8238 if (error)
8239 goto done;
8241 if (edit_script_path) {
8242 error = histedit_load_list(&histedit_cmds,
8243 edit_script_path, repo);
8244 if (error) {
8245 got_worktree_histedit_abort(worktree, fileindex,
8246 repo, branch, base_commit_id,
8247 update_progress, &upa);
8248 print_update_progress_stats(&upa);
8249 goto done;
8251 } else {
8252 const char *branch_name;
8253 branch_name = got_ref_get_symref_target(branch);
8254 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8255 branch_name += 11;
8256 error = histedit_edit_script(&histedit_cmds, &commits,
8257 branch_name, edit_logmsg_only, repo);
8258 if (error) {
8259 got_worktree_histedit_abort(worktree, fileindex,
8260 repo, branch, base_commit_id,
8261 update_progress, &upa);
8262 print_update_progress_stats(&upa);
8263 goto done;
8268 error = histedit_save_list(&histedit_cmds, worktree,
8269 repo);
8270 if (error) {
8271 got_worktree_histedit_abort(worktree, fileindex,
8272 repo, branch, base_commit_id,
8273 update_progress, &upa);
8274 print_update_progress_stats(&upa);
8275 goto done;
8280 error = histedit_check_script(&histedit_cmds, &commits, repo);
8281 if (error)
8282 goto done;
8284 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8285 if (resume_commit_id) {
8286 if (got_object_id_cmp(hle->commit_id,
8287 resume_commit_id) != 0)
8288 continue;
8290 resume_commit_id = NULL;
8291 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8292 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8293 error = histedit_skip_commit(hle, worktree,
8294 repo);
8295 if (error)
8296 goto done;
8297 } else {
8298 struct got_pathlist_head paths;
8299 int have_changes = 0;
8301 TAILQ_INIT(&paths);
8302 error = got_pathlist_append(&paths, "", NULL);
8303 if (error)
8304 goto done;
8305 error = got_worktree_status(worktree, &paths,
8306 repo, check_local_changes, &have_changes,
8307 check_cancelled, NULL);
8308 got_pathlist_free(&paths);
8309 if (error) {
8310 if (error->code != GOT_ERR_CANCELLED)
8311 goto done;
8312 if (sigint_received || sigpipe_received)
8313 goto done;
8315 if (have_changes) {
8316 error = histedit_commit(NULL, worktree,
8317 fileindex, tmp_branch, hle, repo);
8318 if (error)
8319 goto done;
8320 } else {
8321 error = got_object_open_as_commit(
8322 &commit, repo, hle->commit_id);
8323 if (error)
8324 goto done;
8325 error = show_histedit_progress(commit,
8326 hle, NULL);
8327 got_object_commit_close(commit);
8328 commit = NULL;
8329 if (error)
8330 goto done;
8333 continue;
8336 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8337 error = histedit_skip_commit(hle, worktree, repo);
8338 if (error)
8339 goto done;
8340 continue;
8343 error = got_object_open_as_commit(&commit, repo,
8344 hle->commit_id);
8345 if (error)
8346 goto done;
8347 parent_ids = got_object_commit_get_parent_ids(commit);
8348 pid = SIMPLEQ_FIRST(parent_ids);
8350 error = got_worktree_histedit_merge_files(&merged_paths,
8351 worktree, fileindex, pid->id, hle->commit_id, repo,
8352 update_progress, &upa, check_cancelled, NULL);
8353 if (error)
8354 goto done;
8355 got_object_commit_close(commit);
8356 commit = NULL;
8358 print_update_progress_stats(&upa);
8359 if (upa.conflicts > 0)
8360 rebase_status = GOT_STATUS_CONFLICT;
8362 if (rebase_status == GOT_STATUS_CONFLICT) {
8363 error = show_rebase_merge_conflict(hle->commit_id,
8364 repo);
8365 if (error)
8366 goto done;
8367 got_worktree_rebase_pathlist_free(&merged_paths);
8368 break;
8371 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8372 char *id_str;
8373 error = got_object_id_str(&id_str, hle->commit_id);
8374 if (error)
8375 goto done;
8376 printf("Stopping histedit for amending commit %s\n",
8377 id_str);
8378 free(id_str);
8379 got_worktree_rebase_pathlist_free(&merged_paths);
8380 error = got_worktree_histedit_postpone(worktree,
8381 fileindex);
8382 goto done;
8385 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8386 error = histedit_skip_commit(hle, worktree, repo);
8387 if (error)
8388 goto done;
8389 continue;
8392 error = histedit_commit(&merged_paths, worktree, fileindex,
8393 tmp_branch, hle, repo);
8394 got_worktree_rebase_pathlist_free(&merged_paths);
8395 if (error)
8396 goto done;
8399 if (rebase_status == GOT_STATUS_CONFLICT) {
8400 error = got_worktree_histedit_postpone(worktree, fileindex);
8401 if (error)
8402 goto done;
8403 error = got_error_msg(GOT_ERR_CONFLICTS,
8404 "conflicts must be resolved before histedit can continue");
8405 } else
8406 error = histedit_complete(worktree, fileindex, tmp_branch,
8407 branch, repo);
8408 done:
8409 got_object_id_queue_free(&commits);
8410 histedit_free_list(&histedit_cmds);
8411 free(head_commit_id);
8412 free(base_commit_id);
8413 free(resume_commit_id);
8414 if (commit)
8415 got_object_commit_close(commit);
8416 if (branch)
8417 got_ref_close(branch);
8418 if (tmp_branch)
8419 got_ref_close(tmp_branch);
8420 if (worktree)
8421 got_worktree_close(worktree);
8422 if (repo)
8423 got_repo_close(repo);
8424 return error;
8427 __dead static void
8428 usage_integrate(void)
8430 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
8431 exit(1);
8434 static const struct got_error *
8435 cmd_integrate(int argc, char *argv[])
8437 const struct got_error *error = NULL;
8438 struct got_repository *repo = NULL;
8439 struct got_worktree *worktree = NULL;
8440 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
8441 const char *branch_arg = NULL;
8442 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
8443 struct got_fileindex *fileindex = NULL;
8444 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
8445 int ch;
8446 struct got_update_progress_arg upa;
8448 while ((ch = getopt(argc, argv, "")) != -1) {
8449 switch (ch) {
8450 default:
8451 usage_integrate();
8452 /* NOTREACHED */
8456 argc -= optind;
8457 argv += optind;
8459 if (argc != 1)
8460 usage_integrate();
8461 branch_arg = argv[0];
8463 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8464 "unveil", NULL) == -1)
8465 err(1, "pledge");
8467 cwd = getcwd(NULL, 0);
8468 if (cwd == NULL) {
8469 error = got_error_from_errno("getcwd");
8470 goto done;
8473 error = got_worktree_open(&worktree, cwd);
8474 if (error) {
8475 if (error->code == GOT_ERR_NOT_WORKTREE)
8476 error = wrap_not_worktree_error(error, "integrate",
8477 cwd);
8478 goto done;
8481 error = check_rebase_or_histedit_in_progress(worktree);
8482 if (error)
8483 goto done;
8485 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8486 NULL);
8487 if (error != NULL)
8488 goto done;
8490 error = apply_unveil(got_repo_get_path(repo), 0,
8491 got_worktree_get_root_path(worktree));
8492 if (error)
8493 goto done;
8495 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
8496 error = got_error_from_errno("asprintf");
8497 goto done;
8500 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
8501 &base_branch_ref, worktree, refname, repo);
8502 if (error)
8503 goto done;
8505 refname = strdup(got_ref_get_name(branch_ref));
8506 if (refname == NULL) {
8507 error = got_error_from_errno("strdup");
8508 got_worktree_integrate_abort(worktree, fileindex, repo,
8509 branch_ref, base_branch_ref);
8510 goto done;
8512 base_refname = strdup(got_ref_get_name(base_branch_ref));
8513 if (base_refname == NULL) {
8514 error = got_error_from_errno("strdup");
8515 got_worktree_integrate_abort(worktree, fileindex, repo,
8516 branch_ref, base_branch_ref);
8517 goto done;
8520 error = got_ref_resolve(&commit_id, repo, branch_ref);
8521 if (error)
8522 goto done;
8524 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
8525 if (error)
8526 goto done;
8528 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
8529 error = got_error_msg(GOT_ERR_SAME_BRANCH,
8530 "specified branch has already been integrated");
8531 got_worktree_integrate_abort(worktree, fileindex, repo,
8532 branch_ref, base_branch_ref);
8533 goto done;
8536 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
8537 if (error) {
8538 if (error->code == GOT_ERR_ANCESTRY)
8539 error = got_error(GOT_ERR_REBASE_REQUIRED);
8540 got_worktree_integrate_abort(worktree, fileindex, repo,
8541 branch_ref, base_branch_ref);
8542 goto done;
8545 memset(&upa, 0, sizeof(upa));
8546 error = got_worktree_integrate_continue(worktree, fileindex, repo,
8547 branch_ref, base_branch_ref, update_progress, &upa,
8548 check_cancelled, NULL);
8549 if (error)
8550 goto done;
8552 printf("Integrated %s into %s\n", refname, base_refname);
8553 print_update_progress_stats(&upa);
8554 done:
8555 if (repo)
8556 got_repo_close(repo);
8557 if (worktree)
8558 got_worktree_close(worktree);
8559 free(cwd);
8560 free(base_commit_id);
8561 free(commit_id);
8562 free(refname);
8563 free(base_refname);
8564 return error;
8567 __dead static void
8568 usage_stage(void)
8570 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
8571 "[file-path ...]\n",
8572 getprogname());
8573 exit(1);
8576 static const struct got_error *
8577 print_stage(void *arg, unsigned char status, unsigned char staged_status,
8578 const char *path, struct got_object_id *blob_id,
8579 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
8580 int dirfd, const char *de_name)
8582 const struct got_error *err = NULL;
8583 char *id_str = NULL;
8585 if (staged_status != GOT_STATUS_ADD &&
8586 staged_status != GOT_STATUS_MODIFY &&
8587 staged_status != GOT_STATUS_DELETE)
8588 return NULL;
8590 if (staged_status == GOT_STATUS_ADD ||
8591 staged_status == GOT_STATUS_MODIFY)
8592 err = got_object_id_str(&id_str, staged_blob_id);
8593 else
8594 err = got_object_id_str(&id_str, blob_id);
8595 if (err)
8596 return err;
8598 printf("%s %c %s\n", id_str, staged_status, path);
8599 free(id_str);
8600 return NULL;
8603 static const struct got_error *
8604 cmd_stage(int argc, char *argv[])
8606 const struct got_error *error = NULL;
8607 struct got_repository *repo = NULL;
8608 struct got_worktree *worktree = NULL;
8609 char *cwd = NULL;
8610 struct got_pathlist_head paths;
8611 struct got_pathlist_entry *pe;
8612 int ch, list_stage = 0, pflag = 0;
8613 FILE *patch_script_file = NULL;
8614 const char *patch_script_path = NULL;
8615 struct choose_patch_arg cpa;
8617 TAILQ_INIT(&paths);
8619 while ((ch = getopt(argc, argv, "lpF:")) != -1) {
8620 switch (ch) {
8621 case 'l':
8622 list_stage = 1;
8623 break;
8624 case 'p':
8625 pflag = 1;
8626 break;
8627 case 'F':
8628 patch_script_path = optarg;
8629 break;
8630 default:
8631 usage_stage();
8632 /* NOTREACHED */
8636 argc -= optind;
8637 argv += optind;
8639 #ifndef PROFILE
8640 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8641 "unveil", NULL) == -1)
8642 err(1, "pledge");
8643 #endif
8644 if (list_stage && (pflag || patch_script_path))
8645 errx(1, "-l option cannot be used with other options");
8646 if (patch_script_path && !pflag)
8647 errx(1, "-F option can only be used together with -p option");
8649 cwd = getcwd(NULL, 0);
8650 if (cwd == NULL) {
8651 error = got_error_from_errno("getcwd");
8652 goto done;
8655 error = got_worktree_open(&worktree, cwd);
8656 if (error) {
8657 if (error->code == GOT_ERR_NOT_WORKTREE)
8658 error = wrap_not_worktree_error(error, "stage", cwd);
8659 goto done;
8662 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8663 NULL);
8664 if (error != NULL)
8665 goto done;
8667 if (patch_script_path) {
8668 patch_script_file = fopen(patch_script_path, "r");
8669 if (patch_script_file == NULL) {
8670 error = got_error_from_errno2("fopen",
8671 patch_script_path);
8672 goto done;
8675 error = apply_unveil(got_repo_get_path(repo), 0,
8676 got_worktree_get_root_path(worktree));
8677 if (error)
8678 goto done;
8680 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8681 if (error)
8682 goto done;
8684 if (list_stage)
8685 error = got_worktree_status(worktree, &paths, repo,
8686 print_stage, NULL, check_cancelled, NULL);
8687 else {
8688 cpa.patch_script_file = patch_script_file;
8689 cpa.action = "stage";
8690 error = got_worktree_stage(worktree, &paths,
8691 pflag ? NULL : print_status, NULL,
8692 pflag ? choose_patch : NULL, &cpa, repo);
8694 done:
8695 if (patch_script_file && fclose(patch_script_file) == EOF &&
8696 error == NULL)
8697 error = got_error_from_errno2("fclose", patch_script_path);
8698 if (repo)
8699 got_repo_close(repo);
8700 if (worktree)
8701 got_worktree_close(worktree);
8702 TAILQ_FOREACH(pe, &paths, entry)
8703 free((char *)pe->path);
8704 got_pathlist_free(&paths);
8705 free(cwd);
8706 return error;
8709 __dead static void
8710 usage_unstage(void)
8712 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
8713 "[file-path ...]\n",
8714 getprogname());
8715 exit(1);
8719 static const struct got_error *
8720 cmd_unstage(int argc, char *argv[])
8722 const struct got_error *error = NULL;
8723 struct got_repository *repo = NULL;
8724 struct got_worktree *worktree = NULL;
8725 char *cwd = NULL;
8726 struct got_pathlist_head paths;
8727 struct got_pathlist_entry *pe;
8728 int ch, pflag = 0;
8729 struct got_update_progress_arg upa;
8730 FILE *patch_script_file = NULL;
8731 const char *patch_script_path = NULL;
8732 struct choose_patch_arg cpa;
8734 TAILQ_INIT(&paths);
8736 while ((ch = getopt(argc, argv, "pF:")) != -1) {
8737 switch (ch) {
8738 case 'p':
8739 pflag = 1;
8740 break;
8741 case 'F':
8742 patch_script_path = optarg;
8743 break;
8744 default:
8745 usage_unstage();
8746 /* NOTREACHED */
8750 argc -= optind;
8751 argv += optind;
8753 #ifndef PROFILE
8754 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8755 "unveil", NULL) == -1)
8756 err(1, "pledge");
8757 #endif
8758 if (patch_script_path && !pflag)
8759 errx(1, "-F option can only be used together with -p option");
8761 cwd = getcwd(NULL, 0);
8762 if (cwd == NULL) {
8763 error = got_error_from_errno("getcwd");
8764 goto done;
8767 error = got_worktree_open(&worktree, cwd);
8768 if (error) {
8769 if (error->code == GOT_ERR_NOT_WORKTREE)
8770 error = wrap_not_worktree_error(error, "unstage", cwd);
8771 goto done;
8774 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8775 NULL);
8776 if (error != NULL)
8777 goto done;
8779 if (patch_script_path) {
8780 patch_script_file = fopen(patch_script_path, "r");
8781 if (patch_script_file == NULL) {
8782 error = got_error_from_errno2("fopen",
8783 patch_script_path);
8784 goto done;
8788 error = apply_unveil(got_repo_get_path(repo), 0,
8789 got_worktree_get_root_path(worktree));
8790 if (error)
8791 goto done;
8793 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8794 if (error)
8795 goto done;
8797 cpa.patch_script_file = patch_script_file;
8798 cpa.action = "unstage";
8799 memset(&upa, 0, sizeof(upa));
8800 error = got_worktree_unstage(worktree, &paths, update_progress,
8801 &upa, pflag ? choose_patch : NULL, &cpa, repo);
8802 if (!error)
8803 print_update_progress_stats(&upa);
8804 done:
8805 if (patch_script_file && fclose(patch_script_file) == EOF &&
8806 error == NULL)
8807 error = got_error_from_errno2("fclose", patch_script_path);
8808 if (repo)
8809 got_repo_close(repo);
8810 if (worktree)
8811 got_worktree_close(worktree);
8812 TAILQ_FOREACH(pe, &paths, entry)
8813 free((char *)pe->path);
8814 got_pathlist_free(&paths);
8815 free(cwd);
8816 return error;
8819 __dead static void
8820 usage_cat(void)
8822 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
8823 "arg1 [arg2 ...]\n", getprogname());
8824 exit(1);
8827 static const struct got_error *
8828 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8830 const struct got_error *err;
8831 struct got_blob_object *blob;
8833 err = got_object_open_as_blob(&blob, repo, id, 8192);
8834 if (err)
8835 return err;
8837 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
8838 got_object_blob_close(blob);
8839 return err;
8842 static const struct got_error *
8843 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8845 const struct got_error *err;
8846 struct got_tree_object *tree;
8847 int nentries, i;
8849 err = got_object_open_as_tree(&tree, repo, id);
8850 if (err)
8851 return err;
8853 nentries = got_object_tree_get_nentries(tree);
8854 for (i = 0; i < nentries; i++) {
8855 struct got_tree_entry *te;
8856 char *id_str;
8857 if (sigint_received || sigpipe_received)
8858 break;
8859 te = got_object_tree_get_entry(tree, i);
8860 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
8861 if (err)
8862 break;
8863 fprintf(outfile, "%s %.7o %s\n", id_str,
8864 got_tree_entry_get_mode(te),
8865 got_tree_entry_get_name(te));
8866 free(id_str);
8869 got_object_tree_close(tree);
8870 return err;
8873 static const struct got_error *
8874 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8876 const struct got_error *err;
8877 struct got_commit_object *commit;
8878 const struct got_object_id_queue *parent_ids;
8879 struct got_object_qid *pid;
8880 char *id_str = NULL;
8881 const char *logmsg = NULL;
8883 err = got_object_open_as_commit(&commit, repo, id);
8884 if (err)
8885 return err;
8887 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
8888 if (err)
8889 goto done;
8891 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
8892 parent_ids = got_object_commit_get_parent_ids(commit);
8893 fprintf(outfile, "numparents %d\n",
8894 got_object_commit_get_nparents(commit));
8895 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
8896 char *pid_str;
8897 err = got_object_id_str(&pid_str, pid->id);
8898 if (err)
8899 goto done;
8900 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
8901 free(pid_str);
8903 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
8904 got_object_commit_get_author(commit),
8905 got_object_commit_get_author_time(commit));
8907 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
8908 got_object_commit_get_author(commit),
8909 got_object_commit_get_committer_time(commit));
8911 logmsg = got_object_commit_get_logmsg_raw(commit);
8912 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
8913 fprintf(outfile, "%s", logmsg);
8914 done:
8915 free(id_str);
8916 got_object_commit_close(commit);
8917 return err;
8920 static const struct got_error *
8921 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8923 const struct got_error *err;
8924 struct got_tag_object *tag;
8925 char *id_str = NULL;
8926 const char *tagmsg = NULL;
8928 err = got_object_open_as_tag(&tag, repo, id);
8929 if (err)
8930 return err;
8932 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
8933 if (err)
8934 goto done;
8936 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
8938 switch (got_object_tag_get_object_type(tag)) {
8939 case GOT_OBJ_TYPE_BLOB:
8940 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8941 GOT_OBJ_LABEL_BLOB);
8942 break;
8943 case GOT_OBJ_TYPE_TREE:
8944 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8945 GOT_OBJ_LABEL_TREE);
8946 break;
8947 case GOT_OBJ_TYPE_COMMIT:
8948 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8949 GOT_OBJ_LABEL_COMMIT);
8950 break;
8951 case GOT_OBJ_TYPE_TAG:
8952 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8953 GOT_OBJ_LABEL_TAG);
8954 break;
8955 default:
8956 break;
8959 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
8960 got_object_tag_get_name(tag));
8962 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
8963 got_object_tag_get_tagger(tag),
8964 got_object_tag_get_tagger_time(tag));
8966 tagmsg = got_object_tag_get_message(tag);
8967 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
8968 fprintf(outfile, "%s", tagmsg);
8969 done:
8970 free(id_str);
8971 got_object_tag_close(tag);
8972 return err;
8975 static const struct got_error *
8976 cmd_cat(int argc, char *argv[])
8978 const struct got_error *error;
8979 struct got_repository *repo = NULL;
8980 struct got_worktree *worktree = NULL;
8981 char *cwd = NULL, *repo_path = NULL, *label = NULL;
8982 const char *commit_id_str = NULL;
8983 struct got_object_id *id = NULL, *commit_id = NULL;
8984 int ch, obj_type, i, force_path = 0;
8986 #ifndef PROFILE
8987 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8988 NULL) == -1)
8989 err(1, "pledge");
8990 #endif
8992 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
8993 switch (ch) {
8994 case 'c':
8995 commit_id_str = optarg;
8996 break;
8997 case 'r':
8998 repo_path = realpath(optarg, NULL);
8999 if (repo_path == NULL)
9000 return got_error_from_errno2("realpath",
9001 optarg);
9002 got_path_strip_trailing_slashes(repo_path);
9003 break;
9004 case 'P':
9005 force_path = 1;
9006 break;
9007 default:
9008 usage_cat();
9009 /* NOTREACHED */
9013 argc -= optind;
9014 argv += optind;
9016 cwd = getcwd(NULL, 0);
9017 if (cwd == NULL) {
9018 error = got_error_from_errno("getcwd");
9019 goto done;
9021 error = got_worktree_open(&worktree, cwd);
9022 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9023 goto done;
9024 if (worktree) {
9025 if (repo_path == NULL) {
9026 repo_path = strdup(
9027 got_worktree_get_repo_path(worktree));
9028 if (repo_path == NULL) {
9029 error = got_error_from_errno("strdup");
9030 goto done;
9035 if (repo_path == NULL) {
9036 repo_path = getcwd(NULL, 0);
9037 if (repo_path == NULL)
9038 return got_error_from_errno("getcwd");
9041 error = got_repo_open(&repo, repo_path, NULL);
9042 free(repo_path);
9043 if (error != NULL)
9044 goto done;
9046 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9047 if (error)
9048 goto done;
9050 if (commit_id_str == NULL)
9051 commit_id_str = GOT_REF_HEAD;
9052 error = got_repo_match_object_id(&commit_id, NULL,
9053 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
9054 if (error)
9055 goto done;
9057 for (i = 0; i < argc; i++) {
9058 if (force_path) {
9059 error = got_object_id_by_path(&id, repo, commit_id,
9060 argv[i]);
9061 if (error)
9062 break;
9063 } else {
9064 error = got_repo_match_object_id(&id, &label, argv[i],
9065 GOT_OBJ_TYPE_ANY, 0, repo);
9066 if (error) {
9067 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9068 error->code != GOT_ERR_NOT_REF)
9069 break;
9070 error = got_object_id_by_path(&id, repo,
9071 commit_id, argv[i]);
9072 if (error)
9073 break;
9077 error = got_object_get_type(&obj_type, repo, id);
9078 if (error)
9079 break;
9081 switch (obj_type) {
9082 case GOT_OBJ_TYPE_BLOB:
9083 error = cat_blob(id, repo, stdout);
9084 break;
9085 case GOT_OBJ_TYPE_TREE:
9086 error = cat_tree(id, repo, stdout);
9087 break;
9088 case GOT_OBJ_TYPE_COMMIT:
9089 error = cat_commit(id, repo, stdout);
9090 break;
9091 case GOT_OBJ_TYPE_TAG:
9092 error = cat_tag(id, repo, stdout);
9093 break;
9094 default:
9095 error = got_error(GOT_ERR_OBJ_TYPE);
9096 break;
9098 if (error)
9099 break;
9100 free(label);
9101 label = NULL;
9102 free(id);
9103 id = NULL;
9105 done:
9106 free(label);
9107 free(id);
9108 free(commit_id);
9109 if (worktree)
9110 got_worktree_close(worktree);
9111 if (repo) {
9112 const struct got_error *repo_error;
9113 repo_error = got_repo_close(repo);
9114 if (error == NULL)
9115 error = repo_error;
9117 return error;