Blob


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