Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/param.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
41 #include <util.h>
43 #include "got_version.h"
44 #include "got_error.h"
45 #include "got_object.h"
46 #include "got_reference.h"
47 #include "got_repository.h"
48 #include "got_path.h"
49 #include "got_cancel.h"
50 #include "got_worktree.h"
51 #include "got_diff.h"
52 #include "got_commit_graph.h"
53 #include "got_fetch.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_opentemp.h"
58 #ifndef nitems
59 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
60 #endif
62 static volatile sig_atomic_t sigint_received;
63 static volatile sig_atomic_t sigpipe_received;
65 static void
66 catch_sigint(int signo)
67 {
68 sigint_received = 1;
69 }
71 static void
72 catch_sigpipe(int signo)
73 {
74 sigpipe_received = 1;
75 }
78 struct got_cmd {
79 const char *cmd_name;
80 const struct got_error *(*cmd_main)(int, char *[]);
81 void (*cmd_usage)(void);
82 const char *cmd_alias;
83 };
85 __dead static void usage(int);
86 __dead static void usage_init(void);
87 __dead static void usage_import(void);
88 __dead static void usage_clone(void);
89 __dead static void usage_fetch(void);
90 __dead static void usage_checkout(void);
91 __dead static void usage_update(void);
92 __dead static void usage_log(void);
93 __dead static void usage_diff(void);
94 __dead static void usage_blame(void);
95 __dead static void usage_tree(void);
96 __dead static void usage_status(void);
97 __dead static void usage_ref(void);
98 __dead static void usage_branch(void);
99 __dead static void usage_tag(void);
100 __dead static void usage_add(void);
101 __dead static void usage_remove(void);
102 __dead static void usage_revert(void);
103 __dead static void usage_commit(void);
104 __dead static void usage_cherrypick(void);
105 __dead static void usage_backout(void);
106 __dead static void usage_rebase(void);
107 __dead static void usage_histedit(void);
108 __dead static void usage_integrate(void);
109 __dead static void usage_stage(void);
110 __dead static void usage_unstage(void);
111 __dead static void usage_cat(void);
113 static const struct got_error* cmd_init(int, char *[]);
114 static const struct got_error* cmd_import(int, char *[]);
115 static const struct got_error* cmd_clone(int, char *[]);
116 static const struct got_error* cmd_fetch(int, char *[]);
117 static const struct got_error* cmd_checkout(int, char *[]);
118 static const struct got_error* cmd_update(int, char *[]);
119 static const struct got_error* cmd_log(int, char *[]);
120 static const struct got_error* cmd_diff(int, char *[]);
121 static const struct got_error* cmd_blame(int, char *[]);
122 static const struct got_error* cmd_tree(int, char *[]);
123 static const struct got_error* cmd_status(int, char *[]);
124 static const struct got_error* cmd_ref(int, char *[]);
125 static const struct got_error* cmd_branch(int, char *[]);
126 static const struct got_error* cmd_tag(int, char *[]);
127 static const struct got_error* cmd_add(int, char *[]);
128 static const struct got_error* cmd_remove(int, char *[]);
129 static const struct got_error* cmd_revert(int, char *[]);
130 static const struct got_error* cmd_commit(int, char *[]);
131 static const struct got_error* cmd_cherrypick(int, char *[]);
132 static const struct got_error* cmd_backout(int, char *[]);
133 static const struct got_error* cmd_rebase(int, char *[]);
134 static const struct got_error* cmd_histedit(int, char *[]);
135 static const struct got_error* cmd_integrate(int, char *[]);
136 static const struct got_error* cmd_stage(int, char *[]);
137 static const struct got_error* cmd_unstage(int, char *[]);
138 static const struct got_error* cmd_cat(int, char *[]);
140 static struct got_cmd got_commands[] = {
141 { "init", cmd_init, usage_init, "in" },
142 { "import", cmd_import, usage_import, "im" },
143 { "clone", cmd_clone, usage_clone, "cl" },
144 { "fetch", cmd_fetch, usage_fetch, "fe" },
145 { "checkout", cmd_checkout, usage_checkout, "co" },
146 { "update", cmd_update, usage_update, "up" },
147 { "log", cmd_log, usage_log, "" },
148 { "diff", cmd_diff, usage_diff, "di" },
149 { "blame", cmd_blame, usage_blame, "bl" },
150 { "tree", cmd_tree, usage_tree, "tr" },
151 { "status", cmd_status, usage_status, "st" },
152 { "ref", cmd_ref, usage_ref, "" },
153 { "branch", cmd_branch, usage_branch, "br" },
154 { "tag", cmd_tag, usage_tag, "" },
155 { "add", cmd_add, usage_add, "" },
156 { "remove", cmd_remove, usage_remove, "rm" },
157 { "revert", cmd_revert, usage_revert, "rv" },
158 { "commit", cmd_commit, usage_commit, "ci" },
159 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
160 { "backout", cmd_backout, usage_backout, "bo" },
161 { "rebase", cmd_rebase, usage_rebase, "rb" },
162 { "histedit", cmd_histedit, usage_histedit, "he" },
163 { "integrate", cmd_integrate, usage_integrate,"ig" },
164 { "stage", cmd_stage, usage_stage, "sg" },
165 { "unstage", cmd_unstage, usage_unstage, "ug" },
166 { "cat", cmd_cat, usage_cat, "" },
167 };
169 static void
170 list_commands(void)
172 int i;
174 fprintf(stderr, "commands:");
175 for (i = 0; i < nitems(got_commands); i++) {
176 struct got_cmd *cmd = &got_commands[i];
177 fprintf(stderr, " %s", cmd->cmd_name);
179 fputc('\n', stderr);
182 int
183 main(int argc, char *argv[])
185 struct got_cmd *cmd;
186 unsigned int i;
187 int ch;
188 int hflag = 0, Vflag = 0;
189 static struct option longopts[] = {
190 { "version", no_argument, NULL, 'V' },
191 { NULL, 0, NULL, 0}
192 };
194 setlocale(LC_CTYPE, "");
196 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
197 switch (ch) {
198 case 'h':
199 hflag = 1;
200 break;
201 case 'V':
202 Vflag = 1;
203 break;
204 default:
205 usage(hflag);
206 /* NOTREACHED */
210 argc -= optind;
211 argv += optind;
212 optind = 0;
214 if (Vflag) {
215 got_version_print_str();
216 return 1;
219 if (argc <= 0)
220 usage(hflag);
222 signal(SIGINT, catch_sigint);
223 signal(SIGPIPE, catch_sigpipe);
225 for (i = 0; i < nitems(got_commands); i++) {
226 const struct got_error *error;
228 cmd = &got_commands[i];
230 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
231 strcmp(cmd->cmd_alias, argv[0]) != 0)
232 continue;
234 if (hflag)
235 got_commands[i].cmd_usage();
237 error = got_commands[i].cmd_main(argc, argv);
238 if (error && error->code != GOT_ERR_CANCELLED &&
239 error->code != GOT_ERR_PRIVSEP_EXIT &&
240 !(sigpipe_received &&
241 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
242 !(sigint_received &&
243 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
244 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
245 return 1;
248 return 0;
251 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
252 list_commands();
253 return 1;
256 __dead static void
257 usage(int hflag)
259 fprintf(stderr, "usage: %s [-h] [-V | --version] command [arg ...]\n",
260 getprogname());
261 if (hflag)
262 list_commands();
263 exit(1);
266 static const struct got_error *
267 get_editor(char **abspath)
269 const struct got_error *err = NULL;
270 const char *editor;
272 *abspath = NULL;
274 editor = getenv("VISUAL");
275 if (editor == NULL)
276 editor = getenv("EDITOR");
278 if (editor) {
279 err = got_path_find_prog(abspath, editor);
280 if (err)
281 return err;
284 if (*abspath == NULL) {
285 *abspath = strdup("/bin/ed");
286 if (*abspath == NULL)
287 return got_error_from_errno("strdup");
290 return NULL;
293 static const struct got_error *
294 apply_unveil(const char *repo_path, int repo_read_only,
295 const char *worktree_path)
297 const struct got_error *err;
299 #ifdef PROFILE
300 if (unveil("gmon.out", "rwc") != 0)
301 return got_error_from_errno2("unveil", "gmon.out");
302 #endif
303 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
304 return got_error_from_errno2("unveil", repo_path);
306 if (worktree_path && unveil(worktree_path, "rwc") != 0)
307 return got_error_from_errno2("unveil", worktree_path);
309 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
310 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
312 err = got_privsep_unveil_exec_helpers();
313 if (err != NULL)
314 return err;
316 if (unveil(NULL, NULL) != 0)
317 return got_error_from_errno("unveil");
319 return NULL;
322 __dead static void
323 usage_init(void)
325 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
326 exit(1);
329 static const struct got_error *
330 cmd_init(int argc, char *argv[])
332 const struct got_error *error = NULL;
333 char *repo_path = NULL;
334 int ch;
336 while ((ch = getopt(argc, argv, "")) != -1) {
337 switch (ch) {
338 default:
339 usage_init();
340 /* NOTREACHED */
344 argc -= optind;
345 argv += optind;
347 #ifndef PROFILE
348 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
349 err(1, "pledge");
350 #endif
351 if (argc != 1)
352 usage_init();
354 repo_path = strdup(argv[0]);
355 if (repo_path == NULL)
356 return got_error_from_errno("strdup");
358 got_path_strip_trailing_slashes(repo_path);
360 error = got_path_mkdir(repo_path);
361 if (error &&
362 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
363 goto done;
365 error = apply_unveil(repo_path, 0, NULL);
366 if (error)
367 goto done;
369 error = got_repo_init(repo_path);
370 done:
371 free(repo_path);
372 return error;
375 __dead static void
376 usage_import(void)
378 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
379 "[-r repository-path] [-I pattern] path\n", getprogname());
380 exit(1);
383 int
384 spawn_editor(const char *editor, const char *file)
386 pid_t pid;
387 sig_t sighup, sigint, sigquit;
388 int st = -1;
390 sighup = signal(SIGHUP, SIG_IGN);
391 sigint = signal(SIGINT, SIG_IGN);
392 sigquit = signal(SIGQUIT, SIG_IGN);
394 switch (pid = fork()) {
395 case -1:
396 goto doneediting;
397 case 0:
398 execl(editor, editor, file, (char *)NULL);
399 _exit(127);
402 while (waitpid(pid, &st, 0) == -1)
403 if (errno != EINTR)
404 break;
406 doneediting:
407 (void)signal(SIGHUP, sighup);
408 (void)signal(SIGINT, sigint);
409 (void)signal(SIGQUIT, sigquit);
411 if (!WIFEXITED(st)) {
412 errno = EINTR;
413 return -1;
416 return WEXITSTATUS(st);
419 static const struct got_error *
420 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
421 const char *initial_content)
423 const struct got_error *err = NULL;
424 char buf[1024];
425 struct stat st, st2;
426 FILE *fp;
427 int content_changed = 0;
428 size_t len;
430 *logmsg = NULL;
432 if (stat(logmsg_path, &st) == -1)
433 return got_error_from_errno2("stat", logmsg_path);
435 if (spawn_editor(editor, logmsg_path) == -1)
436 return got_error_from_errno("failed spawning editor");
438 if (stat(logmsg_path, &st2) == -1)
439 return got_error_from_errno("stat");
441 if (st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
442 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
443 "no changes made to commit message, aborting");
445 *logmsg = malloc(st2.st_size + 1);
446 if (*logmsg == NULL)
447 return got_error_from_errno("malloc");
448 (*logmsg)[0] = '\0';
449 len = 0;
451 fp = fopen(logmsg_path, "r");
452 if (fp == NULL) {
453 err = got_error_from_errno("fopen");
454 goto done;
456 while (fgets(buf, sizeof(buf), fp) != NULL) {
457 if (!content_changed && strcmp(buf, initial_content) != 0)
458 content_changed = 1;
459 if (buf[0] == '#' || (len == 0 && buf[0] == '\n'))
460 continue; /* remove comments and leading empty lines */
461 len = strlcat(*logmsg, buf, st2.st_size);
463 fclose(fp);
465 while (len > 0 && (*logmsg)[len - 1] == '\n') {
466 (*logmsg)[len - 1] = '\0';
467 len--;
470 if (len == 0 || !content_changed)
471 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
472 "commit message cannot be empty, aborting");
473 done:
474 if (err) {
475 free(*logmsg);
476 *logmsg = NULL;
478 return err;
481 static const struct got_error *
482 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
483 const char *path_dir, const char *branch_name)
485 char *initial_content = NULL;
486 const struct got_error *err = NULL;
487 int fd;
489 if (asprintf(&initial_content,
490 "\n# %s to be imported to branch %s\n", path_dir,
491 branch_name) == -1)
492 return got_error_from_errno("asprintf");
494 err = got_opentemp_named_fd(logmsg_path, &fd,
495 GOT_TMPDIR_STR "/got-importmsg");
496 if (err)
497 goto done;
499 dprintf(fd, initial_content);
500 close(fd);
502 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content);
503 done:
504 free(initial_content);
505 return err;
508 static const struct got_error *
509 import_progress(void *arg, const char *path)
511 printf("A %s\n", path);
512 return NULL;
515 static const struct got_error *
516 get_author(char **author, struct got_repository *repo)
518 const struct got_error *err = NULL;
519 const char *got_author, *name, *email;
521 *author = NULL;
523 name = got_repo_get_gitconfig_author_name(repo);
524 email = got_repo_get_gitconfig_author_email(repo);
525 if (name && email) {
526 if (asprintf(author, "%s <%s>", name, email) == -1)
527 return got_error_from_errno("asprintf");
528 return NULL;
531 got_author = getenv("GOT_AUTHOR");
532 if (got_author == NULL) {
533 name = got_repo_get_global_gitconfig_author_name(repo);
534 email = got_repo_get_global_gitconfig_author_email(repo);
535 if (name && email) {
536 if (asprintf(author, "%s <%s>", name, email) == -1)
537 return got_error_from_errno("asprintf");
538 return NULL;
540 /* TODO: Look up user in password database? */
541 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
544 *author = strdup(got_author);
545 if (*author == NULL)
546 return got_error_from_errno("strdup");
548 /*
549 * Really dumb email address check; we're only doing this to
550 * avoid git's object parser breaking on commits we create.
551 */
552 while (*got_author && *got_author != '<')
553 got_author++;
554 if (*got_author != '<') {
555 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
556 goto done;
558 while (*got_author && *got_author != '@')
559 got_author++;
560 if (*got_author != '@') {
561 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
562 goto done;
564 while (*got_author && *got_author != '>')
565 got_author++;
566 if (*got_author != '>')
567 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
568 done:
569 if (err) {
570 free(*author);
571 *author = NULL;
573 return err;
576 static const struct got_error *
577 get_gitconfig_path(char **gitconfig_path)
579 const char *homedir = getenv("HOME");
581 *gitconfig_path = NULL;
582 if (homedir) {
583 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
584 return got_error_from_errno("asprintf");
587 return NULL;
590 static const struct got_error *
591 cmd_import(int argc, char *argv[])
593 const struct got_error *error = NULL;
594 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
595 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
596 const char *branch_name = "main";
597 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
598 struct got_repository *repo = NULL;
599 struct got_reference *branch_ref = NULL, *head_ref = NULL;
600 struct got_object_id *new_commit_id = NULL;
601 int ch;
602 struct got_pathlist_head ignores;
603 struct got_pathlist_entry *pe;
604 int preserve_logmsg = 0;
606 TAILQ_INIT(&ignores);
608 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
609 switch (ch) {
610 case 'b':
611 branch_name = optarg;
612 break;
613 case 'm':
614 logmsg = strdup(optarg);
615 if (logmsg == NULL) {
616 error = got_error_from_errno("strdup");
617 goto done;
619 break;
620 case 'r':
621 repo_path = realpath(optarg, NULL);
622 if (repo_path == NULL) {
623 error = got_error_from_errno2("realpath",
624 optarg);
625 goto done;
627 break;
628 case 'I':
629 if (optarg[0] == '\0')
630 break;
631 error = got_pathlist_insert(&pe, &ignores, optarg,
632 NULL);
633 if (error)
634 goto done;
635 break;
636 default:
637 usage_import();
638 /* NOTREACHED */
642 argc -= optind;
643 argv += optind;
645 #ifndef PROFILE
646 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
647 "unveil",
648 NULL) == -1)
649 err(1, "pledge");
650 #endif
651 if (argc != 1)
652 usage_import();
654 if (repo_path == NULL) {
655 repo_path = getcwd(NULL, 0);
656 if (repo_path == NULL)
657 return got_error_from_errno("getcwd");
659 got_path_strip_trailing_slashes(repo_path);
660 error = get_gitconfig_path(&gitconfig_path);
661 if (error)
662 goto done;
663 error = got_repo_open(&repo, repo_path, gitconfig_path);
664 if (error)
665 goto done;
667 error = get_author(&author, repo);
668 if (error)
669 return error;
671 /*
672 * Don't let the user create a branch name with a leading '-'.
673 * While technically a valid reference name, this case is usually
674 * an unintended typo.
675 */
676 if (branch_name[0] == '-')
677 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
679 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
680 error = got_error_from_errno("asprintf");
681 goto done;
684 error = got_ref_open(&branch_ref, repo, refname, 0);
685 if (error) {
686 if (error->code != GOT_ERR_NOT_REF)
687 goto done;
688 } else {
689 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
690 "import target branch already exists");
691 goto done;
694 path_dir = realpath(argv[0], NULL);
695 if (path_dir == NULL) {
696 error = got_error_from_errno2("realpath", argv[0]);
697 goto done;
699 got_path_strip_trailing_slashes(path_dir);
701 /*
702 * unveil(2) traverses exec(2); if an editor is used we have
703 * to apply unveil after the log message has been written.
704 */
705 if (logmsg == NULL || strlen(logmsg) == 0) {
706 error = get_editor(&editor);
707 if (error)
708 goto done;
709 free(logmsg);
710 error = collect_import_msg(&logmsg, &logmsg_path, editor,
711 path_dir, refname);
712 if (error) {
713 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
714 logmsg_path != NULL)
715 preserve_logmsg = 1;
716 goto done;
720 if (unveil(path_dir, "r") != 0) {
721 error = got_error_from_errno2("unveil", path_dir);
722 if (logmsg_path)
723 preserve_logmsg = 1;
724 goto done;
727 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
728 if (error) {
729 if (logmsg_path)
730 preserve_logmsg = 1;
731 goto done;
734 error = got_repo_import(&new_commit_id, path_dir, logmsg,
735 author, &ignores, repo, import_progress, NULL);
736 if (error) {
737 if (logmsg_path)
738 preserve_logmsg = 1;
739 goto done;
742 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
743 if (error) {
744 if (logmsg_path)
745 preserve_logmsg = 1;
746 goto done;
749 error = got_ref_write(branch_ref, repo);
750 if (error) {
751 if (logmsg_path)
752 preserve_logmsg = 1;
753 goto done;
756 error = got_object_id_str(&id_str, new_commit_id);
757 if (error) {
758 if (logmsg_path)
759 preserve_logmsg = 1;
760 goto done;
763 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
764 if (error) {
765 if (error->code != GOT_ERR_NOT_REF) {
766 if (logmsg_path)
767 preserve_logmsg = 1;
768 goto done;
771 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
772 branch_ref);
773 if (error) {
774 if (logmsg_path)
775 preserve_logmsg = 1;
776 goto done;
779 error = got_ref_write(head_ref, repo);
780 if (error) {
781 if (logmsg_path)
782 preserve_logmsg = 1;
783 goto done;
787 printf("Created branch %s with commit %s\n",
788 got_ref_get_name(branch_ref), id_str);
789 done:
790 if (preserve_logmsg) {
791 fprintf(stderr, "%s: log message preserved in %s\n",
792 getprogname(), logmsg_path);
793 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
794 error = got_error_from_errno2("unlink", logmsg_path);
795 free(logmsg);
796 free(logmsg_path);
797 free(repo_path);
798 free(editor);
799 free(refname);
800 free(new_commit_id);
801 free(id_str);
802 free(author);
803 free(gitconfig_path);
804 if (branch_ref)
805 got_ref_close(branch_ref);
806 if (head_ref)
807 got_ref_close(head_ref);
808 return error;
811 __dead static void
812 usage_clone(void)
814 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
815 "[-R reference] repository-url [directory]\n", getprogname());
816 exit(1);
819 struct got_fetch_progress_arg {
820 char last_scaled_size[FMT_SCALED_STRSIZE];
821 int last_p_indexed;
822 int last_p_resolved;
823 int verbosity;
824 };
826 static const struct got_error *
827 fetch_progress(void *arg, const char *message, off_t packfile_size,
828 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
830 struct got_fetch_progress_arg *a = arg;
831 char scaled_size[FMT_SCALED_STRSIZE];
832 int p_indexed, p_resolved;
833 int print_size = 0, print_indexed = 0, print_resolved = 0;
835 if (a->verbosity < 0)
836 return NULL;
838 if (message && message[0] != '\0') {
839 printf("\rserver: %s", message);
840 fflush(stdout);
841 return NULL;
844 if (packfile_size > 0 || nobj_indexed > 0) {
845 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
846 (a->last_scaled_size[0] == '\0' ||
847 strcmp(scaled_size, a->last_scaled_size)) != 0) {
848 print_size = 1;
849 if (strlcpy(a->last_scaled_size, scaled_size,
850 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
851 return got_error(GOT_ERR_NO_SPACE);
853 if (nobj_indexed > 0) {
854 p_indexed = (nobj_indexed * 100) / nobj_total;
855 if (p_indexed != a->last_p_indexed) {
856 a->last_p_indexed = p_indexed;
857 print_indexed = 1;
858 print_size = 1;
861 if (nobj_resolved > 0) {
862 p_resolved = (nobj_resolved * 100) /
863 (nobj_total - nobj_loose);
864 if (p_resolved != a->last_p_resolved) {
865 a->last_p_resolved = p_resolved;
866 print_resolved = 1;
867 print_indexed = 1;
868 print_size = 1;
873 if (print_size || print_indexed || print_resolved)
874 printf("\r");
875 if (print_size)
876 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
877 if (print_indexed)
878 printf("; indexing %d%%", p_indexed);
879 if (print_resolved)
880 printf("; resolving deltas %d%%", p_resolved);
881 if (print_size || print_indexed || print_resolved)
882 fflush(stdout);
884 return NULL;
887 static const struct got_error *
888 create_symref(const char *refname, struct got_reference *target_ref,
889 int verbosity, struct got_repository *repo)
891 const struct got_error *err;
892 struct got_reference *head_symref;
894 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
895 if (err)
896 return err;
898 err = got_ref_write(head_symref, repo);
899 got_ref_close(head_symref);
900 if (err == NULL && verbosity > 0) {
901 printf("Created reference %s: %s\n", GOT_REF_HEAD,
902 got_ref_get_name(target_ref));
904 return err;
907 static const struct got_error *
908 list_remote_refs(struct got_pathlist_head *symrefs,
909 struct got_pathlist_head *refs)
911 const struct got_error *err;
912 struct got_pathlist_entry *pe;
914 TAILQ_FOREACH(pe, symrefs, entry) {
915 const char *refname = pe->path;
916 const char *targetref = pe->data;
918 printf("%s: %s\n", refname, targetref);
921 TAILQ_FOREACH(pe, refs, entry) {
922 const char *refname = pe->path;
923 struct got_object_id *id = pe->data;
924 char *id_str;
926 err = got_object_id_str(&id_str, id);
927 if (err)
928 return err;
929 printf("%s: %s\n", refname, id_str);
930 free(id_str);
933 return NULL;
936 static const struct got_error *
937 create_ref(const char *refname, struct got_object_id *id,
938 int verbosity, struct got_repository *repo)
940 const struct got_error *err = NULL;
941 struct got_reference *ref;
942 char *id_str;
944 err = got_object_id_str(&id_str, id);
945 if (err)
946 return err;
948 err = got_ref_alloc(&ref, refname, id);
949 if (err)
950 goto done;
952 err = got_ref_write(ref, repo);
953 got_ref_close(ref);
955 if (err == NULL && verbosity >= 0)
956 printf("Created reference %s: %s\n", refname, id_str);
957 done:
958 free(id_str);
959 return err;
962 static int
963 match_wanted_ref(const char *refname, const char *wanted_ref)
965 if (strncmp(refname, "refs/", 5) != 0)
966 return 0;
967 refname += 5;
969 /*
970 * Prevent fetching of references that won't make any
971 * sense outside of the remote repository's context.
972 */
973 if (strncmp(refname, "got/", 4) == 0)
974 return 0;
975 if (strncmp(refname, "remotes/", 8) == 0)
976 return 0;
978 if (strncmp(wanted_ref, "refs/", 5) == 0)
979 wanted_ref += 5;
981 /* Allow prefix match. */
982 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
983 return 1;
985 /* Allow exact match. */
986 return (strcmp(refname, wanted_ref) == 0);
989 static int
990 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
992 struct got_pathlist_entry *pe;
994 TAILQ_FOREACH(pe, wanted_refs, entry) {
995 if (match_wanted_ref(refname, pe->path))
996 return 1;
999 return 0;
1002 static const struct got_error *
1003 create_wanted_ref(const char *refname, struct got_object_id *id,
1004 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1006 const struct got_error *err;
1007 char *remote_refname;
1009 if (strncmp("refs/", refname, 5) == 0)
1010 refname += 5;
1012 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1013 remote_repo_name, refname) == -1)
1014 return got_error_from_errno("asprintf");
1016 err = create_ref(remote_refname, id, verbosity, repo);
1017 free(remote_refname);
1018 return err;
1021 static const struct got_error *
1022 cmd_clone(int argc, char *argv[])
1024 const struct got_error *error = NULL;
1025 const char *uri, *dirname;
1026 char *proto, *host, *port, *repo_name, *server_path;
1027 char *default_destdir = NULL, *id_str = NULL;
1028 const char *repo_path;
1029 struct got_repository *repo = NULL;
1030 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1031 struct got_pathlist_entry *pe;
1032 struct got_object_id *pack_hash = NULL;
1033 int ch, fetchfd = -1, fetchstatus;
1034 pid_t fetchpid = -1;
1035 struct got_fetch_progress_arg fpa;
1036 char *git_url = NULL;
1037 char *gitconfig_path = NULL;
1038 char *gitconfig = NULL;
1039 FILE *gitconfig_file = NULL;
1040 ssize_t n;
1041 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1042 int list_refs_only = 0;
1043 struct got_reference *head_symref = NULL;
1045 TAILQ_INIT(&refs);
1046 TAILQ_INIT(&symrefs);
1047 TAILQ_INIT(&wanted_branches);
1048 TAILQ_INIT(&wanted_refs);
1050 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1051 switch (ch) {
1052 case 'a':
1053 fetch_all_branches = 1;
1054 break;
1055 case 'b':
1056 error = got_pathlist_append(&wanted_branches,
1057 optarg, NULL);
1058 if (error)
1059 return error;
1060 break;
1061 case 'l':
1062 list_refs_only = 1;
1063 break;
1064 case 'm':
1065 mirror_references = 1;
1066 break;
1067 case 'v':
1068 if (verbosity < 0)
1069 verbosity = 0;
1070 else if (verbosity < 3)
1071 verbosity++;
1072 break;
1073 case 'q':
1074 verbosity = -1;
1075 break;
1076 case 'R':
1077 error = got_pathlist_append(&wanted_refs,
1078 optarg, NULL);
1079 if (error)
1080 return error;
1081 break;
1082 default:
1083 usage_clone();
1084 break;
1087 argc -= optind;
1088 argv += optind;
1090 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1091 errx(1, "-a and -b options are mutually exclusive");
1092 if (list_refs_only) {
1093 if (!TAILQ_EMPTY(&wanted_branches))
1094 errx(1, "-l and -b options are mutually exclusive");
1095 if (fetch_all_branches)
1096 errx(1, "-l and -a options are mutually exclusive");
1097 if (mirror_references)
1098 errx(1, "-l and -m options are mutually exclusive");
1099 if (verbosity == -1)
1100 errx(1, "-l and -q options are mutually exclusive");
1101 if (!TAILQ_EMPTY(&wanted_refs))
1102 errx(1, "-l and -R options are mutually exclusive");
1105 uri = argv[0];
1107 if (argc == 1)
1108 dirname = NULL;
1109 else if (argc == 2)
1110 dirname = argv[1];
1111 else
1112 usage_clone();
1114 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1115 &repo_name, argv[0]);
1116 if (error)
1117 goto done;
1119 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1120 host, port ? ":" : "", port ? port : "",
1121 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1122 error = got_error_from_errno("asprintf");
1123 goto done;
1126 if (strcmp(proto, "git") == 0) {
1127 #ifndef PROFILE
1128 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1129 "sendfd dns inet unveil", NULL) == -1)
1130 err(1, "pledge");
1131 #endif
1132 } else if (strcmp(proto, "git+ssh") == 0 ||
1133 strcmp(proto, "ssh") == 0) {
1134 #ifndef PROFILE
1135 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1136 "sendfd unveil", NULL) == -1)
1137 err(1, "pledge");
1138 #endif
1139 } else if (strcmp(proto, "http") == 0 ||
1140 strcmp(proto, "git+http") == 0) {
1141 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1142 goto done;
1143 } else {
1144 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1145 goto done;
1147 if (dirname == NULL) {
1148 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1149 error = got_error_from_errno("asprintf");
1150 goto done;
1152 repo_path = default_destdir;
1153 } else
1154 repo_path = dirname;
1156 if (!list_refs_only) {
1157 error = got_path_mkdir(repo_path);
1158 if (error)
1159 goto done;
1161 error = got_repo_init(repo_path);
1162 if (error)
1163 goto done;
1164 error = got_repo_open(&repo, repo_path, NULL);
1165 if (error)
1166 goto done;
1169 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1170 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1171 error = got_error_from_errno2("unveil",
1172 GOT_FETCH_PATH_SSH);
1173 goto done;
1176 error = apply_unveil(repo ? got_repo_get_path(repo) : NULL, 0, NULL);
1177 if (error)
1178 goto done;
1180 if (verbosity >= 0)
1181 printf("Connecting to %s%s%s\n", host,
1182 port ? ":" : "", port ? port : "");
1184 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1185 server_path, verbosity);
1186 if (error)
1187 goto done;
1189 fpa.last_scaled_size[0] = '\0';
1190 fpa.last_p_indexed = -1;
1191 fpa.last_p_resolved = -1;
1192 fpa.verbosity = verbosity;
1193 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1194 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1195 fetch_all_branches, &wanted_branches, &wanted_refs,
1196 list_refs_only, verbosity, fetchfd, repo,
1197 fetch_progress, &fpa);
1198 if (error)
1199 goto done;
1201 if (list_refs_only) {
1202 error = list_remote_refs(&symrefs, &refs);
1203 goto done;
1206 error = got_object_id_str(&id_str, pack_hash);
1207 if (error)
1208 goto done;
1209 if (verbosity >= 0)
1210 printf("\nFetched %s.pack\n", id_str);
1211 free(id_str);
1213 /* Set up references provided with the pack file. */
1214 TAILQ_FOREACH(pe, &refs, entry) {
1215 const char *refname = pe->path;
1216 struct got_object_id *id = pe->data;
1217 char *remote_refname;
1219 if (is_wanted_ref(&wanted_refs, refname) &&
1220 !mirror_references) {
1221 error = create_wanted_ref(refname, id,
1222 GOT_FETCH_DEFAULT_REMOTE_NAME,
1223 verbosity - 1, repo);
1224 if (error)
1225 goto done;
1226 continue;
1229 error = create_ref(refname, id, verbosity - 1, repo);
1230 if (error)
1231 goto done;
1233 if (mirror_references)
1234 continue;
1236 if (strncmp("refs/heads/", refname, 11) != 0)
1237 continue;
1239 if (asprintf(&remote_refname,
1240 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1241 refname + 11) == -1) {
1242 error = got_error_from_errno("asprintf");
1243 goto done;
1245 error = create_ref(remote_refname, id, verbosity - 1, repo);
1246 free(remote_refname);
1247 if (error)
1248 goto done;
1251 /* Set the HEAD reference if the server provided one. */
1252 TAILQ_FOREACH(pe, &symrefs, entry) {
1253 struct got_reference *target_ref;
1254 const char *refname = pe->path;
1255 const char *target = pe->data;
1256 char *remote_refname = NULL, *remote_target = NULL;
1258 if (strcmp(refname, GOT_REF_HEAD) != 0)
1259 continue;
1261 error = got_ref_open(&target_ref, repo, target, 0);
1262 if (error) {
1263 if (error->code == GOT_ERR_NOT_REF) {
1264 error = NULL;
1265 continue;
1267 goto done;
1270 error = create_symref(refname, target_ref, verbosity, repo);
1271 got_ref_close(target_ref);
1272 if (error)
1273 goto done;
1275 if (mirror_references)
1276 continue;
1278 if (strncmp("refs/heads/", target, 11) != 0)
1279 continue;
1281 if (asprintf(&remote_refname,
1282 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1283 refname) == -1) {
1284 error = got_error_from_errno("asprintf");
1285 goto done;
1287 if (asprintf(&remote_target,
1288 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1289 target + 11) == -1) {
1290 error = got_error_from_errno("asprintf");
1291 free(remote_refname);
1292 goto done;
1294 error = got_ref_open(&target_ref, repo, remote_target, 0);
1295 if (error) {
1296 free(remote_refname);
1297 free(remote_target);
1298 if (error->code == GOT_ERR_NOT_REF) {
1299 error = NULL;
1300 continue;
1302 goto done;
1304 error = create_symref(remote_refname, target_ref,
1305 verbosity - 1, repo);
1306 free(remote_refname);
1307 free(remote_target);
1308 got_ref_close(target_ref);
1309 if (error)
1310 goto done;
1312 if (pe == NULL) {
1314 * We failed to set the HEAD reference. If we asked for
1315 * a set of wanted branches use the first of one of those
1316 * which could be fetched instead.
1318 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1319 const char *target = pe->path;
1320 struct got_reference *target_ref;
1322 error = got_ref_open(&target_ref, repo, target, 0);
1323 if (error) {
1324 if (error->code == GOT_ERR_NOT_REF) {
1325 error = NULL;
1326 continue;
1328 goto done;
1331 error = create_symref(GOT_REF_HEAD, target_ref,
1332 verbosity, repo);
1333 got_ref_close(target_ref);
1334 if (error)
1335 goto done;
1336 break;
1340 /* Create a config file git-fetch(1) can understand. */
1341 gitconfig_path = got_repo_get_path_gitconfig(repo);
1342 if (gitconfig_path == NULL) {
1343 error = got_error_from_errno("got_repo_get_path_gitconfig");
1344 goto done;
1346 gitconfig_file = fopen(gitconfig_path, "a");
1347 if (gitconfig_file == NULL) {
1348 error = got_error_from_errno2("fopen", gitconfig_path);
1349 goto done;
1351 if (mirror_references) {
1352 if (asprintf(&gitconfig,
1353 "[remote \"%s\"]\n"
1354 "\turl = %s\n"
1355 "\tfetch = +refs/*:refs/*\n"
1356 "\tmirror = true\n",
1357 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1358 error = got_error_from_errno("asprintf");
1359 goto done;
1361 } else if (fetch_all_branches) {
1362 if (asprintf(&gitconfig,
1363 "[remote \"%s\"]\n"
1364 "\turl = %s\n"
1365 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1366 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1367 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1368 error = got_error_from_errno("asprintf");
1369 goto done;
1371 } else {
1372 const char *branchname;
1375 * If the server specified a default branch, use just that one.
1376 * Otherwise fall back to fetching all branches on next fetch.
1378 if (head_symref) {
1379 branchname = got_ref_get_symref_target(head_symref);
1380 if (strncmp(branchname, "refs/heads/", 11) == 0)
1381 branchname += 11;
1382 } else
1383 branchname = "*"; /* fall back to all branches */
1384 if (asprintf(&gitconfig,
1385 "[remote \"%s\"]\n"
1386 "\turl = %s\n"
1387 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1388 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1389 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1390 branchname) == -1) {
1391 error = got_error_from_errno("asprintf");
1392 goto done;
1395 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1396 if (n != strlen(gitconfig)) {
1397 error = got_ferror(gitconfig_file, GOT_ERR_IO);
1398 goto done;
1401 if (verbosity >= 0)
1402 printf("Created %s repository '%s'\n",
1403 mirror_references ? "mirrored" : "cloned", repo_path);
1404 done:
1405 if (fetchpid > 0) {
1406 if (kill(fetchpid, SIGTERM) == -1)
1407 error = got_error_from_errno("kill");
1408 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1409 error = got_error_from_errno("waitpid");
1411 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1412 error = got_error_from_errno("close");
1413 if (gitconfig_file && fclose(gitconfig_file) == EOF && error == NULL)
1414 error = got_error_from_errno("fclose");
1415 if (repo)
1416 got_repo_close(repo);
1417 if (head_symref)
1418 got_ref_close(head_symref);
1419 TAILQ_FOREACH(pe, &refs, entry) {
1420 free((void *)pe->path);
1421 free(pe->data);
1423 got_pathlist_free(&refs);
1424 TAILQ_FOREACH(pe, &symrefs, entry) {
1425 free((void *)pe->path);
1426 free(pe->data);
1428 got_pathlist_free(&symrefs);
1429 got_pathlist_free(&wanted_branches);
1430 got_pathlist_free(&wanted_refs);
1431 free(pack_hash);
1432 free(proto);
1433 free(host);
1434 free(port);
1435 free(server_path);
1436 free(repo_name);
1437 free(default_destdir);
1438 free(gitconfig_path);
1439 free(git_url);
1440 return error;
1443 static const struct got_error *
1444 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1445 int replace_tags, int verbosity, struct got_repository *repo)
1447 const struct got_error *err = NULL;
1448 char *new_id_str = NULL;
1449 struct got_object_id *old_id = NULL;
1451 err = got_object_id_str(&new_id_str, new_id);
1452 if (err)
1453 goto done;
1455 if (!replace_tags &&
1456 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1457 err = got_ref_resolve(&old_id, repo, ref);
1458 if (err)
1459 goto done;
1460 if (got_object_id_cmp(old_id, new_id) == 0)
1461 goto done;
1462 if (verbosity >= 0) {
1463 printf("Rejecting update of existing tag %s: %s\n",
1464 got_ref_get_name(ref), new_id_str);
1466 goto done;
1469 if (got_ref_is_symbolic(ref)) {
1470 if (verbosity >= 0) {
1471 printf("Replacing reference %s: %s\n",
1472 got_ref_get_name(ref),
1473 got_ref_get_symref_target(ref));
1475 err = got_ref_change_symref_to_ref(ref, new_id);
1476 if (err)
1477 goto done;
1478 err = got_ref_write(ref, repo);
1479 if (err)
1480 goto done;
1481 } else {
1482 err = got_ref_resolve(&old_id, repo, ref);
1483 if (err)
1484 goto done;
1485 if (got_object_id_cmp(old_id, new_id) == 0)
1486 goto done;
1488 err = got_ref_change_ref(ref, new_id);
1489 if (err)
1490 goto done;
1491 err = got_ref_write(ref, repo);
1492 if (err)
1493 goto done;
1496 if (verbosity >= 0)
1497 printf("Updated reference %s: %s\n", got_ref_get_name(ref),
1498 new_id_str);
1499 done:
1500 free(old_id);
1501 free(new_id_str);
1502 return err;
1505 static const struct got_error *
1506 update_symref(const char *refname, struct got_reference *target_ref,
1507 int verbosity, struct got_repository *repo)
1509 const struct got_error *err = NULL, *unlock_err;
1510 struct got_reference *symref;
1511 int symref_is_locked = 0;
1513 err = got_ref_open(&symref, repo, refname, 1);
1514 if (err) {
1515 if (err->code != GOT_ERR_NOT_REF)
1516 return err;
1517 err = got_ref_alloc_symref(&symref, refname, target_ref);
1518 if (err)
1519 goto done;
1521 err = got_ref_write(symref, repo);
1522 if (err)
1523 goto done;
1525 if (verbosity >= 0)
1526 printf("Created reference %s: %s\n",
1527 got_ref_get_name(symref),
1528 got_ref_get_symref_target(symref));
1529 } else {
1530 symref_is_locked = 1;
1532 if (strcmp(got_ref_get_symref_target(symref),
1533 got_ref_get_name(target_ref)) == 0)
1534 goto done;
1536 err = got_ref_change_symref(symref,
1537 got_ref_get_name(target_ref));
1538 if (err)
1539 goto done;
1541 err = got_ref_write(symref, repo);
1542 if (err)
1543 goto done;
1545 if (verbosity >= 0)
1546 printf("Updated reference %s: %s\n",
1547 got_ref_get_name(symref),
1548 got_ref_get_symref_target(symref));
1551 done:
1552 if (symref_is_locked) {
1553 unlock_err = got_ref_unlock(symref);
1554 if (unlock_err && err == NULL)
1555 err = unlock_err;
1557 got_ref_close(symref);
1558 return err;
1561 __dead static void
1562 usage_fetch(void)
1564 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1565 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1566 "[remote-repository-name]\n",
1567 getprogname());
1568 exit(1);
1571 static const struct got_error *
1572 delete_missing_ref(struct got_reference *ref,
1573 int verbosity, struct got_repository *repo)
1575 const struct got_error *err = NULL;
1576 struct got_object_id *id = NULL;
1577 char *id_str = NULL;
1579 if (got_ref_is_symbolic(ref)) {
1580 err = got_ref_delete(ref, repo);
1581 if (err)
1582 return err;
1583 if (verbosity >= 0) {
1584 printf("Deleted reference %s: %s\n",
1585 got_ref_get_name(ref),
1586 got_ref_get_symref_target(ref));
1588 } else {
1589 err = got_ref_resolve(&id, repo, ref);
1590 if (err)
1591 return err;
1592 err = got_object_id_str(&id_str, id);
1593 if (err)
1594 goto done;
1596 err = got_ref_delete(ref, repo);
1597 if (err)
1598 goto done;
1599 if (verbosity >= 0) {
1600 printf("Deleted reference %s: %s\n",
1601 got_ref_get_name(ref), id_str);
1604 done:
1605 free(id);
1606 free(id_str);
1607 return NULL;
1610 static const struct got_error *
1611 delete_missing_refs(struct got_pathlist_head *their_refs,
1612 struct got_pathlist_head *their_symrefs, struct got_remote_repo *remote,
1613 int verbosity, struct got_repository *repo)
1615 const struct got_error *err = NULL, *unlock_err;
1616 struct got_reflist_head my_refs;
1617 struct got_reflist_entry *re;
1618 struct got_pathlist_entry *pe;
1619 char *remote_namespace = NULL;
1620 char *local_refname = NULL;
1622 SIMPLEQ_INIT(&my_refs);
1624 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
1625 == -1)
1626 return got_error_from_errno("asprintf");
1628 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1629 if (err)
1630 goto done;
1632 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1633 const char *refname = got_ref_get_name(re->ref);
1635 if (!remote->mirror_references) {
1636 if (strncmp(refname, remote_namespace,
1637 strlen(remote_namespace)) == 0) {
1638 if (strcmp(refname + strlen(remote_namespace),
1639 GOT_REF_HEAD) == 0)
1640 continue;
1641 if (asprintf(&local_refname, "refs/heads/%s",
1642 refname + strlen(remote_namespace)) == -1) {
1643 err = got_error_from_errno("asprintf");
1644 goto done;
1646 } else if (strncmp(refname, "refs/tags/", 10) != 0)
1647 continue;
1650 TAILQ_FOREACH(pe, their_refs, entry) {
1651 if (strcmp(local_refname, pe->path) == 0)
1652 break;
1654 if (pe != NULL)
1655 continue;
1657 TAILQ_FOREACH(pe, their_symrefs, entry) {
1658 if (strcmp(local_refname, pe->path) == 0)
1659 break;
1661 if (pe != NULL)
1662 continue;
1664 err = delete_missing_ref(re->ref, verbosity, repo);
1665 if (err)
1666 break;
1668 if (local_refname) {
1669 struct got_reference *ref;
1670 err = got_ref_open(&ref, repo, local_refname, 1);
1671 if (err) {
1672 if (err->code != GOT_ERR_NOT_REF)
1673 break;
1674 free(local_refname);
1675 local_refname = NULL;
1676 continue;
1678 err = delete_missing_ref(ref, verbosity, repo);
1679 if (err)
1680 break;
1681 unlock_err = got_ref_unlock(ref);
1682 got_ref_close(ref);
1683 if (unlock_err && err == NULL) {
1684 err = unlock_err;
1685 break;
1688 free(local_refname);
1689 local_refname = NULL;
1692 done:
1693 free(remote_namespace);
1694 free(local_refname);
1695 return err;
1698 static const struct got_error *
1699 update_wanted_ref(const char *refname, struct got_object_id *id,
1700 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1702 const struct got_error *err, *unlock_err;
1703 char *remote_refname;
1704 struct got_reference *ref;
1706 if (strncmp("refs/", refname, 5) == 0)
1707 refname += 5;
1709 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1710 remote_repo_name, refname) == -1)
1711 return got_error_from_errno("asprintf");
1713 err = got_ref_open(&ref, repo, remote_refname, 1);
1714 if (err) {
1715 if (err->code != GOT_ERR_NOT_REF)
1716 goto done;
1717 err = create_ref(remote_refname, id, verbosity, repo);
1718 } else {
1719 err = update_ref(ref, id, 0, verbosity, repo);
1720 unlock_err = got_ref_unlock(ref);
1721 if (unlock_err && err == NULL)
1722 err = unlock_err;
1723 got_ref_close(ref);
1725 done:
1726 free(remote_refname);
1727 return err;
1730 static const struct got_error *
1731 cmd_fetch(int argc, char *argv[])
1733 const struct got_error *error = NULL, *unlock_err;
1734 char *cwd = NULL, *repo_path = NULL;
1735 const char *remote_name;
1736 char *proto = NULL, *host = NULL, *port = NULL;
1737 char *repo_name = NULL, *server_path = NULL;
1738 struct got_remote_repo *remotes, *remote = NULL;
1739 int nremotes;
1740 char *id_str = NULL;
1741 struct got_repository *repo = NULL;
1742 struct got_worktree *worktree = NULL;
1743 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1744 struct got_pathlist_entry *pe;
1745 struct got_object_id *pack_hash = NULL;
1746 int i, ch, fetchfd = -1, fetchstatus;
1747 pid_t fetchpid = -1;
1748 struct got_fetch_progress_arg fpa;
1749 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
1750 int delete_refs = 0, replace_tags = 0;
1752 TAILQ_INIT(&refs);
1753 TAILQ_INIT(&symrefs);
1754 TAILQ_INIT(&wanted_branches);
1755 TAILQ_INIT(&wanted_refs);
1757 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
1758 switch (ch) {
1759 case 'a':
1760 fetch_all_branches = 1;
1761 break;
1762 case 'b':
1763 error = got_pathlist_append(&wanted_branches,
1764 optarg, NULL);
1765 if (error)
1766 return error;
1767 break;
1768 case 'd':
1769 delete_refs = 1;
1770 break;
1771 case 'l':
1772 list_refs_only = 1;
1773 break;
1774 case 'r':
1775 repo_path = realpath(optarg, NULL);
1776 if (repo_path == NULL)
1777 return got_error_from_errno2("realpath",
1778 optarg);
1779 got_path_strip_trailing_slashes(repo_path);
1780 break;
1781 case 't':
1782 replace_tags = 1;
1783 break;
1784 case 'v':
1785 if (verbosity < 0)
1786 verbosity = 0;
1787 else if (verbosity < 3)
1788 verbosity++;
1789 break;
1790 case 'q':
1791 verbosity = -1;
1792 break;
1793 case 'R':
1794 error = got_pathlist_append(&wanted_refs,
1795 optarg, NULL);
1796 if (error)
1797 return error;
1798 break;
1799 default:
1800 usage_fetch();
1801 break;
1804 argc -= optind;
1805 argv += optind;
1807 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1808 errx(1, "-a and -b options are mutually exclusive");
1809 if (list_refs_only) {
1810 if (!TAILQ_EMPTY(&wanted_branches))
1811 errx(1, "-l and -b options are mutually exclusive");
1812 if (fetch_all_branches)
1813 errx(1, "-l and -a options are mutually exclusive");
1814 if (delete_refs)
1815 errx(1, "-l and -d options are mutually exclusive");
1816 if (verbosity == -1)
1817 errx(1, "-l and -q options are mutually exclusive");
1820 if (argc == 0)
1821 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
1822 else if (argc == 1)
1823 remote_name = argv[0];
1824 else
1825 usage_fetch();
1827 cwd = getcwd(NULL, 0);
1828 if (cwd == NULL) {
1829 error = got_error_from_errno("getcwd");
1830 goto done;
1833 if (repo_path == NULL) {
1834 error = got_worktree_open(&worktree, cwd);
1835 if (error && error->code != GOT_ERR_NOT_WORKTREE)
1836 goto done;
1837 else
1838 error = NULL;
1839 if (worktree) {
1840 repo_path =
1841 strdup(got_worktree_get_repo_path(worktree));
1842 if (repo_path == NULL)
1843 error = got_error_from_errno("strdup");
1844 if (error)
1845 goto done;
1846 } else {
1847 repo_path = strdup(cwd);
1848 if (repo_path == NULL) {
1849 error = got_error_from_errno("strdup");
1850 goto done;
1855 error = got_repo_open(&repo, repo_path, NULL);
1856 if (error)
1857 goto done;
1859 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
1860 for (i = 0; i < nremotes; i++) {
1861 remote = &remotes[i];
1862 if (strcmp(remote->name, remote_name) == 0)
1863 break;
1865 if (i == nremotes) {
1866 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
1867 goto done;
1870 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1871 &repo_name, remote->url);
1872 if (error)
1873 goto done;
1875 if (strcmp(proto, "git") == 0) {
1876 #ifndef PROFILE
1877 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1878 "sendfd dns inet unveil", NULL) == -1)
1879 err(1, "pledge");
1880 #endif
1881 } else if (strcmp(proto, "git+ssh") == 0 ||
1882 strcmp(proto, "ssh") == 0) {
1883 #ifndef PROFILE
1884 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1885 "sendfd unveil", NULL) == -1)
1886 err(1, "pledge");
1887 #endif
1888 } else if (strcmp(proto, "http") == 0 ||
1889 strcmp(proto, "git+http") == 0) {
1890 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1891 goto done;
1892 } else {
1893 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1894 goto done;
1897 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1898 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1899 error = got_error_from_errno2("unveil",
1900 GOT_FETCH_PATH_SSH);
1901 goto done;
1904 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
1905 if (error)
1906 goto done;
1908 if (verbosity >= 0)
1909 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
1910 port ? ":" : "", port ? port : "");
1912 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1913 server_path, verbosity);
1914 if (error)
1915 goto done;
1917 fpa.last_scaled_size[0] = '\0';
1918 fpa.last_p_indexed = -1;
1919 fpa.last_p_resolved = -1;
1920 fpa.verbosity = verbosity;
1921 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
1922 remote->mirror_references, fetch_all_branches, &wanted_branches,
1923 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
1924 fetch_progress, &fpa);
1925 if (error)
1926 goto done;
1928 if (list_refs_only) {
1929 error = list_remote_refs(&symrefs, &refs);
1930 goto done;
1933 if (pack_hash == NULL) {
1934 if (verbosity >= 0)
1935 printf("Already up-to-date\n");
1936 } else if (verbosity >= 0) {
1937 error = got_object_id_str(&id_str, pack_hash);
1938 if (error)
1939 goto done;
1940 printf("\nFetched %s.pack\n", id_str);
1941 free(id_str);
1942 id_str = NULL;
1945 /* Update references provided with the pack file. */
1946 TAILQ_FOREACH(pe, &refs, entry) {
1947 const char *refname = pe->path;
1948 struct got_object_id *id = pe->data;
1949 struct got_reference *ref;
1950 char *remote_refname;
1952 if (is_wanted_ref(&wanted_refs, refname) &&
1953 !remote->mirror_references) {
1954 error = update_wanted_ref(refname, id,
1955 remote->name, verbosity, repo);
1956 if (error)
1957 goto done;
1958 continue;
1961 if (remote->mirror_references ||
1962 strncmp("refs/tags/", refname, 10) == 0) {
1963 error = got_ref_open(&ref, repo, refname, 1);
1964 if (error) {
1965 if (error->code != GOT_ERR_NOT_REF)
1966 goto done;
1967 error = create_ref(refname, id, verbosity,
1968 repo);
1969 if (error)
1970 goto done;
1971 } else {
1972 error = update_ref(ref, id, replace_tags,
1973 verbosity, repo);
1974 unlock_err = got_ref_unlock(ref);
1975 if (unlock_err && error == NULL)
1976 error = unlock_err;
1977 got_ref_close(ref);
1978 if (error)
1979 goto done;
1981 } else if (strncmp("refs/heads/", refname, 11) == 0) {
1982 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1983 remote_name, refname + 11) == -1) {
1984 error = got_error_from_errno("asprintf");
1985 goto done;
1988 error = got_ref_open(&ref, repo, remote_refname, 1);
1989 if (error) {
1990 if (error->code != GOT_ERR_NOT_REF)
1991 goto done;
1992 error = create_ref(remote_refname, id,
1993 verbosity, repo);
1994 if (error)
1995 goto done;
1996 } else {
1997 error = update_ref(ref, id, replace_tags,
1998 verbosity, repo);
1999 unlock_err = got_ref_unlock(ref);
2000 if (unlock_err && error == NULL)
2001 error = unlock_err;
2002 got_ref_close(ref);
2003 if (error)
2004 goto done;
2007 /* Also create a local branch if none exists yet. */
2008 error = got_ref_open(&ref, repo, refname, 1);
2009 if (error) {
2010 if (error->code != GOT_ERR_NOT_REF)
2011 goto done;
2012 error = create_ref(refname, id, verbosity,
2013 repo);
2014 if (error)
2015 goto done;
2016 } else {
2017 unlock_err = got_ref_unlock(ref);
2018 if (unlock_err && error == NULL)
2019 error = unlock_err;
2020 got_ref_close(ref);
2024 if (delete_refs) {
2025 error = delete_missing_refs(&refs, &symrefs, remote,
2026 verbosity, repo);
2027 if (error)
2028 goto done;
2031 if (!remote->mirror_references) {
2032 /* Update remote HEAD reference if the server provided one. */
2033 TAILQ_FOREACH(pe, &symrefs, entry) {
2034 struct got_reference *target_ref;
2035 const char *refname = pe->path;
2036 const char *target = pe->data;
2037 char *remote_refname = NULL, *remote_target = NULL;
2039 if (strcmp(refname, GOT_REF_HEAD) != 0)
2040 continue;
2042 if (strncmp("refs/heads/", target, 11) != 0)
2043 continue;
2045 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2046 remote->name, refname) == -1) {
2047 error = got_error_from_errno("asprintf");
2048 goto done;
2050 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2051 remote->name, target + 11) == -1) {
2052 error = got_error_from_errno("asprintf");
2053 free(remote_refname);
2054 goto done;
2057 error = got_ref_open(&target_ref, repo, remote_target,
2058 0);
2059 if (error) {
2060 free(remote_refname);
2061 free(remote_target);
2062 if (error->code == GOT_ERR_NOT_REF) {
2063 error = NULL;
2064 continue;
2066 goto done;
2068 error = update_symref(remote_refname, target_ref,
2069 verbosity, repo);
2070 free(remote_refname);
2071 free(remote_target);
2072 got_ref_close(target_ref);
2073 if (error)
2074 goto done;
2077 done:
2078 if (fetchpid > 0) {
2079 if (kill(fetchpid, SIGTERM) == -1)
2080 error = got_error_from_errno("kill");
2081 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2082 error = got_error_from_errno("waitpid");
2084 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2085 error = got_error_from_errno("close");
2086 if (repo)
2087 got_repo_close(repo);
2088 if (worktree)
2089 got_worktree_close(worktree);
2090 TAILQ_FOREACH(pe, &refs, entry) {
2091 free((void *)pe->path);
2092 free(pe->data);
2094 got_pathlist_free(&refs);
2095 TAILQ_FOREACH(pe, &symrefs, entry) {
2096 free((void *)pe->path);
2097 free(pe->data);
2099 got_pathlist_free(&symrefs);
2100 got_pathlist_free(&wanted_branches);
2101 got_pathlist_free(&wanted_refs);
2102 free(id_str);
2103 free(cwd);
2104 free(repo_path);
2105 free(pack_hash);
2106 free(proto);
2107 free(host);
2108 free(port);
2109 free(server_path);
2110 free(repo_name);
2111 return error;
2115 __dead static void
2116 usage_checkout(void)
2118 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2119 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2120 exit(1);
2123 static void
2124 show_worktree_base_ref_warning(void)
2126 fprintf(stderr, "%s: warning: could not create a reference "
2127 "to the work tree's base commit; the commit could be "
2128 "garbage-collected by Git; making the repository "
2129 "writable and running 'got update' will prevent this\n",
2130 getprogname());
2133 struct got_checkout_progress_arg {
2134 const char *worktree_path;
2135 int had_base_commit_ref_error;
2138 static const struct got_error *
2139 checkout_progress(void *arg, unsigned char status, const char *path)
2141 struct got_checkout_progress_arg *a = arg;
2143 /* Base commit bump happens silently. */
2144 if (status == GOT_STATUS_BUMP_BASE)
2145 return NULL;
2147 if (status == GOT_STATUS_BASE_REF_ERR) {
2148 a->had_base_commit_ref_error = 1;
2149 return NULL;
2152 while (path[0] == '/')
2153 path++;
2155 printf("%c %s/%s\n", status, a->worktree_path, path);
2156 return NULL;
2159 static const struct got_error *
2160 check_cancelled(void *arg)
2162 if (sigint_received || sigpipe_received)
2163 return got_error(GOT_ERR_CANCELLED);
2164 return NULL;
2167 static const struct got_error *
2168 check_linear_ancestry(struct got_object_id *commit_id,
2169 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2170 struct got_repository *repo)
2172 const struct got_error *err = NULL;
2173 struct got_object_id *yca_id;
2175 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2176 commit_id, base_commit_id, repo, check_cancelled, NULL);
2177 if (err)
2178 return err;
2180 if (yca_id == NULL)
2181 return got_error(GOT_ERR_ANCESTRY);
2184 * Require a straight line of history between the target commit
2185 * and the work tree's base commit.
2187 * Non-linear situations such as this require a rebase:
2189 * (commit) D F (base_commit)
2190 * \ /
2191 * C E
2192 * \ /
2193 * B (yca)
2194 * |
2195 * A
2197 * 'got update' only handles linear cases:
2198 * Update forwards in time: A (base/yca) - B - C - D (commit)
2199 * Update backwards in time: D (base) - C - B - A (commit/yca)
2201 if (allow_forwards_in_time_only) {
2202 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2203 return got_error(GOT_ERR_ANCESTRY);
2204 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2205 got_object_id_cmp(base_commit_id, yca_id) != 0)
2206 return got_error(GOT_ERR_ANCESTRY);
2208 free(yca_id);
2209 return NULL;
2212 static const struct got_error *
2213 check_same_branch(struct got_object_id *commit_id,
2214 struct got_reference *head_ref, struct got_object_id *yca_id,
2215 struct got_repository *repo)
2217 const struct got_error *err = NULL;
2218 struct got_commit_graph *graph = NULL;
2219 struct got_object_id *head_commit_id = NULL;
2220 int is_same_branch = 0;
2222 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2223 if (err)
2224 goto done;
2226 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2227 is_same_branch = 1;
2228 goto done;
2230 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2231 is_same_branch = 1;
2232 goto done;
2235 err = got_commit_graph_open(&graph, "/", 1);
2236 if (err)
2237 goto done;
2239 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2240 check_cancelled, NULL);
2241 if (err)
2242 goto done;
2244 for (;;) {
2245 struct got_object_id *id;
2246 err = got_commit_graph_iter_next(&id, graph, repo,
2247 check_cancelled, NULL);
2248 if (err) {
2249 if (err->code == GOT_ERR_ITER_COMPLETED)
2250 err = NULL;
2251 break;
2254 if (id) {
2255 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2256 break;
2257 if (got_object_id_cmp(id, commit_id) == 0) {
2258 is_same_branch = 1;
2259 break;
2263 done:
2264 if (graph)
2265 got_commit_graph_close(graph);
2266 free(head_commit_id);
2267 if (!err && !is_same_branch)
2268 err = got_error(GOT_ERR_ANCESTRY);
2269 return err;
2272 static const struct got_error *
2273 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2275 static char msg[512];
2276 const char *branch_name;
2278 if (got_ref_is_symbolic(ref))
2279 branch_name = got_ref_get_symref_target(ref);
2280 else
2281 branch_name = got_ref_get_name(ref);
2283 if (strncmp("refs/heads/", branch_name, 11) == 0)
2284 branch_name += 11;
2286 snprintf(msg, sizeof(msg),
2287 "target commit is not contained in branch '%s'; "
2288 "the branch to use must be specified with -b; "
2289 "if necessary a new branch can be created for "
2290 "this commit with 'got branch -c %s BRANCH_NAME'",
2291 branch_name, commit_id_str);
2293 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2296 static const struct got_error *
2297 cmd_checkout(int argc, char *argv[])
2299 const struct got_error *error = NULL;
2300 struct got_repository *repo = NULL;
2301 struct got_reference *head_ref = NULL;
2302 struct got_worktree *worktree = NULL;
2303 char *repo_path = NULL;
2304 char *worktree_path = NULL;
2305 const char *path_prefix = "";
2306 const char *branch_name = GOT_REF_HEAD;
2307 char *commit_id_str = NULL;
2308 int ch, same_path_prefix, allow_nonempty = 0;
2309 struct got_pathlist_head paths;
2310 struct got_checkout_progress_arg cpa;
2312 TAILQ_INIT(&paths);
2314 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2315 switch (ch) {
2316 case 'b':
2317 branch_name = optarg;
2318 break;
2319 case 'c':
2320 commit_id_str = strdup(optarg);
2321 if (commit_id_str == NULL)
2322 return got_error_from_errno("strdup");
2323 break;
2324 case 'E':
2325 allow_nonempty = 1;
2326 break;
2327 case 'p':
2328 path_prefix = optarg;
2329 break;
2330 default:
2331 usage_checkout();
2332 /* NOTREACHED */
2336 argc -= optind;
2337 argv += optind;
2339 #ifndef PROFILE
2340 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2341 "unveil", NULL) == -1)
2342 err(1, "pledge");
2343 #endif
2344 if (argc == 1) {
2345 char *cwd, *base, *dotgit;
2346 repo_path = realpath(argv[0], NULL);
2347 if (repo_path == NULL)
2348 return got_error_from_errno2("realpath", argv[0]);
2349 cwd = getcwd(NULL, 0);
2350 if (cwd == NULL) {
2351 error = got_error_from_errno("getcwd");
2352 goto done;
2354 if (path_prefix[0]) {
2355 base = basename(path_prefix);
2356 if (base == NULL) {
2357 error = got_error_from_errno2("basename",
2358 path_prefix);
2359 goto done;
2361 } else {
2362 base = basename(repo_path);
2363 if (base == NULL) {
2364 error = got_error_from_errno2("basename",
2365 repo_path);
2366 goto done;
2369 dotgit = strstr(base, ".git");
2370 if (dotgit)
2371 *dotgit = '\0';
2372 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2373 error = got_error_from_errno("asprintf");
2374 free(cwd);
2375 goto done;
2377 free(cwd);
2378 } else if (argc == 2) {
2379 repo_path = realpath(argv[0], NULL);
2380 if (repo_path == NULL) {
2381 error = got_error_from_errno2("realpath", argv[0]);
2382 goto done;
2384 worktree_path = realpath(argv[1], NULL);
2385 if (worktree_path == NULL) {
2386 if (errno != ENOENT) {
2387 error = got_error_from_errno2("realpath",
2388 argv[1]);
2389 goto done;
2391 worktree_path = strdup(argv[1]);
2392 if (worktree_path == NULL) {
2393 error = got_error_from_errno("strdup");
2394 goto done;
2397 } else
2398 usage_checkout();
2400 got_path_strip_trailing_slashes(repo_path);
2401 got_path_strip_trailing_slashes(worktree_path);
2403 error = got_repo_open(&repo, repo_path, NULL);
2404 if (error != NULL)
2405 goto done;
2407 /* Pre-create work tree path for unveil(2) */
2408 error = got_path_mkdir(worktree_path);
2409 if (error) {
2410 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2411 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2412 goto done;
2413 if (!allow_nonempty &&
2414 !got_path_dir_is_empty(worktree_path)) {
2415 error = got_error_path(worktree_path,
2416 GOT_ERR_DIR_NOT_EMPTY);
2417 goto done;
2421 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2422 if (error)
2423 goto done;
2425 error = got_ref_open(&head_ref, repo, branch_name, 0);
2426 if (error != NULL)
2427 goto done;
2429 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2430 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2431 goto done;
2433 error = got_worktree_open(&worktree, worktree_path);
2434 if (error != NULL)
2435 goto done;
2437 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2438 path_prefix);
2439 if (error != NULL)
2440 goto done;
2441 if (!same_path_prefix) {
2442 error = got_error(GOT_ERR_PATH_PREFIX);
2443 goto done;
2446 if (commit_id_str) {
2447 struct got_object_id *commit_id;
2448 error = got_repo_match_object_id(&commit_id, NULL,
2449 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2450 if (error)
2451 goto done;
2452 error = check_linear_ancestry(commit_id,
2453 got_worktree_get_base_commit_id(worktree), 0, repo);
2454 if (error != NULL) {
2455 free(commit_id);
2456 if (error->code == GOT_ERR_ANCESTRY) {
2457 error = checkout_ancestry_error(
2458 head_ref, commit_id_str);
2460 goto done;
2462 error = check_same_branch(commit_id, head_ref, NULL, repo);
2463 if (error) {
2464 if (error->code == GOT_ERR_ANCESTRY) {
2465 error = checkout_ancestry_error(
2466 head_ref, commit_id_str);
2468 goto done;
2470 error = got_worktree_set_base_commit_id(worktree, repo,
2471 commit_id);
2472 free(commit_id);
2473 if (error)
2474 goto done;
2477 error = got_pathlist_append(&paths, "", NULL);
2478 if (error)
2479 goto done;
2480 cpa.worktree_path = worktree_path;
2481 cpa.had_base_commit_ref_error = 0;
2482 error = got_worktree_checkout_files(worktree, &paths, repo,
2483 checkout_progress, &cpa, check_cancelled, NULL);
2484 if (error != NULL)
2485 goto done;
2487 printf("Now shut up and hack\n");
2488 if (cpa.had_base_commit_ref_error)
2489 show_worktree_base_ref_warning();
2490 done:
2491 got_pathlist_free(&paths);
2492 free(commit_id_str);
2493 free(repo_path);
2494 free(worktree_path);
2495 return error;
2498 struct got_update_progress_arg {
2499 int did_something;
2500 int conflicts;
2501 int obstructed;
2502 int not_updated;
2505 void
2506 print_update_progress_stats(struct got_update_progress_arg *upa)
2508 if (!upa->did_something)
2509 return;
2511 if (upa->conflicts > 0)
2512 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2513 if (upa->obstructed > 0)
2514 printf("File paths obstructed by a non-regular file: %d\n",
2515 upa->obstructed);
2516 if (upa->not_updated > 0)
2517 printf("Files not updated because of existing merge "
2518 "conflicts: %d\n", upa->not_updated);
2521 __dead static void
2522 usage_update(void)
2524 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2525 getprogname());
2526 exit(1);
2529 static const struct got_error *
2530 update_progress(void *arg, unsigned char status, const char *path)
2532 struct got_update_progress_arg *upa = arg;
2534 if (status == GOT_STATUS_EXISTS ||
2535 status == GOT_STATUS_BASE_REF_ERR)
2536 return NULL;
2538 upa->did_something = 1;
2540 /* Base commit bump happens silently. */
2541 if (status == GOT_STATUS_BUMP_BASE)
2542 return NULL;
2544 if (status == GOT_STATUS_CONFLICT)
2545 upa->conflicts++;
2546 if (status == GOT_STATUS_OBSTRUCTED)
2547 upa->obstructed++;
2548 if (status == GOT_STATUS_CANNOT_UPDATE)
2549 upa->not_updated++;
2551 while (path[0] == '/')
2552 path++;
2553 printf("%c %s\n", status, path);
2554 return NULL;
2557 static const struct got_error *
2558 switch_head_ref(struct got_reference *head_ref,
2559 struct got_object_id *commit_id, struct got_worktree *worktree,
2560 struct got_repository *repo)
2562 const struct got_error *err = NULL;
2563 char *base_id_str;
2564 int ref_has_moved = 0;
2566 /* Trivial case: switching between two different references. */
2567 if (strcmp(got_ref_get_name(head_ref),
2568 got_worktree_get_head_ref_name(worktree)) != 0) {
2569 printf("Switching work tree from %s to %s\n",
2570 got_worktree_get_head_ref_name(worktree),
2571 got_ref_get_name(head_ref));
2572 return got_worktree_set_head_ref(worktree, head_ref);
2575 err = check_linear_ancestry(commit_id,
2576 got_worktree_get_base_commit_id(worktree), 0, repo);
2577 if (err) {
2578 if (err->code != GOT_ERR_ANCESTRY)
2579 return err;
2580 ref_has_moved = 1;
2582 if (!ref_has_moved)
2583 return NULL;
2585 /* Switching to a rebased branch with the same reference name. */
2586 err = got_object_id_str(&base_id_str,
2587 got_worktree_get_base_commit_id(worktree));
2588 if (err)
2589 return err;
2590 printf("Reference %s now points at a different branch\n",
2591 got_worktree_get_head_ref_name(worktree));
2592 printf("Switching work tree from %s to %s\n", base_id_str,
2593 got_worktree_get_head_ref_name(worktree));
2594 return NULL;
2597 static const struct got_error *
2598 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2600 const struct got_error *err;
2601 int in_progress;
2603 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2604 if (err)
2605 return err;
2606 if (in_progress)
2607 return got_error(GOT_ERR_REBASING);
2609 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2610 if (err)
2611 return err;
2612 if (in_progress)
2613 return got_error(GOT_ERR_HISTEDIT_BUSY);
2615 return NULL;
2618 static const struct got_error *
2619 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2620 char *argv[], struct got_worktree *worktree)
2622 const struct got_error *err = NULL;
2623 char *path;
2624 int i;
2626 if (argc == 0) {
2627 path = strdup("");
2628 if (path == NULL)
2629 return got_error_from_errno("strdup");
2630 return got_pathlist_append(paths, path, NULL);
2633 for (i = 0; i < argc; i++) {
2634 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2635 if (err)
2636 break;
2637 err = got_pathlist_append(paths, path, NULL);
2638 if (err) {
2639 free(path);
2640 break;
2644 return err;
2647 static const struct got_error *
2648 wrap_not_worktree_error(const struct got_error *orig_err,
2649 const char *cmdname, const char *path)
2651 const struct got_error *err;
2652 struct got_repository *repo;
2653 static char msg[512];
2655 err = got_repo_open(&repo, path, NULL);
2656 if (err)
2657 return orig_err;
2659 snprintf(msg, sizeof(msg),
2660 "'got %s' needs a work tree in addition to a git repository\n"
2661 "Work trees can be checked out from this Git repository with "
2662 "'got checkout'.\n"
2663 "The got(1) manual page contains more information.", cmdname);
2664 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2665 got_repo_close(repo);
2666 return err;
2669 static const struct got_error *
2670 cmd_update(int argc, char *argv[])
2672 const struct got_error *error = NULL;
2673 struct got_repository *repo = NULL;
2674 struct got_worktree *worktree = NULL;
2675 char *worktree_path = NULL;
2676 struct got_object_id *commit_id = NULL;
2677 char *commit_id_str = NULL;
2678 const char *branch_name = NULL;
2679 struct got_reference *head_ref = NULL;
2680 struct got_pathlist_head paths;
2681 struct got_pathlist_entry *pe;
2682 int ch;
2683 struct got_update_progress_arg upa;
2685 TAILQ_INIT(&paths);
2687 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2688 switch (ch) {
2689 case 'b':
2690 branch_name = optarg;
2691 break;
2692 case 'c':
2693 commit_id_str = strdup(optarg);
2694 if (commit_id_str == NULL)
2695 return got_error_from_errno("strdup");
2696 break;
2697 default:
2698 usage_update();
2699 /* NOTREACHED */
2703 argc -= optind;
2704 argv += optind;
2706 #ifndef PROFILE
2707 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2708 "unveil", NULL) == -1)
2709 err(1, "pledge");
2710 #endif
2711 worktree_path = getcwd(NULL, 0);
2712 if (worktree_path == NULL) {
2713 error = got_error_from_errno("getcwd");
2714 goto done;
2716 error = got_worktree_open(&worktree, worktree_path);
2717 if (error) {
2718 if (error->code == GOT_ERR_NOT_WORKTREE)
2719 error = wrap_not_worktree_error(error, "update",
2720 worktree_path);
2721 goto done;
2724 error = check_rebase_or_histedit_in_progress(worktree);
2725 if (error)
2726 goto done;
2728 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
2729 NULL);
2730 if (error != NULL)
2731 goto done;
2733 error = apply_unveil(got_repo_get_path(repo), 0,
2734 got_worktree_get_root_path(worktree));
2735 if (error)
2736 goto done;
2738 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2739 if (error)
2740 goto done;
2742 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
2743 got_worktree_get_head_ref_name(worktree), 0);
2744 if (error != NULL)
2745 goto done;
2746 if (commit_id_str == NULL) {
2747 error = got_ref_resolve(&commit_id, repo, head_ref);
2748 if (error != NULL)
2749 goto done;
2750 error = got_object_id_str(&commit_id_str, commit_id);
2751 if (error != NULL)
2752 goto done;
2753 } else {
2754 error = got_repo_match_object_id(&commit_id, NULL,
2755 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2756 free(commit_id_str);
2757 commit_id_str = NULL;
2758 if (error)
2759 goto done;
2760 error = got_object_id_str(&commit_id_str, commit_id);
2761 if (error)
2762 goto done;
2765 if (branch_name) {
2766 struct got_object_id *head_commit_id;
2767 TAILQ_FOREACH(pe, &paths, entry) {
2768 if (pe->path_len == 0)
2769 continue;
2770 error = got_error_msg(GOT_ERR_BAD_PATH,
2771 "switching between branches requires that "
2772 "the entire work tree gets updated");
2773 goto done;
2775 error = got_ref_resolve(&head_commit_id, repo, head_ref);
2776 if (error)
2777 goto done;
2778 error = check_linear_ancestry(commit_id, head_commit_id, 0,
2779 repo);
2780 free(head_commit_id);
2781 if (error != NULL)
2782 goto done;
2783 error = check_same_branch(commit_id, head_ref, NULL, repo);
2784 if (error)
2785 goto done;
2786 error = switch_head_ref(head_ref, commit_id, worktree, repo);
2787 if (error)
2788 goto done;
2789 } else {
2790 error = check_linear_ancestry(commit_id,
2791 got_worktree_get_base_commit_id(worktree), 0, repo);
2792 if (error != NULL) {
2793 if (error->code == GOT_ERR_ANCESTRY)
2794 error = got_error(GOT_ERR_BRANCH_MOVED);
2795 goto done;
2797 error = check_same_branch(commit_id, head_ref, NULL, repo);
2798 if (error)
2799 goto done;
2802 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
2803 commit_id) != 0) {
2804 error = got_worktree_set_base_commit_id(worktree, repo,
2805 commit_id);
2806 if (error)
2807 goto done;
2810 memset(&upa, 0, sizeof(upa));
2811 error = got_worktree_checkout_files(worktree, &paths, repo,
2812 update_progress, &upa, check_cancelled, NULL);
2813 if (error != NULL)
2814 goto done;
2816 if (upa.did_something)
2817 printf("Updated to commit %s\n", commit_id_str);
2818 else
2819 printf("Already up-to-date\n");
2820 print_update_progress_stats(&upa);
2821 done:
2822 free(worktree_path);
2823 TAILQ_FOREACH(pe, &paths, entry)
2824 free((char *)pe->path);
2825 got_pathlist_free(&paths);
2826 free(commit_id);
2827 free(commit_id_str);
2828 return error;
2831 static const struct got_error *
2832 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
2833 const char *path, int diff_context, int ignore_whitespace,
2834 struct got_repository *repo)
2836 const struct got_error *err = NULL;
2837 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
2839 if (blob_id1) {
2840 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
2841 if (err)
2842 goto done;
2845 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
2846 if (err)
2847 goto done;
2849 while (path[0] == '/')
2850 path++;
2851 err = got_diff_blob(blob1, blob2, path, path, diff_context,
2852 ignore_whitespace, stdout);
2853 done:
2854 if (blob1)
2855 got_object_blob_close(blob1);
2856 got_object_blob_close(blob2);
2857 return err;
2860 static const struct got_error *
2861 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
2862 const char *path, int diff_context, int ignore_whitespace,
2863 struct got_repository *repo)
2865 const struct got_error *err = NULL;
2866 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
2867 struct got_diff_blob_output_unidiff_arg arg;
2869 if (tree_id1) {
2870 err = got_object_open_as_tree(&tree1, repo, tree_id1);
2871 if (err)
2872 goto done;
2875 err = got_object_open_as_tree(&tree2, repo, tree_id2);
2876 if (err)
2877 goto done;
2879 arg.diff_context = diff_context;
2880 arg.ignore_whitespace = ignore_whitespace;
2881 arg.outfile = stdout;
2882 while (path[0] == '/')
2883 path++;
2884 err = got_diff_tree(tree1, tree2, path, path, repo,
2885 got_diff_blob_output_unidiff, &arg, 1);
2886 done:
2887 if (tree1)
2888 got_object_tree_close(tree1);
2889 if (tree2)
2890 got_object_tree_close(tree2);
2891 return err;
2894 static const struct got_error *
2895 print_patch(struct got_commit_object *commit, struct got_object_id *id,
2896 const char *path, int diff_context, struct got_repository *repo)
2898 const struct got_error *err = NULL;
2899 struct got_commit_object *pcommit = NULL;
2900 char *id_str1 = NULL, *id_str2 = NULL;
2901 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
2902 struct got_object_qid *qid;
2904 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
2905 if (qid != NULL) {
2906 err = got_object_open_as_commit(&pcommit, repo,
2907 qid->id);
2908 if (err)
2909 return err;
2912 if (path && path[0] != '\0') {
2913 int obj_type;
2914 err = got_object_id_by_path(&obj_id2, repo, id, path);
2915 if (err)
2916 goto done;
2917 err = got_object_id_str(&id_str2, obj_id2);
2918 if (err) {
2919 free(obj_id2);
2920 goto done;
2922 if (pcommit) {
2923 err = got_object_id_by_path(&obj_id1, repo,
2924 qid->id, path);
2925 if (err) {
2926 free(obj_id2);
2927 goto done;
2929 err = got_object_id_str(&id_str1, obj_id1);
2930 if (err) {
2931 free(obj_id2);
2932 goto done;
2935 err = got_object_get_type(&obj_type, repo, obj_id2);
2936 if (err) {
2937 free(obj_id2);
2938 goto done;
2940 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2941 switch (obj_type) {
2942 case GOT_OBJ_TYPE_BLOB:
2943 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
2944 0, repo);
2945 break;
2946 case GOT_OBJ_TYPE_TREE:
2947 err = diff_trees(obj_id1, obj_id2, path, diff_context,
2948 0, repo);
2949 break;
2950 default:
2951 err = got_error(GOT_ERR_OBJ_TYPE);
2952 break;
2954 free(obj_id1);
2955 free(obj_id2);
2956 } else {
2957 obj_id2 = got_object_commit_get_tree_id(commit);
2958 err = got_object_id_str(&id_str2, obj_id2);
2959 if (err)
2960 goto done;
2961 obj_id1 = got_object_commit_get_tree_id(pcommit);
2962 err = got_object_id_str(&id_str1, obj_id1);
2963 if (err)
2964 goto done;
2965 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2966 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
2968 done:
2969 free(id_str1);
2970 free(id_str2);
2971 if (pcommit)
2972 got_object_commit_close(pcommit);
2973 return err;
2976 static char *
2977 get_datestr(time_t *time, char *datebuf)
2979 struct tm mytm, *tm;
2980 char *p, *s;
2982 tm = gmtime_r(time, &mytm);
2983 if (tm == NULL)
2984 return NULL;
2985 s = asctime_r(tm, datebuf);
2986 if (s == NULL)
2987 return NULL;
2988 p = strchr(s, '\n');
2989 if (p)
2990 *p = '\0';
2991 return s;
2994 static const struct got_error *
2995 match_logmsg(int *have_match, struct got_object_id *id,
2996 struct got_commit_object *commit, regex_t *regex)
2998 const struct got_error *err = NULL;
2999 regmatch_t regmatch;
3000 char *id_str = NULL, *logmsg = NULL;
3002 *have_match = 0;
3004 err = got_object_id_str(&id_str, id);
3005 if (err)
3006 return err;
3008 err = got_object_commit_get_logmsg(&logmsg, commit);
3009 if (err)
3010 goto done;
3012 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3013 *have_match = 1;
3014 done:
3015 free(id_str);
3016 free(logmsg);
3017 return err;
3020 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3022 static const struct got_error *
3023 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3024 struct got_repository *repo, const char *path, int show_patch,
3025 int diff_context, struct got_reflist_head *refs)
3027 const struct got_error *err = NULL;
3028 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3029 char datebuf[26];
3030 time_t committer_time;
3031 const char *author, *committer;
3032 char *refs_str = NULL;
3033 struct got_reflist_entry *re;
3035 SIMPLEQ_FOREACH(re, refs, entry) {
3036 char *s;
3037 const char *name;
3038 struct got_tag_object *tag = NULL;
3039 int cmp;
3041 name = got_ref_get_name(re->ref);
3042 if (strcmp(name, GOT_REF_HEAD) == 0)
3043 continue;
3044 if (strncmp(name, "refs/", 5) == 0)
3045 name += 5;
3046 if (strncmp(name, "got/", 4) == 0)
3047 continue;
3048 if (strncmp(name, "heads/", 6) == 0)
3049 name += 6;
3050 if (strncmp(name, "remotes/", 8) == 0)
3051 name += 8;
3052 if (strncmp(name, "tags/", 5) == 0) {
3053 err = got_object_open_as_tag(&tag, repo, re->id);
3054 if (err) {
3055 if (err->code != GOT_ERR_OBJ_TYPE)
3056 return err;
3057 /* Ref points at something other than a tag. */
3058 err = NULL;
3059 tag = NULL;
3062 cmp = got_object_id_cmp(tag ?
3063 got_object_tag_get_object_id(tag) : re->id, id);
3064 if (tag)
3065 got_object_tag_close(tag);
3066 if (cmp != 0)
3067 continue;
3068 s = refs_str;
3069 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3070 name) == -1) {
3071 err = got_error_from_errno("asprintf");
3072 free(s);
3073 return err;
3075 free(s);
3077 err = got_object_id_str(&id_str, id);
3078 if (err)
3079 return err;
3081 printf(GOT_COMMIT_SEP_STR);
3082 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3083 refs_str ? refs_str : "", refs_str ? ")" : "");
3084 free(id_str);
3085 id_str = NULL;
3086 free(refs_str);
3087 refs_str = NULL;
3088 printf("from: %s\n", got_object_commit_get_author(commit));
3089 committer_time = got_object_commit_get_committer_time(commit);
3090 datestr = get_datestr(&committer_time, datebuf);
3091 if (datestr)
3092 printf("date: %s UTC\n", datestr);
3093 author = got_object_commit_get_author(commit);
3094 committer = got_object_commit_get_committer(commit);
3095 if (strcmp(author, committer) != 0)
3096 printf("via: %s\n", committer);
3097 if (got_object_commit_get_nparents(commit) > 1) {
3098 const struct got_object_id_queue *parent_ids;
3099 struct got_object_qid *qid;
3100 int n = 1;
3101 parent_ids = got_object_commit_get_parent_ids(commit);
3102 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3103 err = got_object_id_str(&id_str, qid->id);
3104 if (err)
3105 return err;
3106 printf("parent %d: %s\n", n++, id_str);
3107 free(id_str);
3111 err = got_object_commit_get_logmsg(&logmsg0, commit);
3112 if (err)
3113 return err;
3115 logmsg = logmsg0;
3116 do {
3117 line = strsep(&logmsg, "\n");
3118 if (line)
3119 printf(" %s\n", line);
3120 } while (line);
3121 free(logmsg0);
3123 if (show_patch) {
3124 err = print_patch(commit, id, path, diff_context, repo);
3125 if (err == 0)
3126 printf("\n");
3129 if (fflush(stdout) != 0 && err == NULL)
3130 err = got_error_from_errno("fflush");
3131 return err;
3134 static const struct got_error *
3135 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3136 struct got_repository *repo, const char *path, int show_patch,
3137 const char *search_pattern, int diff_context, int limit, int log_branches,
3138 int reverse_display_order, struct got_reflist_head *refs)
3140 const struct got_error *err;
3141 struct got_commit_graph *graph;
3142 regex_t regex;
3143 int have_match;
3144 struct got_object_id_queue reversed_commits;
3145 struct got_object_qid *qid;
3146 struct got_commit_object *commit;
3148 SIMPLEQ_INIT(&reversed_commits);
3150 if (search_pattern && regcomp(&regex, search_pattern,
3151 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3152 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3154 err = got_commit_graph_open(&graph, path, !log_branches);
3155 if (err)
3156 return err;
3157 err = got_commit_graph_iter_start(graph, root_id, repo,
3158 check_cancelled, NULL);
3159 if (err)
3160 goto done;
3161 for (;;) {
3162 struct got_object_id *id;
3164 if (sigint_received || sigpipe_received)
3165 break;
3167 err = got_commit_graph_iter_next(&id, graph, repo,
3168 check_cancelled, NULL);
3169 if (err) {
3170 if (err->code == GOT_ERR_ITER_COMPLETED)
3171 err = NULL;
3172 break;
3174 if (id == NULL)
3175 break;
3177 err = got_object_open_as_commit(&commit, repo, id);
3178 if (err)
3179 break;
3181 if (search_pattern) {
3182 err = match_logmsg(&have_match, id, commit, &regex);
3183 if (err) {
3184 got_object_commit_close(commit);
3185 break;
3187 if (have_match == 0) {
3188 got_object_commit_close(commit);
3189 continue;
3193 if (reverse_display_order) {
3194 err = got_object_qid_alloc(&qid, id);
3195 if (err)
3196 break;
3197 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3198 got_object_commit_close(commit);
3199 } else {
3200 err = print_commit(commit, id, repo, path, show_patch,
3201 diff_context, refs);
3202 got_object_commit_close(commit);
3203 if (err)
3204 break;
3206 if ((limit && --limit == 0) ||
3207 (end_id && got_object_id_cmp(id, end_id) == 0))
3208 break;
3210 if (reverse_display_order) {
3211 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3212 err = got_object_open_as_commit(&commit, repo, qid->id);
3213 if (err)
3214 break;
3215 err = print_commit(commit, qid->id, repo, path,
3216 show_patch, diff_context, refs);
3217 got_object_commit_close(commit);
3218 if (err)
3219 break;
3222 done:
3223 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3224 qid = SIMPLEQ_FIRST(&reversed_commits);
3225 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3226 got_object_qid_free(qid);
3228 if (search_pattern)
3229 regfree(&regex);
3230 got_commit_graph_close(graph);
3231 return err;
3234 __dead static void
3235 usage_log(void)
3237 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3238 "[-p] [-x commit] [-s search-pattern] [-r repository-path] [-R] "
3239 "[path]\n", getprogname());
3240 exit(1);
3243 static int
3244 get_default_log_limit(void)
3246 const char *got_default_log_limit;
3247 long long n;
3248 const char *errstr;
3250 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3251 if (got_default_log_limit == NULL)
3252 return 0;
3253 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3254 if (errstr != NULL)
3255 return 0;
3256 return n;
3259 static const struct got_error *
3260 resolve_commit_arg(struct got_object_id **id, const char *commit_arg,
3261 struct got_repository *repo)
3263 const struct got_error *err = NULL;
3264 struct got_reference *ref;
3266 *id = NULL;
3268 err = got_ref_open(&ref, repo, commit_arg, 0);
3269 if (err == NULL) {
3270 int obj_type;
3271 err = got_ref_resolve(id, repo, ref);
3272 got_ref_close(ref);
3273 if (err)
3274 return err;
3275 err = got_object_get_type(&obj_type, repo, *id);
3276 if (err)
3277 return err;
3278 if (obj_type == GOT_OBJ_TYPE_TAG) {
3279 struct got_tag_object *tag;
3280 err = got_object_open_as_tag(&tag, repo, *id);
3281 if (err)
3282 return err;
3283 if (got_object_tag_get_object_type(tag) !=
3284 GOT_OBJ_TYPE_COMMIT) {
3285 got_object_tag_close(tag);
3286 return got_error(GOT_ERR_OBJ_TYPE);
3288 free(*id);
3289 *id = got_object_id_dup(
3290 got_object_tag_get_object_id(tag));
3291 if (*id == NULL)
3292 err = got_error_from_errno(
3293 "got_object_id_dup");
3294 got_object_tag_close(tag);
3295 if (err)
3296 return err;
3297 } else if (obj_type != GOT_OBJ_TYPE_COMMIT)
3298 return got_error(GOT_ERR_OBJ_TYPE);
3299 } else {
3300 err = got_repo_match_object_id_prefix(id, commit_arg,
3301 GOT_OBJ_TYPE_COMMIT, repo);
3304 return err;
3307 static const struct got_error *
3308 cmd_log(int argc, char *argv[])
3310 const struct got_error *error;
3311 struct got_repository *repo = NULL;
3312 struct got_worktree *worktree = NULL;
3313 struct got_object_id *start_id = NULL, *end_id = NULL;
3314 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3315 const char *start_commit = NULL, *end_commit = NULL;
3316 const char *search_pattern = NULL;
3317 int diff_context = -1, ch;
3318 int show_patch = 0, limit = 0, log_branches = 0;
3319 int reverse_display_order = 0;
3320 const char *errstr;
3321 struct got_reflist_head refs;
3323 SIMPLEQ_INIT(&refs);
3325 #ifndef PROFILE
3326 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3327 NULL)
3328 == -1)
3329 err(1, "pledge");
3330 #endif
3332 limit = get_default_log_limit();
3334 while ((ch = getopt(argc, argv, "bpc:C:l:r:Rs:x:")) != -1) {
3335 switch (ch) {
3336 case 'p':
3337 show_patch = 1;
3338 break;
3339 case 'c':
3340 start_commit = optarg;
3341 break;
3342 case 'C':
3343 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3344 &errstr);
3345 if (errstr != NULL)
3346 err(1, "-C option %s", errstr);
3347 break;
3348 case 'l':
3349 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3350 if (errstr != NULL)
3351 err(1, "-l option %s", errstr);
3352 break;
3353 case 'b':
3354 log_branches = 1;
3355 break;
3356 case 'r':
3357 repo_path = realpath(optarg, NULL);
3358 if (repo_path == NULL)
3359 return got_error_from_errno2("realpath",
3360 optarg);
3361 got_path_strip_trailing_slashes(repo_path);
3362 break;
3363 case 'R':
3364 reverse_display_order = 1;
3365 break;
3366 case 's':
3367 search_pattern = optarg;
3368 break;
3369 case 'x':
3370 end_commit = optarg;
3371 break;
3372 default:
3373 usage_log();
3374 /* NOTREACHED */
3378 argc -= optind;
3379 argv += optind;
3381 if (diff_context == -1)
3382 diff_context = 3;
3383 else if (!show_patch)
3384 errx(1, "-C reguires -p");
3386 cwd = getcwd(NULL, 0);
3387 if (cwd == NULL) {
3388 error = got_error_from_errno("getcwd");
3389 goto done;
3392 error = got_worktree_open(&worktree, cwd);
3393 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3394 goto done;
3395 error = NULL;
3397 if (argc == 0) {
3398 path = strdup("");
3399 if (path == NULL) {
3400 error = got_error_from_errno("strdup");
3401 goto done;
3403 } else if (argc == 1) {
3404 if (worktree) {
3405 error = got_worktree_resolve_path(&path, worktree,
3406 argv[0]);
3407 if (error)
3408 goto done;
3409 } else {
3410 path = strdup(argv[0]);
3411 if (path == NULL) {
3412 error = got_error_from_errno("strdup");
3413 goto done;
3416 } else
3417 usage_log();
3419 if (repo_path == NULL) {
3420 repo_path = worktree ?
3421 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3423 if (repo_path == NULL) {
3424 error = got_error_from_errno("strdup");
3425 goto done;
3428 error = got_repo_open(&repo, repo_path, NULL);
3429 if (error != NULL)
3430 goto done;
3432 error = apply_unveil(got_repo_get_path(repo), 1,
3433 worktree ? got_worktree_get_root_path(worktree) : NULL);
3434 if (error)
3435 goto done;
3437 if (start_commit == NULL) {
3438 struct got_reference *head_ref;
3439 struct got_commit_object *commit = NULL;
3440 error = got_ref_open(&head_ref, repo,
3441 worktree ? got_worktree_get_head_ref_name(worktree)
3442 : GOT_REF_HEAD, 0);
3443 if (error != NULL)
3444 goto done;
3445 error = got_ref_resolve(&start_id, repo, head_ref);
3446 got_ref_close(head_ref);
3447 if (error != NULL)
3448 goto done;
3449 error = got_object_open_as_commit(&commit, repo,
3450 start_id);
3451 if (error != NULL)
3452 goto done;
3453 got_object_commit_close(commit);
3454 } else {
3455 error = resolve_commit_arg(&start_id, start_commit, repo);
3456 if (error != NULL)
3457 goto done;
3459 if (end_commit != NULL) {
3460 error = resolve_commit_arg(&end_id, end_commit, repo);
3461 if (error != NULL)
3462 goto done;
3465 if (worktree) {
3466 const char *prefix = got_worktree_get_path_prefix(worktree);
3467 char *p;
3468 if (asprintf(&p, "%s%s%s", prefix,
3469 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3470 error = got_error_from_errno("asprintf");
3471 goto done;
3473 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3474 free(p);
3475 } else
3476 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3477 if (error != NULL)
3478 goto done;
3479 if (in_repo_path) {
3480 free(path);
3481 path = in_repo_path;
3484 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3485 if (error)
3486 goto done;
3488 error = print_commits(start_id, end_id, repo, path, show_patch,
3489 search_pattern, diff_context, limit, log_branches,
3490 reverse_display_order, &refs);
3491 done:
3492 free(path);
3493 free(repo_path);
3494 free(cwd);
3495 if (worktree)
3496 got_worktree_close(worktree);
3497 if (repo) {
3498 const struct got_error *repo_error;
3499 repo_error = got_repo_close(repo);
3500 if (error == NULL)
3501 error = repo_error;
3503 got_ref_list_free(&refs);
3504 return error;
3507 __dead static void
3508 usage_diff(void)
3510 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3511 "[-w] [object1 object2 | path]\n", getprogname());
3512 exit(1);
3515 struct print_diff_arg {
3516 struct got_repository *repo;
3517 struct got_worktree *worktree;
3518 int diff_context;
3519 const char *id_str;
3520 int header_shown;
3521 int diff_staged;
3522 int ignore_whitespace;
3525 static const struct got_error *
3526 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3527 const char *path, struct got_object_id *blob_id,
3528 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3529 int dirfd, const char *de_name)
3531 struct print_diff_arg *a = arg;
3532 const struct got_error *err = NULL;
3533 struct got_blob_object *blob1 = NULL;
3534 int fd = -1;
3535 FILE *f2 = NULL;
3536 char *abspath = NULL, *label1 = NULL;
3537 struct stat sb;
3539 if (a->diff_staged) {
3540 if (staged_status != GOT_STATUS_MODIFY &&
3541 staged_status != GOT_STATUS_ADD &&
3542 staged_status != GOT_STATUS_DELETE)
3543 return NULL;
3544 } else {
3545 if (staged_status == GOT_STATUS_DELETE)
3546 return NULL;
3547 if (status == GOT_STATUS_NONEXISTENT)
3548 return got_error_set_errno(ENOENT, path);
3549 if (status != GOT_STATUS_MODIFY &&
3550 status != GOT_STATUS_ADD &&
3551 status != GOT_STATUS_DELETE &&
3552 status != GOT_STATUS_CONFLICT)
3553 return NULL;
3556 if (!a->header_shown) {
3557 printf("diff %s %s%s\n", a->id_str,
3558 got_worktree_get_root_path(a->worktree),
3559 a->diff_staged ? " (staged changes)" : "");
3560 a->header_shown = 1;
3563 if (a->diff_staged) {
3564 const char *label1 = NULL, *label2 = NULL;
3565 switch (staged_status) {
3566 case GOT_STATUS_MODIFY:
3567 label1 = path;
3568 label2 = path;
3569 break;
3570 case GOT_STATUS_ADD:
3571 label2 = path;
3572 break;
3573 case GOT_STATUS_DELETE:
3574 label1 = path;
3575 break;
3576 default:
3577 return got_error(GOT_ERR_FILE_STATUS);
3579 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
3580 label1, label2, a->diff_context, a->ignore_whitespace,
3581 a->repo, stdout);
3584 if (staged_status == GOT_STATUS_ADD ||
3585 staged_status == GOT_STATUS_MODIFY) {
3586 char *id_str;
3587 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
3588 8192);
3589 if (err)
3590 goto done;
3591 err = got_object_id_str(&id_str, staged_blob_id);
3592 if (err)
3593 goto done;
3594 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
3595 err = got_error_from_errno("asprintf");
3596 free(id_str);
3597 goto done;
3599 free(id_str);
3600 } else if (status != GOT_STATUS_ADD) {
3601 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
3602 if (err)
3603 goto done;
3606 if (status != GOT_STATUS_DELETE) {
3607 if (asprintf(&abspath, "%s/%s",
3608 got_worktree_get_root_path(a->worktree), path) == -1) {
3609 err = got_error_from_errno("asprintf");
3610 goto done;
3613 if (dirfd != -1) {
3614 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
3615 if (fd == -1) {
3616 err = got_error_from_errno2("openat", abspath);
3617 goto done;
3619 } else {
3620 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
3621 if (fd == -1) {
3622 err = got_error_from_errno2("open", abspath);
3623 goto done;
3626 if (fstat(fd, &sb) == -1) {
3627 err = got_error_from_errno2("fstat", abspath);
3628 goto done;
3630 f2 = fdopen(fd, "r");
3631 if (f2 == NULL) {
3632 err = got_error_from_errno2("fdopen", abspath);
3633 goto done;
3635 fd = -1;
3636 } else
3637 sb.st_size = 0;
3639 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
3640 a->diff_context, a->ignore_whitespace, stdout);
3641 done:
3642 if (blob1)
3643 got_object_blob_close(blob1);
3644 if (f2 && fclose(f2) == EOF && err == NULL)
3645 err = got_error_from_errno("fclose");
3646 if (fd != -1 && close(fd) == -1 && err == NULL)
3647 err = got_error_from_errno("close");
3648 free(abspath);
3649 return err;
3652 static const struct got_error *
3653 cmd_diff(int argc, char *argv[])
3655 const struct got_error *error;
3656 struct got_repository *repo = NULL;
3657 struct got_worktree *worktree = NULL;
3658 char *cwd = NULL, *repo_path = NULL;
3659 struct got_object_id *id1 = NULL, *id2 = NULL;
3660 const char *id_str1 = NULL, *id_str2 = NULL;
3661 char *label1 = NULL, *label2 = NULL;
3662 int type1, type2;
3663 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
3664 const char *errstr;
3665 char *path = NULL;
3667 #ifndef PROFILE
3668 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3669 NULL) == -1)
3670 err(1, "pledge");
3671 #endif
3673 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
3674 switch (ch) {
3675 case 'C':
3676 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3677 &errstr);
3678 if (errstr != NULL)
3679 err(1, "-C option %s", errstr);
3680 break;
3681 case 'r':
3682 repo_path = realpath(optarg, NULL);
3683 if (repo_path == NULL)
3684 return got_error_from_errno2("realpath",
3685 optarg);
3686 got_path_strip_trailing_slashes(repo_path);
3687 break;
3688 case 's':
3689 diff_staged = 1;
3690 break;
3691 case 'w':
3692 ignore_whitespace = 1;
3693 break;
3694 default:
3695 usage_diff();
3696 /* NOTREACHED */
3700 argc -= optind;
3701 argv += optind;
3703 cwd = getcwd(NULL, 0);
3704 if (cwd == NULL) {
3705 error = got_error_from_errno("getcwd");
3706 goto done;
3708 if (argc <= 1) {
3709 if (repo_path)
3710 errx(1,
3711 "-r option can't be used when diffing a work tree");
3712 error = got_worktree_open(&worktree, cwd);
3713 if (error) {
3714 if (error->code == GOT_ERR_NOT_WORKTREE)
3715 error = wrap_not_worktree_error(error, "diff",
3716 cwd);
3717 goto done;
3719 repo_path = strdup(got_worktree_get_repo_path(worktree));
3720 if (repo_path == NULL) {
3721 error = got_error_from_errno("strdup");
3722 goto done;
3724 if (argc == 1) {
3725 error = got_worktree_resolve_path(&path, worktree,
3726 argv[0]);
3727 if (error)
3728 goto done;
3729 } else {
3730 path = strdup("");
3731 if (path == NULL) {
3732 error = got_error_from_errno("strdup");
3733 goto done;
3736 } else if (argc == 2) {
3737 if (diff_staged)
3738 errx(1, "-s option can't be used when diffing "
3739 "objects in repository");
3740 id_str1 = argv[0];
3741 id_str2 = argv[1];
3742 if (repo_path == NULL) {
3743 error = got_worktree_open(&worktree, cwd);
3744 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3745 goto done;
3746 if (worktree) {
3747 repo_path = strdup(
3748 got_worktree_get_repo_path(worktree));
3749 if (repo_path == NULL) {
3750 error = got_error_from_errno("strdup");
3751 goto done;
3753 } else {
3754 repo_path = strdup(cwd);
3755 if (repo_path == NULL) {
3756 error = got_error_from_errno("strdup");
3757 goto done;
3761 } else
3762 usage_diff();
3764 error = got_repo_open(&repo, repo_path, NULL);
3765 free(repo_path);
3766 if (error != NULL)
3767 goto done;
3769 error = apply_unveil(got_repo_get_path(repo), 1,
3770 worktree ? got_worktree_get_root_path(worktree) : NULL);
3771 if (error)
3772 goto done;
3774 if (argc <= 1) {
3775 struct print_diff_arg arg;
3776 struct got_pathlist_head paths;
3777 char *id_str;
3779 TAILQ_INIT(&paths);
3781 error = got_object_id_str(&id_str,
3782 got_worktree_get_base_commit_id(worktree));
3783 if (error)
3784 goto done;
3785 arg.repo = repo;
3786 arg.worktree = worktree;
3787 arg.diff_context = diff_context;
3788 arg.id_str = id_str;
3789 arg.header_shown = 0;
3790 arg.diff_staged = diff_staged;
3791 arg.ignore_whitespace = ignore_whitespace;
3793 error = got_pathlist_append(&paths, path, NULL);
3794 if (error)
3795 goto done;
3797 error = got_worktree_status(worktree, &paths, repo, print_diff,
3798 &arg, check_cancelled, NULL);
3799 free(id_str);
3800 got_pathlist_free(&paths);
3801 goto done;
3804 error = got_repo_match_object_id(&id1, &label1, id_str1,
3805 GOT_OBJ_TYPE_ANY, 1, repo);
3806 if (error)
3807 goto done;
3809 error = got_repo_match_object_id(&id2, &label2, id_str2,
3810 GOT_OBJ_TYPE_ANY, 1, repo);
3811 if (error)
3812 goto done;
3814 error = got_object_get_type(&type1, repo, id1);
3815 if (error)
3816 goto done;
3818 error = got_object_get_type(&type2, repo, id2);
3819 if (error)
3820 goto done;
3822 if (type1 != type2) {
3823 error = got_error(GOT_ERR_OBJ_TYPE);
3824 goto done;
3827 switch (type1) {
3828 case GOT_OBJ_TYPE_BLOB:
3829 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
3830 diff_context, ignore_whitespace, repo, stdout);
3831 break;
3832 case GOT_OBJ_TYPE_TREE:
3833 error = got_diff_objects_as_trees(id1, id2, "", "",
3834 diff_context, ignore_whitespace, repo, stdout);
3835 break;
3836 case GOT_OBJ_TYPE_COMMIT:
3837 printf("diff %s %s\n", label1, label2);
3838 error = got_diff_objects_as_commits(id1, id2, diff_context,
3839 ignore_whitespace, repo, stdout);
3840 break;
3841 default:
3842 error = got_error(GOT_ERR_OBJ_TYPE);
3844 done:
3845 free(label1);
3846 free(label2);
3847 free(id1);
3848 free(id2);
3849 free(path);
3850 if (worktree)
3851 got_worktree_close(worktree);
3852 if (repo) {
3853 const struct got_error *repo_error;
3854 repo_error = got_repo_close(repo);
3855 if (error == NULL)
3856 error = repo_error;
3858 return error;
3861 __dead static void
3862 usage_blame(void)
3864 fprintf(stderr,
3865 "usage: %s blame [-c commit] [-r repository-path] path\n",
3866 getprogname());
3867 exit(1);
3870 struct blame_line {
3871 int annotated;
3872 char *id_str;
3873 char *committer;
3874 char datebuf[11]; /* YYYY-MM-DD + NUL */
3877 struct blame_cb_args {
3878 struct blame_line *lines;
3879 int nlines;
3880 int nlines_prec;
3881 int lineno_cur;
3882 off_t *line_offsets;
3883 FILE *f;
3884 struct got_repository *repo;
3887 static const struct got_error *
3888 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
3890 const struct got_error *err = NULL;
3891 struct blame_cb_args *a = arg;
3892 struct blame_line *bline;
3893 char *line = NULL;
3894 size_t linesize = 0;
3895 struct got_commit_object *commit = NULL;
3896 off_t offset;
3897 struct tm tm;
3898 time_t committer_time;
3900 if (nlines != a->nlines ||
3901 (lineno != -1 && lineno < 1) || lineno > a->nlines)
3902 return got_error(GOT_ERR_RANGE);
3904 if (sigint_received)
3905 return got_error(GOT_ERR_ITER_COMPLETED);
3907 if (lineno == -1)
3908 return NULL; /* no change in this commit */
3910 /* Annotate this line. */
3911 bline = &a->lines[lineno - 1];
3912 if (bline->annotated)
3913 return NULL;
3914 err = got_object_id_str(&bline->id_str, id);
3915 if (err)
3916 return err;
3918 err = got_object_open_as_commit(&commit, a->repo, id);
3919 if (err)
3920 goto done;
3922 bline->committer = strdup(got_object_commit_get_committer(commit));
3923 if (bline->committer == NULL) {
3924 err = got_error_from_errno("strdup");
3925 goto done;
3928 committer_time = got_object_commit_get_committer_time(commit);
3929 if (localtime_r(&committer_time, &tm) == NULL)
3930 return got_error_from_errno("localtime_r");
3931 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
3932 &tm) >= sizeof(bline->datebuf)) {
3933 err = got_error(GOT_ERR_NO_SPACE);
3934 goto done;
3936 bline->annotated = 1;
3938 /* Print lines annotated so far. */
3939 bline = &a->lines[a->lineno_cur - 1];
3940 if (!bline->annotated)
3941 goto done;
3943 offset = a->line_offsets[a->lineno_cur - 1];
3944 if (fseeko(a->f, offset, SEEK_SET) == -1) {
3945 err = got_error_from_errno("fseeko");
3946 goto done;
3949 while (bline->annotated) {
3950 char *smallerthan, *at, *nl, *committer;
3951 size_t len;
3953 if (getline(&line, &linesize, a->f) == -1) {
3954 if (ferror(a->f))
3955 err = got_error_from_errno("getline");
3956 break;
3959 committer = bline->committer;
3960 smallerthan = strchr(committer, '<');
3961 if (smallerthan && smallerthan[1] != '\0')
3962 committer = smallerthan + 1;
3963 at = strchr(committer, '@');
3964 if (at)
3965 *at = '\0';
3966 len = strlen(committer);
3967 if (len >= 9)
3968 committer[8] = '\0';
3970 nl = strchr(line, '\n');
3971 if (nl)
3972 *nl = '\0';
3973 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
3974 bline->id_str, bline->datebuf, committer, line);
3976 a->lineno_cur++;
3977 bline = &a->lines[a->lineno_cur - 1];
3979 done:
3980 if (commit)
3981 got_object_commit_close(commit);
3982 free(line);
3983 return err;
3986 static const struct got_error *
3987 cmd_blame(int argc, char *argv[])
3989 const struct got_error *error;
3990 struct got_repository *repo = NULL;
3991 struct got_worktree *worktree = NULL;
3992 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
3993 struct got_object_id *obj_id = NULL;
3994 struct got_object_id *commit_id = NULL;
3995 struct got_blob_object *blob = NULL;
3996 char *commit_id_str = NULL;
3997 struct blame_cb_args bca;
3998 int ch, obj_type, i;
3999 size_t filesize;
4001 memset(&bca, 0, sizeof(bca));
4003 #ifndef PROFILE
4004 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4005 NULL) == -1)
4006 err(1, "pledge");
4007 #endif
4009 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4010 switch (ch) {
4011 case 'c':
4012 commit_id_str = optarg;
4013 break;
4014 case 'r':
4015 repo_path = realpath(optarg, NULL);
4016 if (repo_path == NULL)
4017 return got_error_from_errno2("realpath",
4018 optarg);
4019 got_path_strip_trailing_slashes(repo_path);
4020 break;
4021 default:
4022 usage_blame();
4023 /* NOTREACHED */
4027 argc -= optind;
4028 argv += optind;
4030 if (argc == 1)
4031 path = argv[0];
4032 else
4033 usage_blame();
4035 cwd = getcwd(NULL, 0);
4036 if (cwd == NULL) {
4037 error = got_error_from_errno("getcwd");
4038 goto done;
4040 if (repo_path == NULL) {
4041 error = got_worktree_open(&worktree, cwd);
4042 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4043 goto done;
4044 else
4045 error = NULL;
4046 if (worktree) {
4047 repo_path =
4048 strdup(got_worktree_get_repo_path(worktree));
4049 if (repo_path == NULL) {
4050 error = got_error_from_errno("strdup");
4051 if (error)
4052 goto done;
4054 } else {
4055 repo_path = strdup(cwd);
4056 if (repo_path == NULL) {
4057 error = got_error_from_errno("strdup");
4058 goto done;
4063 error = got_repo_open(&repo, repo_path, NULL);
4064 if (error != NULL)
4065 goto done;
4067 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4068 if (error)
4069 goto done;
4071 if (worktree) {
4072 const char *prefix = got_worktree_get_path_prefix(worktree);
4073 char *p, *worktree_subdir = cwd +
4074 strlen(got_worktree_get_root_path(worktree));
4075 if (asprintf(&p, "%s%s%s%s%s",
4076 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
4077 worktree_subdir, worktree_subdir[0] ? "/" : "",
4078 path) == -1) {
4079 error = got_error_from_errno("asprintf");
4080 goto done;
4082 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4083 free(p);
4084 } else {
4085 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4087 if (error)
4088 goto done;
4090 if (commit_id_str == NULL) {
4091 struct got_reference *head_ref;
4092 error = got_ref_open(&head_ref, repo, worktree ?
4093 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4094 if (error != NULL)
4095 goto done;
4096 error = got_ref_resolve(&commit_id, repo, head_ref);
4097 got_ref_close(head_ref);
4098 if (error != NULL)
4099 goto done;
4100 } else {
4101 error = got_repo_match_object_id(&commit_id, NULL,
4102 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4103 if (error)
4104 goto done;
4107 error = got_object_id_by_path(&obj_id, repo, commit_id, in_repo_path);
4108 if (error)
4109 goto done;
4111 error = got_object_get_type(&obj_type, repo, obj_id);
4112 if (error)
4113 goto done;
4115 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4116 error = got_error(GOT_ERR_OBJ_TYPE);
4117 goto done;
4120 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4121 if (error)
4122 goto done;
4123 bca.f = got_opentemp();
4124 if (bca.f == NULL) {
4125 error = got_error_from_errno("got_opentemp");
4126 goto done;
4128 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4129 &bca.line_offsets, bca.f, blob);
4130 if (error || bca.nlines == 0)
4131 goto done;
4133 /* Don't include \n at EOF in the blame line count. */
4134 if (bca.line_offsets[bca.nlines - 1] == filesize)
4135 bca.nlines--;
4137 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4138 if (bca.lines == NULL) {
4139 error = got_error_from_errno("calloc");
4140 goto done;
4142 bca.lineno_cur = 1;
4143 bca.nlines_prec = 0;
4144 i = bca.nlines;
4145 while (i > 0) {
4146 i /= 10;
4147 bca.nlines_prec++;
4149 bca.repo = repo;
4151 error = got_blame(in_repo_path, commit_id, repo, blame_cb, &bca,
4152 check_cancelled, NULL);
4153 done:
4154 free(in_repo_path);
4155 free(repo_path);
4156 free(cwd);
4157 free(commit_id);
4158 free(obj_id);
4159 if (blob)
4160 got_object_blob_close(blob);
4161 if (worktree)
4162 got_worktree_close(worktree);
4163 if (repo) {
4164 const struct got_error *repo_error;
4165 repo_error = got_repo_close(repo);
4166 if (error == NULL)
4167 error = repo_error;
4169 if (bca.lines) {
4170 for (i = 0; i < bca.nlines; i++) {
4171 struct blame_line *bline = &bca.lines[i];
4172 free(bline->id_str);
4173 free(bline->committer);
4175 free(bca.lines);
4177 free(bca.line_offsets);
4178 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4179 error = got_error_from_errno("fclose");
4180 return error;
4183 __dead static void
4184 usage_tree(void)
4186 fprintf(stderr,
4187 "usage: %s tree [-c commit] [-r repository-path] [-iR] path\n",
4188 getprogname());
4189 exit(1);
4192 static void
4193 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4194 const char *root_path)
4196 int is_root_path = (strcmp(path, root_path) == 0);
4197 const char *modestr = "";
4198 mode_t mode = got_tree_entry_get_mode(te);
4200 path += strlen(root_path);
4201 while (path[0] == '/')
4202 path++;
4204 if (got_object_tree_entry_is_submodule(te))
4205 modestr = "$";
4206 else if (S_ISLNK(mode))
4207 modestr = "@";
4208 else if (S_ISDIR(mode))
4209 modestr = "/";
4210 else if (mode & S_IXUSR)
4211 modestr = "*";
4213 printf("%s%s%s%s%s\n", id ? id : "", path,
4214 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr);
4217 static const struct got_error *
4218 print_tree(const char *path, struct got_object_id *commit_id,
4219 int show_ids, int recurse, const char *root_path,
4220 struct got_repository *repo)
4222 const struct got_error *err = NULL;
4223 struct got_object_id *tree_id = NULL;
4224 struct got_tree_object *tree = NULL;
4225 int nentries, i;
4227 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4228 if (err)
4229 goto done;
4231 err = got_object_open_as_tree(&tree, repo, tree_id);
4232 if (err)
4233 goto done;
4234 nentries = got_object_tree_get_nentries(tree);
4235 for (i = 0; i < nentries; i++) {
4236 struct got_tree_entry *te;
4237 char *id = NULL;
4239 if (sigint_received || sigpipe_received)
4240 break;
4242 te = got_object_tree_get_entry(tree, i);
4243 if (show_ids) {
4244 char *id_str;
4245 err = got_object_id_str(&id_str,
4246 got_tree_entry_get_id(te));
4247 if (err)
4248 goto done;
4249 if (asprintf(&id, "%s ", id_str) == -1) {
4250 err = got_error_from_errno("asprintf");
4251 free(id_str);
4252 goto done;
4254 free(id_str);
4256 print_entry(te, id, path, root_path);
4257 free(id);
4259 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4260 char *child_path;
4261 if (asprintf(&child_path, "%s%s%s", path,
4262 path[0] == '/' && path[1] == '\0' ? "" : "/",
4263 got_tree_entry_get_name(te)) == -1) {
4264 err = got_error_from_errno("asprintf");
4265 goto done;
4267 err = print_tree(child_path, commit_id, show_ids, 1,
4268 root_path, repo);
4269 free(child_path);
4270 if (err)
4271 goto done;
4274 done:
4275 if (tree)
4276 got_object_tree_close(tree);
4277 free(tree_id);
4278 return err;
4281 static const struct got_error *
4282 cmd_tree(int argc, char *argv[])
4284 const struct got_error *error;
4285 struct got_repository *repo = NULL;
4286 struct got_worktree *worktree = NULL;
4287 const char *path, *refname = NULL;
4288 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4289 struct got_object_id *commit_id = NULL;
4290 char *commit_id_str = NULL;
4291 int show_ids = 0, recurse = 0;
4292 int ch;
4294 #ifndef PROFILE
4295 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4296 NULL) == -1)
4297 err(1, "pledge");
4298 #endif
4300 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4301 switch (ch) {
4302 case 'c':
4303 commit_id_str = optarg;
4304 break;
4305 case 'r':
4306 repo_path = realpath(optarg, NULL);
4307 if (repo_path == NULL)
4308 return got_error_from_errno2("realpath",
4309 optarg);
4310 got_path_strip_trailing_slashes(repo_path);
4311 break;
4312 case 'i':
4313 show_ids = 1;
4314 break;
4315 case 'R':
4316 recurse = 1;
4317 break;
4318 default:
4319 usage_tree();
4320 /* NOTREACHED */
4324 argc -= optind;
4325 argv += optind;
4327 if (argc == 1)
4328 path = argv[0];
4329 else if (argc > 1)
4330 usage_tree();
4331 else
4332 path = NULL;
4334 cwd = getcwd(NULL, 0);
4335 if (cwd == NULL) {
4336 error = got_error_from_errno("getcwd");
4337 goto done;
4339 if (repo_path == NULL) {
4340 error = got_worktree_open(&worktree, cwd);
4341 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4342 goto done;
4343 else
4344 error = NULL;
4345 if (worktree) {
4346 repo_path =
4347 strdup(got_worktree_get_repo_path(worktree));
4348 if (repo_path == NULL)
4349 error = got_error_from_errno("strdup");
4350 if (error)
4351 goto done;
4352 } else {
4353 repo_path = strdup(cwd);
4354 if (repo_path == NULL) {
4355 error = got_error_from_errno("strdup");
4356 goto done;
4361 error = got_repo_open(&repo, repo_path, NULL);
4362 if (error != NULL)
4363 goto done;
4365 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4366 if (error)
4367 goto done;
4369 if (path == NULL) {
4370 if (worktree) {
4371 char *p, *worktree_subdir = cwd +
4372 strlen(got_worktree_get_root_path(worktree));
4373 if (asprintf(&p, "%s/%s",
4374 got_worktree_get_path_prefix(worktree),
4375 worktree_subdir) == -1) {
4376 error = got_error_from_errno("asprintf");
4377 goto done;
4379 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4380 free(p);
4381 if (error)
4382 goto done;
4383 } else
4384 path = "/";
4386 if (in_repo_path == NULL) {
4387 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4388 if (error != NULL)
4389 goto done;
4392 if (commit_id_str == NULL) {
4393 struct got_reference *head_ref;
4394 if (worktree)
4395 refname = got_worktree_get_head_ref_name(worktree);
4396 else
4397 refname = GOT_REF_HEAD;
4398 error = got_ref_open(&head_ref, repo, refname, 0);
4399 if (error != NULL)
4400 goto done;
4401 error = got_ref_resolve(&commit_id, repo, head_ref);
4402 got_ref_close(head_ref);
4403 if (error != NULL)
4404 goto done;
4405 } else {
4406 error = got_repo_match_object_id(&commit_id, NULL,
4407 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4408 if (error)
4409 goto done;
4412 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4413 in_repo_path, repo);
4414 done:
4415 free(in_repo_path);
4416 free(repo_path);
4417 free(cwd);
4418 free(commit_id);
4419 if (worktree)
4420 got_worktree_close(worktree);
4421 if (repo) {
4422 const struct got_error *repo_error;
4423 repo_error = got_repo_close(repo);
4424 if (error == NULL)
4425 error = repo_error;
4427 return error;
4430 __dead static void
4431 usage_status(void)
4433 fprintf(stderr, "usage: %s status [path ...]\n", getprogname());
4434 exit(1);
4437 static const struct got_error *
4438 print_status(void *arg, unsigned char status, unsigned char staged_status,
4439 const char *path, struct got_object_id *blob_id,
4440 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4441 int dirfd, const char *de_name)
4443 if (status == staged_status && (status == GOT_STATUS_DELETE))
4444 status = GOT_STATUS_NO_CHANGE;
4445 printf("%c%c %s\n", status, staged_status, path);
4446 return NULL;
4449 static const struct got_error *
4450 cmd_status(int argc, char *argv[])
4452 const struct got_error *error = NULL;
4453 struct got_repository *repo = NULL;
4454 struct got_worktree *worktree = NULL;
4455 char *cwd = NULL;
4456 struct got_pathlist_head paths;
4457 struct got_pathlist_entry *pe;
4458 int ch;
4460 TAILQ_INIT(&paths);
4462 while ((ch = getopt(argc, argv, "")) != -1) {
4463 switch (ch) {
4464 default:
4465 usage_status();
4466 /* NOTREACHED */
4470 argc -= optind;
4471 argv += optind;
4473 #ifndef PROFILE
4474 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4475 NULL) == -1)
4476 err(1, "pledge");
4477 #endif
4478 cwd = getcwd(NULL, 0);
4479 if (cwd == NULL) {
4480 error = got_error_from_errno("getcwd");
4481 goto done;
4484 error = got_worktree_open(&worktree, cwd);
4485 if (error) {
4486 if (error->code == GOT_ERR_NOT_WORKTREE)
4487 error = wrap_not_worktree_error(error, "status", cwd);
4488 goto done;
4491 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4492 NULL);
4493 if (error != NULL)
4494 goto done;
4496 error = apply_unveil(got_repo_get_path(repo), 1,
4497 got_worktree_get_root_path(worktree));
4498 if (error)
4499 goto done;
4501 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
4502 if (error)
4503 goto done;
4505 error = got_worktree_status(worktree, &paths, repo, print_status, NULL,
4506 check_cancelled, NULL);
4507 done:
4508 TAILQ_FOREACH(pe, &paths, entry)
4509 free((char *)pe->path);
4510 got_pathlist_free(&paths);
4511 free(cwd);
4512 return error;
4515 __dead static void
4516 usage_ref(void)
4518 fprintf(stderr,
4519 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
4520 "[-d] [name]\n",
4521 getprogname());
4522 exit(1);
4525 static const struct got_error *
4526 list_refs(struct got_repository *repo, const char *refname)
4528 static const struct got_error *err = NULL;
4529 struct got_reflist_head refs;
4530 struct got_reflist_entry *re;
4532 SIMPLEQ_INIT(&refs);
4533 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
4534 if (err)
4535 return err;
4537 SIMPLEQ_FOREACH(re, &refs, entry) {
4538 char *refstr;
4539 refstr = got_ref_to_str(re->ref);
4540 if (refstr == NULL)
4541 return got_error_from_errno("got_ref_to_str");
4542 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
4543 free(refstr);
4546 got_ref_list_free(&refs);
4547 return NULL;
4550 static const struct got_error *
4551 delete_ref(struct got_repository *repo, const char *refname)
4553 const struct got_error *err = NULL;
4554 struct got_reference *ref;
4556 err = got_ref_open(&ref, repo, refname, 0);
4557 if (err)
4558 return err;
4560 err = got_ref_delete(ref, repo);
4561 got_ref_close(ref);
4562 return err;
4565 static const struct got_error *
4566 add_ref(struct got_repository *repo, const char *refname, const char *target)
4568 const struct got_error *err = NULL;
4569 struct got_object_id *id;
4570 struct got_reference *ref = NULL;
4573 * Don't let the user create a reference name with a leading '-'.
4574 * While technically a valid reference name, this case is usually
4575 * an unintended typo.
4577 if (refname[0] == '-')
4578 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4580 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
4581 repo);
4582 if (err) {
4583 struct got_reference *target_ref;
4585 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
4586 return err;
4587 err = got_ref_open(&target_ref, repo, target, 0);
4588 if (err)
4589 return err;
4590 err = got_ref_resolve(&id, repo, target_ref);
4591 got_ref_close(target_ref);
4592 if (err)
4593 return err;
4596 err = got_ref_alloc(&ref, refname, id);
4597 if (err)
4598 goto done;
4600 err = got_ref_write(ref, repo);
4601 done:
4602 if (ref)
4603 got_ref_close(ref);
4604 free(id);
4605 return err;
4608 static const struct got_error *
4609 add_symref(struct got_repository *repo, const char *refname, const char *target)
4611 const struct got_error *err = NULL;
4612 struct got_reference *ref = NULL;
4613 struct got_reference *target_ref = NULL;
4616 * Don't let the user create a reference name with a leading '-'.
4617 * While technically a valid reference name, this case is usually
4618 * an unintended typo.
4620 if (refname[0] == '-')
4621 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4623 err = got_ref_open(&target_ref, repo, target, 0);
4624 if (err)
4625 return err;
4627 err = got_ref_alloc_symref(&ref, refname, target_ref);
4628 if (err)
4629 goto done;
4631 err = got_ref_write(ref, repo);
4632 done:
4633 if (target_ref)
4634 got_ref_close(target_ref);
4635 if (ref)
4636 got_ref_close(ref);
4637 return err;
4640 static const struct got_error *
4641 cmd_ref(int argc, char *argv[])
4643 const struct got_error *error = NULL;
4644 struct got_repository *repo = NULL;
4645 struct got_worktree *worktree = NULL;
4646 char *cwd = NULL, *repo_path = NULL;
4647 int ch, do_list = 0, do_delete = 0;
4648 const char *obj_arg = NULL, *symref_target= NULL;
4649 char *refname = NULL;
4651 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
4652 switch (ch) {
4653 case 'c':
4654 obj_arg = optarg;
4655 break;
4656 case 'd':
4657 do_delete = 1;
4658 break;
4659 case 'r':
4660 repo_path = realpath(optarg, NULL);
4661 if (repo_path == NULL)
4662 return got_error_from_errno2("realpath",
4663 optarg);
4664 got_path_strip_trailing_slashes(repo_path);
4665 break;
4666 case 'l':
4667 do_list = 1;
4668 break;
4669 case 's':
4670 symref_target = optarg;
4671 break;
4672 default:
4673 usage_ref();
4674 /* NOTREACHED */
4678 if (obj_arg && do_list)
4679 errx(1, "-c and -l options are mutually exclusive");
4680 if (obj_arg && do_delete)
4681 errx(1, "-c and -d options are mutually exclusive");
4682 if (obj_arg && symref_target)
4683 errx(1, "-c and -s options are mutually exclusive");
4684 if (symref_target && do_delete)
4685 errx(1, "-s and -d options are mutually exclusive");
4686 if (symref_target && do_list)
4687 errx(1, "-s and -l options are mutually exclusive");
4688 if (do_delete && do_list)
4689 errx(1, "-d and -l options are mutually exclusive");
4691 argc -= optind;
4692 argv += optind;
4694 if (do_list) {
4695 if (argc != 0 && argc != 1)
4696 usage_ref();
4697 if (argc == 1) {
4698 refname = strdup(argv[0]);
4699 if (refname == NULL) {
4700 error = got_error_from_errno("strdup");
4701 goto done;
4704 } else {
4705 if (argc != 1)
4706 usage_ref();
4707 refname = strdup(argv[0]);
4708 if (refname == NULL) {
4709 error = got_error_from_errno("strdup");
4710 goto done;
4714 if (refname)
4715 got_path_strip_trailing_slashes(refname);
4717 #ifndef PROFILE
4718 if (do_list) {
4719 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4720 NULL) == -1)
4721 err(1, "pledge");
4722 } else {
4723 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4724 "sendfd unveil", NULL) == -1)
4725 err(1, "pledge");
4727 #endif
4728 cwd = getcwd(NULL, 0);
4729 if (cwd == NULL) {
4730 error = got_error_from_errno("getcwd");
4731 goto done;
4734 if (repo_path == NULL) {
4735 error = got_worktree_open(&worktree, cwd);
4736 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4737 goto done;
4738 else
4739 error = NULL;
4740 if (worktree) {
4741 repo_path =
4742 strdup(got_worktree_get_repo_path(worktree));
4743 if (repo_path == NULL)
4744 error = got_error_from_errno("strdup");
4745 if (error)
4746 goto done;
4747 } else {
4748 repo_path = strdup(cwd);
4749 if (repo_path == NULL) {
4750 error = got_error_from_errno("strdup");
4751 goto done;
4756 error = got_repo_open(&repo, repo_path, NULL);
4757 if (error != NULL)
4758 goto done;
4760 error = apply_unveil(got_repo_get_path(repo), do_list,
4761 worktree ? got_worktree_get_root_path(worktree) : NULL);
4762 if (error)
4763 goto done;
4765 if (do_list)
4766 error = list_refs(repo, refname);
4767 else if (do_delete)
4768 error = delete_ref(repo, refname);
4769 else if (symref_target)
4770 error = add_symref(repo, refname, symref_target);
4771 else {
4772 if (obj_arg == NULL)
4773 usage_ref();
4774 error = add_ref(repo, refname, obj_arg);
4776 done:
4777 free(refname);
4778 if (repo)
4779 got_repo_close(repo);
4780 if (worktree)
4781 got_worktree_close(worktree);
4782 free(cwd);
4783 free(repo_path);
4784 return error;
4787 __dead static void
4788 usage_branch(void)
4790 fprintf(stderr,
4791 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
4792 "[name]\n", getprogname());
4793 exit(1);
4796 static const struct got_error *
4797 list_branch(struct got_repository *repo, struct got_worktree *worktree,
4798 struct got_reference *ref)
4800 const struct got_error *err = NULL;
4801 const char *refname, *marker = " ";
4802 char *refstr;
4804 refname = got_ref_get_name(ref);
4805 if (worktree && strcmp(refname,
4806 got_worktree_get_head_ref_name(worktree)) == 0) {
4807 struct got_object_id *id = NULL;
4809 err = got_ref_resolve(&id, repo, ref);
4810 if (err)
4811 return err;
4812 if (got_object_id_cmp(id,
4813 got_worktree_get_base_commit_id(worktree)) == 0)
4814 marker = "* ";
4815 else
4816 marker = "~ ";
4817 free(id);
4820 if (strncmp(refname, "refs/heads/", 11) == 0)
4821 refname += 11;
4822 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4823 refname += 18;
4825 refstr = got_ref_to_str(ref);
4826 if (refstr == NULL)
4827 return got_error_from_errno("got_ref_to_str");
4829 printf("%s%s: %s\n", marker, refname, refstr);
4830 free(refstr);
4831 return NULL;
4834 static const struct got_error *
4835 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
4837 const char *refname;
4839 if (worktree == NULL)
4840 return got_error(GOT_ERR_NOT_WORKTREE);
4842 refname = got_worktree_get_head_ref_name(worktree);
4844 if (strncmp(refname, "refs/heads/", 11) == 0)
4845 refname += 11;
4846 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4847 refname += 18;
4849 printf("%s\n", refname);
4851 return NULL;
4854 static const struct got_error *
4855 list_branches(struct got_repository *repo, struct got_worktree *worktree)
4857 static const struct got_error *err = NULL;
4858 struct got_reflist_head refs;
4859 struct got_reflist_entry *re;
4860 struct got_reference *temp_ref = NULL;
4861 int rebase_in_progress, histedit_in_progress;
4863 SIMPLEQ_INIT(&refs);
4865 if (worktree) {
4866 err = got_worktree_rebase_in_progress(&rebase_in_progress,
4867 worktree);
4868 if (err)
4869 return err;
4871 err = got_worktree_histedit_in_progress(&histedit_in_progress,
4872 worktree);
4873 if (err)
4874 return err;
4876 if (rebase_in_progress || histedit_in_progress) {
4877 err = got_ref_open(&temp_ref, repo,
4878 got_worktree_get_head_ref_name(worktree), 0);
4879 if (err)
4880 return err;
4881 list_branch(repo, worktree, temp_ref);
4882 got_ref_close(temp_ref);
4886 err = got_ref_list(&refs, repo, "refs/heads",
4887 got_ref_cmp_by_name, NULL);
4888 if (err)
4889 return err;
4891 SIMPLEQ_FOREACH(re, &refs, entry)
4892 list_branch(repo, worktree, re->ref);
4894 got_ref_list_free(&refs);
4895 return NULL;
4898 static const struct got_error *
4899 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
4900 const char *branch_name)
4902 const struct got_error *err = NULL;
4903 struct got_reference *ref = NULL;
4904 char *refname;
4906 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
4907 return got_error_from_errno("asprintf");
4909 err = got_ref_open(&ref, repo, refname, 0);
4910 if (err)
4911 goto done;
4913 if (worktree &&
4914 strcmp(got_worktree_get_head_ref_name(worktree),
4915 got_ref_get_name(ref)) == 0) {
4916 err = got_error_msg(GOT_ERR_SAME_BRANCH,
4917 "will not delete this work tree's current branch");
4918 goto done;
4921 err = got_ref_delete(ref, repo);
4922 done:
4923 if (ref)
4924 got_ref_close(ref);
4925 free(refname);
4926 return err;
4929 static const struct got_error *
4930 add_branch(struct got_repository *repo, const char *branch_name,
4931 struct got_object_id *base_commit_id)
4933 const struct got_error *err = NULL;
4934 struct got_reference *ref = NULL;
4935 char *base_refname = NULL, *refname = NULL;
4938 * Don't let the user create a branch name with a leading '-'.
4939 * While technically a valid reference name, this case is usually
4940 * an unintended typo.
4942 if (branch_name[0] == '-')
4943 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
4945 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
4946 err = got_error_from_errno("asprintf");
4947 goto done;
4950 err = got_ref_open(&ref, repo, refname, 0);
4951 if (err == NULL) {
4952 err = got_error(GOT_ERR_BRANCH_EXISTS);
4953 goto done;
4954 } else if (err->code != GOT_ERR_NOT_REF)
4955 goto done;
4957 err = got_ref_alloc(&ref, refname, base_commit_id);
4958 if (err)
4959 goto done;
4961 err = got_ref_write(ref, repo);
4962 done:
4963 if (ref)
4964 got_ref_close(ref);
4965 free(base_refname);
4966 free(refname);
4967 return err;
4970 static const struct got_error *
4971 cmd_branch(int argc, char *argv[])
4973 const struct got_error *error = NULL;
4974 struct got_repository *repo = NULL;
4975 struct got_worktree *worktree = NULL;
4976 char *cwd = NULL, *repo_path = NULL;
4977 int ch, do_list = 0, do_show = 0, do_update = 1;
4978 const char *delref = NULL, *commit_id_arg = NULL;
4979 struct got_reference *ref = NULL;
4980 struct got_pathlist_head paths;
4981 struct got_pathlist_entry *pe;
4982 struct got_object_id *commit_id = NULL;
4983 char *commit_id_str = NULL;
4985 TAILQ_INIT(&paths);
4987 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
4988 switch (ch) {
4989 case 'c':
4990 commit_id_arg = optarg;
4991 break;
4992 case 'd':
4993 delref = optarg;
4994 break;
4995 case 'r':
4996 repo_path = realpath(optarg, NULL);
4997 if (repo_path == NULL)
4998 return got_error_from_errno2("realpath",
4999 optarg);
5000 got_path_strip_trailing_slashes(repo_path);
5001 break;
5002 case 'l':
5003 do_list = 1;
5004 break;
5005 case 'n':
5006 do_update = 0;
5007 break;
5008 default:
5009 usage_branch();
5010 /* NOTREACHED */
5014 if (do_list && delref)
5015 errx(1, "-l and -d options are mutually exclusive");
5017 argc -= optind;
5018 argv += optind;
5020 if (!do_list && !delref && argc == 0)
5021 do_show = 1;
5023 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5024 errx(1, "-c option can only be used when creating a branch");
5026 if (do_list || delref) {
5027 if (argc > 0)
5028 usage_branch();
5029 } else if (!do_show && argc != 1)
5030 usage_branch();
5032 #ifndef PROFILE
5033 if (do_list || do_show) {
5034 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5035 NULL) == -1)
5036 err(1, "pledge");
5037 } else {
5038 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5039 "sendfd unveil", NULL) == -1)
5040 err(1, "pledge");
5042 #endif
5043 cwd = getcwd(NULL, 0);
5044 if (cwd == NULL) {
5045 error = got_error_from_errno("getcwd");
5046 goto done;
5049 if (repo_path == NULL) {
5050 error = got_worktree_open(&worktree, cwd);
5051 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5052 goto done;
5053 else
5054 error = NULL;
5055 if (worktree) {
5056 repo_path =
5057 strdup(got_worktree_get_repo_path(worktree));
5058 if (repo_path == NULL)
5059 error = got_error_from_errno("strdup");
5060 if (error)
5061 goto done;
5062 } else {
5063 repo_path = strdup(cwd);
5064 if (repo_path == NULL) {
5065 error = got_error_from_errno("strdup");
5066 goto done;
5071 error = got_repo_open(&repo, repo_path, NULL);
5072 if (error != NULL)
5073 goto done;
5075 error = apply_unveil(got_repo_get_path(repo), do_list,
5076 worktree ? got_worktree_get_root_path(worktree) : NULL);
5077 if (error)
5078 goto done;
5080 if (do_show)
5081 error = show_current_branch(repo, worktree);
5082 else if (do_list)
5083 error = list_branches(repo, worktree);
5084 else if (delref)
5085 error = delete_branch(repo, worktree, delref);
5086 else {
5087 if (commit_id_arg == NULL)
5088 commit_id_arg = worktree ?
5089 got_worktree_get_head_ref_name(worktree) :
5090 GOT_REF_HEAD;
5091 error = got_repo_match_object_id(&commit_id, NULL,
5092 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5093 if (error)
5094 goto done;
5095 error = add_branch(repo, argv[0], commit_id);
5096 if (error)
5097 goto done;
5098 if (worktree && do_update) {
5099 struct got_update_progress_arg upa;
5100 char *branch_refname = NULL;
5102 error = got_object_id_str(&commit_id_str, commit_id);
5103 if (error)
5104 goto done;
5105 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5106 worktree);
5107 if (error)
5108 goto done;
5109 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5110 == -1) {
5111 error = got_error_from_errno("asprintf");
5112 goto done;
5114 error = got_ref_open(&ref, repo, branch_refname, 0);
5115 free(branch_refname);
5116 if (error)
5117 goto done;
5118 error = switch_head_ref(ref, commit_id, worktree,
5119 repo);
5120 if (error)
5121 goto done;
5122 error = got_worktree_set_base_commit_id(worktree, repo,
5123 commit_id);
5124 if (error)
5125 goto done;
5126 memset(&upa, 0, sizeof(upa));
5127 error = got_worktree_checkout_files(worktree, &paths,
5128 repo, update_progress, &upa, check_cancelled,
5129 NULL);
5130 if (error)
5131 goto done;
5132 if (upa.did_something)
5133 printf("Updated to commit %s\n", commit_id_str);
5134 print_update_progress_stats(&upa);
5137 done:
5138 if (ref)
5139 got_ref_close(ref);
5140 if (repo)
5141 got_repo_close(repo);
5142 if (worktree)
5143 got_worktree_close(worktree);
5144 free(cwd);
5145 free(repo_path);
5146 free(commit_id);
5147 free(commit_id_str);
5148 TAILQ_FOREACH(pe, &paths, entry)
5149 free((char *)pe->path);
5150 got_pathlist_free(&paths);
5151 return error;
5155 __dead static void
5156 usage_tag(void)
5158 fprintf(stderr,
5159 "usage: %s tag [-c commit] [-r repository] [-l] "
5160 "[-m message] name\n", getprogname());
5161 exit(1);
5164 #if 0
5165 static const struct got_error *
5166 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5168 const struct got_error *err = NULL;
5169 struct got_reflist_entry *re, *se, *new;
5170 struct got_object_id *re_id, *se_id;
5171 struct got_tag_object *re_tag, *se_tag;
5172 time_t re_time, se_time;
5174 SIMPLEQ_FOREACH(re, tags, entry) {
5175 se = SIMPLEQ_FIRST(sorted);
5176 if (se == NULL) {
5177 err = got_reflist_entry_dup(&new, re);
5178 if (err)
5179 return err;
5180 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5181 continue;
5182 } else {
5183 err = got_ref_resolve(&re_id, repo, re->ref);
5184 if (err)
5185 break;
5186 err = got_object_open_as_tag(&re_tag, repo, re_id);
5187 free(re_id);
5188 if (err)
5189 break;
5190 re_time = got_object_tag_get_tagger_time(re_tag);
5191 got_object_tag_close(re_tag);
5194 while (se) {
5195 err = got_ref_resolve(&se_id, repo, re->ref);
5196 if (err)
5197 break;
5198 err = got_object_open_as_tag(&se_tag, repo, se_id);
5199 free(se_id);
5200 if (err)
5201 break;
5202 se_time = got_object_tag_get_tagger_time(se_tag);
5203 got_object_tag_close(se_tag);
5205 if (se_time > re_time) {
5206 err = got_reflist_entry_dup(&new, re);
5207 if (err)
5208 return err;
5209 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5210 break;
5212 se = SIMPLEQ_NEXT(se, entry);
5213 continue;
5216 done:
5217 return err;
5219 #endif
5221 static const struct got_error *
5222 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5224 static const struct got_error *err = NULL;
5225 struct got_reflist_head refs;
5226 struct got_reflist_entry *re;
5228 SIMPLEQ_INIT(&refs);
5230 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5231 if (err)
5232 return err;
5234 SIMPLEQ_FOREACH(re, &refs, entry) {
5235 const char *refname;
5236 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5237 char datebuf[26];
5238 const char *tagger;
5239 time_t tagger_time;
5240 struct got_object_id *id;
5241 struct got_tag_object *tag;
5242 struct got_commit_object *commit = NULL;
5244 refname = got_ref_get_name(re->ref);
5245 if (strncmp(refname, "refs/tags/", 10) != 0)
5246 continue;
5247 refname += 10;
5248 refstr = got_ref_to_str(re->ref);
5249 if (refstr == NULL) {
5250 err = got_error_from_errno("got_ref_to_str");
5251 break;
5253 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5254 free(refstr);
5256 err = got_ref_resolve(&id, repo, re->ref);
5257 if (err)
5258 break;
5259 err = got_object_open_as_tag(&tag, repo, id);
5260 if (err) {
5261 if (err->code != GOT_ERR_OBJ_TYPE) {
5262 free(id);
5263 break;
5265 /* "lightweight" tag */
5266 err = got_object_open_as_commit(&commit, repo, id);
5267 if (err) {
5268 free(id);
5269 break;
5271 tagger = got_object_commit_get_committer(commit);
5272 tagger_time =
5273 got_object_commit_get_committer_time(commit);
5274 err = got_object_id_str(&id_str, id);
5275 free(id);
5276 if (err)
5277 break;
5278 } else {
5279 free(id);
5280 tagger = got_object_tag_get_tagger(tag);
5281 tagger_time = got_object_tag_get_tagger_time(tag);
5282 err = got_object_id_str(&id_str,
5283 got_object_tag_get_object_id(tag));
5284 if (err)
5285 break;
5287 printf("from: %s\n", tagger);
5288 datestr = get_datestr(&tagger_time, datebuf);
5289 if (datestr)
5290 printf("date: %s UTC\n", datestr);
5291 if (commit)
5292 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5293 else {
5294 switch (got_object_tag_get_object_type(tag)) {
5295 case GOT_OBJ_TYPE_BLOB:
5296 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5297 id_str);
5298 break;
5299 case GOT_OBJ_TYPE_TREE:
5300 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5301 id_str);
5302 break;
5303 case GOT_OBJ_TYPE_COMMIT:
5304 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5305 id_str);
5306 break;
5307 case GOT_OBJ_TYPE_TAG:
5308 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5309 id_str);
5310 break;
5311 default:
5312 break;
5315 free(id_str);
5316 if (commit) {
5317 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5318 if (err)
5319 break;
5320 got_object_commit_close(commit);
5321 } else {
5322 tagmsg0 = strdup(got_object_tag_get_message(tag));
5323 got_object_tag_close(tag);
5324 if (tagmsg0 == NULL) {
5325 err = got_error_from_errno("strdup");
5326 break;
5330 tagmsg = tagmsg0;
5331 do {
5332 line = strsep(&tagmsg, "\n");
5333 if (line)
5334 printf(" %s\n", line);
5335 } while (line);
5336 free(tagmsg0);
5339 got_ref_list_free(&refs);
5340 return NULL;
5343 static const struct got_error *
5344 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5345 const char *tag_name, const char *repo_path)
5347 const struct got_error *err = NULL;
5348 char *template = NULL, *initial_content = NULL;
5349 char *editor = NULL;
5350 int fd = -1;
5352 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5353 err = got_error_from_errno("asprintf");
5354 goto done;
5357 if (asprintf(&initial_content, "\n# tagging commit %s as %s\n",
5358 commit_id_str, tag_name) == -1) {
5359 err = got_error_from_errno("asprintf");
5360 goto done;
5363 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5364 if (err)
5365 goto done;
5367 dprintf(fd, initial_content);
5368 close(fd);
5370 err = get_editor(&editor);
5371 if (err)
5372 goto done;
5373 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
5374 done:
5375 free(initial_content);
5376 free(template);
5377 free(editor);
5379 /* Editor is done; we can now apply unveil(2) */
5380 if (err == NULL) {
5381 err = apply_unveil(repo_path, 0, NULL);
5382 if (err) {
5383 free(*tagmsg);
5384 *tagmsg = NULL;
5387 return err;
5390 static const struct got_error *
5391 add_tag(struct got_repository *repo, const char *tag_name,
5392 const char *commit_arg, const char *tagmsg_arg)
5394 const struct got_error *err = NULL;
5395 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5396 char *label = NULL, *commit_id_str = NULL;
5397 struct got_reference *ref = NULL;
5398 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5399 char *tagmsg_path = NULL, *tag_id_str = NULL;
5400 int preserve_tagmsg = 0;
5403 * Don't let the user create a tag name with a leading '-'.
5404 * While technically a valid reference name, this case is usually
5405 * an unintended typo.
5407 if (tag_name[0] == '-')
5408 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5410 err = get_author(&tagger, repo);
5411 if (err)
5412 return err;
5414 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5415 GOT_OBJ_TYPE_COMMIT, 1, repo);
5416 if (err)
5417 goto done;
5419 err = got_object_id_str(&commit_id_str, commit_id);
5420 if (err)
5421 goto done;
5423 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5424 refname = strdup(tag_name);
5425 if (refname == NULL) {
5426 err = got_error_from_errno("strdup");
5427 goto done;
5429 tag_name += 10;
5430 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5431 err = got_error_from_errno("asprintf");
5432 goto done;
5435 err = got_ref_open(&ref, repo, refname, 0);
5436 if (err == NULL) {
5437 err = got_error(GOT_ERR_TAG_EXISTS);
5438 goto done;
5439 } else if (err->code != GOT_ERR_NOT_REF)
5440 goto done;
5442 if (tagmsg_arg == NULL) {
5443 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5444 tag_name, got_repo_get_path(repo));
5445 if (err) {
5446 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5447 tagmsg_path != NULL)
5448 preserve_tagmsg = 1;
5449 goto done;
5453 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5454 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5455 if (err) {
5456 if (tagmsg_path)
5457 preserve_tagmsg = 1;
5458 goto done;
5461 err = got_ref_alloc(&ref, refname, tag_id);
5462 if (err) {
5463 if (tagmsg_path)
5464 preserve_tagmsg = 1;
5465 goto done;
5468 err = got_ref_write(ref, repo);
5469 if (err) {
5470 if (tagmsg_path)
5471 preserve_tagmsg = 1;
5472 goto done;
5475 err = got_object_id_str(&tag_id_str, tag_id);
5476 if (err) {
5477 if (tagmsg_path)
5478 preserve_tagmsg = 1;
5479 goto done;
5481 printf("Created tag %s\n", tag_id_str);
5482 done:
5483 if (preserve_tagmsg) {
5484 fprintf(stderr, "%s: tag message preserved in %s\n",
5485 getprogname(), tagmsg_path);
5486 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
5487 err = got_error_from_errno2("unlink", tagmsg_path);
5488 free(tag_id_str);
5489 if (ref)
5490 got_ref_close(ref);
5491 free(commit_id);
5492 free(commit_id_str);
5493 free(refname);
5494 free(tagmsg);
5495 free(tagmsg_path);
5496 free(tagger);
5497 return err;
5500 static const struct got_error *
5501 cmd_tag(int argc, char *argv[])
5503 const struct got_error *error = NULL;
5504 struct got_repository *repo = NULL;
5505 struct got_worktree *worktree = NULL;
5506 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
5507 char *gitconfig_path = NULL;
5508 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
5509 int ch, do_list = 0;
5511 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
5512 switch (ch) {
5513 case 'c':
5514 commit_id_arg = optarg;
5515 break;
5516 case 'm':
5517 tagmsg = optarg;
5518 break;
5519 case 'r':
5520 repo_path = realpath(optarg, NULL);
5521 if (repo_path == NULL)
5522 return got_error_from_errno2("realpath",
5523 optarg);
5524 got_path_strip_trailing_slashes(repo_path);
5525 break;
5526 case 'l':
5527 do_list = 1;
5528 break;
5529 default:
5530 usage_tag();
5531 /* NOTREACHED */
5535 argc -= optind;
5536 argv += optind;
5538 if (do_list) {
5539 if (commit_id_arg != NULL)
5540 errx(1,
5541 "-c option can only be used when creating a tag");
5542 if (tagmsg)
5543 errx(1, "-l and -m options are mutually exclusive");
5544 if (argc > 0)
5545 usage_tag();
5546 } else if (argc != 1)
5547 usage_tag();
5549 tag_name = argv[0];
5551 #ifndef PROFILE
5552 if (do_list) {
5553 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5554 NULL) == -1)
5555 err(1, "pledge");
5556 } else {
5557 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5558 "sendfd unveil", NULL) == -1)
5559 err(1, "pledge");
5561 #endif
5562 cwd = getcwd(NULL, 0);
5563 if (cwd == NULL) {
5564 error = got_error_from_errno("getcwd");
5565 goto done;
5568 if (repo_path == NULL) {
5569 error = got_worktree_open(&worktree, cwd);
5570 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5571 goto done;
5572 else
5573 error = NULL;
5574 if (worktree) {
5575 repo_path =
5576 strdup(got_worktree_get_repo_path(worktree));
5577 if (repo_path == NULL)
5578 error = got_error_from_errno("strdup");
5579 if (error)
5580 goto done;
5581 } else {
5582 repo_path = strdup(cwd);
5583 if (repo_path == NULL) {
5584 error = got_error_from_errno("strdup");
5585 goto done;
5590 if (do_list) {
5591 error = got_repo_open(&repo, repo_path, NULL);
5592 if (error != NULL)
5593 goto done;
5594 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5595 if (error)
5596 goto done;
5597 error = list_tags(repo, worktree);
5598 } else {
5599 error = get_gitconfig_path(&gitconfig_path);
5600 if (error)
5601 goto done;
5602 error = got_repo_open(&repo, repo_path, gitconfig_path);
5603 if (error != NULL)
5604 goto done;
5606 if (tagmsg) {
5607 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5608 if (error)
5609 goto done;
5612 if (commit_id_arg == NULL) {
5613 struct got_reference *head_ref;
5614 struct got_object_id *commit_id;
5615 error = got_ref_open(&head_ref, repo,
5616 worktree ? got_worktree_get_head_ref_name(worktree)
5617 : GOT_REF_HEAD, 0);
5618 if (error)
5619 goto done;
5620 error = got_ref_resolve(&commit_id, repo, head_ref);
5621 got_ref_close(head_ref);
5622 if (error)
5623 goto done;
5624 error = got_object_id_str(&commit_id_str, commit_id);
5625 free(commit_id);
5626 if (error)
5627 goto done;
5630 error = add_tag(repo, tag_name,
5631 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
5633 done:
5634 if (repo)
5635 got_repo_close(repo);
5636 if (worktree)
5637 got_worktree_close(worktree);
5638 free(cwd);
5639 free(repo_path);
5640 free(gitconfig_path);
5641 free(commit_id_str);
5642 return error;
5645 __dead static void
5646 usage_add(void)
5648 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
5649 getprogname());
5650 exit(1);
5653 static const struct got_error *
5654 add_progress(void *arg, unsigned char status, const char *path)
5656 while (path[0] == '/')
5657 path++;
5658 printf("%c %s\n", status, path);
5659 return NULL;
5662 static const struct got_error *
5663 cmd_add(int argc, char *argv[])
5665 const struct got_error *error = NULL;
5666 struct got_repository *repo = NULL;
5667 struct got_worktree *worktree = NULL;
5668 char *cwd = NULL;
5669 struct got_pathlist_head paths;
5670 struct got_pathlist_entry *pe;
5671 int ch, can_recurse = 0, no_ignores = 0;
5673 TAILQ_INIT(&paths);
5675 while ((ch = getopt(argc, argv, "IR")) != -1) {
5676 switch (ch) {
5677 case 'I':
5678 no_ignores = 1;
5679 break;
5680 case 'R':
5681 can_recurse = 1;
5682 break;
5683 default:
5684 usage_add();
5685 /* NOTREACHED */
5689 argc -= optind;
5690 argv += optind;
5692 #ifndef PROFILE
5693 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5694 NULL) == -1)
5695 err(1, "pledge");
5696 #endif
5697 if (argc < 1)
5698 usage_add();
5700 cwd = getcwd(NULL, 0);
5701 if (cwd == NULL) {
5702 error = got_error_from_errno("getcwd");
5703 goto done;
5706 error = got_worktree_open(&worktree, cwd);
5707 if (error) {
5708 if (error->code == GOT_ERR_NOT_WORKTREE)
5709 error = wrap_not_worktree_error(error, "add", cwd);
5710 goto done;
5713 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5714 NULL);
5715 if (error != NULL)
5716 goto done;
5718 error = apply_unveil(got_repo_get_path(repo), 1,
5719 got_worktree_get_root_path(worktree));
5720 if (error)
5721 goto done;
5723 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5724 if (error)
5725 goto done;
5727 if (!can_recurse && no_ignores) {
5728 error = got_error_msg(GOT_ERR_BAD_PATH,
5729 "disregarding ignores requires -R option");
5730 goto done;
5734 if (!can_recurse) {
5735 char *ondisk_path;
5736 struct stat sb;
5737 TAILQ_FOREACH(pe, &paths, entry) {
5738 if (asprintf(&ondisk_path, "%s/%s",
5739 got_worktree_get_root_path(worktree),
5740 pe->path) == -1) {
5741 error = got_error_from_errno("asprintf");
5742 goto done;
5744 if (lstat(ondisk_path, &sb) == -1) {
5745 if (errno == ENOENT) {
5746 free(ondisk_path);
5747 continue;
5749 error = got_error_from_errno2("lstat",
5750 ondisk_path);
5751 free(ondisk_path);
5752 goto done;
5754 free(ondisk_path);
5755 if (S_ISDIR(sb.st_mode)) {
5756 error = got_error_msg(GOT_ERR_BAD_PATH,
5757 "adding directories requires -R option");
5758 goto done;
5763 error = got_worktree_schedule_add(worktree, &paths, add_progress,
5764 NULL, repo, no_ignores);
5765 done:
5766 if (repo)
5767 got_repo_close(repo);
5768 if (worktree)
5769 got_worktree_close(worktree);
5770 TAILQ_FOREACH(pe, &paths, entry)
5771 free((char *)pe->path);
5772 got_pathlist_free(&paths);
5773 free(cwd);
5774 return error;
5777 __dead static void
5778 usage_remove(void)
5780 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] path ...\n",
5781 getprogname());
5782 exit(1);
5785 static const struct got_error *
5786 print_remove_status(void *arg, unsigned char status,
5787 unsigned char staged_status, const char *path)
5789 while (path[0] == '/')
5790 path++;
5791 if (status == GOT_STATUS_NONEXISTENT)
5792 return NULL;
5793 if (status == staged_status && (status == GOT_STATUS_DELETE))
5794 status = GOT_STATUS_NO_CHANGE;
5795 printf("%c%c %s\n", status, staged_status, path);
5796 return NULL;
5799 static const struct got_error *
5800 cmd_remove(int argc, char *argv[])
5802 const struct got_error *error = NULL;
5803 struct got_worktree *worktree = NULL;
5804 struct got_repository *repo = NULL;
5805 char *cwd = NULL;
5806 struct got_pathlist_head paths;
5807 struct got_pathlist_entry *pe;
5808 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0;
5810 TAILQ_INIT(&paths);
5812 while ((ch = getopt(argc, argv, "fkR")) != -1) {
5813 switch (ch) {
5814 case 'f':
5815 delete_local_mods = 1;
5816 break;
5817 case 'k':
5818 keep_on_disk = 1;
5819 break;
5820 case 'R':
5821 can_recurse = 1;
5822 break;
5823 default:
5824 usage_remove();
5825 /* NOTREACHED */
5829 argc -= optind;
5830 argv += optind;
5832 #ifndef PROFILE
5833 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5834 NULL) == -1)
5835 err(1, "pledge");
5836 #endif
5837 if (argc < 1)
5838 usage_remove();
5840 cwd = getcwd(NULL, 0);
5841 if (cwd == NULL) {
5842 error = got_error_from_errno("getcwd");
5843 goto done;
5845 error = got_worktree_open(&worktree, cwd);
5846 if (error) {
5847 if (error->code == GOT_ERR_NOT_WORKTREE)
5848 error = wrap_not_worktree_error(error, "remove", cwd);
5849 goto done;
5852 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5853 NULL);
5854 if (error)
5855 goto done;
5857 error = apply_unveil(got_repo_get_path(repo), 1,
5858 got_worktree_get_root_path(worktree));
5859 if (error)
5860 goto done;
5862 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5863 if (error)
5864 goto done;
5866 if (!can_recurse) {
5867 char *ondisk_path;
5868 struct stat sb;
5869 TAILQ_FOREACH(pe, &paths, entry) {
5870 if (asprintf(&ondisk_path, "%s/%s",
5871 got_worktree_get_root_path(worktree),
5872 pe->path) == -1) {
5873 error = got_error_from_errno("asprintf");
5874 goto done;
5876 if (lstat(ondisk_path, &sb) == -1) {
5877 if (errno == ENOENT) {
5878 free(ondisk_path);
5879 continue;
5881 error = got_error_from_errno2("lstat",
5882 ondisk_path);
5883 free(ondisk_path);
5884 goto done;
5886 free(ondisk_path);
5887 if (S_ISDIR(sb.st_mode)) {
5888 error = got_error_msg(GOT_ERR_BAD_PATH,
5889 "removing directories requires -R option");
5890 goto done;
5895 error = got_worktree_schedule_delete(worktree, &paths,
5896 delete_local_mods, print_remove_status, NULL, repo, keep_on_disk);
5897 done:
5898 if (repo)
5899 got_repo_close(repo);
5900 if (worktree)
5901 got_worktree_close(worktree);
5902 TAILQ_FOREACH(pe, &paths, entry)
5903 free((char *)pe->path);
5904 got_pathlist_free(&paths);
5905 free(cwd);
5906 return error;
5909 __dead static void
5910 usage_revert(void)
5912 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
5913 "path ...\n", getprogname());
5914 exit(1);
5917 static const struct got_error *
5918 revert_progress(void *arg, unsigned char status, const char *path)
5920 if (status == GOT_STATUS_UNVERSIONED)
5921 return NULL;
5923 while (path[0] == '/')
5924 path++;
5925 printf("%c %s\n", status, path);
5926 return NULL;
5929 struct choose_patch_arg {
5930 FILE *patch_script_file;
5931 const char *action;
5934 static const struct got_error *
5935 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
5936 int nchanges, const char *action)
5938 char *line = NULL;
5939 size_t linesize = 0;
5940 ssize_t linelen;
5942 switch (status) {
5943 case GOT_STATUS_ADD:
5944 printf("A %s\n%s this addition? [y/n] ", path, action);
5945 break;
5946 case GOT_STATUS_DELETE:
5947 printf("D %s\n%s this deletion? [y/n] ", path, action);
5948 break;
5949 case GOT_STATUS_MODIFY:
5950 if (fseek(patch_file, 0L, SEEK_SET) == -1)
5951 return got_error_from_errno("fseek");
5952 printf(GOT_COMMIT_SEP_STR);
5953 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
5954 printf("%s", line);
5955 if (ferror(patch_file))
5956 return got_error_from_errno("getline");
5957 printf(GOT_COMMIT_SEP_STR);
5958 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
5959 path, n, nchanges, action);
5960 break;
5961 default:
5962 return got_error_path(path, GOT_ERR_FILE_STATUS);
5965 return NULL;
5968 static const struct got_error *
5969 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
5970 FILE *patch_file, int n, int nchanges)
5972 const struct got_error *err = NULL;
5973 char *line = NULL;
5974 size_t linesize = 0;
5975 ssize_t linelen;
5976 int resp = ' ';
5977 struct choose_patch_arg *a = arg;
5979 *choice = GOT_PATCH_CHOICE_NONE;
5981 if (a->patch_script_file) {
5982 char *nl;
5983 err = show_change(status, path, patch_file, n, nchanges,
5984 a->action);
5985 if (err)
5986 return err;
5987 linelen = getline(&line, &linesize, a->patch_script_file);
5988 if (linelen == -1) {
5989 if (ferror(a->patch_script_file))
5990 return got_error_from_errno("getline");
5991 return NULL;
5993 nl = strchr(line, '\n');
5994 if (nl)
5995 *nl = '\0';
5996 if (strcmp(line, "y") == 0) {
5997 *choice = GOT_PATCH_CHOICE_YES;
5998 printf("y\n");
5999 } else if (strcmp(line, "n") == 0) {
6000 *choice = GOT_PATCH_CHOICE_NO;
6001 printf("n\n");
6002 } else if (strcmp(line, "q") == 0 &&
6003 status == GOT_STATUS_MODIFY) {
6004 *choice = GOT_PATCH_CHOICE_QUIT;
6005 printf("q\n");
6006 } else
6007 printf("invalid response '%s'\n", line);
6008 free(line);
6009 return NULL;
6012 while (resp != 'y' && resp != 'n' && resp != 'q') {
6013 err = show_change(status, path, patch_file, n, nchanges,
6014 a->action);
6015 if (err)
6016 return err;
6017 resp = getchar();
6018 if (resp == '\n')
6019 resp = getchar();
6020 if (status == GOT_STATUS_MODIFY) {
6021 if (resp != 'y' && resp != 'n' && resp != 'q') {
6022 printf("invalid response '%c'\n", resp);
6023 resp = ' ';
6025 } else if (resp != 'y' && resp != 'n') {
6026 printf("invalid response '%c'\n", resp);
6027 resp = ' ';
6031 if (resp == 'y')
6032 *choice = GOT_PATCH_CHOICE_YES;
6033 else if (resp == 'n')
6034 *choice = GOT_PATCH_CHOICE_NO;
6035 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6036 *choice = GOT_PATCH_CHOICE_QUIT;
6038 return NULL;
6042 static const struct got_error *
6043 cmd_revert(int argc, char *argv[])
6045 const struct got_error *error = NULL;
6046 struct got_worktree *worktree = NULL;
6047 struct got_repository *repo = NULL;
6048 char *cwd = NULL, *path = NULL;
6049 struct got_pathlist_head paths;
6050 struct got_pathlist_entry *pe;
6051 int ch, can_recurse = 0, pflag = 0;
6052 FILE *patch_script_file = NULL;
6053 const char *patch_script_path = NULL;
6054 struct choose_patch_arg cpa;
6056 TAILQ_INIT(&paths);
6058 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6059 switch (ch) {
6060 case 'p':
6061 pflag = 1;
6062 break;
6063 case 'F':
6064 patch_script_path = optarg;
6065 break;
6066 case 'R':
6067 can_recurse = 1;
6068 break;
6069 default:
6070 usage_revert();
6071 /* NOTREACHED */
6075 argc -= optind;
6076 argv += optind;
6078 #ifndef PROFILE
6079 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6080 "unveil", NULL) == -1)
6081 err(1, "pledge");
6082 #endif
6083 if (argc < 1)
6084 usage_revert();
6085 if (patch_script_path && !pflag)
6086 errx(1, "-F option can only be used together with -p option");
6088 cwd = getcwd(NULL, 0);
6089 if (cwd == NULL) {
6090 error = got_error_from_errno("getcwd");
6091 goto done;
6093 error = got_worktree_open(&worktree, cwd);
6094 if (error) {
6095 if (error->code == GOT_ERR_NOT_WORKTREE)
6096 error = wrap_not_worktree_error(error, "revert", cwd);
6097 goto done;
6100 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6101 NULL);
6102 if (error != NULL)
6103 goto done;
6105 if (patch_script_path) {
6106 patch_script_file = fopen(patch_script_path, "r");
6107 if (patch_script_file == NULL) {
6108 error = got_error_from_errno2("fopen",
6109 patch_script_path);
6110 goto done;
6113 error = apply_unveil(got_repo_get_path(repo), 1,
6114 got_worktree_get_root_path(worktree));
6115 if (error)
6116 goto done;
6118 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6119 if (error)
6120 goto done;
6122 if (!can_recurse) {
6123 char *ondisk_path;
6124 struct stat sb;
6125 TAILQ_FOREACH(pe, &paths, entry) {
6126 if (asprintf(&ondisk_path, "%s/%s",
6127 got_worktree_get_root_path(worktree),
6128 pe->path) == -1) {
6129 error = got_error_from_errno("asprintf");
6130 goto done;
6132 if (lstat(ondisk_path, &sb) == -1) {
6133 if (errno == ENOENT) {
6134 free(ondisk_path);
6135 continue;
6137 error = got_error_from_errno2("lstat",
6138 ondisk_path);
6139 free(ondisk_path);
6140 goto done;
6142 free(ondisk_path);
6143 if (S_ISDIR(sb.st_mode)) {
6144 error = got_error_msg(GOT_ERR_BAD_PATH,
6145 "reverting directories requires -R option");
6146 goto done;
6151 cpa.patch_script_file = patch_script_file;
6152 cpa.action = "revert";
6153 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6154 pflag ? choose_patch : NULL, &cpa, repo);
6155 done:
6156 if (patch_script_file && fclose(patch_script_file) == EOF &&
6157 error == NULL)
6158 error = got_error_from_errno2("fclose", patch_script_path);
6159 if (repo)
6160 got_repo_close(repo);
6161 if (worktree)
6162 got_worktree_close(worktree);
6163 free(path);
6164 free(cwd);
6165 return error;
6168 __dead static void
6169 usage_commit(void)
6171 fprintf(stderr, "usage: %s commit [-m msg] [path ...]\n",
6172 getprogname());
6173 exit(1);
6176 struct collect_commit_logmsg_arg {
6177 const char *cmdline_log;
6178 const char *editor;
6179 const char *worktree_path;
6180 const char *branch_name;
6181 const char *repo_path;
6182 char *logmsg_path;
6186 static const struct got_error *
6187 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6188 void *arg)
6190 char *initial_content = NULL;
6191 struct got_pathlist_entry *pe;
6192 const struct got_error *err = NULL;
6193 char *template = NULL;
6194 struct collect_commit_logmsg_arg *a = arg;
6195 int fd;
6196 size_t len;
6198 /* if a message was specified on the command line, just use it */
6199 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6200 len = strlen(a->cmdline_log) + 1;
6201 *logmsg = malloc(len + 1);
6202 if (*logmsg == NULL)
6203 return got_error_from_errno("malloc");
6204 strlcpy(*logmsg, a->cmdline_log, len);
6205 return NULL;
6208 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6209 return got_error_from_errno("asprintf");
6211 if (asprintf(&initial_content,
6212 "\n# changes to be committed on branch %s:\n",
6213 a->branch_name) == -1)
6214 return got_error_from_errno("asprintf");
6216 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6217 if (err)
6218 goto done;
6220 dprintf(fd, initial_content);
6222 TAILQ_FOREACH(pe, commitable_paths, entry) {
6223 struct got_commitable *ct = pe->data;
6224 dprintf(fd, "# %c %s\n",
6225 got_commitable_get_status(ct),
6226 got_commitable_get_path(ct));
6228 close(fd);
6230 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
6231 done:
6232 free(initial_content);
6233 free(template);
6235 /* Editor is done; we can now apply unveil(2) */
6236 if (err == NULL) {
6237 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6238 if (err) {
6239 free(*logmsg);
6240 *logmsg = NULL;
6243 return err;
6246 static const struct got_error *
6247 cmd_commit(int argc, char *argv[])
6249 const struct got_error *error = NULL;
6250 struct got_worktree *worktree = NULL;
6251 struct got_repository *repo = NULL;
6252 char *cwd = NULL, *id_str = NULL;
6253 struct got_object_id *id = NULL;
6254 const char *logmsg = NULL;
6255 struct collect_commit_logmsg_arg cl_arg;
6256 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6257 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6258 struct got_pathlist_head paths;
6260 TAILQ_INIT(&paths);
6261 cl_arg.logmsg_path = NULL;
6263 while ((ch = getopt(argc, argv, "m:")) != -1) {
6264 switch (ch) {
6265 case 'm':
6266 logmsg = optarg;
6267 break;
6268 default:
6269 usage_commit();
6270 /* NOTREACHED */
6274 argc -= optind;
6275 argv += optind;
6277 #ifndef PROFILE
6278 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6279 "unveil", NULL) == -1)
6280 err(1, "pledge");
6281 #endif
6282 cwd = getcwd(NULL, 0);
6283 if (cwd == NULL) {
6284 error = got_error_from_errno("getcwd");
6285 goto done;
6287 error = got_worktree_open(&worktree, cwd);
6288 if (error) {
6289 if (error->code == GOT_ERR_NOT_WORKTREE)
6290 error = wrap_not_worktree_error(error, "commit", cwd);
6291 goto done;
6294 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6295 if (error)
6296 goto done;
6297 if (rebase_in_progress) {
6298 error = got_error(GOT_ERR_REBASING);
6299 goto done;
6302 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6303 worktree);
6304 if (error)
6305 goto done;
6307 error = get_gitconfig_path(&gitconfig_path);
6308 if (error)
6309 goto done;
6310 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6311 gitconfig_path);
6312 if (error != NULL)
6313 goto done;
6315 error = get_author(&author, repo);
6316 if (error)
6317 return error;
6320 * unveil(2) traverses exec(2); if an editor is used we have
6321 * to apply unveil after the log message has been written.
6323 if (logmsg == NULL || strlen(logmsg) == 0)
6324 error = get_editor(&editor);
6325 else
6326 error = apply_unveil(got_repo_get_path(repo), 0,
6327 got_worktree_get_root_path(worktree));
6328 if (error)
6329 goto done;
6331 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6332 if (error)
6333 goto done;
6335 cl_arg.editor = editor;
6336 cl_arg.cmdline_log = logmsg;
6337 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6338 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6339 if (!histedit_in_progress) {
6340 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6341 error = got_error(GOT_ERR_COMMIT_BRANCH);
6342 goto done;
6344 cl_arg.branch_name += 11;
6346 cl_arg.repo_path = got_repo_get_path(repo);
6347 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6348 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
6349 if (error) {
6350 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6351 cl_arg.logmsg_path != NULL)
6352 preserve_logmsg = 1;
6353 goto done;
6356 error = got_object_id_str(&id_str, id);
6357 if (error)
6358 goto done;
6359 printf("Created commit %s\n", id_str);
6360 done:
6361 if (preserve_logmsg) {
6362 fprintf(stderr, "%s: log message preserved in %s\n",
6363 getprogname(), cl_arg.logmsg_path);
6364 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6365 error == NULL)
6366 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6367 free(cl_arg.logmsg_path);
6368 if (repo)
6369 got_repo_close(repo);
6370 if (worktree)
6371 got_worktree_close(worktree);
6372 free(cwd);
6373 free(id_str);
6374 free(gitconfig_path);
6375 free(editor);
6376 free(author);
6377 return error;
6380 __dead static void
6381 usage_cherrypick(void)
6383 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6384 exit(1);
6387 static const struct got_error *
6388 cmd_cherrypick(int argc, char *argv[])
6390 const struct got_error *error = NULL;
6391 struct got_worktree *worktree = NULL;
6392 struct got_repository *repo = NULL;
6393 char *cwd = NULL, *commit_id_str = NULL;
6394 struct got_object_id *commit_id = NULL;
6395 struct got_commit_object *commit = NULL;
6396 struct got_object_qid *pid;
6397 struct got_reference *head_ref = NULL;
6398 int ch;
6399 struct got_update_progress_arg upa;
6401 while ((ch = getopt(argc, argv, "")) != -1) {
6402 switch (ch) {
6403 default:
6404 usage_cherrypick();
6405 /* NOTREACHED */
6409 argc -= optind;
6410 argv += optind;
6412 #ifndef PROFILE
6413 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6414 "unveil", NULL) == -1)
6415 err(1, "pledge");
6416 #endif
6417 if (argc != 1)
6418 usage_cherrypick();
6420 cwd = getcwd(NULL, 0);
6421 if (cwd == NULL) {
6422 error = got_error_from_errno("getcwd");
6423 goto done;
6425 error = got_worktree_open(&worktree, cwd);
6426 if (error) {
6427 if (error->code == GOT_ERR_NOT_WORKTREE)
6428 error = wrap_not_worktree_error(error, "cherrypick",
6429 cwd);
6430 goto done;
6433 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6434 NULL);
6435 if (error != NULL)
6436 goto done;
6438 error = apply_unveil(got_repo_get_path(repo), 0,
6439 got_worktree_get_root_path(worktree));
6440 if (error)
6441 goto done;
6443 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6444 GOT_OBJ_TYPE_COMMIT, repo);
6445 if (error != NULL) {
6446 struct got_reference *ref;
6447 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6448 goto done;
6449 error = got_ref_open(&ref, repo, argv[0], 0);
6450 if (error != NULL)
6451 goto done;
6452 error = got_ref_resolve(&commit_id, repo, ref);
6453 got_ref_close(ref);
6454 if (error != NULL)
6455 goto done;
6457 error = got_object_id_str(&commit_id_str, commit_id);
6458 if (error)
6459 goto done;
6461 error = got_ref_open(&head_ref, repo,
6462 got_worktree_get_head_ref_name(worktree), 0);
6463 if (error != NULL)
6464 goto done;
6466 error = check_same_branch(commit_id, head_ref, NULL, repo);
6467 if (error) {
6468 if (error->code != GOT_ERR_ANCESTRY)
6469 goto done;
6470 error = NULL;
6471 } else {
6472 error = got_error(GOT_ERR_SAME_BRANCH);
6473 goto done;
6476 error = got_object_open_as_commit(&commit, repo, commit_id);
6477 if (error)
6478 goto done;
6479 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6480 memset(&upa, 0, sizeof(upa));
6481 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
6482 commit_id, repo, update_progress, &upa, check_cancelled,
6483 NULL);
6484 if (error != NULL)
6485 goto done;
6487 if (upa.did_something)
6488 printf("Merged commit %s\n", commit_id_str);
6489 print_update_progress_stats(&upa);
6490 done:
6491 if (commit)
6492 got_object_commit_close(commit);
6493 free(commit_id_str);
6494 if (head_ref)
6495 got_ref_close(head_ref);
6496 if (worktree)
6497 got_worktree_close(worktree);
6498 if (repo)
6499 got_repo_close(repo);
6500 return error;
6503 __dead static void
6504 usage_backout(void)
6506 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
6507 exit(1);
6510 static const struct got_error *
6511 cmd_backout(int argc, char *argv[])
6513 const struct got_error *error = NULL;
6514 struct got_worktree *worktree = NULL;
6515 struct got_repository *repo = NULL;
6516 char *cwd = NULL, *commit_id_str = NULL;
6517 struct got_object_id *commit_id = NULL;
6518 struct got_commit_object *commit = NULL;
6519 struct got_object_qid *pid;
6520 struct got_reference *head_ref = NULL;
6521 int ch;
6522 struct got_update_progress_arg upa;
6524 while ((ch = getopt(argc, argv, "")) != -1) {
6525 switch (ch) {
6526 default:
6527 usage_backout();
6528 /* NOTREACHED */
6532 argc -= optind;
6533 argv += optind;
6535 #ifndef PROFILE
6536 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6537 "unveil", NULL) == -1)
6538 err(1, "pledge");
6539 #endif
6540 if (argc != 1)
6541 usage_backout();
6543 cwd = getcwd(NULL, 0);
6544 if (cwd == NULL) {
6545 error = got_error_from_errno("getcwd");
6546 goto done;
6548 error = got_worktree_open(&worktree, cwd);
6549 if (error) {
6550 if (error->code == GOT_ERR_NOT_WORKTREE)
6551 error = wrap_not_worktree_error(error, "backout", cwd);
6552 goto done;
6555 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6556 NULL);
6557 if (error != NULL)
6558 goto done;
6560 error = apply_unveil(got_repo_get_path(repo), 0,
6561 got_worktree_get_root_path(worktree));
6562 if (error)
6563 goto done;
6565 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6566 GOT_OBJ_TYPE_COMMIT, repo);
6567 if (error != NULL) {
6568 struct got_reference *ref;
6569 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6570 goto done;
6571 error = got_ref_open(&ref, repo, argv[0], 0);
6572 if (error != NULL)
6573 goto done;
6574 error = got_ref_resolve(&commit_id, repo, ref);
6575 got_ref_close(ref);
6576 if (error != NULL)
6577 goto done;
6579 error = got_object_id_str(&commit_id_str, commit_id);
6580 if (error)
6581 goto done;
6583 error = got_ref_open(&head_ref, repo,
6584 got_worktree_get_head_ref_name(worktree), 0);
6585 if (error != NULL)
6586 goto done;
6588 error = check_same_branch(commit_id, head_ref, NULL, repo);
6589 if (error)
6590 goto done;
6592 error = got_object_open_as_commit(&commit, repo, commit_id);
6593 if (error)
6594 goto done;
6595 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6596 if (pid == NULL) {
6597 error = got_error(GOT_ERR_ROOT_COMMIT);
6598 goto done;
6601 memset(&upa, 0, sizeof(upa));
6602 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
6603 update_progress, &upa, check_cancelled, NULL);
6604 if (error != NULL)
6605 goto done;
6607 if (upa.did_something)
6608 printf("Backed out commit %s\n", commit_id_str);
6609 print_update_progress_stats(&upa);
6610 done:
6611 if (commit)
6612 got_object_commit_close(commit);
6613 free(commit_id_str);
6614 if (head_ref)
6615 got_ref_close(head_ref);
6616 if (worktree)
6617 got_worktree_close(worktree);
6618 if (repo)
6619 got_repo_close(repo);
6620 return error;
6623 __dead static void
6624 usage_rebase(void)
6626 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
6627 getprogname());
6628 exit(1);
6631 void
6632 trim_logmsg(char *logmsg, int limit)
6634 char *nl;
6635 size_t len;
6637 len = strlen(logmsg);
6638 if (len > limit)
6639 len = limit;
6640 logmsg[len] = '\0';
6641 nl = strchr(logmsg, '\n');
6642 if (nl)
6643 *nl = '\0';
6646 static const struct got_error *
6647 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
6649 const struct got_error *err;
6650 char *logmsg0 = NULL;
6651 const char *s;
6653 err = got_object_commit_get_logmsg(&logmsg0, commit);
6654 if (err)
6655 return err;
6657 s = logmsg0;
6658 while (isspace((unsigned char)s[0]))
6659 s++;
6661 *logmsg = strdup(s);
6662 if (*logmsg == NULL) {
6663 err = got_error_from_errno("strdup");
6664 goto done;
6667 trim_logmsg(*logmsg, limit);
6668 done:
6669 free(logmsg0);
6670 return err;
6673 static const struct got_error *
6674 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
6676 const struct got_error *err;
6677 struct got_commit_object *commit = NULL;
6678 char *id_str = NULL, *logmsg = NULL;
6680 err = got_object_open_as_commit(&commit, repo, id);
6681 if (err)
6682 return err;
6684 err = got_object_id_str(&id_str, id);
6685 if (err)
6686 goto done;
6688 id_str[12] = '\0';
6690 err = get_short_logmsg(&logmsg, 42, commit);
6691 if (err)
6692 goto done;
6694 printf("%s -> merge conflict: %s\n", id_str, logmsg);
6695 done:
6696 free(id_str);
6697 got_object_commit_close(commit);
6698 free(logmsg);
6699 return err;
6702 static const struct got_error *
6703 show_rebase_progress(struct got_commit_object *commit,
6704 struct got_object_id *old_id, struct got_object_id *new_id)
6706 const struct got_error *err;
6707 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
6709 err = got_object_id_str(&old_id_str, old_id);
6710 if (err)
6711 goto done;
6713 if (new_id) {
6714 err = got_object_id_str(&new_id_str, new_id);
6715 if (err)
6716 goto done;
6719 old_id_str[12] = '\0';
6720 if (new_id_str)
6721 new_id_str[12] = '\0';
6723 err = get_short_logmsg(&logmsg, 42, commit);
6724 if (err)
6725 goto done;
6727 printf("%s -> %s: %s\n", old_id_str,
6728 new_id_str ? new_id_str : "no-op change", logmsg);
6729 done:
6730 free(old_id_str);
6731 free(new_id_str);
6732 free(logmsg);
6733 return err;
6736 static const struct got_error *
6737 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
6738 struct got_reference *branch, struct got_reference *new_base_branch,
6739 struct got_reference *tmp_branch, struct got_repository *repo)
6741 printf("Switching work tree to %s\n", got_ref_get_name(branch));
6742 return got_worktree_rebase_complete(worktree, fileindex,
6743 new_base_branch, tmp_branch, branch, repo);
6746 static const struct got_error *
6747 rebase_commit(struct got_pathlist_head *merged_paths,
6748 struct got_worktree *worktree, struct got_fileindex *fileindex,
6749 struct got_reference *tmp_branch,
6750 struct got_object_id *commit_id, struct got_repository *repo)
6752 const struct got_error *error;
6753 struct got_commit_object *commit;
6754 struct got_object_id *new_commit_id;
6756 error = got_object_open_as_commit(&commit, repo, commit_id);
6757 if (error)
6758 return error;
6760 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
6761 worktree, fileindex, tmp_branch, commit, commit_id, repo);
6762 if (error) {
6763 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
6764 goto done;
6765 error = show_rebase_progress(commit, commit_id, NULL);
6766 } else {
6767 error = show_rebase_progress(commit, commit_id, new_commit_id);
6768 free(new_commit_id);
6770 done:
6771 got_object_commit_close(commit);
6772 return error;
6775 struct check_path_prefix_arg {
6776 const char *path_prefix;
6777 size_t len;
6778 int errcode;
6781 static const struct got_error *
6782 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
6783 struct got_blob_object *blob2, struct got_object_id *id1,
6784 struct got_object_id *id2, const char *path1, const char *path2,
6785 mode_t mode1, mode_t mode2, struct got_repository *repo)
6787 struct check_path_prefix_arg *a = arg;
6789 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
6790 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
6791 return got_error(a->errcode);
6793 return NULL;
6796 static const struct got_error *
6797 check_path_prefix(struct got_object_id *parent_id,
6798 struct got_object_id *commit_id, const char *path_prefix,
6799 int errcode, struct got_repository *repo)
6801 const struct got_error *err;
6802 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
6803 struct got_commit_object *commit = NULL, *parent_commit = NULL;
6804 struct check_path_prefix_arg cpp_arg;
6806 if (got_path_is_root_dir(path_prefix))
6807 return NULL;
6809 err = got_object_open_as_commit(&commit, repo, commit_id);
6810 if (err)
6811 goto done;
6813 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
6814 if (err)
6815 goto done;
6817 err = got_object_open_as_tree(&tree1, repo,
6818 got_object_commit_get_tree_id(parent_commit));
6819 if (err)
6820 goto done;
6822 err = got_object_open_as_tree(&tree2, repo,
6823 got_object_commit_get_tree_id(commit));
6824 if (err)
6825 goto done;
6827 cpp_arg.path_prefix = path_prefix;
6828 while (cpp_arg.path_prefix[0] == '/')
6829 cpp_arg.path_prefix++;
6830 cpp_arg.len = strlen(cpp_arg.path_prefix);
6831 cpp_arg.errcode = errcode;
6832 err = got_diff_tree(tree1, tree2, "", "", repo,
6833 check_path_prefix_in_diff, &cpp_arg, 0);
6834 done:
6835 if (tree1)
6836 got_object_tree_close(tree1);
6837 if (tree2)
6838 got_object_tree_close(tree2);
6839 if (commit)
6840 got_object_commit_close(commit);
6841 if (parent_commit)
6842 got_object_commit_close(parent_commit);
6843 return err;
6846 static const struct got_error *
6847 collect_commits(struct got_object_id_queue *commits,
6848 struct got_object_id *initial_commit_id,
6849 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
6850 const char *path_prefix, int path_prefix_errcode,
6851 struct got_repository *repo)
6853 const struct got_error *err = NULL;
6854 struct got_commit_graph *graph = NULL;
6855 struct got_object_id *parent_id = NULL;
6856 struct got_object_qid *qid;
6857 struct got_object_id *commit_id = initial_commit_id;
6859 err = got_commit_graph_open(&graph, "/", 1);
6860 if (err)
6861 return err;
6863 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
6864 check_cancelled, NULL);
6865 if (err)
6866 goto done;
6867 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
6868 err = got_commit_graph_iter_next(&parent_id, graph, repo,
6869 check_cancelled, NULL);
6870 if (err) {
6871 if (err->code == GOT_ERR_ITER_COMPLETED) {
6872 err = got_error_msg(GOT_ERR_ANCESTRY,
6873 "ran out of commits to rebase before "
6874 "youngest common ancestor commit has "
6875 "been reached?!?");
6877 goto done;
6878 } else {
6879 err = check_path_prefix(parent_id, commit_id,
6880 path_prefix, path_prefix_errcode, repo);
6881 if (err)
6882 goto done;
6884 err = got_object_qid_alloc(&qid, commit_id);
6885 if (err)
6886 goto done;
6887 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
6888 commit_id = parent_id;
6891 done:
6892 got_commit_graph_close(graph);
6893 return err;
6896 static const struct got_error *
6897 cmd_rebase(int argc, char *argv[])
6899 const struct got_error *error = NULL;
6900 struct got_worktree *worktree = NULL;
6901 struct got_repository *repo = NULL;
6902 struct got_fileindex *fileindex = NULL;
6903 char *cwd = NULL;
6904 struct got_reference *branch = NULL;
6905 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
6906 struct got_object_id *commit_id = NULL, *parent_id = NULL;
6907 struct got_object_id *resume_commit_id = NULL;
6908 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
6909 struct got_commit_object *commit = NULL;
6910 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
6911 int histedit_in_progress = 0;
6912 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
6913 struct got_object_id_queue commits;
6914 struct got_pathlist_head merged_paths;
6915 const struct got_object_id_queue *parent_ids;
6916 struct got_object_qid *qid, *pid;
6918 SIMPLEQ_INIT(&commits);
6919 TAILQ_INIT(&merged_paths);
6921 while ((ch = getopt(argc, argv, "ac")) != -1) {
6922 switch (ch) {
6923 case 'a':
6924 abort_rebase = 1;
6925 break;
6926 case 'c':
6927 continue_rebase = 1;
6928 break;
6929 default:
6930 usage_rebase();
6931 /* NOTREACHED */
6935 argc -= optind;
6936 argv += optind;
6938 #ifndef PROFILE
6939 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6940 "unveil", NULL) == -1)
6941 err(1, "pledge");
6942 #endif
6943 if (abort_rebase && continue_rebase)
6944 usage_rebase();
6945 else if (abort_rebase || continue_rebase) {
6946 if (argc != 0)
6947 usage_rebase();
6948 } else if (argc != 1)
6949 usage_rebase();
6951 cwd = getcwd(NULL, 0);
6952 if (cwd == NULL) {
6953 error = got_error_from_errno("getcwd");
6954 goto done;
6956 error = got_worktree_open(&worktree, cwd);
6957 if (error) {
6958 if (error->code == GOT_ERR_NOT_WORKTREE)
6959 error = wrap_not_worktree_error(error, "rebase", cwd);
6960 goto done;
6963 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6964 NULL);
6965 if (error != NULL)
6966 goto done;
6968 error = apply_unveil(got_repo_get_path(repo), 0,
6969 got_worktree_get_root_path(worktree));
6970 if (error)
6971 goto done;
6973 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6974 worktree);
6975 if (error)
6976 goto done;
6977 if (histedit_in_progress) {
6978 error = got_error(GOT_ERR_HISTEDIT_BUSY);
6979 goto done;
6982 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6983 if (error)
6984 goto done;
6986 if (abort_rebase) {
6987 struct got_update_progress_arg upa;
6988 if (!rebase_in_progress) {
6989 error = got_error(GOT_ERR_NOT_REBASING);
6990 goto done;
6992 error = got_worktree_rebase_continue(&resume_commit_id,
6993 &new_base_branch, &tmp_branch, &branch, &fileindex,
6994 worktree, repo);
6995 if (error)
6996 goto done;
6997 printf("Switching work tree to %s\n",
6998 got_ref_get_symref_target(new_base_branch));
6999 memset(&upa, 0, sizeof(upa));
7000 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7001 new_base_branch, update_progress, &upa);
7002 if (error)
7003 goto done;
7004 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7005 print_update_progress_stats(&upa);
7006 goto done; /* nothing else to do */
7009 if (continue_rebase) {
7010 if (!rebase_in_progress) {
7011 error = got_error(GOT_ERR_NOT_REBASING);
7012 goto done;
7014 error = got_worktree_rebase_continue(&resume_commit_id,
7015 &new_base_branch, &tmp_branch, &branch, &fileindex,
7016 worktree, repo);
7017 if (error)
7018 goto done;
7020 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7021 resume_commit_id, repo);
7022 if (error)
7023 goto done;
7025 yca_id = got_object_id_dup(resume_commit_id);
7026 if (yca_id == NULL) {
7027 error = got_error_from_errno("got_object_id_dup");
7028 goto done;
7030 } else {
7031 error = got_ref_open(&branch, repo, argv[0], 0);
7032 if (error != NULL)
7033 goto done;
7036 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7037 if (error)
7038 goto done;
7040 if (!continue_rebase) {
7041 struct got_object_id *base_commit_id;
7043 base_commit_id = got_worktree_get_base_commit_id(worktree);
7044 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7045 base_commit_id, branch_head_commit_id, repo,
7046 check_cancelled, NULL);
7047 if (error)
7048 goto done;
7049 if (yca_id == NULL) {
7050 error = got_error_msg(GOT_ERR_ANCESTRY,
7051 "specified branch shares no common ancestry "
7052 "with work tree's branch");
7053 goto done;
7056 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7057 if (error) {
7058 if (error->code != GOT_ERR_ANCESTRY)
7059 goto done;
7060 error = NULL;
7061 } else {
7062 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7063 "specified branch resolves to a commit which "
7064 "is already contained in work tree's branch");
7065 goto done;
7067 error = got_worktree_rebase_prepare(&new_base_branch,
7068 &tmp_branch, &fileindex, worktree, branch, repo);
7069 if (error)
7070 goto done;
7073 commit_id = branch_head_commit_id;
7074 error = got_object_open_as_commit(&commit, repo, commit_id);
7075 if (error)
7076 goto done;
7078 parent_ids = got_object_commit_get_parent_ids(commit);
7079 pid = SIMPLEQ_FIRST(parent_ids);
7080 if (pid == NULL) {
7081 if (!continue_rebase) {
7082 struct got_update_progress_arg upa;
7083 memset(&upa, 0, sizeof(upa));
7084 error = got_worktree_rebase_abort(worktree, fileindex,
7085 repo, new_base_branch, update_progress, &upa);
7086 if (error)
7087 goto done;
7088 printf("Rebase of %s aborted\n",
7089 got_ref_get_name(branch));
7090 print_update_progress_stats(&upa);
7093 error = got_error(GOT_ERR_EMPTY_REBASE);
7094 goto done;
7096 error = collect_commits(&commits, commit_id, pid->id,
7097 yca_id, got_worktree_get_path_prefix(worktree),
7098 GOT_ERR_REBASE_PATH, repo);
7099 got_object_commit_close(commit);
7100 commit = NULL;
7101 if (error)
7102 goto done;
7104 if (SIMPLEQ_EMPTY(&commits)) {
7105 if (continue_rebase) {
7106 error = rebase_complete(worktree, fileindex,
7107 branch, new_base_branch, tmp_branch, repo);
7108 goto done;
7109 } else {
7110 /* Fast-forward the reference of the branch. */
7111 struct got_object_id *new_head_commit_id;
7112 char *id_str;
7113 error = got_ref_resolve(&new_head_commit_id, repo,
7114 new_base_branch);
7115 if (error)
7116 goto done;
7117 error = got_object_id_str(&id_str, new_head_commit_id);
7118 printf("Forwarding %s to commit %s\n",
7119 got_ref_get_name(branch), id_str);
7120 free(id_str);
7121 error = got_ref_change_ref(branch,
7122 new_head_commit_id);
7123 if (error)
7124 goto done;
7128 pid = NULL;
7129 SIMPLEQ_FOREACH(qid, &commits, entry) {
7130 struct got_update_progress_arg upa;
7132 commit_id = qid->id;
7133 parent_id = pid ? pid->id : yca_id;
7134 pid = qid;
7136 memset(&upa, 0, sizeof(upa));
7137 error = got_worktree_rebase_merge_files(&merged_paths,
7138 worktree, fileindex, parent_id, commit_id, repo,
7139 update_progress, &upa, check_cancelled, NULL);
7140 if (error)
7141 goto done;
7143 print_update_progress_stats(&upa);
7144 if (upa.conflicts > 0)
7145 rebase_status = GOT_STATUS_CONFLICT;
7147 if (rebase_status == GOT_STATUS_CONFLICT) {
7148 error = show_rebase_merge_conflict(qid->id, repo);
7149 if (error)
7150 goto done;
7151 got_worktree_rebase_pathlist_free(&merged_paths);
7152 break;
7155 error = rebase_commit(&merged_paths, worktree, fileindex,
7156 tmp_branch, commit_id, repo);
7157 got_worktree_rebase_pathlist_free(&merged_paths);
7158 if (error)
7159 goto done;
7162 if (rebase_status == GOT_STATUS_CONFLICT) {
7163 error = got_worktree_rebase_postpone(worktree, fileindex);
7164 if (error)
7165 goto done;
7166 error = got_error_msg(GOT_ERR_CONFLICTS,
7167 "conflicts must be resolved before rebasing can continue");
7168 } else
7169 error = rebase_complete(worktree, fileindex, branch,
7170 new_base_branch, tmp_branch, repo);
7171 done:
7172 got_object_id_queue_free(&commits);
7173 free(branch_head_commit_id);
7174 free(resume_commit_id);
7175 free(yca_id);
7176 if (commit)
7177 got_object_commit_close(commit);
7178 if (branch)
7179 got_ref_close(branch);
7180 if (new_base_branch)
7181 got_ref_close(new_base_branch);
7182 if (tmp_branch)
7183 got_ref_close(tmp_branch);
7184 if (worktree)
7185 got_worktree_close(worktree);
7186 if (repo)
7187 got_repo_close(repo);
7188 return error;
7191 __dead static void
7192 usage_histedit(void)
7194 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
7195 getprogname());
7196 exit(1);
7199 #define GOT_HISTEDIT_PICK 'p'
7200 #define GOT_HISTEDIT_EDIT 'e'
7201 #define GOT_HISTEDIT_FOLD 'f'
7202 #define GOT_HISTEDIT_DROP 'd'
7203 #define GOT_HISTEDIT_MESG 'm'
7205 static struct got_histedit_cmd {
7206 unsigned char code;
7207 const char *name;
7208 const char *desc;
7209 } got_histedit_cmds[] = {
7210 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7211 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7212 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7213 "be used" },
7214 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7215 { GOT_HISTEDIT_MESG, "mesg",
7216 "single-line log message for commit above (open editor if empty)" },
7219 struct got_histedit_list_entry {
7220 TAILQ_ENTRY(got_histedit_list_entry) entry;
7221 struct got_object_id *commit_id;
7222 const struct got_histedit_cmd *cmd;
7223 char *logmsg;
7225 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7227 static const struct got_error *
7228 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7229 FILE *f, struct got_repository *repo)
7231 const struct got_error *err = NULL;
7232 char *logmsg = NULL, *id_str = NULL;
7233 struct got_commit_object *commit = NULL;
7234 int n;
7236 err = got_object_open_as_commit(&commit, repo, commit_id);
7237 if (err)
7238 goto done;
7240 err = get_short_logmsg(&logmsg, 34, commit);
7241 if (err)
7242 goto done;
7244 err = got_object_id_str(&id_str, commit_id);
7245 if (err)
7246 goto done;
7248 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7249 if (n < 0)
7250 err = got_ferror(f, GOT_ERR_IO);
7251 done:
7252 if (commit)
7253 got_object_commit_close(commit);
7254 free(id_str);
7255 free(logmsg);
7256 return err;
7259 static const struct got_error *
7260 histedit_write_commit_list(struct got_object_id_queue *commits,
7261 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7263 const struct got_error *err = NULL;
7264 struct got_object_qid *qid;
7266 if (SIMPLEQ_EMPTY(commits))
7267 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7269 SIMPLEQ_FOREACH(qid, commits, entry) {
7270 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7271 f, repo);
7272 if (err)
7273 break;
7274 if (edit_logmsg_only) {
7275 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7276 if (n < 0) {
7277 err = got_ferror(f, GOT_ERR_IO);
7278 break;
7283 return err;
7286 static const struct got_error *
7287 write_cmd_list(FILE *f, const char *branch_name,
7288 struct got_object_id_queue *commits)
7290 const struct got_error *err = NULL;
7291 int n, i;
7292 char *id_str;
7293 struct got_object_qid *qid;
7295 qid = SIMPLEQ_FIRST(commits);
7296 err = got_object_id_str(&id_str, qid->id);
7297 if (err)
7298 return err;
7300 n = fprintf(f,
7301 "# Editing the history of branch '%s' starting at\n"
7302 "# commit %s\n"
7303 "# Commits will be processed in order from top to "
7304 "bottom of this file.\n", branch_name, id_str);
7305 if (n < 0) {
7306 err = got_ferror(f, GOT_ERR_IO);
7307 goto done;
7310 n = fprintf(f, "# Available histedit commands:\n");
7311 if (n < 0) {
7312 err = got_ferror(f, GOT_ERR_IO);
7313 goto done;
7316 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7317 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7318 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7319 cmd->desc);
7320 if (n < 0) {
7321 err = got_ferror(f, GOT_ERR_IO);
7322 break;
7325 done:
7326 free(id_str);
7327 return err;
7330 static const struct got_error *
7331 histedit_syntax_error(int lineno)
7333 static char msg[42];
7334 int ret;
7336 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7337 lineno);
7338 if (ret == -1 || ret >= sizeof(msg))
7339 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7341 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7344 static const struct got_error *
7345 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7346 char *logmsg, struct got_repository *repo)
7348 const struct got_error *err;
7349 struct got_commit_object *folded_commit = NULL;
7350 char *id_str, *folded_logmsg = NULL;
7352 err = got_object_id_str(&id_str, hle->commit_id);
7353 if (err)
7354 return err;
7356 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7357 if (err)
7358 goto done;
7360 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7361 if (err)
7362 goto done;
7363 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7364 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7365 folded_logmsg) == -1) {
7366 err = got_error_from_errno("asprintf");
7368 done:
7369 if (folded_commit)
7370 got_object_commit_close(folded_commit);
7371 free(id_str);
7372 free(folded_logmsg);
7373 return err;
7376 static struct got_histedit_list_entry *
7377 get_folded_commits(struct got_histedit_list_entry *hle)
7379 struct got_histedit_list_entry *prev, *folded = NULL;
7381 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7382 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7383 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7384 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7385 folded = prev;
7386 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7389 return folded;
7392 static const struct got_error *
7393 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7394 struct got_repository *repo)
7396 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7397 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7398 const struct got_error *err = NULL;
7399 struct got_commit_object *commit = NULL;
7400 int fd;
7401 struct got_histedit_list_entry *folded = NULL;
7403 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7404 if (err)
7405 return err;
7407 folded = get_folded_commits(hle);
7408 if (folded) {
7409 while (folded != hle) {
7410 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7411 folded = TAILQ_NEXT(folded, entry);
7412 continue;
7414 err = append_folded_commit_msg(&new_msg, folded,
7415 logmsg, repo);
7416 if (err)
7417 goto done;
7418 free(logmsg);
7419 logmsg = new_msg;
7420 folded = TAILQ_NEXT(folded, entry);
7424 err = got_object_id_str(&id_str, hle->commit_id);
7425 if (err)
7426 goto done;
7427 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7428 if (err)
7429 goto done;
7430 if (asprintf(&new_msg,
7431 "%s\n# original log message of commit %s: %s",
7432 logmsg ? logmsg : "", id_str, orig_logmsg) == -1) {
7433 err = got_error_from_errno("asprintf");
7434 goto done;
7436 free(logmsg);
7437 logmsg = new_msg;
7439 err = got_object_id_str(&id_str, hle->commit_id);
7440 if (err)
7441 goto done;
7443 err = got_opentemp_named_fd(&logmsg_path, &fd,
7444 GOT_TMPDIR_STR "/got-logmsg");
7445 if (err)
7446 goto done;
7448 dprintf(fd, logmsg);
7449 close(fd);
7451 err = get_editor(&editor);
7452 if (err)
7453 goto done;
7455 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
7456 if (err) {
7457 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
7458 goto done;
7459 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
7461 done:
7462 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
7463 err = got_error_from_errno2("unlink", logmsg_path);
7464 free(logmsg_path);
7465 free(logmsg);
7466 free(orig_logmsg);
7467 free(editor);
7468 if (commit)
7469 got_object_commit_close(commit);
7470 return err;
7473 static const struct got_error *
7474 histedit_parse_list(struct got_histedit_list *histedit_cmds,
7475 FILE *f, struct got_repository *repo)
7477 const struct got_error *err = NULL;
7478 char *line = NULL, *p, *end;
7479 size_t size;
7480 ssize_t len;
7481 int lineno = 0, i;
7482 const struct got_histedit_cmd *cmd;
7483 struct got_object_id *commit_id = NULL;
7484 struct got_histedit_list_entry *hle = NULL;
7486 for (;;) {
7487 len = getline(&line, &size, f);
7488 if (len == -1) {
7489 const struct got_error *getline_err;
7490 if (feof(f))
7491 break;
7492 getline_err = got_error_from_errno("getline");
7493 err = got_ferror(f, getline_err->code);
7494 break;
7496 lineno++;
7497 p = line;
7498 while (isspace((unsigned char)p[0]))
7499 p++;
7500 if (p[0] == '#' || p[0] == '\0') {
7501 free(line);
7502 line = NULL;
7503 continue;
7505 cmd = NULL;
7506 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7507 cmd = &got_histedit_cmds[i];
7508 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
7509 isspace((unsigned char)p[strlen(cmd->name)])) {
7510 p += strlen(cmd->name);
7511 break;
7513 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
7514 p++;
7515 break;
7518 if (i == nitems(got_histedit_cmds)) {
7519 err = histedit_syntax_error(lineno);
7520 break;
7522 while (isspace((unsigned char)p[0]))
7523 p++;
7524 if (cmd->code == GOT_HISTEDIT_MESG) {
7525 if (hle == NULL || hle->logmsg != NULL) {
7526 err = got_error(GOT_ERR_HISTEDIT_CMD);
7527 break;
7529 if (p[0] == '\0') {
7530 err = histedit_edit_logmsg(hle, repo);
7531 if (err)
7532 break;
7533 } else {
7534 hle->logmsg = strdup(p);
7535 if (hle->logmsg == NULL) {
7536 err = got_error_from_errno("strdup");
7537 break;
7540 free(line);
7541 line = NULL;
7542 continue;
7543 } else {
7544 end = p;
7545 while (end[0] && !isspace((unsigned char)end[0]))
7546 end++;
7547 *end = '\0';
7549 err = got_object_resolve_id_str(&commit_id, repo, p);
7550 if (err) {
7551 /* override error code */
7552 err = histedit_syntax_error(lineno);
7553 break;
7556 hle = malloc(sizeof(*hle));
7557 if (hle == NULL) {
7558 err = got_error_from_errno("malloc");
7559 break;
7561 hle->cmd = cmd;
7562 hle->commit_id = commit_id;
7563 hle->logmsg = NULL;
7564 commit_id = NULL;
7565 free(line);
7566 line = NULL;
7567 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
7570 free(line);
7571 free(commit_id);
7572 return err;
7575 static const struct got_error *
7576 histedit_check_script(struct got_histedit_list *histedit_cmds,
7577 struct got_object_id_queue *commits, struct got_repository *repo)
7579 const struct got_error *err = NULL;
7580 struct got_object_qid *qid;
7581 struct got_histedit_list_entry *hle;
7582 static char msg[92];
7583 char *id_str;
7585 if (TAILQ_EMPTY(histedit_cmds))
7586 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
7587 "histedit script contains no commands");
7588 if (SIMPLEQ_EMPTY(commits))
7589 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7591 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7592 struct got_histedit_list_entry *hle2;
7593 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
7594 if (hle == hle2)
7595 continue;
7596 if (got_object_id_cmp(hle->commit_id,
7597 hle2->commit_id) != 0)
7598 continue;
7599 err = got_object_id_str(&id_str, hle->commit_id);
7600 if (err)
7601 return err;
7602 snprintf(msg, sizeof(msg), "commit %s is listed "
7603 "more than once in histedit script", id_str);
7604 free(id_str);
7605 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7609 SIMPLEQ_FOREACH(qid, commits, entry) {
7610 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7611 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
7612 break;
7614 if (hle == NULL) {
7615 err = got_object_id_str(&id_str, qid->id);
7616 if (err)
7617 return err;
7618 snprintf(msg, sizeof(msg),
7619 "commit %s missing from histedit script", id_str);
7620 free(id_str);
7621 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7625 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
7626 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
7627 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
7628 "last commit in histedit script cannot be folded");
7630 return NULL;
7633 static const struct got_error *
7634 histedit_run_editor(struct got_histedit_list *histedit_cmds,
7635 const char *path, struct got_object_id_queue *commits,
7636 struct got_repository *repo)
7638 const struct got_error *err = NULL;
7639 char *editor;
7640 FILE *f = NULL;
7642 err = get_editor(&editor);
7643 if (err)
7644 return err;
7646 if (spawn_editor(editor, path) == -1) {
7647 err = got_error_from_errno("failed spawning editor");
7648 goto done;
7651 f = fopen(path, "r");
7652 if (f == NULL) {
7653 err = got_error_from_errno("fopen");
7654 goto done;
7656 err = histedit_parse_list(histedit_cmds, f, repo);
7657 if (err)
7658 goto done;
7660 err = histedit_check_script(histedit_cmds, commits, repo);
7661 done:
7662 if (f && fclose(f) != 0 && err == NULL)
7663 err = got_error_from_errno("fclose");
7664 free(editor);
7665 return err;
7668 static const struct got_error *
7669 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
7670 struct got_object_id_queue *, const char *, const char *,
7671 struct got_repository *);
7673 static const struct got_error *
7674 histedit_edit_script(struct got_histedit_list *histedit_cmds,
7675 struct got_object_id_queue *commits, const char *branch_name,
7676 int edit_logmsg_only, struct got_repository *repo)
7678 const struct got_error *err;
7679 FILE *f = NULL;
7680 char *path = NULL;
7682 err = got_opentemp_named(&path, &f, "got-histedit");
7683 if (err)
7684 return err;
7686 err = write_cmd_list(f, branch_name, commits);
7687 if (err)
7688 goto done;
7690 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
7691 if (err)
7692 goto done;
7694 if (edit_logmsg_only) {
7695 rewind(f);
7696 err = histedit_parse_list(histedit_cmds, f, repo);
7697 } else {
7698 if (fclose(f) != 0) {
7699 err = got_error_from_errno("fclose");
7700 goto done;
7702 f = NULL;
7703 err = histedit_run_editor(histedit_cmds, path, commits, repo);
7704 if (err) {
7705 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7706 err->code != GOT_ERR_HISTEDIT_CMD)
7707 goto done;
7708 err = histedit_edit_list_retry(histedit_cmds, err,
7709 commits, path, branch_name, repo);
7712 done:
7713 if (f && fclose(f) != 0 && err == NULL)
7714 err = got_error_from_errno("fclose");
7715 if (path && unlink(path) != 0 && err == NULL)
7716 err = got_error_from_errno2("unlink", path);
7717 free(path);
7718 return err;
7721 static const struct got_error *
7722 histedit_save_list(struct got_histedit_list *histedit_cmds,
7723 struct got_worktree *worktree, struct got_repository *repo)
7725 const struct got_error *err = NULL;
7726 char *path = NULL;
7727 FILE *f = NULL;
7728 struct got_histedit_list_entry *hle;
7729 struct got_commit_object *commit = NULL;
7731 err = got_worktree_get_histedit_script_path(&path, worktree);
7732 if (err)
7733 return err;
7735 f = fopen(path, "w");
7736 if (f == NULL) {
7737 err = got_error_from_errno2("fopen", path);
7738 goto done;
7740 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7741 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
7742 repo);
7743 if (err)
7744 break;
7746 if (hle->logmsg) {
7747 int n = fprintf(f, "%c %s\n",
7748 GOT_HISTEDIT_MESG, hle->logmsg);
7749 if (n < 0) {
7750 err = got_ferror(f, GOT_ERR_IO);
7751 break;
7755 done:
7756 if (f && fclose(f) != 0 && err == NULL)
7757 err = got_error_from_errno("fclose");
7758 free(path);
7759 if (commit)
7760 got_object_commit_close(commit);
7761 return err;
7764 void
7765 histedit_free_list(struct got_histedit_list *histedit_cmds)
7767 struct got_histedit_list_entry *hle;
7769 while ((hle = TAILQ_FIRST(histedit_cmds))) {
7770 TAILQ_REMOVE(histedit_cmds, hle, entry);
7771 free(hle);
7775 static const struct got_error *
7776 histedit_load_list(struct got_histedit_list *histedit_cmds,
7777 const char *path, struct got_repository *repo)
7779 const struct got_error *err = NULL;
7780 FILE *f = NULL;
7782 f = fopen(path, "r");
7783 if (f == NULL) {
7784 err = got_error_from_errno2("fopen", path);
7785 goto done;
7788 err = histedit_parse_list(histedit_cmds, f, repo);
7789 done:
7790 if (f && fclose(f) != 0 && err == NULL)
7791 err = got_error_from_errno("fclose");
7792 return err;
7795 static const struct got_error *
7796 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
7797 const struct got_error *edit_err, struct got_object_id_queue *commits,
7798 const char *path, const char *branch_name, struct got_repository *repo)
7800 const struct got_error *err = NULL, *prev_err = edit_err;
7801 int resp = ' ';
7803 while (resp != 'c' && resp != 'r' && resp != 'a') {
7804 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
7805 "or (a)bort: ", getprogname(), prev_err->msg);
7806 resp = getchar();
7807 if (resp == '\n')
7808 resp = getchar();
7809 if (resp == 'c') {
7810 histedit_free_list(histedit_cmds);
7811 err = histedit_run_editor(histedit_cmds, path, commits,
7812 repo);
7813 if (err) {
7814 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7815 err->code != GOT_ERR_HISTEDIT_CMD)
7816 break;
7817 prev_err = err;
7818 resp = ' ';
7819 continue;
7821 break;
7822 } else if (resp == 'r') {
7823 histedit_free_list(histedit_cmds);
7824 err = histedit_edit_script(histedit_cmds,
7825 commits, branch_name, 0, repo);
7826 if (err) {
7827 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7828 err->code != GOT_ERR_HISTEDIT_CMD)
7829 break;
7830 prev_err = err;
7831 resp = ' ';
7832 continue;
7834 break;
7835 } else if (resp == 'a') {
7836 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
7837 break;
7838 } else
7839 printf("invalid response '%c'\n", resp);
7842 return err;
7845 static const struct got_error *
7846 histedit_complete(struct got_worktree *worktree,
7847 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
7848 struct got_reference *branch, struct got_repository *repo)
7850 printf("Switching work tree to %s\n",
7851 got_ref_get_symref_target(branch));
7852 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
7853 branch, repo);
7856 static const struct got_error *
7857 show_histedit_progress(struct got_commit_object *commit,
7858 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
7860 const struct got_error *err;
7861 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7863 err = got_object_id_str(&old_id_str, hle->commit_id);
7864 if (err)
7865 goto done;
7867 if (new_id) {
7868 err = got_object_id_str(&new_id_str, new_id);
7869 if (err)
7870 goto done;
7873 old_id_str[12] = '\0';
7874 if (new_id_str)
7875 new_id_str[12] = '\0';
7877 if (hle->logmsg) {
7878 logmsg = strdup(hle->logmsg);
7879 if (logmsg == NULL) {
7880 err = got_error_from_errno("strdup");
7881 goto done;
7883 trim_logmsg(logmsg, 42);
7884 } else {
7885 err = get_short_logmsg(&logmsg, 42, commit);
7886 if (err)
7887 goto done;
7890 switch (hle->cmd->code) {
7891 case GOT_HISTEDIT_PICK:
7892 case GOT_HISTEDIT_EDIT:
7893 printf("%s -> %s: %s\n", old_id_str,
7894 new_id_str ? new_id_str : "no-op change", logmsg);
7895 break;
7896 case GOT_HISTEDIT_DROP:
7897 case GOT_HISTEDIT_FOLD:
7898 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
7899 logmsg);
7900 break;
7901 default:
7902 break;
7904 done:
7905 free(old_id_str);
7906 free(new_id_str);
7907 return err;
7910 static const struct got_error *
7911 histedit_commit(struct got_pathlist_head *merged_paths,
7912 struct got_worktree *worktree, struct got_fileindex *fileindex,
7913 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
7914 struct got_repository *repo)
7916 const struct got_error *err;
7917 struct got_commit_object *commit;
7918 struct got_object_id *new_commit_id;
7920 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
7921 && hle->logmsg == NULL) {
7922 err = histedit_edit_logmsg(hle, repo);
7923 if (err)
7924 return err;
7927 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7928 if (err)
7929 return err;
7931 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
7932 worktree, fileindex, tmp_branch, commit, hle->commit_id,
7933 hle->logmsg, repo);
7934 if (err) {
7935 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
7936 goto done;
7937 err = show_histedit_progress(commit, hle, NULL);
7938 } else {
7939 err = show_histedit_progress(commit, hle, new_commit_id);
7940 free(new_commit_id);
7942 done:
7943 got_object_commit_close(commit);
7944 return err;
7947 static const struct got_error *
7948 histedit_skip_commit(struct got_histedit_list_entry *hle,
7949 struct got_worktree *worktree, struct got_repository *repo)
7951 const struct got_error *error;
7952 struct got_commit_object *commit;
7954 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
7955 repo);
7956 if (error)
7957 return error;
7959 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
7960 if (error)
7961 return error;
7963 error = show_histedit_progress(commit, hle, NULL);
7964 got_object_commit_close(commit);
7965 return error;
7968 static const struct got_error *
7969 check_local_changes(void *arg, unsigned char status,
7970 unsigned char staged_status, const char *path,
7971 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
7972 struct got_object_id *commit_id, int dirfd, const char *de_name)
7974 int *have_local_changes = arg;
7976 switch (status) {
7977 case GOT_STATUS_ADD:
7978 case GOT_STATUS_DELETE:
7979 case GOT_STATUS_MODIFY:
7980 case GOT_STATUS_CONFLICT:
7981 *have_local_changes = 1;
7982 return got_error(GOT_ERR_CANCELLED);
7983 default:
7984 break;
7987 switch (staged_status) {
7988 case GOT_STATUS_ADD:
7989 case GOT_STATUS_DELETE:
7990 case GOT_STATUS_MODIFY:
7991 *have_local_changes = 1;
7992 return got_error(GOT_ERR_CANCELLED);
7993 default:
7994 break;
7997 return NULL;
8000 static const struct got_error *
8001 cmd_histedit(int argc, char *argv[])
8003 const struct got_error *error = NULL;
8004 struct got_worktree *worktree = NULL;
8005 struct got_fileindex *fileindex = NULL;
8006 struct got_repository *repo = NULL;
8007 char *cwd = NULL;
8008 struct got_reference *branch = NULL;
8009 struct got_reference *tmp_branch = NULL;
8010 struct got_object_id *resume_commit_id = NULL;
8011 struct got_object_id *base_commit_id = NULL;
8012 struct got_object_id *head_commit_id = NULL;
8013 struct got_commit_object *commit = NULL;
8014 int ch, rebase_in_progress = 0;
8015 struct got_update_progress_arg upa;
8016 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8017 int edit_logmsg_only = 0;
8018 const char *edit_script_path = NULL;
8019 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8020 struct got_object_id_queue commits;
8021 struct got_pathlist_head merged_paths;
8022 const struct got_object_id_queue *parent_ids;
8023 struct got_object_qid *pid;
8024 struct got_histedit_list histedit_cmds;
8025 struct got_histedit_list_entry *hle;
8027 SIMPLEQ_INIT(&commits);
8028 TAILQ_INIT(&histedit_cmds);
8029 TAILQ_INIT(&merged_paths);
8030 memset(&upa, 0, sizeof(upa));
8032 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
8033 switch (ch) {
8034 case 'a':
8035 abort_edit = 1;
8036 break;
8037 case 'c':
8038 continue_edit = 1;
8039 break;
8040 case 'F':
8041 edit_script_path = optarg;
8042 break;
8043 case 'm':
8044 edit_logmsg_only = 1;
8045 break;
8046 default:
8047 usage_histedit();
8048 /* NOTREACHED */
8052 argc -= optind;
8053 argv += optind;
8055 #ifndef PROFILE
8056 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8057 "unveil", NULL) == -1)
8058 err(1, "pledge");
8059 #endif
8060 if (abort_edit && continue_edit)
8061 errx(1, "histedit's -a and -c options are mutually exclusive");
8062 if (edit_script_path && edit_logmsg_only)
8063 errx(1, "histedit's -F and -m options are mutually exclusive");
8064 if (abort_edit && edit_logmsg_only)
8065 errx(1, "histedit's -a and -m options are mutually exclusive");
8066 if (continue_edit && edit_logmsg_only)
8067 errx(1, "histedit's -c and -m options are mutually exclusive");
8068 if (argc != 0)
8069 usage_histedit();
8072 * This command cannot apply unveil(2) in all cases because the
8073 * user may choose to run an editor to edit the histedit script
8074 * and to edit individual commit log messages.
8075 * unveil(2) traverses exec(2); if an editor is used we have to
8076 * apply unveil after edit script and log messages have been written.
8077 * XXX TODO: Make use of unveil(2) where possible.
8080 cwd = getcwd(NULL, 0);
8081 if (cwd == NULL) {
8082 error = got_error_from_errno("getcwd");
8083 goto done;
8085 error = got_worktree_open(&worktree, cwd);
8086 if (error) {
8087 if (error->code == GOT_ERR_NOT_WORKTREE)
8088 error = wrap_not_worktree_error(error, "histedit", cwd);
8089 goto done;
8092 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8093 NULL);
8094 if (error != NULL)
8095 goto done;
8097 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8098 if (error)
8099 goto done;
8100 if (rebase_in_progress) {
8101 error = got_error(GOT_ERR_REBASING);
8102 goto done;
8105 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8106 if (error)
8107 goto done;
8109 if (edit_in_progress && edit_logmsg_only) {
8110 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8111 "histedit operation is in progress in this "
8112 "work tree and must be continued or aborted "
8113 "before the -m option can be used");
8114 goto done;
8117 if (edit_in_progress && abort_edit) {
8118 error = got_worktree_histedit_continue(&resume_commit_id,
8119 &tmp_branch, &branch, &base_commit_id, &fileindex,
8120 worktree, repo);
8121 if (error)
8122 goto done;
8123 printf("Switching work tree to %s\n",
8124 got_ref_get_symref_target(branch));
8125 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8126 branch, base_commit_id, update_progress, &upa);
8127 if (error)
8128 goto done;
8129 printf("Histedit of %s aborted\n",
8130 got_ref_get_symref_target(branch));
8131 print_update_progress_stats(&upa);
8132 goto done; /* nothing else to do */
8133 } else if (abort_edit) {
8134 error = got_error(GOT_ERR_NOT_HISTEDIT);
8135 goto done;
8138 if (continue_edit) {
8139 char *path;
8141 if (!edit_in_progress) {
8142 error = got_error(GOT_ERR_NOT_HISTEDIT);
8143 goto done;
8146 error = got_worktree_get_histedit_script_path(&path, worktree);
8147 if (error)
8148 goto done;
8150 error = histedit_load_list(&histedit_cmds, path, repo);
8151 free(path);
8152 if (error)
8153 goto done;
8155 error = got_worktree_histedit_continue(&resume_commit_id,
8156 &tmp_branch, &branch, &base_commit_id, &fileindex,
8157 worktree, repo);
8158 if (error)
8159 goto done;
8161 error = got_ref_resolve(&head_commit_id, repo, branch);
8162 if (error)
8163 goto done;
8165 error = got_object_open_as_commit(&commit, repo,
8166 head_commit_id);
8167 if (error)
8168 goto done;
8169 parent_ids = got_object_commit_get_parent_ids(commit);
8170 pid = SIMPLEQ_FIRST(parent_ids);
8171 if (pid == NULL) {
8172 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8173 goto done;
8175 error = collect_commits(&commits, head_commit_id, pid->id,
8176 base_commit_id, got_worktree_get_path_prefix(worktree),
8177 GOT_ERR_HISTEDIT_PATH, repo);
8178 got_object_commit_close(commit);
8179 commit = NULL;
8180 if (error)
8181 goto done;
8182 } else {
8183 if (edit_in_progress) {
8184 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8185 goto done;
8188 error = got_ref_open(&branch, repo,
8189 got_worktree_get_head_ref_name(worktree), 0);
8190 if (error != NULL)
8191 goto done;
8193 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8194 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8195 "will not edit commit history of a branch outside "
8196 "the \"refs/heads/\" reference namespace");
8197 goto done;
8200 error = got_ref_resolve(&head_commit_id, repo, branch);
8201 got_ref_close(branch);
8202 branch = NULL;
8203 if (error)
8204 goto done;
8206 error = got_object_open_as_commit(&commit, repo,
8207 head_commit_id);
8208 if (error)
8209 goto done;
8210 parent_ids = got_object_commit_get_parent_ids(commit);
8211 pid = SIMPLEQ_FIRST(parent_ids);
8212 if (pid == NULL) {
8213 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8214 goto done;
8216 error = collect_commits(&commits, head_commit_id, pid->id,
8217 got_worktree_get_base_commit_id(worktree),
8218 got_worktree_get_path_prefix(worktree),
8219 GOT_ERR_HISTEDIT_PATH, repo);
8220 got_object_commit_close(commit);
8221 commit = NULL;
8222 if (error)
8223 goto done;
8225 if (SIMPLEQ_EMPTY(&commits)) {
8226 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8227 goto done;
8230 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8231 &base_commit_id, &fileindex, worktree, repo);
8232 if (error)
8233 goto done;
8235 if (edit_script_path) {
8236 error = histedit_load_list(&histedit_cmds,
8237 edit_script_path, repo);
8238 if (error) {
8239 got_worktree_histedit_abort(worktree, fileindex,
8240 repo, branch, base_commit_id,
8241 update_progress, &upa);
8242 print_update_progress_stats(&upa);
8243 goto done;
8245 } else {
8246 const char *branch_name;
8247 branch_name = got_ref_get_symref_target(branch);
8248 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8249 branch_name += 11;
8250 error = histedit_edit_script(&histedit_cmds, &commits,
8251 branch_name, edit_logmsg_only, repo);
8252 if (error) {
8253 got_worktree_histedit_abort(worktree, fileindex,
8254 repo, branch, base_commit_id,
8255 update_progress, &upa);
8256 print_update_progress_stats(&upa);
8257 goto done;
8262 error = histedit_save_list(&histedit_cmds, worktree,
8263 repo);
8264 if (error) {
8265 got_worktree_histedit_abort(worktree, fileindex,
8266 repo, branch, base_commit_id,
8267 update_progress, &upa);
8268 print_update_progress_stats(&upa);
8269 goto done;
8274 error = histedit_check_script(&histedit_cmds, &commits, repo);
8275 if (error)
8276 goto done;
8278 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8279 if (resume_commit_id) {
8280 if (got_object_id_cmp(hle->commit_id,
8281 resume_commit_id) != 0)
8282 continue;
8284 resume_commit_id = NULL;
8285 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8286 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8287 error = histedit_skip_commit(hle, worktree,
8288 repo);
8289 if (error)
8290 goto done;
8291 } else {
8292 struct got_pathlist_head paths;
8293 int have_changes = 0;
8295 TAILQ_INIT(&paths);
8296 error = got_pathlist_append(&paths, "", NULL);
8297 if (error)
8298 goto done;
8299 error = got_worktree_status(worktree, &paths,
8300 repo, check_local_changes, &have_changes,
8301 check_cancelled, NULL);
8302 got_pathlist_free(&paths);
8303 if (error) {
8304 if (error->code != GOT_ERR_CANCELLED)
8305 goto done;
8306 if (sigint_received || sigpipe_received)
8307 goto done;
8309 if (have_changes) {
8310 error = histedit_commit(NULL, worktree,
8311 fileindex, tmp_branch, hle, repo);
8312 if (error)
8313 goto done;
8314 } else {
8315 error = got_object_open_as_commit(
8316 &commit, repo, hle->commit_id);
8317 if (error)
8318 goto done;
8319 error = show_histedit_progress(commit,
8320 hle, NULL);
8321 got_object_commit_close(commit);
8322 commit = NULL;
8323 if (error)
8324 goto done;
8327 continue;
8330 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8331 error = histedit_skip_commit(hle, worktree, repo);
8332 if (error)
8333 goto done;
8334 continue;
8337 error = got_object_open_as_commit(&commit, repo,
8338 hle->commit_id);
8339 if (error)
8340 goto done;
8341 parent_ids = got_object_commit_get_parent_ids(commit);
8342 pid = SIMPLEQ_FIRST(parent_ids);
8344 error = got_worktree_histedit_merge_files(&merged_paths,
8345 worktree, fileindex, pid->id, hle->commit_id, repo,
8346 update_progress, &upa, check_cancelled, NULL);
8347 if (error)
8348 goto done;
8349 got_object_commit_close(commit);
8350 commit = NULL;
8352 print_update_progress_stats(&upa);
8353 if (upa.conflicts > 0)
8354 rebase_status = GOT_STATUS_CONFLICT;
8356 if (rebase_status == GOT_STATUS_CONFLICT) {
8357 error = show_rebase_merge_conflict(hle->commit_id,
8358 repo);
8359 if (error)
8360 goto done;
8361 got_worktree_rebase_pathlist_free(&merged_paths);
8362 break;
8365 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8366 char *id_str;
8367 error = got_object_id_str(&id_str, hle->commit_id);
8368 if (error)
8369 goto done;
8370 printf("Stopping histedit for amending commit %s\n",
8371 id_str);
8372 free(id_str);
8373 got_worktree_rebase_pathlist_free(&merged_paths);
8374 error = got_worktree_histedit_postpone(worktree,
8375 fileindex);
8376 goto done;
8379 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8380 error = histedit_skip_commit(hle, worktree, repo);
8381 if (error)
8382 goto done;
8383 continue;
8386 error = histedit_commit(&merged_paths, worktree, fileindex,
8387 tmp_branch, hle, repo);
8388 got_worktree_rebase_pathlist_free(&merged_paths);
8389 if (error)
8390 goto done;
8393 if (rebase_status == GOT_STATUS_CONFLICT) {
8394 error = got_worktree_histedit_postpone(worktree, fileindex);
8395 if (error)
8396 goto done;
8397 error = got_error_msg(GOT_ERR_CONFLICTS,
8398 "conflicts must be resolved before histedit can continue");
8399 } else
8400 error = histedit_complete(worktree, fileindex, tmp_branch,
8401 branch, repo);
8402 done:
8403 got_object_id_queue_free(&commits);
8404 histedit_free_list(&histedit_cmds);
8405 free(head_commit_id);
8406 free(base_commit_id);
8407 free(resume_commit_id);
8408 if (commit)
8409 got_object_commit_close(commit);
8410 if (branch)
8411 got_ref_close(branch);
8412 if (tmp_branch)
8413 got_ref_close(tmp_branch);
8414 if (worktree)
8415 got_worktree_close(worktree);
8416 if (repo)
8417 got_repo_close(repo);
8418 return error;
8421 __dead static void
8422 usage_integrate(void)
8424 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
8425 exit(1);
8428 static const struct got_error *
8429 cmd_integrate(int argc, char *argv[])
8431 const struct got_error *error = NULL;
8432 struct got_repository *repo = NULL;
8433 struct got_worktree *worktree = NULL;
8434 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
8435 const char *branch_arg = NULL;
8436 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
8437 struct got_fileindex *fileindex = NULL;
8438 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
8439 int ch;
8440 struct got_update_progress_arg upa;
8442 while ((ch = getopt(argc, argv, "")) != -1) {
8443 switch (ch) {
8444 default:
8445 usage_integrate();
8446 /* NOTREACHED */
8450 argc -= optind;
8451 argv += optind;
8453 if (argc != 1)
8454 usage_integrate();
8455 branch_arg = argv[0];
8457 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8458 "unveil", NULL) == -1)
8459 err(1, "pledge");
8461 cwd = getcwd(NULL, 0);
8462 if (cwd == NULL) {
8463 error = got_error_from_errno("getcwd");
8464 goto done;
8467 error = got_worktree_open(&worktree, cwd);
8468 if (error) {
8469 if (error->code == GOT_ERR_NOT_WORKTREE)
8470 error = wrap_not_worktree_error(error, "integrate",
8471 cwd);
8472 goto done;
8475 error = check_rebase_or_histedit_in_progress(worktree);
8476 if (error)
8477 goto done;
8479 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8480 NULL);
8481 if (error != NULL)
8482 goto done;
8484 error = apply_unveil(got_repo_get_path(repo), 0,
8485 got_worktree_get_root_path(worktree));
8486 if (error)
8487 goto done;
8489 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
8490 error = got_error_from_errno("asprintf");
8491 goto done;
8494 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
8495 &base_branch_ref, worktree, refname, repo);
8496 if (error)
8497 goto done;
8499 refname = strdup(got_ref_get_name(branch_ref));
8500 if (refname == NULL) {
8501 error = got_error_from_errno("strdup");
8502 got_worktree_integrate_abort(worktree, fileindex, repo,
8503 branch_ref, base_branch_ref);
8504 goto done;
8506 base_refname = strdup(got_ref_get_name(base_branch_ref));
8507 if (base_refname == NULL) {
8508 error = got_error_from_errno("strdup");
8509 got_worktree_integrate_abort(worktree, fileindex, repo,
8510 branch_ref, base_branch_ref);
8511 goto done;
8514 error = got_ref_resolve(&commit_id, repo, branch_ref);
8515 if (error)
8516 goto done;
8518 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
8519 if (error)
8520 goto done;
8522 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
8523 error = got_error_msg(GOT_ERR_SAME_BRANCH,
8524 "specified branch has already been integrated");
8525 got_worktree_integrate_abort(worktree, fileindex, repo,
8526 branch_ref, base_branch_ref);
8527 goto done;
8530 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
8531 if (error) {
8532 if (error->code == GOT_ERR_ANCESTRY)
8533 error = got_error(GOT_ERR_REBASE_REQUIRED);
8534 got_worktree_integrate_abort(worktree, fileindex, repo,
8535 branch_ref, base_branch_ref);
8536 goto done;
8539 memset(&upa, 0, sizeof(upa));
8540 error = got_worktree_integrate_continue(worktree, fileindex, repo,
8541 branch_ref, base_branch_ref, update_progress, &upa,
8542 check_cancelled, NULL);
8543 if (error)
8544 goto done;
8546 printf("Integrated %s into %s\n", refname, base_refname);
8547 print_update_progress_stats(&upa);
8548 done:
8549 if (repo)
8550 got_repo_close(repo);
8551 if (worktree)
8552 got_worktree_close(worktree);
8553 free(cwd);
8554 free(base_commit_id);
8555 free(commit_id);
8556 free(refname);
8557 free(base_refname);
8558 return error;
8561 __dead static void
8562 usage_stage(void)
8564 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
8565 "[file-path ...]\n",
8566 getprogname());
8567 exit(1);
8570 static const struct got_error *
8571 print_stage(void *arg, unsigned char status, unsigned char staged_status,
8572 const char *path, struct got_object_id *blob_id,
8573 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
8574 int dirfd, const char *de_name)
8576 const struct got_error *err = NULL;
8577 char *id_str = NULL;
8579 if (staged_status != GOT_STATUS_ADD &&
8580 staged_status != GOT_STATUS_MODIFY &&
8581 staged_status != GOT_STATUS_DELETE)
8582 return NULL;
8584 if (staged_status == GOT_STATUS_ADD ||
8585 staged_status == GOT_STATUS_MODIFY)
8586 err = got_object_id_str(&id_str, staged_blob_id);
8587 else
8588 err = got_object_id_str(&id_str, blob_id);
8589 if (err)
8590 return err;
8592 printf("%s %c %s\n", id_str, staged_status, path);
8593 free(id_str);
8594 return NULL;
8597 static const struct got_error *
8598 cmd_stage(int argc, char *argv[])
8600 const struct got_error *error = NULL;
8601 struct got_repository *repo = NULL;
8602 struct got_worktree *worktree = NULL;
8603 char *cwd = NULL;
8604 struct got_pathlist_head paths;
8605 struct got_pathlist_entry *pe;
8606 int ch, list_stage = 0, pflag = 0;
8607 FILE *patch_script_file = NULL;
8608 const char *patch_script_path = NULL;
8609 struct choose_patch_arg cpa;
8611 TAILQ_INIT(&paths);
8613 while ((ch = getopt(argc, argv, "lpF:")) != -1) {
8614 switch (ch) {
8615 case 'l':
8616 list_stage = 1;
8617 break;
8618 case 'p':
8619 pflag = 1;
8620 break;
8621 case 'F':
8622 patch_script_path = optarg;
8623 break;
8624 default:
8625 usage_stage();
8626 /* NOTREACHED */
8630 argc -= optind;
8631 argv += optind;
8633 #ifndef PROFILE
8634 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8635 "unveil", NULL) == -1)
8636 err(1, "pledge");
8637 #endif
8638 if (list_stage && (pflag || patch_script_path))
8639 errx(1, "-l option cannot be used with other options");
8640 if (patch_script_path && !pflag)
8641 errx(1, "-F option can only be used together with -p option");
8643 cwd = getcwd(NULL, 0);
8644 if (cwd == NULL) {
8645 error = got_error_from_errno("getcwd");
8646 goto done;
8649 error = got_worktree_open(&worktree, cwd);
8650 if (error) {
8651 if (error->code == GOT_ERR_NOT_WORKTREE)
8652 error = wrap_not_worktree_error(error, "stage", cwd);
8653 goto done;
8656 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8657 NULL);
8658 if (error != NULL)
8659 goto done;
8661 if (patch_script_path) {
8662 patch_script_file = fopen(patch_script_path, "r");
8663 if (patch_script_file == NULL) {
8664 error = got_error_from_errno2("fopen",
8665 patch_script_path);
8666 goto done;
8669 error = apply_unveil(got_repo_get_path(repo), 0,
8670 got_worktree_get_root_path(worktree));
8671 if (error)
8672 goto done;
8674 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8675 if (error)
8676 goto done;
8678 if (list_stage)
8679 error = got_worktree_status(worktree, &paths, repo,
8680 print_stage, NULL, check_cancelled, NULL);
8681 else {
8682 cpa.patch_script_file = patch_script_file;
8683 cpa.action = "stage";
8684 error = got_worktree_stage(worktree, &paths,
8685 pflag ? NULL : print_status, NULL,
8686 pflag ? choose_patch : NULL, &cpa, repo);
8688 done:
8689 if (patch_script_file && fclose(patch_script_file) == EOF &&
8690 error == NULL)
8691 error = got_error_from_errno2("fclose", patch_script_path);
8692 if (repo)
8693 got_repo_close(repo);
8694 if (worktree)
8695 got_worktree_close(worktree);
8696 TAILQ_FOREACH(pe, &paths, entry)
8697 free((char *)pe->path);
8698 got_pathlist_free(&paths);
8699 free(cwd);
8700 return error;
8703 __dead static void
8704 usage_unstage(void)
8706 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
8707 "[file-path ...]\n",
8708 getprogname());
8709 exit(1);
8713 static const struct got_error *
8714 cmd_unstage(int argc, char *argv[])
8716 const struct got_error *error = NULL;
8717 struct got_repository *repo = NULL;
8718 struct got_worktree *worktree = NULL;
8719 char *cwd = NULL;
8720 struct got_pathlist_head paths;
8721 struct got_pathlist_entry *pe;
8722 int ch, pflag = 0;
8723 struct got_update_progress_arg upa;
8724 FILE *patch_script_file = NULL;
8725 const char *patch_script_path = NULL;
8726 struct choose_patch_arg cpa;
8728 TAILQ_INIT(&paths);
8730 while ((ch = getopt(argc, argv, "pF:")) != -1) {
8731 switch (ch) {
8732 case 'p':
8733 pflag = 1;
8734 break;
8735 case 'F':
8736 patch_script_path = optarg;
8737 break;
8738 default:
8739 usage_unstage();
8740 /* NOTREACHED */
8744 argc -= optind;
8745 argv += optind;
8747 #ifndef PROFILE
8748 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8749 "unveil", NULL) == -1)
8750 err(1, "pledge");
8751 #endif
8752 if (patch_script_path && !pflag)
8753 errx(1, "-F option can only be used together with -p option");
8755 cwd = getcwd(NULL, 0);
8756 if (cwd == NULL) {
8757 error = got_error_from_errno("getcwd");
8758 goto done;
8761 error = got_worktree_open(&worktree, cwd);
8762 if (error) {
8763 if (error->code == GOT_ERR_NOT_WORKTREE)
8764 error = wrap_not_worktree_error(error, "unstage", cwd);
8765 goto done;
8768 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8769 NULL);
8770 if (error != NULL)
8771 goto done;
8773 if (patch_script_path) {
8774 patch_script_file = fopen(patch_script_path, "r");
8775 if (patch_script_file == NULL) {
8776 error = got_error_from_errno2("fopen",
8777 patch_script_path);
8778 goto done;
8782 error = apply_unveil(got_repo_get_path(repo), 0,
8783 got_worktree_get_root_path(worktree));
8784 if (error)
8785 goto done;
8787 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8788 if (error)
8789 goto done;
8791 cpa.patch_script_file = patch_script_file;
8792 cpa.action = "unstage";
8793 memset(&upa, 0, sizeof(upa));
8794 error = got_worktree_unstage(worktree, &paths, update_progress,
8795 &upa, pflag ? choose_patch : NULL, &cpa, repo);
8796 if (!error)
8797 print_update_progress_stats(&upa);
8798 done:
8799 if (patch_script_file && fclose(patch_script_file) == EOF &&
8800 error == NULL)
8801 error = got_error_from_errno2("fclose", patch_script_path);
8802 if (repo)
8803 got_repo_close(repo);
8804 if (worktree)
8805 got_worktree_close(worktree);
8806 TAILQ_FOREACH(pe, &paths, entry)
8807 free((char *)pe->path);
8808 got_pathlist_free(&paths);
8809 free(cwd);
8810 return error;
8813 __dead static void
8814 usage_cat(void)
8816 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
8817 "arg1 [arg2 ...]\n", getprogname());
8818 exit(1);
8821 static const struct got_error *
8822 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8824 const struct got_error *err;
8825 struct got_blob_object *blob;
8827 err = got_object_open_as_blob(&blob, repo, id, 8192);
8828 if (err)
8829 return err;
8831 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
8832 got_object_blob_close(blob);
8833 return err;
8836 static const struct got_error *
8837 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8839 const struct got_error *err;
8840 struct got_tree_object *tree;
8841 int nentries, i;
8843 err = got_object_open_as_tree(&tree, repo, id);
8844 if (err)
8845 return err;
8847 nentries = got_object_tree_get_nentries(tree);
8848 for (i = 0; i < nentries; i++) {
8849 struct got_tree_entry *te;
8850 char *id_str;
8851 if (sigint_received || sigpipe_received)
8852 break;
8853 te = got_object_tree_get_entry(tree, i);
8854 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
8855 if (err)
8856 break;
8857 fprintf(outfile, "%s %.7o %s\n", id_str,
8858 got_tree_entry_get_mode(te),
8859 got_tree_entry_get_name(te));
8860 free(id_str);
8863 got_object_tree_close(tree);
8864 return err;
8867 static const struct got_error *
8868 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8870 const struct got_error *err;
8871 struct got_commit_object *commit;
8872 const struct got_object_id_queue *parent_ids;
8873 struct got_object_qid *pid;
8874 char *id_str = NULL;
8875 const char *logmsg = NULL;
8877 err = got_object_open_as_commit(&commit, repo, id);
8878 if (err)
8879 return err;
8881 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
8882 if (err)
8883 goto done;
8885 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
8886 parent_ids = got_object_commit_get_parent_ids(commit);
8887 fprintf(outfile, "numparents %d\n",
8888 got_object_commit_get_nparents(commit));
8889 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
8890 char *pid_str;
8891 err = got_object_id_str(&pid_str, pid->id);
8892 if (err)
8893 goto done;
8894 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
8895 free(pid_str);
8897 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
8898 got_object_commit_get_author(commit),
8899 got_object_commit_get_author_time(commit));
8901 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
8902 got_object_commit_get_author(commit),
8903 got_object_commit_get_committer_time(commit));
8905 logmsg = got_object_commit_get_logmsg_raw(commit);
8906 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
8907 fprintf(outfile, "%s", logmsg);
8908 done:
8909 free(id_str);
8910 got_object_commit_close(commit);
8911 return err;
8914 static const struct got_error *
8915 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8917 const struct got_error *err;
8918 struct got_tag_object *tag;
8919 char *id_str = NULL;
8920 const char *tagmsg = NULL;
8922 err = got_object_open_as_tag(&tag, repo, id);
8923 if (err)
8924 return err;
8926 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
8927 if (err)
8928 goto done;
8930 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
8932 switch (got_object_tag_get_object_type(tag)) {
8933 case GOT_OBJ_TYPE_BLOB:
8934 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8935 GOT_OBJ_LABEL_BLOB);
8936 break;
8937 case GOT_OBJ_TYPE_TREE:
8938 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8939 GOT_OBJ_LABEL_TREE);
8940 break;
8941 case GOT_OBJ_TYPE_COMMIT:
8942 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8943 GOT_OBJ_LABEL_COMMIT);
8944 break;
8945 case GOT_OBJ_TYPE_TAG:
8946 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8947 GOT_OBJ_LABEL_TAG);
8948 break;
8949 default:
8950 break;
8953 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
8954 got_object_tag_get_name(tag));
8956 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
8957 got_object_tag_get_tagger(tag),
8958 got_object_tag_get_tagger_time(tag));
8960 tagmsg = got_object_tag_get_message(tag);
8961 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
8962 fprintf(outfile, "%s", tagmsg);
8963 done:
8964 free(id_str);
8965 got_object_tag_close(tag);
8966 return err;
8969 static const struct got_error *
8970 cmd_cat(int argc, char *argv[])
8972 const struct got_error *error;
8973 struct got_repository *repo = NULL;
8974 struct got_worktree *worktree = NULL;
8975 char *cwd = NULL, *repo_path = NULL, *label = NULL;
8976 const char *commit_id_str = NULL;
8977 struct got_object_id *id = NULL, *commit_id = NULL;
8978 int ch, obj_type, i, force_path = 0;
8980 #ifndef PROFILE
8981 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8982 NULL) == -1)
8983 err(1, "pledge");
8984 #endif
8986 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
8987 switch (ch) {
8988 case 'c':
8989 commit_id_str = optarg;
8990 break;
8991 case 'r':
8992 repo_path = realpath(optarg, NULL);
8993 if (repo_path == NULL)
8994 return got_error_from_errno2("realpath",
8995 optarg);
8996 got_path_strip_trailing_slashes(repo_path);
8997 break;
8998 case 'P':
8999 force_path = 1;
9000 break;
9001 default:
9002 usage_cat();
9003 /* NOTREACHED */
9007 argc -= optind;
9008 argv += optind;
9010 cwd = getcwd(NULL, 0);
9011 if (cwd == NULL) {
9012 error = got_error_from_errno("getcwd");
9013 goto done;
9015 error = got_worktree_open(&worktree, cwd);
9016 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9017 goto done;
9018 if (worktree) {
9019 if (repo_path == NULL) {
9020 repo_path = strdup(
9021 got_worktree_get_repo_path(worktree));
9022 if (repo_path == NULL) {
9023 error = got_error_from_errno("strdup");
9024 goto done;
9029 if (repo_path == NULL) {
9030 repo_path = getcwd(NULL, 0);
9031 if (repo_path == NULL)
9032 return got_error_from_errno("getcwd");
9035 error = got_repo_open(&repo, repo_path, NULL);
9036 free(repo_path);
9037 if (error != NULL)
9038 goto done;
9040 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9041 if (error)
9042 goto done;
9044 if (commit_id_str == NULL)
9045 commit_id_str = GOT_REF_HEAD;
9046 error = got_repo_match_object_id(&commit_id, NULL,
9047 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
9048 if (error)
9049 goto done;
9051 for (i = 0; i < argc; i++) {
9052 if (force_path) {
9053 error = got_object_id_by_path(&id, repo, commit_id,
9054 argv[i]);
9055 if (error)
9056 break;
9057 } else {
9058 error = got_repo_match_object_id(&id, &label, argv[i],
9059 GOT_OBJ_TYPE_ANY, 0, repo);
9060 if (error) {
9061 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9062 error->code != GOT_ERR_NOT_REF)
9063 break;
9064 error = got_object_id_by_path(&id, repo,
9065 commit_id, argv[i]);
9066 if (error)
9067 break;
9071 error = got_object_get_type(&obj_type, repo, id);
9072 if (error)
9073 break;
9075 switch (obj_type) {
9076 case GOT_OBJ_TYPE_BLOB:
9077 error = cat_blob(id, repo, stdout);
9078 break;
9079 case GOT_OBJ_TYPE_TREE:
9080 error = cat_tree(id, repo, stdout);
9081 break;
9082 case GOT_OBJ_TYPE_COMMIT:
9083 error = cat_commit(id, repo, stdout);
9084 break;
9085 case GOT_OBJ_TYPE_TAG:
9086 error = cat_tag(id, repo, stdout);
9087 break;
9088 default:
9089 error = got_error(GOT_ERR_OBJ_TYPE);
9090 break;
9092 if (error)
9093 break;
9094 free(label);
9095 label = NULL;
9096 free(id);
9097 id = NULL;
9099 done:
9100 free(label);
9101 free(id);
9102 free(commit_id);
9103 if (worktree)
9104 got_worktree_close(worktree);
9105 if (repo) {
9106 const struct got_error *repo_error;
9107 repo_error = got_repo_close(repo);
9108 if (error == NULL)
9109 error = repo_error;
9111 return error;