Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/param.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
41 #include <util.h>
43 #include "got_version.h"
44 #include "got_error.h"
45 #include "got_object.h"
46 #include "got_reference.h"
47 #include "got_repository.h"
48 #include "got_path.h"
49 #include "got_cancel.h"
50 #include "got_worktree.h"
51 #include "got_diff.h"
52 #include "got_commit_graph.h"
53 #include "got_fetch.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_opentemp.h"
58 #ifndef nitems
59 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
60 #endif
62 static volatile sig_atomic_t sigint_received;
63 static volatile sig_atomic_t sigpipe_received;
65 static void
66 catch_sigint(int signo)
67 {
68 sigint_received = 1;
69 }
71 static void
72 catch_sigpipe(int signo)
73 {
74 sigpipe_received = 1;
75 }
78 struct got_cmd {
79 const char *cmd_name;
80 const struct got_error *(*cmd_main)(int, char *[]);
81 void (*cmd_usage)(void);
82 const char *cmd_alias;
83 };
85 __dead static void usage(int);
86 __dead static void usage_init(void);
87 __dead static void usage_import(void);
88 __dead static void usage_clone(void);
89 __dead static void usage_fetch(void);
90 __dead static void usage_checkout(void);
91 __dead static void usage_update(void);
92 __dead static void usage_log(void);
93 __dead static void usage_diff(void);
94 __dead static void usage_blame(void);
95 __dead static void usage_tree(void);
96 __dead static void usage_status(void);
97 __dead static void usage_ref(void);
98 __dead static void usage_branch(void);
99 __dead static void usage_tag(void);
100 __dead static void usage_add(void);
101 __dead static void usage_remove(void);
102 __dead static void usage_revert(void);
103 __dead static void usage_commit(void);
104 __dead static void usage_cherrypick(void);
105 __dead static void usage_backout(void);
106 __dead static void usage_rebase(void);
107 __dead static void usage_histedit(void);
108 __dead static void usage_integrate(void);
109 __dead static void usage_stage(void);
110 __dead static void usage_unstage(void);
111 __dead static void usage_cat(void);
113 static const struct got_error* cmd_init(int, char *[]);
114 static const struct got_error* cmd_import(int, char *[]);
115 static const struct got_error* cmd_clone(int, char *[]);
116 static const struct got_error* cmd_fetch(int, char *[]);
117 static const struct got_error* cmd_checkout(int, char *[]);
118 static const struct got_error* cmd_update(int, char *[]);
119 static const struct got_error* cmd_log(int, char *[]);
120 static const struct got_error* cmd_diff(int, char *[]);
121 static const struct got_error* cmd_blame(int, char *[]);
122 static const struct got_error* cmd_tree(int, char *[]);
123 static const struct got_error* cmd_status(int, char *[]);
124 static const struct got_error* cmd_ref(int, char *[]);
125 static const struct got_error* cmd_branch(int, char *[]);
126 static const struct got_error* cmd_tag(int, char *[]);
127 static const struct got_error* cmd_add(int, char *[]);
128 static const struct got_error* cmd_remove(int, char *[]);
129 static const struct got_error* cmd_revert(int, char *[]);
130 static const struct got_error* cmd_commit(int, char *[]);
131 static const struct got_error* cmd_cherrypick(int, char *[]);
132 static const struct got_error* cmd_backout(int, char *[]);
133 static const struct got_error* cmd_rebase(int, char *[]);
134 static const struct got_error* cmd_histedit(int, char *[]);
135 static const struct got_error* cmd_integrate(int, char *[]);
136 static const struct got_error* cmd_stage(int, char *[]);
137 static const struct got_error* cmd_unstage(int, char *[]);
138 static const struct got_error* cmd_cat(int, char *[]);
140 static struct got_cmd got_commands[] = {
141 { "init", cmd_init, usage_init, "in" },
142 { "import", cmd_import, usage_import, "im" },
143 { "clone", cmd_clone, usage_clone, "cl" },
144 { "fetch", cmd_fetch, usage_fetch, "fe" },
145 { "checkout", cmd_checkout, usage_checkout, "co" },
146 { "update", cmd_update, usage_update, "up" },
147 { "log", cmd_log, usage_log, "" },
148 { "diff", cmd_diff, usage_diff, "di" },
149 { "blame", cmd_blame, usage_blame, "bl" },
150 { "tree", cmd_tree, usage_tree, "tr" },
151 { "status", cmd_status, usage_status, "st" },
152 { "ref", cmd_ref, usage_ref, "" },
153 { "branch", cmd_branch, usage_branch, "br" },
154 { "tag", cmd_tag, usage_tag, "" },
155 { "add", cmd_add, usage_add, "" },
156 { "remove", cmd_remove, usage_remove, "rm" },
157 { "revert", cmd_revert, usage_revert, "rv" },
158 { "commit", cmd_commit, usage_commit, "ci" },
159 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
160 { "backout", cmd_backout, usage_backout, "bo" },
161 { "rebase", cmd_rebase, usage_rebase, "rb" },
162 { "histedit", cmd_histedit, usage_histedit, "he" },
163 { "integrate", cmd_integrate, usage_integrate,"ig" },
164 { "stage", cmd_stage, usage_stage, "sg" },
165 { "unstage", cmd_unstage, usage_unstage, "ug" },
166 { "cat", cmd_cat, usage_cat, "" },
167 };
169 static void
170 list_commands(void)
172 int i;
174 fprintf(stderr, "commands:");
175 for (i = 0; i < nitems(got_commands); i++) {
176 struct got_cmd *cmd = &got_commands[i];
177 fprintf(stderr, " %s", cmd->cmd_name);
179 fputc('\n', stderr);
182 int
183 main(int argc, char *argv[])
185 struct got_cmd *cmd;
186 unsigned int i;
187 int ch;
188 int hflag = 0, Vflag = 0;
189 static struct option longopts[] = {
190 { "version", no_argument, NULL, 'V' },
191 { NULL, 0, NULL, 0}
192 };
194 setlocale(LC_CTYPE, "");
196 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
197 switch (ch) {
198 case 'h':
199 hflag = 1;
200 break;
201 case 'V':
202 Vflag = 1;
203 break;
204 default:
205 usage(hflag);
206 /* NOTREACHED */
210 argc -= optind;
211 argv += optind;
212 optind = 0;
214 if (Vflag) {
215 got_version_print_str();
216 return 1;
219 if (argc <= 0)
220 usage(hflag);
222 signal(SIGINT, catch_sigint);
223 signal(SIGPIPE, catch_sigpipe);
225 for (i = 0; i < nitems(got_commands); i++) {
226 const struct got_error *error;
228 cmd = &got_commands[i];
230 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
231 strcmp(cmd->cmd_alias, argv[0]) != 0)
232 continue;
234 if (hflag)
235 got_commands[i].cmd_usage();
237 error = got_commands[i].cmd_main(argc, argv);
238 if (error && error->code != GOT_ERR_CANCELLED &&
239 error->code != GOT_ERR_PRIVSEP_EXIT &&
240 !(sigpipe_received &&
241 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
242 !(sigint_received &&
243 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
244 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
245 return 1;
248 return 0;
251 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
252 list_commands();
253 return 1;
256 __dead static void
257 usage(int hflag)
259 fprintf(stderr, "usage: %s [-h] [-V | --version] command [arg ...]\n",
260 getprogname());
261 if (hflag)
262 list_commands();
263 exit(1);
266 static const struct got_error *
267 get_editor(char **abspath)
269 const struct got_error *err = NULL;
270 const char *editor;
272 *abspath = NULL;
274 editor = getenv("VISUAL");
275 if (editor == NULL)
276 editor = getenv("EDITOR");
278 if (editor) {
279 err = got_path_find_prog(abspath, editor);
280 if (err)
281 return err;
284 if (*abspath == NULL) {
285 *abspath = strdup("/bin/ed");
286 if (*abspath == NULL)
287 return got_error_from_errno("strdup");
290 return NULL;
293 static const struct got_error *
294 apply_unveil(const char *repo_path, int repo_read_only,
295 const char *worktree_path)
297 const struct got_error *err;
299 #ifdef PROFILE
300 if (unveil("gmon.out", "rwc") != 0)
301 return got_error_from_errno2("unveil", "gmon.out");
302 #endif
303 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
304 return got_error_from_errno2("unveil", repo_path);
306 if (worktree_path && unveil(worktree_path, "rwc") != 0)
307 return got_error_from_errno2("unveil", worktree_path);
309 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
310 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
312 err = got_privsep_unveil_exec_helpers();
313 if (err != NULL)
314 return err;
316 if (unveil(NULL, NULL) != 0)
317 return got_error_from_errno("unveil");
319 return NULL;
322 __dead static void
323 usage_init(void)
325 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
326 exit(1);
329 static const struct got_error *
330 cmd_init(int argc, char *argv[])
332 const struct got_error *error = NULL;
333 char *repo_path = NULL;
334 int ch;
336 while ((ch = getopt(argc, argv, "")) != -1) {
337 switch (ch) {
338 default:
339 usage_init();
340 /* NOTREACHED */
344 argc -= optind;
345 argv += optind;
347 #ifndef PROFILE
348 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
349 err(1, "pledge");
350 #endif
351 if (argc != 1)
352 usage_init();
354 repo_path = strdup(argv[0]);
355 if (repo_path == NULL)
356 return got_error_from_errno("strdup");
358 got_path_strip_trailing_slashes(repo_path);
360 error = got_path_mkdir(repo_path);
361 if (error &&
362 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
363 goto done;
365 error = apply_unveil(repo_path, 0, NULL);
366 if (error)
367 goto done;
369 error = got_repo_init(repo_path);
370 done:
371 free(repo_path);
372 return error;
375 __dead static void
376 usage_import(void)
378 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
379 "[-r repository-path] [-I pattern] path\n", getprogname());
380 exit(1);
383 int
384 spawn_editor(const char *editor, const char *file)
386 pid_t pid;
387 sig_t sighup, sigint, sigquit;
388 int st = -1;
390 sighup = signal(SIGHUP, SIG_IGN);
391 sigint = signal(SIGINT, SIG_IGN);
392 sigquit = signal(SIGQUIT, SIG_IGN);
394 switch (pid = fork()) {
395 case -1:
396 goto doneediting;
397 case 0:
398 execl(editor, editor, file, (char *)NULL);
399 _exit(127);
402 while (waitpid(pid, &st, 0) == -1)
403 if (errno != EINTR)
404 break;
406 doneediting:
407 (void)signal(SIGHUP, sighup);
408 (void)signal(SIGINT, sigint);
409 (void)signal(SIGQUIT, sigquit);
411 if (!WIFEXITED(st)) {
412 errno = EINTR;
413 return -1;
416 return WEXITSTATUS(st);
419 static const struct got_error *
420 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
421 const char *initial_content)
423 const struct got_error *err = NULL;
424 char buf[1024];
425 struct stat st, st2;
426 FILE *fp;
427 int content_changed = 0;
428 size_t len;
430 *logmsg = NULL;
432 if (stat(logmsg_path, &st) == -1)
433 return got_error_from_errno2("stat", logmsg_path);
435 if (spawn_editor(editor, logmsg_path) == -1)
436 return got_error_from_errno("failed spawning editor");
438 if (stat(logmsg_path, &st2) == -1)
439 return got_error_from_errno("stat");
441 if (st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
442 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
443 "no changes made to commit message, aborting");
445 *logmsg = malloc(st2.st_size + 1);
446 if (*logmsg == NULL)
447 return got_error_from_errno("malloc");
448 (*logmsg)[0] = '\0';
449 len = 0;
451 fp = fopen(logmsg_path, "r");
452 if (fp == NULL) {
453 err = got_error_from_errno("fopen");
454 goto done;
456 while (fgets(buf, sizeof(buf), fp) != NULL) {
457 if (!content_changed && strcmp(buf, initial_content) != 0)
458 content_changed = 1;
459 if (buf[0] == '#' || (len == 0 && buf[0] == '\n'))
460 continue; /* remove comments and leading empty lines */
461 len = strlcat(*logmsg, buf, st2.st_size);
463 fclose(fp);
465 while (len > 0 && (*logmsg)[len - 1] == '\n') {
466 (*logmsg)[len - 1] = '\0';
467 len--;
470 if (len == 0 || !content_changed)
471 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
472 "commit message cannot be empty, aborting");
473 done:
474 if (err) {
475 free(*logmsg);
476 *logmsg = NULL;
478 return err;
481 static const struct got_error *
482 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
483 const char *path_dir, const char *branch_name)
485 char *initial_content = NULL;
486 const struct got_error *err = NULL;
487 int fd;
489 if (asprintf(&initial_content,
490 "\n# %s to be imported to branch %s\n", path_dir,
491 branch_name) == -1)
492 return got_error_from_errno("asprintf");
494 err = got_opentemp_named_fd(logmsg_path, &fd,
495 GOT_TMPDIR_STR "/got-importmsg");
496 if (err)
497 goto done;
499 dprintf(fd, initial_content);
500 close(fd);
502 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content);
503 done:
504 free(initial_content);
505 return err;
508 static const struct got_error *
509 import_progress(void *arg, const char *path)
511 printf("A %s\n", path);
512 return NULL;
515 static const struct got_error *
516 get_author(char **author, struct got_repository *repo)
518 const struct got_error *err = NULL;
519 const char *got_author, *name, *email;
521 *author = NULL;
523 name = got_repo_get_gitconfig_author_name(repo);
524 email = got_repo_get_gitconfig_author_email(repo);
525 if (name && email) {
526 if (asprintf(author, "%s <%s>", name, email) == -1)
527 return got_error_from_errno("asprintf");
528 return NULL;
531 got_author = getenv("GOT_AUTHOR");
532 if (got_author == NULL) {
533 name = got_repo_get_global_gitconfig_author_name(repo);
534 email = got_repo_get_global_gitconfig_author_email(repo);
535 if (name && email) {
536 if (asprintf(author, "%s <%s>", name, email) == -1)
537 return got_error_from_errno("asprintf");
538 return NULL;
540 /* TODO: Look up user in password database? */
541 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
544 *author = strdup(got_author);
545 if (*author == NULL)
546 return got_error_from_errno("strdup");
548 /*
549 * Really dumb email address check; we're only doing this to
550 * avoid git's object parser breaking on commits we create.
551 */
552 while (*got_author && *got_author != '<')
553 got_author++;
554 if (*got_author != '<') {
555 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
556 goto done;
558 while (*got_author && *got_author != '@')
559 got_author++;
560 if (*got_author != '@') {
561 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
562 goto done;
564 while (*got_author && *got_author != '>')
565 got_author++;
566 if (*got_author != '>')
567 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
568 done:
569 if (err) {
570 free(*author);
571 *author = NULL;
573 return err;
576 static const struct got_error *
577 get_gitconfig_path(char **gitconfig_path)
579 const char *homedir = getenv("HOME");
581 *gitconfig_path = NULL;
582 if (homedir) {
583 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
584 return got_error_from_errno("asprintf");
587 return NULL;
590 static const struct got_error *
591 cmd_import(int argc, char *argv[])
593 const struct got_error *error = NULL;
594 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
595 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
596 const char *branch_name = "main";
597 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
598 struct got_repository *repo = NULL;
599 struct got_reference *branch_ref = NULL, *head_ref = NULL;
600 struct got_object_id *new_commit_id = NULL;
601 int ch;
602 struct got_pathlist_head ignores;
603 struct got_pathlist_entry *pe;
604 int preserve_logmsg = 0;
606 TAILQ_INIT(&ignores);
608 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
609 switch (ch) {
610 case 'b':
611 branch_name = optarg;
612 break;
613 case 'm':
614 logmsg = strdup(optarg);
615 if (logmsg == NULL) {
616 error = got_error_from_errno("strdup");
617 goto done;
619 break;
620 case 'r':
621 repo_path = realpath(optarg, NULL);
622 if (repo_path == NULL) {
623 error = got_error_from_errno2("realpath",
624 optarg);
625 goto done;
627 break;
628 case 'I':
629 if (optarg[0] == '\0')
630 break;
631 error = got_pathlist_insert(&pe, &ignores, optarg,
632 NULL);
633 if (error)
634 goto done;
635 break;
636 default:
637 usage_import();
638 /* NOTREACHED */
642 argc -= optind;
643 argv += optind;
645 #ifndef PROFILE
646 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
647 "unveil",
648 NULL) == -1)
649 err(1, "pledge");
650 #endif
651 if (argc != 1)
652 usage_import();
654 if (repo_path == NULL) {
655 repo_path = getcwd(NULL, 0);
656 if (repo_path == NULL)
657 return got_error_from_errno("getcwd");
659 got_path_strip_trailing_slashes(repo_path);
660 error = get_gitconfig_path(&gitconfig_path);
661 if (error)
662 goto done;
663 error = got_repo_open(&repo, repo_path, gitconfig_path);
664 if (error)
665 goto done;
667 error = get_author(&author, repo);
668 if (error)
669 return error;
671 /*
672 * Don't let the user create a branch name with a leading '-'.
673 * While technically a valid reference name, this case is usually
674 * an unintended typo.
675 */
676 if (branch_name[0] == '-')
677 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
679 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
680 error = got_error_from_errno("asprintf");
681 goto done;
684 error = got_ref_open(&branch_ref, repo, refname, 0);
685 if (error) {
686 if (error->code != GOT_ERR_NOT_REF)
687 goto done;
688 } else {
689 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
690 "import target branch already exists");
691 goto done;
694 path_dir = realpath(argv[0], NULL);
695 if (path_dir == NULL) {
696 error = got_error_from_errno2("realpath", argv[0]);
697 goto done;
699 got_path_strip_trailing_slashes(path_dir);
701 /*
702 * unveil(2) traverses exec(2); if an editor is used we have
703 * to apply unveil after the log message has been written.
704 */
705 if (logmsg == NULL || strlen(logmsg) == 0) {
706 error = get_editor(&editor);
707 if (error)
708 goto done;
709 free(logmsg);
710 error = collect_import_msg(&logmsg, &logmsg_path, editor,
711 path_dir, refname);
712 if (error) {
713 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
714 logmsg_path != NULL)
715 preserve_logmsg = 1;
716 goto done;
720 if (unveil(path_dir, "r") != 0) {
721 error = got_error_from_errno2("unveil", path_dir);
722 if (logmsg_path)
723 preserve_logmsg = 1;
724 goto done;
727 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
728 if (error) {
729 if (logmsg_path)
730 preserve_logmsg = 1;
731 goto done;
734 error = got_repo_import(&new_commit_id, path_dir, logmsg,
735 author, &ignores, repo, import_progress, NULL);
736 if (error) {
737 if (logmsg_path)
738 preserve_logmsg = 1;
739 goto done;
742 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
743 if (error) {
744 if (logmsg_path)
745 preserve_logmsg = 1;
746 goto done;
749 error = got_ref_write(branch_ref, repo);
750 if (error) {
751 if (logmsg_path)
752 preserve_logmsg = 1;
753 goto done;
756 error = got_object_id_str(&id_str, new_commit_id);
757 if (error) {
758 if (logmsg_path)
759 preserve_logmsg = 1;
760 goto done;
763 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
764 if (error) {
765 if (error->code != GOT_ERR_NOT_REF) {
766 if (logmsg_path)
767 preserve_logmsg = 1;
768 goto done;
771 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
772 branch_ref);
773 if (error) {
774 if (logmsg_path)
775 preserve_logmsg = 1;
776 goto done;
779 error = got_ref_write(head_ref, repo);
780 if (error) {
781 if (logmsg_path)
782 preserve_logmsg = 1;
783 goto done;
787 printf("Created branch %s with commit %s\n",
788 got_ref_get_name(branch_ref), id_str);
789 done:
790 if (preserve_logmsg) {
791 fprintf(stderr, "%s: log message preserved in %s\n",
792 getprogname(), logmsg_path);
793 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
794 error = got_error_from_errno2("unlink", logmsg_path);
795 free(logmsg);
796 free(logmsg_path);
797 free(repo_path);
798 free(editor);
799 free(refname);
800 free(new_commit_id);
801 free(id_str);
802 free(author);
803 free(gitconfig_path);
804 if (branch_ref)
805 got_ref_close(branch_ref);
806 if (head_ref)
807 got_ref_close(head_ref);
808 return error;
811 __dead static void
812 usage_clone(void)
814 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
815 "[-R reference] repository-url [directory]\n", getprogname());
816 exit(1);
819 struct got_fetch_progress_arg {
820 char last_scaled_size[FMT_SCALED_STRSIZE];
821 int last_p_indexed;
822 int last_p_resolved;
823 int verbosity;
824 };
826 static const struct got_error *
827 fetch_progress(void *arg, const char *message, off_t packfile_size,
828 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
830 struct got_fetch_progress_arg *a = arg;
831 char scaled_size[FMT_SCALED_STRSIZE];
832 int p_indexed, p_resolved;
833 int print_size = 0, print_indexed = 0, print_resolved = 0;
835 if (a->verbosity < 0)
836 return NULL;
838 if (message && message[0] != '\0') {
839 printf("\rserver: %s", message);
840 fflush(stdout);
841 return NULL;
844 if (packfile_size > 0 || nobj_indexed > 0) {
845 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
846 (a->last_scaled_size[0] == '\0' ||
847 strcmp(scaled_size, a->last_scaled_size)) != 0) {
848 print_size = 1;
849 if (strlcpy(a->last_scaled_size, scaled_size,
850 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
851 return got_error(GOT_ERR_NO_SPACE);
853 if (nobj_indexed > 0) {
854 p_indexed = (nobj_indexed * 100) / nobj_total;
855 if (p_indexed != a->last_p_indexed) {
856 a->last_p_indexed = p_indexed;
857 print_indexed = 1;
858 print_size = 1;
861 if (nobj_resolved > 0) {
862 p_resolved = (nobj_resolved * 100) /
863 (nobj_total - nobj_loose);
864 if (p_resolved != a->last_p_resolved) {
865 a->last_p_resolved = p_resolved;
866 print_resolved = 1;
867 print_indexed = 1;
868 print_size = 1;
873 if (print_size || print_indexed || print_resolved)
874 printf("\r");
875 if (print_size)
876 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
877 if (print_indexed)
878 printf("; indexing %d%%", p_indexed);
879 if (print_resolved)
880 printf("; resolving deltas %d%%", p_resolved);
881 if (print_size || print_indexed || print_resolved)
882 fflush(stdout);
884 return NULL;
887 static const struct got_error *
888 create_symref(const char *refname, struct got_reference *target_ref,
889 int verbosity, struct got_repository *repo)
891 const struct got_error *err;
892 struct got_reference *head_symref;
894 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
895 if (err)
896 return err;
898 err = got_ref_write(head_symref, repo);
899 got_ref_close(head_symref);
900 if (err == NULL && verbosity > 0) {
901 printf("Created reference %s: %s\n", GOT_REF_HEAD,
902 got_ref_get_name(target_ref));
904 return err;
907 static const struct got_error *
908 list_remote_refs(struct got_pathlist_head *symrefs,
909 struct got_pathlist_head *refs)
911 const struct got_error *err;
912 struct got_pathlist_entry *pe;
914 TAILQ_FOREACH(pe, symrefs, entry) {
915 const char *refname = pe->path;
916 const char *targetref = pe->data;
918 printf("%s: %s\n", refname, targetref);
921 TAILQ_FOREACH(pe, refs, entry) {
922 const char *refname = pe->path;
923 struct got_object_id *id = pe->data;
924 char *id_str;
926 err = got_object_id_str(&id_str, id);
927 if (err)
928 return err;
929 printf("%s: %s\n", refname, id_str);
930 free(id_str);
933 return NULL;
936 static const struct got_error *
937 create_ref(const char *refname, struct got_object_id *id,
938 int verbosity, struct got_repository *repo)
940 const struct got_error *err = NULL;
941 struct got_reference *ref;
942 char *id_str;
944 err = got_object_id_str(&id_str, id);
945 if (err)
946 return err;
948 err = got_ref_alloc(&ref, refname, id);
949 if (err)
950 goto done;
952 err = got_ref_write(ref, repo);
953 got_ref_close(ref);
955 if (err == NULL && verbosity >= 0)
956 printf("Created reference %s: %s\n", refname, id_str);
957 done:
958 free(id_str);
959 return err;
962 static int
963 match_wanted_ref(const char *refname, const char *wanted_ref)
965 if (strncmp(refname, "refs/", 5) != 0)
966 return 0;
967 refname += 5;
969 /*
970 * Prevent fetching of references that won't make any
971 * sense outside of the remote repository's context.
972 */
973 if (strncmp(refname, "got/", 4) == 0)
974 return 0;
975 if (strncmp(refname, "remotes/", 8) == 0)
976 return 0;
978 if (strncmp(wanted_ref, "refs/", 5) == 0)
979 wanted_ref += 5;
981 /* Allow prefix match. */
982 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
983 return 1;
985 /* Allow exact match. */
986 return (strcmp(refname, wanted_ref) == 0);
989 static int
990 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
992 struct got_pathlist_entry *pe;
994 TAILQ_FOREACH(pe, wanted_refs, entry) {
995 if (match_wanted_ref(refname, pe->path))
996 return 1;
999 return 0;
1002 static const struct got_error *
1003 create_wanted_ref(const char *refname, struct got_object_id *id,
1004 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1006 const struct got_error *err;
1007 char *remote_refname;
1009 if (strncmp("refs/", refname, 5) == 0)
1010 refname += 5;
1012 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1013 remote_repo_name, refname) == -1)
1014 return got_error_from_errno("asprintf");
1016 err = create_ref(remote_refname, id, verbosity, repo);
1017 free(remote_refname);
1018 return err;
1021 static const struct got_error *
1022 cmd_clone(int argc, char *argv[])
1024 const struct got_error *error = NULL;
1025 const char *uri, *dirname;
1026 char *proto, *host, *port, *repo_name, *server_path;
1027 char *default_destdir = NULL, *id_str = NULL;
1028 const char *repo_path;
1029 struct got_repository *repo = NULL;
1030 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1031 struct got_pathlist_entry *pe;
1032 struct got_object_id *pack_hash = NULL;
1033 int ch, fetchfd = -1, fetchstatus;
1034 pid_t fetchpid = -1;
1035 struct got_fetch_progress_arg fpa;
1036 char *git_url = NULL;
1037 char *gitconfig_path = NULL;
1038 char *gitconfig = NULL;
1039 FILE *gitconfig_file = NULL;
1040 ssize_t n;
1041 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1042 int list_refs_only = 0;
1043 struct got_reference *head_symref = NULL;
1045 TAILQ_INIT(&refs);
1046 TAILQ_INIT(&symrefs);
1047 TAILQ_INIT(&wanted_branches);
1048 TAILQ_INIT(&wanted_refs);
1050 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1051 switch (ch) {
1052 case 'a':
1053 fetch_all_branches = 1;
1054 break;
1055 case 'b':
1056 error = got_pathlist_append(&wanted_branches,
1057 optarg, NULL);
1058 if (error)
1059 return error;
1060 break;
1061 case 'l':
1062 list_refs_only = 1;
1063 break;
1064 case 'm':
1065 mirror_references = 1;
1066 break;
1067 case 'v':
1068 if (verbosity < 0)
1069 verbosity = 0;
1070 else if (verbosity < 3)
1071 verbosity++;
1072 break;
1073 case 'q':
1074 verbosity = -1;
1075 break;
1076 case 'R':
1077 error = got_pathlist_append(&wanted_refs,
1078 optarg, NULL);
1079 if (error)
1080 return error;
1081 break;
1082 default:
1083 usage_clone();
1084 break;
1087 argc -= optind;
1088 argv += optind;
1090 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1091 errx(1, "-a and -b options are mutually exclusive");
1092 if (list_refs_only) {
1093 if (!TAILQ_EMPTY(&wanted_branches))
1094 errx(1, "-l and -b options are mutually exclusive");
1095 if (fetch_all_branches)
1096 errx(1, "-l and -a options are mutually exclusive");
1097 if (mirror_references)
1098 errx(1, "-l and -m options are mutually exclusive");
1099 if (verbosity == -1)
1100 errx(1, "-l and -q options are mutually exclusive");
1101 if (!TAILQ_EMPTY(&wanted_refs))
1102 errx(1, "-l and -R options are mutually exclusive");
1105 uri = argv[0];
1107 if (argc == 1)
1108 dirname = NULL;
1109 else if (argc == 2)
1110 dirname = argv[1];
1111 else
1112 usage_clone();
1114 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1115 &repo_name, argv[0]);
1116 if (error)
1117 goto done;
1119 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1120 host, port ? ":" : "", port ? port : "",
1121 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1122 error = got_error_from_errno("asprintf");
1123 goto done;
1126 if (strcmp(proto, "git") == 0) {
1127 #ifndef PROFILE
1128 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1129 "sendfd dns inet unveil", NULL) == -1)
1130 err(1, "pledge");
1131 #endif
1132 } else if (strcmp(proto, "git+ssh") == 0 ||
1133 strcmp(proto, "ssh") == 0) {
1134 #ifndef PROFILE
1135 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1136 "sendfd unveil", NULL) == -1)
1137 err(1, "pledge");
1138 #endif
1139 } else if (strcmp(proto, "http") == 0 ||
1140 strcmp(proto, "git+http") == 0) {
1141 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1142 goto done;
1143 } else {
1144 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1145 goto done;
1147 if (dirname == NULL) {
1148 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1149 error = got_error_from_errno("asprintf");
1150 goto done;
1152 repo_path = default_destdir;
1153 } else
1154 repo_path = dirname;
1156 if (!list_refs_only) {
1157 error = got_path_mkdir(repo_path);
1158 if (error)
1159 goto done;
1161 error = got_repo_init(repo_path);
1162 if (error)
1163 goto done;
1164 error = got_repo_open(&repo, repo_path, NULL);
1165 if (error)
1166 goto done;
1169 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1170 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1171 error = got_error_from_errno2("unveil",
1172 GOT_FETCH_PATH_SSH);
1173 goto done;
1176 error = apply_unveil(repo ? got_repo_get_path(repo) : NULL, 0, NULL);
1177 if (error)
1178 goto done;
1180 if (verbosity >= 0)
1181 printf("Connecting to %s%s%s\n", host,
1182 port ? ":" : "", port ? port : "");
1184 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1185 server_path, verbosity);
1186 if (error)
1187 goto done;
1189 fpa.last_scaled_size[0] = '\0';
1190 fpa.last_p_indexed = -1;
1191 fpa.last_p_resolved = -1;
1192 fpa.verbosity = verbosity;
1193 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1194 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1195 fetch_all_branches, &wanted_branches, &wanted_refs,
1196 list_refs_only, verbosity, fetchfd, repo,
1197 fetch_progress, &fpa);
1198 if (error)
1199 goto done;
1201 if (list_refs_only) {
1202 error = list_remote_refs(&symrefs, &refs);
1203 goto done;
1206 error = got_object_id_str(&id_str, pack_hash);
1207 if (error)
1208 goto done;
1209 if (verbosity >= 0)
1210 printf("\nFetched %s.pack\n", id_str);
1211 free(id_str);
1213 /* Set up references provided with the pack file. */
1214 TAILQ_FOREACH(pe, &refs, entry) {
1215 const char *refname = pe->path;
1216 struct got_object_id *id = pe->data;
1217 char *remote_refname;
1219 if (is_wanted_ref(&wanted_refs, refname) &&
1220 !mirror_references) {
1221 error = create_wanted_ref(refname, id,
1222 GOT_FETCH_DEFAULT_REMOTE_NAME,
1223 verbosity - 1, repo);
1224 if (error)
1225 goto done;
1226 continue;
1229 error = create_ref(refname, id, verbosity - 1, repo);
1230 if (error)
1231 goto done;
1233 if (mirror_references)
1234 continue;
1236 if (strncmp("refs/heads/", refname, 11) != 0)
1237 continue;
1239 if (asprintf(&remote_refname,
1240 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1241 refname + 11) == -1) {
1242 error = got_error_from_errno("asprintf");
1243 goto done;
1245 error = create_ref(remote_refname, id, verbosity - 1, repo);
1246 free(remote_refname);
1247 if (error)
1248 goto done;
1251 /* Set the HEAD reference if the server provided one. */
1252 TAILQ_FOREACH(pe, &symrefs, entry) {
1253 struct got_reference *target_ref;
1254 const char *refname = pe->path;
1255 const char *target = pe->data;
1256 char *remote_refname = NULL, *remote_target = NULL;
1258 if (strcmp(refname, GOT_REF_HEAD) != 0)
1259 continue;
1261 error = got_ref_open(&target_ref, repo, target, 0);
1262 if (error) {
1263 if (error->code == GOT_ERR_NOT_REF) {
1264 error = NULL;
1265 continue;
1267 goto done;
1270 error = create_symref(refname, target_ref, verbosity, repo);
1271 got_ref_close(target_ref);
1272 if (error)
1273 goto done;
1275 if (mirror_references)
1276 continue;
1278 if (strncmp("refs/heads/", target, 11) != 0)
1279 continue;
1281 if (asprintf(&remote_refname,
1282 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1283 refname) == -1) {
1284 error = got_error_from_errno("asprintf");
1285 goto done;
1287 if (asprintf(&remote_target,
1288 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1289 target + 11) == -1) {
1290 error = got_error_from_errno("asprintf");
1291 free(remote_refname);
1292 goto done;
1294 error = got_ref_open(&target_ref, repo, remote_target, 0);
1295 if (error) {
1296 free(remote_refname);
1297 free(remote_target);
1298 if (error->code == GOT_ERR_NOT_REF) {
1299 error = NULL;
1300 continue;
1302 goto done;
1304 error = create_symref(remote_refname, target_ref,
1305 verbosity - 1, repo);
1306 free(remote_refname);
1307 free(remote_target);
1308 got_ref_close(target_ref);
1309 if (error)
1310 goto done;
1312 if (pe == NULL) {
1314 * We failed to set the HEAD reference. If we asked for
1315 * a set of wanted branches use the first of one of those
1316 * which could be fetched instead.
1318 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1319 const char *target = pe->path;
1320 struct got_reference *target_ref;
1322 error = got_ref_open(&target_ref, repo, target, 0);
1323 if (error) {
1324 if (error->code == GOT_ERR_NOT_REF) {
1325 error = NULL;
1326 continue;
1328 goto done;
1331 error = create_symref(GOT_REF_HEAD, target_ref,
1332 verbosity, repo);
1333 got_ref_close(target_ref);
1334 if (error)
1335 goto done;
1336 break;
1340 /* Create a config file git-fetch(1) can understand. */
1341 gitconfig_path = got_repo_get_path_gitconfig(repo);
1342 if (gitconfig_path == NULL) {
1343 error = got_error_from_errno("got_repo_get_path_gitconfig");
1344 goto done;
1346 gitconfig_file = fopen(gitconfig_path, "a");
1347 if (gitconfig_file == NULL) {
1348 error = got_error_from_errno2("fopen", gitconfig_path);
1349 goto done;
1351 if (mirror_references) {
1352 if (asprintf(&gitconfig,
1353 "[remote \"%s\"]\n"
1354 "\turl = %s\n"
1355 "\tfetch = +refs/*:refs/*\n"
1356 "\tmirror = true\n",
1357 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1358 error = got_error_from_errno("asprintf");
1359 goto done;
1361 } else if (fetch_all_branches) {
1362 if (asprintf(&gitconfig,
1363 "[remote \"%s\"]\n"
1364 "\turl = %s\n"
1365 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1366 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1367 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1368 error = got_error_from_errno("asprintf");
1369 goto done;
1371 } else {
1372 const char *branchname;
1375 * If the server specified a default branch, use just that one.
1376 * Otherwise fall back to fetching all branches on next fetch.
1378 if (head_symref) {
1379 branchname = got_ref_get_symref_target(head_symref);
1380 if (strncmp(branchname, "refs/heads/", 11) == 0)
1381 branchname += 11;
1382 } else
1383 branchname = "*"; /* fall back to all branches */
1384 if (asprintf(&gitconfig,
1385 "[remote \"%s\"]\n"
1386 "\turl = %s\n"
1387 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1388 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1389 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1390 branchname) == -1) {
1391 error = got_error_from_errno("asprintf");
1392 goto done;
1395 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1396 if (n != strlen(gitconfig)) {
1397 error = got_ferror(gitconfig_file, GOT_ERR_IO);
1398 goto done;
1401 if (verbosity >= 0)
1402 printf("Created %s repository '%s'\n",
1403 mirror_references ? "mirrored" : "cloned", repo_path);
1404 done:
1405 if (fetchpid > 0) {
1406 if (kill(fetchpid, SIGTERM) == -1)
1407 error = got_error_from_errno("kill");
1408 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1409 error = got_error_from_errno("waitpid");
1411 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1412 error = got_error_from_errno("close");
1413 if (gitconfig_file && fclose(gitconfig_file) == EOF && error == NULL)
1414 error = got_error_from_errno("fclose");
1415 if (repo)
1416 got_repo_close(repo);
1417 if (head_symref)
1418 got_ref_close(head_symref);
1419 TAILQ_FOREACH(pe, &refs, entry) {
1420 free((void *)pe->path);
1421 free(pe->data);
1423 got_pathlist_free(&refs);
1424 TAILQ_FOREACH(pe, &symrefs, entry) {
1425 free((void *)pe->path);
1426 free(pe->data);
1428 got_pathlist_free(&symrefs);
1429 got_pathlist_free(&wanted_branches);
1430 got_pathlist_free(&wanted_refs);
1431 free(pack_hash);
1432 free(proto);
1433 free(host);
1434 free(port);
1435 free(server_path);
1436 free(repo_name);
1437 free(default_destdir);
1438 free(gitconfig_path);
1439 free(git_url);
1440 return error;
1443 static const struct got_error *
1444 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1445 int replace_tags, int verbosity, struct got_repository *repo)
1447 const struct got_error *err = NULL;
1448 char *new_id_str = NULL;
1449 struct got_object_id *old_id = NULL;
1451 err = got_object_id_str(&new_id_str, new_id);
1452 if (err)
1453 goto done;
1455 if (!replace_tags &&
1456 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1457 err = got_ref_resolve(&old_id, repo, ref);
1458 if (err)
1459 goto done;
1460 if (got_object_id_cmp(old_id, new_id) == 0)
1461 goto done;
1462 if (verbosity >= 0) {
1463 printf("Rejecting update of existing tag %s: %s\n",
1464 got_ref_get_name(ref), new_id_str);
1466 goto done;
1469 if (got_ref_is_symbolic(ref)) {
1470 if (verbosity >= 0) {
1471 printf("Replacing reference %s: %s\n",
1472 got_ref_get_name(ref),
1473 got_ref_get_symref_target(ref));
1475 err = got_ref_change_symref_to_ref(ref, new_id);
1476 if (err)
1477 goto done;
1478 err = got_ref_write(ref, repo);
1479 if (err)
1480 goto done;
1481 } else {
1482 err = got_ref_resolve(&old_id, repo, ref);
1483 if (err)
1484 goto done;
1485 if (got_object_id_cmp(old_id, new_id) == 0)
1486 goto done;
1488 err = got_ref_change_ref(ref, new_id);
1489 if (err)
1490 goto done;
1491 err = got_ref_write(ref, repo);
1492 if (err)
1493 goto done;
1496 if (verbosity >= 0)
1497 printf("Updated reference %s: %s\n", got_ref_get_name(ref),
1498 new_id_str);
1499 done:
1500 free(old_id);
1501 free(new_id_str);
1502 return err;
1505 static const struct got_error *
1506 update_symref(const char *refname, struct got_reference *target_ref,
1507 int verbosity, struct got_repository *repo)
1509 const struct got_error *err = NULL, *unlock_err;
1510 struct got_reference *symref;
1511 int symref_is_locked = 0;
1513 err = got_ref_open(&symref, repo, refname, 1);
1514 if (err) {
1515 if (err->code != GOT_ERR_NOT_REF)
1516 return err;
1517 err = got_ref_alloc_symref(&symref, refname, target_ref);
1518 if (err)
1519 goto done;
1521 err = got_ref_write(symref, repo);
1522 if (err)
1523 goto done;
1525 if (verbosity >= 0)
1526 printf("Created reference %s: %s\n",
1527 got_ref_get_name(symref),
1528 got_ref_get_symref_target(symref));
1529 } else {
1530 symref_is_locked = 1;
1532 if (strcmp(got_ref_get_symref_target(symref),
1533 got_ref_get_name(target_ref)) == 0)
1534 goto done;
1536 err = got_ref_change_symref(symref,
1537 got_ref_get_name(target_ref));
1538 if (err)
1539 goto done;
1541 err = got_ref_write(symref, repo);
1542 if (err)
1543 goto done;
1545 if (verbosity >= 0)
1546 printf("Updated reference %s: %s\n",
1547 got_ref_get_name(symref),
1548 got_ref_get_symref_target(symref));
1551 done:
1552 if (symref_is_locked) {
1553 unlock_err = got_ref_unlock(symref);
1554 if (unlock_err && err == NULL)
1555 err = unlock_err;
1557 got_ref_close(symref);
1558 return err;
1561 __dead static void
1562 usage_fetch(void)
1564 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1565 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1566 "[remote-repository-name]\n",
1567 getprogname());
1568 exit(1);
1571 static const struct got_error *
1572 delete_missing_ref(struct got_reference *ref,
1573 int verbosity, struct got_repository *repo)
1575 const struct got_error *err = NULL;
1576 struct got_object_id *id = NULL;
1577 char *id_str = NULL;
1579 if (got_ref_is_symbolic(ref)) {
1580 err = got_ref_delete(ref, repo);
1581 if (err)
1582 return err;
1583 if (verbosity >= 0) {
1584 printf("Deleted reference %s: %s\n",
1585 got_ref_get_name(ref),
1586 got_ref_get_symref_target(ref));
1588 } else {
1589 err = got_ref_resolve(&id, repo, ref);
1590 if (err)
1591 return err;
1592 err = got_object_id_str(&id_str, id);
1593 if (err)
1594 goto done;
1596 err = got_ref_delete(ref, repo);
1597 if (err)
1598 goto done;
1599 if (verbosity >= 0) {
1600 printf("Deleted reference %s: %s\n",
1601 got_ref_get_name(ref), id_str);
1604 done:
1605 free(id);
1606 free(id_str);
1607 return NULL;
1610 static const struct got_error *
1611 delete_missing_refs(struct got_pathlist_head *their_refs,
1612 struct got_pathlist_head *their_symrefs, struct got_remote_repo *remote,
1613 int verbosity, struct got_repository *repo)
1615 const struct got_error *err = NULL, *unlock_err;
1616 struct got_reflist_head my_refs;
1617 struct got_reflist_entry *re;
1618 struct got_pathlist_entry *pe;
1619 char *remote_namespace = NULL;
1620 char *local_refname = NULL;
1622 SIMPLEQ_INIT(&my_refs);
1624 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
1625 == -1)
1626 return got_error_from_errno("asprintf");
1628 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1629 if (err)
1630 goto done;
1632 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1633 const char *refname = got_ref_get_name(re->ref);
1635 if (!remote->mirror_references) {
1636 if (strncmp(refname, remote_namespace,
1637 strlen(remote_namespace)) == 0) {
1638 if (strcmp(refname + strlen(remote_namespace),
1639 GOT_REF_HEAD) == 0)
1640 continue;
1641 if (asprintf(&local_refname, "refs/heads/%s",
1642 refname + strlen(remote_namespace)) == -1) {
1643 err = got_error_from_errno("asprintf");
1644 goto done;
1646 } else if (strncmp(refname, "refs/tags/", 10) != 0)
1647 continue;
1650 TAILQ_FOREACH(pe, their_refs, entry) {
1651 if (strcmp(local_refname, pe->path) == 0)
1652 break;
1654 if (pe != NULL)
1655 continue;
1657 TAILQ_FOREACH(pe, their_symrefs, entry) {
1658 if (strcmp(local_refname, pe->path) == 0)
1659 break;
1661 if (pe != NULL)
1662 continue;
1664 err = delete_missing_ref(re->ref, verbosity, repo);
1665 if (err)
1666 break;
1668 if (local_refname) {
1669 struct got_reference *ref;
1670 err = got_ref_open(&ref, repo, local_refname, 1);
1671 if (err) {
1672 if (err->code != GOT_ERR_NOT_REF)
1673 break;
1674 free(local_refname);
1675 local_refname = NULL;
1676 continue;
1678 err = delete_missing_ref(ref, verbosity, repo);
1679 if (err)
1680 break;
1681 unlock_err = got_ref_unlock(ref);
1682 got_ref_close(ref);
1683 if (unlock_err && err == NULL) {
1684 err = unlock_err;
1685 break;
1688 free(local_refname);
1689 local_refname = NULL;
1692 done:
1693 free(remote_namespace);
1694 free(local_refname);
1695 return err;
1698 static const struct got_error *
1699 update_wanted_ref(const char *refname, struct got_object_id *id,
1700 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1702 const struct got_error *err, *unlock_err;
1703 char *remote_refname;
1704 struct got_reference *ref;
1706 if (strncmp("refs/", refname, 5) == 0)
1707 refname += 5;
1709 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1710 remote_repo_name, refname) == -1)
1711 return got_error_from_errno("asprintf");
1713 err = got_ref_open(&ref, repo, remote_refname, 1);
1714 if (err) {
1715 if (err->code != GOT_ERR_NOT_REF)
1716 goto done;
1717 err = create_ref(remote_refname, id, verbosity, repo);
1718 } else {
1719 err = update_ref(ref, id, 0, verbosity, repo);
1720 unlock_err = got_ref_unlock(ref);
1721 if (unlock_err && err == NULL)
1722 err = unlock_err;
1723 got_ref_close(ref);
1725 done:
1726 free(remote_refname);
1727 return err;
1730 static const struct got_error *
1731 cmd_fetch(int argc, char *argv[])
1733 const struct got_error *error = NULL, *unlock_err;
1734 char *cwd = NULL, *repo_path = NULL;
1735 const char *remote_name;
1736 char *proto = NULL, *host = NULL, *port = NULL;
1737 char *repo_name = NULL, *server_path = NULL;
1738 struct got_remote_repo *remotes, *remote = NULL;
1739 int nremotes;
1740 char *id_str = NULL;
1741 struct got_repository *repo = NULL;
1742 struct got_worktree *worktree = NULL;
1743 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1744 struct got_pathlist_entry *pe;
1745 struct got_object_id *pack_hash = NULL;
1746 int i, ch, fetchfd = -1, fetchstatus;
1747 pid_t fetchpid = -1;
1748 struct got_fetch_progress_arg fpa;
1749 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
1750 int delete_refs = 0, replace_tags = 0;
1752 TAILQ_INIT(&refs);
1753 TAILQ_INIT(&symrefs);
1754 TAILQ_INIT(&wanted_branches);
1755 TAILQ_INIT(&wanted_refs);
1757 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
1758 switch (ch) {
1759 case 'a':
1760 fetch_all_branches = 1;
1761 break;
1762 case 'b':
1763 error = got_pathlist_append(&wanted_branches,
1764 optarg, NULL);
1765 if (error)
1766 return error;
1767 break;
1768 case 'd':
1769 delete_refs = 1;
1770 break;
1771 case 'l':
1772 list_refs_only = 1;
1773 break;
1774 case 'r':
1775 repo_path = realpath(optarg, NULL);
1776 if (repo_path == NULL)
1777 return got_error_from_errno2("realpath",
1778 optarg);
1779 got_path_strip_trailing_slashes(repo_path);
1780 break;
1781 case 't':
1782 replace_tags = 1;
1783 break;
1784 case 'v':
1785 if (verbosity < 0)
1786 verbosity = 0;
1787 else if (verbosity < 3)
1788 verbosity++;
1789 break;
1790 case 'q':
1791 verbosity = -1;
1792 break;
1793 case 'R':
1794 error = got_pathlist_append(&wanted_refs,
1795 optarg, NULL);
1796 if (error)
1797 return error;
1798 break;
1799 default:
1800 usage_fetch();
1801 break;
1804 argc -= optind;
1805 argv += optind;
1807 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1808 errx(1, "-a and -b options are mutually exclusive");
1809 if (list_refs_only) {
1810 if (!TAILQ_EMPTY(&wanted_branches))
1811 errx(1, "-l and -b options are mutually exclusive");
1812 if (fetch_all_branches)
1813 errx(1, "-l and -a options are mutually exclusive");
1814 if (delete_refs)
1815 errx(1, "-l and -d options are mutually exclusive");
1816 if (verbosity == -1)
1817 errx(1, "-l and -q options are mutually exclusive");
1820 if (argc == 0)
1821 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
1822 else if (argc == 1)
1823 remote_name = argv[0];
1824 else
1825 usage_fetch();
1827 cwd = getcwd(NULL, 0);
1828 if (cwd == NULL) {
1829 error = got_error_from_errno("getcwd");
1830 goto done;
1833 if (repo_path == NULL) {
1834 error = got_worktree_open(&worktree, cwd);
1835 if (error && error->code != GOT_ERR_NOT_WORKTREE)
1836 goto done;
1837 else
1838 error = NULL;
1839 if (worktree) {
1840 repo_path =
1841 strdup(got_worktree_get_repo_path(worktree));
1842 if (repo_path == NULL)
1843 error = got_error_from_errno("strdup");
1844 if (error)
1845 goto done;
1846 } else {
1847 repo_path = strdup(cwd);
1848 if (repo_path == NULL) {
1849 error = got_error_from_errno("strdup");
1850 goto done;
1855 error = got_repo_open(&repo, repo_path, NULL);
1856 if (error)
1857 goto done;
1859 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
1860 for (i = 0; i < nremotes; i++) {
1861 remote = &remotes[i];
1862 if (strcmp(remote->name, remote_name) == 0)
1863 break;
1865 if (i == nremotes) {
1866 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
1867 goto done;
1870 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1871 &repo_name, remote->url);
1872 if (error)
1873 goto done;
1875 if (strcmp(proto, "git") == 0) {
1876 #ifndef PROFILE
1877 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1878 "sendfd dns inet unveil", NULL) == -1)
1879 err(1, "pledge");
1880 #endif
1881 } else if (strcmp(proto, "git+ssh") == 0 ||
1882 strcmp(proto, "ssh") == 0) {
1883 #ifndef PROFILE
1884 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1885 "sendfd unveil", NULL) == -1)
1886 err(1, "pledge");
1887 #endif
1888 } else if (strcmp(proto, "http") == 0 ||
1889 strcmp(proto, "git+http") == 0) {
1890 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1891 goto done;
1892 } else {
1893 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1894 goto done;
1897 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1898 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1899 error = got_error_from_errno2("unveil",
1900 GOT_FETCH_PATH_SSH);
1901 goto done;
1904 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
1905 if (error)
1906 goto done;
1908 if (verbosity >= 0)
1909 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
1910 port ? ":" : "", port ? port : "");
1912 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1913 server_path, verbosity);
1914 if (error)
1915 goto done;
1917 fpa.last_scaled_size[0] = '\0';
1918 fpa.last_p_indexed = -1;
1919 fpa.last_p_resolved = -1;
1920 fpa.verbosity = verbosity;
1921 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
1922 remote->mirror_references, fetch_all_branches, &wanted_branches,
1923 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
1924 fetch_progress, &fpa);
1925 if (error)
1926 goto done;
1928 if (list_refs_only) {
1929 error = list_remote_refs(&symrefs, &refs);
1930 goto done;
1933 if (pack_hash == NULL) {
1934 if (verbosity >= 0)
1935 printf("Already up-to-date\n");
1936 } else if (verbosity >= 0) {
1937 error = got_object_id_str(&id_str, pack_hash);
1938 if (error)
1939 goto done;
1940 printf("\nFetched %s.pack\n", id_str);
1941 free(id_str);
1942 id_str = NULL;
1945 /* Update references provided with the pack file. */
1946 TAILQ_FOREACH(pe, &refs, entry) {
1947 const char *refname = pe->path;
1948 struct got_object_id *id = pe->data;
1949 struct got_reference *ref;
1950 char *remote_refname;
1952 if (is_wanted_ref(&wanted_refs, refname) &&
1953 !remote->mirror_references) {
1954 error = update_wanted_ref(refname, id,
1955 remote->name, verbosity, repo);
1956 if (error)
1957 goto done;
1958 continue;
1961 if (remote->mirror_references ||
1962 strncmp("refs/tags/", refname, 10) == 0) {
1963 error = got_ref_open(&ref, repo, refname, 1);
1964 if (error) {
1965 if (error->code != GOT_ERR_NOT_REF)
1966 goto done;
1967 error = create_ref(refname, id, verbosity,
1968 repo);
1969 if (error)
1970 goto done;
1971 } else {
1972 error = update_ref(ref, id, replace_tags,
1973 verbosity, repo);
1974 unlock_err = got_ref_unlock(ref);
1975 if (unlock_err && error == NULL)
1976 error = unlock_err;
1977 got_ref_close(ref);
1978 if (error)
1979 goto done;
1981 } else if (strncmp("refs/heads/", refname, 11) == 0) {
1982 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1983 remote_name, refname + 11) == -1) {
1984 error = got_error_from_errno("asprintf");
1985 goto done;
1988 error = got_ref_open(&ref, repo, remote_refname, 1);
1989 if (error) {
1990 if (error->code != GOT_ERR_NOT_REF)
1991 goto done;
1992 error = create_ref(remote_refname, id,
1993 verbosity, repo);
1994 if (error)
1995 goto done;
1996 } else {
1997 error = update_ref(ref, id, replace_tags,
1998 verbosity, repo);
1999 unlock_err = got_ref_unlock(ref);
2000 if (unlock_err && error == NULL)
2001 error = unlock_err;
2002 got_ref_close(ref);
2003 if (error)
2004 goto done;
2007 /* Also create a local branch if none exists yet. */
2008 error = got_ref_open(&ref, repo, refname, 1);
2009 if (error) {
2010 if (error->code != GOT_ERR_NOT_REF)
2011 goto done;
2012 error = create_ref(refname, id, verbosity,
2013 repo);
2014 if (error)
2015 goto done;
2016 } else {
2017 unlock_err = got_ref_unlock(ref);
2018 if (unlock_err && error == NULL)
2019 error = unlock_err;
2020 got_ref_close(ref);
2024 if (delete_refs) {
2025 error = delete_missing_refs(&refs, &symrefs, remote,
2026 verbosity, repo);
2027 if (error)
2028 goto done;
2031 if (!remote->mirror_references) {
2032 /* Update remote HEAD reference if the server provided one. */
2033 TAILQ_FOREACH(pe, &symrefs, entry) {
2034 struct got_reference *target_ref;
2035 const char *refname = pe->path;
2036 const char *target = pe->data;
2037 char *remote_refname = NULL, *remote_target = NULL;
2039 if (strcmp(refname, GOT_REF_HEAD) != 0)
2040 continue;
2042 if (strncmp("refs/heads/", target, 11) != 0)
2043 continue;
2045 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2046 remote->name, refname) == -1) {
2047 error = got_error_from_errno("asprintf");
2048 goto done;
2050 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2051 remote->name, target + 11) == -1) {
2052 error = got_error_from_errno("asprintf");
2053 free(remote_refname);
2054 goto done;
2057 error = got_ref_open(&target_ref, repo, remote_target,
2058 0);
2059 if (error) {
2060 free(remote_refname);
2061 free(remote_target);
2062 if (error->code == GOT_ERR_NOT_REF) {
2063 error = NULL;
2064 continue;
2066 goto done;
2068 error = update_symref(remote_refname, target_ref,
2069 verbosity, repo);
2070 free(remote_refname);
2071 free(remote_target);
2072 got_ref_close(target_ref);
2073 if (error)
2074 goto done;
2077 done:
2078 if (fetchpid > 0) {
2079 if (kill(fetchpid, SIGTERM) == -1)
2080 error = got_error_from_errno("kill");
2081 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2082 error = got_error_from_errno("waitpid");
2084 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2085 error = got_error_from_errno("close");
2086 if (repo)
2087 got_repo_close(repo);
2088 if (worktree)
2089 got_worktree_close(worktree);
2090 TAILQ_FOREACH(pe, &refs, entry) {
2091 free((void *)pe->path);
2092 free(pe->data);
2094 got_pathlist_free(&refs);
2095 TAILQ_FOREACH(pe, &symrefs, entry) {
2096 free((void *)pe->path);
2097 free(pe->data);
2099 got_pathlist_free(&symrefs);
2100 got_pathlist_free(&wanted_branches);
2101 got_pathlist_free(&wanted_refs);
2102 free(id_str);
2103 free(cwd);
2104 free(repo_path);
2105 free(pack_hash);
2106 free(proto);
2107 free(host);
2108 free(port);
2109 free(server_path);
2110 free(repo_name);
2111 return error;
2115 __dead static void
2116 usage_checkout(void)
2118 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2119 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2120 exit(1);
2123 static void
2124 show_worktree_base_ref_warning(void)
2126 fprintf(stderr, "%s: warning: could not create a reference "
2127 "to the work tree's base commit; the commit could be "
2128 "garbage-collected by Git; making the repository "
2129 "writable and running 'got update' will prevent this\n",
2130 getprogname());
2133 struct got_checkout_progress_arg {
2134 const char *worktree_path;
2135 int had_base_commit_ref_error;
2138 static const struct got_error *
2139 checkout_progress(void *arg, unsigned char status, const char *path)
2141 struct got_checkout_progress_arg *a = arg;
2143 /* Base commit bump happens silently. */
2144 if (status == GOT_STATUS_BUMP_BASE)
2145 return NULL;
2147 if (status == GOT_STATUS_BASE_REF_ERR) {
2148 a->had_base_commit_ref_error = 1;
2149 return NULL;
2152 while (path[0] == '/')
2153 path++;
2155 printf("%c %s/%s\n", status, a->worktree_path, path);
2156 return NULL;
2159 static const struct got_error *
2160 check_cancelled(void *arg)
2162 if (sigint_received || sigpipe_received)
2163 return got_error(GOT_ERR_CANCELLED);
2164 return NULL;
2167 static const struct got_error *
2168 check_linear_ancestry(struct got_object_id *commit_id,
2169 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2170 struct got_repository *repo)
2172 const struct got_error *err = NULL;
2173 struct got_object_id *yca_id;
2175 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2176 commit_id, base_commit_id, repo, check_cancelled, NULL);
2177 if (err)
2178 return err;
2180 if (yca_id == NULL)
2181 return got_error(GOT_ERR_ANCESTRY);
2184 * Require a straight line of history between the target commit
2185 * and the work tree's base commit.
2187 * Non-linear situations such as this require a rebase:
2189 * (commit) D F (base_commit)
2190 * \ /
2191 * C E
2192 * \ /
2193 * B (yca)
2194 * |
2195 * A
2197 * 'got update' only handles linear cases:
2198 * Update forwards in time: A (base/yca) - B - C - D (commit)
2199 * Update backwards in time: D (base) - C - B - A (commit/yca)
2201 if (allow_forwards_in_time_only) {
2202 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2203 return got_error(GOT_ERR_ANCESTRY);
2204 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2205 got_object_id_cmp(base_commit_id, yca_id) != 0)
2206 return got_error(GOT_ERR_ANCESTRY);
2208 free(yca_id);
2209 return NULL;
2212 static const struct got_error *
2213 check_same_branch(struct got_object_id *commit_id,
2214 struct got_reference *head_ref, struct got_object_id *yca_id,
2215 struct got_repository *repo)
2217 const struct got_error *err = NULL;
2218 struct got_commit_graph *graph = NULL;
2219 struct got_object_id *head_commit_id = NULL;
2220 int is_same_branch = 0;
2222 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2223 if (err)
2224 goto done;
2226 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2227 is_same_branch = 1;
2228 goto done;
2230 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2231 is_same_branch = 1;
2232 goto done;
2235 err = got_commit_graph_open(&graph, "/", 1);
2236 if (err)
2237 goto done;
2239 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2240 check_cancelled, NULL);
2241 if (err)
2242 goto done;
2244 for (;;) {
2245 struct got_object_id *id;
2246 err = got_commit_graph_iter_next(&id, graph, repo,
2247 check_cancelled, NULL);
2248 if (err) {
2249 if (err->code == GOT_ERR_ITER_COMPLETED)
2250 err = NULL;
2251 break;
2254 if (id) {
2255 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2256 break;
2257 if (got_object_id_cmp(id, commit_id) == 0) {
2258 is_same_branch = 1;
2259 break;
2263 done:
2264 if (graph)
2265 got_commit_graph_close(graph);
2266 free(head_commit_id);
2267 if (!err && !is_same_branch)
2268 err = got_error(GOT_ERR_ANCESTRY);
2269 return err;
2272 static const struct got_error *
2273 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2275 static char msg[512];
2276 const char *branch_name;
2278 if (got_ref_is_symbolic(ref))
2279 branch_name = got_ref_get_symref_target(ref);
2280 else
2281 branch_name = got_ref_get_name(ref);
2283 if (strncmp("refs/heads/", branch_name, 11) == 0)
2284 branch_name += 11;
2286 snprintf(msg, sizeof(msg),
2287 "target commit is not contained in branch '%s'; "
2288 "the branch to use must be specified with -b; "
2289 "if necessary a new branch can be created for "
2290 "this commit with 'got branch -c %s BRANCH_NAME'",
2291 branch_name, commit_id_str);
2293 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2296 static const struct got_error *
2297 cmd_checkout(int argc, char *argv[])
2299 const struct got_error *error = NULL;
2300 struct got_repository *repo = NULL;
2301 struct got_reference *head_ref = NULL;
2302 struct got_worktree *worktree = NULL;
2303 char *repo_path = NULL;
2304 char *worktree_path = NULL;
2305 const char *path_prefix = "";
2306 const char *branch_name = GOT_REF_HEAD;
2307 char *commit_id_str = NULL;
2308 int ch, same_path_prefix, allow_nonempty = 0;
2309 struct got_pathlist_head paths;
2310 struct got_checkout_progress_arg cpa;
2312 TAILQ_INIT(&paths);
2314 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2315 switch (ch) {
2316 case 'b':
2317 branch_name = optarg;
2318 break;
2319 case 'c':
2320 commit_id_str = strdup(optarg);
2321 if (commit_id_str == NULL)
2322 return got_error_from_errno("strdup");
2323 break;
2324 case 'E':
2325 allow_nonempty = 1;
2326 break;
2327 case 'p':
2328 path_prefix = optarg;
2329 break;
2330 default:
2331 usage_checkout();
2332 /* NOTREACHED */
2336 argc -= optind;
2337 argv += optind;
2339 #ifndef PROFILE
2340 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2341 "unveil", NULL) == -1)
2342 err(1, "pledge");
2343 #endif
2344 if (argc == 1) {
2345 char *cwd, *base, *dotgit;
2346 repo_path = realpath(argv[0], NULL);
2347 if (repo_path == NULL)
2348 return got_error_from_errno2("realpath", argv[0]);
2349 cwd = getcwd(NULL, 0);
2350 if (cwd == NULL) {
2351 error = got_error_from_errno("getcwd");
2352 goto done;
2354 if (path_prefix[0]) {
2355 base = basename(path_prefix);
2356 if (base == NULL) {
2357 error = got_error_from_errno2("basename",
2358 path_prefix);
2359 goto done;
2361 } else {
2362 base = basename(repo_path);
2363 if (base == NULL) {
2364 error = got_error_from_errno2("basename",
2365 repo_path);
2366 goto done;
2369 dotgit = strstr(base, ".git");
2370 if (dotgit)
2371 *dotgit = '\0';
2372 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2373 error = got_error_from_errno("asprintf");
2374 free(cwd);
2375 goto done;
2377 free(cwd);
2378 } else if (argc == 2) {
2379 repo_path = realpath(argv[0], NULL);
2380 if (repo_path == NULL) {
2381 error = got_error_from_errno2("realpath", argv[0]);
2382 goto done;
2384 worktree_path = realpath(argv[1], NULL);
2385 if (worktree_path == NULL) {
2386 if (errno != ENOENT) {
2387 error = got_error_from_errno2("realpath",
2388 argv[1]);
2389 goto done;
2391 worktree_path = strdup(argv[1]);
2392 if (worktree_path == NULL) {
2393 error = got_error_from_errno("strdup");
2394 goto done;
2397 } else
2398 usage_checkout();
2400 got_path_strip_trailing_slashes(repo_path);
2401 got_path_strip_trailing_slashes(worktree_path);
2403 error = got_repo_open(&repo, repo_path, NULL);
2404 if (error != NULL)
2405 goto done;
2407 /* Pre-create work tree path for unveil(2) */
2408 error = got_path_mkdir(worktree_path);
2409 if (error) {
2410 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2411 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2412 goto done;
2413 if (!allow_nonempty &&
2414 !got_path_dir_is_empty(worktree_path)) {
2415 error = got_error_path(worktree_path,
2416 GOT_ERR_DIR_NOT_EMPTY);
2417 goto done;
2421 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2422 if (error)
2423 goto done;
2425 error = got_ref_open(&head_ref, repo, branch_name, 0);
2426 if (error != NULL)
2427 goto done;
2429 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2430 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2431 goto done;
2433 error = got_worktree_open(&worktree, worktree_path);
2434 if (error != NULL)
2435 goto done;
2437 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2438 path_prefix);
2439 if (error != NULL)
2440 goto done;
2441 if (!same_path_prefix) {
2442 error = got_error(GOT_ERR_PATH_PREFIX);
2443 goto done;
2446 if (commit_id_str) {
2447 struct got_object_id *commit_id;
2448 error = got_repo_match_object_id(&commit_id, NULL,
2449 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2450 if (error)
2451 goto done;
2452 error = check_linear_ancestry(commit_id,
2453 got_worktree_get_base_commit_id(worktree), 0, repo);
2454 if (error != NULL) {
2455 free(commit_id);
2456 if (error->code == GOT_ERR_ANCESTRY) {
2457 error = checkout_ancestry_error(
2458 head_ref, commit_id_str);
2460 goto done;
2462 error = check_same_branch(commit_id, head_ref, NULL, repo);
2463 if (error) {
2464 if (error->code == GOT_ERR_ANCESTRY) {
2465 error = checkout_ancestry_error(
2466 head_ref, commit_id_str);
2468 goto done;
2470 error = got_worktree_set_base_commit_id(worktree, repo,
2471 commit_id);
2472 free(commit_id);
2473 if (error)
2474 goto done;
2477 error = got_pathlist_append(&paths, "", NULL);
2478 if (error)
2479 goto done;
2480 cpa.worktree_path = worktree_path;
2481 cpa.had_base_commit_ref_error = 0;
2482 error = got_worktree_checkout_files(worktree, &paths, repo,
2483 checkout_progress, &cpa, check_cancelled, NULL);
2484 if (error != NULL)
2485 goto done;
2487 printf("Now shut up and hack\n");
2488 if (cpa.had_base_commit_ref_error)
2489 show_worktree_base_ref_warning();
2490 done:
2491 got_pathlist_free(&paths);
2492 free(commit_id_str);
2493 free(repo_path);
2494 free(worktree_path);
2495 return error;
2498 struct got_update_progress_arg {
2499 int did_something;
2500 int conflicts;
2501 int obstructed;
2502 int not_updated;
2505 void
2506 print_update_progress_stats(struct got_update_progress_arg *upa)
2508 if (!upa->did_something)
2509 return;
2511 if (upa->conflicts > 0)
2512 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2513 if (upa->obstructed > 0)
2514 printf("File paths obstructed by a non-regular file: %d\n",
2515 upa->obstructed);
2516 if (upa->not_updated > 0)
2517 printf("Files not updated because of existing merge "
2518 "conflicts: %d\n", upa->not_updated);
2521 __dead static void
2522 usage_update(void)
2524 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2525 getprogname());
2526 exit(1);
2529 static const struct got_error *
2530 update_progress(void *arg, unsigned char status, const char *path)
2532 struct got_update_progress_arg *upa = arg;
2534 if (status == GOT_STATUS_EXISTS ||
2535 status == GOT_STATUS_BASE_REF_ERR)
2536 return NULL;
2538 upa->did_something = 1;
2540 /* Base commit bump happens silently. */
2541 if (status == GOT_STATUS_BUMP_BASE)
2542 return NULL;
2544 if (status == GOT_STATUS_CONFLICT)
2545 upa->conflicts++;
2546 if (status == GOT_STATUS_OBSTRUCTED)
2547 upa->obstructed++;
2548 if (status == GOT_STATUS_CANNOT_UPDATE)
2549 upa->not_updated++;
2551 while (path[0] == '/')
2552 path++;
2553 printf("%c %s\n", status, path);
2554 return NULL;
2557 static const struct got_error *
2558 switch_head_ref(struct got_reference *head_ref,
2559 struct got_object_id *commit_id, struct got_worktree *worktree,
2560 struct got_repository *repo)
2562 const struct got_error *err = NULL;
2563 char *base_id_str;
2564 int ref_has_moved = 0;
2566 /* Trivial case: switching between two different references. */
2567 if (strcmp(got_ref_get_name(head_ref),
2568 got_worktree_get_head_ref_name(worktree)) != 0) {
2569 printf("Switching work tree from %s to %s\n",
2570 got_worktree_get_head_ref_name(worktree),
2571 got_ref_get_name(head_ref));
2572 return got_worktree_set_head_ref(worktree, head_ref);
2575 err = check_linear_ancestry(commit_id,
2576 got_worktree_get_base_commit_id(worktree), 0, repo);
2577 if (err) {
2578 if (err->code != GOT_ERR_ANCESTRY)
2579 return err;
2580 ref_has_moved = 1;
2582 if (!ref_has_moved)
2583 return NULL;
2585 /* Switching to a rebased branch with the same reference name. */
2586 err = got_object_id_str(&base_id_str,
2587 got_worktree_get_base_commit_id(worktree));
2588 if (err)
2589 return err;
2590 printf("Reference %s now points at a different branch\n",
2591 got_worktree_get_head_ref_name(worktree));
2592 printf("Switching work tree from %s to %s\n", base_id_str,
2593 got_worktree_get_head_ref_name(worktree));
2594 return NULL;
2597 static const struct got_error *
2598 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2600 const struct got_error *err;
2601 int in_progress;
2603 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2604 if (err)
2605 return err;
2606 if (in_progress)
2607 return got_error(GOT_ERR_REBASING);
2609 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2610 if (err)
2611 return err;
2612 if (in_progress)
2613 return got_error(GOT_ERR_HISTEDIT_BUSY);
2615 return NULL;
2618 static const struct got_error *
2619 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2620 char *argv[], struct got_worktree *worktree)
2622 const struct got_error *err = NULL;
2623 char *path;
2624 int i;
2626 if (argc == 0) {
2627 path = strdup("");
2628 if (path == NULL)
2629 return got_error_from_errno("strdup");
2630 return got_pathlist_append(paths, path, NULL);
2633 for (i = 0; i < argc; i++) {
2634 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2635 if (err)
2636 break;
2637 err = got_pathlist_append(paths, path, NULL);
2638 if (err) {
2639 free(path);
2640 break;
2644 return err;
2647 static const struct got_error *
2648 wrap_not_worktree_error(const struct got_error *orig_err,
2649 const char *cmdname, const char *path)
2651 const struct got_error *err;
2652 struct got_repository *repo;
2653 static char msg[512];
2655 err = got_repo_open(&repo, path, NULL);
2656 if (err)
2657 return orig_err;
2659 snprintf(msg, sizeof(msg),
2660 "'got %s' needs a work tree in addition to a git repository\n"
2661 "Work trees can be checked out from this Git repository with "
2662 "'got checkout'.\n"
2663 "The got(1) manual page contains more information.", cmdname);
2664 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2665 got_repo_close(repo);
2666 return err;
2669 static const struct got_error *
2670 cmd_update(int argc, char *argv[])
2672 const struct got_error *error = NULL;
2673 struct got_repository *repo = NULL;
2674 struct got_worktree *worktree = NULL;
2675 char *worktree_path = NULL;
2676 struct got_object_id *commit_id = NULL;
2677 char *commit_id_str = NULL;
2678 const char *branch_name = NULL;
2679 struct got_reference *head_ref = NULL;
2680 struct got_pathlist_head paths;
2681 struct got_pathlist_entry *pe;
2682 int ch;
2683 struct got_update_progress_arg upa;
2685 TAILQ_INIT(&paths);
2687 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2688 switch (ch) {
2689 case 'b':
2690 branch_name = optarg;
2691 break;
2692 case 'c':
2693 commit_id_str = strdup(optarg);
2694 if (commit_id_str == NULL)
2695 return got_error_from_errno("strdup");
2696 break;
2697 default:
2698 usage_update();
2699 /* NOTREACHED */
2703 argc -= optind;
2704 argv += optind;
2706 #ifndef PROFILE
2707 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2708 "unveil", NULL) == -1)
2709 err(1, "pledge");
2710 #endif
2711 worktree_path = getcwd(NULL, 0);
2712 if (worktree_path == NULL) {
2713 error = got_error_from_errno("getcwd");
2714 goto done;
2716 error = got_worktree_open(&worktree, worktree_path);
2717 if (error) {
2718 if (error->code == GOT_ERR_NOT_WORKTREE)
2719 error = wrap_not_worktree_error(error, "update",
2720 worktree_path);
2721 goto done;
2724 error = check_rebase_or_histedit_in_progress(worktree);
2725 if (error)
2726 goto done;
2728 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
2729 NULL);
2730 if (error != NULL)
2731 goto done;
2733 error = apply_unveil(got_repo_get_path(repo), 0,
2734 got_worktree_get_root_path(worktree));
2735 if (error)
2736 goto done;
2738 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2739 if (error)
2740 goto done;
2742 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
2743 got_worktree_get_head_ref_name(worktree), 0);
2744 if (error != NULL)
2745 goto done;
2746 if (commit_id_str == NULL) {
2747 error = got_ref_resolve(&commit_id, repo, head_ref);
2748 if (error != NULL)
2749 goto done;
2750 error = got_object_id_str(&commit_id_str, commit_id);
2751 if (error != NULL)
2752 goto done;
2753 } else {
2754 error = got_repo_match_object_id(&commit_id, NULL,
2755 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2756 free(commit_id_str);
2757 commit_id_str = NULL;
2758 if (error)
2759 goto done;
2760 error = got_object_id_str(&commit_id_str, commit_id);
2761 if (error)
2762 goto done;
2765 if (branch_name) {
2766 struct got_object_id *head_commit_id;
2767 TAILQ_FOREACH(pe, &paths, entry) {
2768 if (pe->path_len == 0)
2769 continue;
2770 error = got_error_msg(GOT_ERR_BAD_PATH,
2771 "switching between branches requires that "
2772 "the entire work tree gets updated");
2773 goto done;
2775 error = got_ref_resolve(&head_commit_id, repo, head_ref);
2776 if (error)
2777 goto done;
2778 error = check_linear_ancestry(commit_id, head_commit_id, 0,
2779 repo);
2780 free(head_commit_id);
2781 if (error != NULL)
2782 goto done;
2783 error = check_same_branch(commit_id, head_ref, NULL, repo);
2784 if (error)
2785 goto done;
2786 error = switch_head_ref(head_ref, commit_id, worktree, repo);
2787 if (error)
2788 goto done;
2789 } else {
2790 error = check_linear_ancestry(commit_id,
2791 got_worktree_get_base_commit_id(worktree), 0, repo);
2792 if (error != NULL) {
2793 if (error->code == GOT_ERR_ANCESTRY)
2794 error = got_error(GOT_ERR_BRANCH_MOVED);
2795 goto done;
2797 error = check_same_branch(commit_id, head_ref, NULL, repo);
2798 if (error)
2799 goto done;
2802 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
2803 commit_id) != 0) {
2804 error = got_worktree_set_base_commit_id(worktree, repo,
2805 commit_id);
2806 if (error)
2807 goto done;
2810 memset(&upa, 0, sizeof(upa));
2811 error = got_worktree_checkout_files(worktree, &paths, repo,
2812 update_progress, &upa, check_cancelled, NULL);
2813 if (error != NULL)
2814 goto done;
2816 if (upa.did_something)
2817 printf("Updated to commit %s\n", commit_id_str);
2818 else
2819 printf("Already up-to-date\n");
2820 print_update_progress_stats(&upa);
2821 done:
2822 free(worktree_path);
2823 TAILQ_FOREACH(pe, &paths, entry)
2824 free((char *)pe->path);
2825 got_pathlist_free(&paths);
2826 free(commit_id);
2827 free(commit_id_str);
2828 return error;
2831 static const struct got_error *
2832 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
2833 const char *path, int diff_context, int ignore_whitespace,
2834 struct got_repository *repo)
2836 const struct got_error *err = NULL;
2837 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
2839 if (blob_id1) {
2840 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
2841 if (err)
2842 goto done;
2845 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
2846 if (err)
2847 goto done;
2849 while (path[0] == '/')
2850 path++;
2851 err = got_diff_blob(blob1, blob2, path, path, diff_context,
2852 ignore_whitespace, stdout);
2853 done:
2854 if (blob1)
2855 got_object_blob_close(blob1);
2856 got_object_blob_close(blob2);
2857 return err;
2860 static const struct got_error *
2861 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
2862 const char *path, int diff_context, int ignore_whitespace,
2863 struct got_repository *repo)
2865 const struct got_error *err = NULL;
2866 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
2867 struct got_diff_blob_output_unidiff_arg arg;
2869 if (tree_id1) {
2870 err = got_object_open_as_tree(&tree1, repo, tree_id1);
2871 if (err)
2872 goto done;
2875 err = got_object_open_as_tree(&tree2, repo, tree_id2);
2876 if (err)
2877 goto done;
2879 arg.diff_context = diff_context;
2880 arg.ignore_whitespace = ignore_whitespace;
2881 arg.outfile = stdout;
2882 while (path[0] == '/')
2883 path++;
2884 err = got_diff_tree(tree1, tree2, path, path, repo,
2885 got_diff_blob_output_unidiff, &arg, 1);
2886 done:
2887 if (tree1)
2888 got_object_tree_close(tree1);
2889 if (tree2)
2890 got_object_tree_close(tree2);
2891 return err;
2894 static const struct got_error *
2895 get_changed_paths(struct got_pathlist_head *paths,
2896 struct got_commit_object *commit, struct got_repository *repo)
2898 const struct got_error *err = NULL;
2899 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
2900 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
2901 struct got_object_qid *qid;
2903 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
2904 if (qid != NULL) {
2905 struct got_commit_object *pcommit;
2906 err = got_object_open_as_commit(&pcommit, repo,
2907 qid->id);
2908 if (err)
2909 return err;
2911 tree_id1 = got_object_commit_get_tree_id(pcommit);
2912 got_object_commit_close(pcommit);
2916 if (tree_id1) {
2917 err = got_object_open_as_tree(&tree1, repo, tree_id1);
2918 if (err)
2919 goto done;
2922 tree_id2 = got_object_commit_get_tree_id(commit);
2923 err = got_object_open_as_tree(&tree2, repo, tree_id2);
2924 if (err)
2925 goto done;
2927 err = got_diff_tree(tree1, tree2, "", "", repo,
2928 got_diff_tree_collect_changed_paths, paths, 0);
2929 done:
2930 if (tree1)
2931 got_object_tree_close(tree1);
2932 if (tree2)
2933 got_object_tree_close(tree2);
2934 return err;
2937 static const struct got_error *
2938 print_patch(struct got_commit_object *commit, struct got_object_id *id,
2939 const char *path, int diff_context, struct got_repository *repo)
2941 const struct got_error *err = NULL;
2942 struct got_commit_object *pcommit = NULL;
2943 char *id_str1 = NULL, *id_str2 = NULL;
2944 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
2945 struct got_object_qid *qid;
2947 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
2948 if (qid != NULL) {
2949 err = got_object_open_as_commit(&pcommit, repo,
2950 qid->id);
2951 if (err)
2952 return err;
2955 if (path && path[0] != '\0') {
2956 int obj_type;
2957 err = got_object_id_by_path(&obj_id2, repo, id, path);
2958 if (err)
2959 goto done;
2960 err = got_object_id_str(&id_str2, obj_id2);
2961 if (err) {
2962 free(obj_id2);
2963 goto done;
2965 if (pcommit) {
2966 err = got_object_id_by_path(&obj_id1, repo,
2967 qid->id, path);
2968 if (err) {
2969 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
2970 free(obj_id2);
2971 goto done;
2973 } else {
2974 err = got_object_id_str(&id_str1, obj_id1);
2975 if (err) {
2976 free(obj_id2);
2977 goto done;
2981 err = got_object_get_type(&obj_type, repo, obj_id2);
2982 if (err) {
2983 free(obj_id2);
2984 goto done;
2986 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2987 switch (obj_type) {
2988 case GOT_OBJ_TYPE_BLOB:
2989 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
2990 0, repo);
2991 break;
2992 case GOT_OBJ_TYPE_TREE:
2993 err = diff_trees(obj_id1, obj_id2, path, diff_context,
2994 0, repo);
2995 break;
2996 default:
2997 err = got_error(GOT_ERR_OBJ_TYPE);
2998 break;
3000 free(obj_id1);
3001 free(obj_id2);
3002 } else {
3003 obj_id2 = got_object_commit_get_tree_id(commit);
3004 err = got_object_id_str(&id_str2, obj_id2);
3005 if (err)
3006 goto done;
3007 obj_id1 = got_object_commit_get_tree_id(pcommit);
3008 err = got_object_id_str(&id_str1, obj_id1);
3009 if (err)
3010 goto done;
3011 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3012 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
3014 done:
3015 free(id_str1);
3016 free(id_str2);
3017 if (pcommit)
3018 got_object_commit_close(pcommit);
3019 return err;
3022 static char *
3023 get_datestr(time_t *time, char *datebuf)
3025 struct tm mytm, *tm;
3026 char *p, *s;
3028 tm = gmtime_r(time, &mytm);
3029 if (tm == NULL)
3030 return NULL;
3031 s = asctime_r(tm, datebuf);
3032 if (s == NULL)
3033 return NULL;
3034 p = strchr(s, '\n');
3035 if (p)
3036 *p = '\0';
3037 return s;
3040 static const struct got_error *
3041 match_logmsg(int *have_match, struct got_object_id *id,
3042 struct got_commit_object *commit, regex_t *regex)
3044 const struct got_error *err = NULL;
3045 regmatch_t regmatch;
3046 char *id_str = NULL, *logmsg = NULL;
3048 *have_match = 0;
3050 err = got_object_id_str(&id_str, id);
3051 if (err)
3052 return err;
3054 err = got_object_commit_get_logmsg(&logmsg, commit);
3055 if (err)
3056 goto done;
3058 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3059 *have_match = 1;
3060 done:
3061 free(id_str);
3062 free(logmsg);
3063 return err;
3066 static void
3067 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3068 regex_t *regex)
3070 regmatch_t regmatch;
3071 struct got_pathlist_entry *pe;
3073 *have_match = 0;
3075 TAILQ_FOREACH(pe, changed_paths, entry) {
3076 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3077 *have_match = 1;
3078 break;
3083 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3085 static const struct got_error *
3086 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3087 struct got_repository *repo, const char *path,
3088 struct got_pathlist_head *changed_paths, int show_patch,
3089 int diff_context, struct got_reflist_head *refs)
3091 const struct got_error *err = NULL;
3092 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3093 char datebuf[26];
3094 time_t committer_time;
3095 const char *author, *committer;
3096 char *refs_str = NULL;
3097 struct got_reflist_entry *re;
3099 SIMPLEQ_FOREACH(re, refs, entry) {
3100 char *s;
3101 const char *name;
3102 struct got_tag_object *tag = NULL;
3103 int cmp;
3105 name = got_ref_get_name(re->ref);
3106 if (strcmp(name, GOT_REF_HEAD) == 0)
3107 continue;
3108 if (strncmp(name, "refs/", 5) == 0)
3109 name += 5;
3110 if (strncmp(name, "got/", 4) == 0)
3111 continue;
3112 if (strncmp(name, "heads/", 6) == 0)
3113 name += 6;
3114 if (strncmp(name, "remotes/", 8) == 0) {
3115 name += 8;
3116 s = strstr(name, "/" GOT_REF_HEAD);
3117 if (s != NULL && s[strlen(s)] == '\0')
3118 continue;
3120 if (strncmp(name, "tags/", 5) == 0) {
3121 err = got_object_open_as_tag(&tag, repo, re->id);
3122 if (err) {
3123 if (err->code != GOT_ERR_OBJ_TYPE)
3124 return err;
3125 /* Ref points at something other than a tag. */
3126 err = NULL;
3127 tag = NULL;
3130 cmp = got_object_id_cmp(tag ?
3131 got_object_tag_get_object_id(tag) : re->id, id);
3132 if (tag)
3133 got_object_tag_close(tag);
3134 if (cmp != 0)
3135 continue;
3136 s = refs_str;
3137 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3138 name) == -1) {
3139 err = got_error_from_errno("asprintf");
3140 free(s);
3141 return err;
3143 free(s);
3145 err = got_object_id_str(&id_str, id);
3146 if (err)
3147 return err;
3149 printf(GOT_COMMIT_SEP_STR);
3150 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3151 refs_str ? refs_str : "", refs_str ? ")" : "");
3152 free(id_str);
3153 id_str = NULL;
3154 free(refs_str);
3155 refs_str = NULL;
3156 printf("from: %s\n", got_object_commit_get_author(commit));
3157 committer_time = got_object_commit_get_committer_time(commit);
3158 datestr = get_datestr(&committer_time, datebuf);
3159 if (datestr)
3160 printf("date: %s UTC\n", datestr);
3161 author = got_object_commit_get_author(commit);
3162 committer = got_object_commit_get_committer(commit);
3163 if (strcmp(author, committer) != 0)
3164 printf("via: %s\n", committer);
3165 if (got_object_commit_get_nparents(commit) > 1) {
3166 const struct got_object_id_queue *parent_ids;
3167 struct got_object_qid *qid;
3168 int n = 1;
3169 parent_ids = got_object_commit_get_parent_ids(commit);
3170 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3171 err = got_object_id_str(&id_str, qid->id);
3172 if (err)
3173 return err;
3174 printf("parent %d: %s\n", n++, id_str);
3175 free(id_str);
3179 err = got_object_commit_get_logmsg(&logmsg0, commit);
3180 if (err)
3181 return err;
3183 logmsg = logmsg0;
3184 do {
3185 line = strsep(&logmsg, "\n");
3186 if (line)
3187 printf(" %s\n", line);
3188 } while (line);
3189 free(logmsg0);
3191 if (changed_paths) {
3192 struct got_pathlist_entry *pe;
3193 TAILQ_FOREACH(pe, changed_paths, entry) {
3194 struct got_diff_changed_path *cp = pe->data;
3195 printf(" %c %s\n", cp->status, pe->path);
3197 printf("\n");
3199 if (show_patch) {
3200 err = print_patch(commit, id, path, diff_context, repo);
3201 if (err == 0)
3202 printf("\n");
3205 if (fflush(stdout) != 0 && err == NULL)
3206 err = got_error_from_errno("fflush");
3207 return err;
3210 static const struct got_error *
3211 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3212 struct got_repository *repo, const char *path, int show_changed_paths,
3213 int show_patch, const char *search_pattern, int diff_context, int limit,
3214 int log_branches, int reverse_display_order, struct got_reflist_head *refs)
3216 const struct got_error *err;
3217 struct got_commit_graph *graph;
3218 regex_t regex;
3219 int have_match;
3220 struct got_object_id_queue reversed_commits;
3221 struct got_object_qid *qid;
3222 struct got_commit_object *commit;
3223 struct got_pathlist_head changed_paths;
3224 struct got_pathlist_entry *pe;
3226 SIMPLEQ_INIT(&reversed_commits);
3227 TAILQ_INIT(&changed_paths);
3229 if (search_pattern && regcomp(&regex, search_pattern,
3230 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3231 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3233 err = got_commit_graph_open(&graph, path, !log_branches);
3234 if (err)
3235 return err;
3236 err = got_commit_graph_iter_start(graph, root_id, repo,
3237 check_cancelled, NULL);
3238 if (err)
3239 goto done;
3240 for (;;) {
3241 struct got_object_id *id;
3243 if (sigint_received || sigpipe_received)
3244 break;
3246 err = got_commit_graph_iter_next(&id, graph, repo,
3247 check_cancelled, NULL);
3248 if (err) {
3249 if (err->code == GOT_ERR_ITER_COMPLETED)
3250 err = NULL;
3251 break;
3253 if (id == NULL)
3254 break;
3256 err = got_object_open_as_commit(&commit, repo, id);
3257 if (err)
3258 break;
3260 if (show_changed_paths) {
3261 err = get_changed_paths(&changed_paths, commit, repo);
3262 if (err)
3263 break;
3266 if (search_pattern) {
3267 err = match_logmsg(&have_match, id, commit, &regex);
3268 if (err) {
3269 got_object_commit_close(commit);
3270 break;
3272 if (have_match == 0 && show_changed_paths)
3273 match_changed_paths(&have_match,
3274 &changed_paths, &regex);
3275 if (have_match == 0) {
3276 got_object_commit_close(commit);
3277 TAILQ_FOREACH(pe, &changed_paths, entry) {
3278 free((char *)pe->path);
3279 free(pe->data);
3281 got_pathlist_free(&changed_paths);
3282 continue;
3286 if (reverse_display_order) {
3287 err = got_object_qid_alloc(&qid, id);
3288 if (err)
3289 break;
3290 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3291 got_object_commit_close(commit);
3292 } else {
3293 err = print_commit(commit, id, repo, path,
3294 show_changed_paths ? &changed_paths : NULL,
3295 show_patch, diff_context, refs);
3296 got_object_commit_close(commit);
3297 if (err)
3298 break;
3300 if ((limit && --limit == 0) ||
3301 (end_id && got_object_id_cmp(id, end_id) == 0))
3302 break;
3304 TAILQ_FOREACH(pe, &changed_paths, entry) {
3305 free((char *)pe->path);
3306 free(pe->data);
3308 got_pathlist_free(&changed_paths);
3310 if (reverse_display_order) {
3311 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3312 err = got_object_open_as_commit(&commit, repo, qid->id);
3313 if (err)
3314 break;
3315 err = print_commit(commit, qid->id, repo, path,
3316 show_changed_paths ? &changed_paths : NULL,
3317 show_patch, diff_context, refs);
3318 got_object_commit_close(commit);
3319 if (err)
3320 break;
3323 done:
3324 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3325 qid = SIMPLEQ_FIRST(&reversed_commits);
3326 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3327 got_object_qid_free(qid);
3329 TAILQ_FOREACH(pe, &changed_paths, entry) {
3330 free((char *)pe->path);
3331 free(pe->data);
3333 got_pathlist_free(&changed_paths);
3334 if (search_pattern)
3335 regfree(&regex);
3336 got_commit_graph_close(graph);
3337 return err;
3340 __dead static void
3341 usage_log(void)
3343 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3344 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3345 "[-R] [path]\n", getprogname());
3346 exit(1);
3349 static int
3350 get_default_log_limit(void)
3352 const char *got_default_log_limit;
3353 long long n;
3354 const char *errstr;
3356 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3357 if (got_default_log_limit == NULL)
3358 return 0;
3359 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3360 if (errstr != NULL)
3361 return 0;
3362 return n;
3365 static const struct got_error *
3366 resolve_commit_arg(struct got_object_id **id, const char *commit_arg,
3367 struct got_repository *repo)
3369 const struct got_error *err = NULL;
3370 struct got_reference *ref;
3372 *id = NULL;
3374 err = got_ref_open(&ref, repo, commit_arg, 0);
3375 if (err == NULL) {
3376 int obj_type;
3377 err = got_ref_resolve(id, repo, ref);
3378 got_ref_close(ref);
3379 if (err)
3380 return err;
3381 err = got_object_get_type(&obj_type, repo, *id);
3382 if (err)
3383 return err;
3384 if (obj_type == GOT_OBJ_TYPE_TAG) {
3385 struct got_tag_object *tag;
3386 err = got_object_open_as_tag(&tag, repo, *id);
3387 if (err)
3388 return err;
3389 if (got_object_tag_get_object_type(tag) !=
3390 GOT_OBJ_TYPE_COMMIT) {
3391 got_object_tag_close(tag);
3392 return got_error(GOT_ERR_OBJ_TYPE);
3394 free(*id);
3395 *id = got_object_id_dup(
3396 got_object_tag_get_object_id(tag));
3397 if (*id == NULL)
3398 err = got_error_from_errno(
3399 "got_object_id_dup");
3400 got_object_tag_close(tag);
3401 if (err)
3402 return err;
3403 } else if (obj_type != GOT_OBJ_TYPE_COMMIT)
3404 return got_error(GOT_ERR_OBJ_TYPE);
3405 } else {
3406 err = got_repo_match_object_id_prefix(id, commit_arg,
3407 GOT_OBJ_TYPE_COMMIT, repo);
3410 return err;
3413 static const struct got_error *
3414 cmd_log(int argc, char *argv[])
3416 const struct got_error *error;
3417 struct got_repository *repo = NULL;
3418 struct got_worktree *worktree = NULL;
3419 struct got_object_id *start_id = NULL, *end_id = NULL;
3420 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3421 const char *start_commit = NULL, *end_commit = NULL;
3422 const char *search_pattern = NULL;
3423 int diff_context = -1, ch;
3424 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3425 int reverse_display_order = 0;
3426 const char *errstr;
3427 struct got_reflist_head refs;
3429 SIMPLEQ_INIT(&refs);
3431 #ifndef PROFILE
3432 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3433 NULL)
3434 == -1)
3435 err(1, "pledge");
3436 #endif
3438 limit = get_default_log_limit();
3440 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3441 switch (ch) {
3442 case 'p':
3443 show_patch = 1;
3444 break;
3445 case 'P':
3446 show_changed_paths = 1;
3447 break;
3448 case 'c':
3449 start_commit = optarg;
3450 break;
3451 case 'C':
3452 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3453 &errstr);
3454 if (errstr != NULL)
3455 err(1, "-C option %s", errstr);
3456 break;
3457 case 'l':
3458 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3459 if (errstr != NULL)
3460 err(1, "-l option %s", errstr);
3461 break;
3462 case 'b':
3463 log_branches = 1;
3464 break;
3465 case 'r':
3466 repo_path = realpath(optarg, NULL);
3467 if (repo_path == NULL)
3468 return got_error_from_errno2("realpath",
3469 optarg);
3470 got_path_strip_trailing_slashes(repo_path);
3471 break;
3472 case 'R':
3473 reverse_display_order = 1;
3474 break;
3475 case 's':
3476 search_pattern = optarg;
3477 break;
3478 case 'x':
3479 end_commit = optarg;
3480 break;
3481 default:
3482 usage_log();
3483 /* NOTREACHED */
3487 argc -= optind;
3488 argv += optind;
3490 if (diff_context == -1)
3491 diff_context = 3;
3492 else if (!show_patch)
3493 errx(1, "-C reguires -p");
3495 cwd = getcwd(NULL, 0);
3496 if (cwd == NULL) {
3497 error = got_error_from_errno("getcwd");
3498 goto done;
3501 if (repo_path == NULL) {
3502 error = got_worktree_open(&worktree, cwd);
3503 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3504 goto done;
3505 error = NULL;
3508 if (argc == 0) {
3509 path = strdup("");
3510 if (path == NULL) {
3511 error = got_error_from_errno("strdup");
3512 goto done;
3514 } else if (argc == 1) {
3515 if (worktree) {
3516 error = got_worktree_resolve_path(&path, worktree,
3517 argv[0]);
3518 if (error)
3519 goto done;
3520 } else {
3521 path = strdup(argv[0]);
3522 if (path == NULL) {
3523 error = got_error_from_errno("strdup");
3524 goto done;
3527 } else
3528 usage_log();
3530 if (repo_path == NULL) {
3531 repo_path = worktree ?
3532 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3534 if (repo_path == NULL) {
3535 error = got_error_from_errno("strdup");
3536 goto done;
3539 error = got_repo_open(&repo, repo_path, NULL);
3540 if (error != NULL)
3541 goto done;
3543 error = apply_unveil(got_repo_get_path(repo), 1,
3544 worktree ? got_worktree_get_root_path(worktree) : NULL);
3545 if (error)
3546 goto done;
3548 if (start_commit == NULL) {
3549 struct got_reference *head_ref;
3550 struct got_commit_object *commit = NULL;
3551 error = got_ref_open(&head_ref, repo,
3552 worktree ? got_worktree_get_head_ref_name(worktree)
3553 : GOT_REF_HEAD, 0);
3554 if (error != NULL)
3555 goto done;
3556 error = got_ref_resolve(&start_id, repo, head_ref);
3557 got_ref_close(head_ref);
3558 if (error != NULL)
3559 goto done;
3560 error = got_object_open_as_commit(&commit, repo,
3561 start_id);
3562 if (error != NULL)
3563 goto done;
3564 got_object_commit_close(commit);
3565 } else {
3566 error = resolve_commit_arg(&start_id, start_commit, repo);
3567 if (error != NULL)
3568 goto done;
3570 if (end_commit != NULL) {
3571 error = resolve_commit_arg(&end_id, end_commit, repo);
3572 if (error != NULL)
3573 goto done;
3576 if (worktree) {
3577 const char *prefix = got_worktree_get_path_prefix(worktree);
3578 char *p;
3579 if (asprintf(&p, "%s%s%s", prefix,
3580 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3581 error = got_error_from_errno("asprintf");
3582 goto done;
3584 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3585 free(p);
3586 } else
3587 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3588 if (error != NULL)
3589 goto done;
3590 if (in_repo_path) {
3591 free(path);
3592 path = in_repo_path;
3595 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3596 if (error)
3597 goto done;
3599 error = print_commits(start_id, end_id, repo, path, show_changed_paths,
3600 show_patch, search_pattern, diff_context, limit, log_branches,
3601 reverse_display_order, &refs);
3602 done:
3603 free(path);
3604 free(repo_path);
3605 free(cwd);
3606 if (worktree)
3607 got_worktree_close(worktree);
3608 if (repo) {
3609 const struct got_error *repo_error;
3610 repo_error = got_repo_close(repo);
3611 if (error == NULL)
3612 error = repo_error;
3614 got_ref_list_free(&refs);
3615 return error;
3618 __dead static void
3619 usage_diff(void)
3621 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3622 "[-w] [object1 object2 | path]\n", getprogname());
3623 exit(1);
3626 struct print_diff_arg {
3627 struct got_repository *repo;
3628 struct got_worktree *worktree;
3629 int diff_context;
3630 const char *id_str;
3631 int header_shown;
3632 int diff_staged;
3633 int ignore_whitespace;
3636 static const struct got_error *
3637 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3638 const char *path, struct got_object_id *blob_id,
3639 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3640 int dirfd, const char *de_name)
3642 struct print_diff_arg *a = arg;
3643 const struct got_error *err = NULL;
3644 struct got_blob_object *blob1 = NULL;
3645 int fd = -1;
3646 FILE *f2 = NULL;
3647 char *abspath = NULL, *label1 = NULL;
3648 struct stat sb;
3650 if (a->diff_staged) {
3651 if (staged_status != GOT_STATUS_MODIFY &&
3652 staged_status != GOT_STATUS_ADD &&
3653 staged_status != GOT_STATUS_DELETE)
3654 return NULL;
3655 } else {
3656 if (staged_status == GOT_STATUS_DELETE)
3657 return NULL;
3658 if (status == GOT_STATUS_NONEXISTENT)
3659 return got_error_set_errno(ENOENT, path);
3660 if (status != GOT_STATUS_MODIFY &&
3661 status != GOT_STATUS_ADD &&
3662 status != GOT_STATUS_DELETE &&
3663 status != GOT_STATUS_CONFLICT)
3664 return NULL;
3667 if (!a->header_shown) {
3668 printf("diff %s %s%s\n", a->id_str,
3669 got_worktree_get_root_path(a->worktree),
3670 a->diff_staged ? " (staged changes)" : "");
3671 a->header_shown = 1;
3674 if (a->diff_staged) {
3675 const char *label1 = NULL, *label2 = NULL;
3676 switch (staged_status) {
3677 case GOT_STATUS_MODIFY:
3678 label1 = path;
3679 label2 = path;
3680 break;
3681 case GOT_STATUS_ADD:
3682 label2 = path;
3683 break;
3684 case GOT_STATUS_DELETE:
3685 label1 = path;
3686 break;
3687 default:
3688 return got_error(GOT_ERR_FILE_STATUS);
3690 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
3691 label1, label2, a->diff_context, a->ignore_whitespace,
3692 a->repo, stdout);
3695 if (staged_status == GOT_STATUS_ADD ||
3696 staged_status == GOT_STATUS_MODIFY) {
3697 char *id_str;
3698 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
3699 8192);
3700 if (err)
3701 goto done;
3702 err = got_object_id_str(&id_str, staged_blob_id);
3703 if (err)
3704 goto done;
3705 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
3706 err = got_error_from_errno("asprintf");
3707 free(id_str);
3708 goto done;
3710 free(id_str);
3711 } else if (status != GOT_STATUS_ADD) {
3712 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
3713 if (err)
3714 goto done;
3717 if (status != GOT_STATUS_DELETE) {
3718 if (asprintf(&abspath, "%s/%s",
3719 got_worktree_get_root_path(a->worktree), path) == -1) {
3720 err = got_error_from_errno("asprintf");
3721 goto done;
3724 if (dirfd != -1) {
3725 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
3726 if (fd == -1) {
3727 err = got_error_from_errno2("openat", abspath);
3728 goto done;
3730 } else {
3731 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
3732 if (fd == -1) {
3733 err = got_error_from_errno2("open", abspath);
3734 goto done;
3737 if (fstat(fd, &sb) == -1) {
3738 err = got_error_from_errno2("fstat", abspath);
3739 goto done;
3741 f2 = fdopen(fd, "r");
3742 if (f2 == NULL) {
3743 err = got_error_from_errno2("fdopen", abspath);
3744 goto done;
3746 fd = -1;
3747 } else
3748 sb.st_size = 0;
3750 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
3751 a->diff_context, a->ignore_whitespace, stdout);
3752 done:
3753 if (blob1)
3754 got_object_blob_close(blob1);
3755 if (f2 && fclose(f2) == EOF && err == NULL)
3756 err = got_error_from_errno("fclose");
3757 if (fd != -1 && close(fd) == -1 && err == NULL)
3758 err = got_error_from_errno("close");
3759 free(abspath);
3760 return err;
3763 static const struct got_error *
3764 cmd_diff(int argc, char *argv[])
3766 const struct got_error *error;
3767 struct got_repository *repo = NULL;
3768 struct got_worktree *worktree = NULL;
3769 char *cwd = NULL, *repo_path = NULL;
3770 struct got_object_id *id1 = NULL, *id2 = NULL;
3771 const char *id_str1 = NULL, *id_str2 = NULL;
3772 char *label1 = NULL, *label2 = NULL;
3773 int type1, type2;
3774 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
3775 const char *errstr;
3776 char *path = NULL;
3778 #ifndef PROFILE
3779 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3780 NULL) == -1)
3781 err(1, "pledge");
3782 #endif
3784 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
3785 switch (ch) {
3786 case 'C':
3787 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3788 &errstr);
3789 if (errstr != NULL)
3790 err(1, "-C option %s", errstr);
3791 break;
3792 case 'r':
3793 repo_path = realpath(optarg, NULL);
3794 if (repo_path == NULL)
3795 return got_error_from_errno2("realpath",
3796 optarg);
3797 got_path_strip_trailing_slashes(repo_path);
3798 break;
3799 case 's':
3800 diff_staged = 1;
3801 break;
3802 case 'w':
3803 ignore_whitespace = 1;
3804 break;
3805 default:
3806 usage_diff();
3807 /* NOTREACHED */
3811 argc -= optind;
3812 argv += optind;
3814 cwd = getcwd(NULL, 0);
3815 if (cwd == NULL) {
3816 error = got_error_from_errno("getcwd");
3817 goto done;
3819 if (argc <= 1) {
3820 if (repo_path)
3821 errx(1,
3822 "-r option can't be used when diffing a work tree");
3823 error = got_worktree_open(&worktree, cwd);
3824 if (error) {
3825 if (error->code == GOT_ERR_NOT_WORKTREE)
3826 error = wrap_not_worktree_error(error, "diff",
3827 cwd);
3828 goto done;
3830 repo_path = strdup(got_worktree_get_repo_path(worktree));
3831 if (repo_path == NULL) {
3832 error = got_error_from_errno("strdup");
3833 goto done;
3835 if (argc == 1) {
3836 error = got_worktree_resolve_path(&path, worktree,
3837 argv[0]);
3838 if (error)
3839 goto done;
3840 } else {
3841 path = strdup("");
3842 if (path == NULL) {
3843 error = got_error_from_errno("strdup");
3844 goto done;
3847 } else if (argc == 2) {
3848 if (diff_staged)
3849 errx(1, "-s option can't be used when diffing "
3850 "objects in repository");
3851 id_str1 = argv[0];
3852 id_str2 = argv[1];
3853 if (repo_path == NULL) {
3854 error = got_worktree_open(&worktree, cwd);
3855 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3856 goto done;
3857 if (worktree) {
3858 repo_path = strdup(
3859 got_worktree_get_repo_path(worktree));
3860 if (repo_path == NULL) {
3861 error = got_error_from_errno("strdup");
3862 goto done;
3864 } else {
3865 repo_path = strdup(cwd);
3866 if (repo_path == NULL) {
3867 error = got_error_from_errno("strdup");
3868 goto done;
3872 } else
3873 usage_diff();
3875 error = got_repo_open(&repo, repo_path, NULL);
3876 free(repo_path);
3877 if (error != NULL)
3878 goto done;
3880 error = apply_unveil(got_repo_get_path(repo), 1,
3881 worktree ? got_worktree_get_root_path(worktree) : NULL);
3882 if (error)
3883 goto done;
3885 if (argc <= 1) {
3886 struct print_diff_arg arg;
3887 struct got_pathlist_head paths;
3888 char *id_str;
3890 TAILQ_INIT(&paths);
3892 error = got_object_id_str(&id_str,
3893 got_worktree_get_base_commit_id(worktree));
3894 if (error)
3895 goto done;
3896 arg.repo = repo;
3897 arg.worktree = worktree;
3898 arg.diff_context = diff_context;
3899 arg.id_str = id_str;
3900 arg.header_shown = 0;
3901 arg.diff_staged = diff_staged;
3902 arg.ignore_whitespace = ignore_whitespace;
3904 error = got_pathlist_append(&paths, path, NULL);
3905 if (error)
3906 goto done;
3908 error = got_worktree_status(worktree, &paths, repo, print_diff,
3909 &arg, check_cancelled, NULL);
3910 free(id_str);
3911 got_pathlist_free(&paths);
3912 goto done;
3915 error = got_repo_match_object_id(&id1, &label1, id_str1,
3916 GOT_OBJ_TYPE_ANY, 1, repo);
3917 if (error)
3918 goto done;
3920 error = got_repo_match_object_id(&id2, &label2, id_str2,
3921 GOT_OBJ_TYPE_ANY, 1, repo);
3922 if (error)
3923 goto done;
3925 error = got_object_get_type(&type1, repo, id1);
3926 if (error)
3927 goto done;
3929 error = got_object_get_type(&type2, repo, id2);
3930 if (error)
3931 goto done;
3933 if (type1 != type2) {
3934 error = got_error(GOT_ERR_OBJ_TYPE);
3935 goto done;
3938 switch (type1) {
3939 case GOT_OBJ_TYPE_BLOB:
3940 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
3941 diff_context, ignore_whitespace, repo, stdout);
3942 break;
3943 case GOT_OBJ_TYPE_TREE:
3944 error = got_diff_objects_as_trees(id1, id2, "", "",
3945 diff_context, ignore_whitespace, repo, stdout);
3946 break;
3947 case GOT_OBJ_TYPE_COMMIT:
3948 printf("diff %s %s\n", label1, label2);
3949 error = got_diff_objects_as_commits(id1, id2, diff_context,
3950 ignore_whitespace, repo, stdout);
3951 break;
3952 default:
3953 error = got_error(GOT_ERR_OBJ_TYPE);
3955 done:
3956 free(label1);
3957 free(label2);
3958 free(id1);
3959 free(id2);
3960 free(path);
3961 if (worktree)
3962 got_worktree_close(worktree);
3963 if (repo) {
3964 const struct got_error *repo_error;
3965 repo_error = got_repo_close(repo);
3966 if (error == NULL)
3967 error = repo_error;
3969 return error;
3972 __dead static void
3973 usage_blame(void)
3975 fprintf(stderr,
3976 "usage: %s blame [-c commit] [-r repository-path] path\n",
3977 getprogname());
3978 exit(1);
3981 struct blame_line {
3982 int annotated;
3983 char *id_str;
3984 char *committer;
3985 char datebuf[11]; /* YYYY-MM-DD + NUL */
3988 struct blame_cb_args {
3989 struct blame_line *lines;
3990 int nlines;
3991 int nlines_prec;
3992 int lineno_cur;
3993 off_t *line_offsets;
3994 FILE *f;
3995 struct got_repository *repo;
3998 static const struct got_error *
3999 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4001 const struct got_error *err = NULL;
4002 struct blame_cb_args *a = arg;
4003 struct blame_line *bline;
4004 char *line = NULL;
4005 size_t linesize = 0;
4006 struct got_commit_object *commit = NULL;
4007 off_t offset;
4008 struct tm tm;
4009 time_t committer_time;
4011 if (nlines != a->nlines ||
4012 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4013 return got_error(GOT_ERR_RANGE);
4015 if (sigint_received)
4016 return got_error(GOT_ERR_ITER_COMPLETED);
4018 if (lineno == -1)
4019 return NULL; /* no change in this commit */
4021 /* Annotate this line. */
4022 bline = &a->lines[lineno - 1];
4023 if (bline->annotated)
4024 return NULL;
4025 err = got_object_id_str(&bline->id_str, id);
4026 if (err)
4027 return err;
4029 err = got_object_open_as_commit(&commit, a->repo, id);
4030 if (err)
4031 goto done;
4033 bline->committer = strdup(got_object_commit_get_committer(commit));
4034 if (bline->committer == NULL) {
4035 err = got_error_from_errno("strdup");
4036 goto done;
4039 committer_time = got_object_commit_get_committer_time(commit);
4040 if (localtime_r(&committer_time, &tm) == NULL)
4041 return got_error_from_errno("localtime_r");
4042 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4043 &tm) >= sizeof(bline->datebuf)) {
4044 err = got_error(GOT_ERR_NO_SPACE);
4045 goto done;
4047 bline->annotated = 1;
4049 /* Print lines annotated so far. */
4050 bline = &a->lines[a->lineno_cur - 1];
4051 if (!bline->annotated)
4052 goto done;
4054 offset = a->line_offsets[a->lineno_cur - 1];
4055 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4056 err = got_error_from_errno("fseeko");
4057 goto done;
4060 while (bline->annotated) {
4061 char *smallerthan, *at, *nl, *committer;
4062 size_t len;
4064 if (getline(&line, &linesize, a->f) == -1) {
4065 if (ferror(a->f))
4066 err = got_error_from_errno("getline");
4067 break;
4070 committer = bline->committer;
4071 smallerthan = strchr(committer, '<');
4072 if (smallerthan && smallerthan[1] != '\0')
4073 committer = smallerthan + 1;
4074 at = strchr(committer, '@');
4075 if (at)
4076 *at = '\0';
4077 len = strlen(committer);
4078 if (len >= 9)
4079 committer[8] = '\0';
4081 nl = strchr(line, '\n');
4082 if (nl)
4083 *nl = '\0';
4084 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4085 bline->id_str, bline->datebuf, committer, line);
4087 a->lineno_cur++;
4088 bline = &a->lines[a->lineno_cur - 1];
4090 done:
4091 if (commit)
4092 got_object_commit_close(commit);
4093 free(line);
4094 return err;
4097 static const struct got_error *
4098 cmd_blame(int argc, char *argv[])
4100 const struct got_error *error;
4101 struct got_repository *repo = NULL;
4102 struct got_worktree *worktree = NULL;
4103 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4104 struct got_object_id *obj_id = NULL;
4105 struct got_object_id *commit_id = NULL;
4106 struct got_blob_object *blob = NULL;
4107 char *commit_id_str = NULL;
4108 struct blame_cb_args bca;
4109 int ch, obj_type, i;
4110 size_t filesize;
4112 memset(&bca, 0, sizeof(bca));
4114 #ifndef PROFILE
4115 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4116 NULL) == -1)
4117 err(1, "pledge");
4118 #endif
4120 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4121 switch (ch) {
4122 case 'c':
4123 commit_id_str = optarg;
4124 break;
4125 case 'r':
4126 repo_path = realpath(optarg, NULL);
4127 if (repo_path == NULL)
4128 return got_error_from_errno2("realpath",
4129 optarg);
4130 got_path_strip_trailing_slashes(repo_path);
4131 break;
4132 default:
4133 usage_blame();
4134 /* NOTREACHED */
4138 argc -= optind;
4139 argv += optind;
4141 if (argc == 1)
4142 path = argv[0];
4143 else
4144 usage_blame();
4146 cwd = getcwd(NULL, 0);
4147 if (cwd == NULL) {
4148 error = got_error_from_errno("getcwd");
4149 goto done;
4151 if (repo_path == NULL) {
4152 error = got_worktree_open(&worktree, cwd);
4153 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4154 goto done;
4155 else
4156 error = NULL;
4157 if (worktree) {
4158 repo_path =
4159 strdup(got_worktree_get_repo_path(worktree));
4160 if (repo_path == NULL) {
4161 error = got_error_from_errno("strdup");
4162 if (error)
4163 goto done;
4165 } else {
4166 repo_path = strdup(cwd);
4167 if (repo_path == NULL) {
4168 error = got_error_from_errno("strdup");
4169 goto done;
4174 error = got_repo_open(&repo, repo_path, NULL);
4175 if (error != NULL)
4176 goto done;
4178 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4179 if (error)
4180 goto done;
4182 if (worktree) {
4183 const char *prefix = got_worktree_get_path_prefix(worktree);
4184 char *p, *worktree_subdir = cwd +
4185 strlen(got_worktree_get_root_path(worktree));
4186 if (asprintf(&p, "%s%s%s%s%s",
4187 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
4188 worktree_subdir, worktree_subdir[0] ? "/" : "",
4189 path) == -1) {
4190 error = got_error_from_errno("asprintf");
4191 goto done;
4193 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4194 free(p);
4195 } else {
4196 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4198 if (error)
4199 goto done;
4201 if (commit_id_str == NULL) {
4202 struct got_reference *head_ref;
4203 error = got_ref_open(&head_ref, repo, worktree ?
4204 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4205 if (error != NULL)
4206 goto done;
4207 error = got_ref_resolve(&commit_id, repo, head_ref);
4208 got_ref_close(head_ref);
4209 if (error != NULL)
4210 goto done;
4211 } else {
4212 error = got_repo_match_object_id(&commit_id, NULL,
4213 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4214 if (error)
4215 goto done;
4218 error = got_object_id_by_path(&obj_id, repo, commit_id, in_repo_path);
4219 if (error)
4220 goto done;
4222 error = got_object_get_type(&obj_type, repo, obj_id);
4223 if (error)
4224 goto done;
4226 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4227 error = got_error(GOT_ERR_OBJ_TYPE);
4228 goto done;
4231 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4232 if (error)
4233 goto done;
4234 bca.f = got_opentemp();
4235 if (bca.f == NULL) {
4236 error = got_error_from_errno("got_opentemp");
4237 goto done;
4239 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4240 &bca.line_offsets, bca.f, blob);
4241 if (error || bca.nlines == 0)
4242 goto done;
4244 /* Don't include \n at EOF in the blame line count. */
4245 if (bca.line_offsets[bca.nlines - 1] == filesize)
4246 bca.nlines--;
4248 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4249 if (bca.lines == NULL) {
4250 error = got_error_from_errno("calloc");
4251 goto done;
4253 bca.lineno_cur = 1;
4254 bca.nlines_prec = 0;
4255 i = bca.nlines;
4256 while (i > 0) {
4257 i /= 10;
4258 bca.nlines_prec++;
4260 bca.repo = repo;
4262 error = got_blame(in_repo_path, commit_id, repo, blame_cb, &bca,
4263 check_cancelled, NULL);
4264 done:
4265 free(in_repo_path);
4266 free(repo_path);
4267 free(cwd);
4268 free(commit_id);
4269 free(obj_id);
4270 if (blob)
4271 got_object_blob_close(blob);
4272 if (worktree)
4273 got_worktree_close(worktree);
4274 if (repo) {
4275 const struct got_error *repo_error;
4276 repo_error = got_repo_close(repo);
4277 if (error == NULL)
4278 error = repo_error;
4280 if (bca.lines) {
4281 for (i = 0; i < bca.nlines; i++) {
4282 struct blame_line *bline = &bca.lines[i];
4283 free(bline->id_str);
4284 free(bline->committer);
4286 free(bca.lines);
4288 free(bca.line_offsets);
4289 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4290 error = got_error_from_errno("fclose");
4291 return error;
4294 __dead static void
4295 usage_tree(void)
4297 fprintf(stderr,
4298 "usage: %s tree [-c commit] [-r repository-path] [-iR] path\n",
4299 getprogname());
4300 exit(1);
4303 static void
4304 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4305 const char *root_path)
4307 int is_root_path = (strcmp(path, root_path) == 0);
4308 const char *modestr = "";
4309 mode_t mode = got_tree_entry_get_mode(te);
4311 path += strlen(root_path);
4312 while (path[0] == '/')
4313 path++;
4315 if (got_object_tree_entry_is_submodule(te))
4316 modestr = "$";
4317 else if (S_ISLNK(mode))
4318 modestr = "@";
4319 else if (S_ISDIR(mode))
4320 modestr = "/";
4321 else if (mode & S_IXUSR)
4322 modestr = "*";
4324 printf("%s%s%s%s%s\n", id ? id : "", path,
4325 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr);
4328 static const struct got_error *
4329 print_tree(const char *path, struct got_object_id *commit_id,
4330 int show_ids, int recurse, const char *root_path,
4331 struct got_repository *repo)
4333 const struct got_error *err = NULL;
4334 struct got_object_id *tree_id = NULL;
4335 struct got_tree_object *tree = NULL;
4336 int nentries, i;
4338 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4339 if (err)
4340 goto done;
4342 err = got_object_open_as_tree(&tree, repo, tree_id);
4343 if (err)
4344 goto done;
4345 nentries = got_object_tree_get_nentries(tree);
4346 for (i = 0; i < nentries; i++) {
4347 struct got_tree_entry *te;
4348 char *id = NULL;
4350 if (sigint_received || sigpipe_received)
4351 break;
4353 te = got_object_tree_get_entry(tree, i);
4354 if (show_ids) {
4355 char *id_str;
4356 err = got_object_id_str(&id_str,
4357 got_tree_entry_get_id(te));
4358 if (err)
4359 goto done;
4360 if (asprintf(&id, "%s ", id_str) == -1) {
4361 err = got_error_from_errno("asprintf");
4362 free(id_str);
4363 goto done;
4365 free(id_str);
4367 print_entry(te, id, path, root_path);
4368 free(id);
4370 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4371 char *child_path;
4372 if (asprintf(&child_path, "%s%s%s", path,
4373 path[0] == '/' && path[1] == '\0' ? "" : "/",
4374 got_tree_entry_get_name(te)) == -1) {
4375 err = got_error_from_errno("asprintf");
4376 goto done;
4378 err = print_tree(child_path, commit_id, show_ids, 1,
4379 root_path, repo);
4380 free(child_path);
4381 if (err)
4382 goto done;
4385 done:
4386 if (tree)
4387 got_object_tree_close(tree);
4388 free(tree_id);
4389 return err;
4392 static const struct got_error *
4393 cmd_tree(int argc, char *argv[])
4395 const struct got_error *error;
4396 struct got_repository *repo = NULL;
4397 struct got_worktree *worktree = NULL;
4398 const char *path, *refname = NULL;
4399 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4400 struct got_object_id *commit_id = NULL;
4401 char *commit_id_str = NULL;
4402 int show_ids = 0, recurse = 0;
4403 int ch;
4405 #ifndef PROFILE
4406 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4407 NULL) == -1)
4408 err(1, "pledge");
4409 #endif
4411 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4412 switch (ch) {
4413 case 'c':
4414 commit_id_str = optarg;
4415 break;
4416 case 'r':
4417 repo_path = realpath(optarg, NULL);
4418 if (repo_path == NULL)
4419 return got_error_from_errno2("realpath",
4420 optarg);
4421 got_path_strip_trailing_slashes(repo_path);
4422 break;
4423 case 'i':
4424 show_ids = 1;
4425 break;
4426 case 'R':
4427 recurse = 1;
4428 break;
4429 default:
4430 usage_tree();
4431 /* NOTREACHED */
4435 argc -= optind;
4436 argv += optind;
4438 if (argc == 1)
4439 path = argv[0];
4440 else if (argc > 1)
4441 usage_tree();
4442 else
4443 path = NULL;
4445 cwd = getcwd(NULL, 0);
4446 if (cwd == NULL) {
4447 error = got_error_from_errno("getcwd");
4448 goto done;
4450 if (repo_path == NULL) {
4451 error = got_worktree_open(&worktree, cwd);
4452 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4453 goto done;
4454 else
4455 error = NULL;
4456 if (worktree) {
4457 repo_path =
4458 strdup(got_worktree_get_repo_path(worktree));
4459 if (repo_path == NULL)
4460 error = got_error_from_errno("strdup");
4461 if (error)
4462 goto done;
4463 } else {
4464 repo_path = strdup(cwd);
4465 if (repo_path == NULL) {
4466 error = got_error_from_errno("strdup");
4467 goto done;
4472 error = got_repo_open(&repo, repo_path, NULL);
4473 if (error != NULL)
4474 goto done;
4476 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4477 if (error)
4478 goto done;
4480 if (path == NULL) {
4481 if (worktree) {
4482 char *p, *worktree_subdir = cwd +
4483 strlen(got_worktree_get_root_path(worktree));
4484 if (asprintf(&p, "%s/%s",
4485 got_worktree_get_path_prefix(worktree),
4486 worktree_subdir) == -1) {
4487 error = got_error_from_errno("asprintf");
4488 goto done;
4490 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4491 free(p);
4492 if (error)
4493 goto done;
4494 } else
4495 path = "/";
4497 if (in_repo_path == NULL) {
4498 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4499 if (error != NULL)
4500 goto done;
4503 if (commit_id_str == NULL) {
4504 struct got_reference *head_ref;
4505 if (worktree)
4506 refname = got_worktree_get_head_ref_name(worktree);
4507 else
4508 refname = GOT_REF_HEAD;
4509 error = got_ref_open(&head_ref, repo, refname, 0);
4510 if (error != NULL)
4511 goto done;
4512 error = got_ref_resolve(&commit_id, repo, head_ref);
4513 got_ref_close(head_ref);
4514 if (error != NULL)
4515 goto done;
4516 } else {
4517 error = got_repo_match_object_id(&commit_id, NULL,
4518 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4519 if (error)
4520 goto done;
4523 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4524 in_repo_path, repo);
4525 done:
4526 free(in_repo_path);
4527 free(repo_path);
4528 free(cwd);
4529 free(commit_id);
4530 if (worktree)
4531 got_worktree_close(worktree);
4532 if (repo) {
4533 const struct got_error *repo_error;
4534 repo_error = got_repo_close(repo);
4535 if (error == NULL)
4536 error = repo_error;
4538 return error;
4541 __dead static void
4542 usage_status(void)
4544 fprintf(stderr, "usage: %s status [path ...]\n", getprogname());
4545 exit(1);
4548 static const struct got_error *
4549 print_status(void *arg, unsigned char status, unsigned char staged_status,
4550 const char *path, struct got_object_id *blob_id,
4551 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4552 int dirfd, const char *de_name)
4554 if (status == staged_status && (status == GOT_STATUS_DELETE))
4555 status = GOT_STATUS_NO_CHANGE;
4556 printf("%c%c %s\n", status, staged_status, path);
4557 return NULL;
4560 static const struct got_error *
4561 cmd_status(int argc, char *argv[])
4563 const struct got_error *error = NULL;
4564 struct got_repository *repo = NULL;
4565 struct got_worktree *worktree = NULL;
4566 char *cwd = NULL;
4567 struct got_pathlist_head paths;
4568 struct got_pathlist_entry *pe;
4569 int ch;
4571 TAILQ_INIT(&paths);
4573 while ((ch = getopt(argc, argv, "")) != -1) {
4574 switch (ch) {
4575 default:
4576 usage_status();
4577 /* NOTREACHED */
4581 argc -= optind;
4582 argv += optind;
4584 #ifndef PROFILE
4585 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4586 NULL) == -1)
4587 err(1, "pledge");
4588 #endif
4589 cwd = getcwd(NULL, 0);
4590 if (cwd == NULL) {
4591 error = got_error_from_errno("getcwd");
4592 goto done;
4595 error = got_worktree_open(&worktree, cwd);
4596 if (error) {
4597 if (error->code == GOT_ERR_NOT_WORKTREE)
4598 error = wrap_not_worktree_error(error, "status", cwd);
4599 goto done;
4602 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4603 NULL);
4604 if (error != NULL)
4605 goto done;
4607 error = apply_unveil(got_repo_get_path(repo), 1,
4608 got_worktree_get_root_path(worktree));
4609 if (error)
4610 goto done;
4612 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
4613 if (error)
4614 goto done;
4616 error = got_worktree_status(worktree, &paths, repo, print_status, NULL,
4617 check_cancelled, NULL);
4618 done:
4619 TAILQ_FOREACH(pe, &paths, entry)
4620 free((char *)pe->path);
4621 got_pathlist_free(&paths);
4622 free(cwd);
4623 return error;
4626 __dead static void
4627 usage_ref(void)
4629 fprintf(stderr,
4630 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
4631 "[-d] [name]\n",
4632 getprogname());
4633 exit(1);
4636 static const struct got_error *
4637 list_refs(struct got_repository *repo, const char *refname)
4639 static const struct got_error *err = NULL;
4640 struct got_reflist_head refs;
4641 struct got_reflist_entry *re;
4643 SIMPLEQ_INIT(&refs);
4644 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
4645 if (err)
4646 return err;
4648 SIMPLEQ_FOREACH(re, &refs, entry) {
4649 char *refstr;
4650 refstr = got_ref_to_str(re->ref);
4651 if (refstr == NULL)
4652 return got_error_from_errno("got_ref_to_str");
4653 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
4654 free(refstr);
4657 got_ref_list_free(&refs);
4658 return NULL;
4661 static const struct got_error *
4662 delete_ref(struct got_repository *repo, const char *refname)
4664 const struct got_error *err = NULL;
4665 struct got_reference *ref;
4667 err = got_ref_open(&ref, repo, refname, 0);
4668 if (err)
4669 return err;
4671 err = got_ref_delete(ref, repo);
4672 got_ref_close(ref);
4673 return err;
4676 static const struct got_error *
4677 add_ref(struct got_repository *repo, const char *refname, const char *target)
4679 const struct got_error *err = NULL;
4680 struct got_object_id *id;
4681 struct got_reference *ref = NULL;
4684 * Don't let the user create a reference name with a leading '-'.
4685 * While technically a valid reference name, this case is usually
4686 * an unintended typo.
4688 if (refname[0] == '-')
4689 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4691 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
4692 repo);
4693 if (err) {
4694 struct got_reference *target_ref;
4696 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
4697 return err;
4698 err = got_ref_open(&target_ref, repo, target, 0);
4699 if (err)
4700 return err;
4701 err = got_ref_resolve(&id, repo, target_ref);
4702 got_ref_close(target_ref);
4703 if (err)
4704 return err;
4707 err = got_ref_alloc(&ref, refname, id);
4708 if (err)
4709 goto done;
4711 err = got_ref_write(ref, repo);
4712 done:
4713 if (ref)
4714 got_ref_close(ref);
4715 free(id);
4716 return err;
4719 static const struct got_error *
4720 add_symref(struct got_repository *repo, const char *refname, const char *target)
4722 const struct got_error *err = NULL;
4723 struct got_reference *ref = NULL;
4724 struct got_reference *target_ref = NULL;
4727 * Don't let the user create a reference name with a leading '-'.
4728 * While technically a valid reference name, this case is usually
4729 * an unintended typo.
4731 if (refname[0] == '-')
4732 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4734 err = got_ref_open(&target_ref, repo, target, 0);
4735 if (err)
4736 return err;
4738 err = got_ref_alloc_symref(&ref, refname, target_ref);
4739 if (err)
4740 goto done;
4742 err = got_ref_write(ref, repo);
4743 done:
4744 if (target_ref)
4745 got_ref_close(target_ref);
4746 if (ref)
4747 got_ref_close(ref);
4748 return err;
4751 static const struct got_error *
4752 cmd_ref(int argc, char *argv[])
4754 const struct got_error *error = NULL;
4755 struct got_repository *repo = NULL;
4756 struct got_worktree *worktree = NULL;
4757 char *cwd = NULL, *repo_path = NULL;
4758 int ch, do_list = 0, do_delete = 0;
4759 const char *obj_arg = NULL, *symref_target= NULL;
4760 char *refname = NULL;
4762 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
4763 switch (ch) {
4764 case 'c':
4765 obj_arg = optarg;
4766 break;
4767 case 'd':
4768 do_delete = 1;
4769 break;
4770 case 'r':
4771 repo_path = realpath(optarg, NULL);
4772 if (repo_path == NULL)
4773 return got_error_from_errno2("realpath",
4774 optarg);
4775 got_path_strip_trailing_slashes(repo_path);
4776 break;
4777 case 'l':
4778 do_list = 1;
4779 break;
4780 case 's':
4781 symref_target = optarg;
4782 break;
4783 default:
4784 usage_ref();
4785 /* NOTREACHED */
4789 if (obj_arg && do_list)
4790 errx(1, "-c and -l options are mutually exclusive");
4791 if (obj_arg && do_delete)
4792 errx(1, "-c and -d options are mutually exclusive");
4793 if (obj_arg && symref_target)
4794 errx(1, "-c and -s options are mutually exclusive");
4795 if (symref_target && do_delete)
4796 errx(1, "-s and -d options are mutually exclusive");
4797 if (symref_target && do_list)
4798 errx(1, "-s and -l options are mutually exclusive");
4799 if (do_delete && do_list)
4800 errx(1, "-d and -l options are mutually exclusive");
4802 argc -= optind;
4803 argv += optind;
4805 if (do_list) {
4806 if (argc != 0 && argc != 1)
4807 usage_ref();
4808 if (argc == 1) {
4809 refname = strdup(argv[0]);
4810 if (refname == NULL) {
4811 error = got_error_from_errno("strdup");
4812 goto done;
4815 } else {
4816 if (argc != 1)
4817 usage_ref();
4818 refname = strdup(argv[0]);
4819 if (refname == NULL) {
4820 error = got_error_from_errno("strdup");
4821 goto done;
4825 if (refname)
4826 got_path_strip_trailing_slashes(refname);
4828 #ifndef PROFILE
4829 if (do_list) {
4830 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4831 NULL) == -1)
4832 err(1, "pledge");
4833 } else {
4834 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4835 "sendfd unveil", NULL) == -1)
4836 err(1, "pledge");
4838 #endif
4839 cwd = getcwd(NULL, 0);
4840 if (cwd == NULL) {
4841 error = got_error_from_errno("getcwd");
4842 goto done;
4845 if (repo_path == NULL) {
4846 error = got_worktree_open(&worktree, cwd);
4847 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4848 goto done;
4849 else
4850 error = NULL;
4851 if (worktree) {
4852 repo_path =
4853 strdup(got_worktree_get_repo_path(worktree));
4854 if (repo_path == NULL)
4855 error = got_error_from_errno("strdup");
4856 if (error)
4857 goto done;
4858 } else {
4859 repo_path = strdup(cwd);
4860 if (repo_path == NULL) {
4861 error = got_error_from_errno("strdup");
4862 goto done;
4867 error = got_repo_open(&repo, repo_path, NULL);
4868 if (error != NULL)
4869 goto done;
4871 error = apply_unveil(got_repo_get_path(repo), do_list,
4872 worktree ? got_worktree_get_root_path(worktree) : NULL);
4873 if (error)
4874 goto done;
4876 if (do_list)
4877 error = list_refs(repo, refname);
4878 else if (do_delete)
4879 error = delete_ref(repo, refname);
4880 else if (symref_target)
4881 error = add_symref(repo, refname, symref_target);
4882 else {
4883 if (obj_arg == NULL)
4884 usage_ref();
4885 error = add_ref(repo, refname, obj_arg);
4887 done:
4888 free(refname);
4889 if (repo)
4890 got_repo_close(repo);
4891 if (worktree)
4892 got_worktree_close(worktree);
4893 free(cwd);
4894 free(repo_path);
4895 return error;
4898 __dead static void
4899 usage_branch(void)
4901 fprintf(stderr,
4902 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
4903 "[name]\n", getprogname());
4904 exit(1);
4907 static const struct got_error *
4908 list_branch(struct got_repository *repo, struct got_worktree *worktree,
4909 struct got_reference *ref)
4911 const struct got_error *err = NULL;
4912 const char *refname, *marker = " ";
4913 char *refstr;
4915 refname = got_ref_get_name(ref);
4916 if (worktree && strcmp(refname,
4917 got_worktree_get_head_ref_name(worktree)) == 0) {
4918 struct got_object_id *id = NULL;
4920 err = got_ref_resolve(&id, repo, ref);
4921 if (err)
4922 return err;
4923 if (got_object_id_cmp(id,
4924 got_worktree_get_base_commit_id(worktree)) == 0)
4925 marker = "* ";
4926 else
4927 marker = "~ ";
4928 free(id);
4931 if (strncmp(refname, "refs/heads/", 11) == 0)
4932 refname += 11;
4933 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4934 refname += 18;
4936 refstr = got_ref_to_str(ref);
4937 if (refstr == NULL)
4938 return got_error_from_errno("got_ref_to_str");
4940 printf("%s%s: %s\n", marker, refname, refstr);
4941 free(refstr);
4942 return NULL;
4945 static const struct got_error *
4946 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
4948 const char *refname;
4950 if (worktree == NULL)
4951 return got_error(GOT_ERR_NOT_WORKTREE);
4953 refname = got_worktree_get_head_ref_name(worktree);
4955 if (strncmp(refname, "refs/heads/", 11) == 0)
4956 refname += 11;
4957 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4958 refname += 18;
4960 printf("%s\n", refname);
4962 return NULL;
4965 static const struct got_error *
4966 list_branches(struct got_repository *repo, struct got_worktree *worktree)
4968 static const struct got_error *err = NULL;
4969 struct got_reflist_head refs;
4970 struct got_reflist_entry *re;
4971 struct got_reference *temp_ref = NULL;
4972 int rebase_in_progress, histedit_in_progress;
4974 SIMPLEQ_INIT(&refs);
4976 if (worktree) {
4977 err = got_worktree_rebase_in_progress(&rebase_in_progress,
4978 worktree);
4979 if (err)
4980 return err;
4982 err = got_worktree_histedit_in_progress(&histedit_in_progress,
4983 worktree);
4984 if (err)
4985 return err;
4987 if (rebase_in_progress || histedit_in_progress) {
4988 err = got_ref_open(&temp_ref, repo,
4989 got_worktree_get_head_ref_name(worktree), 0);
4990 if (err)
4991 return err;
4992 list_branch(repo, worktree, temp_ref);
4993 got_ref_close(temp_ref);
4997 err = got_ref_list(&refs, repo, "refs/heads",
4998 got_ref_cmp_by_name, NULL);
4999 if (err)
5000 return err;
5002 SIMPLEQ_FOREACH(re, &refs, entry)
5003 list_branch(repo, worktree, re->ref);
5005 got_ref_list_free(&refs);
5006 return NULL;
5009 static const struct got_error *
5010 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5011 const char *branch_name)
5013 const struct got_error *err = NULL;
5014 struct got_reference *ref = NULL;
5015 char *refname;
5017 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5018 return got_error_from_errno("asprintf");
5020 err = got_ref_open(&ref, repo, refname, 0);
5021 if (err)
5022 goto done;
5024 if (worktree &&
5025 strcmp(got_worktree_get_head_ref_name(worktree),
5026 got_ref_get_name(ref)) == 0) {
5027 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5028 "will not delete this work tree's current branch");
5029 goto done;
5032 err = got_ref_delete(ref, repo);
5033 done:
5034 if (ref)
5035 got_ref_close(ref);
5036 free(refname);
5037 return err;
5040 static const struct got_error *
5041 add_branch(struct got_repository *repo, const char *branch_name,
5042 struct got_object_id *base_commit_id)
5044 const struct got_error *err = NULL;
5045 struct got_reference *ref = NULL;
5046 char *base_refname = NULL, *refname = NULL;
5049 * Don't let the user create a branch name with a leading '-'.
5050 * While technically a valid reference name, this case is usually
5051 * an unintended typo.
5053 if (branch_name[0] == '-')
5054 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5056 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5057 err = got_error_from_errno("asprintf");
5058 goto done;
5061 err = got_ref_open(&ref, repo, refname, 0);
5062 if (err == NULL) {
5063 err = got_error(GOT_ERR_BRANCH_EXISTS);
5064 goto done;
5065 } else if (err->code != GOT_ERR_NOT_REF)
5066 goto done;
5068 err = got_ref_alloc(&ref, refname, base_commit_id);
5069 if (err)
5070 goto done;
5072 err = got_ref_write(ref, repo);
5073 done:
5074 if (ref)
5075 got_ref_close(ref);
5076 free(base_refname);
5077 free(refname);
5078 return err;
5081 static const struct got_error *
5082 cmd_branch(int argc, char *argv[])
5084 const struct got_error *error = NULL;
5085 struct got_repository *repo = NULL;
5086 struct got_worktree *worktree = NULL;
5087 char *cwd = NULL, *repo_path = NULL;
5088 int ch, do_list = 0, do_show = 0, do_update = 1;
5089 const char *delref = NULL, *commit_id_arg = NULL;
5090 struct got_reference *ref = NULL;
5091 struct got_pathlist_head paths;
5092 struct got_pathlist_entry *pe;
5093 struct got_object_id *commit_id = NULL;
5094 char *commit_id_str = NULL;
5096 TAILQ_INIT(&paths);
5098 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5099 switch (ch) {
5100 case 'c':
5101 commit_id_arg = optarg;
5102 break;
5103 case 'd':
5104 delref = optarg;
5105 break;
5106 case 'r':
5107 repo_path = realpath(optarg, NULL);
5108 if (repo_path == NULL)
5109 return got_error_from_errno2("realpath",
5110 optarg);
5111 got_path_strip_trailing_slashes(repo_path);
5112 break;
5113 case 'l':
5114 do_list = 1;
5115 break;
5116 case 'n':
5117 do_update = 0;
5118 break;
5119 default:
5120 usage_branch();
5121 /* NOTREACHED */
5125 if (do_list && delref)
5126 errx(1, "-l and -d options are mutually exclusive");
5128 argc -= optind;
5129 argv += optind;
5131 if (!do_list && !delref && argc == 0)
5132 do_show = 1;
5134 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5135 errx(1, "-c option can only be used when creating a branch");
5137 if (do_list || delref) {
5138 if (argc > 0)
5139 usage_branch();
5140 } else if (!do_show && argc != 1)
5141 usage_branch();
5143 #ifndef PROFILE
5144 if (do_list || do_show) {
5145 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5146 NULL) == -1)
5147 err(1, "pledge");
5148 } else {
5149 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5150 "sendfd unveil", NULL) == -1)
5151 err(1, "pledge");
5153 #endif
5154 cwd = getcwd(NULL, 0);
5155 if (cwd == NULL) {
5156 error = got_error_from_errno("getcwd");
5157 goto done;
5160 if (repo_path == NULL) {
5161 error = got_worktree_open(&worktree, cwd);
5162 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5163 goto done;
5164 else
5165 error = NULL;
5166 if (worktree) {
5167 repo_path =
5168 strdup(got_worktree_get_repo_path(worktree));
5169 if (repo_path == NULL)
5170 error = got_error_from_errno("strdup");
5171 if (error)
5172 goto done;
5173 } else {
5174 repo_path = strdup(cwd);
5175 if (repo_path == NULL) {
5176 error = got_error_from_errno("strdup");
5177 goto done;
5182 error = got_repo_open(&repo, repo_path, NULL);
5183 if (error != NULL)
5184 goto done;
5186 error = apply_unveil(got_repo_get_path(repo), do_list,
5187 worktree ? got_worktree_get_root_path(worktree) : NULL);
5188 if (error)
5189 goto done;
5191 if (do_show)
5192 error = show_current_branch(repo, worktree);
5193 else if (do_list)
5194 error = list_branches(repo, worktree);
5195 else if (delref)
5196 error = delete_branch(repo, worktree, delref);
5197 else {
5198 if (commit_id_arg == NULL)
5199 commit_id_arg = worktree ?
5200 got_worktree_get_head_ref_name(worktree) :
5201 GOT_REF_HEAD;
5202 error = got_repo_match_object_id(&commit_id, NULL,
5203 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5204 if (error)
5205 goto done;
5206 error = add_branch(repo, argv[0], commit_id);
5207 if (error)
5208 goto done;
5209 if (worktree && do_update) {
5210 struct got_update_progress_arg upa;
5211 char *branch_refname = NULL;
5213 error = got_object_id_str(&commit_id_str, commit_id);
5214 if (error)
5215 goto done;
5216 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5217 worktree);
5218 if (error)
5219 goto done;
5220 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5221 == -1) {
5222 error = got_error_from_errno("asprintf");
5223 goto done;
5225 error = got_ref_open(&ref, repo, branch_refname, 0);
5226 free(branch_refname);
5227 if (error)
5228 goto done;
5229 error = switch_head_ref(ref, commit_id, worktree,
5230 repo);
5231 if (error)
5232 goto done;
5233 error = got_worktree_set_base_commit_id(worktree, repo,
5234 commit_id);
5235 if (error)
5236 goto done;
5237 memset(&upa, 0, sizeof(upa));
5238 error = got_worktree_checkout_files(worktree, &paths,
5239 repo, update_progress, &upa, check_cancelled,
5240 NULL);
5241 if (error)
5242 goto done;
5243 if (upa.did_something)
5244 printf("Updated to commit %s\n", commit_id_str);
5245 print_update_progress_stats(&upa);
5248 done:
5249 if (ref)
5250 got_ref_close(ref);
5251 if (repo)
5252 got_repo_close(repo);
5253 if (worktree)
5254 got_worktree_close(worktree);
5255 free(cwd);
5256 free(repo_path);
5257 free(commit_id);
5258 free(commit_id_str);
5259 TAILQ_FOREACH(pe, &paths, entry)
5260 free((char *)pe->path);
5261 got_pathlist_free(&paths);
5262 return error;
5266 __dead static void
5267 usage_tag(void)
5269 fprintf(stderr,
5270 "usage: %s tag [-c commit] [-r repository] [-l] "
5271 "[-m message] name\n", getprogname());
5272 exit(1);
5275 #if 0
5276 static const struct got_error *
5277 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5279 const struct got_error *err = NULL;
5280 struct got_reflist_entry *re, *se, *new;
5281 struct got_object_id *re_id, *se_id;
5282 struct got_tag_object *re_tag, *se_tag;
5283 time_t re_time, se_time;
5285 SIMPLEQ_FOREACH(re, tags, entry) {
5286 se = SIMPLEQ_FIRST(sorted);
5287 if (se == NULL) {
5288 err = got_reflist_entry_dup(&new, re);
5289 if (err)
5290 return err;
5291 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5292 continue;
5293 } else {
5294 err = got_ref_resolve(&re_id, repo, re->ref);
5295 if (err)
5296 break;
5297 err = got_object_open_as_tag(&re_tag, repo, re_id);
5298 free(re_id);
5299 if (err)
5300 break;
5301 re_time = got_object_tag_get_tagger_time(re_tag);
5302 got_object_tag_close(re_tag);
5305 while (se) {
5306 err = got_ref_resolve(&se_id, repo, re->ref);
5307 if (err)
5308 break;
5309 err = got_object_open_as_tag(&se_tag, repo, se_id);
5310 free(se_id);
5311 if (err)
5312 break;
5313 se_time = got_object_tag_get_tagger_time(se_tag);
5314 got_object_tag_close(se_tag);
5316 if (se_time > re_time) {
5317 err = got_reflist_entry_dup(&new, re);
5318 if (err)
5319 return err;
5320 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5321 break;
5323 se = SIMPLEQ_NEXT(se, entry);
5324 continue;
5327 done:
5328 return err;
5330 #endif
5332 static const struct got_error *
5333 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5335 static const struct got_error *err = NULL;
5336 struct got_reflist_head refs;
5337 struct got_reflist_entry *re;
5339 SIMPLEQ_INIT(&refs);
5341 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5342 if (err)
5343 return err;
5345 SIMPLEQ_FOREACH(re, &refs, entry) {
5346 const char *refname;
5347 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5348 char datebuf[26];
5349 const char *tagger;
5350 time_t tagger_time;
5351 struct got_object_id *id;
5352 struct got_tag_object *tag;
5353 struct got_commit_object *commit = NULL;
5355 refname = got_ref_get_name(re->ref);
5356 if (strncmp(refname, "refs/tags/", 10) != 0)
5357 continue;
5358 refname += 10;
5359 refstr = got_ref_to_str(re->ref);
5360 if (refstr == NULL) {
5361 err = got_error_from_errno("got_ref_to_str");
5362 break;
5364 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5365 free(refstr);
5367 err = got_ref_resolve(&id, repo, re->ref);
5368 if (err)
5369 break;
5370 err = got_object_open_as_tag(&tag, repo, id);
5371 if (err) {
5372 if (err->code != GOT_ERR_OBJ_TYPE) {
5373 free(id);
5374 break;
5376 /* "lightweight" tag */
5377 err = got_object_open_as_commit(&commit, repo, id);
5378 if (err) {
5379 free(id);
5380 break;
5382 tagger = got_object_commit_get_committer(commit);
5383 tagger_time =
5384 got_object_commit_get_committer_time(commit);
5385 err = got_object_id_str(&id_str, id);
5386 free(id);
5387 if (err)
5388 break;
5389 } else {
5390 free(id);
5391 tagger = got_object_tag_get_tagger(tag);
5392 tagger_time = got_object_tag_get_tagger_time(tag);
5393 err = got_object_id_str(&id_str,
5394 got_object_tag_get_object_id(tag));
5395 if (err)
5396 break;
5398 printf("from: %s\n", tagger);
5399 datestr = get_datestr(&tagger_time, datebuf);
5400 if (datestr)
5401 printf("date: %s UTC\n", datestr);
5402 if (commit)
5403 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5404 else {
5405 switch (got_object_tag_get_object_type(tag)) {
5406 case GOT_OBJ_TYPE_BLOB:
5407 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5408 id_str);
5409 break;
5410 case GOT_OBJ_TYPE_TREE:
5411 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5412 id_str);
5413 break;
5414 case GOT_OBJ_TYPE_COMMIT:
5415 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5416 id_str);
5417 break;
5418 case GOT_OBJ_TYPE_TAG:
5419 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5420 id_str);
5421 break;
5422 default:
5423 break;
5426 free(id_str);
5427 if (commit) {
5428 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5429 if (err)
5430 break;
5431 got_object_commit_close(commit);
5432 } else {
5433 tagmsg0 = strdup(got_object_tag_get_message(tag));
5434 got_object_tag_close(tag);
5435 if (tagmsg0 == NULL) {
5436 err = got_error_from_errno("strdup");
5437 break;
5441 tagmsg = tagmsg0;
5442 do {
5443 line = strsep(&tagmsg, "\n");
5444 if (line)
5445 printf(" %s\n", line);
5446 } while (line);
5447 free(tagmsg0);
5450 got_ref_list_free(&refs);
5451 return NULL;
5454 static const struct got_error *
5455 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5456 const char *tag_name, const char *repo_path)
5458 const struct got_error *err = NULL;
5459 char *template = NULL, *initial_content = NULL;
5460 char *editor = NULL;
5461 int fd = -1;
5463 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5464 err = got_error_from_errno("asprintf");
5465 goto done;
5468 if (asprintf(&initial_content, "\n# tagging commit %s as %s\n",
5469 commit_id_str, tag_name) == -1) {
5470 err = got_error_from_errno("asprintf");
5471 goto done;
5474 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5475 if (err)
5476 goto done;
5478 dprintf(fd, initial_content);
5479 close(fd);
5481 err = get_editor(&editor);
5482 if (err)
5483 goto done;
5484 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
5485 done:
5486 free(initial_content);
5487 free(template);
5488 free(editor);
5490 /* Editor is done; we can now apply unveil(2) */
5491 if (err == NULL) {
5492 err = apply_unveil(repo_path, 0, NULL);
5493 if (err) {
5494 free(*tagmsg);
5495 *tagmsg = NULL;
5498 return err;
5501 static const struct got_error *
5502 add_tag(struct got_repository *repo, const char *tag_name,
5503 const char *commit_arg, const char *tagmsg_arg)
5505 const struct got_error *err = NULL;
5506 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5507 char *label = NULL, *commit_id_str = NULL;
5508 struct got_reference *ref = NULL;
5509 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5510 char *tagmsg_path = NULL, *tag_id_str = NULL;
5511 int preserve_tagmsg = 0;
5514 * Don't let the user create a tag name with a leading '-'.
5515 * While technically a valid reference name, this case is usually
5516 * an unintended typo.
5518 if (tag_name[0] == '-')
5519 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5521 err = get_author(&tagger, repo);
5522 if (err)
5523 return err;
5525 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5526 GOT_OBJ_TYPE_COMMIT, 1, repo);
5527 if (err)
5528 goto done;
5530 err = got_object_id_str(&commit_id_str, commit_id);
5531 if (err)
5532 goto done;
5534 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5535 refname = strdup(tag_name);
5536 if (refname == NULL) {
5537 err = got_error_from_errno("strdup");
5538 goto done;
5540 tag_name += 10;
5541 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5542 err = got_error_from_errno("asprintf");
5543 goto done;
5546 err = got_ref_open(&ref, repo, refname, 0);
5547 if (err == NULL) {
5548 err = got_error(GOT_ERR_TAG_EXISTS);
5549 goto done;
5550 } else if (err->code != GOT_ERR_NOT_REF)
5551 goto done;
5553 if (tagmsg_arg == NULL) {
5554 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5555 tag_name, got_repo_get_path(repo));
5556 if (err) {
5557 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5558 tagmsg_path != NULL)
5559 preserve_tagmsg = 1;
5560 goto done;
5564 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5565 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5566 if (err) {
5567 if (tagmsg_path)
5568 preserve_tagmsg = 1;
5569 goto done;
5572 err = got_ref_alloc(&ref, refname, tag_id);
5573 if (err) {
5574 if (tagmsg_path)
5575 preserve_tagmsg = 1;
5576 goto done;
5579 err = got_ref_write(ref, repo);
5580 if (err) {
5581 if (tagmsg_path)
5582 preserve_tagmsg = 1;
5583 goto done;
5586 err = got_object_id_str(&tag_id_str, tag_id);
5587 if (err) {
5588 if (tagmsg_path)
5589 preserve_tagmsg = 1;
5590 goto done;
5592 printf("Created tag %s\n", tag_id_str);
5593 done:
5594 if (preserve_tagmsg) {
5595 fprintf(stderr, "%s: tag message preserved in %s\n",
5596 getprogname(), tagmsg_path);
5597 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
5598 err = got_error_from_errno2("unlink", tagmsg_path);
5599 free(tag_id_str);
5600 if (ref)
5601 got_ref_close(ref);
5602 free(commit_id);
5603 free(commit_id_str);
5604 free(refname);
5605 free(tagmsg);
5606 free(tagmsg_path);
5607 free(tagger);
5608 return err;
5611 static const struct got_error *
5612 cmd_tag(int argc, char *argv[])
5614 const struct got_error *error = NULL;
5615 struct got_repository *repo = NULL;
5616 struct got_worktree *worktree = NULL;
5617 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
5618 char *gitconfig_path = NULL;
5619 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
5620 int ch, do_list = 0;
5622 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
5623 switch (ch) {
5624 case 'c':
5625 commit_id_arg = optarg;
5626 break;
5627 case 'm':
5628 tagmsg = optarg;
5629 break;
5630 case 'r':
5631 repo_path = realpath(optarg, NULL);
5632 if (repo_path == NULL)
5633 return got_error_from_errno2("realpath",
5634 optarg);
5635 got_path_strip_trailing_slashes(repo_path);
5636 break;
5637 case 'l':
5638 do_list = 1;
5639 break;
5640 default:
5641 usage_tag();
5642 /* NOTREACHED */
5646 argc -= optind;
5647 argv += optind;
5649 if (do_list) {
5650 if (commit_id_arg != NULL)
5651 errx(1,
5652 "-c option can only be used when creating a tag");
5653 if (tagmsg)
5654 errx(1, "-l and -m options are mutually exclusive");
5655 if (argc > 0)
5656 usage_tag();
5657 } else if (argc != 1)
5658 usage_tag();
5660 tag_name = argv[0];
5662 #ifndef PROFILE
5663 if (do_list) {
5664 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5665 NULL) == -1)
5666 err(1, "pledge");
5667 } else {
5668 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5669 "sendfd unveil", NULL) == -1)
5670 err(1, "pledge");
5672 #endif
5673 cwd = getcwd(NULL, 0);
5674 if (cwd == NULL) {
5675 error = got_error_from_errno("getcwd");
5676 goto done;
5679 if (repo_path == NULL) {
5680 error = got_worktree_open(&worktree, cwd);
5681 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5682 goto done;
5683 else
5684 error = NULL;
5685 if (worktree) {
5686 repo_path =
5687 strdup(got_worktree_get_repo_path(worktree));
5688 if (repo_path == NULL)
5689 error = got_error_from_errno("strdup");
5690 if (error)
5691 goto done;
5692 } else {
5693 repo_path = strdup(cwd);
5694 if (repo_path == NULL) {
5695 error = got_error_from_errno("strdup");
5696 goto done;
5701 if (do_list) {
5702 error = got_repo_open(&repo, repo_path, NULL);
5703 if (error != NULL)
5704 goto done;
5705 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5706 if (error)
5707 goto done;
5708 error = list_tags(repo, worktree);
5709 } else {
5710 error = get_gitconfig_path(&gitconfig_path);
5711 if (error)
5712 goto done;
5713 error = got_repo_open(&repo, repo_path, gitconfig_path);
5714 if (error != NULL)
5715 goto done;
5717 if (tagmsg) {
5718 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5719 if (error)
5720 goto done;
5723 if (commit_id_arg == NULL) {
5724 struct got_reference *head_ref;
5725 struct got_object_id *commit_id;
5726 error = got_ref_open(&head_ref, repo,
5727 worktree ? got_worktree_get_head_ref_name(worktree)
5728 : GOT_REF_HEAD, 0);
5729 if (error)
5730 goto done;
5731 error = got_ref_resolve(&commit_id, repo, head_ref);
5732 got_ref_close(head_ref);
5733 if (error)
5734 goto done;
5735 error = got_object_id_str(&commit_id_str, commit_id);
5736 free(commit_id);
5737 if (error)
5738 goto done;
5741 error = add_tag(repo, tag_name,
5742 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
5744 done:
5745 if (repo)
5746 got_repo_close(repo);
5747 if (worktree)
5748 got_worktree_close(worktree);
5749 free(cwd);
5750 free(repo_path);
5751 free(gitconfig_path);
5752 free(commit_id_str);
5753 return error;
5756 __dead static void
5757 usage_add(void)
5759 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
5760 getprogname());
5761 exit(1);
5764 static const struct got_error *
5765 add_progress(void *arg, unsigned char status, const char *path)
5767 while (path[0] == '/')
5768 path++;
5769 printf("%c %s\n", status, path);
5770 return NULL;
5773 static const struct got_error *
5774 cmd_add(int argc, char *argv[])
5776 const struct got_error *error = NULL;
5777 struct got_repository *repo = NULL;
5778 struct got_worktree *worktree = NULL;
5779 char *cwd = NULL;
5780 struct got_pathlist_head paths;
5781 struct got_pathlist_entry *pe;
5782 int ch, can_recurse = 0, no_ignores = 0;
5784 TAILQ_INIT(&paths);
5786 while ((ch = getopt(argc, argv, "IR")) != -1) {
5787 switch (ch) {
5788 case 'I':
5789 no_ignores = 1;
5790 break;
5791 case 'R':
5792 can_recurse = 1;
5793 break;
5794 default:
5795 usage_add();
5796 /* NOTREACHED */
5800 argc -= optind;
5801 argv += optind;
5803 #ifndef PROFILE
5804 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5805 NULL) == -1)
5806 err(1, "pledge");
5807 #endif
5808 if (argc < 1)
5809 usage_add();
5811 cwd = getcwd(NULL, 0);
5812 if (cwd == NULL) {
5813 error = got_error_from_errno("getcwd");
5814 goto done;
5817 error = got_worktree_open(&worktree, cwd);
5818 if (error) {
5819 if (error->code == GOT_ERR_NOT_WORKTREE)
5820 error = wrap_not_worktree_error(error, "add", cwd);
5821 goto done;
5824 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5825 NULL);
5826 if (error != NULL)
5827 goto done;
5829 error = apply_unveil(got_repo_get_path(repo), 1,
5830 got_worktree_get_root_path(worktree));
5831 if (error)
5832 goto done;
5834 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5835 if (error)
5836 goto done;
5838 if (!can_recurse && no_ignores) {
5839 error = got_error_msg(GOT_ERR_BAD_PATH,
5840 "disregarding ignores requires -R option");
5841 goto done;
5845 if (!can_recurse) {
5846 char *ondisk_path;
5847 struct stat sb;
5848 TAILQ_FOREACH(pe, &paths, entry) {
5849 if (asprintf(&ondisk_path, "%s/%s",
5850 got_worktree_get_root_path(worktree),
5851 pe->path) == -1) {
5852 error = got_error_from_errno("asprintf");
5853 goto done;
5855 if (lstat(ondisk_path, &sb) == -1) {
5856 if (errno == ENOENT) {
5857 free(ondisk_path);
5858 continue;
5860 error = got_error_from_errno2("lstat",
5861 ondisk_path);
5862 free(ondisk_path);
5863 goto done;
5865 free(ondisk_path);
5866 if (S_ISDIR(sb.st_mode)) {
5867 error = got_error_msg(GOT_ERR_BAD_PATH,
5868 "adding directories requires -R option");
5869 goto done;
5874 error = got_worktree_schedule_add(worktree, &paths, add_progress,
5875 NULL, repo, no_ignores);
5876 done:
5877 if (repo)
5878 got_repo_close(repo);
5879 if (worktree)
5880 got_worktree_close(worktree);
5881 TAILQ_FOREACH(pe, &paths, entry)
5882 free((char *)pe->path);
5883 got_pathlist_free(&paths);
5884 free(cwd);
5885 return error;
5888 __dead static void
5889 usage_remove(void)
5891 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] path ...\n",
5892 getprogname());
5893 exit(1);
5896 static const struct got_error *
5897 print_remove_status(void *arg, unsigned char status,
5898 unsigned char staged_status, const char *path)
5900 while (path[0] == '/')
5901 path++;
5902 if (status == GOT_STATUS_NONEXISTENT)
5903 return NULL;
5904 if (status == staged_status && (status == GOT_STATUS_DELETE))
5905 status = GOT_STATUS_NO_CHANGE;
5906 printf("%c%c %s\n", status, staged_status, path);
5907 return NULL;
5910 static const struct got_error *
5911 cmd_remove(int argc, char *argv[])
5913 const struct got_error *error = NULL;
5914 struct got_worktree *worktree = NULL;
5915 struct got_repository *repo = NULL;
5916 char *cwd = NULL;
5917 struct got_pathlist_head paths;
5918 struct got_pathlist_entry *pe;
5919 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0;
5921 TAILQ_INIT(&paths);
5923 while ((ch = getopt(argc, argv, "fkR")) != -1) {
5924 switch (ch) {
5925 case 'f':
5926 delete_local_mods = 1;
5927 break;
5928 case 'k':
5929 keep_on_disk = 1;
5930 break;
5931 case 'R':
5932 can_recurse = 1;
5933 break;
5934 default:
5935 usage_remove();
5936 /* NOTREACHED */
5940 argc -= optind;
5941 argv += optind;
5943 #ifndef PROFILE
5944 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5945 NULL) == -1)
5946 err(1, "pledge");
5947 #endif
5948 if (argc < 1)
5949 usage_remove();
5951 cwd = getcwd(NULL, 0);
5952 if (cwd == NULL) {
5953 error = got_error_from_errno("getcwd");
5954 goto done;
5956 error = got_worktree_open(&worktree, cwd);
5957 if (error) {
5958 if (error->code == GOT_ERR_NOT_WORKTREE)
5959 error = wrap_not_worktree_error(error, "remove", cwd);
5960 goto done;
5963 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5964 NULL);
5965 if (error)
5966 goto done;
5968 error = apply_unveil(got_repo_get_path(repo), 1,
5969 got_worktree_get_root_path(worktree));
5970 if (error)
5971 goto done;
5973 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5974 if (error)
5975 goto done;
5977 if (!can_recurse) {
5978 char *ondisk_path;
5979 struct stat sb;
5980 TAILQ_FOREACH(pe, &paths, entry) {
5981 if (asprintf(&ondisk_path, "%s/%s",
5982 got_worktree_get_root_path(worktree),
5983 pe->path) == -1) {
5984 error = got_error_from_errno("asprintf");
5985 goto done;
5987 if (lstat(ondisk_path, &sb) == -1) {
5988 if (errno == ENOENT) {
5989 free(ondisk_path);
5990 continue;
5992 error = got_error_from_errno2("lstat",
5993 ondisk_path);
5994 free(ondisk_path);
5995 goto done;
5997 free(ondisk_path);
5998 if (S_ISDIR(sb.st_mode)) {
5999 error = got_error_msg(GOT_ERR_BAD_PATH,
6000 "removing directories requires -R option");
6001 goto done;
6006 error = got_worktree_schedule_delete(worktree, &paths,
6007 delete_local_mods, print_remove_status, NULL, repo, keep_on_disk);
6008 done:
6009 if (repo)
6010 got_repo_close(repo);
6011 if (worktree)
6012 got_worktree_close(worktree);
6013 TAILQ_FOREACH(pe, &paths, entry)
6014 free((char *)pe->path);
6015 got_pathlist_free(&paths);
6016 free(cwd);
6017 return error;
6020 __dead static void
6021 usage_revert(void)
6023 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6024 "path ...\n", getprogname());
6025 exit(1);
6028 static const struct got_error *
6029 revert_progress(void *arg, unsigned char status, const char *path)
6031 if (status == GOT_STATUS_UNVERSIONED)
6032 return NULL;
6034 while (path[0] == '/')
6035 path++;
6036 printf("%c %s\n", status, path);
6037 return NULL;
6040 struct choose_patch_arg {
6041 FILE *patch_script_file;
6042 const char *action;
6045 static const struct got_error *
6046 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6047 int nchanges, const char *action)
6049 char *line = NULL;
6050 size_t linesize = 0;
6051 ssize_t linelen;
6053 switch (status) {
6054 case GOT_STATUS_ADD:
6055 printf("A %s\n%s this addition? [y/n] ", path, action);
6056 break;
6057 case GOT_STATUS_DELETE:
6058 printf("D %s\n%s this deletion? [y/n] ", path, action);
6059 break;
6060 case GOT_STATUS_MODIFY:
6061 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6062 return got_error_from_errno("fseek");
6063 printf(GOT_COMMIT_SEP_STR);
6064 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6065 printf("%s", line);
6066 if (ferror(patch_file))
6067 return got_error_from_errno("getline");
6068 printf(GOT_COMMIT_SEP_STR);
6069 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6070 path, n, nchanges, action);
6071 break;
6072 default:
6073 return got_error_path(path, GOT_ERR_FILE_STATUS);
6076 return NULL;
6079 static const struct got_error *
6080 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6081 FILE *patch_file, int n, int nchanges)
6083 const struct got_error *err = NULL;
6084 char *line = NULL;
6085 size_t linesize = 0;
6086 ssize_t linelen;
6087 int resp = ' ';
6088 struct choose_patch_arg *a = arg;
6090 *choice = GOT_PATCH_CHOICE_NONE;
6092 if (a->patch_script_file) {
6093 char *nl;
6094 err = show_change(status, path, patch_file, n, nchanges,
6095 a->action);
6096 if (err)
6097 return err;
6098 linelen = getline(&line, &linesize, a->patch_script_file);
6099 if (linelen == -1) {
6100 if (ferror(a->patch_script_file))
6101 return got_error_from_errno("getline");
6102 return NULL;
6104 nl = strchr(line, '\n');
6105 if (nl)
6106 *nl = '\0';
6107 if (strcmp(line, "y") == 0) {
6108 *choice = GOT_PATCH_CHOICE_YES;
6109 printf("y\n");
6110 } else if (strcmp(line, "n") == 0) {
6111 *choice = GOT_PATCH_CHOICE_NO;
6112 printf("n\n");
6113 } else if (strcmp(line, "q") == 0 &&
6114 status == GOT_STATUS_MODIFY) {
6115 *choice = GOT_PATCH_CHOICE_QUIT;
6116 printf("q\n");
6117 } else
6118 printf("invalid response '%s'\n", line);
6119 free(line);
6120 return NULL;
6123 while (resp != 'y' && resp != 'n' && resp != 'q') {
6124 err = show_change(status, path, patch_file, n, nchanges,
6125 a->action);
6126 if (err)
6127 return err;
6128 resp = getchar();
6129 if (resp == '\n')
6130 resp = getchar();
6131 if (status == GOT_STATUS_MODIFY) {
6132 if (resp != 'y' && resp != 'n' && resp != 'q') {
6133 printf("invalid response '%c'\n", resp);
6134 resp = ' ';
6136 } else if (resp != 'y' && resp != 'n') {
6137 printf("invalid response '%c'\n", resp);
6138 resp = ' ';
6142 if (resp == 'y')
6143 *choice = GOT_PATCH_CHOICE_YES;
6144 else if (resp == 'n')
6145 *choice = GOT_PATCH_CHOICE_NO;
6146 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6147 *choice = GOT_PATCH_CHOICE_QUIT;
6149 return NULL;
6153 static const struct got_error *
6154 cmd_revert(int argc, char *argv[])
6156 const struct got_error *error = NULL;
6157 struct got_worktree *worktree = NULL;
6158 struct got_repository *repo = NULL;
6159 char *cwd = NULL, *path = NULL;
6160 struct got_pathlist_head paths;
6161 struct got_pathlist_entry *pe;
6162 int ch, can_recurse = 0, pflag = 0;
6163 FILE *patch_script_file = NULL;
6164 const char *patch_script_path = NULL;
6165 struct choose_patch_arg cpa;
6167 TAILQ_INIT(&paths);
6169 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6170 switch (ch) {
6171 case 'p':
6172 pflag = 1;
6173 break;
6174 case 'F':
6175 patch_script_path = optarg;
6176 break;
6177 case 'R':
6178 can_recurse = 1;
6179 break;
6180 default:
6181 usage_revert();
6182 /* NOTREACHED */
6186 argc -= optind;
6187 argv += optind;
6189 #ifndef PROFILE
6190 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6191 "unveil", NULL) == -1)
6192 err(1, "pledge");
6193 #endif
6194 if (argc < 1)
6195 usage_revert();
6196 if (patch_script_path && !pflag)
6197 errx(1, "-F option can only be used together with -p option");
6199 cwd = getcwd(NULL, 0);
6200 if (cwd == NULL) {
6201 error = got_error_from_errno("getcwd");
6202 goto done;
6204 error = got_worktree_open(&worktree, cwd);
6205 if (error) {
6206 if (error->code == GOT_ERR_NOT_WORKTREE)
6207 error = wrap_not_worktree_error(error, "revert", cwd);
6208 goto done;
6211 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6212 NULL);
6213 if (error != NULL)
6214 goto done;
6216 if (patch_script_path) {
6217 patch_script_file = fopen(patch_script_path, "r");
6218 if (patch_script_file == NULL) {
6219 error = got_error_from_errno2("fopen",
6220 patch_script_path);
6221 goto done;
6224 error = apply_unveil(got_repo_get_path(repo), 1,
6225 got_worktree_get_root_path(worktree));
6226 if (error)
6227 goto done;
6229 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6230 if (error)
6231 goto done;
6233 if (!can_recurse) {
6234 char *ondisk_path;
6235 struct stat sb;
6236 TAILQ_FOREACH(pe, &paths, entry) {
6237 if (asprintf(&ondisk_path, "%s/%s",
6238 got_worktree_get_root_path(worktree),
6239 pe->path) == -1) {
6240 error = got_error_from_errno("asprintf");
6241 goto done;
6243 if (lstat(ondisk_path, &sb) == -1) {
6244 if (errno == ENOENT) {
6245 free(ondisk_path);
6246 continue;
6248 error = got_error_from_errno2("lstat",
6249 ondisk_path);
6250 free(ondisk_path);
6251 goto done;
6253 free(ondisk_path);
6254 if (S_ISDIR(sb.st_mode)) {
6255 error = got_error_msg(GOT_ERR_BAD_PATH,
6256 "reverting directories requires -R option");
6257 goto done;
6262 cpa.patch_script_file = patch_script_file;
6263 cpa.action = "revert";
6264 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6265 pflag ? choose_patch : NULL, &cpa, repo);
6266 done:
6267 if (patch_script_file && fclose(patch_script_file) == EOF &&
6268 error == NULL)
6269 error = got_error_from_errno2("fclose", patch_script_path);
6270 if (repo)
6271 got_repo_close(repo);
6272 if (worktree)
6273 got_worktree_close(worktree);
6274 free(path);
6275 free(cwd);
6276 return error;
6279 __dead static void
6280 usage_commit(void)
6282 fprintf(stderr, "usage: %s commit [-m msg] [path ...]\n",
6283 getprogname());
6284 exit(1);
6287 struct collect_commit_logmsg_arg {
6288 const char *cmdline_log;
6289 const char *editor;
6290 const char *worktree_path;
6291 const char *branch_name;
6292 const char *repo_path;
6293 char *logmsg_path;
6297 static const struct got_error *
6298 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6299 void *arg)
6301 char *initial_content = NULL;
6302 struct got_pathlist_entry *pe;
6303 const struct got_error *err = NULL;
6304 char *template = NULL;
6305 struct collect_commit_logmsg_arg *a = arg;
6306 int fd;
6307 size_t len;
6309 /* if a message was specified on the command line, just use it */
6310 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6311 len = strlen(a->cmdline_log) + 1;
6312 *logmsg = malloc(len + 1);
6313 if (*logmsg == NULL)
6314 return got_error_from_errno("malloc");
6315 strlcpy(*logmsg, a->cmdline_log, len);
6316 return NULL;
6319 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6320 return got_error_from_errno("asprintf");
6322 if (asprintf(&initial_content,
6323 "\n# changes to be committed on branch %s:\n",
6324 a->branch_name) == -1)
6325 return got_error_from_errno("asprintf");
6327 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6328 if (err)
6329 goto done;
6331 dprintf(fd, initial_content);
6333 TAILQ_FOREACH(pe, commitable_paths, entry) {
6334 struct got_commitable *ct = pe->data;
6335 dprintf(fd, "# %c %s\n",
6336 got_commitable_get_status(ct),
6337 got_commitable_get_path(ct));
6339 close(fd);
6341 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
6342 done:
6343 free(initial_content);
6344 free(template);
6346 /* Editor is done; we can now apply unveil(2) */
6347 if (err == NULL) {
6348 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6349 if (err) {
6350 free(*logmsg);
6351 *logmsg = NULL;
6354 return err;
6357 static const struct got_error *
6358 cmd_commit(int argc, char *argv[])
6360 const struct got_error *error = NULL;
6361 struct got_worktree *worktree = NULL;
6362 struct got_repository *repo = NULL;
6363 char *cwd = NULL, *id_str = NULL;
6364 struct got_object_id *id = NULL;
6365 const char *logmsg = NULL;
6366 struct collect_commit_logmsg_arg cl_arg;
6367 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6368 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6369 struct got_pathlist_head paths;
6371 TAILQ_INIT(&paths);
6372 cl_arg.logmsg_path = NULL;
6374 while ((ch = getopt(argc, argv, "m:")) != -1) {
6375 switch (ch) {
6376 case 'm':
6377 logmsg = optarg;
6378 break;
6379 default:
6380 usage_commit();
6381 /* NOTREACHED */
6385 argc -= optind;
6386 argv += optind;
6388 #ifndef PROFILE
6389 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6390 "unveil", NULL) == -1)
6391 err(1, "pledge");
6392 #endif
6393 cwd = getcwd(NULL, 0);
6394 if (cwd == NULL) {
6395 error = got_error_from_errno("getcwd");
6396 goto done;
6398 error = got_worktree_open(&worktree, cwd);
6399 if (error) {
6400 if (error->code == GOT_ERR_NOT_WORKTREE)
6401 error = wrap_not_worktree_error(error, "commit", cwd);
6402 goto done;
6405 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6406 if (error)
6407 goto done;
6408 if (rebase_in_progress) {
6409 error = got_error(GOT_ERR_REBASING);
6410 goto done;
6413 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6414 worktree);
6415 if (error)
6416 goto done;
6418 error = get_gitconfig_path(&gitconfig_path);
6419 if (error)
6420 goto done;
6421 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6422 gitconfig_path);
6423 if (error != NULL)
6424 goto done;
6426 error = get_author(&author, repo);
6427 if (error)
6428 return error;
6431 * unveil(2) traverses exec(2); if an editor is used we have
6432 * to apply unveil after the log message has been written.
6434 if (logmsg == NULL || strlen(logmsg) == 0)
6435 error = get_editor(&editor);
6436 else
6437 error = apply_unveil(got_repo_get_path(repo), 0,
6438 got_worktree_get_root_path(worktree));
6439 if (error)
6440 goto done;
6442 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6443 if (error)
6444 goto done;
6446 cl_arg.editor = editor;
6447 cl_arg.cmdline_log = logmsg;
6448 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6449 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6450 if (!histedit_in_progress) {
6451 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6452 error = got_error(GOT_ERR_COMMIT_BRANCH);
6453 goto done;
6455 cl_arg.branch_name += 11;
6457 cl_arg.repo_path = got_repo_get_path(repo);
6458 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6459 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
6460 if (error) {
6461 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6462 cl_arg.logmsg_path != NULL)
6463 preserve_logmsg = 1;
6464 goto done;
6467 error = got_object_id_str(&id_str, id);
6468 if (error)
6469 goto done;
6470 printf("Created commit %s\n", id_str);
6471 done:
6472 if (preserve_logmsg) {
6473 fprintf(stderr, "%s: log message preserved in %s\n",
6474 getprogname(), cl_arg.logmsg_path);
6475 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6476 error == NULL)
6477 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6478 free(cl_arg.logmsg_path);
6479 if (repo)
6480 got_repo_close(repo);
6481 if (worktree)
6482 got_worktree_close(worktree);
6483 free(cwd);
6484 free(id_str);
6485 free(gitconfig_path);
6486 free(editor);
6487 free(author);
6488 return error;
6491 __dead static void
6492 usage_cherrypick(void)
6494 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6495 exit(1);
6498 static const struct got_error *
6499 cmd_cherrypick(int argc, char *argv[])
6501 const struct got_error *error = NULL;
6502 struct got_worktree *worktree = NULL;
6503 struct got_repository *repo = NULL;
6504 char *cwd = NULL, *commit_id_str = NULL;
6505 struct got_object_id *commit_id = NULL;
6506 struct got_commit_object *commit = NULL;
6507 struct got_object_qid *pid;
6508 struct got_reference *head_ref = NULL;
6509 int ch;
6510 struct got_update_progress_arg upa;
6512 while ((ch = getopt(argc, argv, "")) != -1) {
6513 switch (ch) {
6514 default:
6515 usage_cherrypick();
6516 /* NOTREACHED */
6520 argc -= optind;
6521 argv += optind;
6523 #ifndef PROFILE
6524 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6525 "unveil", NULL) == -1)
6526 err(1, "pledge");
6527 #endif
6528 if (argc != 1)
6529 usage_cherrypick();
6531 cwd = getcwd(NULL, 0);
6532 if (cwd == NULL) {
6533 error = got_error_from_errno("getcwd");
6534 goto done;
6536 error = got_worktree_open(&worktree, cwd);
6537 if (error) {
6538 if (error->code == GOT_ERR_NOT_WORKTREE)
6539 error = wrap_not_worktree_error(error, "cherrypick",
6540 cwd);
6541 goto done;
6544 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6545 NULL);
6546 if (error != NULL)
6547 goto done;
6549 error = apply_unveil(got_repo_get_path(repo), 0,
6550 got_worktree_get_root_path(worktree));
6551 if (error)
6552 goto done;
6554 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6555 GOT_OBJ_TYPE_COMMIT, repo);
6556 if (error != NULL) {
6557 struct got_reference *ref;
6558 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6559 goto done;
6560 error = got_ref_open(&ref, repo, argv[0], 0);
6561 if (error != NULL)
6562 goto done;
6563 error = got_ref_resolve(&commit_id, repo, ref);
6564 got_ref_close(ref);
6565 if (error != NULL)
6566 goto done;
6568 error = got_object_id_str(&commit_id_str, commit_id);
6569 if (error)
6570 goto done;
6572 error = got_ref_open(&head_ref, repo,
6573 got_worktree_get_head_ref_name(worktree), 0);
6574 if (error != NULL)
6575 goto done;
6577 error = check_same_branch(commit_id, head_ref, NULL, repo);
6578 if (error) {
6579 if (error->code != GOT_ERR_ANCESTRY)
6580 goto done;
6581 error = NULL;
6582 } else {
6583 error = got_error(GOT_ERR_SAME_BRANCH);
6584 goto done;
6587 error = got_object_open_as_commit(&commit, repo, commit_id);
6588 if (error)
6589 goto done;
6590 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6591 memset(&upa, 0, sizeof(upa));
6592 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
6593 commit_id, repo, update_progress, &upa, check_cancelled,
6594 NULL);
6595 if (error != NULL)
6596 goto done;
6598 if (upa.did_something)
6599 printf("Merged commit %s\n", commit_id_str);
6600 print_update_progress_stats(&upa);
6601 done:
6602 if (commit)
6603 got_object_commit_close(commit);
6604 free(commit_id_str);
6605 if (head_ref)
6606 got_ref_close(head_ref);
6607 if (worktree)
6608 got_worktree_close(worktree);
6609 if (repo)
6610 got_repo_close(repo);
6611 return error;
6614 __dead static void
6615 usage_backout(void)
6617 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
6618 exit(1);
6621 static const struct got_error *
6622 cmd_backout(int argc, char *argv[])
6624 const struct got_error *error = NULL;
6625 struct got_worktree *worktree = NULL;
6626 struct got_repository *repo = NULL;
6627 char *cwd = NULL, *commit_id_str = NULL;
6628 struct got_object_id *commit_id = NULL;
6629 struct got_commit_object *commit = NULL;
6630 struct got_object_qid *pid;
6631 struct got_reference *head_ref = NULL;
6632 int ch;
6633 struct got_update_progress_arg upa;
6635 while ((ch = getopt(argc, argv, "")) != -1) {
6636 switch (ch) {
6637 default:
6638 usage_backout();
6639 /* NOTREACHED */
6643 argc -= optind;
6644 argv += optind;
6646 #ifndef PROFILE
6647 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6648 "unveil", NULL) == -1)
6649 err(1, "pledge");
6650 #endif
6651 if (argc != 1)
6652 usage_backout();
6654 cwd = getcwd(NULL, 0);
6655 if (cwd == NULL) {
6656 error = got_error_from_errno("getcwd");
6657 goto done;
6659 error = got_worktree_open(&worktree, cwd);
6660 if (error) {
6661 if (error->code == GOT_ERR_NOT_WORKTREE)
6662 error = wrap_not_worktree_error(error, "backout", cwd);
6663 goto done;
6666 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6667 NULL);
6668 if (error != NULL)
6669 goto done;
6671 error = apply_unveil(got_repo_get_path(repo), 0,
6672 got_worktree_get_root_path(worktree));
6673 if (error)
6674 goto done;
6676 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6677 GOT_OBJ_TYPE_COMMIT, repo);
6678 if (error != NULL) {
6679 struct got_reference *ref;
6680 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6681 goto done;
6682 error = got_ref_open(&ref, repo, argv[0], 0);
6683 if (error != NULL)
6684 goto done;
6685 error = got_ref_resolve(&commit_id, repo, ref);
6686 got_ref_close(ref);
6687 if (error != NULL)
6688 goto done;
6690 error = got_object_id_str(&commit_id_str, commit_id);
6691 if (error)
6692 goto done;
6694 error = got_ref_open(&head_ref, repo,
6695 got_worktree_get_head_ref_name(worktree), 0);
6696 if (error != NULL)
6697 goto done;
6699 error = check_same_branch(commit_id, head_ref, NULL, repo);
6700 if (error)
6701 goto done;
6703 error = got_object_open_as_commit(&commit, repo, commit_id);
6704 if (error)
6705 goto done;
6706 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6707 if (pid == NULL) {
6708 error = got_error(GOT_ERR_ROOT_COMMIT);
6709 goto done;
6712 memset(&upa, 0, sizeof(upa));
6713 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
6714 update_progress, &upa, check_cancelled, NULL);
6715 if (error != NULL)
6716 goto done;
6718 if (upa.did_something)
6719 printf("Backed out commit %s\n", commit_id_str);
6720 print_update_progress_stats(&upa);
6721 done:
6722 if (commit)
6723 got_object_commit_close(commit);
6724 free(commit_id_str);
6725 if (head_ref)
6726 got_ref_close(head_ref);
6727 if (worktree)
6728 got_worktree_close(worktree);
6729 if (repo)
6730 got_repo_close(repo);
6731 return error;
6734 __dead static void
6735 usage_rebase(void)
6737 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
6738 getprogname());
6739 exit(1);
6742 void
6743 trim_logmsg(char *logmsg, int limit)
6745 char *nl;
6746 size_t len;
6748 len = strlen(logmsg);
6749 if (len > limit)
6750 len = limit;
6751 logmsg[len] = '\0';
6752 nl = strchr(logmsg, '\n');
6753 if (nl)
6754 *nl = '\0';
6757 static const struct got_error *
6758 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
6760 const struct got_error *err;
6761 char *logmsg0 = NULL;
6762 const char *s;
6764 err = got_object_commit_get_logmsg(&logmsg0, commit);
6765 if (err)
6766 return err;
6768 s = logmsg0;
6769 while (isspace((unsigned char)s[0]))
6770 s++;
6772 *logmsg = strdup(s);
6773 if (*logmsg == NULL) {
6774 err = got_error_from_errno("strdup");
6775 goto done;
6778 trim_logmsg(*logmsg, limit);
6779 done:
6780 free(logmsg0);
6781 return err;
6784 static const struct got_error *
6785 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
6787 const struct got_error *err;
6788 struct got_commit_object *commit = NULL;
6789 char *id_str = NULL, *logmsg = NULL;
6791 err = got_object_open_as_commit(&commit, repo, id);
6792 if (err)
6793 return err;
6795 err = got_object_id_str(&id_str, id);
6796 if (err)
6797 goto done;
6799 id_str[12] = '\0';
6801 err = get_short_logmsg(&logmsg, 42, commit);
6802 if (err)
6803 goto done;
6805 printf("%s -> merge conflict: %s\n", id_str, logmsg);
6806 done:
6807 free(id_str);
6808 got_object_commit_close(commit);
6809 free(logmsg);
6810 return err;
6813 static const struct got_error *
6814 show_rebase_progress(struct got_commit_object *commit,
6815 struct got_object_id *old_id, struct got_object_id *new_id)
6817 const struct got_error *err;
6818 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
6820 err = got_object_id_str(&old_id_str, old_id);
6821 if (err)
6822 goto done;
6824 if (new_id) {
6825 err = got_object_id_str(&new_id_str, new_id);
6826 if (err)
6827 goto done;
6830 old_id_str[12] = '\0';
6831 if (new_id_str)
6832 new_id_str[12] = '\0';
6834 err = get_short_logmsg(&logmsg, 42, commit);
6835 if (err)
6836 goto done;
6838 printf("%s -> %s: %s\n", old_id_str,
6839 new_id_str ? new_id_str : "no-op change", logmsg);
6840 done:
6841 free(old_id_str);
6842 free(new_id_str);
6843 free(logmsg);
6844 return err;
6847 static const struct got_error *
6848 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
6849 struct got_reference *branch, struct got_reference *new_base_branch,
6850 struct got_reference *tmp_branch, struct got_repository *repo)
6852 printf("Switching work tree to %s\n", got_ref_get_name(branch));
6853 return got_worktree_rebase_complete(worktree, fileindex,
6854 new_base_branch, tmp_branch, branch, repo);
6857 static const struct got_error *
6858 rebase_commit(struct got_pathlist_head *merged_paths,
6859 struct got_worktree *worktree, struct got_fileindex *fileindex,
6860 struct got_reference *tmp_branch,
6861 struct got_object_id *commit_id, struct got_repository *repo)
6863 const struct got_error *error;
6864 struct got_commit_object *commit;
6865 struct got_object_id *new_commit_id;
6867 error = got_object_open_as_commit(&commit, repo, commit_id);
6868 if (error)
6869 return error;
6871 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
6872 worktree, fileindex, tmp_branch, commit, commit_id, repo);
6873 if (error) {
6874 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
6875 goto done;
6876 error = show_rebase_progress(commit, commit_id, NULL);
6877 } else {
6878 error = show_rebase_progress(commit, commit_id, new_commit_id);
6879 free(new_commit_id);
6881 done:
6882 got_object_commit_close(commit);
6883 return error;
6886 struct check_path_prefix_arg {
6887 const char *path_prefix;
6888 size_t len;
6889 int errcode;
6892 static const struct got_error *
6893 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
6894 struct got_blob_object *blob2, struct got_object_id *id1,
6895 struct got_object_id *id2, const char *path1, const char *path2,
6896 mode_t mode1, mode_t mode2, struct got_repository *repo)
6898 struct check_path_prefix_arg *a = arg;
6900 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
6901 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
6902 return got_error(a->errcode);
6904 return NULL;
6907 static const struct got_error *
6908 check_path_prefix(struct got_object_id *parent_id,
6909 struct got_object_id *commit_id, const char *path_prefix,
6910 int errcode, struct got_repository *repo)
6912 const struct got_error *err;
6913 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
6914 struct got_commit_object *commit = NULL, *parent_commit = NULL;
6915 struct check_path_prefix_arg cpp_arg;
6917 if (got_path_is_root_dir(path_prefix))
6918 return NULL;
6920 err = got_object_open_as_commit(&commit, repo, commit_id);
6921 if (err)
6922 goto done;
6924 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
6925 if (err)
6926 goto done;
6928 err = got_object_open_as_tree(&tree1, repo,
6929 got_object_commit_get_tree_id(parent_commit));
6930 if (err)
6931 goto done;
6933 err = got_object_open_as_tree(&tree2, repo,
6934 got_object_commit_get_tree_id(commit));
6935 if (err)
6936 goto done;
6938 cpp_arg.path_prefix = path_prefix;
6939 while (cpp_arg.path_prefix[0] == '/')
6940 cpp_arg.path_prefix++;
6941 cpp_arg.len = strlen(cpp_arg.path_prefix);
6942 cpp_arg.errcode = errcode;
6943 err = got_diff_tree(tree1, tree2, "", "", repo,
6944 check_path_prefix_in_diff, &cpp_arg, 0);
6945 done:
6946 if (tree1)
6947 got_object_tree_close(tree1);
6948 if (tree2)
6949 got_object_tree_close(tree2);
6950 if (commit)
6951 got_object_commit_close(commit);
6952 if (parent_commit)
6953 got_object_commit_close(parent_commit);
6954 return err;
6957 static const struct got_error *
6958 collect_commits(struct got_object_id_queue *commits,
6959 struct got_object_id *initial_commit_id,
6960 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
6961 const char *path_prefix, int path_prefix_errcode,
6962 struct got_repository *repo)
6964 const struct got_error *err = NULL;
6965 struct got_commit_graph *graph = NULL;
6966 struct got_object_id *parent_id = NULL;
6967 struct got_object_qid *qid;
6968 struct got_object_id *commit_id = initial_commit_id;
6970 err = got_commit_graph_open(&graph, "/", 1);
6971 if (err)
6972 return err;
6974 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
6975 check_cancelled, NULL);
6976 if (err)
6977 goto done;
6978 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
6979 err = got_commit_graph_iter_next(&parent_id, graph, repo,
6980 check_cancelled, NULL);
6981 if (err) {
6982 if (err->code == GOT_ERR_ITER_COMPLETED) {
6983 err = got_error_msg(GOT_ERR_ANCESTRY,
6984 "ran out of commits to rebase before "
6985 "youngest common ancestor commit has "
6986 "been reached?!?");
6988 goto done;
6989 } else {
6990 err = check_path_prefix(parent_id, commit_id,
6991 path_prefix, path_prefix_errcode, repo);
6992 if (err)
6993 goto done;
6995 err = got_object_qid_alloc(&qid, commit_id);
6996 if (err)
6997 goto done;
6998 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
6999 commit_id = parent_id;
7002 done:
7003 got_commit_graph_close(graph);
7004 return err;
7007 static const struct got_error *
7008 cmd_rebase(int argc, char *argv[])
7010 const struct got_error *error = NULL;
7011 struct got_worktree *worktree = NULL;
7012 struct got_repository *repo = NULL;
7013 struct got_fileindex *fileindex = NULL;
7014 char *cwd = NULL;
7015 struct got_reference *branch = NULL;
7016 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
7017 struct got_object_id *commit_id = NULL, *parent_id = NULL;
7018 struct got_object_id *resume_commit_id = NULL;
7019 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
7020 struct got_commit_object *commit = NULL;
7021 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
7022 int histedit_in_progress = 0;
7023 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7024 struct got_object_id_queue commits;
7025 struct got_pathlist_head merged_paths;
7026 const struct got_object_id_queue *parent_ids;
7027 struct got_object_qid *qid, *pid;
7029 SIMPLEQ_INIT(&commits);
7030 TAILQ_INIT(&merged_paths);
7032 while ((ch = getopt(argc, argv, "ac")) != -1) {
7033 switch (ch) {
7034 case 'a':
7035 abort_rebase = 1;
7036 break;
7037 case 'c':
7038 continue_rebase = 1;
7039 break;
7040 default:
7041 usage_rebase();
7042 /* NOTREACHED */
7046 argc -= optind;
7047 argv += optind;
7049 #ifndef PROFILE
7050 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7051 "unveil", NULL) == -1)
7052 err(1, "pledge");
7053 #endif
7054 if (abort_rebase && continue_rebase)
7055 usage_rebase();
7056 else if (abort_rebase || continue_rebase) {
7057 if (argc != 0)
7058 usage_rebase();
7059 } else if (argc != 1)
7060 usage_rebase();
7062 cwd = getcwd(NULL, 0);
7063 if (cwd == NULL) {
7064 error = got_error_from_errno("getcwd");
7065 goto done;
7067 error = got_worktree_open(&worktree, cwd);
7068 if (error) {
7069 if (error->code == GOT_ERR_NOT_WORKTREE)
7070 error = wrap_not_worktree_error(error, "rebase", cwd);
7071 goto done;
7074 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7075 NULL);
7076 if (error != NULL)
7077 goto done;
7079 error = apply_unveil(got_repo_get_path(repo), 0,
7080 got_worktree_get_root_path(worktree));
7081 if (error)
7082 goto done;
7084 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7085 worktree);
7086 if (error)
7087 goto done;
7088 if (histedit_in_progress) {
7089 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7090 goto done;
7093 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7094 if (error)
7095 goto done;
7097 if (abort_rebase) {
7098 struct got_update_progress_arg upa;
7099 if (!rebase_in_progress) {
7100 error = got_error(GOT_ERR_NOT_REBASING);
7101 goto done;
7103 error = got_worktree_rebase_continue(&resume_commit_id,
7104 &new_base_branch, &tmp_branch, &branch, &fileindex,
7105 worktree, repo);
7106 if (error)
7107 goto done;
7108 printf("Switching work tree to %s\n",
7109 got_ref_get_symref_target(new_base_branch));
7110 memset(&upa, 0, sizeof(upa));
7111 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7112 new_base_branch, update_progress, &upa);
7113 if (error)
7114 goto done;
7115 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7116 print_update_progress_stats(&upa);
7117 goto done; /* nothing else to do */
7120 if (continue_rebase) {
7121 if (!rebase_in_progress) {
7122 error = got_error(GOT_ERR_NOT_REBASING);
7123 goto done;
7125 error = got_worktree_rebase_continue(&resume_commit_id,
7126 &new_base_branch, &tmp_branch, &branch, &fileindex,
7127 worktree, repo);
7128 if (error)
7129 goto done;
7131 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7132 resume_commit_id, repo);
7133 if (error)
7134 goto done;
7136 yca_id = got_object_id_dup(resume_commit_id);
7137 if (yca_id == NULL) {
7138 error = got_error_from_errno("got_object_id_dup");
7139 goto done;
7141 } else {
7142 error = got_ref_open(&branch, repo, argv[0], 0);
7143 if (error != NULL)
7144 goto done;
7147 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7148 if (error)
7149 goto done;
7151 if (!continue_rebase) {
7152 struct got_object_id *base_commit_id;
7154 base_commit_id = got_worktree_get_base_commit_id(worktree);
7155 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7156 base_commit_id, branch_head_commit_id, repo,
7157 check_cancelled, NULL);
7158 if (error)
7159 goto done;
7160 if (yca_id == NULL) {
7161 error = got_error_msg(GOT_ERR_ANCESTRY,
7162 "specified branch shares no common ancestry "
7163 "with work tree's branch");
7164 goto done;
7167 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7168 if (error) {
7169 if (error->code != GOT_ERR_ANCESTRY)
7170 goto done;
7171 error = NULL;
7172 } else {
7173 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7174 "specified branch resolves to a commit which "
7175 "is already contained in work tree's branch");
7176 goto done;
7178 error = got_worktree_rebase_prepare(&new_base_branch,
7179 &tmp_branch, &fileindex, worktree, branch, repo);
7180 if (error)
7181 goto done;
7184 commit_id = branch_head_commit_id;
7185 error = got_object_open_as_commit(&commit, repo, commit_id);
7186 if (error)
7187 goto done;
7189 parent_ids = got_object_commit_get_parent_ids(commit);
7190 pid = SIMPLEQ_FIRST(parent_ids);
7191 if (pid == NULL) {
7192 if (!continue_rebase) {
7193 struct got_update_progress_arg upa;
7194 memset(&upa, 0, sizeof(upa));
7195 error = got_worktree_rebase_abort(worktree, fileindex,
7196 repo, new_base_branch, update_progress, &upa);
7197 if (error)
7198 goto done;
7199 printf("Rebase of %s aborted\n",
7200 got_ref_get_name(branch));
7201 print_update_progress_stats(&upa);
7204 error = got_error(GOT_ERR_EMPTY_REBASE);
7205 goto done;
7207 error = collect_commits(&commits, commit_id, pid->id,
7208 yca_id, got_worktree_get_path_prefix(worktree),
7209 GOT_ERR_REBASE_PATH, repo);
7210 got_object_commit_close(commit);
7211 commit = NULL;
7212 if (error)
7213 goto done;
7215 if (SIMPLEQ_EMPTY(&commits)) {
7216 if (continue_rebase) {
7217 error = rebase_complete(worktree, fileindex,
7218 branch, new_base_branch, tmp_branch, repo);
7219 goto done;
7220 } else {
7221 /* Fast-forward the reference of the branch. */
7222 struct got_object_id *new_head_commit_id;
7223 char *id_str;
7224 error = got_ref_resolve(&new_head_commit_id, repo,
7225 new_base_branch);
7226 if (error)
7227 goto done;
7228 error = got_object_id_str(&id_str, new_head_commit_id);
7229 printf("Forwarding %s to commit %s\n",
7230 got_ref_get_name(branch), id_str);
7231 free(id_str);
7232 error = got_ref_change_ref(branch,
7233 new_head_commit_id);
7234 if (error)
7235 goto done;
7239 pid = NULL;
7240 SIMPLEQ_FOREACH(qid, &commits, entry) {
7241 struct got_update_progress_arg upa;
7243 commit_id = qid->id;
7244 parent_id = pid ? pid->id : yca_id;
7245 pid = qid;
7247 memset(&upa, 0, sizeof(upa));
7248 error = got_worktree_rebase_merge_files(&merged_paths,
7249 worktree, fileindex, parent_id, commit_id, repo,
7250 update_progress, &upa, check_cancelled, NULL);
7251 if (error)
7252 goto done;
7254 print_update_progress_stats(&upa);
7255 if (upa.conflicts > 0)
7256 rebase_status = GOT_STATUS_CONFLICT;
7258 if (rebase_status == GOT_STATUS_CONFLICT) {
7259 error = show_rebase_merge_conflict(qid->id, repo);
7260 if (error)
7261 goto done;
7262 got_worktree_rebase_pathlist_free(&merged_paths);
7263 break;
7266 error = rebase_commit(&merged_paths, worktree, fileindex,
7267 tmp_branch, commit_id, repo);
7268 got_worktree_rebase_pathlist_free(&merged_paths);
7269 if (error)
7270 goto done;
7273 if (rebase_status == GOT_STATUS_CONFLICT) {
7274 error = got_worktree_rebase_postpone(worktree, fileindex);
7275 if (error)
7276 goto done;
7277 error = got_error_msg(GOT_ERR_CONFLICTS,
7278 "conflicts must be resolved before rebasing can continue");
7279 } else
7280 error = rebase_complete(worktree, fileindex, branch,
7281 new_base_branch, tmp_branch, repo);
7282 done:
7283 got_object_id_queue_free(&commits);
7284 free(branch_head_commit_id);
7285 free(resume_commit_id);
7286 free(yca_id);
7287 if (commit)
7288 got_object_commit_close(commit);
7289 if (branch)
7290 got_ref_close(branch);
7291 if (new_base_branch)
7292 got_ref_close(new_base_branch);
7293 if (tmp_branch)
7294 got_ref_close(tmp_branch);
7295 if (worktree)
7296 got_worktree_close(worktree);
7297 if (repo)
7298 got_repo_close(repo);
7299 return error;
7302 __dead static void
7303 usage_histedit(void)
7305 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
7306 getprogname());
7307 exit(1);
7310 #define GOT_HISTEDIT_PICK 'p'
7311 #define GOT_HISTEDIT_EDIT 'e'
7312 #define GOT_HISTEDIT_FOLD 'f'
7313 #define GOT_HISTEDIT_DROP 'd'
7314 #define GOT_HISTEDIT_MESG 'm'
7316 static struct got_histedit_cmd {
7317 unsigned char code;
7318 const char *name;
7319 const char *desc;
7320 } got_histedit_cmds[] = {
7321 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7322 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7323 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7324 "be used" },
7325 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7326 { GOT_HISTEDIT_MESG, "mesg",
7327 "single-line log message for commit above (open editor if empty)" },
7330 struct got_histedit_list_entry {
7331 TAILQ_ENTRY(got_histedit_list_entry) entry;
7332 struct got_object_id *commit_id;
7333 const struct got_histedit_cmd *cmd;
7334 char *logmsg;
7336 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7338 static const struct got_error *
7339 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7340 FILE *f, struct got_repository *repo)
7342 const struct got_error *err = NULL;
7343 char *logmsg = NULL, *id_str = NULL;
7344 struct got_commit_object *commit = NULL;
7345 int n;
7347 err = got_object_open_as_commit(&commit, repo, commit_id);
7348 if (err)
7349 goto done;
7351 err = get_short_logmsg(&logmsg, 34, commit);
7352 if (err)
7353 goto done;
7355 err = got_object_id_str(&id_str, commit_id);
7356 if (err)
7357 goto done;
7359 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7360 if (n < 0)
7361 err = got_ferror(f, GOT_ERR_IO);
7362 done:
7363 if (commit)
7364 got_object_commit_close(commit);
7365 free(id_str);
7366 free(logmsg);
7367 return err;
7370 static const struct got_error *
7371 histedit_write_commit_list(struct got_object_id_queue *commits,
7372 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7374 const struct got_error *err = NULL;
7375 struct got_object_qid *qid;
7377 if (SIMPLEQ_EMPTY(commits))
7378 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7380 SIMPLEQ_FOREACH(qid, commits, entry) {
7381 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7382 f, repo);
7383 if (err)
7384 break;
7385 if (edit_logmsg_only) {
7386 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7387 if (n < 0) {
7388 err = got_ferror(f, GOT_ERR_IO);
7389 break;
7394 return err;
7397 static const struct got_error *
7398 write_cmd_list(FILE *f, const char *branch_name,
7399 struct got_object_id_queue *commits)
7401 const struct got_error *err = NULL;
7402 int n, i;
7403 char *id_str;
7404 struct got_object_qid *qid;
7406 qid = SIMPLEQ_FIRST(commits);
7407 err = got_object_id_str(&id_str, qid->id);
7408 if (err)
7409 return err;
7411 n = fprintf(f,
7412 "# Editing the history of branch '%s' starting at\n"
7413 "# commit %s\n"
7414 "# Commits will be processed in order from top to "
7415 "bottom of this file.\n", branch_name, id_str);
7416 if (n < 0) {
7417 err = got_ferror(f, GOT_ERR_IO);
7418 goto done;
7421 n = fprintf(f, "# Available histedit commands:\n");
7422 if (n < 0) {
7423 err = got_ferror(f, GOT_ERR_IO);
7424 goto done;
7427 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7428 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7429 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7430 cmd->desc);
7431 if (n < 0) {
7432 err = got_ferror(f, GOT_ERR_IO);
7433 break;
7436 done:
7437 free(id_str);
7438 return err;
7441 static const struct got_error *
7442 histedit_syntax_error(int lineno)
7444 static char msg[42];
7445 int ret;
7447 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7448 lineno);
7449 if (ret == -1 || ret >= sizeof(msg))
7450 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7452 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7455 static const struct got_error *
7456 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7457 char *logmsg, struct got_repository *repo)
7459 const struct got_error *err;
7460 struct got_commit_object *folded_commit = NULL;
7461 char *id_str, *folded_logmsg = NULL;
7463 err = got_object_id_str(&id_str, hle->commit_id);
7464 if (err)
7465 return err;
7467 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7468 if (err)
7469 goto done;
7471 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7472 if (err)
7473 goto done;
7474 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7475 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7476 folded_logmsg) == -1) {
7477 err = got_error_from_errno("asprintf");
7479 done:
7480 if (folded_commit)
7481 got_object_commit_close(folded_commit);
7482 free(id_str);
7483 free(folded_logmsg);
7484 return err;
7487 static struct got_histedit_list_entry *
7488 get_folded_commits(struct got_histedit_list_entry *hle)
7490 struct got_histedit_list_entry *prev, *folded = NULL;
7492 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7493 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7494 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7495 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7496 folded = prev;
7497 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7500 return folded;
7503 static const struct got_error *
7504 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7505 struct got_repository *repo)
7507 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7508 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7509 const struct got_error *err = NULL;
7510 struct got_commit_object *commit = NULL;
7511 int fd;
7512 struct got_histedit_list_entry *folded = NULL;
7514 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7515 if (err)
7516 return err;
7518 folded = get_folded_commits(hle);
7519 if (folded) {
7520 while (folded != hle) {
7521 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7522 folded = TAILQ_NEXT(folded, entry);
7523 continue;
7525 err = append_folded_commit_msg(&new_msg, folded,
7526 logmsg, repo);
7527 if (err)
7528 goto done;
7529 free(logmsg);
7530 logmsg = new_msg;
7531 folded = TAILQ_NEXT(folded, entry);
7535 err = got_object_id_str(&id_str, hle->commit_id);
7536 if (err)
7537 goto done;
7538 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7539 if (err)
7540 goto done;
7541 if (asprintf(&new_msg,
7542 "%s\n# original log message of commit %s: %s",
7543 logmsg ? logmsg : "", id_str, orig_logmsg) == -1) {
7544 err = got_error_from_errno("asprintf");
7545 goto done;
7547 free(logmsg);
7548 logmsg = new_msg;
7550 err = got_object_id_str(&id_str, hle->commit_id);
7551 if (err)
7552 goto done;
7554 err = got_opentemp_named_fd(&logmsg_path, &fd,
7555 GOT_TMPDIR_STR "/got-logmsg");
7556 if (err)
7557 goto done;
7559 dprintf(fd, logmsg);
7560 close(fd);
7562 err = get_editor(&editor);
7563 if (err)
7564 goto done;
7566 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
7567 if (err) {
7568 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
7569 goto done;
7570 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
7572 done:
7573 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
7574 err = got_error_from_errno2("unlink", logmsg_path);
7575 free(logmsg_path);
7576 free(logmsg);
7577 free(orig_logmsg);
7578 free(editor);
7579 if (commit)
7580 got_object_commit_close(commit);
7581 return err;
7584 static const struct got_error *
7585 histedit_parse_list(struct got_histedit_list *histedit_cmds,
7586 FILE *f, struct got_repository *repo)
7588 const struct got_error *err = NULL;
7589 char *line = NULL, *p, *end;
7590 size_t size;
7591 ssize_t len;
7592 int lineno = 0, i;
7593 const struct got_histedit_cmd *cmd;
7594 struct got_object_id *commit_id = NULL;
7595 struct got_histedit_list_entry *hle = NULL;
7597 for (;;) {
7598 len = getline(&line, &size, f);
7599 if (len == -1) {
7600 const struct got_error *getline_err;
7601 if (feof(f))
7602 break;
7603 getline_err = got_error_from_errno("getline");
7604 err = got_ferror(f, getline_err->code);
7605 break;
7607 lineno++;
7608 p = line;
7609 while (isspace((unsigned char)p[0]))
7610 p++;
7611 if (p[0] == '#' || p[0] == '\0') {
7612 free(line);
7613 line = NULL;
7614 continue;
7616 cmd = NULL;
7617 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7618 cmd = &got_histedit_cmds[i];
7619 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
7620 isspace((unsigned char)p[strlen(cmd->name)])) {
7621 p += strlen(cmd->name);
7622 break;
7624 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
7625 p++;
7626 break;
7629 if (i == nitems(got_histedit_cmds)) {
7630 err = histedit_syntax_error(lineno);
7631 break;
7633 while (isspace((unsigned char)p[0]))
7634 p++;
7635 if (cmd->code == GOT_HISTEDIT_MESG) {
7636 if (hle == NULL || hle->logmsg != NULL) {
7637 err = got_error(GOT_ERR_HISTEDIT_CMD);
7638 break;
7640 if (p[0] == '\0') {
7641 err = histedit_edit_logmsg(hle, repo);
7642 if (err)
7643 break;
7644 } else {
7645 hle->logmsg = strdup(p);
7646 if (hle->logmsg == NULL) {
7647 err = got_error_from_errno("strdup");
7648 break;
7651 free(line);
7652 line = NULL;
7653 continue;
7654 } else {
7655 end = p;
7656 while (end[0] && !isspace((unsigned char)end[0]))
7657 end++;
7658 *end = '\0';
7660 err = got_object_resolve_id_str(&commit_id, repo, p);
7661 if (err) {
7662 /* override error code */
7663 err = histedit_syntax_error(lineno);
7664 break;
7667 hle = malloc(sizeof(*hle));
7668 if (hle == NULL) {
7669 err = got_error_from_errno("malloc");
7670 break;
7672 hle->cmd = cmd;
7673 hle->commit_id = commit_id;
7674 hle->logmsg = NULL;
7675 commit_id = NULL;
7676 free(line);
7677 line = NULL;
7678 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
7681 free(line);
7682 free(commit_id);
7683 return err;
7686 static const struct got_error *
7687 histedit_check_script(struct got_histedit_list *histedit_cmds,
7688 struct got_object_id_queue *commits, struct got_repository *repo)
7690 const struct got_error *err = NULL;
7691 struct got_object_qid *qid;
7692 struct got_histedit_list_entry *hle;
7693 static char msg[92];
7694 char *id_str;
7696 if (TAILQ_EMPTY(histedit_cmds))
7697 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
7698 "histedit script contains no commands");
7699 if (SIMPLEQ_EMPTY(commits))
7700 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7702 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7703 struct got_histedit_list_entry *hle2;
7704 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
7705 if (hle == hle2)
7706 continue;
7707 if (got_object_id_cmp(hle->commit_id,
7708 hle2->commit_id) != 0)
7709 continue;
7710 err = got_object_id_str(&id_str, hle->commit_id);
7711 if (err)
7712 return err;
7713 snprintf(msg, sizeof(msg), "commit %s is listed "
7714 "more than once in histedit script", id_str);
7715 free(id_str);
7716 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7720 SIMPLEQ_FOREACH(qid, commits, entry) {
7721 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7722 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
7723 break;
7725 if (hle == NULL) {
7726 err = got_object_id_str(&id_str, qid->id);
7727 if (err)
7728 return err;
7729 snprintf(msg, sizeof(msg),
7730 "commit %s missing from histedit script", id_str);
7731 free(id_str);
7732 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7736 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
7737 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
7738 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
7739 "last commit in histedit script cannot be folded");
7741 return NULL;
7744 static const struct got_error *
7745 histedit_run_editor(struct got_histedit_list *histedit_cmds,
7746 const char *path, struct got_object_id_queue *commits,
7747 struct got_repository *repo)
7749 const struct got_error *err = NULL;
7750 char *editor;
7751 FILE *f = NULL;
7753 err = get_editor(&editor);
7754 if (err)
7755 return err;
7757 if (spawn_editor(editor, path) == -1) {
7758 err = got_error_from_errno("failed spawning editor");
7759 goto done;
7762 f = fopen(path, "r");
7763 if (f == NULL) {
7764 err = got_error_from_errno("fopen");
7765 goto done;
7767 err = histedit_parse_list(histedit_cmds, f, repo);
7768 if (err)
7769 goto done;
7771 err = histedit_check_script(histedit_cmds, commits, repo);
7772 done:
7773 if (f && fclose(f) != 0 && err == NULL)
7774 err = got_error_from_errno("fclose");
7775 free(editor);
7776 return err;
7779 static const struct got_error *
7780 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
7781 struct got_object_id_queue *, const char *, const char *,
7782 struct got_repository *);
7784 static const struct got_error *
7785 histedit_edit_script(struct got_histedit_list *histedit_cmds,
7786 struct got_object_id_queue *commits, const char *branch_name,
7787 int edit_logmsg_only, struct got_repository *repo)
7789 const struct got_error *err;
7790 FILE *f = NULL;
7791 char *path = NULL;
7793 err = got_opentemp_named(&path, &f, "got-histedit");
7794 if (err)
7795 return err;
7797 err = write_cmd_list(f, branch_name, commits);
7798 if (err)
7799 goto done;
7801 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
7802 if (err)
7803 goto done;
7805 if (edit_logmsg_only) {
7806 rewind(f);
7807 err = histedit_parse_list(histedit_cmds, f, repo);
7808 } else {
7809 if (fclose(f) != 0) {
7810 err = got_error_from_errno("fclose");
7811 goto done;
7813 f = NULL;
7814 err = histedit_run_editor(histedit_cmds, path, commits, repo);
7815 if (err) {
7816 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7817 err->code != GOT_ERR_HISTEDIT_CMD)
7818 goto done;
7819 err = histedit_edit_list_retry(histedit_cmds, err,
7820 commits, path, branch_name, repo);
7823 done:
7824 if (f && fclose(f) != 0 && err == NULL)
7825 err = got_error_from_errno("fclose");
7826 if (path && unlink(path) != 0 && err == NULL)
7827 err = got_error_from_errno2("unlink", path);
7828 free(path);
7829 return err;
7832 static const struct got_error *
7833 histedit_save_list(struct got_histedit_list *histedit_cmds,
7834 struct got_worktree *worktree, struct got_repository *repo)
7836 const struct got_error *err = NULL;
7837 char *path = NULL;
7838 FILE *f = NULL;
7839 struct got_histedit_list_entry *hle;
7840 struct got_commit_object *commit = NULL;
7842 err = got_worktree_get_histedit_script_path(&path, worktree);
7843 if (err)
7844 return err;
7846 f = fopen(path, "w");
7847 if (f == NULL) {
7848 err = got_error_from_errno2("fopen", path);
7849 goto done;
7851 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7852 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
7853 repo);
7854 if (err)
7855 break;
7857 if (hle->logmsg) {
7858 int n = fprintf(f, "%c %s\n",
7859 GOT_HISTEDIT_MESG, hle->logmsg);
7860 if (n < 0) {
7861 err = got_ferror(f, GOT_ERR_IO);
7862 break;
7866 done:
7867 if (f && fclose(f) != 0 && err == NULL)
7868 err = got_error_from_errno("fclose");
7869 free(path);
7870 if (commit)
7871 got_object_commit_close(commit);
7872 return err;
7875 void
7876 histedit_free_list(struct got_histedit_list *histedit_cmds)
7878 struct got_histedit_list_entry *hle;
7880 while ((hle = TAILQ_FIRST(histedit_cmds))) {
7881 TAILQ_REMOVE(histedit_cmds, hle, entry);
7882 free(hle);
7886 static const struct got_error *
7887 histedit_load_list(struct got_histedit_list *histedit_cmds,
7888 const char *path, struct got_repository *repo)
7890 const struct got_error *err = NULL;
7891 FILE *f = NULL;
7893 f = fopen(path, "r");
7894 if (f == NULL) {
7895 err = got_error_from_errno2("fopen", path);
7896 goto done;
7899 err = histedit_parse_list(histedit_cmds, f, repo);
7900 done:
7901 if (f && fclose(f) != 0 && err == NULL)
7902 err = got_error_from_errno("fclose");
7903 return err;
7906 static const struct got_error *
7907 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
7908 const struct got_error *edit_err, struct got_object_id_queue *commits,
7909 const char *path, const char *branch_name, struct got_repository *repo)
7911 const struct got_error *err = NULL, *prev_err = edit_err;
7912 int resp = ' ';
7914 while (resp != 'c' && resp != 'r' && resp != 'a') {
7915 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
7916 "or (a)bort: ", getprogname(), prev_err->msg);
7917 resp = getchar();
7918 if (resp == '\n')
7919 resp = getchar();
7920 if (resp == 'c') {
7921 histedit_free_list(histedit_cmds);
7922 err = histedit_run_editor(histedit_cmds, path, commits,
7923 repo);
7924 if (err) {
7925 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7926 err->code != GOT_ERR_HISTEDIT_CMD)
7927 break;
7928 prev_err = err;
7929 resp = ' ';
7930 continue;
7932 break;
7933 } else if (resp == 'r') {
7934 histedit_free_list(histedit_cmds);
7935 err = histedit_edit_script(histedit_cmds,
7936 commits, branch_name, 0, repo);
7937 if (err) {
7938 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7939 err->code != GOT_ERR_HISTEDIT_CMD)
7940 break;
7941 prev_err = err;
7942 resp = ' ';
7943 continue;
7945 break;
7946 } else if (resp == 'a') {
7947 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
7948 break;
7949 } else
7950 printf("invalid response '%c'\n", resp);
7953 return err;
7956 static const struct got_error *
7957 histedit_complete(struct got_worktree *worktree,
7958 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
7959 struct got_reference *branch, struct got_repository *repo)
7961 printf("Switching work tree to %s\n",
7962 got_ref_get_symref_target(branch));
7963 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
7964 branch, repo);
7967 static const struct got_error *
7968 show_histedit_progress(struct got_commit_object *commit,
7969 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
7971 const struct got_error *err;
7972 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7974 err = got_object_id_str(&old_id_str, hle->commit_id);
7975 if (err)
7976 goto done;
7978 if (new_id) {
7979 err = got_object_id_str(&new_id_str, new_id);
7980 if (err)
7981 goto done;
7984 old_id_str[12] = '\0';
7985 if (new_id_str)
7986 new_id_str[12] = '\0';
7988 if (hle->logmsg) {
7989 logmsg = strdup(hle->logmsg);
7990 if (logmsg == NULL) {
7991 err = got_error_from_errno("strdup");
7992 goto done;
7994 trim_logmsg(logmsg, 42);
7995 } else {
7996 err = get_short_logmsg(&logmsg, 42, commit);
7997 if (err)
7998 goto done;
8001 switch (hle->cmd->code) {
8002 case GOT_HISTEDIT_PICK:
8003 case GOT_HISTEDIT_EDIT:
8004 printf("%s -> %s: %s\n", old_id_str,
8005 new_id_str ? new_id_str : "no-op change", logmsg);
8006 break;
8007 case GOT_HISTEDIT_DROP:
8008 case GOT_HISTEDIT_FOLD:
8009 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
8010 logmsg);
8011 break;
8012 default:
8013 break;
8015 done:
8016 free(old_id_str);
8017 free(new_id_str);
8018 return err;
8021 static const struct got_error *
8022 histedit_commit(struct got_pathlist_head *merged_paths,
8023 struct got_worktree *worktree, struct got_fileindex *fileindex,
8024 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
8025 struct got_repository *repo)
8027 const struct got_error *err;
8028 struct got_commit_object *commit;
8029 struct got_object_id *new_commit_id;
8031 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
8032 && hle->logmsg == NULL) {
8033 err = histedit_edit_logmsg(hle, repo);
8034 if (err)
8035 return err;
8038 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8039 if (err)
8040 return err;
8042 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
8043 worktree, fileindex, tmp_branch, commit, hle->commit_id,
8044 hle->logmsg, repo);
8045 if (err) {
8046 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
8047 goto done;
8048 err = show_histedit_progress(commit, hle, NULL);
8049 } else {
8050 err = show_histedit_progress(commit, hle, new_commit_id);
8051 free(new_commit_id);
8053 done:
8054 got_object_commit_close(commit);
8055 return err;
8058 static const struct got_error *
8059 histedit_skip_commit(struct got_histedit_list_entry *hle,
8060 struct got_worktree *worktree, struct got_repository *repo)
8062 const struct got_error *error;
8063 struct got_commit_object *commit;
8065 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
8066 repo);
8067 if (error)
8068 return error;
8070 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
8071 if (error)
8072 return error;
8074 error = show_histedit_progress(commit, hle, NULL);
8075 got_object_commit_close(commit);
8076 return error;
8079 static const struct got_error *
8080 check_local_changes(void *arg, unsigned char status,
8081 unsigned char staged_status, const char *path,
8082 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8083 struct got_object_id *commit_id, int dirfd, const char *de_name)
8085 int *have_local_changes = arg;
8087 switch (status) {
8088 case GOT_STATUS_ADD:
8089 case GOT_STATUS_DELETE:
8090 case GOT_STATUS_MODIFY:
8091 case GOT_STATUS_CONFLICT:
8092 *have_local_changes = 1;
8093 return got_error(GOT_ERR_CANCELLED);
8094 default:
8095 break;
8098 switch (staged_status) {
8099 case GOT_STATUS_ADD:
8100 case GOT_STATUS_DELETE:
8101 case GOT_STATUS_MODIFY:
8102 *have_local_changes = 1;
8103 return got_error(GOT_ERR_CANCELLED);
8104 default:
8105 break;
8108 return NULL;
8111 static const struct got_error *
8112 cmd_histedit(int argc, char *argv[])
8114 const struct got_error *error = NULL;
8115 struct got_worktree *worktree = NULL;
8116 struct got_fileindex *fileindex = NULL;
8117 struct got_repository *repo = NULL;
8118 char *cwd = NULL;
8119 struct got_reference *branch = NULL;
8120 struct got_reference *tmp_branch = NULL;
8121 struct got_object_id *resume_commit_id = NULL;
8122 struct got_object_id *base_commit_id = NULL;
8123 struct got_object_id *head_commit_id = NULL;
8124 struct got_commit_object *commit = NULL;
8125 int ch, rebase_in_progress = 0;
8126 struct got_update_progress_arg upa;
8127 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8128 int edit_logmsg_only = 0;
8129 const char *edit_script_path = NULL;
8130 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8131 struct got_object_id_queue commits;
8132 struct got_pathlist_head merged_paths;
8133 const struct got_object_id_queue *parent_ids;
8134 struct got_object_qid *pid;
8135 struct got_histedit_list histedit_cmds;
8136 struct got_histedit_list_entry *hle;
8138 SIMPLEQ_INIT(&commits);
8139 TAILQ_INIT(&histedit_cmds);
8140 TAILQ_INIT(&merged_paths);
8141 memset(&upa, 0, sizeof(upa));
8143 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
8144 switch (ch) {
8145 case 'a':
8146 abort_edit = 1;
8147 break;
8148 case 'c':
8149 continue_edit = 1;
8150 break;
8151 case 'F':
8152 edit_script_path = optarg;
8153 break;
8154 case 'm':
8155 edit_logmsg_only = 1;
8156 break;
8157 default:
8158 usage_histedit();
8159 /* NOTREACHED */
8163 argc -= optind;
8164 argv += optind;
8166 #ifndef PROFILE
8167 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8168 "unveil", NULL) == -1)
8169 err(1, "pledge");
8170 #endif
8171 if (abort_edit && continue_edit)
8172 errx(1, "histedit's -a and -c options are mutually exclusive");
8173 if (edit_script_path && edit_logmsg_only)
8174 errx(1, "histedit's -F and -m options are mutually exclusive");
8175 if (abort_edit && edit_logmsg_only)
8176 errx(1, "histedit's -a and -m options are mutually exclusive");
8177 if (continue_edit && edit_logmsg_only)
8178 errx(1, "histedit's -c and -m options are mutually exclusive");
8179 if (argc != 0)
8180 usage_histedit();
8183 * This command cannot apply unveil(2) in all cases because the
8184 * user may choose to run an editor to edit the histedit script
8185 * and to edit individual commit log messages.
8186 * unveil(2) traverses exec(2); if an editor is used we have to
8187 * apply unveil after edit script and log messages have been written.
8188 * XXX TODO: Make use of unveil(2) where possible.
8191 cwd = getcwd(NULL, 0);
8192 if (cwd == NULL) {
8193 error = got_error_from_errno("getcwd");
8194 goto done;
8196 error = got_worktree_open(&worktree, cwd);
8197 if (error) {
8198 if (error->code == GOT_ERR_NOT_WORKTREE)
8199 error = wrap_not_worktree_error(error, "histedit", cwd);
8200 goto done;
8203 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8204 NULL);
8205 if (error != NULL)
8206 goto done;
8208 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8209 if (error)
8210 goto done;
8211 if (rebase_in_progress) {
8212 error = got_error(GOT_ERR_REBASING);
8213 goto done;
8216 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8217 if (error)
8218 goto done;
8220 if (edit_in_progress && edit_logmsg_only) {
8221 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8222 "histedit operation is in progress in this "
8223 "work tree and must be continued or aborted "
8224 "before the -m option can be used");
8225 goto done;
8228 if (edit_in_progress && abort_edit) {
8229 error = got_worktree_histedit_continue(&resume_commit_id,
8230 &tmp_branch, &branch, &base_commit_id, &fileindex,
8231 worktree, repo);
8232 if (error)
8233 goto done;
8234 printf("Switching work tree to %s\n",
8235 got_ref_get_symref_target(branch));
8236 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8237 branch, base_commit_id, update_progress, &upa);
8238 if (error)
8239 goto done;
8240 printf("Histedit of %s aborted\n",
8241 got_ref_get_symref_target(branch));
8242 print_update_progress_stats(&upa);
8243 goto done; /* nothing else to do */
8244 } else if (abort_edit) {
8245 error = got_error(GOT_ERR_NOT_HISTEDIT);
8246 goto done;
8249 if (continue_edit) {
8250 char *path;
8252 if (!edit_in_progress) {
8253 error = got_error(GOT_ERR_NOT_HISTEDIT);
8254 goto done;
8257 error = got_worktree_get_histedit_script_path(&path, worktree);
8258 if (error)
8259 goto done;
8261 error = histedit_load_list(&histedit_cmds, path, repo);
8262 free(path);
8263 if (error)
8264 goto done;
8266 error = got_worktree_histedit_continue(&resume_commit_id,
8267 &tmp_branch, &branch, &base_commit_id, &fileindex,
8268 worktree, repo);
8269 if (error)
8270 goto done;
8272 error = got_ref_resolve(&head_commit_id, repo, branch);
8273 if (error)
8274 goto done;
8276 error = got_object_open_as_commit(&commit, repo,
8277 head_commit_id);
8278 if (error)
8279 goto done;
8280 parent_ids = got_object_commit_get_parent_ids(commit);
8281 pid = SIMPLEQ_FIRST(parent_ids);
8282 if (pid == NULL) {
8283 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8284 goto done;
8286 error = collect_commits(&commits, head_commit_id, pid->id,
8287 base_commit_id, got_worktree_get_path_prefix(worktree),
8288 GOT_ERR_HISTEDIT_PATH, repo);
8289 got_object_commit_close(commit);
8290 commit = NULL;
8291 if (error)
8292 goto done;
8293 } else {
8294 if (edit_in_progress) {
8295 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8296 goto done;
8299 error = got_ref_open(&branch, repo,
8300 got_worktree_get_head_ref_name(worktree), 0);
8301 if (error != NULL)
8302 goto done;
8304 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8305 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8306 "will not edit commit history of a branch outside "
8307 "the \"refs/heads/\" reference namespace");
8308 goto done;
8311 error = got_ref_resolve(&head_commit_id, repo, branch);
8312 got_ref_close(branch);
8313 branch = NULL;
8314 if (error)
8315 goto done;
8317 error = got_object_open_as_commit(&commit, repo,
8318 head_commit_id);
8319 if (error)
8320 goto done;
8321 parent_ids = got_object_commit_get_parent_ids(commit);
8322 pid = SIMPLEQ_FIRST(parent_ids);
8323 if (pid == NULL) {
8324 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8325 goto done;
8327 error = collect_commits(&commits, head_commit_id, pid->id,
8328 got_worktree_get_base_commit_id(worktree),
8329 got_worktree_get_path_prefix(worktree),
8330 GOT_ERR_HISTEDIT_PATH, repo);
8331 got_object_commit_close(commit);
8332 commit = NULL;
8333 if (error)
8334 goto done;
8336 if (SIMPLEQ_EMPTY(&commits)) {
8337 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8338 goto done;
8341 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8342 &base_commit_id, &fileindex, worktree, repo);
8343 if (error)
8344 goto done;
8346 if (edit_script_path) {
8347 error = histedit_load_list(&histedit_cmds,
8348 edit_script_path, repo);
8349 if (error) {
8350 got_worktree_histedit_abort(worktree, fileindex,
8351 repo, branch, base_commit_id,
8352 update_progress, &upa);
8353 print_update_progress_stats(&upa);
8354 goto done;
8356 } else {
8357 const char *branch_name;
8358 branch_name = got_ref_get_symref_target(branch);
8359 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8360 branch_name += 11;
8361 error = histedit_edit_script(&histedit_cmds, &commits,
8362 branch_name, edit_logmsg_only, repo);
8363 if (error) {
8364 got_worktree_histedit_abort(worktree, fileindex,
8365 repo, branch, base_commit_id,
8366 update_progress, &upa);
8367 print_update_progress_stats(&upa);
8368 goto done;
8373 error = histedit_save_list(&histedit_cmds, worktree,
8374 repo);
8375 if (error) {
8376 got_worktree_histedit_abort(worktree, fileindex,
8377 repo, branch, base_commit_id,
8378 update_progress, &upa);
8379 print_update_progress_stats(&upa);
8380 goto done;
8385 error = histedit_check_script(&histedit_cmds, &commits, repo);
8386 if (error)
8387 goto done;
8389 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8390 if (resume_commit_id) {
8391 if (got_object_id_cmp(hle->commit_id,
8392 resume_commit_id) != 0)
8393 continue;
8395 resume_commit_id = NULL;
8396 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8397 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8398 error = histedit_skip_commit(hle, worktree,
8399 repo);
8400 if (error)
8401 goto done;
8402 } else {
8403 struct got_pathlist_head paths;
8404 int have_changes = 0;
8406 TAILQ_INIT(&paths);
8407 error = got_pathlist_append(&paths, "", NULL);
8408 if (error)
8409 goto done;
8410 error = got_worktree_status(worktree, &paths,
8411 repo, check_local_changes, &have_changes,
8412 check_cancelled, NULL);
8413 got_pathlist_free(&paths);
8414 if (error) {
8415 if (error->code != GOT_ERR_CANCELLED)
8416 goto done;
8417 if (sigint_received || sigpipe_received)
8418 goto done;
8420 if (have_changes) {
8421 error = histedit_commit(NULL, worktree,
8422 fileindex, tmp_branch, hle, repo);
8423 if (error)
8424 goto done;
8425 } else {
8426 error = got_object_open_as_commit(
8427 &commit, repo, hle->commit_id);
8428 if (error)
8429 goto done;
8430 error = show_histedit_progress(commit,
8431 hle, NULL);
8432 got_object_commit_close(commit);
8433 commit = NULL;
8434 if (error)
8435 goto done;
8438 continue;
8441 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8442 error = histedit_skip_commit(hle, worktree, repo);
8443 if (error)
8444 goto done;
8445 continue;
8448 error = got_object_open_as_commit(&commit, repo,
8449 hle->commit_id);
8450 if (error)
8451 goto done;
8452 parent_ids = got_object_commit_get_parent_ids(commit);
8453 pid = SIMPLEQ_FIRST(parent_ids);
8455 error = got_worktree_histedit_merge_files(&merged_paths,
8456 worktree, fileindex, pid->id, hle->commit_id, repo,
8457 update_progress, &upa, check_cancelled, NULL);
8458 if (error)
8459 goto done;
8460 got_object_commit_close(commit);
8461 commit = NULL;
8463 print_update_progress_stats(&upa);
8464 if (upa.conflicts > 0)
8465 rebase_status = GOT_STATUS_CONFLICT;
8467 if (rebase_status == GOT_STATUS_CONFLICT) {
8468 error = show_rebase_merge_conflict(hle->commit_id,
8469 repo);
8470 if (error)
8471 goto done;
8472 got_worktree_rebase_pathlist_free(&merged_paths);
8473 break;
8476 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8477 char *id_str;
8478 error = got_object_id_str(&id_str, hle->commit_id);
8479 if (error)
8480 goto done;
8481 printf("Stopping histedit for amending commit %s\n",
8482 id_str);
8483 free(id_str);
8484 got_worktree_rebase_pathlist_free(&merged_paths);
8485 error = got_worktree_histedit_postpone(worktree,
8486 fileindex);
8487 goto done;
8490 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8491 error = histedit_skip_commit(hle, worktree, repo);
8492 if (error)
8493 goto done;
8494 continue;
8497 error = histedit_commit(&merged_paths, worktree, fileindex,
8498 tmp_branch, hle, repo);
8499 got_worktree_rebase_pathlist_free(&merged_paths);
8500 if (error)
8501 goto done;
8504 if (rebase_status == GOT_STATUS_CONFLICT) {
8505 error = got_worktree_histedit_postpone(worktree, fileindex);
8506 if (error)
8507 goto done;
8508 error = got_error_msg(GOT_ERR_CONFLICTS,
8509 "conflicts must be resolved before histedit can continue");
8510 } else
8511 error = histedit_complete(worktree, fileindex, tmp_branch,
8512 branch, repo);
8513 done:
8514 got_object_id_queue_free(&commits);
8515 histedit_free_list(&histedit_cmds);
8516 free(head_commit_id);
8517 free(base_commit_id);
8518 free(resume_commit_id);
8519 if (commit)
8520 got_object_commit_close(commit);
8521 if (branch)
8522 got_ref_close(branch);
8523 if (tmp_branch)
8524 got_ref_close(tmp_branch);
8525 if (worktree)
8526 got_worktree_close(worktree);
8527 if (repo)
8528 got_repo_close(repo);
8529 return error;
8532 __dead static void
8533 usage_integrate(void)
8535 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
8536 exit(1);
8539 static const struct got_error *
8540 cmd_integrate(int argc, char *argv[])
8542 const struct got_error *error = NULL;
8543 struct got_repository *repo = NULL;
8544 struct got_worktree *worktree = NULL;
8545 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
8546 const char *branch_arg = NULL;
8547 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
8548 struct got_fileindex *fileindex = NULL;
8549 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
8550 int ch;
8551 struct got_update_progress_arg upa;
8553 while ((ch = getopt(argc, argv, "")) != -1) {
8554 switch (ch) {
8555 default:
8556 usage_integrate();
8557 /* NOTREACHED */
8561 argc -= optind;
8562 argv += optind;
8564 if (argc != 1)
8565 usage_integrate();
8566 branch_arg = argv[0];
8568 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8569 "unveil", NULL) == -1)
8570 err(1, "pledge");
8572 cwd = getcwd(NULL, 0);
8573 if (cwd == NULL) {
8574 error = got_error_from_errno("getcwd");
8575 goto done;
8578 error = got_worktree_open(&worktree, cwd);
8579 if (error) {
8580 if (error->code == GOT_ERR_NOT_WORKTREE)
8581 error = wrap_not_worktree_error(error, "integrate",
8582 cwd);
8583 goto done;
8586 error = check_rebase_or_histedit_in_progress(worktree);
8587 if (error)
8588 goto done;
8590 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8591 NULL);
8592 if (error != NULL)
8593 goto done;
8595 error = apply_unveil(got_repo_get_path(repo), 0,
8596 got_worktree_get_root_path(worktree));
8597 if (error)
8598 goto done;
8600 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
8601 error = got_error_from_errno("asprintf");
8602 goto done;
8605 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
8606 &base_branch_ref, worktree, refname, repo);
8607 if (error)
8608 goto done;
8610 refname = strdup(got_ref_get_name(branch_ref));
8611 if (refname == NULL) {
8612 error = got_error_from_errno("strdup");
8613 got_worktree_integrate_abort(worktree, fileindex, repo,
8614 branch_ref, base_branch_ref);
8615 goto done;
8617 base_refname = strdup(got_ref_get_name(base_branch_ref));
8618 if (base_refname == NULL) {
8619 error = got_error_from_errno("strdup");
8620 got_worktree_integrate_abort(worktree, fileindex, repo,
8621 branch_ref, base_branch_ref);
8622 goto done;
8625 error = got_ref_resolve(&commit_id, repo, branch_ref);
8626 if (error)
8627 goto done;
8629 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
8630 if (error)
8631 goto done;
8633 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
8634 error = got_error_msg(GOT_ERR_SAME_BRANCH,
8635 "specified branch has already been integrated");
8636 got_worktree_integrate_abort(worktree, fileindex, repo,
8637 branch_ref, base_branch_ref);
8638 goto done;
8641 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
8642 if (error) {
8643 if (error->code == GOT_ERR_ANCESTRY)
8644 error = got_error(GOT_ERR_REBASE_REQUIRED);
8645 got_worktree_integrate_abort(worktree, fileindex, repo,
8646 branch_ref, base_branch_ref);
8647 goto done;
8650 memset(&upa, 0, sizeof(upa));
8651 error = got_worktree_integrate_continue(worktree, fileindex, repo,
8652 branch_ref, base_branch_ref, update_progress, &upa,
8653 check_cancelled, NULL);
8654 if (error)
8655 goto done;
8657 printf("Integrated %s into %s\n", refname, base_refname);
8658 print_update_progress_stats(&upa);
8659 done:
8660 if (repo)
8661 got_repo_close(repo);
8662 if (worktree)
8663 got_worktree_close(worktree);
8664 free(cwd);
8665 free(base_commit_id);
8666 free(commit_id);
8667 free(refname);
8668 free(base_refname);
8669 return error;
8672 __dead static void
8673 usage_stage(void)
8675 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
8676 "[file-path ...]\n",
8677 getprogname());
8678 exit(1);
8681 static const struct got_error *
8682 print_stage(void *arg, unsigned char status, unsigned char staged_status,
8683 const char *path, struct got_object_id *blob_id,
8684 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
8685 int dirfd, const char *de_name)
8687 const struct got_error *err = NULL;
8688 char *id_str = NULL;
8690 if (staged_status != GOT_STATUS_ADD &&
8691 staged_status != GOT_STATUS_MODIFY &&
8692 staged_status != GOT_STATUS_DELETE)
8693 return NULL;
8695 if (staged_status == GOT_STATUS_ADD ||
8696 staged_status == GOT_STATUS_MODIFY)
8697 err = got_object_id_str(&id_str, staged_blob_id);
8698 else
8699 err = got_object_id_str(&id_str, blob_id);
8700 if (err)
8701 return err;
8703 printf("%s %c %s\n", id_str, staged_status, path);
8704 free(id_str);
8705 return NULL;
8708 static const struct got_error *
8709 cmd_stage(int argc, char *argv[])
8711 const struct got_error *error = NULL;
8712 struct got_repository *repo = NULL;
8713 struct got_worktree *worktree = NULL;
8714 char *cwd = NULL;
8715 struct got_pathlist_head paths;
8716 struct got_pathlist_entry *pe;
8717 int ch, list_stage = 0, pflag = 0;
8718 FILE *patch_script_file = NULL;
8719 const char *patch_script_path = NULL;
8720 struct choose_patch_arg cpa;
8722 TAILQ_INIT(&paths);
8724 while ((ch = getopt(argc, argv, "lpF:")) != -1) {
8725 switch (ch) {
8726 case 'l':
8727 list_stage = 1;
8728 break;
8729 case 'p':
8730 pflag = 1;
8731 break;
8732 case 'F':
8733 patch_script_path = optarg;
8734 break;
8735 default:
8736 usage_stage();
8737 /* NOTREACHED */
8741 argc -= optind;
8742 argv += optind;
8744 #ifndef PROFILE
8745 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8746 "unveil", NULL) == -1)
8747 err(1, "pledge");
8748 #endif
8749 if (list_stage && (pflag || patch_script_path))
8750 errx(1, "-l option cannot be used with other options");
8751 if (patch_script_path && !pflag)
8752 errx(1, "-F option can only be used together with -p option");
8754 cwd = getcwd(NULL, 0);
8755 if (cwd == NULL) {
8756 error = got_error_from_errno("getcwd");
8757 goto done;
8760 error = got_worktree_open(&worktree, cwd);
8761 if (error) {
8762 if (error->code == GOT_ERR_NOT_WORKTREE)
8763 error = wrap_not_worktree_error(error, "stage", cwd);
8764 goto done;
8767 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8768 NULL);
8769 if (error != NULL)
8770 goto done;
8772 if (patch_script_path) {
8773 patch_script_file = fopen(patch_script_path, "r");
8774 if (patch_script_file == NULL) {
8775 error = got_error_from_errno2("fopen",
8776 patch_script_path);
8777 goto done;
8780 error = apply_unveil(got_repo_get_path(repo), 0,
8781 got_worktree_get_root_path(worktree));
8782 if (error)
8783 goto done;
8785 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8786 if (error)
8787 goto done;
8789 if (list_stage)
8790 error = got_worktree_status(worktree, &paths, repo,
8791 print_stage, NULL, check_cancelled, NULL);
8792 else {
8793 cpa.patch_script_file = patch_script_file;
8794 cpa.action = "stage";
8795 error = got_worktree_stage(worktree, &paths,
8796 pflag ? NULL : print_status, NULL,
8797 pflag ? choose_patch : NULL, &cpa, repo);
8799 done:
8800 if (patch_script_file && fclose(patch_script_file) == EOF &&
8801 error == NULL)
8802 error = got_error_from_errno2("fclose", patch_script_path);
8803 if (repo)
8804 got_repo_close(repo);
8805 if (worktree)
8806 got_worktree_close(worktree);
8807 TAILQ_FOREACH(pe, &paths, entry)
8808 free((char *)pe->path);
8809 got_pathlist_free(&paths);
8810 free(cwd);
8811 return error;
8814 __dead static void
8815 usage_unstage(void)
8817 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
8818 "[file-path ...]\n",
8819 getprogname());
8820 exit(1);
8824 static const struct got_error *
8825 cmd_unstage(int argc, char *argv[])
8827 const struct got_error *error = NULL;
8828 struct got_repository *repo = NULL;
8829 struct got_worktree *worktree = NULL;
8830 char *cwd = NULL;
8831 struct got_pathlist_head paths;
8832 struct got_pathlist_entry *pe;
8833 int ch, pflag = 0;
8834 struct got_update_progress_arg upa;
8835 FILE *patch_script_file = NULL;
8836 const char *patch_script_path = NULL;
8837 struct choose_patch_arg cpa;
8839 TAILQ_INIT(&paths);
8841 while ((ch = getopt(argc, argv, "pF:")) != -1) {
8842 switch (ch) {
8843 case 'p':
8844 pflag = 1;
8845 break;
8846 case 'F':
8847 patch_script_path = optarg;
8848 break;
8849 default:
8850 usage_unstage();
8851 /* NOTREACHED */
8855 argc -= optind;
8856 argv += optind;
8858 #ifndef PROFILE
8859 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8860 "unveil", NULL) == -1)
8861 err(1, "pledge");
8862 #endif
8863 if (patch_script_path && !pflag)
8864 errx(1, "-F option can only be used together with -p option");
8866 cwd = getcwd(NULL, 0);
8867 if (cwd == NULL) {
8868 error = got_error_from_errno("getcwd");
8869 goto done;
8872 error = got_worktree_open(&worktree, cwd);
8873 if (error) {
8874 if (error->code == GOT_ERR_NOT_WORKTREE)
8875 error = wrap_not_worktree_error(error, "unstage", cwd);
8876 goto done;
8879 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8880 NULL);
8881 if (error != NULL)
8882 goto done;
8884 if (patch_script_path) {
8885 patch_script_file = fopen(patch_script_path, "r");
8886 if (patch_script_file == NULL) {
8887 error = got_error_from_errno2("fopen",
8888 patch_script_path);
8889 goto done;
8893 error = apply_unveil(got_repo_get_path(repo), 0,
8894 got_worktree_get_root_path(worktree));
8895 if (error)
8896 goto done;
8898 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8899 if (error)
8900 goto done;
8902 cpa.patch_script_file = patch_script_file;
8903 cpa.action = "unstage";
8904 memset(&upa, 0, sizeof(upa));
8905 error = got_worktree_unstage(worktree, &paths, update_progress,
8906 &upa, pflag ? choose_patch : NULL, &cpa, repo);
8907 if (!error)
8908 print_update_progress_stats(&upa);
8909 done:
8910 if (patch_script_file && fclose(patch_script_file) == EOF &&
8911 error == NULL)
8912 error = got_error_from_errno2("fclose", patch_script_path);
8913 if (repo)
8914 got_repo_close(repo);
8915 if (worktree)
8916 got_worktree_close(worktree);
8917 TAILQ_FOREACH(pe, &paths, entry)
8918 free((char *)pe->path);
8919 got_pathlist_free(&paths);
8920 free(cwd);
8921 return error;
8924 __dead static void
8925 usage_cat(void)
8927 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
8928 "arg1 [arg2 ...]\n", getprogname());
8929 exit(1);
8932 static const struct got_error *
8933 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8935 const struct got_error *err;
8936 struct got_blob_object *blob;
8938 err = got_object_open_as_blob(&blob, repo, id, 8192);
8939 if (err)
8940 return err;
8942 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
8943 got_object_blob_close(blob);
8944 return err;
8947 static const struct got_error *
8948 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8950 const struct got_error *err;
8951 struct got_tree_object *tree;
8952 int nentries, i;
8954 err = got_object_open_as_tree(&tree, repo, id);
8955 if (err)
8956 return err;
8958 nentries = got_object_tree_get_nentries(tree);
8959 for (i = 0; i < nentries; i++) {
8960 struct got_tree_entry *te;
8961 char *id_str;
8962 if (sigint_received || sigpipe_received)
8963 break;
8964 te = got_object_tree_get_entry(tree, i);
8965 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
8966 if (err)
8967 break;
8968 fprintf(outfile, "%s %.7o %s\n", id_str,
8969 got_tree_entry_get_mode(te),
8970 got_tree_entry_get_name(te));
8971 free(id_str);
8974 got_object_tree_close(tree);
8975 return err;
8978 static const struct got_error *
8979 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8981 const struct got_error *err;
8982 struct got_commit_object *commit;
8983 const struct got_object_id_queue *parent_ids;
8984 struct got_object_qid *pid;
8985 char *id_str = NULL;
8986 const char *logmsg = NULL;
8988 err = got_object_open_as_commit(&commit, repo, id);
8989 if (err)
8990 return err;
8992 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
8993 if (err)
8994 goto done;
8996 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
8997 parent_ids = got_object_commit_get_parent_ids(commit);
8998 fprintf(outfile, "numparents %d\n",
8999 got_object_commit_get_nparents(commit));
9000 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
9001 char *pid_str;
9002 err = got_object_id_str(&pid_str, pid->id);
9003 if (err)
9004 goto done;
9005 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
9006 free(pid_str);
9008 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
9009 got_object_commit_get_author(commit),
9010 got_object_commit_get_author_time(commit));
9012 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
9013 got_object_commit_get_author(commit),
9014 got_object_commit_get_committer_time(commit));
9016 logmsg = got_object_commit_get_logmsg_raw(commit);
9017 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
9018 fprintf(outfile, "%s", logmsg);
9019 done:
9020 free(id_str);
9021 got_object_commit_close(commit);
9022 return err;
9025 static const struct got_error *
9026 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9028 const struct got_error *err;
9029 struct got_tag_object *tag;
9030 char *id_str = NULL;
9031 const char *tagmsg = NULL;
9033 err = got_object_open_as_tag(&tag, repo, id);
9034 if (err)
9035 return err;
9037 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
9038 if (err)
9039 goto done;
9041 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
9043 switch (got_object_tag_get_object_type(tag)) {
9044 case GOT_OBJ_TYPE_BLOB:
9045 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9046 GOT_OBJ_LABEL_BLOB);
9047 break;
9048 case GOT_OBJ_TYPE_TREE:
9049 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9050 GOT_OBJ_LABEL_TREE);
9051 break;
9052 case GOT_OBJ_TYPE_COMMIT:
9053 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9054 GOT_OBJ_LABEL_COMMIT);
9055 break;
9056 case GOT_OBJ_TYPE_TAG:
9057 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9058 GOT_OBJ_LABEL_TAG);
9059 break;
9060 default:
9061 break;
9064 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
9065 got_object_tag_get_name(tag));
9067 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
9068 got_object_tag_get_tagger(tag),
9069 got_object_tag_get_tagger_time(tag));
9071 tagmsg = got_object_tag_get_message(tag);
9072 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
9073 fprintf(outfile, "%s", tagmsg);
9074 done:
9075 free(id_str);
9076 got_object_tag_close(tag);
9077 return err;
9080 static const struct got_error *
9081 cmd_cat(int argc, char *argv[])
9083 const struct got_error *error;
9084 struct got_repository *repo = NULL;
9085 struct got_worktree *worktree = NULL;
9086 char *cwd = NULL, *repo_path = NULL, *label = NULL;
9087 const char *commit_id_str = NULL;
9088 struct got_object_id *id = NULL, *commit_id = NULL;
9089 int ch, obj_type, i, force_path = 0;
9091 #ifndef PROFILE
9092 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9093 NULL) == -1)
9094 err(1, "pledge");
9095 #endif
9097 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
9098 switch (ch) {
9099 case 'c':
9100 commit_id_str = optarg;
9101 break;
9102 case 'r':
9103 repo_path = realpath(optarg, NULL);
9104 if (repo_path == NULL)
9105 return got_error_from_errno2("realpath",
9106 optarg);
9107 got_path_strip_trailing_slashes(repo_path);
9108 break;
9109 case 'P':
9110 force_path = 1;
9111 break;
9112 default:
9113 usage_cat();
9114 /* NOTREACHED */
9118 argc -= optind;
9119 argv += optind;
9121 cwd = getcwd(NULL, 0);
9122 if (cwd == NULL) {
9123 error = got_error_from_errno("getcwd");
9124 goto done;
9126 error = got_worktree_open(&worktree, cwd);
9127 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9128 goto done;
9129 if (worktree) {
9130 if (repo_path == NULL) {
9131 repo_path = strdup(
9132 got_worktree_get_repo_path(worktree));
9133 if (repo_path == NULL) {
9134 error = got_error_from_errno("strdup");
9135 goto done;
9140 if (repo_path == NULL) {
9141 repo_path = getcwd(NULL, 0);
9142 if (repo_path == NULL)
9143 return got_error_from_errno("getcwd");
9146 error = got_repo_open(&repo, repo_path, NULL);
9147 free(repo_path);
9148 if (error != NULL)
9149 goto done;
9151 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9152 if (error)
9153 goto done;
9155 if (commit_id_str == NULL)
9156 commit_id_str = GOT_REF_HEAD;
9157 error = got_repo_match_object_id(&commit_id, NULL,
9158 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
9159 if (error)
9160 goto done;
9162 for (i = 0; i < argc; i++) {
9163 if (force_path) {
9164 error = got_object_id_by_path(&id, repo, commit_id,
9165 argv[i]);
9166 if (error)
9167 break;
9168 } else {
9169 error = got_repo_match_object_id(&id, &label, argv[i],
9170 GOT_OBJ_TYPE_ANY, 0, repo);
9171 if (error) {
9172 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9173 error->code != GOT_ERR_NOT_REF)
9174 break;
9175 error = got_object_id_by_path(&id, repo,
9176 commit_id, argv[i]);
9177 if (error)
9178 break;
9182 error = got_object_get_type(&obj_type, repo, id);
9183 if (error)
9184 break;
9186 switch (obj_type) {
9187 case GOT_OBJ_TYPE_BLOB:
9188 error = cat_blob(id, repo, stdout);
9189 break;
9190 case GOT_OBJ_TYPE_TREE:
9191 error = cat_tree(id, repo, stdout);
9192 break;
9193 case GOT_OBJ_TYPE_COMMIT:
9194 error = cat_commit(id, repo, stdout);
9195 break;
9196 case GOT_OBJ_TYPE_TAG:
9197 error = cat_tag(id, repo, stdout);
9198 break;
9199 default:
9200 error = got_error(GOT_ERR_OBJ_TYPE);
9201 break;
9203 if (error)
9204 break;
9205 free(label);
9206 label = NULL;
9207 free(id);
9208 id = NULL;
9210 done:
9211 free(label);
9212 free(id);
9213 free(commit_id);
9214 if (worktree)
9215 got_worktree_close(worktree);
9216 if (repo) {
9217 const struct got_error *repo_error;
9218 repo_error = got_repo_close(repo);
9219 if (error == NULL)
9220 error = repo_error;
9222 return error;