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 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
2927 free(obj_id2);
2928 goto done;
2930 } else {
2931 err = got_object_id_str(&id_str1, obj_id1);
2932 if (err) {
2933 free(obj_id2);
2934 goto done;
2938 err = got_object_get_type(&obj_type, repo, obj_id2);
2939 if (err) {
2940 free(obj_id2);
2941 goto done;
2943 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2944 switch (obj_type) {
2945 case GOT_OBJ_TYPE_BLOB:
2946 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
2947 0, repo);
2948 break;
2949 case GOT_OBJ_TYPE_TREE:
2950 err = diff_trees(obj_id1, obj_id2, path, diff_context,
2951 0, repo);
2952 break;
2953 default:
2954 err = got_error(GOT_ERR_OBJ_TYPE);
2955 break;
2957 free(obj_id1);
2958 free(obj_id2);
2959 } else {
2960 obj_id2 = got_object_commit_get_tree_id(commit);
2961 err = got_object_id_str(&id_str2, obj_id2);
2962 if (err)
2963 goto done;
2964 obj_id1 = got_object_commit_get_tree_id(pcommit);
2965 err = got_object_id_str(&id_str1, obj_id1);
2966 if (err)
2967 goto done;
2968 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2969 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
2971 done:
2972 free(id_str1);
2973 free(id_str2);
2974 if (pcommit)
2975 got_object_commit_close(pcommit);
2976 return err;
2979 static char *
2980 get_datestr(time_t *time, char *datebuf)
2982 struct tm mytm, *tm;
2983 char *p, *s;
2985 tm = gmtime_r(time, &mytm);
2986 if (tm == NULL)
2987 return NULL;
2988 s = asctime_r(tm, datebuf);
2989 if (s == NULL)
2990 return NULL;
2991 p = strchr(s, '\n');
2992 if (p)
2993 *p = '\0';
2994 return s;
2997 static const struct got_error *
2998 match_logmsg(int *have_match, struct got_object_id *id,
2999 struct got_commit_object *commit, regex_t *regex)
3001 const struct got_error *err = NULL;
3002 regmatch_t regmatch;
3003 char *id_str = NULL, *logmsg = NULL;
3005 *have_match = 0;
3007 err = got_object_id_str(&id_str, id);
3008 if (err)
3009 return err;
3011 err = got_object_commit_get_logmsg(&logmsg, commit);
3012 if (err)
3013 goto done;
3015 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3016 *have_match = 1;
3017 done:
3018 free(id_str);
3019 free(logmsg);
3020 return err;
3023 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3025 static const struct got_error *
3026 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3027 struct got_repository *repo, const char *path, int show_patch,
3028 int diff_context, struct got_reflist_head *refs)
3030 const struct got_error *err = NULL;
3031 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3032 char datebuf[26];
3033 time_t committer_time;
3034 const char *author, *committer;
3035 char *refs_str = NULL;
3036 struct got_reflist_entry *re;
3038 SIMPLEQ_FOREACH(re, refs, entry) {
3039 char *s;
3040 const char *name;
3041 struct got_tag_object *tag = NULL;
3042 int cmp;
3044 name = got_ref_get_name(re->ref);
3045 if (strcmp(name, GOT_REF_HEAD) == 0)
3046 continue;
3047 if (strncmp(name, "refs/", 5) == 0)
3048 name += 5;
3049 if (strncmp(name, "got/", 4) == 0)
3050 continue;
3051 if (strncmp(name, "heads/", 6) == 0)
3052 name += 6;
3053 if (strncmp(name, "remotes/", 8) == 0) {
3054 name += 8;
3055 s = strstr(name, "/" GOT_REF_HEAD);
3056 if (s != NULL && s[strlen(s)] == '\0')
3057 continue;
3059 if (strncmp(name, "tags/", 5) == 0) {
3060 err = got_object_open_as_tag(&tag, repo, re->id);
3061 if (err) {
3062 if (err->code != GOT_ERR_OBJ_TYPE)
3063 return err;
3064 /* Ref points at something other than a tag. */
3065 err = NULL;
3066 tag = NULL;
3069 cmp = got_object_id_cmp(tag ?
3070 got_object_tag_get_object_id(tag) : re->id, id);
3071 if (tag)
3072 got_object_tag_close(tag);
3073 if (cmp != 0)
3074 continue;
3075 s = refs_str;
3076 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3077 name) == -1) {
3078 err = got_error_from_errno("asprintf");
3079 free(s);
3080 return err;
3082 free(s);
3084 err = got_object_id_str(&id_str, id);
3085 if (err)
3086 return err;
3088 printf(GOT_COMMIT_SEP_STR);
3089 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3090 refs_str ? refs_str : "", refs_str ? ")" : "");
3091 free(id_str);
3092 id_str = NULL;
3093 free(refs_str);
3094 refs_str = NULL;
3095 printf("from: %s\n", got_object_commit_get_author(commit));
3096 committer_time = got_object_commit_get_committer_time(commit);
3097 datestr = get_datestr(&committer_time, datebuf);
3098 if (datestr)
3099 printf("date: %s UTC\n", datestr);
3100 author = got_object_commit_get_author(commit);
3101 committer = got_object_commit_get_committer(commit);
3102 if (strcmp(author, committer) != 0)
3103 printf("via: %s\n", committer);
3104 if (got_object_commit_get_nparents(commit) > 1) {
3105 const struct got_object_id_queue *parent_ids;
3106 struct got_object_qid *qid;
3107 int n = 1;
3108 parent_ids = got_object_commit_get_parent_ids(commit);
3109 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3110 err = got_object_id_str(&id_str, qid->id);
3111 if (err)
3112 return err;
3113 printf("parent %d: %s\n", n++, id_str);
3114 free(id_str);
3118 err = got_object_commit_get_logmsg(&logmsg0, commit);
3119 if (err)
3120 return err;
3122 logmsg = logmsg0;
3123 do {
3124 line = strsep(&logmsg, "\n");
3125 if (line)
3126 printf(" %s\n", line);
3127 } while (line);
3128 free(logmsg0);
3130 if (show_patch) {
3131 err = print_patch(commit, id, path, diff_context, repo);
3132 if (err == 0)
3133 printf("\n");
3136 if (fflush(stdout) != 0 && err == NULL)
3137 err = got_error_from_errno("fflush");
3138 return err;
3141 static const struct got_error *
3142 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3143 struct got_repository *repo, const char *path, int show_patch,
3144 const char *search_pattern, int diff_context, int limit, int log_branches,
3145 int reverse_display_order, struct got_reflist_head *refs)
3147 const struct got_error *err;
3148 struct got_commit_graph *graph;
3149 regex_t regex;
3150 int have_match;
3151 struct got_object_id_queue reversed_commits;
3152 struct got_object_qid *qid;
3153 struct got_commit_object *commit;
3155 SIMPLEQ_INIT(&reversed_commits);
3157 if (search_pattern && regcomp(&regex, search_pattern,
3158 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3159 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3161 err = got_commit_graph_open(&graph, path, !log_branches);
3162 if (err)
3163 return err;
3164 err = got_commit_graph_iter_start(graph, root_id, repo,
3165 check_cancelled, NULL);
3166 if (err)
3167 goto done;
3168 for (;;) {
3169 struct got_object_id *id;
3171 if (sigint_received || sigpipe_received)
3172 break;
3174 err = got_commit_graph_iter_next(&id, graph, repo,
3175 check_cancelled, NULL);
3176 if (err) {
3177 if (err->code == GOT_ERR_ITER_COMPLETED)
3178 err = NULL;
3179 break;
3181 if (id == NULL)
3182 break;
3184 err = got_object_open_as_commit(&commit, repo, id);
3185 if (err)
3186 break;
3188 if (search_pattern) {
3189 err = match_logmsg(&have_match, id, commit, &regex);
3190 if (err) {
3191 got_object_commit_close(commit);
3192 break;
3194 if (have_match == 0) {
3195 got_object_commit_close(commit);
3196 continue;
3200 if (reverse_display_order) {
3201 err = got_object_qid_alloc(&qid, id);
3202 if (err)
3203 break;
3204 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3205 got_object_commit_close(commit);
3206 } else {
3207 err = print_commit(commit, id, repo, path, show_patch,
3208 diff_context, refs);
3209 got_object_commit_close(commit);
3210 if (err)
3211 break;
3213 if ((limit && --limit == 0) ||
3214 (end_id && got_object_id_cmp(id, end_id) == 0))
3215 break;
3217 if (reverse_display_order) {
3218 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3219 err = got_object_open_as_commit(&commit, repo, qid->id);
3220 if (err)
3221 break;
3222 err = print_commit(commit, qid->id, repo, path,
3223 show_patch, diff_context, refs);
3224 got_object_commit_close(commit);
3225 if (err)
3226 break;
3229 done:
3230 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3231 qid = SIMPLEQ_FIRST(&reversed_commits);
3232 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3233 got_object_qid_free(qid);
3235 if (search_pattern)
3236 regfree(&regex);
3237 got_commit_graph_close(graph);
3238 return err;
3241 __dead static void
3242 usage_log(void)
3244 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3245 "[-p] [-x commit] [-s search-pattern] [-r repository-path] [-R] "
3246 "[path]\n", getprogname());
3247 exit(1);
3250 static int
3251 get_default_log_limit(void)
3253 const char *got_default_log_limit;
3254 long long n;
3255 const char *errstr;
3257 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3258 if (got_default_log_limit == NULL)
3259 return 0;
3260 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3261 if (errstr != NULL)
3262 return 0;
3263 return n;
3266 static const struct got_error *
3267 resolve_commit_arg(struct got_object_id **id, const char *commit_arg,
3268 struct got_repository *repo)
3270 const struct got_error *err = NULL;
3271 struct got_reference *ref;
3273 *id = NULL;
3275 err = got_ref_open(&ref, repo, commit_arg, 0);
3276 if (err == NULL) {
3277 int obj_type;
3278 err = got_ref_resolve(id, repo, ref);
3279 got_ref_close(ref);
3280 if (err)
3281 return err;
3282 err = got_object_get_type(&obj_type, repo, *id);
3283 if (err)
3284 return err;
3285 if (obj_type == GOT_OBJ_TYPE_TAG) {
3286 struct got_tag_object *tag;
3287 err = got_object_open_as_tag(&tag, repo, *id);
3288 if (err)
3289 return err;
3290 if (got_object_tag_get_object_type(tag) !=
3291 GOT_OBJ_TYPE_COMMIT) {
3292 got_object_tag_close(tag);
3293 return got_error(GOT_ERR_OBJ_TYPE);
3295 free(*id);
3296 *id = got_object_id_dup(
3297 got_object_tag_get_object_id(tag));
3298 if (*id == NULL)
3299 err = got_error_from_errno(
3300 "got_object_id_dup");
3301 got_object_tag_close(tag);
3302 if (err)
3303 return err;
3304 } else if (obj_type != GOT_OBJ_TYPE_COMMIT)
3305 return got_error(GOT_ERR_OBJ_TYPE);
3306 } else {
3307 err = got_repo_match_object_id_prefix(id, commit_arg,
3308 GOT_OBJ_TYPE_COMMIT, repo);
3311 return err;
3314 static const struct got_error *
3315 cmd_log(int argc, char *argv[])
3317 const struct got_error *error;
3318 struct got_repository *repo = NULL;
3319 struct got_worktree *worktree = NULL;
3320 struct got_object_id *start_id = NULL, *end_id = NULL;
3321 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3322 const char *start_commit = NULL, *end_commit = NULL;
3323 const char *search_pattern = NULL;
3324 int diff_context = -1, ch;
3325 int show_patch = 0, limit = 0, log_branches = 0;
3326 int reverse_display_order = 0;
3327 const char *errstr;
3328 struct got_reflist_head refs;
3330 SIMPLEQ_INIT(&refs);
3332 #ifndef PROFILE
3333 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3334 NULL)
3335 == -1)
3336 err(1, "pledge");
3337 #endif
3339 limit = get_default_log_limit();
3341 while ((ch = getopt(argc, argv, "bpc:C:l:r:Rs:x:")) != -1) {
3342 switch (ch) {
3343 case 'p':
3344 show_patch = 1;
3345 break;
3346 case 'c':
3347 start_commit = optarg;
3348 break;
3349 case 'C':
3350 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3351 &errstr);
3352 if (errstr != NULL)
3353 err(1, "-C option %s", errstr);
3354 break;
3355 case 'l':
3356 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3357 if (errstr != NULL)
3358 err(1, "-l option %s", errstr);
3359 break;
3360 case 'b':
3361 log_branches = 1;
3362 break;
3363 case 'r':
3364 repo_path = realpath(optarg, NULL);
3365 if (repo_path == NULL)
3366 return got_error_from_errno2("realpath",
3367 optarg);
3368 got_path_strip_trailing_slashes(repo_path);
3369 break;
3370 case 'R':
3371 reverse_display_order = 1;
3372 break;
3373 case 's':
3374 search_pattern = optarg;
3375 break;
3376 case 'x':
3377 end_commit = optarg;
3378 break;
3379 default:
3380 usage_log();
3381 /* NOTREACHED */
3385 argc -= optind;
3386 argv += optind;
3388 if (diff_context == -1)
3389 diff_context = 3;
3390 else if (!show_patch)
3391 errx(1, "-C reguires -p");
3393 cwd = getcwd(NULL, 0);
3394 if (cwd == NULL) {
3395 error = got_error_from_errno("getcwd");
3396 goto done;
3399 if (repo_path == NULL) {
3400 error = got_worktree_open(&worktree, cwd);
3401 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3402 goto done;
3403 error = NULL;
3406 if (argc == 0) {
3407 path = strdup("");
3408 if (path == NULL) {
3409 error = got_error_from_errno("strdup");
3410 goto done;
3412 } else if (argc == 1) {
3413 if (worktree) {
3414 error = got_worktree_resolve_path(&path, worktree,
3415 argv[0]);
3416 if (error)
3417 goto done;
3418 } else {
3419 path = strdup(argv[0]);
3420 if (path == NULL) {
3421 error = got_error_from_errno("strdup");
3422 goto done;
3425 } else
3426 usage_log();
3428 if (repo_path == NULL) {
3429 repo_path = worktree ?
3430 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3432 if (repo_path == NULL) {
3433 error = got_error_from_errno("strdup");
3434 goto done;
3437 error = got_repo_open(&repo, repo_path, NULL);
3438 if (error != NULL)
3439 goto done;
3441 error = apply_unveil(got_repo_get_path(repo), 1,
3442 worktree ? got_worktree_get_root_path(worktree) : NULL);
3443 if (error)
3444 goto done;
3446 if (start_commit == NULL) {
3447 struct got_reference *head_ref;
3448 struct got_commit_object *commit = NULL;
3449 error = got_ref_open(&head_ref, repo,
3450 worktree ? got_worktree_get_head_ref_name(worktree)
3451 : GOT_REF_HEAD, 0);
3452 if (error != NULL)
3453 goto done;
3454 error = got_ref_resolve(&start_id, repo, head_ref);
3455 got_ref_close(head_ref);
3456 if (error != NULL)
3457 goto done;
3458 error = got_object_open_as_commit(&commit, repo,
3459 start_id);
3460 if (error != NULL)
3461 goto done;
3462 got_object_commit_close(commit);
3463 } else {
3464 error = resolve_commit_arg(&start_id, start_commit, repo);
3465 if (error != NULL)
3466 goto done;
3468 if (end_commit != NULL) {
3469 error = resolve_commit_arg(&end_id, end_commit, repo);
3470 if (error != NULL)
3471 goto done;
3474 if (worktree) {
3475 const char *prefix = got_worktree_get_path_prefix(worktree);
3476 char *p;
3477 if (asprintf(&p, "%s%s%s", prefix,
3478 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3479 error = got_error_from_errno("asprintf");
3480 goto done;
3482 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3483 free(p);
3484 } else
3485 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3486 if (error != NULL)
3487 goto done;
3488 if (in_repo_path) {
3489 free(path);
3490 path = in_repo_path;
3493 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3494 if (error)
3495 goto done;
3497 error = print_commits(start_id, end_id, repo, path, show_patch,
3498 search_pattern, diff_context, limit, log_branches,
3499 reverse_display_order, &refs);
3500 done:
3501 free(path);
3502 free(repo_path);
3503 free(cwd);
3504 if (worktree)
3505 got_worktree_close(worktree);
3506 if (repo) {
3507 const struct got_error *repo_error;
3508 repo_error = got_repo_close(repo);
3509 if (error == NULL)
3510 error = repo_error;
3512 got_ref_list_free(&refs);
3513 return error;
3516 __dead static void
3517 usage_diff(void)
3519 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3520 "[-w] [object1 object2 | path]\n", getprogname());
3521 exit(1);
3524 struct print_diff_arg {
3525 struct got_repository *repo;
3526 struct got_worktree *worktree;
3527 int diff_context;
3528 const char *id_str;
3529 int header_shown;
3530 int diff_staged;
3531 int ignore_whitespace;
3534 static const struct got_error *
3535 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3536 const char *path, struct got_object_id *blob_id,
3537 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3538 int dirfd, const char *de_name)
3540 struct print_diff_arg *a = arg;
3541 const struct got_error *err = NULL;
3542 struct got_blob_object *blob1 = NULL;
3543 int fd = -1;
3544 FILE *f2 = NULL;
3545 char *abspath = NULL, *label1 = NULL;
3546 struct stat sb;
3548 if (a->diff_staged) {
3549 if (staged_status != GOT_STATUS_MODIFY &&
3550 staged_status != GOT_STATUS_ADD &&
3551 staged_status != GOT_STATUS_DELETE)
3552 return NULL;
3553 } else {
3554 if (staged_status == GOT_STATUS_DELETE)
3555 return NULL;
3556 if (status == GOT_STATUS_NONEXISTENT)
3557 return got_error_set_errno(ENOENT, path);
3558 if (status != GOT_STATUS_MODIFY &&
3559 status != GOT_STATUS_ADD &&
3560 status != GOT_STATUS_DELETE &&
3561 status != GOT_STATUS_CONFLICT)
3562 return NULL;
3565 if (!a->header_shown) {
3566 printf("diff %s %s%s\n", a->id_str,
3567 got_worktree_get_root_path(a->worktree),
3568 a->diff_staged ? " (staged changes)" : "");
3569 a->header_shown = 1;
3572 if (a->diff_staged) {
3573 const char *label1 = NULL, *label2 = NULL;
3574 switch (staged_status) {
3575 case GOT_STATUS_MODIFY:
3576 label1 = path;
3577 label2 = path;
3578 break;
3579 case GOT_STATUS_ADD:
3580 label2 = path;
3581 break;
3582 case GOT_STATUS_DELETE:
3583 label1 = path;
3584 break;
3585 default:
3586 return got_error(GOT_ERR_FILE_STATUS);
3588 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
3589 label1, label2, a->diff_context, a->ignore_whitespace,
3590 a->repo, stdout);
3593 if (staged_status == GOT_STATUS_ADD ||
3594 staged_status == GOT_STATUS_MODIFY) {
3595 char *id_str;
3596 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
3597 8192);
3598 if (err)
3599 goto done;
3600 err = got_object_id_str(&id_str, staged_blob_id);
3601 if (err)
3602 goto done;
3603 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
3604 err = got_error_from_errno("asprintf");
3605 free(id_str);
3606 goto done;
3608 free(id_str);
3609 } else if (status != GOT_STATUS_ADD) {
3610 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
3611 if (err)
3612 goto done;
3615 if (status != GOT_STATUS_DELETE) {
3616 if (asprintf(&abspath, "%s/%s",
3617 got_worktree_get_root_path(a->worktree), path) == -1) {
3618 err = got_error_from_errno("asprintf");
3619 goto done;
3622 if (dirfd != -1) {
3623 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
3624 if (fd == -1) {
3625 err = got_error_from_errno2("openat", abspath);
3626 goto done;
3628 } else {
3629 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
3630 if (fd == -1) {
3631 err = got_error_from_errno2("open", abspath);
3632 goto done;
3635 if (fstat(fd, &sb) == -1) {
3636 err = got_error_from_errno2("fstat", abspath);
3637 goto done;
3639 f2 = fdopen(fd, "r");
3640 if (f2 == NULL) {
3641 err = got_error_from_errno2("fdopen", abspath);
3642 goto done;
3644 fd = -1;
3645 } else
3646 sb.st_size = 0;
3648 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
3649 a->diff_context, a->ignore_whitespace, stdout);
3650 done:
3651 if (blob1)
3652 got_object_blob_close(blob1);
3653 if (f2 && fclose(f2) == EOF && err == NULL)
3654 err = got_error_from_errno("fclose");
3655 if (fd != -1 && close(fd) == -1 && err == NULL)
3656 err = got_error_from_errno("close");
3657 free(abspath);
3658 return err;
3661 static const struct got_error *
3662 cmd_diff(int argc, char *argv[])
3664 const struct got_error *error;
3665 struct got_repository *repo = NULL;
3666 struct got_worktree *worktree = NULL;
3667 char *cwd = NULL, *repo_path = NULL;
3668 struct got_object_id *id1 = NULL, *id2 = NULL;
3669 const char *id_str1 = NULL, *id_str2 = NULL;
3670 char *label1 = NULL, *label2 = NULL;
3671 int type1, type2;
3672 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
3673 const char *errstr;
3674 char *path = NULL;
3676 #ifndef PROFILE
3677 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3678 NULL) == -1)
3679 err(1, "pledge");
3680 #endif
3682 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
3683 switch (ch) {
3684 case 'C':
3685 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3686 &errstr);
3687 if (errstr != NULL)
3688 err(1, "-C option %s", errstr);
3689 break;
3690 case 'r':
3691 repo_path = realpath(optarg, NULL);
3692 if (repo_path == NULL)
3693 return got_error_from_errno2("realpath",
3694 optarg);
3695 got_path_strip_trailing_slashes(repo_path);
3696 break;
3697 case 's':
3698 diff_staged = 1;
3699 break;
3700 case 'w':
3701 ignore_whitespace = 1;
3702 break;
3703 default:
3704 usage_diff();
3705 /* NOTREACHED */
3709 argc -= optind;
3710 argv += optind;
3712 cwd = getcwd(NULL, 0);
3713 if (cwd == NULL) {
3714 error = got_error_from_errno("getcwd");
3715 goto done;
3717 if (argc <= 1) {
3718 if (repo_path)
3719 errx(1,
3720 "-r option can't be used when diffing a work tree");
3721 error = got_worktree_open(&worktree, cwd);
3722 if (error) {
3723 if (error->code == GOT_ERR_NOT_WORKTREE)
3724 error = wrap_not_worktree_error(error, "diff",
3725 cwd);
3726 goto done;
3728 repo_path = strdup(got_worktree_get_repo_path(worktree));
3729 if (repo_path == NULL) {
3730 error = got_error_from_errno("strdup");
3731 goto done;
3733 if (argc == 1) {
3734 error = got_worktree_resolve_path(&path, worktree,
3735 argv[0]);
3736 if (error)
3737 goto done;
3738 } else {
3739 path = strdup("");
3740 if (path == NULL) {
3741 error = got_error_from_errno("strdup");
3742 goto done;
3745 } else if (argc == 2) {
3746 if (diff_staged)
3747 errx(1, "-s option can't be used when diffing "
3748 "objects in repository");
3749 id_str1 = argv[0];
3750 id_str2 = argv[1];
3751 if (repo_path == NULL) {
3752 error = got_worktree_open(&worktree, cwd);
3753 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3754 goto done;
3755 if (worktree) {
3756 repo_path = strdup(
3757 got_worktree_get_repo_path(worktree));
3758 if (repo_path == NULL) {
3759 error = got_error_from_errno("strdup");
3760 goto done;
3762 } else {
3763 repo_path = strdup(cwd);
3764 if (repo_path == NULL) {
3765 error = got_error_from_errno("strdup");
3766 goto done;
3770 } else
3771 usage_diff();
3773 error = got_repo_open(&repo, repo_path, NULL);
3774 free(repo_path);
3775 if (error != NULL)
3776 goto done;
3778 error = apply_unveil(got_repo_get_path(repo), 1,
3779 worktree ? got_worktree_get_root_path(worktree) : NULL);
3780 if (error)
3781 goto done;
3783 if (argc <= 1) {
3784 struct print_diff_arg arg;
3785 struct got_pathlist_head paths;
3786 char *id_str;
3788 TAILQ_INIT(&paths);
3790 error = got_object_id_str(&id_str,
3791 got_worktree_get_base_commit_id(worktree));
3792 if (error)
3793 goto done;
3794 arg.repo = repo;
3795 arg.worktree = worktree;
3796 arg.diff_context = diff_context;
3797 arg.id_str = id_str;
3798 arg.header_shown = 0;
3799 arg.diff_staged = diff_staged;
3800 arg.ignore_whitespace = ignore_whitespace;
3802 error = got_pathlist_append(&paths, path, NULL);
3803 if (error)
3804 goto done;
3806 error = got_worktree_status(worktree, &paths, repo, print_diff,
3807 &arg, check_cancelled, NULL);
3808 free(id_str);
3809 got_pathlist_free(&paths);
3810 goto done;
3813 error = got_repo_match_object_id(&id1, &label1, id_str1,
3814 GOT_OBJ_TYPE_ANY, 1, repo);
3815 if (error)
3816 goto done;
3818 error = got_repo_match_object_id(&id2, &label2, id_str2,
3819 GOT_OBJ_TYPE_ANY, 1, repo);
3820 if (error)
3821 goto done;
3823 error = got_object_get_type(&type1, repo, id1);
3824 if (error)
3825 goto done;
3827 error = got_object_get_type(&type2, repo, id2);
3828 if (error)
3829 goto done;
3831 if (type1 != type2) {
3832 error = got_error(GOT_ERR_OBJ_TYPE);
3833 goto done;
3836 switch (type1) {
3837 case GOT_OBJ_TYPE_BLOB:
3838 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
3839 diff_context, ignore_whitespace, repo, stdout);
3840 break;
3841 case GOT_OBJ_TYPE_TREE:
3842 error = got_diff_objects_as_trees(id1, id2, "", "",
3843 diff_context, ignore_whitespace, repo, stdout);
3844 break;
3845 case GOT_OBJ_TYPE_COMMIT:
3846 printf("diff %s %s\n", label1, label2);
3847 error = got_diff_objects_as_commits(id1, id2, diff_context,
3848 ignore_whitespace, repo, stdout);
3849 break;
3850 default:
3851 error = got_error(GOT_ERR_OBJ_TYPE);
3853 done:
3854 free(label1);
3855 free(label2);
3856 free(id1);
3857 free(id2);
3858 free(path);
3859 if (worktree)
3860 got_worktree_close(worktree);
3861 if (repo) {
3862 const struct got_error *repo_error;
3863 repo_error = got_repo_close(repo);
3864 if (error == NULL)
3865 error = repo_error;
3867 return error;
3870 __dead static void
3871 usage_blame(void)
3873 fprintf(stderr,
3874 "usage: %s blame [-c commit] [-r repository-path] path\n",
3875 getprogname());
3876 exit(1);
3879 struct blame_line {
3880 int annotated;
3881 char *id_str;
3882 char *committer;
3883 char datebuf[11]; /* YYYY-MM-DD + NUL */
3886 struct blame_cb_args {
3887 struct blame_line *lines;
3888 int nlines;
3889 int nlines_prec;
3890 int lineno_cur;
3891 off_t *line_offsets;
3892 FILE *f;
3893 struct got_repository *repo;
3896 static const struct got_error *
3897 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
3899 const struct got_error *err = NULL;
3900 struct blame_cb_args *a = arg;
3901 struct blame_line *bline;
3902 char *line = NULL;
3903 size_t linesize = 0;
3904 struct got_commit_object *commit = NULL;
3905 off_t offset;
3906 struct tm tm;
3907 time_t committer_time;
3909 if (nlines != a->nlines ||
3910 (lineno != -1 && lineno < 1) || lineno > a->nlines)
3911 return got_error(GOT_ERR_RANGE);
3913 if (sigint_received)
3914 return got_error(GOT_ERR_ITER_COMPLETED);
3916 if (lineno == -1)
3917 return NULL; /* no change in this commit */
3919 /* Annotate this line. */
3920 bline = &a->lines[lineno - 1];
3921 if (bline->annotated)
3922 return NULL;
3923 err = got_object_id_str(&bline->id_str, id);
3924 if (err)
3925 return err;
3927 err = got_object_open_as_commit(&commit, a->repo, id);
3928 if (err)
3929 goto done;
3931 bline->committer = strdup(got_object_commit_get_committer(commit));
3932 if (bline->committer == NULL) {
3933 err = got_error_from_errno("strdup");
3934 goto done;
3937 committer_time = got_object_commit_get_committer_time(commit);
3938 if (localtime_r(&committer_time, &tm) == NULL)
3939 return got_error_from_errno("localtime_r");
3940 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
3941 &tm) >= sizeof(bline->datebuf)) {
3942 err = got_error(GOT_ERR_NO_SPACE);
3943 goto done;
3945 bline->annotated = 1;
3947 /* Print lines annotated so far. */
3948 bline = &a->lines[a->lineno_cur - 1];
3949 if (!bline->annotated)
3950 goto done;
3952 offset = a->line_offsets[a->lineno_cur - 1];
3953 if (fseeko(a->f, offset, SEEK_SET) == -1) {
3954 err = got_error_from_errno("fseeko");
3955 goto done;
3958 while (bline->annotated) {
3959 char *smallerthan, *at, *nl, *committer;
3960 size_t len;
3962 if (getline(&line, &linesize, a->f) == -1) {
3963 if (ferror(a->f))
3964 err = got_error_from_errno("getline");
3965 break;
3968 committer = bline->committer;
3969 smallerthan = strchr(committer, '<');
3970 if (smallerthan && smallerthan[1] != '\0')
3971 committer = smallerthan + 1;
3972 at = strchr(committer, '@');
3973 if (at)
3974 *at = '\0';
3975 len = strlen(committer);
3976 if (len >= 9)
3977 committer[8] = '\0';
3979 nl = strchr(line, '\n');
3980 if (nl)
3981 *nl = '\0';
3982 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
3983 bline->id_str, bline->datebuf, committer, line);
3985 a->lineno_cur++;
3986 bline = &a->lines[a->lineno_cur - 1];
3988 done:
3989 if (commit)
3990 got_object_commit_close(commit);
3991 free(line);
3992 return err;
3995 static const struct got_error *
3996 cmd_blame(int argc, char *argv[])
3998 const struct got_error *error;
3999 struct got_repository *repo = NULL;
4000 struct got_worktree *worktree = NULL;
4001 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4002 struct got_object_id *obj_id = NULL;
4003 struct got_object_id *commit_id = NULL;
4004 struct got_blob_object *blob = NULL;
4005 char *commit_id_str = NULL;
4006 struct blame_cb_args bca;
4007 int ch, obj_type, i;
4008 size_t filesize;
4010 memset(&bca, 0, sizeof(bca));
4012 #ifndef PROFILE
4013 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4014 NULL) == -1)
4015 err(1, "pledge");
4016 #endif
4018 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4019 switch (ch) {
4020 case 'c':
4021 commit_id_str = optarg;
4022 break;
4023 case 'r':
4024 repo_path = realpath(optarg, NULL);
4025 if (repo_path == NULL)
4026 return got_error_from_errno2("realpath",
4027 optarg);
4028 got_path_strip_trailing_slashes(repo_path);
4029 break;
4030 default:
4031 usage_blame();
4032 /* NOTREACHED */
4036 argc -= optind;
4037 argv += optind;
4039 if (argc == 1)
4040 path = argv[0];
4041 else
4042 usage_blame();
4044 cwd = getcwd(NULL, 0);
4045 if (cwd == NULL) {
4046 error = got_error_from_errno("getcwd");
4047 goto done;
4049 if (repo_path == NULL) {
4050 error = got_worktree_open(&worktree, cwd);
4051 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4052 goto done;
4053 else
4054 error = NULL;
4055 if (worktree) {
4056 repo_path =
4057 strdup(got_worktree_get_repo_path(worktree));
4058 if (repo_path == NULL) {
4059 error = got_error_from_errno("strdup");
4060 if (error)
4061 goto done;
4063 } else {
4064 repo_path = strdup(cwd);
4065 if (repo_path == NULL) {
4066 error = got_error_from_errno("strdup");
4067 goto done;
4072 error = got_repo_open(&repo, repo_path, NULL);
4073 if (error != NULL)
4074 goto done;
4076 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4077 if (error)
4078 goto done;
4080 if (worktree) {
4081 const char *prefix = got_worktree_get_path_prefix(worktree);
4082 char *p, *worktree_subdir = cwd +
4083 strlen(got_worktree_get_root_path(worktree));
4084 if (asprintf(&p, "%s%s%s%s%s",
4085 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
4086 worktree_subdir, worktree_subdir[0] ? "/" : "",
4087 path) == -1) {
4088 error = got_error_from_errno("asprintf");
4089 goto done;
4091 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4092 free(p);
4093 } else {
4094 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4096 if (error)
4097 goto done;
4099 if (commit_id_str == NULL) {
4100 struct got_reference *head_ref;
4101 error = got_ref_open(&head_ref, repo, worktree ?
4102 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4103 if (error != NULL)
4104 goto done;
4105 error = got_ref_resolve(&commit_id, repo, head_ref);
4106 got_ref_close(head_ref);
4107 if (error != NULL)
4108 goto done;
4109 } else {
4110 error = got_repo_match_object_id(&commit_id, NULL,
4111 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4112 if (error)
4113 goto done;
4116 error = got_object_id_by_path(&obj_id, repo, commit_id, in_repo_path);
4117 if (error)
4118 goto done;
4120 error = got_object_get_type(&obj_type, repo, obj_id);
4121 if (error)
4122 goto done;
4124 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4125 error = got_error(GOT_ERR_OBJ_TYPE);
4126 goto done;
4129 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4130 if (error)
4131 goto done;
4132 bca.f = got_opentemp();
4133 if (bca.f == NULL) {
4134 error = got_error_from_errno("got_opentemp");
4135 goto done;
4137 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4138 &bca.line_offsets, bca.f, blob);
4139 if (error || bca.nlines == 0)
4140 goto done;
4142 /* Don't include \n at EOF in the blame line count. */
4143 if (bca.line_offsets[bca.nlines - 1] == filesize)
4144 bca.nlines--;
4146 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4147 if (bca.lines == NULL) {
4148 error = got_error_from_errno("calloc");
4149 goto done;
4151 bca.lineno_cur = 1;
4152 bca.nlines_prec = 0;
4153 i = bca.nlines;
4154 while (i > 0) {
4155 i /= 10;
4156 bca.nlines_prec++;
4158 bca.repo = repo;
4160 error = got_blame(in_repo_path, commit_id, repo, blame_cb, &bca,
4161 check_cancelled, NULL);
4162 done:
4163 free(in_repo_path);
4164 free(repo_path);
4165 free(cwd);
4166 free(commit_id);
4167 free(obj_id);
4168 if (blob)
4169 got_object_blob_close(blob);
4170 if (worktree)
4171 got_worktree_close(worktree);
4172 if (repo) {
4173 const struct got_error *repo_error;
4174 repo_error = got_repo_close(repo);
4175 if (error == NULL)
4176 error = repo_error;
4178 if (bca.lines) {
4179 for (i = 0; i < bca.nlines; i++) {
4180 struct blame_line *bline = &bca.lines[i];
4181 free(bline->id_str);
4182 free(bline->committer);
4184 free(bca.lines);
4186 free(bca.line_offsets);
4187 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4188 error = got_error_from_errno("fclose");
4189 return error;
4192 __dead static void
4193 usage_tree(void)
4195 fprintf(stderr,
4196 "usage: %s tree [-c commit] [-r repository-path] [-iR] path\n",
4197 getprogname());
4198 exit(1);
4201 static void
4202 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4203 const char *root_path)
4205 int is_root_path = (strcmp(path, root_path) == 0);
4206 const char *modestr = "";
4207 mode_t mode = got_tree_entry_get_mode(te);
4209 path += strlen(root_path);
4210 while (path[0] == '/')
4211 path++;
4213 if (got_object_tree_entry_is_submodule(te))
4214 modestr = "$";
4215 else if (S_ISLNK(mode))
4216 modestr = "@";
4217 else if (S_ISDIR(mode))
4218 modestr = "/";
4219 else if (mode & S_IXUSR)
4220 modestr = "*";
4222 printf("%s%s%s%s%s\n", id ? id : "", path,
4223 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr);
4226 static const struct got_error *
4227 print_tree(const char *path, struct got_object_id *commit_id,
4228 int show_ids, int recurse, const char *root_path,
4229 struct got_repository *repo)
4231 const struct got_error *err = NULL;
4232 struct got_object_id *tree_id = NULL;
4233 struct got_tree_object *tree = NULL;
4234 int nentries, i;
4236 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4237 if (err)
4238 goto done;
4240 err = got_object_open_as_tree(&tree, repo, tree_id);
4241 if (err)
4242 goto done;
4243 nentries = got_object_tree_get_nentries(tree);
4244 for (i = 0; i < nentries; i++) {
4245 struct got_tree_entry *te;
4246 char *id = NULL;
4248 if (sigint_received || sigpipe_received)
4249 break;
4251 te = got_object_tree_get_entry(tree, i);
4252 if (show_ids) {
4253 char *id_str;
4254 err = got_object_id_str(&id_str,
4255 got_tree_entry_get_id(te));
4256 if (err)
4257 goto done;
4258 if (asprintf(&id, "%s ", id_str) == -1) {
4259 err = got_error_from_errno("asprintf");
4260 free(id_str);
4261 goto done;
4263 free(id_str);
4265 print_entry(te, id, path, root_path);
4266 free(id);
4268 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4269 char *child_path;
4270 if (asprintf(&child_path, "%s%s%s", path,
4271 path[0] == '/' && path[1] == '\0' ? "" : "/",
4272 got_tree_entry_get_name(te)) == -1) {
4273 err = got_error_from_errno("asprintf");
4274 goto done;
4276 err = print_tree(child_path, commit_id, show_ids, 1,
4277 root_path, repo);
4278 free(child_path);
4279 if (err)
4280 goto done;
4283 done:
4284 if (tree)
4285 got_object_tree_close(tree);
4286 free(tree_id);
4287 return err;
4290 static const struct got_error *
4291 cmd_tree(int argc, char *argv[])
4293 const struct got_error *error;
4294 struct got_repository *repo = NULL;
4295 struct got_worktree *worktree = NULL;
4296 const char *path, *refname = NULL;
4297 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4298 struct got_object_id *commit_id = NULL;
4299 char *commit_id_str = NULL;
4300 int show_ids = 0, recurse = 0;
4301 int ch;
4303 #ifndef PROFILE
4304 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4305 NULL) == -1)
4306 err(1, "pledge");
4307 #endif
4309 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4310 switch (ch) {
4311 case 'c':
4312 commit_id_str = optarg;
4313 break;
4314 case 'r':
4315 repo_path = realpath(optarg, NULL);
4316 if (repo_path == NULL)
4317 return got_error_from_errno2("realpath",
4318 optarg);
4319 got_path_strip_trailing_slashes(repo_path);
4320 break;
4321 case 'i':
4322 show_ids = 1;
4323 break;
4324 case 'R':
4325 recurse = 1;
4326 break;
4327 default:
4328 usage_tree();
4329 /* NOTREACHED */
4333 argc -= optind;
4334 argv += optind;
4336 if (argc == 1)
4337 path = argv[0];
4338 else if (argc > 1)
4339 usage_tree();
4340 else
4341 path = NULL;
4343 cwd = getcwd(NULL, 0);
4344 if (cwd == NULL) {
4345 error = got_error_from_errno("getcwd");
4346 goto done;
4348 if (repo_path == NULL) {
4349 error = got_worktree_open(&worktree, cwd);
4350 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4351 goto done;
4352 else
4353 error = NULL;
4354 if (worktree) {
4355 repo_path =
4356 strdup(got_worktree_get_repo_path(worktree));
4357 if (repo_path == NULL)
4358 error = got_error_from_errno("strdup");
4359 if (error)
4360 goto done;
4361 } else {
4362 repo_path = strdup(cwd);
4363 if (repo_path == NULL) {
4364 error = got_error_from_errno("strdup");
4365 goto done;
4370 error = got_repo_open(&repo, repo_path, NULL);
4371 if (error != NULL)
4372 goto done;
4374 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4375 if (error)
4376 goto done;
4378 if (path == NULL) {
4379 if (worktree) {
4380 char *p, *worktree_subdir = cwd +
4381 strlen(got_worktree_get_root_path(worktree));
4382 if (asprintf(&p, "%s/%s",
4383 got_worktree_get_path_prefix(worktree),
4384 worktree_subdir) == -1) {
4385 error = got_error_from_errno("asprintf");
4386 goto done;
4388 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4389 free(p);
4390 if (error)
4391 goto done;
4392 } else
4393 path = "/";
4395 if (in_repo_path == NULL) {
4396 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4397 if (error != NULL)
4398 goto done;
4401 if (commit_id_str == NULL) {
4402 struct got_reference *head_ref;
4403 if (worktree)
4404 refname = got_worktree_get_head_ref_name(worktree);
4405 else
4406 refname = GOT_REF_HEAD;
4407 error = got_ref_open(&head_ref, repo, refname, 0);
4408 if (error != NULL)
4409 goto done;
4410 error = got_ref_resolve(&commit_id, repo, head_ref);
4411 got_ref_close(head_ref);
4412 if (error != NULL)
4413 goto done;
4414 } else {
4415 error = got_repo_match_object_id(&commit_id, NULL,
4416 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4417 if (error)
4418 goto done;
4421 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4422 in_repo_path, repo);
4423 done:
4424 free(in_repo_path);
4425 free(repo_path);
4426 free(cwd);
4427 free(commit_id);
4428 if (worktree)
4429 got_worktree_close(worktree);
4430 if (repo) {
4431 const struct got_error *repo_error;
4432 repo_error = got_repo_close(repo);
4433 if (error == NULL)
4434 error = repo_error;
4436 return error;
4439 __dead static void
4440 usage_status(void)
4442 fprintf(stderr, "usage: %s status [path ...]\n", getprogname());
4443 exit(1);
4446 static const struct got_error *
4447 print_status(void *arg, unsigned char status, unsigned char staged_status,
4448 const char *path, struct got_object_id *blob_id,
4449 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4450 int dirfd, const char *de_name)
4452 if (status == staged_status && (status == GOT_STATUS_DELETE))
4453 status = GOT_STATUS_NO_CHANGE;
4454 printf("%c%c %s\n", status, staged_status, path);
4455 return NULL;
4458 static const struct got_error *
4459 cmd_status(int argc, char *argv[])
4461 const struct got_error *error = NULL;
4462 struct got_repository *repo = NULL;
4463 struct got_worktree *worktree = NULL;
4464 char *cwd = NULL;
4465 struct got_pathlist_head paths;
4466 struct got_pathlist_entry *pe;
4467 int ch;
4469 TAILQ_INIT(&paths);
4471 while ((ch = getopt(argc, argv, "")) != -1) {
4472 switch (ch) {
4473 default:
4474 usage_status();
4475 /* NOTREACHED */
4479 argc -= optind;
4480 argv += optind;
4482 #ifndef PROFILE
4483 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4484 NULL) == -1)
4485 err(1, "pledge");
4486 #endif
4487 cwd = getcwd(NULL, 0);
4488 if (cwd == NULL) {
4489 error = got_error_from_errno("getcwd");
4490 goto done;
4493 error = got_worktree_open(&worktree, cwd);
4494 if (error) {
4495 if (error->code == GOT_ERR_NOT_WORKTREE)
4496 error = wrap_not_worktree_error(error, "status", cwd);
4497 goto done;
4500 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4501 NULL);
4502 if (error != NULL)
4503 goto done;
4505 error = apply_unveil(got_repo_get_path(repo), 1,
4506 got_worktree_get_root_path(worktree));
4507 if (error)
4508 goto done;
4510 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
4511 if (error)
4512 goto done;
4514 error = got_worktree_status(worktree, &paths, repo, print_status, NULL,
4515 check_cancelled, NULL);
4516 done:
4517 TAILQ_FOREACH(pe, &paths, entry)
4518 free((char *)pe->path);
4519 got_pathlist_free(&paths);
4520 free(cwd);
4521 return error;
4524 __dead static void
4525 usage_ref(void)
4527 fprintf(stderr,
4528 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
4529 "[-d] [name]\n",
4530 getprogname());
4531 exit(1);
4534 static const struct got_error *
4535 list_refs(struct got_repository *repo, const char *refname)
4537 static const struct got_error *err = NULL;
4538 struct got_reflist_head refs;
4539 struct got_reflist_entry *re;
4541 SIMPLEQ_INIT(&refs);
4542 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
4543 if (err)
4544 return err;
4546 SIMPLEQ_FOREACH(re, &refs, entry) {
4547 char *refstr;
4548 refstr = got_ref_to_str(re->ref);
4549 if (refstr == NULL)
4550 return got_error_from_errno("got_ref_to_str");
4551 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
4552 free(refstr);
4555 got_ref_list_free(&refs);
4556 return NULL;
4559 static const struct got_error *
4560 delete_ref(struct got_repository *repo, const char *refname)
4562 const struct got_error *err = NULL;
4563 struct got_reference *ref;
4565 err = got_ref_open(&ref, repo, refname, 0);
4566 if (err)
4567 return err;
4569 err = got_ref_delete(ref, repo);
4570 got_ref_close(ref);
4571 return err;
4574 static const struct got_error *
4575 add_ref(struct got_repository *repo, const char *refname, const char *target)
4577 const struct got_error *err = NULL;
4578 struct got_object_id *id;
4579 struct got_reference *ref = NULL;
4582 * Don't let the user create a reference name with a leading '-'.
4583 * While technically a valid reference name, this case is usually
4584 * an unintended typo.
4586 if (refname[0] == '-')
4587 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4589 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
4590 repo);
4591 if (err) {
4592 struct got_reference *target_ref;
4594 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
4595 return err;
4596 err = got_ref_open(&target_ref, repo, target, 0);
4597 if (err)
4598 return err;
4599 err = got_ref_resolve(&id, repo, target_ref);
4600 got_ref_close(target_ref);
4601 if (err)
4602 return err;
4605 err = got_ref_alloc(&ref, refname, id);
4606 if (err)
4607 goto done;
4609 err = got_ref_write(ref, repo);
4610 done:
4611 if (ref)
4612 got_ref_close(ref);
4613 free(id);
4614 return err;
4617 static const struct got_error *
4618 add_symref(struct got_repository *repo, const char *refname, const char *target)
4620 const struct got_error *err = NULL;
4621 struct got_reference *ref = NULL;
4622 struct got_reference *target_ref = NULL;
4625 * Don't let the user create a reference name with a leading '-'.
4626 * While technically a valid reference name, this case is usually
4627 * an unintended typo.
4629 if (refname[0] == '-')
4630 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4632 err = got_ref_open(&target_ref, repo, target, 0);
4633 if (err)
4634 return err;
4636 err = got_ref_alloc_symref(&ref, refname, target_ref);
4637 if (err)
4638 goto done;
4640 err = got_ref_write(ref, repo);
4641 done:
4642 if (target_ref)
4643 got_ref_close(target_ref);
4644 if (ref)
4645 got_ref_close(ref);
4646 return err;
4649 static const struct got_error *
4650 cmd_ref(int argc, char *argv[])
4652 const struct got_error *error = NULL;
4653 struct got_repository *repo = NULL;
4654 struct got_worktree *worktree = NULL;
4655 char *cwd = NULL, *repo_path = NULL;
4656 int ch, do_list = 0, do_delete = 0;
4657 const char *obj_arg = NULL, *symref_target= NULL;
4658 char *refname = NULL;
4660 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
4661 switch (ch) {
4662 case 'c':
4663 obj_arg = optarg;
4664 break;
4665 case 'd':
4666 do_delete = 1;
4667 break;
4668 case 'r':
4669 repo_path = realpath(optarg, NULL);
4670 if (repo_path == NULL)
4671 return got_error_from_errno2("realpath",
4672 optarg);
4673 got_path_strip_trailing_slashes(repo_path);
4674 break;
4675 case 'l':
4676 do_list = 1;
4677 break;
4678 case 's':
4679 symref_target = optarg;
4680 break;
4681 default:
4682 usage_ref();
4683 /* NOTREACHED */
4687 if (obj_arg && do_list)
4688 errx(1, "-c and -l options are mutually exclusive");
4689 if (obj_arg && do_delete)
4690 errx(1, "-c and -d options are mutually exclusive");
4691 if (obj_arg && symref_target)
4692 errx(1, "-c and -s options are mutually exclusive");
4693 if (symref_target && do_delete)
4694 errx(1, "-s and -d options are mutually exclusive");
4695 if (symref_target && do_list)
4696 errx(1, "-s and -l options are mutually exclusive");
4697 if (do_delete && do_list)
4698 errx(1, "-d and -l options are mutually exclusive");
4700 argc -= optind;
4701 argv += optind;
4703 if (do_list) {
4704 if (argc != 0 && argc != 1)
4705 usage_ref();
4706 if (argc == 1) {
4707 refname = strdup(argv[0]);
4708 if (refname == NULL) {
4709 error = got_error_from_errno("strdup");
4710 goto done;
4713 } else {
4714 if (argc != 1)
4715 usage_ref();
4716 refname = strdup(argv[0]);
4717 if (refname == NULL) {
4718 error = got_error_from_errno("strdup");
4719 goto done;
4723 if (refname)
4724 got_path_strip_trailing_slashes(refname);
4726 #ifndef PROFILE
4727 if (do_list) {
4728 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4729 NULL) == -1)
4730 err(1, "pledge");
4731 } else {
4732 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4733 "sendfd unveil", NULL) == -1)
4734 err(1, "pledge");
4736 #endif
4737 cwd = getcwd(NULL, 0);
4738 if (cwd == NULL) {
4739 error = got_error_from_errno("getcwd");
4740 goto done;
4743 if (repo_path == NULL) {
4744 error = got_worktree_open(&worktree, cwd);
4745 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4746 goto done;
4747 else
4748 error = NULL;
4749 if (worktree) {
4750 repo_path =
4751 strdup(got_worktree_get_repo_path(worktree));
4752 if (repo_path == NULL)
4753 error = got_error_from_errno("strdup");
4754 if (error)
4755 goto done;
4756 } else {
4757 repo_path = strdup(cwd);
4758 if (repo_path == NULL) {
4759 error = got_error_from_errno("strdup");
4760 goto done;
4765 error = got_repo_open(&repo, repo_path, NULL);
4766 if (error != NULL)
4767 goto done;
4769 error = apply_unveil(got_repo_get_path(repo), do_list,
4770 worktree ? got_worktree_get_root_path(worktree) : NULL);
4771 if (error)
4772 goto done;
4774 if (do_list)
4775 error = list_refs(repo, refname);
4776 else if (do_delete)
4777 error = delete_ref(repo, refname);
4778 else if (symref_target)
4779 error = add_symref(repo, refname, symref_target);
4780 else {
4781 if (obj_arg == NULL)
4782 usage_ref();
4783 error = add_ref(repo, refname, obj_arg);
4785 done:
4786 free(refname);
4787 if (repo)
4788 got_repo_close(repo);
4789 if (worktree)
4790 got_worktree_close(worktree);
4791 free(cwd);
4792 free(repo_path);
4793 return error;
4796 __dead static void
4797 usage_branch(void)
4799 fprintf(stderr,
4800 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
4801 "[name]\n", getprogname());
4802 exit(1);
4805 static const struct got_error *
4806 list_branch(struct got_repository *repo, struct got_worktree *worktree,
4807 struct got_reference *ref)
4809 const struct got_error *err = NULL;
4810 const char *refname, *marker = " ";
4811 char *refstr;
4813 refname = got_ref_get_name(ref);
4814 if (worktree && strcmp(refname,
4815 got_worktree_get_head_ref_name(worktree)) == 0) {
4816 struct got_object_id *id = NULL;
4818 err = got_ref_resolve(&id, repo, ref);
4819 if (err)
4820 return err;
4821 if (got_object_id_cmp(id,
4822 got_worktree_get_base_commit_id(worktree)) == 0)
4823 marker = "* ";
4824 else
4825 marker = "~ ";
4826 free(id);
4829 if (strncmp(refname, "refs/heads/", 11) == 0)
4830 refname += 11;
4831 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4832 refname += 18;
4834 refstr = got_ref_to_str(ref);
4835 if (refstr == NULL)
4836 return got_error_from_errno("got_ref_to_str");
4838 printf("%s%s: %s\n", marker, refname, refstr);
4839 free(refstr);
4840 return NULL;
4843 static const struct got_error *
4844 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
4846 const char *refname;
4848 if (worktree == NULL)
4849 return got_error(GOT_ERR_NOT_WORKTREE);
4851 refname = got_worktree_get_head_ref_name(worktree);
4853 if (strncmp(refname, "refs/heads/", 11) == 0)
4854 refname += 11;
4855 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4856 refname += 18;
4858 printf("%s\n", refname);
4860 return NULL;
4863 static const struct got_error *
4864 list_branches(struct got_repository *repo, struct got_worktree *worktree)
4866 static const struct got_error *err = NULL;
4867 struct got_reflist_head refs;
4868 struct got_reflist_entry *re;
4869 struct got_reference *temp_ref = NULL;
4870 int rebase_in_progress, histedit_in_progress;
4872 SIMPLEQ_INIT(&refs);
4874 if (worktree) {
4875 err = got_worktree_rebase_in_progress(&rebase_in_progress,
4876 worktree);
4877 if (err)
4878 return err;
4880 err = got_worktree_histedit_in_progress(&histedit_in_progress,
4881 worktree);
4882 if (err)
4883 return err;
4885 if (rebase_in_progress || histedit_in_progress) {
4886 err = got_ref_open(&temp_ref, repo,
4887 got_worktree_get_head_ref_name(worktree), 0);
4888 if (err)
4889 return err;
4890 list_branch(repo, worktree, temp_ref);
4891 got_ref_close(temp_ref);
4895 err = got_ref_list(&refs, repo, "refs/heads",
4896 got_ref_cmp_by_name, NULL);
4897 if (err)
4898 return err;
4900 SIMPLEQ_FOREACH(re, &refs, entry)
4901 list_branch(repo, worktree, re->ref);
4903 got_ref_list_free(&refs);
4904 return NULL;
4907 static const struct got_error *
4908 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
4909 const char *branch_name)
4911 const struct got_error *err = NULL;
4912 struct got_reference *ref = NULL;
4913 char *refname;
4915 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
4916 return got_error_from_errno("asprintf");
4918 err = got_ref_open(&ref, repo, refname, 0);
4919 if (err)
4920 goto done;
4922 if (worktree &&
4923 strcmp(got_worktree_get_head_ref_name(worktree),
4924 got_ref_get_name(ref)) == 0) {
4925 err = got_error_msg(GOT_ERR_SAME_BRANCH,
4926 "will not delete this work tree's current branch");
4927 goto done;
4930 err = got_ref_delete(ref, repo);
4931 done:
4932 if (ref)
4933 got_ref_close(ref);
4934 free(refname);
4935 return err;
4938 static const struct got_error *
4939 add_branch(struct got_repository *repo, const char *branch_name,
4940 struct got_object_id *base_commit_id)
4942 const struct got_error *err = NULL;
4943 struct got_reference *ref = NULL;
4944 char *base_refname = NULL, *refname = NULL;
4947 * Don't let the user create a branch name with a leading '-'.
4948 * While technically a valid reference name, this case is usually
4949 * an unintended typo.
4951 if (branch_name[0] == '-')
4952 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
4954 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
4955 err = got_error_from_errno("asprintf");
4956 goto done;
4959 err = got_ref_open(&ref, repo, refname, 0);
4960 if (err == NULL) {
4961 err = got_error(GOT_ERR_BRANCH_EXISTS);
4962 goto done;
4963 } else if (err->code != GOT_ERR_NOT_REF)
4964 goto done;
4966 err = got_ref_alloc(&ref, refname, base_commit_id);
4967 if (err)
4968 goto done;
4970 err = got_ref_write(ref, repo);
4971 done:
4972 if (ref)
4973 got_ref_close(ref);
4974 free(base_refname);
4975 free(refname);
4976 return err;
4979 static const struct got_error *
4980 cmd_branch(int argc, char *argv[])
4982 const struct got_error *error = NULL;
4983 struct got_repository *repo = NULL;
4984 struct got_worktree *worktree = NULL;
4985 char *cwd = NULL, *repo_path = NULL;
4986 int ch, do_list = 0, do_show = 0, do_update = 1;
4987 const char *delref = NULL, *commit_id_arg = NULL;
4988 struct got_reference *ref = NULL;
4989 struct got_pathlist_head paths;
4990 struct got_pathlist_entry *pe;
4991 struct got_object_id *commit_id = NULL;
4992 char *commit_id_str = NULL;
4994 TAILQ_INIT(&paths);
4996 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
4997 switch (ch) {
4998 case 'c':
4999 commit_id_arg = optarg;
5000 break;
5001 case 'd':
5002 delref = optarg;
5003 break;
5004 case 'r':
5005 repo_path = realpath(optarg, NULL);
5006 if (repo_path == NULL)
5007 return got_error_from_errno2("realpath",
5008 optarg);
5009 got_path_strip_trailing_slashes(repo_path);
5010 break;
5011 case 'l':
5012 do_list = 1;
5013 break;
5014 case 'n':
5015 do_update = 0;
5016 break;
5017 default:
5018 usage_branch();
5019 /* NOTREACHED */
5023 if (do_list && delref)
5024 errx(1, "-l and -d options are mutually exclusive");
5026 argc -= optind;
5027 argv += optind;
5029 if (!do_list && !delref && argc == 0)
5030 do_show = 1;
5032 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5033 errx(1, "-c option can only be used when creating a branch");
5035 if (do_list || delref) {
5036 if (argc > 0)
5037 usage_branch();
5038 } else if (!do_show && argc != 1)
5039 usage_branch();
5041 #ifndef PROFILE
5042 if (do_list || do_show) {
5043 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5044 NULL) == -1)
5045 err(1, "pledge");
5046 } else {
5047 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5048 "sendfd unveil", NULL) == -1)
5049 err(1, "pledge");
5051 #endif
5052 cwd = getcwd(NULL, 0);
5053 if (cwd == NULL) {
5054 error = got_error_from_errno("getcwd");
5055 goto done;
5058 if (repo_path == NULL) {
5059 error = got_worktree_open(&worktree, cwd);
5060 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5061 goto done;
5062 else
5063 error = NULL;
5064 if (worktree) {
5065 repo_path =
5066 strdup(got_worktree_get_repo_path(worktree));
5067 if (repo_path == NULL)
5068 error = got_error_from_errno("strdup");
5069 if (error)
5070 goto done;
5071 } else {
5072 repo_path = strdup(cwd);
5073 if (repo_path == NULL) {
5074 error = got_error_from_errno("strdup");
5075 goto done;
5080 error = got_repo_open(&repo, repo_path, NULL);
5081 if (error != NULL)
5082 goto done;
5084 error = apply_unveil(got_repo_get_path(repo), do_list,
5085 worktree ? got_worktree_get_root_path(worktree) : NULL);
5086 if (error)
5087 goto done;
5089 if (do_show)
5090 error = show_current_branch(repo, worktree);
5091 else if (do_list)
5092 error = list_branches(repo, worktree);
5093 else if (delref)
5094 error = delete_branch(repo, worktree, delref);
5095 else {
5096 if (commit_id_arg == NULL)
5097 commit_id_arg = worktree ?
5098 got_worktree_get_head_ref_name(worktree) :
5099 GOT_REF_HEAD;
5100 error = got_repo_match_object_id(&commit_id, NULL,
5101 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5102 if (error)
5103 goto done;
5104 error = add_branch(repo, argv[0], commit_id);
5105 if (error)
5106 goto done;
5107 if (worktree && do_update) {
5108 struct got_update_progress_arg upa;
5109 char *branch_refname = NULL;
5111 error = got_object_id_str(&commit_id_str, commit_id);
5112 if (error)
5113 goto done;
5114 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5115 worktree);
5116 if (error)
5117 goto done;
5118 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5119 == -1) {
5120 error = got_error_from_errno("asprintf");
5121 goto done;
5123 error = got_ref_open(&ref, repo, branch_refname, 0);
5124 free(branch_refname);
5125 if (error)
5126 goto done;
5127 error = switch_head_ref(ref, commit_id, worktree,
5128 repo);
5129 if (error)
5130 goto done;
5131 error = got_worktree_set_base_commit_id(worktree, repo,
5132 commit_id);
5133 if (error)
5134 goto done;
5135 memset(&upa, 0, sizeof(upa));
5136 error = got_worktree_checkout_files(worktree, &paths,
5137 repo, update_progress, &upa, check_cancelled,
5138 NULL);
5139 if (error)
5140 goto done;
5141 if (upa.did_something)
5142 printf("Updated to commit %s\n", commit_id_str);
5143 print_update_progress_stats(&upa);
5146 done:
5147 if (ref)
5148 got_ref_close(ref);
5149 if (repo)
5150 got_repo_close(repo);
5151 if (worktree)
5152 got_worktree_close(worktree);
5153 free(cwd);
5154 free(repo_path);
5155 free(commit_id);
5156 free(commit_id_str);
5157 TAILQ_FOREACH(pe, &paths, entry)
5158 free((char *)pe->path);
5159 got_pathlist_free(&paths);
5160 return error;
5164 __dead static void
5165 usage_tag(void)
5167 fprintf(stderr,
5168 "usage: %s tag [-c commit] [-r repository] [-l] "
5169 "[-m message] name\n", getprogname());
5170 exit(1);
5173 #if 0
5174 static const struct got_error *
5175 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5177 const struct got_error *err = NULL;
5178 struct got_reflist_entry *re, *se, *new;
5179 struct got_object_id *re_id, *se_id;
5180 struct got_tag_object *re_tag, *se_tag;
5181 time_t re_time, se_time;
5183 SIMPLEQ_FOREACH(re, tags, entry) {
5184 se = SIMPLEQ_FIRST(sorted);
5185 if (se == NULL) {
5186 err = got_reflist_entry_dup(&new, re);
5187 if (err)
5188 return err;
5189 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5190 continue;
5191 } else {
5192 err = got_ref_resolve(&re_id, repo, re->ref);
5193 if (err)
5194 break;
5195 err = got_object_open_as_tag(&re_tag, repo, re_id);
5196 free(re_id);
5197 if (err)
5198 break;
5199 re_time = got_object_tag_get_tagger_time(re_tag);
5200 got_object_tag_close(re_tag);
5203 while (se) {
5204 err = got_ref_resolve(&se_id, repo, re->ref);
5205 if (err)
5206 break;
5207 err = got_object_open_as_tag(&se_tag, repo, se_id);
5208 free(se_id);
5209 if (err)
5210 break;
5211 se_time = got_object_tag_get_tagger_time(se_tag);
5212 got_object_tag_close(se_tag);
5214 if (se_time > re_time) {
5215 err = got_reflist_entry_dup(&new, re);
5216 if (err)
5217 return err;
5218 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5219 break;
5221 se = SIMPLEQ_NEXT(se, entry);
5222 continue;
5225 done:
5226 return err;
5228 #endif
5230 static const struct got_error *
5231 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5233 static const struct got_error *err = NULL;
5234 struct got_reflist_head refs;
5235 struct got_reflist_entry *re;
5237 SIMPLEQ_INIT(&refs);
5239 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5240 if (err)
5241 return err;
5243 SIMPLEQ_FOREACH(re, &refs, entry) {
5244 const char *refname;
5245 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5246 char datebuf[26];
5247 const char *tagger;
5248 time_t tagger_time;
5249 struct got_object_id *id;
5250 struct got_tag_object *tag;
5251 struct got_commit_object *commit = NULL;
5253 refname = got_ref_get_name(re->ref);
5254 if (strncmp(refname, "refs/tags/", 10) != 0)
5255 continue;
5256 refname += 10;
5257 refstr = got_ref_to_str(re->ref);
5258 if (refstr == NULL) {
5259 err = got_error_from_errno("got_ref_to_str");
5260 break;
5262 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5263 free(refstr);
5265 err = got_ref_resolve(&id, repo, re->ref);
5266 if (err)
5267 break;
5268 err = got_object_open_as_tag(&tag, repo, id);
5269 if (err) {
5270 if (err->code != GOT_ERR_OBJ_TYPE) {
5271 free(id);
5272 break;
5274 /* "lightweight" tag */
5275 err = got_object_open_as_commit(&commit, repo, id);
5276 if (err) {
5277 free(id);
5278 break;
5280 tagger = got_object_commit_get_committer(commit);
5281 tagger_time =
5282 got_object_commit_get_committer_time(commit);
5283 err = got_object_id_str(&id_str, id);
5284 free(id);
5285 if (err)
5286 break;
5287 } else {
5288 free(id);
5289 tagger = got_object_tag_get_tagger(tag);
5290 tagger_time = got_object_tag_get_tagger_time(tag);
5291 err = got_object_id_str(&id_str,
5292 got_object_tag_get_object_id(tag));
5293 if (err)
5294 break;
5296 printf("from: %s\n", tagger);
5297 datestr = get_datestr(&tagger_time, datebuf);
5298 if (datestr)
5299 printf("date: %s UTC\n", datestr);
5300 if (commit)
5301 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5302 else {
5303 switch (got_object_tag_get_object_type(tag)) {
5304 case GOT_OBJ_TYPE_BLOB:
5305 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5306 id_str);
5307 break;
5308 case GOT_OBJ_TYPE_TREE:
5309 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5310 id_str);
5311 break;
5312 case GOT_OBJ_TYPE_COMMIT:
5313 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5314 id_str);
5315 break;
5316 case GOT_OBJ_TYPE_TAG:
5317 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5318 id_str);
5319 break;
5320 default:
5321 break;
5324 free(id_str);
5325 if (commit) {
5326 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5327 if (err)
5328 break;
5329 got_object_commit_close(commit);
5330 } else {
5331 tagmsg0 = strdup(got_object_tag_get_message(tag));
5332 got_object_tag_close(tag);
5333 if (tagmsg0 == NULL) {
5334 err = got_error_from_errno("strdup");
5335 break;
5339 tagmsg = tagmsg0;
5340 do {
5341 line = strsep(&tagmsg, "\n");
5342 if (line)
5343 printf(" %s\n", line);
5344 } while (line);
5345 free(tagmsg0);
5348 got_ref_list_free(&refs);
5349 return NULL;
5352 static const struct got_error *
5353 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5354 const char *tag_name, const char *repo_path)
5356 const struct got_error *err = NULL;
5357 char *template = NULL, *initial_content = NULL;
5358 char *editor = NULL;
5359 int fd = -1;
5361 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5362 err = got_error_from_errno("asprintf");
5363 goto done;
5366 if (asprintf(&initial_content, "\n# tagging commit %s as %s\n",
5367 commit_id_str, tag_name) == -1) {
5368 err = got_error_from_errno("asprintf");
5369 goto done;
5372 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5373 if (err)
5374 goto done;
5376 dprintf(fd, initial_content);
5377 close(fd);
5379 err = get_editor(&editor);
5380 if (err)
5381 goto done;
5382 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
5383 done:
5384 free(initial_content);
5385 free(template);
5386 free(editor);
5388 /* Editor is done; we can now apply unveil(2) */
5389 if (err == NULL) {
5390 err = apply_unveil(repo_path, 0, NULL);
5391 if (err) {
5392 free(*tagmsg);
5393 *tagmsg = NULL;
5396 return err;
5399 static const struct got_error *
5400 add_tag(struct got_repository *repo, const char *tag_name,
5401 const char *commit_arg, const char *tagmsg_arg)
5403 const struct got_error *err = NULL;
5404 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5405 char *label = NULL, *commit_id_str = NULL;
5406 struct got_reference *ref = NULL;
5407 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5408 char *tagmsg_path = NULL, *tag_id_str = NULL;
5409 int preserve_tagmsg = 0;
5412 * Don't let the user create a tag name with a leading '-'.
5413 * While technically a valid reference name, this case is usually
5414 * an unintended typo.
5416 if (tag_name[0] == '-')
5417 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5419 err = get_author(&tagger, repo);
5420 if (err)
5421 return err;
5423 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5424 GOT_OBJ_TYPE_COMMIT, 1, repo);
5425 if (err)
5426 goto done;
5428 err = got_object_id_str(&commit_id_str, commit_id);
5429 if (err)
5430 goto done;
5432 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5433 refname = strdup(tag_name);
5434 if (refname == NULL) {
5435 err = got_error_from_errno("strdup");
5436 goto done;
5438 tag_name += 10;
5439 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5440 err = got_error_from_errno("asprintf");
5441 goto done;
5444 err = got_ref_open(&ref, repo, refname, 0);
5445 if (err == NULL) {
5446 err = got_error(GOT_ERR_TAG_EXISTS);
5447 goto done;
5448 } else if (err->code != GOT_ERR_NOT_REF)
5449 goto done;
5451 if (tagmsg_arg == NULL) {
5452 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5453 tag_name, got_repo_get_path(repo));
5454 if (err) {
5455 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5456 tagmsg_path != NULL)
5457 preserve_tagmsg = 1;
5458 goto done;
5462 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5463 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5464 if (err) {
5465 if (tagmsg_path)
5466 preserve_tagmsg = 1;
5467 goto done;
5470 err = got_ref_alloc(&ref, refname, tag_id);
5471 if (err) {
5472 if (tagmsg_path)
5473 preserve_tagmsg = 1;
5474 goto done;
5477 err = got_ref_write(ref, repo);
5478 if (err) {
5479 if (tagmsg_path)
5480 preserve_tagmsg = 1;
5481 goto done;
5484 err = got_object_id_str(&tag_id_str, tag_id);
5485 if (err) {
5486 if (tagmsg_path)
5487 preserve_tagmsg = 1;
5488 goto done;
5490 printf("Created tag %s\n", tag_id_str);
5491 done:
5492 if (preserve_tagmsg) {
5493 fprintf(stderr, "%s: tag message preserved in %s\n",
5494 getprogname(), tagmsg_path);
5495 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
5496 err = got_error_from_errno2("unlink", tagmsg_path);
5497 free(tag_id_str);
5498 if (ref)
5499 got_ref_close(ref);
5500 free(commit_id);
5501 free(commit_id_str);
5502 free(refname);
5503 free(tagmsg);
5504 free(tagmsg_path);
5505 free(tagger);
5506 return err;
5509 static const struct got_error *
5510 cmd_tag(int argc, char *argv[])
5512 const struct got_error *error = NULL;
5513 struct got_repository *repo = NULL;
5514 struct got_worktree *worktree = NULL;
5515 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
5516 char *gitconfig_path = NULL;
5517 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
5518 int ch, do_list = 0;
5520 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
5521 switch (ch) {
5522 case 'c':
5523 commit_id_arg = optarg;
5524 break;
5525 case 'm':
5526 tagmsg = optarg;
5527 break;
5528 case 'r':
5529 repo_path = realpath(optarg, NULL);
5530 if (repo_path == NULL)
5531 return got_error_from_errno2("realpath",
5532 optarg);
5533 got_path_strip_trailing_slashes(repo_path);
5534 break;
5535 case 'l':
5536 do_list = 1;
5537 break;
5538 default:
5539 usage_tag();
5540 /* NOTREACHED */
5544 argc -= optind;
5545 argv += optind;
5547 if (do_list) {
5548 if (commit_id_arg != NULL)
5549 errx(1,
5550 "-c option can only be used when creating a tag");
5551 if (tagmsg)
5552 errx(1, "-l and -m options are mutually exclusive");
5553 if (argc > 0)
5554 usage_tag();
5555 } else if (argc != 1)
5556 usage_tag();
5558 tag_name = argv[0];
5560 #ifndef PROFILE
5561 if (do_list) {
5562 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5563 NULL) == -1)
5564 err(1, "pledge");
5565 } else {
5566 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5567 "sendfd unveil", NULL) == -1)
5568 err(1, "pledge");
5570 #endif
5571 cwd = getcwd(NULL, 0);
5572 if (cwd == NULL) {
5573 error = got_error_from_errno("getcwd");
5574 goto done;
5577 if (repo_path == NULL) {
5578 error = got_worktree_open(&worktree, cwd);
5579 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5580 goto done;
5581 else
5582 error = NULL;
5583 if (worktree) {
5584 repo_path =
5585 strdup(got_worktree_get_repo_path(worktree));
5586 if (repo_path == NULL)
5587 error = got_error_from_errno("strdup");
5588 if (error)
5589 goto done;
5590 } else {
5591 repo_path = strdup(cwd);
5592 if (repo_path == NULL) {
5593 error = got_error_from_errno("strdup");
5594 goto done;
5599 if (do_list) {
5600 error = got_repo_open(&repo, repo_path, NULL);
5601 if (error != NULL)
5602 goto done;
5603 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5604 if (error)
5605 goto done;
5606 error = list_tags(repo, worktree);
5607 } else {
5608 error = get_gitconfig_path(&gitconfig_path);
5609 if (error)
5610 goto done;
5611 error = got_repo_open(&repo, repo_path, gitconfig_path);
5612 if (error != NULL)
5613 goto done;
5615 if (tagmsg) {
5616 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5617 if (error)
5618 goto done;
5621 if (commit_id_arg == NULL) {
5622 struct got_reference *head_ref;
5623 struct got_object_id *commit_id;
5624 error = got_ref_open(&head_ref, repo,
5625 worktree ? got_worktree_get_head_ref_name(worktree)
5626 : GOT_REF_HEAD, 0);
5627 if (error)
5628 goto done;
5629 error = got_ref_resolve(&commit_id, repo, head_ref);
5630 got_ref_close(head_ref);
5631 if (error)
5632 goto done;
5633 error = got_object_id_str(&commit_id_str, commit_id);
5634 free(commit_id);
5635 if (error)
5636 goto done;
5639 error = add_tag(repo, tag_name,
5640 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
5642 done:
5643 if (repo)
5644 got_repo_close(repo);
5645 if (worktree)
5646 got_worktree_close(worktree);
5647 free(cwd);
5648 free(repo_path);
5649 free(gitconfig_path);
5650 free(commit_id_str);
5651 return error;
5654 __dead static void
5655 usage_add(void)
5657 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
5658 getprogname());
5659 exit(1);
5662 static const struct got_error *
5663 add_progress(void *arg, unsigned char status, const char *path)
5665 while (path[0] == '/')
5666 path++;
5667 printf("%c %s\n", status, path);
5668 return NULL;
5671 static const struct got_error *
5672 cmd_add(int argc, char *argv[])
5674 const struct got_error *error = NULL;
5675 struct got_repository *repo = NULL;
5676 struct got_worktree *worktree = NULL;
5677 char *cwd = NULL;
5678 struct got_pathlist_head paths;
5679 struct got_pathlist_entry *pe;
5680 int ch, can_recurse = 0, no_ignores = 0;
5682 TAILQ_INIT(&paths);
5684 while ((ch = getopt(argc, argv, "IR")) != -1) {
5685 switch (ch) {
5686 case 'I':
5687 no_ignores = 1;
5688 break;
5689 case 'R':
5690 can_recurse = 1;
5691 break;
5692 default:
5693 usage_add();
5694 /* NOTREACHED */
5698 argc -= optind;
5699 argv += optind;
5701 #ifndef PROFILE
5702 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5703 NULL) == -1)
5704 err(1, "pledge");
5705 #endif
5706 if (argc < 1)
5707 usage_add();
5709 cwd = getcwd(NULL, 0);
5710 if (cwd == NULL) {
5711 error = got_error_from_errno("getcwd");
5712 goto done;
5715 error = got_worktree_open(&worktree, cwd);
5716 if (error) {
5717 if (error->code == GOT_ERR_NOT_WORKTREE)
5718 error = wrap_not_worktree_error(error, "add", cwd);
5719 goto done;
5722 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5723 NULL);
5724 if (error != NULL)
5725 goto done;
5727 error = apply_unveil(got_repo_get_path(repo), 1,
5728 got_worktree_get_root_path(worktree));
5729 if (error)
5730 goto done;
5732 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5733 if (error)
5734 goto done;
5736 if (!can_recurse && no_ignores) {
5737 error = got_error_msg(GOT_ERR_BAD_PATH,
5738 "disregarding ignores requires -R option");
5739 goto done;
5743 if (!can_recurse) {
5744 char *ondisk_path;
5745 struct stat sb;
5746 TAILQ_FOREACH(pe, &paths, entry) {
5747 if (asprintf(&ondisk_path, "%s/%s",
5748 got_worktree_get_root_path(worktree),
5749 pe->path) == -1) {
5750 error = got_error_from_errno("asprintf");
5751 goto done;
5753 if (lstat(ondisk_path, &sb) == -1) {
5754 if (errno == ENOENT) {
5755 free(ondisk_path);
5756 continue;
5758 error = got_error_from_errno2("lstat",
5759 ondisk_path);
5760 free(ondisk_path);
5761 goto done;
5763 free(ondisk_path);
5764 if (S_ISDIR(sb.st_mode)) {
5765 error = got_error_msg(GOT_ERR_BAD_PATH,
5766 "adding directories requires -R option");
5767 goto done;
5772 error = got_worktree_schedule_add(worktree, &paths, add_progress,
5773 NULL, repo, no_ignores);
5774 done:
5775 if (repo)
5776 got_repo_close(repo);
5777 if (worktree)
5778 got_worktree_close(worktree);
5779 TAILQ_FOREACH(pe, &paths, entry)
5780 free((char *)pe->path);
5781 got_pathlist_free(&paths);
5782 free(cwd);
5783 return error;
5786 __dead static void
5787 usage_remove(void)
5789 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] path ...\n",
5790 getprogname());
5791 exit(1);
5794 static const struct got_error *
5795 print_remove_status(void *arg, unsigned char status,
5796 unsigned char staged_status, const char *path)
5798 while (path[0] == '/')
5799 path++;
5800 if (status == GOT_STATUS_NONEXISTENT)
5801 return NULL;
5802 if (status == staged_status && (status == GOT_STATUS_DELETE))
5803 status = GOT_STATUS_NO_CHANGE;
5804 printf("%c%c %s\n", status, staged_status, path);
5805 return NULL;
5808 static const struct got_error *
5809 cmd_remove(int argc, char *argv[])
5811 const struct got_error *error = NULL;
5812 struct got_worktree *worktree = NULL;
5813 struct got_repository *repo = NULL;
5814 char *cwd = NULL;
5815 struct got_pathlist_head paths;
5816 struct got_pathlist_entry *pe;
5817 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0;
5819 TAILQ_INIT(&paths);
5821 while ((ch = getopt(argc, argv, "fkR")) != -1) {
5822 switch (ch) {
5823 case 'f':
5824 delete_local_mods = 1;
5825 break;
5826 case 'k':
5827 keep_on_disk = 1;
5828 break;
5829 case 'R':
5830 can_recurse = 1;
5831 break;
5832 default:
5833 usage_remove();
5834 /* NOTREACHED */
5838 argc -= optind;
5839 argv += optind;
5841 #ifndef PROFILE
5842 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5843 NULL) == -1)
5844 err(1, "pledge");
5845 #endif
5846 if (argc < 1)
5847 usage_remove();
5849 cwd = getcwd(NULL, 0);
5850 if (cwd == NULL) {
5851 error = got_error_from_errno("getcwd");
5852 goto done;
5854 error = got_worktree_open(&worktree, cwd);
5855 if (error) {
5856 if (error->code == GOT_ERR_NOT_WORKTREE)
5857 error = wrap_not_worktree_error(error, "remove", cwd);
5858 goto done;
5861 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5862 NULL);
5863 if (error)
5864 goto done;
5866 error = apply_unveil(got_repo_get_path(repo), 1,
5867 got_worktree_get_root_path(worktree));
5868 if (error)
5869 goto done;
5871 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5872 if (error)
5873 goto done;
5875 if (!can_recurse) {
5876 char *ondisk_path;
5877 struct stat sb;
5878 TAILQ_FOREACH(pe, &paths, entry) {
5879 if (asprintf(&ondisk_path, "%s/%s",
5880 got_worktree_get_root_path(worktree),
5881 pe->path) == -1) {
5882 error = got_error_from_errno("asprintf");
5883 goto done;
5885 if (lstat(ondisk_path, &sb) == -1) {
5886 if (errno == ENOENT) {
5887 free(ondisk_path);
5888 continue;
5890 error = got_error_from_errno2("lstat",
5891 ondisk_path);
5892 free(ondisk_path);
5893 goto done;
5895 free(ondisk_path);
5896 if (S_ISDIR(sb.st_mode)) {
5897 error = got_error_msg(GOT_ERR_BAD_PATH,
5898 "removing directories requires -R option");
5899 goto done;
5904 error = got_worktree_schedule_delete(worktree, &paths,
5905 delete_local_mods, print_remove_status, NULL, repo, keep_on_disk);
5906 done:
5907 if (repo)
5908 got_repo_close(repo);
5909 if (worktree)
5910 got_worktree_close(worktree);
5911 TAILQ_FOREACH(pe, &paths, entry)
5912 free((char *)pe->path);
5913 got_pathlist_free(&paths);
5914 free(cwd);
5915 return error;
5918 __dead static void
5919 usage_revert(void)
5921 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
5922 "path ...\n", getprogname());
5923 exit(1);
5926 static const struct got_error *
5927 revert_progress(void *arg, unsigned char status, const char *path)
5929 if (status == GOT_STATUS_UNVERSIONED)
5930 return NULL;
5932 while (path[0] == '/')
5933 path++;
5934 printf("%c %s\n", status, path);
5935 return NULL;
5938 struct choose_patch_arg {
5939 FILE *patch_script_file;
5940 const char *action;
5943 static const struct got_error *
5944 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
5945 int nchanges, const char *action)
5947 char *line = NULL;
5948 size_t linesize = 0;
5949 ssize_t linelen;
5951 switch (status) {
5952 case GOT_STATUS_ADD:
5953 printf("A %s\n%s this addition? [y/n] ", path, action);
5954 break;
5955 case GOT_STATUS_DELETE:
5956 printf("D %s\n%s this deletion? [y/n] ", path, action);
5957 break;
5958 case GOT_STATUS_MODIFY:
5959 if (fseek(patch_file, 0L, SEEK_SET) == -1)
5960 return got_error_from_errno("fseek");
5961 printf(GOT_COMMIT_SEP_STR);
5962 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
5963 printf("%s", line);
5964 if (ferror(patch_file))
5965 return got_error_from_errno("getline");
5966 printf(GOT_COMMIT_SEP_STR);
5967 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
5968 path, n, nchanges, action);
5969 break;
5970 default:
5971 return got_error_path(path, GOT_ERR_FILE_STATUS);
5974 return NULL;
5977 static const struct got_error *
5978 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
5979 FILE *patch_file, int n, int nchanges)
5981 const struct got_error *err = NULL;
5982 char *line = NULL;
5983 size_t linesize = 0;
5984 ssize_t linelen;
5985 int resp = ' ';
5986 struct choose_patch_arg *a = arg;
5988 *choice = GOT_PATCH_CHOICE_NONE;
5990 if (a->patch_script_file) {
5991 char *nl;
5992 err = show_change(status, path, patch_file, n, nchanges,
5993 a->action);
5994 if (err)
5995 return err;
5996 linelen = getline(&line, &linesize, a->patch_script_file);
5997 if (linelen == -1) {
5998 if (ferror(a->patch_script_file))
5999 return got_error_from_errno("getline");
6000 return NULL;
6002 nl = strchr(line, '\n');
6003 if (nl)
6004 *nl = '\0';
6005 if (strcmp(line, "y") == 0) {
6006 *choice = GOT_PATCH_CHOICE_YES;
6007 printf("y\n");
6008 } else if (strcmp(line, "n") == 0) {
6009 *choice = GOT_PATCH_CHOICE_NO;
6010 printf("n\n");
6011 } else if (strcmp(line, "q") == 0 &&
6012 status == GOT_STATUS_MODIFY) {
6013 *choice = GOT_PATCH_CHOICE_QUIT;
6014 printf("q\n");
6015 } else
6016 printf("invalid response '%s'\n", line);
6017 free(line);
6018 return NULL;
6021 while (resp != 'y' && resp != 'n' && resp != 'q') {
6022 err = show_change(status, path, patch_file, n, nchanges,
6023 a->action);
6024 if (err)
6025 return err;
6026 resp = getchar();
6027 if (resp == '\n')
6028 resp = getchar();
6029 if (status == GOT_STATUS_MODIFY) {
6030 if (resp != 'y' && resp != 'n' && resp != 'q') {
6031 printf("invalid response '%c'\n", resp);
6032 resp = ' ';
6034 } else if (resp != 'y' && resp != 'n') {
6035 printf("invalid response '%c'\n", resp);
6036 resp = ' ';
6040 if (resp == 'y')
6041 *choice = GOT_PATCH_CHOICE_YES;
6042 else if (resp == 'n')
6043 *choice = GOT_PATCH_CHOICE_NO;
6044 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6045 *choice = GOT_PATCH_CHOICE_QUIT;
6047 return NULL;
6051 static const struct got_error *
6052 cmd_revert(int argc, char *argv[])
6054 const struct got_error *error = NULL;
6055 struct got_worktree *worktree = NULL;
6056 struct got_repository *repo = NULL;
6057 char *cwd = NULL, *path = NULL;
6058 struct got_pathlist_head paths;
6059 struct got_pathlist_entry *pe;
6060 int ch, can_recurse = 0, pflag = 0;
6061 FILE *patch_script_file = NULL;
6062 const char *patch_script_path = NULL;
6063 struct choose_patch_arg cpa;
6065 TAILQ_INIT(&paths);
6067 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6068 switch (ch) {
6069 case 'p':
6070 pflag = 1;
6071 break;
6072 case 'F':
6073 patch_script_path = optarg;
6074 break;
6075 case 'R':
6076 can_recurse = 1;
6077 break;
6078 default:
6079 usage_revert();
6080 /* NOTREACHED */
6084 argc -= optind;
6085 argv += optind;
6087 #ifndef PROFILE
6088 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6089 "unveil", NULL) == -1)
6090 err(1, "pledge");
6091 #endif
6092 if (argc < 1)
6093 usage_revert();
6094 if (patch_script_path && !pflag)
6095 errx(1, "-F option can only be used together with -p option");
6097 cwd = getcwd(NULL, 0);
6098 if (cwd == NULL) {
6099 error = got_error_from_errno("getcwd");
6100 goto done;
6102 error = got_worktree_open(&worktree, cwd);
6103 if (error) {
6104 if (error->code == GOT_ERR_NOT_WORKTREE)
6105 error = wrap_not_worktree_error(error, "revert", cwd);
6106 goto done;
6109 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6110 NULL);
6111 if (error != NULL)
6112 goto done;
6114 if (patch_script_path) {
6115 patch_script_file = fopen(patch_script_path, "r");
6116 if (patch_script_file == NULL) {
6117 error = got_error_from_errno2("fopen",
6118 patch_script_path);
6119 goto done;
6122 error = apply_unveil(got_repo_get_path(repo), 1,
6123 got_worktree_get_root_path(worktree));
6124 if (error)
6125 goto done;
6127 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6128 if (error)
6129 goto done;
6131 if (!can_recurse) {
6132 char *ondisk_path;
6133 struct stat sb;
6134 TAILQ_FOREACH(pe, &paths, entry) {
6135 if (asprintf(&ondisk_path, "%s/%s",
6136 got_worktree_get_root_path(worktree),
6137 pe->path) == -1) {
6138 error = got_error_from_errno("asprintf");
6139 goto done;
6141 if (lstat(ondisk_path, &sb) == -1) {
6142 if (errno == ENOENT) {
6143 free(ondisk_path);
6144 continue;
6146 error = got_error_from_errno2("lstat",
6147 ondisk_path);
6148 free(ondisk_path);
6149 goto done;
6151 free(ondisk_path);
6152 if (S_ISDIR(sb.st_mode)) {
6153 error = got_error_msg(GOT_ERR_BAD_PATH,
6154 "reverting directories requires -R option");
6155 goto done;
6160 cpa.patch_script_file = patch_script_file;
6161 cpa.action = "revert";
6162 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6163 pflag ? choose_patch : NULL, &cpa, repo);
6164 done:
6165 if (patch_script_file && fclose(patch_script_file) == EOF &&
6166 error == NULL)
6167 error = got_error_from_errno2("fclose", patch_script_path);
6168 if (repo)
6169 got_repo_close(repo);
6170 if (worktree)
6171 got_worktree_close(worktree);
6172 free(path);
6173 free(cwd);
6174 return error;
6177 __dead static void
6178 usage_commit(void)
6180 fprintf(stderr, "usage: %s commit [-m msg] [path ...]\n",
6181 getprogname());
6182 exit(1);
6185 struct collect_commit_logmsg_arg {
6186 const char *cmdline_log;
6187 const char *editor;
6188 const char *worktree_path;
6189 const char *branch_name;
6190 const char *repo_path;
6191 char *logmsg_path;
6195 static const struct got_error *
6196 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6197 void *arg)
6199 char *initial_content = NULL;
6200 struct got_pathlist_entry *pe;
6201 const struct got_error *err = NULL;
6202 char *template = NULL;
6203 struct collect_commit_logmsg_arg *a = arg;
6204 int fd;
6205 size_t len;
6207 /* if a message was specified on the command line, just use it */
6208 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6209 len = strlen(a->cmdline_log) + 1;
6210 *logmsg = malloc(len + 1);
6211 if (*logmsg == NULL)
6212 return got_error_from_errno("malloc");
6213 strlcpy(*logmsg, a->cmdline_log, len);
6214 return NULL;
6217 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6218 return got_error_from_errno("asprintf");
6220 if (asprintf(&initial_content,
6221 "\n# changes to be committed on branch %s:\n",
6222 a->branch_name) == -1)
6223 return got_error_from_errno("asprintf");
6225 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6226 if (err)
6227 goto done;
6229 dprintf(fd, initial_content);
6231 TAILQ_FOREACH(pe, commitable_paths, entry) {
6232 struct got_commitable *ct = pe->data;
6233 dprintf(fd, "# %c %s\n",
6234 got_commitable_get_status(ct),
6235 got_commitable_get_path(ct));
6237 close(fd);
6239 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
6240 done:
6241 free(initial_content);
6242 free(template);
6244 /* Editor is done; we can now apply unveil(2) */
6245 if (err == NULL) {
6246 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6247 if (err) {
6248 free(*logmsg);
6249 *logmsg = NULL;
6252 return err;
6255 static const struct got_error *
6256 cmd_commit(int argc, char *argv[])
6258 const struct got_error *error = NULL;
6259 struct got_worktree *worktree = NULL;
6260 struct got_repository *repo = NULL;
6261 char *cwd = NULL, *id_str = NULL;
6262 struct got_object_id *id = NULL;
6263 const char *logmsg = NULL;
6264 struct collect_commit_logmsg_arg cl_arg;
6265 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6266 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6267 struct got_pathlist_head paths;
6269 TAILQ_INIT(&paths);
6270 cl_arg.logmsg_path = NULL;
6272 while ((ch = getopt(argc, argv, "m:")) != -1) {
6273 switch (ch) {
6274 case 'm':
6275 logmsg = optarg;
6276 break;
6277 default:
6278 usage_commit();
6279 /* NOTREACHED */
6283 argc -= optind;
6284 argv += optind;
6286 #ifndef PROFILE
6287 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6288 "unveil", NULL) == -1)
6289 err(1, "pledge");
6290 #endif
6291 cwd = getcwd(NULL, 0);
6292 if (cwd == NULL) {
6293 error = got_error_from_errno("getcwd");
6294 goto done;
6296 error = got_worktree_open(&worktree, cwd);
6297 if (error) {
6298 if (error->code == GOT_ERR_NOT_WORKTREE)
6299 error = wrap_not_worktree_error(error, "commit", cwd);
6300 goto done;
6303 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6304 if (error)
6305 goto done;
6306 if (rebase_in_progress) {
6307 error = got_error(GOT_ERR_REBASING);
6308 goto done;
6311 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6312 worktree);
6313 if (error)
6314 goto done;
6316 error = get_gitconfig_path(&gitconfig_path);
6317 if (error)
6318 goto done;
6319 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6320 gitconfig_path);
6321 if (error != NULL)
6322 goto done;
6324 error = get_author(&author, repo);
6325 if (error)
6326 return error;
6329 * unveil(2) traverses exec(2); if an editor is used we have
6330 * to apply unveil after the log message has been written.
6332 if (logmsg == NULL || strlen(logmsg) == 0)
6333 error = get_editor(&editor);
6334 else
6335 error = apply_unveil(got_repo_get_path(repo), 0,
6336 got_worktree_get_root_path(worktree));
6337 if (error)
6338 goto done;
6340 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6341 if (error)
6342 goto done;
6344 cl_arg.editor = editor;
6345 cl_arg.cmdline_log = logmsg;
6346 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6347 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6348 if (!histedit_in_progress) {
6349 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6350 error = got_error(GOT_ERR_COMMIT_BRANCH);
6351 goto done;
6353 cl_arg.branch_name += 11;
6355 cl_arg.repo_path = got_repo_get_path(repo);
6356 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6357 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
6358 if (error) {
6359 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6360 cl_arg.logmsg_path != NULL)
6361 preserve_logmsg = 1;
6362 goto done;
6365 error = got_object_id_str(&id_str, id);
6366 if (error)
6367 goto done;
6368 printf("Created commit %s\n", id_str);
6369 done:
6370 if (preserve_logmsg) {
6371 fprintf(stderr, "%s: log message preserved in %s\n",
6372 getprogname(), cl_arg.logmsg_path);
6373 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6374 error == NULL)
6375 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6376 free(cl_arg.logmsg_path);
6377 if (repo)
6378 got_repo_close(repo);
6379 if (worktree)
6380 got_worktree_close(worktree);
6381 free(cwd);
6382 free(id_str);
6383 free(gitconfig_path);
6384 free(editor);
6385 free(author);
6386 return error;
6389 __dead static void
6390 usage_cherrypick(void)
6392 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6393 exit(1);
6396 static const struct got_error *
6397 cmd_cherrypick(int argc, char *argv[])
6399 const struct got_error *error = NULL;
6400 struct got_worktree *worktree = NULL;
6401 struct got_repository *repo = NULL;
6402 char *cwd = NULL, *commit_id_str = NULL;
6403 struct got_object_id *commit_id = NULL;
6404 struct got_commit_object *commit = NULL;
6405 struct got_object_qid *pid;
6406 struct got_reference *head_ref = NULL;
6407 int ch;
6408 struct got_update_progress_arg upa;
6410 while ((ch = getopt(argc, argv, "")) != -1) {
6411 switch (ch) {
6412 default:
6413 usage_cherrypick();
6414 /* NOTREACHED */
6418 argc -= optind;
6419 argv += optind;
6421 #ifndef PROFILE
6422 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6423 "unveil", NULL) == -1)
6424 err(1, "pledge");
6425 #endif
6426 if (argc != 1)
6427 usage_cherrypick();
6429 cwd = getcwd(NULL, 0);
6430 if (cwd == NULL) {
6431 error = got_error_from_errno("getcwd");
6432 goto done;
6434 error = got_worktree_open(&worktree, cwd);
6435 if (error) {
6436 if (error->code == GOT_ERR_NOT_WORKTREE)
6437 error = wrap_not_worktree_error(error, "cherrypick",
6438 cwd);
6439 goto done;
6442 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6443 NULL);
6444 if (error != NULL)
6445 goto done;
6447 error = apply_unveil(got_repo_get_path(repo), 0,
6448 got_worktree_get_root_path(worktree));
6449 if (error)
6450 goto done;
6452 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6453 GOT_OBJ_TYPE_COMMIT, repo);
6454 if (error != NULL) {
6455 struct got_reference *ref;
6456 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6457 goto done;
6458 error = got_ref_open(&ref, repo, argv[0], 0);
6459 if (error != NULL)
6460 goto done;
6461 error = got_ref_resolve(&commit_id, repo, ref);
6462 got_ref_close(ref);
6463 if (error != NULL)
6464 goto done;
6466 error = got_object_id_str(&commit_id_str, commit_id);
6467 if (error)
6468 goto done;
6470 error = got_ref_open(&head_ref, repo,
6471 got_worktree_get_head_ref_name(worktree), 0);
6472 if (error != NULL)
6473 goto done;
6475 error = check_same_branch(commit_id, head_ref, NULL, repo);
6476 if (error) {
6477 if (error->code != GOT_ERR_ANCESTRY)
6478 goto done;
6479 error = NULL;
6480 } else {
6481 error = got_error(GOT_ERR_SAME_BRANCH);
6482 goto done;
6485 error = got_object_open_as_commit(&commit, repo, commit_id);
6486 if (error)
6487 goto done;
6488 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6489 memset(&upa, 0, sizeof(upa));
6490 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
6491 commit_id, repo, update_progress, &upa, check_cancelled,
6492 NULL);
6493 if (error != NULL)
6494 goto done;
6496 if (upa.did_something)
6497 printf("Merged commit %s\n", commit_id_str);
6498 print_update_progress_stats(&upa);
6499 done:
6500 if (commit)
6501 got_object_commit_close(commit);
6502 free(commit_id_str);
6503 if (head_ref)
6504 got_ref_close(head_ref);
6505 if (worktree)
6506 got_worktree_close(worktree);
6507 if (repo)
6508 got_repo_close(repo);
6509 return error;
6512 __dead static void
6513 usage_backout(void)
6515 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
6516 exit(1);
6519 static const struct got_error *
6520 cmd_backout(int argc, char *argv[])
6522 const struct got_error *error = NULL;
6523 struct got_worktree *worktree = NULL;
6524 struct got_repository *repo = NULL;
6525 char *cwd = NULL, *commit_id_str = NULL;
6526 struct got_object_id *commit_id = NULL;
6527 struct got_commit_object *commit = NULL;
6528 struct got_object_qid *pid;
6529 struct got_reference *head_ref = NULL;
6530 int ch;
6531 struct got_update_progress_arg upa;
6533 while ((ch = getopt(argc, argv, "")) != -1) {
6534 switch (ch) {
6535 default:
6536 usage_backout();
6537 /* NOTREACHED */
6541 argc -= optind;
6542 argv += optind;
6544 #ifndef PROFILE
6545 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6546 "unveil", NULL) == -1)
6547 err(1, "pledge");
6548 #endif
6549 if (argc != 1)
6550 usage_backout();
6552 cwd = getcwd(NULL, 0);
6553 if (cwd == NULL) {
6554 error = got_error_from_errno("getcwd");
6555 goto done;
6557 error = got_worktree_open(&worktree, cwd);
6558 if (error) {
6559 if (error->code == GOT_ERR_NOT_WORKTREE)
6560 error = wrap_not_worktree_error(error, "backout", cwd);
6561 goto done;
6564 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6565 NULL);
6566 if (error != NULL)
6567 goto done;
6569 error = apply_unveil(got_repo_get_path(repo), 0,
6570 got_worktree_get_root_path(worktree));
6571 if (error)
6572 goto done;
6574 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6575 GOT_OBJ_TYPE_COMMIT, repo);
6576 if (error != NULL) {
6577 struct got_reference *ref;
6578 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6579 goto done;
6580 error = got_ref_open(&ref, repo, argv[0], 0);
6581 if (error != NULL)
6582 goto done;
6583 error = got_ref_resolve(&commit_id, repo, ref);
6584 got_ref_close(ref);
6585 if (error != NULL)
6586 goto done;
6588 error = got_object_id_str(&commit_id_str, commit_id);
6589 if (error)
6590 goto done;
6592 error = got_ref_open(&head_ref, repo,
6593 got_worktree_get_head_ref_name(worktree), 0);
6594 if (error != NULL)
6595 goto done;
6597 error = check_same_branch(commit_id, head_ref, NULL, repo);
6598 if (error)
6599 goto done;
6601 error = got_object_open_as_commit(&commit, repo, commit_id);
6602 if (error)
6603 goto done;
6604 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6605 if (pid == NULL) {
6606 error = got_error(GOT_ERR_ROOT_COMMIT);
6607 goto done;
6610 memset(&upa, 0, sizeof(upa));
6611 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
6612 update_progress, &upa, check_cancelled, NULL);
6613 if (error != NULL)
6614 goto done;
6616 if (upa.did_something)
6617 printf("Backed out commit %s\n", commit_id_str);
6618 print_update_progress_stats(&upa);
6619 done:
6620 if (commit)
6621 got_object_commit_close(commit);
6622 free(commit_id_str);
6623 if (head_ref)
6624 got_ref_close(head_ref);
6625 if (worktree)
6626 got_worktree_close(worktree);
6627 if (repo)
6628 got_repo_close(repo);
6629 return error;
6632 __dead static void
6633 usage_rebase(void)
6635 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
6636 getprogname());
6637 exit(1);
6640 void
6641 trim_logmsg(char *logmsg, int limit)
6643 char *nl;
6644 size_t len;
6646 len = strlen(logmsg);
6647 if (len > limit)
6648 len = limit;
6649 logmsg[len] = '\0';
6650 nl = strchr(logmsg, '\n');
6651 if (nl)
6652 *nl = '\0';
6655 static const struct got_error *
6656 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
6658 const struct got_error *err;
6659 char *logmsg0 = NULL;
6660 const char *s;
6662 err = got_object_commit_get_logmsg(&logmsg0, commit);
6663 if (err)
6664 return err;
6666 s = logmsg0;
6667 while (isspace((unsigned char)s[0]))
6668 s++;
6670 *logmsg = strdup(s);
6671 if (*logmsg == NULL) {
6672 err = got_error_from_errno("strdup");
6673 goto done;
6676 trim_logmsg(*logmsg, limit);
6677 done:
6678 free(logmsg0);
6679 return err;
6682 static const struct got_error *
6683 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
6685 const struct got_error *err;
6686 struct got_commit_object *commit = NULL;
6687 char *id_str = NULL, *logmsg = NULL;
6689 err = got_object_open_as_commit(&commit, repo, id);
6690 if (err)
6691 return err;
6693 err = got_object_id_str(&id_str, id);
6694 if (err)
6695 goto done;
6697 id_str[12] = '\0';
6699 err = get_short_logmsg(&logmsg, 42, commit);
6700 if (err)
6701 goto done;
6703 printf("%s -> merge conflict: %s\n", id_str, logmsg);
6704 done:
6705 free(id_str);
6706 got_object_commit_close(commit);
6707 free(logmsg);
6708 return err;
6711 static const struct got_error *
6712 show_rebase_progress(struct got_commit_object *commit,
6713 struct got_object_id *old_id, struct got_object_id *new_id)
6715 const struct got_error *err;
6716 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
6718 err = got_object_id_str(&old_id_str, old_id);
6719 if (err)
6720 goto done;
6722 if (new_id) {
6723 err = got_object_id_str(&new_id_str, new_id);
6724 if (err)
6725 goto done;
6728 old_id_str[12] = '\0';
6729 if (new_id_str)
6730 new_id_str[12] = '\0';
6732 err = get_short_logmsg(&logmsg, 42, commit);
6733 if (err)
6734 goto done;
6736 printf("%s -> %s: %s\n", old_id_str,
6737 new_id_str ? new_id_str : "no-op change", logmsg);
6738 done:
6739 free(old_id_str);
6740 free(new_id_str);
6741 free(logmsg);
6742 return err;
6745 static const struct got_error *
6746 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
6747 struct got_reference *branch, struct got_reference *new_base_branch,
6748 struct got_reference *tmp_branch, struct got_repository *repo)
6750 printf("Switching work tree to %s\n", got_ref_get_name(branch));
6751 return got_worktree_rebase_complete(worktree, fileindex,
6752 new_base_branch, tmp_branch, branch, repo);
6755 static const struct got_error *
6756 rebase_commit(struct got_pathlist_head *merged_paths,
6757 struct got_worktree *worktree, struct got_fileindex *fileindex,
6758 struct got_reference *tmp_branch,
6759 struct got_object_id *commit_id, struct got_repository *repo)
6761 const struct got_error *error;
6762 struct got_commit_object *commit;
6763 struct got_object_id *new_commit_id;
6765 error = got_object_open_as_commit(&commit, repo, commit_id);
6766 if (error)
6767 return error;
6769 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
6770 worktree, fileindex, tmp_branch, commit, commit_id, repo);
6771 if (error) {
6772 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
6773 goto done;
6774 error = show_rebase_progress(commit, commit_id, NULL);
6775 } else {
6776 error = show_rebase_progress(commit, commit_id, new_commit_id);
6777 free(new_commit_id);
6779 done:
6780 got_object_commit_close(commit);
6781 return error;
6784 struct check_path_prefix_arg {
6785 const char *path_prefix;
6786 size_t len;
6787 int errcode;
6790 static const struct got_error *
6791 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
6792 struct got_blob_object *blob2, struct got_object_id *id1,
6793 struct got_object_id *id2, const char *path1, const char *path2,
6794 mode_t mode1, mode_t mode2, struct got_repository *repo)
6796 struct check_path_prefix_arg *a = arg;
6798 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
6799 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
6800 return got_error(a->errcode);
6802 return NULL;
6805 static const struct got_error *
6806 check_path_prefix(struct got_object_id *parent_id,
6807 struct got_object_id *commit_id, const char *path_prefix,
6808 int errcode, struct got_repository *repo)
6810 const struct got_error *err;
6811 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
6812 struct got_commit_object *commit = NULL, *parent_commit = NULL;
6813 struct check_path_prefix_arg cpp_arg;
6815 if (got_path_is_root_dir(path_prefix))
6816 return NULL;
6818 err = got_object_open_as_commit(&commit, repo, commit_id);
6819 if (err)
6820 goto done;
6822 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
6823 if (err)
6824 goto done;
6826 err = got_object_open_as_tree(&tree1, repo,
6827 got_object_commit_get_tree_id(parent_commit));
6828 if (err)
6829 goto done;
6831 err = got_object_open_as_tree(&tree2, repo,
6832 got_object_commit_get_tree_id(commit));
6833 if (err)
6834 goto done;
6836 cpp_arg.path_prefix = path_prefix;
6837 while (cpp_arg.path_prefix[0] == '/')
6838 cpp_arg.path_prefix++;
6839 cpp_arg.len = strlen(cpp_arg.path_prefix);
6840 cpp_arg.errcode = errcode;
6841 err = got_diff_tree(tree1, tree2, "", "", repo,
6842 check_path_prefix_in_diff, &cpp_arg, 0);
6843 done:
6844 if (tree1)
6845 got_object_tree_close(tree1);
6846 if (tree2)
6847 got_object_tree_close(tree2);
6848 if (commit)
6849 got_object_commit_close(commit);
6850 if (parent_commit)
6851 got_object_commit_close(parent_commit);
6852 return err;
6855 static const struct got_error *
6856 collect_commits(struct got_object_id_queue *commits,
6857 struct got_object_id *initial_commit_id,
6858 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
6859 const char *path_prefix, int path_prefix_errcode,
6860 struct got_repository *repo)
6862 const struct got_error *err = NULL;
6863 struct got_commit_graph *graph = NULL;
6864 struct got_object_id *parent_id = NULL;
6865 struct got_object_qid *qid;
6866 struct got_object_id *commit_id = initial_commit_id;
6868 err = got_commit_graph_open(&graph, "/", 1);
6869 if (err)
6870 return err;
6872 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
6873 check_cancelled, NULL);
6874 if (err)
6875 goto done;
6876 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
6877 err = got_commit_graph_iter_next(&parent_id, graph, repo,
6878 check_cancelled, NULL);
6879 if (err) {
6880 if (err->code == GOT_ERR_ITER_COMPLETED) {
6881 err = got_error_msg(GOT_ERR_ANCESTRY,
6882 "ran out of commits to rebase before "
6883 "youngest common ancestor commit has "
6884 "been reached?!?");
6886 goto done;
6887 } else {
6888 err = check_path_prefix(parent_id, commit_id,
6889 path_prefix, path_prefix_errcode, repo);
6890 if (err)
6891 goto done;
6893 err = got_object_qid_alloc(&qid, commit_id);
6894 if (err)
6895 goto done;
6896 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
6897 commit_id = parent_id;
6900 done:
6901 got_commit_graph_close(graph);
6902 return err;
6905 static const struct got_error *
6906 cmd_rebase(int argc, char *argv[])
6908 const struct got_error *error = NULL;
6909 struct got_worktree *worktree = NULL;
6910 struct got_repository *repo = NULL;
6911 struct got_fileindex *fileindex = NULL;
6912 char *cwd = NULL;
6913 struct got_reference *branch = NULL;
6914 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
6915 struct got_object_id *commit_id = NULL, *parent_id = NULL;
6916 struct got_object_id *resume_commit_id = NULL;
6917 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
6918 struct got_commit_object *commit = NULL;
6919 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
6920 int histedit_in_progress = 0;
6921 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
6922 struct got_object_id_queue commits;
6923 struct got_pathlist_head merged_paths;
6924 const struct got_object_id_queue *parent_ids;
6925 struct got_object_qid *qid, *pid;
6927 SIMPLEQ_INIT(&commits);
6928 TAILQ_INIT(&merged_paths);
6930 while ((ch = getopt(argc, argv, "ac")) != -1) {
6931 switch (ch) {
6932 case 'a':
6933 abort_rebase = 1;
6934 break;
6935 case 'c':
6936 continue_rebase = 1;
6937 break;
6938 default:
6939 usage_rebase();
6940 /* NOTREACHED */
6944 argc -= optind;
6945 argv += optind;
6947 #ifndef PROFILE
6948 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6949 "unveil", NULL) == -1)
6950 err(1, "pledge");
6951 #endif
6952 if (abort_rebase && continue_rebase)
6953 usage_rebase();
6954 else if (abort_rebase || continue_rebase) {
6955 if (argc != 0)
6956 usage_rebase();
6957 } else if (argc != 1)
6958 usage_rebase();
6960 cwd = getcwd(NULL, 0);
6961 if (cwd == NULL) {
6962 error = got_error_from_errno("getcwd");
6963 goto done;
6965 error = got_worktree_open(&worktree, cwd);
6966 if (error) {
6967 if (error->code == GOT_ERR_NOT_WORKTREE)
6968 error = wrap_not_worktree_error(error, "rebase", cwd);
6969 goto done;
6972 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6973 NULL);
6974 if (error != NULL)
6975 goto done;
6977 error = apply_unveil(got_repo_get_path(repo), 0,
6978 got_worktree_get_root_path(worktree));
6979 if (error)
6980 goto done;
6982 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6983 worktree);
6984 if (error)
6985 goto done;
6986 if (histedit_in_progress) {
6987 error = got_error(GOT_ERR_HISTEDIT_BUSY);
6988 goto done;
6991 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6992 if (error)
6993 goto done;
6995 if (abort_rebase) {
6996 struct got_update_progress_arg upa;
6997 if (!rebase_in_progress) {
6998 error = got_error(GOT_ERR_NOT_REBASING);
6999 goto done;
7001 error = got_worktree_rebase_continue(&resume_commit_id,
7002 &new_base_branch, &tmp_branch, &branch, &fileindex,
7003 worktree, repo);
7004 if (error)
7005 goto done;
7006 printf("Switching work tree to %s\n",
7007 got_ref_get_symref_target(new_base_branch));
7008 memset(&upa, 0, sizeof(upa));
7009 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7010 new_base_branch, update_progress, &upa);
7011 if (error)
7012 goto done;
7013 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7014 print_update_progress_stats(&upa);
7015 goto done; /* nothing else to do */
7018 if (continue_rebase) {
7019 if (!rebase_in_progress) {
7020 error = got_error(GOT_ERR_NOT_REBASING);
7021 goto done;
7023 error = got_worktree_rebase_continue(&resume_commit_id,
7024 &new_base_branch, &tmp_branch, &branch, &fileindex,
7025 worktree, repo);
7026 if (error)
7027 goto done;
7029 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7030 resume_commit_id, repo);
7031 if (error)
7032 goto done;
7034 yca_id = got_object_id_dup(resume_commit_id);
7035 if (yca_id == NULL) {
7036 error = got_error_from_errno("got_object_id_dup");
7037 goto done;
7039 } else {
7040 error = got_ref_open(&branch, repo, argv[0], 0);
7041 if (error != NULL)
7042 goto done;
7045 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7046 if (error)
7047 goto done;
7049 if (!continue_rebase) {
7050 struct got_object_id *base_commit_id;
7052 base_commit_id = got_worktree_get_base_commit_id(worktree);
7053 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7054 base_commit_id, branch_head_commit_id, repo,
7055 check_cancelled, NULL);
7056 if (error)
7057 goto done;
7058 if (yca_id == NULL) {
7059 error = got_error_msg(GOT_ERR_ANCESTRY,
7060 "specified branch shares no common ancestry "
7061 "with work tree's branch");
7062 goto done;
7065 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7066 if (error) {
7067 if (error->code != GOT_ERR_ANCESTRY)
7068 goto done;
7069 error = NULL;
7070 } else {
7071 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7072 "specified branch resolves to a commit which "
7073 "is already contained in work tree's branch");
7074 goto done;
7076 error = got_worktree_rebase_prepare(&new_base_branch,
7077 &tmp_branch, &fileindex, worktree, branch, repo);
7078 if (error)
7079 goto done;
7082 commit_id = branch_head_commit_id;
7083 error = got_object_open_as_commit(&commit, repo, commit_id);
7084 if (error)
7085 goto done;
7087 parent_ids = got_object_commit_get_parent_ids(commit);
7088 pid = SIMPLEQ_FIRST(parent_ids);
7089 if (pid == NULL) {
7090 if (!continue_rebase) {
7091 struct got_update_progress_arg upa;
7092 memset(&upa, 0, sizeof(upa));
7093 error = got_worktree_rebase_abort(worktree, fileindex,
7094 repo, new_base_branch, update_progress, &upa);
7095 if (error)
7096 goto done;
7097 printf("Rebase of %s aborted\n",
7098 got_ref_get_name(branch));
7099 print_update_progress_stats(&upa);
7102 error = got_error(GOT_ERR_EMPTY_REBASE);
7103 goto done;
7105 error = collect_commits(&commits, commit_id, pid->id,
7106 yca_id, got_worktree_get_path_prefix(worktree),
7107 GOT_ERR_REBASE_PATH, repo);
7108 got_object_commit_close(commit);
7109 commit = NULL;
7110 if (error)
7111 goto done;
7113 if (SIMPLEQ_EMPTY(&commits)) {
7114 if (continue_rebase) {
7115 error = rebase_complete(worktree, fileindex,
7116 branch, new_base_branch, tmp_branch, repo);
7117 goto done;
7118 } else {
7119 /* Fast-forward the reference of the branch. */
7120 struct got_object_id *new_head_commit_id;
7121 char *id_str;
7122 error = got_ref_resolve(&new_head_commit_id, repo,
7123 new_base_branch);
7124 if (error)
7125 goto done;
7126 error = got_object_id_str(&id_str, new_head_commit_id);
7127 printf("Forwarding %s to commit %s\n",
7128 got_ref_get_name(branch), id_str);
7129 free(id_str);
7130 error = got_ref_change_ref(branch,
7131 new_head_commit_id);
7132 if (error)
7133 goto done;
7137 pid = NULL;
7138 SIMPLEQ_FOREACH(qid, &commits, entry) {
7139 struct got_update_progress_arg upa;
7141 commit_id = qid->id;
7142 parent_id = pid ? pid->id : yca_id;
7143 pid = qid;
7145 memset(&upa, 0, sizeof(upa));
7146 error = got_worktree_rebase_merge_files(&merged_paths,
7147 worktree, fileindex, parent_id, commit_id, repo,
7148 update_progress, &upa, check_cancelled, NULL);
7149 if (error)
7150 goto done;
7152 print_update_progress_stats(&upa);
7153 if (upa.conflicts > 0)
7154 rebase_status = GOT_STATUS_CONFLICT;
7156 if (rebase_status == GOT_STATUS_CONFLICT) {
7157 error = show_rebase_merge_conflict(qid->id, repo);
7158 if (error)
7159 goto done;
7160 got_worktree_rebase_pathlist_free(&merged_paths);
7161 break;
7164 error = rebase_commit(&merged_paths, worktree, fileindex,
7165 tmp_branch, commit_id, repo);
7166 got_worktree_rebase_pathlist_free(&merged_paths);
7167 if (error)
7168 goto done;
7171 if (rebase_status == GOT_STATUS_CONFLICT) {
7172 error = got_worktree_rebase_postpone(worktree, fileindex);
7173 if (error)
7174 goto done;
7175 error = got_error_msg(GOT_ERR_CONFLICTS,
7176 "conflicts must be resolved before rebasing can continue");
7177 } else
7178 error = rebase_complete(worktree, fileindex, branch,
7179 new_base_branch, tmp_branch, repo);
7180 done:
7181 got_object_id_queue_free(&commits);
7182 free(branch_head_commit_id);
7183 free(resume_commit_id);
7184 free(yca_id);
7185 if (commit)
7186 got_object_commit_close(commit);
7187 if (branch)
7188 got_ref_close(branch);
7189 if (new_base_branch)
7190 got_ref_close(new_base_branch);
7191 if (tmp_branch)
7192 got_ref_close(tmp_branch);
7193 if (worktree)
7194 got_worktree_close(worktree);
7195 if (repo)
7196 got_repo_close(repo);
7197 return error;
7200 __dead static void
7201 usage_histedit(void)
7203 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
7204 getprogname());
7205 exit(1);
7208 #define GOT_HISTEDIT_PICK 'p'
7209 #define GOT_HISTEDIT_EDIT 'e'
7210 #define GOT_HISTEDIT_FOLD 'f'
7211 #define GOT_HISTEDIT_DROP 'd'
7212 #define GOT_HISTEDIT_MESG 'm'
7214 static struct got_histedit_cmd {
7215 unsigned char code;
7216 const char *name;
7217 const char *desc;
7218 } got_histedit_cmds[] = {
7219 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7220 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7221 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7222 "be used" },
7223 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7224 { GOT_HISTEDIT_MESG, "mesg",
7225 "single-line log message for commit above (open editor if empty)" },
7228 struct got_histedit_list_entry {
7229 TAILQ_ENTRY(got_histedit_list_entry) entry;
7230 struct got_object_id *commit_id;
7231 const struct got_histedit_cmd *cmd;
7232 char *logmsg;
7234 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7236 static const struct got_error *
7237 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7238 FILE *f, struct got_repository *repo)
7240 const struct got_error *err = NULL;
7241 char *logmsg = NULL, *id_str = NULL;
7242 struct got_commit_object *commit = NULL;
7243 int n;
7245 err = got_object_open_as_commit(&commit, repo, commit_id);
7246 if (err)
7247 goto done;
7249 err = get_short_logmsg(&logmsg, 34, commit);
7250 if (err)
7251 goto done;
7253 err = got_object_id_str(&id_str, commit_id);
7254 if (err)
7255 goto done;
7257 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7258 if (n < 0)
7259 err = got_ferror(f, GOT_ERR_IO);
7260 done:
7261 if (commit)
7262 got_object_commit_close(commit);
7263 free(id_str);
7264 free(logmsg);
7265 return err;
7268 static const struct got_error *
7269 histedit_write_commit_list(struct got_object_id_queue *commits,
7270 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7272 const struct got_error *err = NULL;
7273 struct got_object_qid *qid;
7275 if (SIMPLEQ_EMPTY(commits))
7276 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7278 SIMPLEQ_FOREACH(qid, commits, entry) {
7279 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7280 f, repo);
7281 if (err)
7282 break;
7283 if (edit_logmsg_only) {
7284 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7285 if (n < 0) {
7286 err = got_ferror(f, GOT_ERR_IO);
7287 break;
7292 return err;
7295 static const struct got_error *
7296 write_cmd_list(FILE *f, const char *branch_name,
7297 struct got_object_id_queue *commits)
7299 const struct got_error *err = NULL;
7300 int n, i;
7301 char *id_str;
7302 struct got_object_qid *qid;
7304 qid = SIMPLEQ_FIRST(commits);
7305 err = got_object_id_str(&id_str, qid->id);
7306 if (err)
7307 return err;
7309 n = fprintf(f,
7310 "# Editing the history of branch '%s' starting at\n"
7311 "# commit %s\n"
7312 "# Commits will be processed in order from top to "
7313 "bottom of this file.\n", branch_name, id_str);
7314 if (n < 0) {
7315 err = got_ferror(f, GOT_ERR_IO);
7316 goto done;
7319 n = fprintf(f, "# Available histedit commands:\n");
7320 if (n < 0) {
7321 err = got_ferror(f, GOT_ERR_IO);
7322 goto done;
7325 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7326 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7327 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7328 cmd->desc);
7329 if (n < 0) {
7330 err = got_ferror(f, GOT_ERR_IO);
7331 break;
7334 done:
7335 free(id_str);
7336 return err;
7339 static const struct got_error *
7340 histedit_syntax_error(int lineno)
7342 static char msg[42];
7343 int ret;
7345 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7346 lineno);
7347 if (ret == -1 || ret >= sizeof(msg))
7348 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7350 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7353 static const struct got_error *
7354 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7355 char *logmsg, struct got_repository *repo)
7357 const struct got_error *err;
7358 struct got_commit_object *folded_commit = NULL;
7359 char *id_str, *folded_logmsg = NULL;
7361 err = got_object_id_str(&id_str, hle->commit_id);
7362 if (err)
7363 return err;
7365 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7366 if (err)
7367 goto done;
7369 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7370 if (err)
7371 goto done;
7372 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7373 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7374 folded_logmsg) == -1) {
7375 err = got_error_from_errno("asprintf");
7377 done:
7378 if (folded_commit)
7379 got_object_commit_close(folded_commit);
7380 free(id_str);
7381 free(folded_logmsg);
7382 return err;
7385 static struct got_histedit_list_entry *
7386 get_folded_commits(struct got_histedit_list_entry *hle)
7388 struct got_histedit_list_entry *prev, *folded = NULL;
7390 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7391 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7392 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7393 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7394 folded = prev;
7395 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7398 return folded;
7401 static const struct got_error *
7402 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7403 struct got_repository *repo)
7405 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7406 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7407 const struct got_error *err = NULL;
7408 struct got_commit_object *commit = NULL;
7409 int fd;
7410 struct got_histedit_list_entry *folded = NULL;
7412 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7413 if (err)
7414 return err;
7416 folded = get_folded_commits(hle);
7417 if (folded) {
7418 while (folded != hle) {
7419 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7420 folded = TAILQ_NEXT(folded, entry);
7421 continue;
7423 err = append_folded_commit_msg(&new_msg, folded,
7424 logmsg, repo);
7425 if (err)
7426 goto done;
7427 free(logmsg);
7428 logmsg = new_msg;
7429 folded = TAILQ_NEXT(folded, entry);
7433 err = got_object_id_str(&id_str, hle->commit_id);
7434 if (err)
7435 goto done;
7436 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7437 if (err)
7438 goto done;
7439 if (asprintf(&new_msg,
7440 "%s\n# original log message of commit %s: %s",
7441 logmsg ? logmsg : "", id_str, orig_logmsg) == -1) {
7442 err = got_error_from_errno("asprintf");
7443 goto done;
7445 free(logmsg);
7446 logmsg = new_msg;
7448 err = got_object_id_str(&id_str, hle->commit_id);
7449 if (err)
7450 goto done;
7452 err = got_opentemp_named_fd(&logmsg_path, &fd,
7453 GOT_TMPDIR_STR "/got-logmsg");
7454 if (err)
7455 goto done;
7457 dprintf(fd, logmsg);
7458 close(fd);
7460 err = get_editor(&editor);
7461 if (err)
7462 goto done;
7464 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
7465 if (err) {
7466 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
7467 goto done;
7468 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
7470 done:
7471 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
7472 err = got_error_from_errno2("unlink", logmsg_path);
7473 free(logmsg_path);
7474 free(logmsg);
7475 free(orig_logmsg);
7476 free(editor);
7477 if (commit)
7478 got_object_commit_close(commit);
7479 return err;
7482 static const struct got_error *
7483 histedit_parse_list(struct got_histedit_list *histedit_cmds,
7484 FILE *f, struct got_repository *repo)
7486 const struct got_error *err = NULL;
7487 char *line = NULL, *p, *end;
7488 size_t size;
7489 ssize_t len;
7490 int lineno = 0, i;
7491 const struct got_histedit_cmd *cmd;
7492 struct got_object_id *commit_id = NULL;
7493 struct got_histedit_list_entry *hle = NULL;
7495 for (;;) {
7496 len = getline(&line, &size, f);
7497 if (len == -1) {
7498 const struct got_error *getline_err;
7499 if (feof(f))
7500 break;
7501 getline_err = got_error_from_errno("getline");
7502 err = got_ferror(f, getline_err->code);
7503 break;
7505 lineno++;
7506 p = line;
7507 while (isspace((unsigned char)p[0]))
7508 p++;
7509 if (p[0] == '#' || p[0] == '\0') {
7510 free(line);
7511 line = NULL;
7512 continue;
7514 cmd = NULL;
7515 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7516 cmd = &got_histedit_cmds[i];
7517 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
7518 isspace((unsigned char)p[strlen(cmd->name)])) {
7519 p += strlen(cmd->name);
7520 break;
7522 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
7523 p++;
7524 break;
7527 if (i == nitems(got_histedit_cmds)) {
7528 err = histedit_syntax_error(lineno);
7529 break;
7531 while (isspace((unsigned char)p[0]))
7532 p++;
7533 if (cmd->code == GOT_HISTEDIT_MESG) {
7534 if (hle == NULL || hle->logmsg != NULL) {
7535 err = got_error(GOT_ERR_HISTEDIT_CMD);
7536 break;
7538 if (p[0] == '\0') {
7539 err = histedit_edit_logmsg(hle, repo);
7540 if (err)
7541 break;
7542 } else {
7543 hle->logmsg = strdup(p);
7544 if (hle->logmsg == NULL) {
7545 err = got_error_from_errno("strdup");
7546 break;
7549 free(line);
7550 line = NULL;
7551 continue;
7552 } else {
7553 end = p;
7554 while (end[0] && !isspace((unsigned char)end[0]))
7555 end++;
7556 *end = '\0';
7558 err = got_object_resolve_id_str(&commit_id, repo, p);
7559 if (err) {
7560 /* override error code */
7561 err = histedit_syntax_error(lineno);
7562 break;
7565 hle = malloc(sizeof(*hle));
7566 if (hle == NULL) {
7567 err = got_error_from_errno("malloc");
7568 break;
7570 hle->cmd = cmd;
7571 hle->commit_id = commit_id;
7572 hle->logmsg = NULL;
7573 commit_id = NULL;
7574 free(line);
7575 line = NULL;
7576 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
7579 free(line);
7580 free(commit_id);
7581 return err;
7584 static const struct got_error *
7585 histedit_check_script(struct got_histedit_list *histedit_cmds,
7586 struct got_object_id_queue *commits, struct got_repository *repo)
7588 const struct got_error *err = NULL;
7589 struct got_object_qid *qid;
7590 struct got_histedit_list_entry *hle;
7591 static char msg[92];
7592 char *id_str;
7594 if (TAILQ_EMPTY(histedit_cmds))
7595 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
7596 "histedit script contains no commands");
7597 if (SIMPLEQ_EMPTY(commits))
7598 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7600 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7601 struct got_histedit_list_entry *hle2;
7602 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
7603 if (hle == hle2)
7604 continue;
7605 if (got_object_id_cmp(hle->commit_id,
7606 hle2->commit_id) != 0)
7607 continue;
7608 err = got_object_id_str(&id_str, hle->commit_id);
7609 if (err)
7610 return err;
7611 snprintf(msg, sizeof(msg), "commit %s is listed "
7612 "more than once in histedit script", id_str);
7613 free(id_str);
7614 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7618 SIMPLEQ_FOREACH(qid, commits, entry) {
7619 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7620 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
7621 break;
7623 if (hle == NULL) {
7624 err = got_object_id_str(&id_str, qid->id);
7625 if (err)
7626 return err;
7627 snprintf(msg, sizeof(msg),
7628 "commit %s missing from histedit script", id_str);
7629 free(id_str);
7630 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7634 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
7635 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
7636 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
7637 "last commit in histedit script cannot be folded");
7639 return NULL;
7642 static const struct got_error *
7643 histedit_run_editor(struct got_histedit_list *histedit_cmds,
7644 const char *path, struct got_object_id_queue *commits,
7645 struct got_repository *repo)
7647 const struct got_error *err = NULL;
7648 char *editor;
7649 FILE *f = NULL;
7651 err = get_editor(&editor);
7652 if (err)
7653 return err;
7655 if (spawn_editor(editor, path) == -1) {
7656 err = got_error_from_errno("failed spawning editor");
7657 goto done;
7660 f = fopen(path, "r");
7661 if (f == NULL) {
7662 err = got_error_from_errno("fopen");
7663 goto done;
7665 err = histedit_parse_list(histedit_cmds, f, repo);
7666 if (err)
7667 goto done;
7669 err = histedit_check_script(histedit_cmds, commits, repo);
7670 done:
7671 if (f && fclose(f) != 0 && err == NULL)
7672 err = got_error_from_errno("fclose");
7673 free(editor);
7674 return err;
7677 static const struct got_error *
7678 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
7679 struct got_object_id_queue *, const char *, const char *,
7680 struct got_repository *);
7682 static const struct got_error *
7683 histedit_edit_script(struct got_histedit_list *histedit_cmds,
7684 struct got_object_id_queue *commits, const char *branch_name,
7685 int edit_logmsg_only, struct got_repository *repo)
7687 const struct got_error *err;
7688 FILE *f = NULL;
7689 char *path = NULL;
7691 err = got_opentemp_named(&path, &f, "got-histedit");
7692 if (err)
7693 return err;
7695 err = write_cmd_list(f, branch_name, commits);
7696 if (err)
7697 goto done;
7699 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
7700 if (err)
7701 goto done;
7703 if (edit_logmsg_only) {
7704 rewind(f);
7705 err = histedit_parse_list(histedit_cmds, f, repo);
7706 } else {
7707 if (fclose(f) != 0) {
7708 err = got_error_from_errno("fclose");
7709 goto done;
7711 f = NULL;
7712 err = histedit_run_editor(histedit_cmds, path, commits, repo);
7713 if (err) {
7714 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7715 err->code != GOT_ERR_HISTEDIT_CMD)
7716 goto done;
7717 err = histedit_edit_list_retry(histedit_cmds, err,
7718 commits, path, branch_name, repo);
7721 done:
7722 if (f && fclose(f) != 0 && err == NULL)
7723 err = got_error_from_errno("fclose");
7724 if (path && unlink(path) != 0 && err == NULL)
7725 err = got_error_from_errno2("unlink", path);
7726 free(path);
7727 return err;
7730 static const struct got_error *
7731 histedit_save_list(struct got_histedit_list *histedit_cmds,
7732 struct got_worktree *worktree, struct got_repository *repo)
7734 const struct got_error *err = NULL;
7735 char *path = NULL;
7736 FILE *f = NULL;
7737 struct got_histedit_list_entry *hle;
7738 struct got_commit_object *commit = NULL;
7740 err = got_worktree_get_histedit_script_path(&path, worktree);
7741 if (err)
7742 return err;
7744 f = fopen(path, "w");
7745 if (f == NULL) {
7746 err = got_error_from_errno2("fopen", path);
7747 goto done;
7749 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7750 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
7751 repo);
7752 if (err)
7753 break;
7755 if (hle->logmsg) {
7756 int n = fprintf(f, "%c %s\n",
7757 GOT_HISTEDIT_MESG, hle->logmsg);
7758 if (n < 0) {
7759 err = got_ferror(f, GOT_ERR_IO);
7760 break;
7764 done:
7765 if (f && fclose(f) != 0 && err == NULL)
7766 err = got_error_from_errno("fclose");
7767 free(path);
7768 if (commit)
7769 got_object_commit_close(commit);
7770 return err;
7773 void
7774 histedit_free_list(struct got_histedit_list *histedit_cmds)
7776 struct got_histedit_list_entry *hle;
7778 while ((hle = TAILQ_FIRST(histedit_cmds))) {
7779 TAILQ_REMOVE(histedit_cmds, hle, entry);
7780 free(hle);
7784 static const struct got_error *
7785 histedit_load_list(struct got_histedit_list *histedit_cmds,
7786 const char *path, struct got_repository *repo)
7788 const struct got_error *err = NULL;
7789 FILE *f = NULL;
7791 f = fopen(path, "r");
7792 if (f == NULL) {
7793 err = got_error_from_errno2("fopen", path);
7794 goto done;
7797 err = histedit_parse_list(histedit_cmds, f, repo);
7798 done:
7799 if (f && fclose(f) != 0 && err == NULL)
7800 err = got_error_from_errno("fclose");
7801 return err;
7804 static const struct got_error *
7805 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
7806 const struct got_error *edit_err, struct got_object_id_queue *commits,
7807 const char *path, const char *branch_name, struct got_repository *repo)
7809 const struct got_error *err = NULL, *prev_err = edit_err;
7810 int resp = ' ';
7812 while (resp != 'c' && resp != 'r' && resp != 'a') {
7813 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
7814 "or (a)bort: ", getprogname(), prev_err->msg);
7815 resp = getchar();
7816 if (resp == '\n')
7817 resp = getchar();
7818 if (resp == 'c') {
7819 histedit_free_list(histedit_cmds);
7820 err = histedit_run_editor(histedit_cmds, path, commits,
7821 repo);
7822 if (err) {
7823 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7824 err->code != GOT_ERR_HISTEDIT_CMD)
7825 break;
7826 prev_err = err;
7827 resp = ' ';
7828 continue;
7830 break;
7831 } else if (resp == 'r') {
7832 histedit_free_list(histedit_cmds);
7833 err = histedit_edit_script(histedit_cmds,
7834 commits, branch_name, 0, repo);
7835 if (err) {
7836 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7837 err->code != GOT_ERR_HISTEDIT_CMD)
7838 break;
7839 prev_err = err;
7840 resp = ' ';
7841 continue;
7843 break;
7844 } else if (resp == 'a') {
7845 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
7846 break;
7847 } else
7848 printf("invalid response '%c'\n", resp);
7851 return err;
7854 static const struct got_error *
7855 histedit_complete(struct got_worktree *worktree,
7856 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
7857 struct got_reference *branch, struct got_repository *repo)
7859 printf("Switching work tree to %s\n",
7860 got_ref_get_symref_target(branch));
7861 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
7862 branch, repo);
7865 static const struct got_error *
7866 show_histedit_progress(struct got_commit_object *commit,
7867 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
7869 const struct got_error *err;
7870 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7872 err = got_object_id_str(&old_id_str, hle->commit_id);
7873 if (err)
7874 goto done;
7876 if (new_id) {
7877 err = got_object_id_str(&new_id_str, new_id);
7878 if (err)
7879 goto done;
7882 old_id_str[12] = '\0';
7883 if (new_id_str)
7884 new_id_str[12] = '\0';
7886 if (hle->logmsg) {
7887 logmsg = strdup(hle->logmsg);
7888 if (logmsg == NULL) {
7889 err = got_error_from_errno("strdup");
7890 goto done;
7892 trim_logmsg(logmsg, 42);
7893 } else {
7894 err = get_short_logmsg(&logmsg, 42, commit);
7895 if (err)
7896 goto done;
7899 switch (hle->cmd->code) {
7900 case GOT_HISTEDIT_PICK:
7901 case GOT_HISTEDIT_EDIT:
7902 printf("%s -> %s: %s\n", old_id_str,
7903 new_id_str ? new_id_str : "no-op change", logmsg);
7904 break;
7905 case GOT_HISTEDIT_DROP:
7906 case GOT_HISTEDIT_FOLD:
7907 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
7908 logmsg);
7909 break;
7910 default:
7911 break;
7913 done:
7914 free(old_id_str);
7915 free(new_id_str);
7916 return err;
7919 static const struct got_error *
7920 histedit_commit(struct got_pathlist_head *merged_paths,
7921 struct got_worktree *worktree, struct got_fileindex *fileindex,
7922 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
7923 struct got_repository *repo)
7925 const struct got_error *err;
7926 struct got_commit_object *commit;
7927 struct got_object_id *new_commit_id;
7929 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
7930 && hle->logmsg == NULL) {
7931 err = histedit_edit_logmsg(hle, repo);
7932 if (err)
7933 return err;
7936 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7937 if (err)
7938 return err;
7940 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
7941 worktree, fileindex, tmp_branch, commit, hle->commit_id,
7942 hle->logmsg, repo);
7943 if (err) {
7944 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
7945 goto done;
7946 err = show_histedit_progress(commit, hle, NULL);
7947 } else {
7948 err = show_histedit_progress(commit, hle, new_commit_id);
7949 free(new_commit_id);
7951 done:
7952 got_object_commit_close(commit);
7953 return err;
7956 static const struct got_error *
7957 histedit_skip_commit(struct got_histedit_list_entry *hle,
7958 struct got_worktree *worktree, struct got_repository *repo)
7960 const struct got_error *error;
7961 struct got_commit_object *commit;
7963 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
7964 repo);
7965 if (error)
7966 return error;
7968 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
7969 if (error)
7970 return error;
7972 error = show_histedit_progress(commit, hle, NULL);
7973 got_object_commit_close(commit);
7974 return error;
7977 static const struct got_error *
7978 check_local_changes(void *arg, unsigned char status,
7979 unsigned char staged_status, const char *path,
7980 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
7981 struct got_object_id *commit_id, int dirfd, const char *de_name)
7983 int *have_local_changes = arg;
7985 switch (status) {
7986 case GOT_STATUS_ADD:
7987 case GOT_STATUS_DELETE:
7988 case GOT_STATUS_MODIFY:
7989 case GOT_STATUS_CONFLICT:
7990 *have_local_changes = 1;
7991 return got_error(GOT_ERR_CANCELLED);
7992 default:
7993 break;
7996 switch (staged_status) {
7997 case GOT_STATUS_ADD:
7998 case GOT_STATUS_DELETE:
7999 case GOT_STATUS_MODIFY:
8000 *have_local_changes = 1;
8001 return got_error(GOT_ERR_CANCELLED);
8002 default:
8003 break;
8006 return NULL;
8009 static const struct got_error *
8010 cmd_histedit(int argc, char *argv[])
8012 const struct got_error *error = NULL;
8013 struct got_worktree *worktree = NULL;
8014 struct got_fileindex *fileindex = NULL;
8015 struct got_repository *repo = NULL;
8016 char *cwd = NULL;
8017 struct got_reference *branch = NULL;
8018 struct got_reference *tmp_branch = NULL;
8019 struct got_object_id *resume_commit_id = NULL;
8020 struct got_object_id *base_commit_id = NULL;
8021 struct got_object_id *head_commit_id = NULL;
8022 struct got_commit_object *commit = NULL;
8023 int ch, rebase_in_progress = 0;
8024 struct got_update_progress_arg upa;
8025 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8026 int edit_logmsg_only = 0;
8027 const char *edit_script_path = NULL;
8028 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8029 struct got_object_id_queue commits;
8030 struct got_pathlist_head merged_paths;
8031 const struct got_object_id_queue *parent_ids;
8032 struct got_object_qid *pid;
8033 struct got_histedit_list histedit_cmds;
8034 struct got_histedit_list_entry *hle;
8036 SIMPLEQ_INIT(&commits);
8037 TAILQ_INIT(&histedit_cmds);
8038 TAILQ_INIT(&merged_paths);
8039 memset(&upa, 0, sizeof(upa));
8041 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
8042 switch (ch) {
8043 case 'a':
8044 abort_edit = 1;
8045 break;
8046 case 'c':
8047 continue_edit = 1;
8048 break;
8049 case 'F':
8050 edit_script_path = optarg;
8051 break;
8052 case 'm':
8053 edit_logmsg_only = 1;
8054 break;
8055 default:
8056 usage_histedit();
8057 /* NOTREACHED */
8061 argc -= optind;
8062 argv += optind;
8064 #ifndef PROFILE
8065 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8066 "unveil", NULL) == -1)
8067 err(1, "pledge");
8068 #endif
8069 if (abort_edit && continue_edit)
8070 errx(1, "histedit's -a and -c options are mutually exclusive");
8071 if (edit_script_path && edit_logmsg_only)
8072 errx(1, "histedit's -F and -m options are mutually exclusive");
8073 if (abort_edit && edit_logmsg_only)
8074 errx(1, "histedit's -a and -m options are mutually exclusive");
8075 if (continue_edit && edit_logmsg_only)
8076 errx(1, "histedit's -c and -m options are mutually exclusive");
8077 if (argc != 0)
8078 usage_histedit();
8081 * This command cannot apply unveil(2) in all cases because the
8082 * user may choose to run an editor to edit the histedit script
8083 * and to edit individual commit log messages.
8084 * unveil(2) traverses exec(2); if an editor is used we have to
8085 * apply unveil after edit script and log messages have been written.
8086 * XXX TODO: Make use of unveil(2) where possible.
8089 cwd = getcwd(NULL, 0);
8090 if (cwd == NULL) {
8091 error = got_error_from_errno("getcwd");
8092 goto done;
8094 error = got_worktree_open(&worktree, cwd);
8095 if (error) {
8096 if (error->code == GOT_ERR_NOT_WORKTREE)
8097 error = wrap_not_worktree_error(error, "histedit", cwd);
8098 goto done;
8101 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8102 NULL);
8103 if (error != NULL)
8104 goto done;
8106 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8107 if (error)
8108 goto done;
8109 if (rebase_in_progress) {
8110 error = got_error(GOT_ERR_REBASING);
8111 goto done;
8114 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8115 if (error)
8116 goto done;
8118 if (edit_in_progress && edit_logmsg_only) {
8119 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8120 "histedit operation is in progress in this "
8121 "work tree and must be continued or aborted "
8122 "before the -m option can be used");
8123 goto done;
8126 if (edit_in_progress && abort_edit) {
8127 error = got_worktree_histedit_continue(&resume_commit_id,
8128 &tmp_branch, &branch, &base_commit_id, &fileindex,
8129 worktree, repo);
8130 if (error)
8131 goto done;
8132 printf("Switching work tree to %s\n",
8133 got_ref_get_symref_target(branch));
8134 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8135 branch, base_commit_id, update_progress, &upa);
8136 if (error)
8137 goto done;
8138 printf("Histedit of %s aborted\n",
8139 got_ref_get_symref_target(branch));
8140 print_update_progress_stats(&upa);
8141 goto done; /* nothing else to do */
8142 } else if (abort_edit) {
8143 error = got_error(GOT_ERR_NOT_HISTEDIT);
8144 goto done;
8147 if (continue_edit) {
8148 char *path;
8150 if (!edit_in_progress) {
8151 error = got_error(GOT_ERR_NOT_HISTEDIT);
8152 goto done;
8155 error = got_worktree_get_histedit_script_path(&path, worktree);
8156 if (error)
8157 goto done;
8159 error = histedit_load_list(&histedit_cmds, path, repo);
8160 free(path);
8161 if (error)
8162 goto done;
8164 error = got_worktree_histedit_continue(&resume_commit_id,
8165 &tmp_branch, &branch, &base_commit_id, &fileindex,
8166 worktree, repo);
8167 if (error)
8168 goto done;
8170 error = got_ref_resolve(&head_commit_id, repo, branch);
8171 if (error)
8172 goto done;
8174 error = got_object_open_as_commit(&commit, repo,
8175 head_commit_id);
8176 if (error)
8177 goto done;
8178 parent_ids = got_object_commit_get_parent_ids(commit);
8179 pid = SIMPLEQ_FIRST(parent_ids);
8180 if (pid == NULL) {
8181 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8182 goto done;
8184 error = collect_commits(&commits, head_commit_id, pid->id,
8185 base_commit_id, got_worktree_get_path_prefix(worktree),
8186 GOT_ERR_HISTEDIT_PATH, repo);
8187 got_object_commit_close(commit);
8188 commit = NULL;
8189 if (error)
8190 goto done;
8191 } else {
8192 if (edit_in_progress) {
8193 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8194 goto done;
8197 error = got_ref_open(&branch, repo,
8198 got_worktree_get_head_ref_name(worktree), 0);
8199 if (error != NULL)
8200 goto done;
8202 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8203 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8204 "will not edit commit history of a branch outside "
8205 "the \"refs/heads/\" reference namespace");
8206 goto done;
8209 error = got_ref_resolve(&head_commit_id, repo, branch);
8210 got_ref_close(branch);
8211 branch = NULL;
8212 if (error)
8213 goto done;
8215 error = got_object_open_as_commit(&commit, repo,
8216 head_commit_id);
8217 if (error)
8218 goto done;
8219 parent_ids = got_object_commit_get_parent_ids(commit);
8220 pid = SIMPLEQ_FIRST(parent_ids);
8221 if (pid == NULL) {
8222 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8223 goto done;
8225 error = collect_commits(&commits, head_commit_id, pid->id,
8226 got_worktree_get_base_commit_id(worktree),
8227 got_worktree_get_path_prefix(worktree),
8228 GOT_ERR_HISTEDIT_PATH, repo);
8229 got_object_commit_close(commit);
8230 commit = NULL;
8231 if (error)
8232 goto done;
8234 if (SIMPLEQ_EMPTY(&commits)) {
8235 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8236 goto done;
8239 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8240 &base_commit_id, &fileindex, worktree, repo);
8241 if (error)
8242 goto done;
8244 if (edit_script_path) {
8245 error = histedit_load_list(&histedit_cmds,
8246 edit_script_path, repo);
8247 if (error) {
8248 got_worktree_histedit_abort(worktree, fileindex,
8249 repo, branch, base_commit_id,
8250 update_progress, &upa);
8251 print_update_progress_stats(&upa);
8252 goto done;
8254 } else {
8255 const char *branch_name;
8256 branch_name = got_ref_get_symref_target(branch);
8257 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8258 branch_name += 11;
8259 error = histedit_edit_script(&histedit_cmds, &commits,
8260 branch_name, edit_logmsg_only, repo);
8261 if (error) {
8262 got_worktree_histedit_abort(worktree, fileindex,
8263 repo, branch, base_commit_id,
8264 update_progress, &upa);
8265 print_update_progress_stats(&upa);
8266 goto done;
8271 error = histedit_save_list(&histedit_cmds, worktree,
8272 repo);
8273 if (error) {
8274 got_worktree_histedit_abort(worktree, fileindex,
8275 repo, branch, base_commit_id,
8276 update_progress, &upa);
8277 print_update_progress_stats(&upa);
8278 goto done;
8283 error = histedit_check_script(&histedit_cmds, &commits, repo);
8284 if (error)
8285 goto done;
8287 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8288 if (resume_commit_id) {
8289 if (got_object_id_cmp(hle->commit_id,
8290 resume_commit_id) != 0)
8291 continue;
8293 resume_commit_id = NULL;
8294 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8295 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8296 error = histedit_skip_commit(hle, worktree,
8297 repo);
8298 if (error)
8299 goto done;
8300 } else {
8301 struct got_pathlist_head paths;
8302 int have_changes = 0;
8304 TAILQ_INIT(&paths);
8305 error = got_pathlist_append(&paths, "", NULL);
8306 if (error)
8307 goto done;
8308 error = got_worktree_status(worktree, &paths,
8309 repo, check_local_changes, &have_changes,
8310 check_cancelled, NULL);
8311 got_pathlist_free(&paths);
8312 if (error) {
8313 if (error->code != GOT_ERR_CANCELLED)
8314 goto done;
8315 if (sigint_received || sigpipe_received)
8316 goto done;
8318 if (have_changes) {
8319 error = histedit_commit(NULL, worktree,
8320 fileindex, tmp_branch, hle, repo);
8321 if (error)
8322 goto done;
8323 } else {
8324 error = got_object_open_as_commit(
8325 &commit, repo, hle->commit_id);
8326 if (error)
8327 goto done;
8328 error = show_histedit_progress(commit,
8329 hle, NULL);
8330 got_object_commit_close(commit);
8331 commit = NULL;
8332 if (error)
8333 goto done;
8336 continue;
8339 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8340 error = histedit_skip_commit(hle, worktree, repo);
8341 if (error)
8342 goto done;
8343 continue;
8346 error = got_object_open_as_commit(&commit, repo,
8347 hle->commit_id);
8348 if (error)
8349 goto done;
8350 parent_ids = got_object_commit_get_parent_ids(commit);
8351 pid = SIMPLEQ_FIRST(parent_ids);
8353 error = got_worktree_histedit_merge_files(&merged_paths,
8354 worktree, fileindex, pid->id, hle->commit_id, repo,
8355 update_progress, &upa, check_cancelled, NULL);
8356 if (error)
8357 goto done;
8358 got_object_commit_close(commit);
8359 commit = NULL;
8361 print_update_progress_stats(&upa);
8362 if (upa.conflicts > 0)
8363 rebase_status = GOT_STATUS_CONFLICT;
8365 if (rebase_status == GOT_STATUS_CONFLICT) {
8366 error = show_rebase_merge_conflict(hle->commit_id,
8367 repo);
8368 if (error)
8369 goto done;
8370 got_worktree_rebase_pathlist_free(&merged_paths);
8371 break;
8374 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8375 char *id_str;
8376 error = got_object_id_str(&id_str, hle->commit_id);
8377 if (error)
8378 goto done;
8379 printf("Stopping histedit for amending commit %s\n",
8380 id_str);
8381 free(id_str);
8382 got_worktree_rebase_pathlist_free(&merged_paths);
8383 error = got_worktree_histedit_postpone(worktree,
8384 fileindex);
8385 goto done;
8388 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8389 error = histedit_skip_commit(hle, worktree, repo);
8390 if (error)
8391 goto done;
8392 continue;
8395 error = histedit_commit(&merged_paths, worktree, fileindex,
8396 tmp_branch, hle, repo);
8397 got_worktree_rebase_pathlist_free(&merged_paths);
8398 if (error)
8399 goto done;
8402 if (rebase_status == GOT_STATUS_CONFLICT) {
8403 error = got_worktree_histedit_postpone(worktree, fileindex);
8404 if (error)
8405 goto done;
8406 error = got_error_msg(GOT_ERR_CONFLICTS,
8407 "conflicts must be resolved before histedit can continue");
8408 } else
8409 error = histedit_complete(worktree, fileindex, tmp_branch,
8410 branch, repo);
8411 done:
8412 got_object_id_queue_free(&commits);
8413 histedit_free_list(&histedit_cmds);
8414 free(head_commit_id);
8415 free(base_commit_id);
8416 free(resume_commit_id);
8417 if (commit)
8418 got_object_commit_close(commit);
8419 if (branch)
8420 got_ref_close(branch);
8421 if (tmp_branch)
8422 got_ref_close(tmp_branch);
8423 if (worktree)
8424 got_worktree_close(worktree);
8425 if (repo)
8426 got_repo_close(repo);
8427 return error;
8430 __dead static void
8431 usage_integrate(void)
8433 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
8434 exit(1);
8437 static const struct got_error *
8438 cmd_integrate(int argc, char *argv[])
8440 const struct got_error *error = NULL;
8441 struct got_repository *repo = NULL;
8442 struct got_worktree *worktree = NULL;
8443 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
8444 const char *branch_arg = NULL;
8445 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
8446 struct got_fileindex *fileindex = NULL;
8447 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
8448 int ch;
8449 struct got_update_progress_arg upa;
8451 while ((ch = getopt(argc, argv, "")) != -1) {
8452 switch (ch) {
8453 default:
8454 usage_integrate();
8455 /* NOTREACHED */
8459 argc -= optind;
8460 argv += optind;
8462 if (argc != 1)
8463 usage_integrate();
8464 branch_arg = argv[0];
8466 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8467 "unveil", NULL) == -1)
8468 err(1, "pledge");
8470 cwd = getcwd(NULL, 0);
8471 if (cwd == NULL) {
8472 error = got_error_from_errno("getcwd");
8473 goto done;
8476 error = got_worktree_open(&worktree, cwd);
8477 if (error) {
8478 if (error->code == GOT_ERR_NOT_WORKTREE)
8479 error = wrap_not_worktree_error(error, "integrate",
8480 cwd);
8481 goto done;
8484 error = check_rebase_or_histedit_in_progress(worktree);
8485 if (error)
8486 goto done;
8488 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8489 NULL);
8490 if (error != NULL)
8491 goto done;
8493 error = apply_unveil(got_repo_get_path(repo), 0,
8494 got_worktree_get_root_path(worktree));
8495 if (error)
8496 goto done;
8498 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
8499 error = got_error_from_errno("asprintf");
8500 goto done;
8503 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
8504 &base_branch_ref, worktree, refname, repo);
8505 if (error)
8506 goto done;
8508 refname = strdup(got_ref_get_name(branch_ref));
8509 if (refname == NULL) {
8510 error = got_error_from_errno("strdup");
8511 got_worktree_integrate_abort(worktree, fileindex, repo,
8512 branch_ref, base_branch_ref);
8513 goto done;
8515 base_refname = strdup(got_ref_get_name(base_branch_ref));
8516 if (base_refname == NULL) {
8517 error = got_error_from_errno("strdup");
8518 got_worktree_integrate_abort(worktree, fileindex, repo,
8519 branch_ref, base_branch_ref);
8520 goto done;
8523 error = got_ref_resolve(&commit_id, repo, branch_ref);
8524 if (error)
8525 goto done;
8527 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
8528 if (error)
8529 goto done;
8531 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
8532 error = got_error_msg(GOT_ERR_SAME_BRANCH,
8533 "specified branch has already been integrated");
8534 got_worktree_integrate_abort(worktree, fileindex, repo,
8535 branch_ref, base_branch_ref);
8536 goto done;
8539 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
8540 if (error) {
8541 if (error->code == GOT_ERR_ANCESTRY)
8542 error = got_error(GOT_ERR_REBASE_REQUIRED);
8543 got_worktree_integrate_abort(worktree, fileindex, repo,
8544 branch_ref, base_branch_ref);
8545 goto done;
8548 memset(&upa, 0, sizeof(upa));
8549 error = got_worktree_integrate_continue(worktree, fileindex, repo,
8550 branch_ref, base_branch_ref, update_progress, &upa,
8551 check_cancelled, NULL);
8552 if (error)
8553 goto done;
8555 printf("Integrated %s into %s\n", refname, base_refname);
8556 print_update_progress_stats(&upa);
8557 done:
8558 if (repo)
8559 got_repo_close(repo);
8560 if (worktree)
8561 got_worktree_close(worktree);
8562 free(cwd);
8563 free(base_commit_id);
8564 free(commit_id);
8565 free(refname);
8566 free(base_refname);
8567 return error;
8570 __dead static void
8571 usage_stage(void)
8573 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
8574 "[file-path ...]\n",
8575 getprogname());
8576 exit(1);
8579 static const struct got_error *
8580 print_stage(void *arg, unsigned char status, unsigned char staged_status,
8581 const char *path, struct got_object_id *blob_id,
8582 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
8583 int dirfd, const char *de_name)
8585 const struct got_error *err = NULL;
8586 char *id_str = NULL;
8588 if (staged_status != GOT_STATUS_ADD &&
8589 staged_status != GOT_STATUS_MODIFY &&
8590 staged_status != GOT_STATUS_DELETE)
8591 return NULL;
8593 if (staged_status == GOT_STATUS_ADD ||
8594 staged_status == GOT_STATUS_MODIFY)
8595 err = got_object_id_str(&id_str, staged_blob_id);
8596 else
8597 err = got_object_id_str(&id_str, blob_id);
8598 if (err)
8599 return err;
8601 printf("%s %c %s\n", id_str, staged_status, path);
8602 free(id_str);
8603 return NULL;
8606 static const struct got_error *
8607 cmd_stage(int argc, char *argv[])
8609 const struct got_error *error = NULL;
8610 struct got_repository *repo = NULL;
8611 struct got_worktree *worktree = NULL;
8612 char *cwd = NULL;
8613 struct got_pathlist_head paths;
8614 struct got_pathlist_entry *pe;
8615 int ch, list_stage = 0, pflag = 0;
8616 FILE *patch_script_file = NULL;
8617 const char *patch_script_path = NULL;
8618 struct choose_patch_arg cpa;
8620 TAILQ_INIT(&paths);
8622 while ((ch = getopt(argc, argv, "lpF:")) != -1) {
8623 switch (ch) {
8624 case 'l':
8625 list_stage = 1;
8626 break;
8627 case 'p':
8628 pflag = 1;
8629 break;
8630 case 'F':
8631 patch_script_path = optarg;
8632 break;
8633 default:
8634 usage_stage();
8635 /* NOTREACHED */
8639 argc -= optind;
8640 argv += optind;
8642 #ifndef PROFILE
8643 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8644 "unveil", NULL) == -1)
8645 err(1, "pledge");
8646 #endif
8647 if (list_stage && (pflag || patch_script_path))
8648 errx(1, "-l option cannot be used with other options");
8649 if (patch_script_path && !pflag)
8650 errx(1, "-F option can only be used together with -p option");
8652 cwd = getcwd(NULL, 0);
8653 if (cwd == NULL) {
8654 error = got_error_from_errno("getcwd");
8655 goto done;
8658 error = got_worktree_open(&worktree, cwd);
8659 if (error) {
8660 if (error->code == GOT_ERR_NOT_WORKTREE)
8661 error = wrap_not_worktree_error(error, "stage", cwd);
8662 goto done;
8665 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8666 NULL);
8667 if (error != NULL)
8668 goto done;
8670 if (patch_script_path) {
8671 patch_script_file = fopen(patch_script_path, "r");
8672 if (patch_script_file == NULL) {
8673 error = got_error_from_errno2("fopen",
8674 patch_script_path);
8675 goto done;
8678 error = apply_unveil(got_repo_get_path(repo), 0,
8679 got_worktree_get_root_path(worktree));
8680 if (error)
8681 goto done;
8683 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8684 if (error)
8685 goto done;
8687 if (list_stage)
8688 error = got_worktree_status(worktree, &paths, repo,
8689 print_stage, NULL, check_cancelled, NULL);
8690 else {
8691 cpa.patch_script_file = patch_script_file;
8692 cpa.action = "stage";
8693 error = got_worktree_stage(worktree, &paths,
8694 pflag ? NULL : print_status, NULL,
8695 pflag ? choose_patch : NULL, &cpa, repo);
8697 done:
8698 if (patch_script_file && fclose(patch_script_file) == EOF &&
8699 error == NULL)
8700 error = got_error_from_errno2("fclose", patch_script_path);
8701 if (repo)
8702 got_repo_close(repo);
8703 if (worktree)
8704 got_worktree_close(worktree);
8705 TAILQ_FOREACH(pe, &paths, entry)
8706 free((char *)pe->path);
8707 got_pathlist_free(&paths);
8708 free(cwd);
8709 return error;
8712 __dead static void
8713 usage_unstage(void)
8715 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
8716 "[file-path ...]\n",
8717 getprogname());
8718 exit(1);
8722 static const struct got_error *
8723 cmd_unstage(int argc, char *argv[])
8725 const struct got_error *error = NULL;
8726 struct got_repository *repo = NULL;
8727 struct got_worktree *worktree = NULL;
8728 char *cwd = NULL;
8729 struct got_pathlist_head paths;
8730 struct got_pathlist_entry *pe;
8731 int ch, pflag = 0;
8732 struct got_update_progress_arg upa;
8733 FILE *patch_script_file = NULL;
8734 const char *patch_script_path = NULL;
8735 struct choose_patch_arg cpa;
8737 TAILQ_INIT(&paths);
8739 while ((ch = getopt(argc, argv, "pF:")) != -1) {
8740 switch (ch) {
8741 case 'p':
8742 pflag = 1;
8743 break;
8744 case 'F':
8745 patch_script_path = optarg;
8746 break;
8747 default:
8748 usage_unstage();
8749 /* NOTREACHED */
8753 argc -= optind;
8754 argv += optind;
8756 #ifndef PROFILE
8757 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8758 "unveil", NULL) == -1)
8759 err(1, "pledge");
8760 #endif
8761 if (patch_script_path && !pflag)
8762 errx(1, "-F option can only be used together with -p option");
8764 cwd = getcwd(NULL, 0);
8765 if (cwd == NULL) {
8766 error = got_error_from_errno("getcwd");
8767 goto done;
8770 error = got_worktree_open(&worktree, cwd);
8771 if (error) {
8772 if (error->code == GOT_ERR_NOT_WORKTREE)
8773 error = wrap_not_worktree_error(error, "unstage", cwd);
8774 goto done;
8777 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8778 NULL);
8779 if (error != NULL)
8780 goto done;
8782 if (patch_script_path) {
8783 patch_script_file = fopen(patch_script_path, "r");
8784 if (patch_script_file == NULL) {
8785 error = got_error_from_errno2("fopen",
8786 patch_script_path);
8787 goto done;
8791 error = apply_unveil(got_repo_get_path(repo), 0,
8792 got_worktree_get_root_path(worktree));
8793 if (error)
8794 goto done;
8796 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8797 if (error)
8798 goto done;
8800 cpa.patch_script_file = patch_script_file;
8801 cpa.action = "unstage";
8802 memset(&upa, 0, sizeof(upa));
8803 error = got_worktree_unstage(worktree, &paths, update_progress,
8804 &upa, pflag ? choose_patch : NULL, &cpa, repo);
8805 if (!error)
8806 print_update_progress_stats(&upa);
8807 done:
8808 if (patch_script_file && fclose(patch_script_file) == EOF &&
8809 error == NULL)
8810 error = got_error_from_errno2("fclose", patch_script_path);
8811 if (repo)
8812 got_repo_close(repo);
8813 if (worktree)
8814 got_worktree_close(worktree);
8815 TAILQ_FOREACH(pe, &paths, entry)
8816 free((char *)pe->path);
8817 got_pathlist_free(&paths);
8818 free(cwd);
8819 return error;
8822 __dead static void
8823 usage_cat(void)
8825 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
8826 "arg1 [arg2 ...]\n", getprogname());
8827 exit(1);
8830 static const struct got_error *
8831 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8833 const struct got_error *err;
8834 struct got_blob_object *blob;
8836 err = got_object_open_as_blob(&blob, repo, id, 8192);
8837 if (err)
8838 return err;
8840 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
8841 got_object_blob_close(blob);
8842 return err;
8845 static const struct got_error *
8846 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8848 const struct got_error *err;
8849 struct got_tree_object *tree;
8850 int nentries, i;
8852 err = got_object_open_as_tree(&tree, repo, id);
8853 if (err)
8854 return err;
8856 nentries = got_object_tree_get_nentries(tree);
8857 for (i = 0; i < nentries; i++) {
8858 struct got_tree_entry *te;
8859 char *id_str;
8860 if (sigint_received || sigpipe_received)
8861 break;
8862 te = got_object_tree_get_entry(tree, i);
8863 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
8864 if (err)
8865 break;
8866 fprintf(outfile, "%s %.7o %s\n", id_str,
8867 got_tree_entry_get_mode(te),
8868 got_tree_entry_get_name(te));
8869 free(id_str);
8872 got_object_tree_close(tree);
8873 return err;
8876 static const struct got_error *
8877 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8879 const struct got_error *err;
8880 struct got_commit_object *commit;
8881 const struct got_object_id_queue *parent_ids;
8882 struct got_object_qid *pid;
8883 char *id_str = NULL;
8884 const char *logmsg = NULL;
8886 err = got_object_open_as_commit(&commit, repo, id);
8887 if (err)
8888 return err;
8890 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
8891 if (err)
8892 goto done;
8894 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
8895 parent_ids = got_object_commit_get_parent_ids(commit);
8896 fprintf(outfile, "numparents %d\n",
8897 got_object_commit_get_nparents(commit));
8898 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
8899 char *pid_str;
8900 err = got_object_id_str(&pid_str, pid->id);
8901 if (err)
8902 goto done;
8903 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
8904 free(pid_str);
8906 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
8907 got_object_commit_get_author(commit),
8908 got_object_commit_get_author_time(commit));
8910 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
8911 got_object_commit_get_author(commit),
8912 got_object_commit_get_committer_time(commit));
8914 logmsg = got_object_commit_get_logmsg_raw(commit);
8915 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
8916 fprintf(outfile, "%s", logmsg);
8917 done:
8918 free(id_str);
8919 got_object_commit_close(commit);
8920 return err;
8923 static const struct got_error *
8924 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8926 const struct got_error *err;
8927 struct got_tag_object *tag;
8928 char *id_str = NULL;
8929 const char *tagmsg = NULL;
8931 err = got_object_open_as_tag(&tag, repo, id);
8932 if (err)
8933 return err;
8935 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
8936 if (err)
8937 goto done;
8939 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
8941 switch (got_object_tag_get_object_type(tag)) {
8942 case GOT_OBJ_TYPE_BLOB:
8943 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8944 GOT_OBJ_LABEL_BLOB);
8945 break;
8946 case GOT_OBJ_TYPE_TREE:
8947 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8948 GOT_OBJ_LABEL_TREE);
8949 break;
8950 case GOT_OBJ_TYPE_COMMIT:
8951 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8952 GOT_OBJ_LABEL_COMMIT);
8953 break;
8954 case GOT_OBJ_TYPE_TAG:
8955 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8956 GOT_OBJ_LABEL_TAG);
8957 break;
8958 default:
8959 break;
8962 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
8963 got_object_tag_get_name(tag));
8965 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
8966 got_object_tag_get_tagger(tag),
8967 got_object_tag_get_tagger_time(tag));
8969 tagmsg = got_object_tag_get_message(tag);
8970 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
8971 fprintf(outfile, "%s", tagmsg);
8972 done:
8973 free(id_str);
8974 got_object_tag_close(tag);
8975 return err;
8978 static const struct got_error *
8979 cmd_cat(int argc, char *argv[])
8981 const struct got_error *error;
8982 struct got_repository *repo = NULL;
8983 struct got_worktree *worktree = NULL;
8984 char *cwd = NULL, *repo_path = NULL, *label = NULL;
8985 const char *commit_id_str = NULL;
8986 struct got_object_id *id = NULL, *commit_id = NULL;
8987 int ch, obj_type, i, force_path = 0;
8989 #ifndef PROFILE
8990 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8991 NULL) == -1)
8992 err(1, "pledge");
8993 #endif
8995 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
8996 switch (ch) {
8997 case 'c':
8998 commit_id_str = optarg;
8999 break;
9000 case 'r':
9001 repo_path = realpath(optarg, NULL);
9002 if (repo_path == NULL)
9003 return got_error_from_errno2("realpath",
9004 optarg);
9005 got_path_strip_trailing_slashes(repo_path);
9006 break;
9007 case 'P':
9008 force_path = 1;
9009 break;
9010 default:
9011 usage_cat();
9012 /* NOTREACHED */
9016 argc -= optind;
9017 argv += optind;
9019 cwd = getcwd(NULL, 0);
9020 if (cwd == NULL) {
9021 error = got_error_from_errno("getcwd");
9022 goto done;
9024 error = got_worktree_open(&worktree, cwd);
9025 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9026 goto done;
9027 if (worktree) {
9028 if (repo_path == NULL) {
9029 repo_path = strdup(
9030 got_worktree_get_repo_path(worktree));
9031 if (repo_path == NULL) {
9032 error = got_error_from_errno("strdup");
9033 goto done;
9038 if (repo_path == NULL) {
9039 repo_path = getcwd(NULL, 0);
9040 if (repo_path == NULL)
9041 return got_error_from_errno("getcwd");
9044 error = got_repo_open(&repo, repo_path, NULL);
9045 free(repo_path);
9046 if (error != NULL)
9047 goto done;
9049 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9050 if (error)
9051 goto done;
9053 if (commit_id_str == NULL)
9054 commit_id_str = GOT_REF_HEAD;
9055 error = got_repo_match_object_id(&commit_id, NULL,
9056 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
9057 if (error)
9058 goto done;
9060 for (i = 0; i < argc; i++) {
9061 if (force_path) {
9062 error = got_object_id_by_path(&id, repo, commit_id,
9063 argv[i]);
9064 if (error)
9065 break;
9066 } else {
9067 error = got_repo_match_object_id(&id, &label, argv[i],
9068 GOT_OBJ_TYPE_ANY, 0, repo);
9069 if (error) {
9070 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9071 error->code != GOT_ERR_NOT_REF)
9072 break;
9073 error = got_object_id_by_path(&id, repo,
9074 commit_id, argv[i]);
9075 if (error)
9076 break;
9080 error = got_object_get_type(&obj_type, repo, id);
9081 if (error)
9082 break;
9084 switch (obj_type) {
9085 case GOT_OBJ_TYPE_BLOB:
9086 error = cat_blob(id, repo, stdout);
9087 break;
9088 case GOT_OBJ_TYPE_TREE:
9089 error = cat_tree(id, repo, stdout);
9090 break;
9091 case GOT_OBJ_TYPE_COMMIT:
9092 error = cat_commit(id, repo, stdout);
9093 break;
9094 case GOT_OBJ_TYPE_TAG:
9095 error = cat_tag(id, repo, stdout);
9096 break;
9097 default:
9098 error = got_error(GOT_ERR_OBJ_TYPE);
9099 break;
9101 if (error)
9102 break;
9103 free(label);
9104 label = NULL;
9105 free(id);
9106 id = NULL;
9108 done:
9109 free(label);
9110 free(id);
9111 free(commit_id);
9112 if (worktree)
9113 got_worktree_close(worktree);
9114 if (repo) {
9115 const struct got_error *repo_error;
9116 repo_error = got_repo_close(repo);
9117 if (error == NULL)
9118 error = repo_error;
9120 return error;