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 if (repo_path == NULL) {
3393 error = got_worktree_open(&worktree, cwd);
3394 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3395 goto done;
3396 error = NULL;
3399 if (argc == 0) {
3400 path = strdup("");
3401 if (path == NULL) {
3402 error = got_error_from_errno("strdup");
3403 goto done;
3405 } else if (argc == 1) {
3406 if (worktree) {
3407 error = got_worktree_resolve_path(&path, worktree,
3408 argv[0]);
3409 if (error)
3410 goto done;
3411 } else {
3412 path = strdup(argv[0]);
3413 if (path == NULL) {
3414 error = got_error_from_errno("strdup");
3415 goto done;
3418 } else
3419 usage_log();
3421 if (repo_path == NULL) {
3422 repo_path = worktree ?
3423 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3425 if (repo_path == NULL) {
3426 error = got_error_from_errno("strdup");
3427 goto done;
3430 error = got_repo_open(&repo, repo_path, NULL);
3431 if (error != NULL)
3432 goto done;
3434 error = apply_unveil(got_repo_get_path(repo), 1,
3435 worktree ? got_worktree_get_root_path(worktree) : NULL);
3436 if (error)
3437 goto done;
3439 if (start_commit == NULL) {
3440 struct got_reference *head_ref;
3441 struct got_commit_object *commit = NULL;
3442 error = got_ref_open(&head_ref, repo,
3443 worktree ? got_worktree_get_head_ref_name(worktree)
3444 : GOT_REF_HEAD, 0);
3445 if (error != NULL)
3446 goto done;
3447 error = got_ref_resolve(&start_id, repo, head_ref);
3448 got_ref_close(head_ref);
3449 if (error != NULL)
3450 goto done;
3451 error = got_object_open_as_commit(&commit, repo,
3452 start_id);
3453 if (error != NULL)
3454 goto done;
3455 got_object_commit_close(commit);
3456 } else {
3457 error = resolve_commit_arg(&start_id, start_commit, repo);
3458 if (error != NULL)
3459 goto done;
3461 if (end_commit != NULL) {
3462 error = resolve_commit_arg(&end_id, end_commit, repo);
3463 if (error != NULL)
3464 goto done;
3467 if (worktree) {
3468 const char *prefix = got_worktree_get_path_prefix(worktree);
3469 char *p;
3470 if (asprintf(&p, "%s%s%s", prefix,
3471 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3472 error = got_error_from_errno("asprintf");
3473 goto done;
3475 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3476 free(p);
3477 } else
3478 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3479 if (error != NULL)
3480 goto done;
3481 if (in_repo_path) {
3482 free(path);
3483 path = in_repo_path;
3486 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3487 if (error)
3488 goto done;
3490 error = print_commits(start_id, end_id, repo, path, show_patch,
3491 search_pattern, diff_context, limit, log_branches,
3492 reverse_display_order, &refs);
3493 done:
3494 free(path);
3495 free(repo_path);
3496 free(cwd);
3497 if (worktree)
3498 got_worktree_close(worktree);
3499 if (repo) {
3500 const struct got_error *repo_error;
3501 repo_error = got_repo_close(repo);
3502 if (error == NULL)
3503 error = repo_error;
3505 got_ref_list_free(&refs);
3506 return error;
3509 __dead static void
3510 usage_diff(void)
3512 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3513 "[-w] [object1 object2 | path]\n", getprogname());
3514 exit(1);
3517 struct print_diff_arg {
3518 struct got_repository *repo;
3519 struct got_worktree *worktree;
3520 int diff_context;
3521 const char *id_str;
3522 int header_shown;
3523 int diff_staged;
3524 int ignore_whitespace;
3527 static const struct got_error *
3528 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3529 const char *path, struct got_object_id *blob_id,
3530 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3531 int dirfd, const char *de_name)
3533 struct print_diff_arg *a = arg;
3534 const struct got_error *err = NULL;
3535 struct got_blob_object *blob1 = NULL;
3536 int fd = -1;
3537 FILE *f2 = NULL;
3538 char *abspath = NULL, *label1 = NULL;
3539 struct stat sb;
3541 if (a->diff_staged) {
3542 if (staged_status != GOT_STATUS_MODIFY &&
3543 staged_status != GOT_STATUS_ADD &&
3544 staged_status != GOT_STATUS_DELETE)
3545 return NULL;
3546 } else {
3547 if (staged_status == GOT_STATUS_DELETE)
3548 return NULL;
3549 if (status == GOT_STATUS_NONEXISTENT)
3550 return got_error_set_errno(ENOENT, path);
3551 if (status != GOT_STATUS_MODIFY &&
3552 status != GOT_STATUS_ADD &&
3553 status != GOT_STATUS_DELETE &&
3554 status != GOT_STATUS_CONFLICT)
3555 return NULL;
3558 if (!a->header_shown) {
3559 printf("diff %s %s%s\n", a->id_str,
3560 got_worktree_get_root_path(a->worktree),
3561 a->diff_staged ? " (staged changes)" : "");
3562 a->header_shown = 1;
3565 if (a->diff_staged) {
3566 const char *label1 = NULL, *label2 = NULL;
3567 switch (staged_status) {
3568 case GOT_STATUS_MODIFY:
3569 label1 = path;
3570 label2 = path;
3571 break;
3572 case GOT_STATUS_ADD:
3573 label2 = path;
3574 break;
3575 case GOT_STATUS_DELETE:
3576 label1 = path;
3577 break;
3578 default:
3579 return got_error(GOT_ERR_FILE_STATUS);
3581 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
3582 label1, label2, a->diff_context, a->ignore_whitespace,
3583 a->repo, stdout);
3586 if (staged_status == GOT_STATUS_ADD ||
3587 staged_status == GOT_STATUS_MODIFY) {
3588 char *id_str;
3589 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
3590 8192);
3591 if (err)
3592 goto done;
3593 err = got_object_id_str(&id_str, staged_blob_id);
3594 if (err)
3595 goto done;
3596 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
3597 err = got_error_from_errno("asprintf");
3598 free(id_str);
3599 goto done;
3601 free(id_str);
3602 } else if (status != GOT_STATUS_ADD) {
3603 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
3604 if (err)
3605 goto done;
3608 if (status != GOT_STATUS_DELETE) {
3609 if (asprintf(&abspath, "%s/%s",
3610 got_worktree_get_root_path(a->worktree), path) == -1) {
3611 err = got_error_from_errno("asprintf");
3612 goto done;
3615 if (dirfd != -1) {
3616 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
3617 if (fd == -1) {
3618 err = got_error_from_errno2("openat", abspath);
3619 goto done;
3621 } else {
3622 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
3623 if (fd == -1) {
3624 err = got_error_from_errno2("open", abspath);
3625 goto done;
3628 if (fstat(fd, &sb) == -1) {
3629 err = got_error_from_errno2("fstat", abspath);
3630 goto done;
3632 f2 = fdopen(fd, "r");
3633 if (f2 == NULL) {
3634 err = got_error_from_errno2("fdopen", abspath);
3635 goto done;
3637 fd = -1;
3638 } else
3639 sb.st_size = 0;
3641 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
3642 a->diff_context, a->ignore_whitespace, stdout);
3643 done:
3644 if (blob1)
3645 got_object_blob_close(blob1);
3646 if (f2 && fclose(f2) == EOF && err == NULL)
3647 err = got_error_from_errno("fclose");
3648 if (fd != -1 && close(fd) == -1 && err == NULL)
3649 err = got_error_from_errno("close");
3650 free(abspath);
3651 return err;
3654 static const struct got_error *
3655 cmd_diff(int argc, char *argv[])
3657 const struct got_error *error;
3658 struct got_repository *repo = NULL;
3659 struct got_worktree *worktree = NULL;
3660 char *cwd = NULL, *repo_path = NULL;
3661 struct got_object_id *id1 = NULL, *id2 = NULL;
3662 const char *id_str1 = NULL, *id_str2 = NULL;
3663 char *label1 = NULL, *label2 = NULL;
3664 int type1, type2;
3665 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
3666 const char *errstr;
3667 char *path = NULL;
3669 #ifndef PROFILE
3670 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3671 NULL) == -1)
3672 err(1, "pledge");
3673 #endif
3675 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
3676 switch (ch) {
3677 case 'C':
3678 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3679 &errstr);
3680 if (errstr != NULL)
3681 err(1, "-C option %s", errstr);
3682 break;
3683 case 'r':
3684 repo_path = realpath(optarg, NULL);
3685 if (repo_path == NULL)
3686 return got_error_from_errno2("realpath",
3687 optarg);
3688 got_path_strip_trailing_slashes(repo_path);
3689 break;
3690 case 's':
3691 diff_staged = 1;
3692 break;
3693 case 'w':
3694 ignore_whitespace = 1;
3695 break;
3696 default:
3697 usage_diff();
3698 /* NOTREACHED */
3702 argc -= optind;
3703 argv += optind;
3705 cwd = getcwd(NULL, 0);
3706 if (cwd == NULL) {
3707 error = got_error_from_errno("getcwd");
3708 goto done;
3710 if (argc <= 1) {
3711 if (repo_path)
3712 errx(1,
3713 "-r option can't be used when diffing a work tree");
3714 error = got_worktree_open(&worktree, cwd);
3715 if (error) {
3716 if (error->code == GOT_ERR_NOT_WORKTREE)
3717 error = wrap_not_worktree_error(error, "diff",
3718 cwd);
3719 goto done;
3721 repo_path = strdup(got_worktree_get_repo_path(worktree));
3722 if (repo_path == NULL) {
3723 error = got_error_from_errno("strdup");
3724 goto done;
3726 if (argc == 1) {
3727 error = got_worktree_resolve_path(&path, worktree,
3728 argv[0]);
3729 if (error)
3730 goto done;
3731 } else {
3732 path = strdup("");
3733 if (path == NULL) {
3734 error = got_error_from_errno("strdup");
3735 goto done;
3738 } else if (argc == 2) {
3739 if (diff_staged)
3740 errx(1, "-s option can't be used when diffing "
3741 "objects in repository");
3742 id_str1 = argv[0];
3743 id_str2 = argv[1];
3744 if (repo_path == NULL) {
3745 error = got_worktree_open(&worktree, cwd);
3746 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3747 goto done;
3748 if (worktree) {
3749 repo_path = strdup(
3750 got_worktree_get_repo_path(worktree));
3751 if (repo_path == NULL) {
3752 error = got_error_from_errno("strdup");
3753 goto done;
3755 } else {
3756 repo_path = strdup(cwd);
3757 if (repo_path == NULL) {
3758 error = got_error_from_errno("strdup");
3759 goto done;
3763 } else
3764 usage_diff();
3766 error = got_repo_open(&repo, repo_path, NULL);
3767 free(repo_path);
3768 if (error != NULL)
3769 goto done;
3771 error = apply_unveil(got_repo_get_path(repo), 1,
3772 worktree ? got_worktree_get_root_path(worktree) : NULL);
3773 if (error)
3774 goto done;
3776 if (argc <= 1) {
3777 struct print_diff_arg arg;
3778 struct got_pathlist_head paths;
3779 char *id_str;
3781 TAILQ_INIT(&paths);
3783 error = got_object_id_str(&id_str,
3784 got_worktree_get_base_commit_id(worktree));
3785 if (error)
3786 goto done;
3787 arg.repo = repo;
3788 arg.worktree = worktree;
3789 arg.diff_context = diff_context;
3790 arg.id_str = id_str;
3791 arg.header_shown = 0;
3792 arg.diff_staged = diff_staged;
3793 arg.ignore_whitespace = ignore_whitespace;
3795 error = got_pathlist_append(&paths, path, NULL);
3796 if (error)
3797 goto done;
3799 error = got_worktree_status(worktree, &paths, repo, print_diff,
3800 &arg, check_cancelled, NULL);
3801 free(id_str);
3802 got_pathlist_free(&paths);
3803 goto done;
3806 error = got_repo_match_object_id(&id1, &label1, id_str1,
3807 GOT_OBJ_TYPE_ANY, 1, repo);
3808 if (error)
3809 goto done;
3811 error = got_repo_match_object_id(&id2, &label2, id_str2,
3812 GOT_OBJ_TYPE_ANY, 1, repo);
3813 if (error)
3814 goto done;
3816 error = got_object_get_type(&type1, repo, id1);
3817 if (error)
3818 goto done;
3820 error = got_object_get_type(&type2, repo, id2);
3821 if (error)
3822 goto done;
3824 if (type1 != type2) {
3825 error = got_error(GOT_ERR_OBJ_TYPE);
3826 goto done;
3829 switch (type1) {
3830 case GOT_OBJ_TYPE_BLOB:
3831 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
3832 diff_context, ignore_whitespace, repo, stdout);
3833 break;
3834 case GOT_OBJ_TYPE_TREE:
3835 error = got_diff_objects_as_trees(id1, id2, "", "",
3836 diff_context, ignore_whitespace, repo, stdout);
3837 break;
3838 case GOT_OBJ_TYPE_COMMIT:
3839 printf("diff %s %s\n", label1, label2);
3840 error = got_diff_objects_as_commits(id1, id2, diff_context,
3841 ignore_whitespace, repo, stdout);
3842 break;
3843 default:
3844 error = got_error(GOT_ERR_OBJ_TYPE);
3846 done:
3847 free(label1);
3848 free(label2);
3849 free(id1);
3850 free(id2);
3851 free(path);
3852 if (worktree)
3853 got_worktree_close(worktree);
3854 if (repo) {
3855 const struct got_error *repo_error;
3856 repo_error = got_repo_close(repo);
3857 if (error == NULL)
3858 error = repo_error;
3860 return error;
3863 __dead static void
3864 usage_blame(void)
3866 fprintf(stderr,
3867 "usage: %s blame [-c commit] [-r repository-path] path\n",
3868 getprogname());
3869 exit(1);
3872 struct blame_line {
3873 int annotated;
3874 char *id_str;
3875 char *committer;
3876 char datebuf[11]; /* YYYY-MM-DD + NUL */
3879 struct blame_cb_args {
3880 struct blame_line *lines;
3881 int nlines;
3882 int nlines_prec;
3883 int lineno_cur;
3884 off_t *line_offsets;
3885 FILE *f;
3886 struct got_repository *repo;
3889 static const struct got_error *
3890 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
3892 const struct got_error *err = NULL;
3893 struct blame_cb_args *a = arg;
3894 struct blame_line *bline;
3895 char *line = NULL;
3896 size_t linesize = 0;
3897 struct got_commit_object *commit = NULL;
3898 off_t offset;
3899 struct tm tm;
3900 time_t committer_time;
3902 if (nlines != a->nlines ||
3903 (lineno != -1 && lineno < 1) || lineno > a->nlines)
3904 return got_error(GOT_ERR_RANGE);
3906 if (sigint_received)
3907 return got_error(GOT_ERR_ITER_COMPLETED);
3909 if (lineno == -1)
3910 return NULL; /* no change in this commit */
3912 /* Annotate this line. */
3913 bline = &a->lines[lineno - 1];
3914 if (bline->annotated)
3915 return NULL;
3916 err = got_object_id_str(&bline->id_str, id);
3917 if (err)
3918 return err;
3920 err = got_object_open_as_commit(&commit, a->repo, id);
3921 if (err)
3922 goto done;
3924 bline->committer = strdup(got_object_commit_get_committer(commit));
3925 if (bline->committer == NULL) {
3926 err = got_error_from_errno("strdup");
3927 goto done;
3930 committer_time = got_object_commit_get_committer_time(commit);
3931 if (localtime_r(&committer_time, &tm) == NULL)
3932 return got_error_from_errno("localtime_r");
3933 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
3934 &tm) >= sizeof(bline->datebuf)) {
3935 err = got_error(GOT_ERR_NO_SPACE);
3936 goto done;
3938 bline->annotated = 1;
3940 /* Print lines annotated so far. */
3941 bline = &a->lines[a->lineno_cur - 1];
3942 if (!bline->annotated)
3943 goto done;
3945 offset = a->line_offsets[a->lineno_cur - 1];
3946 if (fseeko(a->f, offset, SEEK_SET) == -1) {
3947 err = got_error_from_errno("fseeko");
3948 goto done;
3951 while (bline->annotated) {
3952 char *smallerthan, *at, *nl, *committer;
3953 size_t len;
3955 if (getline(&line, &linesize, a->f) == -1) {
3956 if (ferror(a->f))
3957 err = got_error_from_errno("getline");
3958 break;
3961 committer = bline->committer;
3962 smallerthan = strchr(committer, '<');
3963 if (smallerthan && smallerthan[1] != '\0')
3964 committer = smallerthan + 1;
3965 at = strchr(committer, '@');
3966 if (at)
3967 *at = '\0';
3968 len = strlen(committer);
3969 if (len >= 9)
3970 committer[8] = '\0';
3972 nl = strchr(line, '\n');
3973 if (nl)
3974 *nl = '\0';
3975 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
3976 bline->id_str, bline->datebuf, committer, line);
3978 a->lineno_cur++;
3979 bline = &a->lines[a->lineno_cur - 1];
3981 done:
3982 if (commit)
3983 got_object_commit_close(commit);
3984 free(line);
3985 return err;
3988 static const struct got_error *
3989 cmd_blame(int argc, char *argv[])
3991 const struct got_error *error;
3992 struct got_repository *repo = NULL;
3993 struct got_worktree *worktree = NULL;
3994 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
3995 struct got_object_id *obj_id = NULL;
3996 struct got_object_id *commit_id = NULL;
3997 struct got_blob_object *blob = NULL;
3998 char *commit_id_str = NULL;
3999 struct blame_cb_args bca;
4000 int ch, obj_type, i;
4001 size_t filesize;
4003 memset(&bca, 0, sizeof(bca));
4005 #ifndef PROFILE
4006 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4007 NULL) == -1)
4008 err(1, "pledge");
4009 #endif
4011 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4012 switch (ch) {
4013 case 'c':
4014 commit_id_str = optarg;
4015 break;
4016 case 'r':
4017 repo_path = realpath(optarg, NULL);
4018 if (repo_path == NULL)
4019 return got_error_from_errno2("realpath",
4020 optarg);
4021 got_path_strip_trailing_slashes(repo_path);
4022 break;
4023 default:
4024 usage_blame();
4025 /* NOTREACHED */
4029 argc -= optind;
4030 argv += optind;
4032 if (argc == 1)
4033 path = argv[0];
4034 else
4035 usage_blame();
4037 cwd = getcwd(NULL, 0);
4038 if (cwd == NULL) {
4039 error = got_error_from_errno("getcwd");
4040 goto done;
4042 if (repo_path == NULL) {
4043 error = got_worktree_open(&worktree, cwd);
4044 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4045 goto done;
4046 else
4047 error = NULL;
4048 if (worktree) {
4049 repo_path =
4050 strdup(got_worktree_get_repo_path(worktree));
4051 if (repo_path == NULL) {
4052 error = got_error_from_errno("strdup");
4053 if (error)
4054 goto done;
4056 } else {
4057 repo_path = strdup(cwd);
4058 if (repo_path == NULL) {
4059 error = got_error_from_errno("strdup");
4060 goto done;
4065 error = got_repo_open(&repo, repo_path, NULL);
4066 if (error != NULL)
4067 goto done;
4069 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4070 if (error)
4071 goto done;
4073 if (worktree) {
4074 const char *prefix = got_worktree_get_path_prefix(worktree);
4075 char *p, *worktree_subdir = cwd +
4076 strlen(got_worktree_get_root_path(worktree));
4077 if (asprintf(&p, "%s%s%s%s%s",
4078 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
4079 worktree_subdir, worktree_subdir[0] ? "/" : "",
4080 path) == -1) {
4081 error = got_error_from_errno("asprintf");
4082 goto done;
4084 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4085 free(p);
4086 } else {
4087 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4089 if (error)
4090 goto done;
4092 if (commit_id_str == NULL) {
4093 struct got_reference *head_ref;
4094 error = got_ref_open(&head_ref, repo, worktree ?
4095 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4096 if (error != NULL)
4097 goto done;
4098 error = got_ref_resolve(&commit_id, repo, head_ref);
4099 got_ref_close(head_ref);
4100 if (error != NULL)
4101 goto done;
4102 } else {
4103 error = got_repo_match_object_id(&commit_id, NULL,
4104 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4105 if (error)
4106 goto done;
4109 error = got_object_id_by_path(&obj_id, repo, commit_id, in_repo_path);
4110 if (error)
4111 goto done;
4113 error = got_object_get_type(&obj_type, repo, obj_id);
4114 if (error)
4115 goto done;
4117 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4118 error = got_error(GOT_ERR_OBJ_TYPE);
4119 goto done;
4122 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4123 if (error)
4124 goto done;
4125 bca.f = got_opentemp();
4126 if (bca.f == NULL) {
4127 error = got_error_from_errno("got_opentemp");
4128 goto done;
4130 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4131 &bca.line_offsets, bca.f, blob);
4132 if (error || bca.nlines == 0)
4133 goto done;
4135 /* Don't include \n at EOF in the blame line count. */
4136 if (bca.line_offsets[bca.nlines - 1] == filesize)
4137 bca.nlines--;
4139 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4140 if (bca.lines == NULL) {
4141 error = got_error_from_errno("calloc");
4142 goto done;
4144 bca.lineno_cur = 1;
4145 bca.nlines_prec = 0;
4146 i = bca.nlines;
4147 while (i > 0) {
4148 i /= 10;
4149 bca.nlines_prec++;
4151 bca.repo = repo;
4153 error = got_blame(in_repo_path, commit_id, repo, blame_cb, &bca,
4154 check_cancelled, NULL);
4155 done:
4156 free(in_repo_path);
4157 free(repo_path);
4158 free(cwd);
4159 free(commit_id);
4160 free(obj_id);
4161 if (blob)
4162 got_object_blob_close(blob);
4163 if (worktree)
4164 got_worktree_close(worktree);
4165 if (repo) {
4166 const struct got_error *repo_error;
4167 repo_error = got_repo_close(repo);
4168 if (error == NULL)
4169 error = repo_error;
4171 if (bca.lines) {
4172 for (i = 0; i < bca.nlines; i++) {
4173 struct blame_line *bline = &bca.lines[i];
4174 free(bline->id_str);
4175 free(bline->committer);
4177 free(bca.lines);
4179 free(bca.line_offsets);
4180 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4181 error = got_error_from_errno("fclose");
4182 return error;
4185 __dead static void
4186 usage_tree(void)
4188 fprintf(stderr,
4189 "usage: %s tree [-c commit] [-r repository-path] [-iR] path\n",
4190 getprogname());
4191 exit(1);
4194 static void
4195 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4196 const char *root_path)
4198 int is_root_path = (strcmp(path, root_path) == 0);
4199 const char *modestr = "";
4200 mode_t mode = got_tree_entry_get_mode(te);
4202 path += strlen(root_path);
4203 while (path[0] == '/')
4204 path++;
4206 if (got_object_tree_entry_is_submodule(te))
4207 modestr = "$";
4208 else if (S_ISLNK(mode))
4209 modestr = "@";
4210 else if (S_ISDIR(mode))
4211 modestr = "/";
4212 else if (mode & S_IXUSR)
4213 modestr = "*";
4215 printf("%s%s%s%s%s\n", id ? id : "", path,
4216 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr);
4219 static const struct got_error *
4220 print_tree(const char *path, struct got_object_id *commit_id,
4221 int show_ids, int recurse, const char *root_path,
4222 struct got_repository *repo)
4224 const struct got_error *err = NULL;
4225 struct got_object_id *tree_id = NULL;
4226 struct got_tree_object *tree = NULL;
4227 int nentries, i;
4229 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4230 if (err)
4231 goto done;
4233 err = got_object_open_as_tree(&tree, repo, tree_id);
4234 if (err)
4235 goto done;
4236 nentries = got_object_tree_get_nentries(tree);
4237 for (i = 0; i < nentries; i++) {
4238 struct got_tree_entry *te;
4239 char *id = NULL;
4241 if (sigint_received || sigpipe_received)
4242 break;
4244 te = got_object_tree_get_entry(tree, i);
4245 if (show_ids) {
4246 char *id_str;
4247 err = got_object_id_str(&id_str,
4248 got_tree_entry_get_id(te));
4249 if (err)
4250 goto done;
4251 if (asprintf(&id, "%s ", id_str) == -1) {
4252 err = got_error_from_errno("asprintf");
4253 free(id_str);
4254 goto done;
4256 free(id_str);
4258 print_entry(te, id, path, root_path);
4259 free(id);
4261 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4262 char *child_path;
4263 if (asprintf(&child_path, "%s%s%s", path,
4264 path[0] == '/' && path[1] == '\0' ? "" : "/",
4265 got_tree_entry_get_name(te)) == -1) {
4266 err = got_error_from_errno("asprintf");
4267 goto done;
4269 err = print_tree(child_path, commit_id, show_ids, 1,
4270 root_path, repo);
4271 free(child_path);
4272 if (err)
4273 goto done;
4276 done:
4277 if (tree)
4278 got_object_tree_close(tree);
4279 free(tree_id);
4280 return err;
4283 static const struct got_error *
4284 cmd_tree(int argc, char *argv[])
4286 const struct got_error *error;
4287 struct got_repository *repo = NULL;
4288 struct got_worktree *worktree = NULL;
4289 const char *path, *refname = NULL;
4290 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4291 struct got_object_id *commit_id = NULL;
4292 char *commit_id_str = NULL;
4293 int show_ids = 0, recurse = 0;
4294 int ch;
4296 #ifndef PROFILE
4297 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4298 NULL) == -1)
4299 err(1, "pledge");
4300 #endif
4302 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4303 switch (ch) {
4304 case 'c':
4305 commit_id_str = optarg;
4306 break;
4307 case 'r':
4308 repo_path = realpath(optarg, NULL);
4309 if (repo_path == NULL)
4310 return got_error_from_errno2("realpath",
4311 optarg);
4312 got_path_strip_trailing_slashes(repo_path);
4313 break;
4314 case 'i':
4315 show_ids = 1;
4316 break;
4317 case 'R':
4318 recurse = 1;
4319 break;
4320 default:
4321 usage_tree();
4322 /* NOTREACHED */
4326 argc -= optind;
4327 argv += optind;
4329 if (argc == 1)
4330 path = argv[0];
4331 else if (argc > 1)
4332 usage_tree();
4333 else
4334 path = NULL;
4336 cwd = getcwd(NULL, 0);
4337 if (cwd == NULL) {
4338 error = got_error_from_errno("getcwd");
4339 goto done;
4341 if (repo_path == NULL) {
4342 error = got_worktree_open(&worktree, cwd);
4343 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4344 goto done;
4345 else
4346 error = NULL;
4347 if (worktree) {
4348 repo_path =
4349 strdup(got_worktree_get_repo_path(worktree));
4350 if (repo_path == NULL)
4351 error = got_error_from_errno("strdup");
4352 if (error)
4353 goto done;
4354 } else {
4355 repo_path = strdup(cwd);
4356 if (repo_path == NULL) {
4357 error = got_error_from_errno("strdup");
4358 goto done;
4363 error = got_repo_open(&repo, repo_path, NULL);
4364 if (error != NULL)
4365 goto done;
4367 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4368 if (error)
4369 goto done;
4371 if (path == NULL) {
4372 if (worktree) {
4373 char *p, *worktree_subdir = cwd +
4374 strlen(got_worktree_get_root_path(worktree));
4375 if (asprintf(&p, "%s/%s",
4376 got_worktree_get_path_prefix(worktree),
4377 worktree_subdir) == -1) {
4378 error = got_error_from_errno("asprintf");
4379 goto done;
4381 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4382 free(p);
4383 if (error)
4384 goto done;
4385 } else
4386 path = "/";
4388 if (in_repo_path == NULL) {
4389 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4390 if (error != NULL)
4391 goto done;
4394 if (commit_id_str == NULL) {
4395 struct got_reference *head_ref;
4396 if (worktree)
4397 refname = got_worktree_get_head_ref_name(worktree);
4398 else
4399 refname = GOT_REF_HEAD;
4400 error = got_ref_open(&head_ref, repo, refname, 0);
4401 if (error != NULL)
4402 goto done;
4403 error = got_ref_resolve(&commit_id, repo, head_ref);
4404 got_ref_close(head_ref);
4405 if (error != NULL)
4406 goto done;
4407 } else {
4408 error = got_repo_match_object_id(&commit_id, NULL,
4409 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4410 if (error)
4411 goto done;
4414 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4415 in_repo_path, repo);
4416 done:
4417 free(in_repo_path);
4418 free(repo_path);
4419 free(cwd);
4420 free(commit_id);
4421 if (worktree)
4422 got_worktree_close(worktree);
4423 if (repo) {
4424 const struct got_error *repo_error;
4425 repo_error = got_repo_close(repo);
4426 if (error == NULL)
4427 error = repo_error;
4429 return error;
4432 __dead static void
4433 usage_status(void)
4435 fprintf(stderr, "usage: %s status [path ...]\n", getprogname());
4436 exit(1);
4439 static const struct got_error *
4440 print_status(void *arg, unsigned char status, unsigned char staged_status,
4441 const char *path, struct got_object_id *blob_id,
4442 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4443 int dirfd, const char *de_name)
4445 if (status == staged_status && (status == GOT_STATUS_DELETE))
4446 status = GOT_STATUS_NO_CHANGE;
4447 printf("%c%c %s\n", status, staged_status, path);
4448 return NULL;
4451 static const struct got_error *
4452 cmd_status(int argc, char *argv[])
4454 const struct got_error *error = NULL;
4455 struct got_repository *repo = NULL;
4456 struct got_worktree *worktree = NULL;
4457 char *cwd = NULL;
4458 struct got_pathlist_head paths;
4459 struct got_pathlist_entry *pe;
4460 int ch;
4462 TAILQ_INIT(&paths);
4464 while ((ch = getopt(argc, argv, "")) != -1) {
4465 switch (ch) {
4466 default:
4467 usage_status();
4468 /* NOTREACHED */
4472 argc -= optind;
4473 argv += optind;
4475 #ifndef PROFILE
4476 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4477 NULL) == -1)
4478 err(1, "pledge");
4479 #endif
4480 cwd = getcwd(NULL, 0);
4481 if (cwd == NULL) {
4482 error = got_error_from_errno("getcwd");
4483 goto done;
4486 error = got_worktree_open(&worktree, cwd);
4487 if (error) {
4488 if (error->code == GOT_ERR_NOT_WORKTREE)
4489 error = wrap_not_worktree_error(error, "status", cwd);
4490 goto done;
4493 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4494 NULL);
4495 if (error != NULL)
4496 goto done;
4498 error = apply_unveil(got_repo_get_path(repo), 1,
4499 got_worktree_get_root_path(worktree));
4500 if (error)
4501 goto done;
4503 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
4504 if (error)
4505 goto done;
4507 error = got_worktree_status(worktree, &paths, repo, print_status, NULL,
4508 check_cancelled, NULL);
4509 done:
4510 TAILQ_FOREACH(pe, &paths, entry)
4511 free((char *)pe->path);
4512 got_pathlist_free(&paths);
4513 free(cwd);
4514 return error;
4517 __dead static void
4518 usage_ref(void)
4520 fprintf(stderr,
4521 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
4522 "[-d] [name]\n",
4523 getprogname());
4524 exit(1);
4527 static const struct got_error *
4528 list_refs(struct got_repository *repo, const char *refname)
4530 static const struct got_error *err = NULL;
4531 struct got_reflist_head refs;
4532 struct got_reflist_entry *re;
4534 SIMPLEQ_INIT(&refs);
4535 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
4536 if (err)
4537 return err;
4539 SIMPLEQ_FOREACH(re, &refs, entry) {
4540 char *refstr;
4541 refstr = got_ref_to_str(re->ref);
4542 if (refstr == NULL)
4543 return got_error_from_errno("got_ref_to_str");
4544 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
4545 free(refstr);
4548 got_ref_list_free(&refs);
4549 return NULL;
4552 static const struct got_error *
4553 delete_ref(struct got_repository *repo, const char *refname)
4555 const struct got_error *err = NULL;
4556 struct got_reference *ref;
4558 err = got_ref_open(&ref, repo, refname, 0);
4559 if (err)
4560 return err;
4562 err = got_ref_delete(ref, repo);
4563 got_ref_close(ref);
4564 return err;
4567 static const struct got_error *
4568 add_ref(struct got_repository *repo, const char *refname, const char *target)
4570 const struct got_error *err = NULL;
4571 struct got_object_id *id;
4572 struct got_reference *ref = NULL;
4575 * Don't let the user create a reference name with a leading '-'.
4576 * While technically a valid reference name, this case is usually
4577 * an unintended typo.
4579 if (refname[0] == '-')
4580 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4582 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
4583 repo);
4584 if (err) {
4585 struct got_reference *target_ref;
4587 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
4588 return err;
4589 err = got_ref_open(&target_ref, repo, target, 0);
4590 if (err)
4591 return err;
4592 err = got_ref_resolve(&id, repo, target_ref);
4593 got_ref_close(target_ref);
4594 if (err)
4595 return err;
4598 err = got_ref_alloc(&ref, refname, id);
4599 if (err)
4600 goto done;
4602 err = got_ref_write(ref, repo);
4603 done:
4604 if (ref)
4605 got_ref_close(ref);
4606 free(id);
4607 return err;
4610 static const struct got_error *
4611 add_symref(struct got_repository *repo, const char *refname, const char *target)
4613 const struct got_error *err = NULL;
4614 struct got_reference *ref = NULL;
4615 struct got_reference *target_ref = NULL;
4618 * Don't let the user create a reference name with a leading '-'.
4619 * While technically a valid reference name, this case is usually
4620 * an unintended typo.
4622 if (refname[0] == '-')
4623 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4625 err = got_ref_open(&target_ref, repo, target, 0);
4626 if (err)
4627 return err;
4629 err = got_ref_alloc_symref(&ref, refname, target_ref);
4630 if (err)
4631 goto done;
4633 err = got_ref_write(ref, repo);
4634 done:
4635 if (target_ref)
4636 got_ref_close(target_ref);
4637 if (ref)
4638 got_ref_close(ref);
4639 return err;
4642 static const struct got_error *
4643 cmd_ref(int argc, char *argv[])
4645 const struct got_error *error = NULL;
4646 struct got_repository *repo = NULL;
4647 struct got_worktree *worktree = NULL;
4648 char *cwd = NULL, *repo_path = NULL;
4649 int ch, do_list = 0, do_delete = 0;
4650 const char *obj_arg = NULL, *symref_target= NULL;
4651 char *refname = NULL;
4653 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
4654 switch (ch) {
4655 case 'c':
4656 obj_arg = optarg;
4657 break;
4658 case 'd':
4659 do_delete = 1;
4660 break;
4661 case 'r':
4662 repo_path = realpath(optarg, NULL);
4663 if (repo_path == NULL)
4664 return got_error_from_errno2("realpath",
4665 optarg);
4666 got_path_strip_trailing_slashes(repo_path);
4667 break;
4668 case 'l':
4669 do_list = 1;
4670 break;
4671 case 's':
4672 symref_target = optarg;
4673 break;
4674 default:
4675 usage_ref();
4676 /* NOTREACHED */
4680 if (obj_arg && do_list)
4681 errx(1, "-c and -l options are mutually exclusive");
4682 if (obj_arg && do_delete)
4683 errx(1, "-c and -d options are mutually exclusive");
4684 if (obj_arg && symref_target)
4685 errx(1, "-c and -s options are mutually exclusive");
4686 if (symref_target && do_delete)
4687 errx(1, "-s and -d options are mutually exclusive");
4688 if (symref_target && do_list)
4689 errx(1, "-s and -l options are mutually exclusive");
4690 if (do_delete && do_list)
4691 errx(1, "-d and -l options are mutually exclusive");
4693 argc -= optind;
4694 argv += optind;
4696 if (do_list) {
4697 if (argc != 0 && argc != 1)
4698 usage_ref();
4699 if (argc == 1) {
4700 refname = strdup(argv[0]);
4701 if (refname == NULL) {
4702 error = got_error_from_errno("strdup");
4703 goto done;
4706 } else {
4707 if (argc != 1)
4708 usage_ref();
4709 refname = strdup(argv[0]);
4710 if (refname == NULL) {
4711 error = got_error_from_errno("strdup");
4712 goto done;
4716 if (refname)
4717 got_path_strip_trailing_slashes(refname);
4719 #ifndef PROFILE
4720 if (do_list) {
4721 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4722 NULL) == -1)
4723 err(1, "pledge");
4724 } else {
4725 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4726 "sendfd unveil", NULL) == -1)
4727 err(1, "pledge");
4729 #endif
4730 cwd = getcwd(NULL, 0);
4731 if (cwd == NULL) {
4732 error = got_error_from_errno("getcwd");
4733 goto done;
4736 if (repo_path == NULL) {
4737 error = got_worktree_open(&worktree, cwd);
4738 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4739 goto done;
4740 else
4741 error = NULL;
4742 if (worktree) {
4743 repo_path =
4744 strdup(got_worktree_get_repo_path(worktree));
4745 if (repo_path == NULL)
4746 error = got_error_from_errno("strdup");
4747 if (error)
4748 goto done;
4749 } else {
4750 repo_path = strdup(cwd);
4751 if (repo_path == NULL) {
4752 error = got_error_from_errno("strdup");
4753 goto done;
4758 error = got_repo_open(&repo, repo_path, NULL);
4759 if (error != NULL)
4760 goto done;
4762 error = apply_unveil(got_repo_get_path(repo), do_list,
4763 worktree ? got_worktree_get_root_path(worktree) : NULL);
4764 if (error)
4765 goto done;
4767 if (do_list)
4768 error = list_refs(repo, refname);
4769 else if (do_delete)
4770 error = delete_ref(repo, refname);
4771 else if (symref_target)
4772 error = add_symref(repo, refname, symref_target);
4773 else {
4774 if (obj_arg == NULL)
4775 usage_ref();
4776 error = add_ref(repo, refname, obj_arg);
4778 done:
4779 free(refname);
4780 if (repo)
4781 got_repo_close(repo);
4782 if (worktree)
4783 got_worktree_close(worktree);
4784 free(cwd);
4785 free(repo_path);
4786 return error;
4789 __dead static void
4790 usage_branch(void)
4792 fprintf(stderr,
4793 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
4794 "[name]\n", getprogname());
4795 exit(1);
4798 static const struct got_error *
4799 list_branch(struct got_repository *repo, struct got_worktree *worktree,
4800 struct got_reference *ref)
4802 const struct got_error *err = NULL;
4803 const char *refname, *marker = " ";
4804 char *refstr;
4806 refname = got_ref_get_name(ref);
4807 if (worktree && strcmp(refname,
4808 got_worktree_get_head_ref_name(worktree)) == 0) {
4809 struct got_object_id *id = NULL;
4811 err = got_ref_resolve(&id, repo, ref);
4812 if (err)
4813 return err;
4814 if (got_object_id_cmp(id,
4815 got_worktree_get_base_commit_id(worktree)) == 0)
4816 marker = "* ";
4817 else
4818 marker = "~ ";
4819 free(id);
4822 if (strncmp(refname, "refs/heads/", 11) == 0)
4823 refname += 11;
4824 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4825 refname += 18;
4827 refstr = got_ref_to_str(ref);
4828 if (refstr == NULL)
4829 return got_error_from_errno("got_ref_to_str");
4831 printf("%s%s: %s\n", marker, refname, refstr);
4832 free(refstr);
4833 return NULL;
4836 static const struct got_error *
4837 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
4839 const char *refname;
4841 if (worktree == NULL)
4842 return got_error(GOT_ERR_NOT_WORKTREE);
4844 refname = got_worktree_get_head_ref_name(worktree);
4846 if (strncmp(refname, "refs/heads/", 11) == 0)
4847 refname += 11;
4848 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4849 refname += 18;
4851 printf("%s\n", refname);
4853 return NULL;
4856 static const struct got_error *
4857 list_branches(struct got_repository *repo, struct got_worktree *worktree)
4859 static const struct got_error *err = NULL;
4860 struct got_reflist_head refs;
4861 struct got_reflist_entry *re;
4862 struct got_reference *temp_ref = NULL;
4863 int rebase_in_progress, histedit_in_progress;
4865 SIMPLEQ_INIT(&refs);
4867 if (worktree) {
4868 err = got_worktree_rebase_in_progress(&rebase_in_progress,
4869 worktree);
4870 if (err)
4871 return err;
4873 err = got_worktree_histedit_in_progress(&histedit_in_progress,
4874 worktree);
4875 if (err)
4876 return err;
4878 if (rebase_in_progress || histedit_in_progress) {
4879 err = got_ref_open(&temp_ref, repo,
4880 got_worktree_get_head_ref_name(worktree), 0);
4881 if (err)
4882 return err;
4883 list_branch(repo, worktree, temp_ref);
4884 got_ref_close(temp_ref);
4888 err = got_ref_list(&refs, repo, "refs/heads",
4889 got_ref_cmp_by_name, NULL);
4890 if (err)
4891 return err;
4893 SIMPLEQ_FOREACH(re, &refs, entry)
4894 list_branch(repo, worktree, re->ref);
4896 got_ref_list_free(&refs);
4897 return NULL;
4900 static const struct got_error *
4901 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
4902 const char *branch_name)
4904 const struct got_error *err = NULL;
4905 struct got_reference *ref = NULL;
4906 char *refname;
4908 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
4909 return got_error_from_errno("asprintf");
4911 err = got_ref_open(&ref, repo, refname, 0);
4912 if (err)
4913 goto done;
4915 if (worktree &&
4916 strcmp(got_worktree_get_head_ref_name(worktree),
4917 got_ref_get_name(ref)) == 0) {
4918 err = got_error_msg(GOT_ERR_SAME_BRANCH,
4919 "will not delete this work tree's current branch");
4920 goto done;
4923 err = got_ref_delete(ref, repo);
4924 done:
4925 if (ref)
4926 got_ref_close(ref);
4927 free(refname);
4928 return err;
4931 static const struct got_error *
4932 add_branch(struct got_repository *repo, const char *branch_name,
4933 struct got_object_id *base_commit_id)
4935 const struct got_error *err = NULL;
4936 struct got_reference *ref = NULL;
4937 char *base_refname = NULL, *refname = NULL;
4940 * Don't let the user create a branch name with a leading '-'.
4941 * While technically a valid reference name, this case is usually
4942 * an unintended typo.
4944 if (branch_name[0] == '-')
4945 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
4947 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
4948 err = got_error_from_errno("asprintf");
4949 goto done;
4952 err = got_ref_open(&ref, repo, refname, 0);
4953 if (err == NULL) {
4954 err = got_error(GOT_ERR_BRANCH_EXISTS);
4955 goto done;
4956 } else if (err->code != GOT_ERR_NOT_REF)
4957 goto done;
4959 err = got_ref_alloc(&ref, refname, base_commit_id);
4960 if (err)
4961 goto done;
4963 err = got_ref_write(ref, repo);
4964 done:
4965 if (ref)
4966 got_ref_close(ref);
4967 free(base_refname);
4968 free(refname);
4969 return err;
4972 static const struct got_error *
4973 cmd_branch(int argc, char *argv[])
4975 const struct got_error *error = NULL;
4976 struct got_repository *repo = NULL;
4977 struct got_worktree *worktree = NULL;
4978 char *cwd = NULL, *repo_path = NULL;
4979 int ch, do_list = 0, do_show = 0, do_update = 1;
4980 const char *delref = NULL, *commit_id_arg = NULL;
4981 struct got_reference *ref = NULL;
4982 struct got_pathlist_head paths;
4983 struct got_pathlist_entry *pe;
4984 struct got_object_id *commit_id = NULL;
4985 char *commit_id_str = NULL;
4987 TAILQ_INIT(&paths);
4989 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
4990 switch (ch) {
4991 case 'c':
4992 commit_id_arg = optarg;
4993 break;
4994 case 'd':
4995 delref = optarg;
4996 break;
4997 case 'r':
4998 repo_path = realpath(optarg, NULL);
4999 if (repo_path == NULL)
5000 return got_error_from_errno2("realpath",
5001 optarg);
5002 got_path_strip_trailing_slashes(repo_path);
5003 break;
5004 case 'l':
5005 do_list = 1;
5006 break;
5007 case 'n':
5008 do_update = 0;
5009 break;
5010 default:
5011 usage_branch();
5012 /* NOTREACHED */
5016 if (do_list && delref)
5017 errx(1, "-l and -d options are mutually exclusive");
5019 argc -= optind;
5020 argv += optind;
5022 if (!do_list && !delref && argc == 0)
5023 do_show = 1;
5025 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5026 errx(1, "-c option can only be used when creating a branch");
5028 if (do_list || delref) {
5029 if (argc > 0)
5030 usage_branch();
5031 } else if (!do_show && argc != 1)
5032 usage_branch();
5034 #ifndef PROFILE
5035 if (do_list || do_show) {
5036 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5037 NULL) == -1)
5038 err(1, "pledge");
5039 } else {
5040 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5041 "sendfd unveil", NULL) == -1)
5042 err(1, "pledge");
5044 #endif
5045 cwd = getcwd(NULL, 0);
5046 if (cwd == NULL) {
5047 error = got_error_from_errno("getcwd");
5048 goto done;
5051 if (repo_path == NULL) {
5052 error = got_worktree_open(&worktree, cwd);
5053 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5054 goto done;
5055 else
5056 error = NULL;
5057 if (worktree) {
5058 repo_path =
5059 strdup(got_worktree_get_repo_path(worktree));
5060 if (repo_path == NULL)
5061 error = got_error_from_errno("strdup");
5062 if (error)
5063 goto done;
5064 } else {
5065 repo_path = strdup(cwd);
5066 if (repo_path == NULL) {
5067 error = got_error_from_errno("strdup");
5068 goto done;
5073 error = got_repo_open(&repo, repo_path, NULL);
5074 if (error != NULL)
5075 goto done;
5077 error = apply_unveil(got_repo_get_path(repo), do_list,
5078 worktree ? got_worktree_get_root_path(worktree) : NULL);
5079 if (error)
5080 goto done;
5082 if (do_show)
5083 error = show_current_branch(repo, worktree);
5084 else if (do_list)
5085 error = list_branches(repo, worktree);
5086 else if (delref)
5087 error = delete_branch(repo, worktree, delref);
5088 else {
5089 if (commit_id_arg == NULL)
5090 commit_id_arg = worktree ?
5091 got_worktree_get_head_ref_name(worktree) :
5092 GOT_REF_HEAD;
5093 error = got_repo_match_object_id(&commit_id, NULL,
5094 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5095 if (error)
5096 goto done;
5097 error = add_branch(repo, argv[0], commit_id);
5098 if (error)
5099 goto done;
5100 if (worktree && do_update) {
5101 struct got_update_progress_arg upa;
5102 char *branch_refname = NULL;
5104 error = got_object_id_str(&commit_id_str, commit_id);
5105 if (error)
5106 goto done;
5107 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5108 worktree);
5109 if (error)
5110 goto done;
5111 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5112 == -1) {
5113 error = got_error_from_errno("asprintf");
5114 goto done;
5116 error = got_ref_open(&ref, repo, branch_refname, 0);
5117 free(branch_refname);
5118 if (error)
5119 goto done;
5120 error = switch_head_ref(ref, commit_id, worktree,
5121 repo);
5122 if (error)
5123 goto done;
5124 error = got_worktree_set_base_commit_id(worktree, repo,
5125 commit_id);
5126 if (error)
5127 goto done;
5128 memset(&upa, 0, sizeof(upa));
5129 error = got_worktree_checkout_files(worktree, &paths,
5130 repo, update_progress, &upa, check_cancelled,
5131 NULL);
5132 if (error)
5133 goto done;
5134 if (upa.did_something)
5135 printf("Updated to commit %s\n", commit_id_str);
5136 print_update_progress_stats(&upa);
5139 done:
5140 if (ref)
5141 got_ref_close(ref);
5142 if (repo)
5143 got_repo_close(repo);
5144 if (worktree)
5145 got_worktree_close(worktree);
5146 free(cwd);
5147 free(repo_path);
5148 free(commit_id);
5149 free(commit_id_str);
5150 TAILQ_FOREACH(pe, &paths, entry)
5151 free((char *)pe->path);
5152 got_pathlist_free(&paths);
5153 return error;
5157 __dead static void
5158 usage_tag(void)
5160 fprintf(stderr,
5161 "usage: %s tag [-c commit] [-r repository] [-l] "
5162 "[-m message] name\n", getprogname());
5163 exit(1);
5166 #if 0
5167 static const struct got_error *
5168 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5170 const struct got_error *err = NULL;
5171 struct got_reflist_entry *re, *se, *new;
5172 struct got_object_id *re_id, *se_id;
5173 struct got_tag_object *re_tag, *se_tag;
5174 time_t re_time, se_time;
5176 SIMPLEQ_FOREACH(re, tags, entry) {
5177 se = SIMPLEQ_FIRST(sorted);
5178 if (se == NULL) {
5179 err = got_reflist_entry_dup(&new, re);
5180 if (err)
5181 return err;
5182 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5183 continue;
5184 } else {
5185 err = got_ref_resolve(&re_id, repo, re->ref);
5186 if (err)
5187 break;
5188 err = got_object_open_as_tag(&re_tag, repo, re_id);
5189 free(re_id);
5190 if (err)
5191 break;
5192 re_time = got_object_tag_get_tagger_time(re_tag);
5193 got_object_tag_close(re_tag);
5196 while (se) {
5197 err = got_ref_resolve(&se_id, repo, re->ref);
5198 if (err)
5199 break;
5200 err = got_object_open_as_tag(&se_tag, repo, se_id);
5201 free(se_id);
5202 if (err)
5203 break;
5204 se_time = got_object_tag_get_tagger_time(se_tag);
5205 got_object_tag_close(se_tag);
5207 if (se_time > re_time) {
5208 err = got_reflist_entry_dup(&new, re);
5209 if (err)
5210 return err;
5211 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5212 break;
5214 se = SIMPLEQ_NEXT(se, entry);
5215 continue;
5218 done:
5219 return err;
5221 #endif
5223 static const struct got_error *
5224 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5226 static const struct got_error *err = NULL;
5227 struct got_reflist_head refs;
5228 struct got_reflist_entry *re;
5230 SIMPLEQ_INIT(&refs);
5232 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5233 if (err)
5234 return err;
5236 SIMPLEQ_FOREACH(re, &refs, entry) {
5237 const char *refname;
5238 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5239 char datebuf[26];
5240 const char *tagger;
5241 time_t tagger_time;
5242 struct got_object_id *id;
5243 struct got_tag_object *tag;
5244 struct got_commit_object *commit = NULL;
5246 refname = got_ref_get_name(re->ref);
5247 if (strncmp(refname, "refs/tags/", 10) != 0)
5248 continue;
5249 refname += 10;
5250 refstr = got_ref_to_str(re->ref);
5251 if (refstr == NULL) {
5252 err = got_error_from_errno("got_ref_to_str");
5253 break;
5255 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5256 free(refstr);
5258 err = got_ref_resolve(&id, repo, re->ref);
5259 if (err)
5260 break;
5261 err = got_object_open_as_tag(&tag, repo, id);
5262 if (err) {
5263 if (err->code != GOT_ERR_OBJ_TYPE) {
5264 free(id);
5265 break;
5267 /* "lightweight" tag */
5268 err = got_object_open_as_commit(&commit, repo, id);
5269 if (err) {
5270 free(id);
5271 break;
5273 tagger = got_object_commit_get_committer(commit);
5274 tagger_time =
5275 got_object_commit_get_committer_time(commit);
5276 err = got_object_id_str(&id_str, id);
5277 free(id);
5278 if (err)
5279 break;
5280 } else {
5281 free(id);
5282 tagger = got_object_tag_get_tagger(tag);
5283 tagger_time = got_object_tag_get_tagger_time(tag);
5284 err = got_object_id_str(&id_str,
5285 got_object_tag_get_object_id(tag));
5286 if (err)
5287 break;
5289 printf("from: %s\n", tagger);
5290 datestr = get_datestr(&tagger_time, datebuf);
5291 if (datestr)
5292 printf("date: %s UTC\n", datestr);
5293 if (commit)
5294 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5295 else {
5296 switch (got_object_tag_get_object_type(tag)) {
5297 case GOT_OBJ_TYPE_BLOB:
5298 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5299 id_str);
5300 break;
5301 case GOT_OBJ_TYPE_TREE:
5302 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5303 id_str);
5304 break;
5305 case GOT_OBJ_TYPE_COMMIT:
5306 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5307 id_str);
5308 break;
5309 case GOT_OBJ_TYPE_TAG:
5310 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5311 id_str);
5312 break;
5313 default:
5314 break;
5317 free(id_str);
5318 if (commit) {
5319 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5320 if (err)
5321 break;
5322 got_object_commit_close(commit);
5323 } else {
5324 tagmsg0 = strdup(got_object_tag_get_message(tag));
5325 got_object_tag_close(tag);
5326 if (tagmsg0 == NULL) {
5327 err = got_error_from_errno("strdup");
5328 break;
5332 tagmsg = tagmsg0;
5333 do {
5334 line = strsep(&tagmsg, "\n");
5335 if (line)
5336 printf(" %s\n", line);
5337 } while (line);
5338 free(tagmsg0);
5341 got_ref_list_free(&refs);
5342 return NULL;
5345 static const struct got_error *
5346 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5347 const char *tag_name, const char *repo_path)
5349 const struct got_error *err = NULL;
5350 char *template = NULL, *initial_content = NULL;
5351 char *editor = NULL;
5352 int fd = -1;
5354 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5355 err = got_error_from_errno("asprintf");
5356 goto done;
5359 if (asprintf(&initial_content, "\n# tagging commit %s as %s\n",
5360 commit_id_str, tag_name) == -1) {
5361 err = got_error_from_errno("asprintf");
5362 goto done;
5365 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5366 if (err)
5367 goto done;
5369 dprintf(fd, initial_content);
5370 close(fd);
5372 err = get_editor(&editor);
5373 if (err)
5374 goto done;
5375 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
5376 done:
5377 free(initial_content);
5378 free(template);
5379 free(editor);
5381 /* Editor is done; we can now apply unveil(2) */
5382 if (err == NULL) {
5383 err = apply_unveil(repo_path, 0, NULL);
5384 if (err) {
5385 free(*tagmsg);
5386 *tagmsg = NULL;
5389 return err;
5392 static const struct got_error *
5393 add_tag(struct got_repository *repo, const char *tag_name,
5394 const char *commit_arg, const char *tagmsg_arg)
5396 const struct got_error *err = NULL;
5397 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5398 char *label = NULL, *commit_id_str = NULL;
5399 struct got_reference *ref = NULL;
5400 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5401 char *tagmsg_path = NULL, *tag_id_str = NULL;
5402 int preserve_tagmsg = 0;
5405 * Don't let the user create a tag name with a leading '-'.
5406 * While technically a valid reference name, this case is usually
5407 * an unintended typo.
5409 if (tag_name[0] == '-')
5410 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5412 err = get_author(&tagger, repo);
5413 if (err)
5414 return err;
5416 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5417 GOT_OBJ_TYPE_COMMIT, 1, repo);
5418 if (err)
5419 goto done;
5421 err = got_object_id_str(&commit_id_str, commit_id);
5422 if (err)
5423 goto done;
5425 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5426 refname = strdup(tag_name);
5427 if (refname == NULL) {
5428 err = got_error_from_errno("strdup");
5429 goto done;
5431 tag_name += 10;
5432 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5433 err = got_error_from_errno("asprintf");
5434 goto done;
5437 err = got_ref_open(&ref, repo, refname, 0);
5438 if (err == NULL) {
5439 err = got_error(GOT_ERR_TAG_EXISTS);
5440 goto done;
5441 } else if (err->code != GOT_ERR_NOT_REF)
5442 goto done;
5444 if (tagmsg_arg == NULL) {
5445 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5446 tag_name, got_repo_get_path(repo));
5447 if (err) {
5448 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5449 tagmsg_path != NULL)
5450 preserve_tagmsg = 1;
5451 goto done;
5455 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5456 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5457 if (err) {
5458 if (tagmsg_path)
5459 preserve_tagmsg = 1;
5460 goto done;
5463 err = got_ref_alloc(&ref, refname, tag_id);
5464 if (err) {
5465 if (tagmsg_path)
5466 preserve_tagmsg = 1;
5467 goto done;
5470 err = got_ref_write(ref, repo);
5471 if (err) {
5472 if (tagmsg_path)
5473 preserve_tagmsg = 1;
5474 goto done;
5477 err = got_object_id_str(&tag_id_str, tag_id);
5478 if (err) {
5479 if (tagmsg_path)
5480 preserve_tagmsg = 1;
5481 goto done;
5483 printf("Created tag %s\n", tag_id_str);
5484 done:
5485 if (preserve_tagmsg) {
5486 fprintf(stderr, "%s: tag message preserved in %s\n",
5487 getprogname(), tagmsg_path);
5488 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
5489 err = got_error_from_errno2("unlink", tagmsg_path);
5490 free(tag_id_str);
5491 if (ref)
5492 got_ref_close(ref);
5493 free(commit_id);
5494 free(commit_id_str);
5495 free(refname);
5496 free(tagmsg);
5497 free(tagmsg_path);
5498 free(tagger);
5499 return err;
5502 static const struct got_error *
5503 cmd_tag(int argc, char *argv[])
5505 const struct got_error *error = NULL;
5506 struct got_repository *repo = NULL;
5507 struct got_worktree *worktree = NULL;
5508 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
5509 char *gitconfig_path = NULL;
5510 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
5511 int ch, do_list = 0;
5513 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
5514 switch (ch) {
5515 case 'c':
5516 commit_id_arg = optarg;
5517 break;
5518 case 'm':
5519 tagmsg = optarg;
5520 break;
5521 case 'r':
5522 repo_path = realpath(optarg, NULL);
5523 if (repo_path == NULL)
5524 return got_error_from_errno2("realpath",
5525 optarg);
5526 got_path_strip_trailing_slashes(repo_path);
5527 break;
5528 case 'l':
5529 do_list = 1;
5530 break;
5531 default:
5532 usage_tag();
5533 /* NOTREACHED */
5537 argc -= optind;
5538 argv += optind;
5540 if (do_list) {
5541 if (commit_id_arg != NULL)
5542 errx(1,
5543 "-c option can only be used when creating a tag");
5544 if (tagmsg)
5545 errx(1, "-l and -m options are mutually exclusive");
5546 if (argc > 0)
5547 usage_tag();
5548 } else if (argc != 1)
5549 usage_tag();
5551 tag_name = argv[0];
5553 #ifndef PROFILE
5554 if (do_list) {
5555 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5556 NULL) == -1)
5557 err(1, "pledge");
5558 } else {
5559 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5560 "sendfd unveil", NULL) == -1)
5561 err(1, "pledge");
5563 #endif
5564 cwd = getcwd(NULL, 0);
5565 if (cwd == NULL) {
5566 error = got_error_from_errno("getcwd");
5567 goto done;
5570 if (repo_path == NULL) {
5571 error = got_worktree_open(&worktree, cwd);
5572 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5573 goto done;
5574 else
5575 error = NULL;
5576 if (worktree) {
5577 repo_path =
5578 strdup(got_worktree_get_repo_path(worktree));
5579 if (repo_path == NULL)
5580 error = got_error_from_errno("strdup");
5581 if (error)
5582 goto done;
5583 } else {
5584 repo_path = strdup(cwd);
5585 if (repo_path == NULL) {
5586 error = got_error_from_errno("strdup");
5587 goto done;
5592 if (do_list) {
5593 error = got_repo_open(&repo, repo_path, NULL);
5594 if (error != NULL)
5595 goto done;
5596 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5597 if (error)
5598 goto done;
5599 error = list_tags(repo, worktree);
5600 } else {
5601 error = get_gitconfig_path(&gitconfig_path);
5602 if (error)
5603 goto done;
5604 error = got_repo_open(&repo, repo_path, gitconfig_path);
5605 if (error != NULL)
5606 goto done;
5608 if (tagmsg) {
5609 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5610 if (error)
5611 goto done;
5614 if (commit_id_arg == NULL) {
5615 struct got_reference *head_ref;
5616 struct got_object_id *commit_id;
5617 error = got_ref_open(&head_ref, repo,
5618 worktree ? got_worktree_get_head_ref_name(worktree)
5619 : GOT_REF_HEAD, 0);
5620 if (error)
5621 goto done;
5622 error = got_ref_resolve(&commit_id, repo, head_ref);
5623 got_ref_close(head_ref);
5624 if (error)
5625 goto done;
5626 error = got_object_id_str(&commit_id_str, commit_id);
5627 free(commit_id);
5628 if (error)
5629 goto done;
5632 error = add_tag(repo, tag_name,
5633 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
5635 done:
5636 if (repo)
5637 got_repo_close(repo);
5638 if (worktree)
5639 got_worktree_close(worktree);
5640 free(cwd);
5641 free(repo_path);
5642 free(gitconfig_path);
5643 free(commit_id_str);
5644 return error;
5647 __dead static void
5648 usage_add(void)
5650 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
5651 getprogname());
5652 exit(1);
5655 static const struct got_error *
5656 add_progress(void *arg, unsigned char status, const char *path)
5658 while (path[0] == '/')
5659 path++;
5660 printf("%c %s\n", status, path);
5661 return NULL;
5664 static const struct got_error *
5665 cmd_add(int argc, char *argv[])
5667 const struct got_error *error = NULL;
5668 struct got_repository *repo = NULL;
5669 struct got_worktree *worktree = NULL;
5670 char *cwd = NULL;
5671 struct got_pathlist_head paths;
5672 struct got_pathlist_entry *pe;
5673 int ch, can_recurse = 0, no_ignores = 0;
5675 TAILQ_INIT(&paths);
5677 while ((ch = getopt(argc, argv, "IR")) != -1) {
5678 switch (ch) {
5679 case 'I':
5680 no_ignores = 1;
5681 break;
5682 case 'R':
5683 can_recurse = 1;
5684 break;
5685 default:
5686 usage_add();
5687 /* NOTREACHED */
5691 argc -= optind;
5692 argv += optind;
5694 #ifndef PROFILE
5695 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5696 NULL) == -1)
5697 err(1, "pledge");
5698 #endif
5699 if (argc < 1)
5700 usage_add();
5702 cwd = getcwd(NULL, 0);
5703 if (cwd == NULL) {
5704 error = got_error_from_errno("getcwd");
5705 goto done;
5708 error = got_worktree_open(&worktree, cwd);
5709 if (error) {
5710 if (error->code == GOT_ERR_NOT_WORKTREE)
5711 error = wrap_not_worktree_error(error, "add", cwd);
5712 goto done;
5715 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5716 NULL);
5717 if (error != NULL)
5718 goto done;
5720 error = apply_unveil(got_repo_get_path(repo), 1,
5721 got_worktree_get_root_path(worktree));
5722 if (error)
5723 goto done;
5725 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5726 if (error)
5727 goto done;
5729 if (!can_recurse && no_ignores) {
5730 error = got_error_msg(GOT_ERR_BAD_PATH,
5731 "disregarding ignores requires -R option");
5732 goto done;
5736 if (!can_recurse) {
5737 char *ondisk_path;
5738 struct stat sb;
5739 TAILQ_FOREACH(pe, &paths, entry) {
5740 if (asprintf(&ondisk_path, "%s/%s",
5741 got_worktree_get_root_path(worktree),
5742 pe->path) == -1) {
5743 error = got_error_from_errno("asprintf");
5744 goto done;
5746 if (lstat(ondisk_path, &sb) == -1) {
5747 if (errno == ENOENT) {
5748 free(ondisk_path);
5749 continue;
5751 error = got_error_from_errno2("lstat",
5752 ondisk_path);
5753 free(ondisk_path);
5754 goto done;
5756 free(ondisk_path);
5757 if (S_ISDIR(sb.st_mode)) {
5758 error = got_error_msg(GOT_ERR_BAD_PATH,
5759 "adding directories requires -R option");
5760 goto done;
5765 error = got_worktree_schedule_add(worktree, &paths, add_progress,
5766 NULL, repo, no_ignores);
5767 done:
5768 if (repo)
5769 got_repo_close(repo);
5770 if (worktree)
5771 got_worktree_close(worktree);
5772 TAILQ_FOREACH(pe, &paths, entry)
5773 free((char *)pe->path);
5774 got_pathlist_free(&paths);
5775 free(cwd);
5776 return error;
5779 __dead static void
5780 usage_remove(void)
5782 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] path ...\n",
5783 getprogname());
5784 exit(1);
5787 static const struct got_error *
5788 print_remove_status(void *arg, unsigned char status,
5789 unsigned char staged_status, const char *path)
5791 while (path[0] == '/')
5792 path++;
5793 if (status == GOT_STATUS_NONEXISTENT)
5794 return NULL;
5795 if (status == staged_status && (status == GOT_STATUS_DELETE))
5796 status = GOT_STATUS_NO_CHANGE;
5797 printf("%c%c %s\n", status, staged_status, path);
5798 return NULL;
5801 static const struct got_error *
5802 cmd_remove(int argc, char *argv[])
5804 const struct got_error *error = NULL;
5805 struct got_worktree *worktree = NULL;
5806 struct got_repository *repo = NULL;
5807 char *cwd = NULL;
5808 struct got_pathlist_head paths;
5809 struct got_pathlist_entry *pe;
5810 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0;
5812 TAILQ_INIT(&paths);
5814 while ((ch = getopt(argc, argv, "fkR")) != -1) {
5815 switch (ch) {
5816 case 'f':
5817 delete_local_mods = 1;
5818 break;
5819 case 'k':
5820 keep_on_disk = 1;
5821 break;
5822 case 'R':
5823 can_recurse = 1;
5824 break;
5825 default:
5826 usage_remove();
5827 /* NOTREACHED */
5831 argc -= optind;
5832 argv += optind;
5834 #ifndef PROFILE
5835 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5836 NULL) == -1)
5837 err(1, "pledge");
5838 #endif
5839 if (argc < 1)
5840 usage_remove();
5842 cwd = getcwd(NULL, 0);
5843 if (cwd == NULL) {
5844 error = got_error_from_errno("getcwd");
5845 goto done;
5847 error = got_worktree_open(&worktree, cwd);
5848 if (error) {
5849 if (error->code == GOT_ERR_NOT_WORKTREE)
5850 error = wrap_not_worktree_error(error, "remove", cwd);
5851 goto done;
5854 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5855 NULL);
5856 if (error)
5857 goto done;
5859 error = apply_unveil(got_repo_get_path(repo), 1,
5860 got_worktree_get_root_path(worktree));
5861 if (error)
5862 goto done;
5864 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5865 if (error)
5866 goto done;
5868 if (!can_recurse) {
5869 char *ondisk_path;
5870 struct stat sb;
5871 TAILQ_FOREACH(pe, &paths, entry) {
5872 if (asprintf(&ondisk_path, "%s/%s",
5873 got_worktree_get_root_path(worktree),
5874 pe->path) == -1) {
5875 error = got_error_from_errno("asprintf");
5876 goto done;
5878 if (lstat(ondisk_path, &sb) == -1) {
5879 if (errno == ENOENT) {
5880 free(ondisk_path);
5881 continue;
5883 error = got_error_from_errno2("lstat",
5884 ondisk_path);
5885 free(ondisk_path);
5886 goto done;
5888 free(ondisk_path);
5889 if (S_ISDIR(sb.st_mode)) {
5890 error = got_error_msg(GOT_ERR_BAD_PATH,
5891 "removing directories requires -R option");
5892 goto done;
5897 error = got_worktree_schedule_delete(worktree, &paths,
5898 delete_local_mods, print_remove_status, NULL, repo, keep_on_disk);
5899 done:
5900 if (repo)
5901 got_repo_close(repo);
5902 if (worktree)
5903 got_worktree_close(worktree);
5904 TAILQ_FOREACH(pe, &paths, entry)
5905 free((char *)pe->path);
5906 got_pathlist_free(&paths);
5907 free(cwd);
5908 return error;
5911 __dead static void
5912 usage_revert(void)
5914 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
5915 "path ...\n", getprogname());
5916 exit(1);
5919 static const struct got_error *
5920 revert_progress(void *arg, unsigned char status, const char *path)
5922 if (status == GOT_STATUS_UNVERSIONED)
5923 return NULL;
5925 while (path[0] == '/')
5926 path++;
5927 printf("%c %s\n", status, path);
5928 return NULL;
5931 struct choose_patch_arg {
5932 FILE *patch_script_file;
5933 const char *action;
5936 static const struct got_error *
5937 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
5938 int nchanges, const char *action)
5940 char *line = NULL;
5941 size_t linesize = 0;
5942 ssize_t linelen;
5944 switch (status) {
5945 case GOT_STATUS_ADD:
5946 printf("A %s\n%s this addition? [y/n] ", path, action);
5947 break;
5948 case GOT_STATUS_DELETE:
5949 printf("D %s\n%s this deletion? [y/n] ", path, action);
5950 break;
5951 case GOT_STATUS_MODIFY:
5952 if (fseek(patch_file, 0L, SEEK_SET) == -1)
5953 return got_error_from_errno("fseek");
5954 printf(GOT_COMMIT_SEP_STR);
5955 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
5956 printf("%s", line);
5957 if (ferror(patch_file))
5958 return got_error_from_errno("getline");
5959 printf(GOT_COMMIT_SEP_STR);
5960 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
5961 path, n, nchanges, action);
5962 break;
5963 default:
5964 return got_error_path(path, GOT_ERR_FILE_STATUS);
5967 return NULL;
5970 static const struct got_error *
5971 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
5972 FILE *patch_file, int n, int nchanges)
5974 const struct got_error *err = NULL;
5975 char *line = NULL;
5976 size_t linesize = 0;
5977 ssize_t linelen;
5978 int resp = ' ';
5979 struct choose_patch_arg *a = arg;
5981 *choice = GOT_PATCH_CHOICE_NONE;
5983 if (a->patch_script_file) {
5984 char *nl;
5985 err = show_change(status, path, patch_file, n, nchanges,
5986 a->action);
5987 if (err)
5988 return err;
5989 linelen = getline(&line, &linesize, a->patch_script_file);
5990 if (linelen == -1) {
5991 if (ferror(a->patch_script_file))
5992 return got_error_from_errno("getline");
5993 return NULL;
5995 nl = strchr(line, '\n');
5996 if (nl)
5997 *nl = '\0';
5998 if (strcmp(line, "y") == 0) {
5999 *choice = GOT_PATCH_CHOICE_YES;
6000 printf("y\n");
6001 } else if (strcmp(line, "n") == 0) {
6002 *choice = GOT_PATCH_CHOICE_NO;
6003 printf("n\n");
6004 } else if (strcmp(line, "q") == 0 &&
6005 status == GOT_STATUS_MODIFY) {
6006 *choice = GOT_PATCH_CHOICE_QUIT;
6007 printf("q\n");
6008 } else
6009 printf("invalid response '%s'\n", line);
6010 free(line);
6011 return NULL;
6014 while (resp != 'y' && resp != 'n' && resp != 'q') {
6015 err = show_change(status, path, patch_file, n, nchanges,
6016 a->action);
6017 if (err)
6018 return err;
6019 resp = getchar();
6020 if (resp == '\n')
6021 resp = getchar();
6022 if (status == GOT_STATUS_MODIFY) {
6023 if (resp != 'y' && resp != 'n' && resp != 'q') {
6024 printf("invalid response '%c'\n", resp);
6025 resp = ' ';
6027 } else if (resp != 'y' && resp != 'n') {
6028 printf("invalid response '%c'\n", resp);
6029 resp = ' ';
6033 if (resp == 'y')
6034 *choice = GOT_PATCH_CHOICE_YES;
6035 else if (resp == 'n')
6036 *choice = GOT_PATCH_CHOICE_NO;
6037 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6038 *choice = GOT_PATCH_CHOICE_QUIT;
6040 return NULL;
6044 static const struct got_error *
6045 cmd_revert(int argc, char *argv[])
6047 const struct got_error *error = NULL;
6048 struct got_worktree *worktree = NULL;
6049 struct got_repository *repo = NULL;
6050 char *cwd = NULL, *path = NULL;
6051 struct got_pathlist_head paths;
6052 struct got_pathlist_entry *pe;
6053 int ch, can_recurse = 0, pflag = 0;
6054 FILE *patch_script_file = NULL;
6055 const char *patch_script_path = NULL;
6056 struct choose_patch_arg cpa;
6058 TAILQ_INIT(&paths);
6060 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6061 switch (ch) {
6062 case 'p':
6063 pflag = 1;
6064 break;
6065 case 'F':
6066 patch_script_path = optarg;
6067 break;
6068 case 'R':
6069 can_recurse = 1;
6070 break;
6071 default:
6072 usage_revert();
6073 /* NOTREACHED */
6077 argc -= optind;
6078 argv += optind;
6080 #ifndef PROFILE
6081 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6082 "unveil", NULL) == -1)
6083 err(1, "pledge");
6084 #endif
6085 if (argc < 1)
6086 usage_revert();
6087 if (patch_script_path && !pflag)
6088 errx(1, "-F option can only be used together with -p option");
6090 cwd = getcwd(NULL, 0);
6091 if (cwd == NULL) {
6092 error = got_error_from_errno("getcwd");
6093 goto done;
6095 error = got_worktree_open(&worktree, cwd);
6096 if (error) {
6097 if (error->code == GOT_ERR_NOT_WORKTREE)
6098 error = wrap_not_worktree_error(error, "revert", cwd);
6099 goto done;
6102 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6103 NULL);
6104 if (error != NULL)
6105 goto done;
6107 if (patch_script_path) {
6108 patch_script_file = fopen(patch_script_path, "r");
6109 if (patch_script_file == NULL) {
6110 error = got_error_from_errno2("fopen",
6111 patch_script_path);
6112 goto done;
6115 error = apply_unveil(got_repo_get_path(repo), 1,
6116 got_worktree_get_root_path(worktree));
6117 if (error)
6118 goto done;
6120 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6121 if (error)
6122 goto done;
6124 if (!can_recurse) {
6125 char *ondisk_path;
6126 struct stat sb;
6127 TAILQ_FOREACH(pe, &paths, entry) {
6128 if (asprintf(&ondisk_path, "%s/%s",
6129 got_worktree_get_root_path(worktree),
6130 pe->path) == -1) {
6131 error = got_error_from_errno("asprintf");
6132 goto done;
6134 if (lstat(ondisk_path, &sb) == -1) {
6135 if (errno == ENOENT) {
6136 free(ondisk_path);
6137 continue;
6139 error = got_error_from_errno2("lstat",
6140 ondisk_path);
6141 free(ondisk_path);
6142 goto done;
6144 free(ondisk_path);
6145 if (S_ISDIR(sb.st_mode)) {
6146 error = got_error_msg(GOT_ERR_BAD_PATH,
6147 "reverting directories requires -R option");
6148 goto done;
6153 cpa.patch_script_file = patch_script_file;
6154 cpa.action = "revert";
6155 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6156 pflag ? choose_patch : NULL, &cpa, repo);
6157 done:
6158 if (patch_script_file && fclose(patch_script_file) == EOF &&
6159 error == NULL)
6160 error = got_error_from_errno2("fclose", patch_script_path);
6161 if (repo)
6162 got_repo_close(repo);
6163 if (worktree)
6164 got_worktree_close(worktree);
6165 free(path);
6166 free(cwd);
6167 return error;
6170 __dead static void
6171 usage_commit(void)
6173 fprintf(stderr, "usage: %s commit [-m msg] [path ...]\n",
6174 getprogname());
6175 exit(1);
6178 struct collect_commit_logmsg_arg {
6179 const char *cmdline_log;
6180 const char *editor;
6181 const char *worktree_path;
6182 const char *branch_name;
6183 const char *repo_path;
6184 char *logmsg_path;
6188 static const struct got_error *
6189 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6190 void *arg)
6192 char *initial_content = NULL;
6193 struct got_pathlist_entry *pe;
6194 const struct got_error *err = NULL;
6195 char *template = NULL;
6196 struct collect_commit_logmsg_arg *a = arg;
6197 int fd;
6198 size_t len;
6200 /* if a message was specified on the command line, just use it */
6201 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6202 len = strlen(a->cmdline_log) + 1;
6203 *logmsg = malloc(len + 1);
6204 if (*logmsg == NULL)
6205 return got_error_from_errno("malloc");
6206 strlcpy(*logmsg, a->cmdline_log, len);
6207 return NULL;
6210 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6211 return got_error_from_errno("asprintf");
6213 if (asprintf(&initial_content,
6214 "\n# changes to be committed on branch %s:\n",
6215 a->branch_name) == -1)
6216 return got_error_from_errno("asprintf");
6218 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6219 if (err)
6220 goto done;
6222 dprintf(fd, initial_content);
6224 TAILQ_FOREACH(pe, commitable_paths, entry) {
6225 struct got_commitable *ct = pe->data;
6226 dprintf(fd, "# %c %s\n",
6227 got_commitable_get_status(ct),
6228 got_commitable_get_path(ct));
6230 close(fd);
6232 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
6233 done:
6234 free(initial_content);
6235 free(template);
6237 /* Editor is done; we can now apply unveil(2) */
6238 if (err == NULL) {
6239 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6240 if (err) {
6241 free(*logmsg);
6242 *logmsg = NULL;
6245 return err;
6248 static const struct got_error *
6249 cmd_commit(int argc, char *argv[])
6251 const struct got_error *error = NULL;
6252 struct got_worktree *worktree = NULL;
6253 struct got_repository *repo = NULL;
6254 char *cwd = NULL, *id_str = NULL;
6255 struct got_object_id *id = NULL;
6256 const char *logmsg = NULL;
6257 struct collect_commit_logmsg_arg cl_arg;
6258 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6259 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6260 struct got_pathlist_head paths;
6262 TAILQ_INIT(&paths);
6263 cl_arg.logmsg_path = NULL;
6265 while ((ch = getopt(argc, argv, "m:")) != -1) {
6266 switch (ch) {
6267 case 'm':
6268 logmsg = optarg;
6269 break;
6270 default:
6271 usage_commit();
6272 /* NOTREACHED */
6276 argc -= optind;
6277 argv += optind;
6279 #ifndef PROFILE
6280 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6281 "unveil", NULL) == -1)
6282 err(1, "pledge");
6283 #endif
6284 cwd = getcwd(NULL, 0);
6285 if (cwd == NULL) {
6286 error = got_error_from_errno("getcwd");
6287 goto done;
6289 error = got_worktree_open(&worktree, cwd);
6290 if (error) {
6291 if (error->code == GOT_ERR_NOT_WORKTREE)
6292 error = wrap_not_worktree_error(error, "commit", cwd);
6293 goto done;
6296 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6297 if (error)
6298 goto done;
6299 if (rebase_in_progress) {
6300 error = got_error(GOT_ERR_REBASING);
6301 goto done;
6304 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6305 worktree);
6306 if (error)
6307 goto done;
6309 error = get_gitconfig_path(&gitconfig_path);
6310 if (error)
6311 goto done;
6312 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6313 gitconfig_path);
6314 if (error != NULL)
6315 goto done;
6317 error = get_author(&author, repo);
6318 if (error)
6319 return error;
6322 * unveil(2) traverses exec(2); if an editor is used we have
6323 * to apply unveil after the log message has been written.
6325 if (logmsg == NULL || strlen(logmsg) == 0)
6326 error = get_editor(&editor);
6327 else
6328 error = apply_unveil(got_repo_get_path(repo), 0,
6329 got_worktree_get_root_path(worktree));
6330 if (error)
6331 goto done;
6333 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6334 if (error)
6335 goto done;
6337 cl_arg.editor = editor;
6338 cl_arg.cmdline_log = logmsg;
6339 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6340 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6341 if (!histedit_in_progress) {
6342 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6343 error = got_error(GOT_ERR_COMMIT_BRANCH);
6344 goto done;
6346 cl_arg.branch_name += 11;
6348 cl_arg.repo_path = got_repo_get_path(repo);
6349 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6350 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
6351 if (error) {
6352 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6353 cl_arg.logmsg_path != NULL)
6354 preserve_logmsg = 1;
6355 goto done;
6358 error = got_object_id_str(&id_str, id);
6359 if (error)
6360 goto done;
6361 printf("Created commit %s\n", id_str);
6362 done:
6363 if (preserve_logmsg) {
6364 fprintf(stderr, "%s: log message preserved in %s\n",
6365 getprogname(), cl_arg.logmsg_path);
6366 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6367 error == NULL)
6368 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6369 free(cl_arg.logmsg_path);
6370 if (repo)
6371 got_repo_close(repo);
6372 if (worktree)
6373 got_worktree_close(worktree);
6374 free(cwd);
6375 free(id_str);
6376 free(gitconfig_path);
6377 free(editor);
6378 free(author);
6379 return error;
6382 __dead static void
6383 usage_cherrypick(void)
6385 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6386 exit(1);
6389 static const struct got_error *
6390 cmd_cherrypick(int argc, char *argv[])
6392 const struct got_error *error = NULL;
6393 struct got_worktree *worktree = NULL;
6394 struct got_repository *repo = NULL;
6395 char *cwd = NULL, *commit_id_str = NULL;
6396 struct got_object_id *commit_id = NULL;
6397 struct got_commit_object *commit = NULL;
6398 struct got_object_qid *pid;
6399 struct got_reference *head_ref = NULL;
6400 int ch;
6401 struct got_update_progress_arg upa;
6403 while ((ch = getopt(argc, argv, "")) != -1) {
6404 switch (ch) {
6405 default:
6406 usage_cherrypick();
6407 /* NOTREACHED */
6411 argc -= optind;
6412 argv += optind;
6414 #ifndef PROFILE
6415 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6416 "unveil", NULL) == -1)
6417 err(1, "pledge");
6418 #endif
6419 if (argc != 1)
6420 usage_cherrypick();
6422 cwd = getcwd(NULL, 0);
6423 if (cwd == NULL) {
6424 error = got_error_from_errno("getcwd");
6425 goto done;
6427 error = got_worktree_open(&worktree, cwd);
6428 if (error) {
6429 if (error->code == GOT_ERR_NOT_WORKTREE)
6430 error = wrap_not_worktree_error(error, "cherrypick",
6431 cwd);
6432 goto done;
6435 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6436 NULL);
6437 if (error != NULL)
6438 goto done;
6440 error = apply_unveil(got_repo_get_path(repo), 0,
6441 got_worktree_get_root_path(worktree));
6442 if (error)
6443 goto done;
6445 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6446 GOT_OBJ_TYPE_COMMIT, repo);
6447 if (error != NULL) {
6448 struct got_reference *ref;
6449 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6450 goto done;
6451 error = got_ref_open(&ref, repo, argv[0], 0);
6452 if (error != NULL)
6453 goto done;
6454 error = got_ref_resolve(&commit_id, repo, ref);
6455 got_ref_close(ref);
6456 if (error != NULL)
6457 goto done;
6459 error = got_object_id_str(&commit_id_str, commit_id);
6460 if (error)
6461 goto done;
6463 error = got_ref_open(&head_ref, repo,
6464 got_worktree_get_head_ref_name(worktree), 0);
6465 if (error != NULL)
6466 goto done;
6468 error = check_same_branch(commit_id, head_ref, NULL, repo);
6469 if (error) {
6470 if (error->code != GOT_ERR_ANCESTRY)
6471 goto done;
6472 error = NULL;
6473 } else {
6474 error = got_error(GOT_ERR_SAME_BRANCH);
6475 goto done;
6478 error = got_object_open_as_commit(&commit, repo, commit_id);
6479 if (error)
6480 goto done;
6481 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6482 memset(&upa, 0, sizeof(upa));
6483 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
6484 commit_id, repo, update_progress, &upa, check_cancelled,
6485 NULL);
6486 if (error != NULL)
6487 goto done;
6489 if (upa.did_something)
6490 printf("Merged commit %s\n", commit_id_str);
6491 print_update_progress_stats(&upa);
6492 done:
6493 if (commit)
6494 got_object_commit_close(commit);
6495 free(commit_id_str);
6496 if (head_ref)
6497 got_ref_close(head_ref);
6498 if (worktree)
6499 got_worktree_close(worktree);
6500 if (repo)
6501 got_repo_close(repo);
6502 return error;
6505 __dead static void
6506 usage_backout(void)
6508 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
6509 exit(1);
6512 static const struct got_error *
6513 cmd_backout(int argc, char *argv[])
6515 const struct got_error *error = NULL;
6516 struct got_worktree *worktree = NULL;
6517 struct got_repository *repo = NULL;
6518 char *cwd = NULL, *commit_id_str = NULL;
6519 struct got_object_id *commit_id = NULL;
6520 struct got_commit_object *commit = NULL;
6521 struct got_object_qid *pid;
6522 struct got_reference *head_ref = NULL;
6523 int ch;
6524 struct got_update_progress_arg upa;
6526 while ((ch = getopt(argc, argv, "")) != -1) {
6527 switch (ch) {
6528 default:
6529 usage_backout();
6530 /* NOTREACHED */
6534 argc -= optind;
6535 argv += optind;
6537 #ifndef PROFILE
6538 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6539 "unveil", NULL) == -1)
6540 err(1, "pledge");
6541 #endif
6542 if (argc != 1)
6543 usage_backout();
6545 cwd = getcwd(NULL, 0);
6546 if (cwd == NULL) {
6547 error = got_error_from_errno("getcwd");
6548 goto done;
6550 error = got_worktree_open(&worktree, cwd);
6551 if (error) {
6552 if (error->code == GOT_ERR_NOT_WORKTREE)
6553 error = wrap_not_worktree_error(error, "backout", cwd);
6554 goto done;
6557 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6558 NULL);
6559 if (error != NULL)
6560 goto done;
6562 error = apply_unveil(got_repo_get_path(repo), 0,
6563 got_worktree_get_root_path(worktree));
6564 if (error)
6565 goto done;
6567 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6568 GOT_OBJ_TYPE_COMMIT, repo);
6569 if (error != NULL) {
6570 struct got_reference *ref;
6571 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6572 goto done;
6573 error = got_ref_open(&ref, repo, argv[0], 0);
6574 if (error != NULL)
6575 goto done;
6576 error = got_ref_resolve(&commit_id, repo, ref);
6577 got_ref_close(ref);
6578 if (error != NULL)
6579 goto done;
6581 error = got_object_id_str(&commit_id_str, commit_id);
6582 if (error)
6583 goto done;
6585 error = got_ref_open(&head_ref, repo,
6586 got_worktree_get_head_ref_name(worktree), 0);
6587 if (error != NULL)
6588 goto done;
6590 error = check_same_branch(commit_id, head_ref, NULL, repo);
6591 if (error)
6592 goto done;
6594 error = got_object_open_as_commit(&commit, repo, commit_id);
6595 if (error)
6596 goto done;
6597 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6598 if (pid == NULL) {
6599 error = got_error(GOT_ERR_ROOT_COMMIT);
6600 goto done;
6603 memset(&upa, 0, sizeof(upa));
6604 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
6605 update_progress, &upa, check_cancelled, NULL);
6606 if (error != NULL)
6607 goto done;
6609 if (upa.did_something)
6610 printf("Backed out commit %s\n", commit_id_str);
6611 print_update_progress_stats(&upa);
6612 done:
6613 if (commit)
6614 got_object_commit_close(commit);
6615 free(commit_id_str);
6616 if (head_ref)
6617 got_ref_close(head_ref);
6618 if (worktree)
6619 got_worktree_close(worktree);
6620 if (repo)
6621 got_repo_close(repo);
6622 return error;
6625 __dead static void
6626 usage_rebase(void)
6628 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
6629 getprogname());
6630 exit(1);
6633 void
6634 trim_logmsg(char *logmsg, int limit)
6636 char *nl;
6637 size_t len;
6639 len = strlen(logmsg);
6640 if (len > limit)
6641 len = limit;
6642 logmsg[len] = '\0';
6643 nl = strchr(logmsg, '\n');
6644 if (nl)
6645 *nl = '\0';
6648 static const struct got_error *
6649 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
6651 const struct got_error *err;
6652 char *logmsg0 = NULL;
6653 const char *s;
6655 err = got_object_commit_get_logmsg(&logmsg0, commit);
6656 if (err)
6657 return err;
6659 s = logmsg0;
6660 while (isspace((unsigned char)s[0]))
6661 s++;
6663 *logmsg = strdup(s);
6664 if (*logmsg == NULL) {
6665 err = got_error_from_errno("strdup");
6666 goto done;
6669 trim_logmsg(*logmsg, limit);
6670 done:
6671 free(logmsg0);
6672 return err;
6675 static const struct got_error *
6676 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
6678 const struct got_error *err;
6679 struct got_commit_object *commit = NULL;
6680 char *id_str = NULL, *logmsg = NULL;
6682 err = got_object_open_as_commit(&commit, repo, id);
6683 if (err)
6684 return err;
6686 err = got_object_id_str(&id_str, id);
6687 if (err)
6688 goto done;
6690 id_str[12] = '\0';
6692 err = get_short_logmsg(&logmsg, 42, commit);
6693 if (err)
6694 goto done;
6696 printf("%s -> merge conflict: %s\n", id_str, logmsg);
6697 done:
6698 free(id_str);
6699 got_object_commit_close(commit);
6700 free(logmsg);
6701 return err;
6704 static const struct got_error *
6705 show_rebase_progress(struct got_commit_object *commit,
6706 struct got_object_id *old_id, struct got_object_id *new_id)
6708 const struct got_error *err;
6709 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
6711 err = got_object_id_str(&old_id_str, old_id);
6712 if (err)
6713 goto done;
6715 if (new_id) {
6716 err = got_object_id_str(&new_id_str, new_id);
6717 if (err)
6718 goto done;
6721 old_id_str[12] = '\0';
6722 if (new_id_str)
6723 new_id_str[12] = '\0';
6725 err = get_short_logmsg(&logmsg, 42, commit);
6726 if (err)
6727 goto done;
6729 printf("%s -> %s: %s\n", old_id_str,
6730 new_id_str ? new_id_str : "no-op change", logmsg);
6731 done:
6732 free(old_id_str);
6733 free(new_id_str);
6734 free(logmsg);
6735 return err;
6738 static const struct got_error *
6739 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
6740 struct got_reference *branch, struct got_reference *new_base_branch,
6741 struct got_reference *tmp_branch, struct got_repository *repo)
6743 printf("Switching work tree to %s\n", got_ref_get_name(branch));
6744 return got_worktree_rebase_complete(worktree, fileindex,
6745 new_base_branch, tmp_branch, branch, repo);
6748 static const struct got_error *
6749 rebase_commit(struct got_pathlist_head *merged_paths,
6750 struct got_worktree *worktree, struct got_fileindex *fileindex,
6751 struct got_reference *tmp_branch,
6752 struct got_object_id *commit_id, struct got_repository *repo)
6754 const struct got_error *error;
6755 struct got_commit_object *commit;
6756 struct got_object_id *new_commit_id;
6758 error = got_object_open_as_commit(&commit, repo, commit_id);
6759 if (error)
6760 return error;
6762 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
6763 worktree, fileindex, tmp_branch, commit, commit_id, repo);
6764 if (error) {
6765 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
6766 goto done;
6767 error = show_rebase_progress(commit, commit_id, NULL);
6768 } else {
6769 error = show_rebase_progress(commit, commit_id, new_commit_id);
6770 free(new_commit_id);
6772 done:
6773 got_object_commit_close(commit);
6774 return error;
6777 struct check_path_prefix_arg {
6778 const char *path_prefix;
6779 size_t len;
6780 int errcode;
6783 static const struct got_error *
6784 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
6785 struct got_blob_object *blob2, struct got_object_id *id1,
6786 struct got_object_id *id2, const char *path1, const char *path2,
6787 mode_t mode1, mode_t mode2, struct got_repository *repo)
6789 struct check_path_prefix_arg *a = arg;
6791 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
6792 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
6793 return got_error(a->errcode);
6795 return NULL;
6798 static const struct got_error *
6799 check_path_prefix(struct got_object_id *parent_id,
6800 struct got_object_id *commit_id, const char *path_prefix,
6801 int errcode, struct got_repository *repo)
6803 const struct got_error *err;
6804 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
6805 struct got_commit_object *commit = NULL, *parent_commit = NULL;
6806 struct check_path_prefix_arg cpp_arg;
6808 if (got_path_is_root_dir(path_prefix))
6809 return NULL;
6811 err = got_object_open_as_commit(&commit, repo, commit_id);
6812 if (err)
6813 goto done;
6815 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
6816 if (err)
6817 goto done;
6819 err = got_object_open_as_tree(&tree1, repo,
6820 got_object_commit_get_tree_id(parent_commit));
6821 if (err)
6822 goto done;
6824 err = got_object_open_as_tree(&tree2, repo,
6825 got_object_commit_get_tree_id(commit));
6826 if (err)
6827 goto done;
6829 cpp_arg.path_prefix = path_prefix;
6830 while (cpp_arg.path_prefix[0] == '/')
6831 cpp_arg.path_prefix++;
6832 cpp_arg.len = strlen(cpp_arg.path_prefix);
6833 cpp_arg.errcode = errcode;
6834 err = got_diff_tree(tree1, tree2, "", "", repo,
6835 check_path_prefix_in_diff, &cpp_arg, 0);
6836 done:
6837 if (tree1)
6838 got_object_tree_close(tree1);
6839 if (tree2)
6840 got_object_tree_close(tree2);
6841 if (commit)
6842 got_object_commit_close(commit);
6843 if (parent_commit)
6844 got_object_commit_close(parent_commit);
6845 return err;
6848 static const struct got_error *
6849 collect_commits(struct got_object_id_queue *commits,
6850 struct got_object_id *initial_commit_id,
6851 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
6852 const char *path_prefix, int path_prefix_errcode,
6853 struct got_repository *repo)
6855 const struct got_error *err = NULL;
6856 struct got_commit_graph *graph = NULL;
6857 struct got_object_id *parent_id = NULL;
6858 struct got_object_qid *qid;
6859 struct got_object_id *commit_id = initial_commit_id;
6861 err = got_commit_graph_open(&graph, "/", 1);
6862 if (err)
6863 return err;
6865 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
6866 check_cancelled, NULL);
6867 if (err)
6868 goto done;
6869 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
6870 err = got_commit_graph_iter_next(&parent_id, graph, repo,
6871 check_cancelled, NULL);
6872 if (err) {
6873 if (err->code == GOT_ERR_ITER_COMPLETED) {
6874 err = got_error_msg(GOT_ERR_ANCESTRY,
6875 "ran out of commits to rebase before "
6876 "youngest common ancestor commit has "
6877 "been reached?!?");
6879 goto done;
6880 } else {
6881 err = check_path_prefix(parent_id, commit_id,
6882 path_prefix, path_prefix_errcode, repo);
6883 if (err)
6884 goto done;
6886 err = got_object_qid_alloc(&qid, commit_id);
6887 if (err)
6888 goto done;
6889 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
6890 commit_id = parent_id;
6893 done:
6894 got_commit_graph_close(graph);
6895 return err;
6898 static const struct got_error *
6899 cmd_rebase(int argc, char *argv[])
6901 const struct got_error *error = NULL;
6902 struct got_worktree *worktree = NULL;
6903 struct got_repository *repo = NULL;
6904 struct got_fileindex *fileindex = NULL;
6905 char *cwd = NULL;
6906 struct got_reference *branch = NULL;
6907 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
6908 struct got_object_id *commit_id = NULL, *parent_id = NULL;
6909 struct got_object_id *resume_commit_id = NULL;
6910 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
6911 struct got_commit_object *commit = NULL;
6912 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
6913 int histedit_in_progress = 0;
6914 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
6915 struct got_object_id_queue commits;
6916 struct got_pathlist_head merged_paths;
6917 const struct got_object_id_queue *parent_ids;
6918 struct got_object_qid *qid, *pid;
6920 SIMPLEQ_INIT(&commits);
6921 TAILQ_INIT(&merged_paths);
6923 while ((ch = getopt(argc, argv, "ac")) != -1) {
6924 switch (ch) {
6925 case 'a':
6926 abort_rebase = 1;
6927 break;
6928 case 'c':
6929 continue_rebase = 1;
6930 break;
6931 default:
6932 usage_rebase();
6933 /* NOTREACHED */
6937 argc -= optind;
6938 argv += optind;
6940 #ifndef PROFILE
6941 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6942 "unveil", NULL) == -1)
6943 err(1, "pledge");
6944 #endif
6945 if (abort_rebase && continue_rebase)
6946 usage_rebase();
6947 else if (abort_rebase || continue_rebase) {
6948 if (argc != 0)
6949 usage_rebase();
6950 } else if (argc != 1)
6951 usage_rebase();
6953 cwd = getcwd(NULL, 0);
6954 if (cwd == NULL) {
6955 error = got_error_from_errno("getcwd");
6956 goto done;
6958 error = got_worktree_open(&worktree, cwd);
6959 if (error) {
6960 if (error->code == GOT_ERR_NOT_WORKTREE)
6961 error = wrap_not_worktree_error(error, "rebase", cwd);
6962 goto done;
6965 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6966 NULL);
6967 if (error != NULL)
6968 goto done;
6970 error = apply_unveil(got_repo_get_path(repo), 0,
6971 got_worktree_get_root_path(worktree));
6972 if (error)
6973 goto done;
6975 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6976 worktree);
6977 if (error)
6978 goto done;
6979 if (histedit_in_progress) {
6980 error = got_error(GOT_ERR_HISTEDIT_BUSY);
6981 goto done;
6984 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6985 if (error)
6986 goto done;
6988 if (abort_rebase) {
6989 struct got_update_progress_arg upa;
6990 if (!rebase_in_progress) {
6991 error = got_error(GOT_ERR_NOT_REBASING);
6992 goto done;
6994 error = got_worktree_rebase_continue(&resume_commit_id,
6995 &new_base_branch, &tmp_branch, &branch, &fileindex,
6996 worktree, repo);
6997 if (error)
6998 goto done;
6999 printf("Switching work tree to %s\n",
7000 got_ref_get_symref_target(new_base_branch));
7001 memset(&upa, 0, sizeof(upa));
7002 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7003 new_base_branch, update_progress, &upa);
7004 if (error)
7005 goto done;
7006 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7007 print_update_progress_stats(&upa);
7008 goto done; /* nothing else to do */
7011 if (continue_rebase) {
7012 if (!rebase_in_progress) {
7013 error = got_error(GOT_ERR_NOT_REBASING);
7014 goto done;
7016 error = got_worktree_rebase_continue(&resume_commit_id,
7017 &new_base_branch, &tmp_branch, &branch, &fileindex,
7018 worktree, repo);
7019 if (error)
7020 goto done;
7022 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7023 resume_commit_id, repo);
7024 if (error)
7025 goto done;
7027 yca_id = got_object_id_dup(resume_commit_id);
7028 if (yca_id == NULL) {
7029 error = got_error_from_errno("got_object_id_dup");
7030 goto done;
7032 } else {
7033 error = got_ref_open(&branch, repo, argv[0], 0);
7034 if (error != NULL)
7035 goto done;
7038 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7039 if (error)
7040 goto done;
7042 if (!continue_rebase) {
7043 struct got_object_id *base_commit_id;
7045 base_commit_id = got_worktree_get_base_commit_id(worktree);
7046 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7047 base_commit_id, branch_head_commit_id, repo,
7048 check_cancelled, NULL);
7049 if (error)
7050 goto done;
7051 if (yca_id == NULL) {
7052 error = got_error_msg(GOT_ERR_ANCESTRY,
7053 "specified branch shares no common ancestry "
7054 "with work tree's branch");
7055 goto done;
7058 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7059 if (error) {
7060 if (error->code != GOT_ERR_ANCESTRY)
7061 goto done;
7062 error = NULL;
7063 } else {
7064 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7065 "specified branch resolves to a commit which "
7066 "is already contained in work tree's branch");
7067 goto done;
7069 error = got_worktree_rebase_prepare(&new_base_branch,
7070 &tmp_branch, &fileindex, worktree, branch, repo);
7071 if (error)
7072 goto done;
7075 commit_id = branch_head_commit_id;
7076 error = got_object_open_as_commit(&commit, repo, commit_id);
7077 if (error)
7078 goto done;
7080 parent_ids = got_object_commit_get_parent_ids(commit);
7081 pid = SIMPLEQ_FIRST(parent_ids);
7082 if (pid == NULL) {
7083 if (!continue_rebase) {
7084 struct got_update_progress_arg upa;
7085 memset(&upa, 0, sizeof(upa));
7086 error = got_worktree_rebase_abort(worktree, fileindex,
7087 repo, new_base_branch, update_progress, &upa);
7088 if (error)
7089 goto done;
7090 printf("Rebase of %s aborted\n",
7091 got_ref_get_name(branch));
7092 print_update_progress_stats(&upa);
7095 error = got_error(GOT_ERR_EMPTY_REBASE);
7096 goto done;
7098 error = collect_commits(&commits, commit_id, pid->id,
7099 yca_id, got_worktree_get_path_prefix(worktree),
7100 GOT_ERR_REBASE_PATH, repo);
7101 got_object_commit_close(commit);
7102 commit = NULL;
7103 if (error)
7104 goto done;
7106 if (SIMPLEQ_EMPTY(&commits)) {
7107 if (continue_rebase) {
7108 error = rebase_complete(worktree, fileindex,
7109 branch, new_base_branch, tmp_branch, repo);
7110 goto done;
7111 } else {
7112 /* Fast-forward the reference of the branch. */
7113 struct got_object_id *new_head_commit_id;
7114 char *id_str;
7115 error = got_ref_resolve(&new_head_commit_id, repo,
7116 new_base_branch);
7117 if (error)
7118 goto done;
7119 error = got_object_id_str(&id_str, new_head_commit_id);
7120 printf("Forwarding %s to commit %s\n",
7121 got_ref_get_name(branch), id_str);
7122 free(id_str);
7123 error = got_ref_change_ref(branch,
7124 new_head_commit_id);
7125 if (error)
7126 goto done;
7130 pid = NULL;
7131 SIMPLEQ_FOREACH(qid, &commits, entry) {
7132 struct got_update_progress_arg upa;
7134 commit_id = qid->id;
7135 parent_id = pid ? pid->id : yca_id;
7136 pid = qid;
7138 memset(&upa, 0, sizeof(upa));
7139 error = got_worktree_rebase_merge_files(&merged_paths,
7140 worktree, fileindex, parent_id, commit_id, repo,
7141 update_progress, &upa, check_cancelled, NULL);
7142 if (error)
7143 goto done;
7145 print_update_progress_stats(&upa);
7146 if (upa.conflicts > 0)
7147 rebase_status = GOT_STATUS_CONFLICT;
7149 if (rebase_status == GOT_STATUS_CONFLICT) {
7150 error = show_rebase_merge_conflict(qid->id, repo);
7151 if (error)
7152 goto done;
7153 got_worktree_rebase_pathlist_free(&merged_paths);
7154 break;
7157 error = rebase_commit(&merged_paths, worktree, fileindex,
7158 tmp_branch, commit_id, repo);
7159 got_worktree_rebase_pathlist_free(&merged_paths);
7160 if (error)
7161 goto done;
7164 if (rebase_status == GOT_STATUS_CONFLICT) {
7165 error = got_worktree_rebase_postpone(worktree, fileindex);
7166 if (error)
7167 goto done;
7168 error = got_error_msg(GOT_ERR_CONFLICTS,
7169 "conflicts must be resolved before rebasing can continue");
7170 } else
7171 error = rebase_complete(worktree, fileindex, branch,
7172 new_base_branch, tmp_branch, repo);
7173 done:
7174 got_object_id_queue_free(&commits);
7175 free(branch_head_commit_id);
7176 free(resume_commit_id);
7177 free(yca_id);
7178 if (commit)
7179 got_object_commit_close(commit);
7180 if (branch)
7181 got_ref_close(branch);
7182 if (new_base_branch)
7183 got_ref_close(new_base_branch);
7184 if (tmp_branch)
7185 got_ref_close(tmp_branch);
7186 if (worktree)
7187 got_worktree_close(worktree);
7188 if (repo)
7189 got_repo_close(repo);
7190 return error;
7193 __dead static void
7194 usage_histedit(void)
7196 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
7197 getprogname());
7198 exit(1);
7201 #define GOT_HISTEDIT_PICK 'p'
7202 #define GOT_HISTEDIT_EDIT 'e'
7203 #define GOT_HISTEDIT_FOLD 'f'
7204 #define GOT_HISTEDIT_DROP 'd'
7205 #define GOT_HISTEDIT_MESG 'm'
7207 static struct got_histedit_cmd {
7208 unsigned char code;
7209 const char *name;
7210 const char *desc;
7211 } got_histedit_cmds[] = {
7212 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7213 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7214 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7215 "be used" },
7216 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7217 { GOT_HISTEDIT_MESG, "mesg",
7218 "single-line log message for commit above (open editor if empty)" },
7221 struct got_histedit_list_entry {
7222 TAILQ_ENTRY(got_histedit_list_entry) entry;
7223 struct got_object_id *commit_id;
7224 const struct got_histedit_cmd *cmd;
7225 char *logmsg;
7227 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7229 static const struct got_error *
7230 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7231 FILE *f, struct got_repository *repo)
7233 const struct got_error *err = NULL;
7234 char *logmsg = NULL, *id_str = NULL;
7235 struct got_commit_object *commit = NULL;
7236 int n;
7238 err = got_object_open_as_commit(&commit, repo, commit_id);
7239 if (err)
7240 goto done;
7242 err = get_short_logmsg(&logmsg, 34, commit);
7243 if (err)
7244 goto done;
7246 err = got_object_id_str(&id_str, commit_id);
7247 if (err)
7248 goto done;
7250 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7251 if (n < 0)
7252 err = got_ferror(f, GOT_ERR_IO);
7253 done:
7254 if (commit)
7255 got_object_commit_close(commit);
7256 free(id_str);
7257 free(logmsg);
7258 return err;
7261 static const struct got_error *
7262 histedit_write_commit_list(struct got_object_id_queue *commits,
7263 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7265 const struct got_error *err = NULL;
7266 struct got_object_qid *qid;
7268 if (SIMPLEQ_EMPTY(commits))
7269 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7271 SIMPLEQ_FOREACH(qid, commits, entry) {
7272 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7273 f, repo);
7274 if (err)
7275 break;
7276 if (edit_logmsg_only) {
7277 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7278 if (n < 0) {
7279 err = got_ferror(f, GOT_ERR_IO);
7280 break;
7285 return err;
7288 static const struct got_error *
7289 write_cmd_list(FILE *f, const char *branch_name,
7290 struct got_object_id_queue *commits)
7292 const struct got_error *err = NULL;
7293 int n, i;
7294 char *id_str;
7295 struct got_object_qid *qid;
7297 qid = SIMPLEQ_FIRST(commits);
7298 err = got_object_id_str(&id_str, qid->id);
7299 if (err)
7300 return err;
7302 n = fprintf(f,
7303 "# Editing the history of branch '%s' starting at\n"
7304 "# commit %s\n"
7305 "# Commits will be processed in order from top to "
7306 "bottom of this file.\n", branch_name, id_str);
7307 if (n < 0) {
7308 err = got_ferror(f, GOT_ERR_IO);
7309 goto done;
7312 n = fprintf(f, "# Available histedit commands:\n");
7313 if (n < 0) {
7314 err = got_ferror(f, GOT_ERR_IO);
7315 goto done;
7318 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7319 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7320 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7321 cmd->desc);
7322 if (n < 0) {
7323 err = got_ferror(f, GOT_ERR_IO);
7324 break;
7327 done:
7328 free(id_str);
7329 return err;
7332 static const struct got_error *
7333 histedit_syntax_error(int lineno)
7335 static char msg[42];
7336 int ret;
7338 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7339 lineno);
7340 if (ret == -1 || ret >= sizeof(msg))
7341 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7343 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7346 static const struct got_error *
7347 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7348 char *logmsg, struct got_repository *repo)
7350 const struct got_error *err;
7351 struct got_commit_object *folded_commit = NULL;
7352 char *id_str, *folded_logmsg = NULL;
7354 err = got_object_id_str(&id_str, hle->commit_id);
7355 if (err)
7356 return err;
7358 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7359 if (err)
7360 goto done;
7362 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7363 if (err)
7364 goto done;
7365 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7366 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7367 folded_logmsg) == -1) {
7368 err = got_error_from_errno("asprintf");
7370 done:
7371 if (folded_commit)
7372 got_object_commit_close(folded_commit);
7373 free(id_str);
7374 free(folded_logmsg);
7375 return err;
7378 static struct got_histedit_list_entry *
7379 get_folded_commits(struct got_histedit_list_entry *hle)
7381 struct got_histedit_list_entry *prev, *folded = NULL;
7383 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7384 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7385 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7386 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7387 folded = prev;
7388 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7391 return folded;
7394 static const struct got_error *
7395 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7396 struct got_repository *repo)
7398 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7399 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7400 const struct got_error *err = NULL;
7401 struct got_commit_object *commit = NULL;
7402 int fd;
7403 struct got_histedit_list_entry *folded = NULL;
7405 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7406 if (err)
7407 return err;
7409 folded = get_folded_commits(hle);
7410 if (folded) {
7411 while (folded != hle) {
7412 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7413 folded = TAILQ_NEXT(folded, entry);
7414 continue;
7416 err = append_folded_commit_msg(&new_msg, folded,
7417 logmsg, repo);
7418 if (err)
7419 goto done;
7420 free(logmsg);
7421 logmsg = new_msg;
7422 folded = TAILQ_NEXT(folded, entry);
7426 err = got_object_id_str(&id_str, hle->commit_id);
7427 if (err)
7428 goto done;
7429 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7430 if (err)
7431 goto done;
7432 if (asprintf(&new_msg,
7433 "%s\n# original log message of commit %s: %s",
7434 logmsg ? logmsg : "", id_str, orig_logmsg) == -1) {
7435 err = got_error_from_errno("asprintf");
7436 goto done;
7438 free(logmsg);
7439 logmsg = new_msg;
7441 err = got_object_id_str(&id_str, hle->commit_id);
7442 if (err)
7443 goto done;
7445 err = got_opentemp_named_fd(&logmsg_path, &fd,
7446 GOT_TMPDIR_STR "/got-logmsg");
7447 if (err)
7448 goto done;
7450 dprintf(fd, logmsg);
7451 close(fd);
7453 err = get_editor(&editor);
7454 if (err)
7455 goto done;
7457 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
7458 if (err) {
7459 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
7460 goto done;
7461 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
7463 done:
7464 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
7465 err = got_error_from_errno2("unlink", logmsg_path);
7466 free(logmsg_path);
7467 free(logmsg);
7468 free(orig_logmsg);
7469 free(editor);
7470 if (commit)
7471 got_object_commit_close(commit);
7472 return err;
7475 static const struct got_error *
7476 histedit_parse_list(struct got_histedit_list *histedit_cmds,
7477 FILE *f, struct got_repository *repo)
7479 const struct got_error *err = NULL;
7480 char *line = NULL, *p, *end;
7481 size_t size;
7482 ssize_t len;
7483 int lineno = 0, i;
7484 const struct got_histedit_cmd *cmd;
7485 struct got_object_id *commit_id = NULL;
7486 struct got_histedit_list_entry *hle = NULL;
7488 for (;;) {
7489 len = getline(&line, &size, f);
7490 if (len == -1) {
7491 const struct got_error *getline_err;
7492 if (feof(f))
7493 break;
7494 getline_err = got_error_from_errno("getline");
7495 err = got_ferror(f, getline_err->code);
7496 break;
7498 lineno++;
7499 p = line;
7500 while (isspace((unsigned char)p[0]))
7501 p++;
7502 if (p[0] == '#' || p[0] == '\0') {
7503 free(line);
7504 line = NULL;
7505 continue;
7507 cmd = NULL;
7508 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7509 cmd = &got_histedit_cmds[i];
7510 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
7511 isspace((unsigned char)p[strlen(cmd->name)])) {
7512 p += strlen(cmd->name);
7513 break;
7515 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
7516 p++;
7517 break;
7520 if (i == nitems(got_histedit_cmds)) {
7521 err = histedit_syntax_error(lineno);
7522 break;
7524 while (isspace((unsigned char)p[0]))
7525 p++;
7526 if (cmd->code == GOT_HISTEDIT_MESG) {
7527 if (hle == NULL || hle->logmsg != NULL) {
7528 err = got_error(GOT_ERR_HISTEDIT_CMD);
7529 break;
7531 if (p[0] == '\0') {
7532 err = histedit_edit_logmsg(hle, repo);
7533 if (err)
7534 break;
7535 } else {
7536 hle->logmsg = strdup(p);
7537 if (hle->logmsg == NULL) {
7538 err = got_error_from_errno("strdup");
7539 break;
7542 free(line);
7543 line = NULL;
7544 continue;
7545 } else {
7546 end = p;
7547 while (end[0] && !isspace((unsigned char)end[0]))
7548 end++;
7549 *end = '\0';
7551 err = got_object_resolve_id_str(&commit_id, repo, p);
7552 if (err) {
7553 /* override error code */
7554 err = histedit_syntax_error(lineno);
7555 break;
7558 hle = malloc(sizeof(*hle));
7559 if (hle == NULL) {
7560 err = got_error_from_errno("malloc");
7561 break;
7563 hle->cmd = cmd;
7564 hle->commit_id = commit_id;
7565 hle->logmsg = NULL;
7566 commit_id = NULL;
7567 free(line);
7568 line = NULL;
7569 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
7572 free(line);
7573 free(commit_id);
7574 return err;
7577 static const struct got_error *
7578 histedit_check_script(struct got_histedit_list *histedit_cmds,
7579 struct got_object_id_queue *commits, struct got_repository *repo)
7581 const struct got_error *err = NULL;
7582 struct got_object_qid *qid;
7583 struct got_histedit_list_entry *hle;
7584 static char msg[92];
7585 char *id_str;
7587 if (TAILQ_EMPTY(histedit_cmds))
7588 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
7589 "histedit script contains no commands");
7590 if (SIMPLEQ_EMPTY(commits))
7591 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7593 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7594 struct got_histedit_list_entry *hle2;
7595 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
7596 if (hle == hle2)
7597 continue;
7598 if (got_object_id_cmp(hle->commit_id,
7599 hle2->commit_id) != 0)
7600 continue;
7601 err = got_object_id_str(&id_str, hle->commit_id);
7602 if (err)
7603 return err;
7604 snprintf(msg, sizeof(msg), "commit %s is listed "
7605 "more than once in histedit script", id_str);
7606 free(id_str);
7607 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7611 SIMPLEQ_FOREACH(qid, commits, entry) {
7612 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7613 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
7614 break;
7616 if (hle == NULL) {
7617 err = got_object_id_str(&id_str, qid->id);
7618 if (err)
7619 return err;
7620 snprintf(msg, sizeof(msg),
7621 "commit %s missing from histedit script", id_str);
7622 free(id_str);
7623 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7627 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
7628 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
7629 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
7630 "last commit in histedit script cannot be folded");
7632 return NULL;
7635 static const struct got_error *
7636 histedit_run_editor(struct got_histedit_list *histedit_cmds,
7637 const char *path, struct got_object_id_queue *commits,
7638 struct got_repository *repo)
7640 const struct got_error *err = NULL;
7641 char *editor;
7642 FILE *f = NULL;
7644 err = get_editor(&editor);
7645 if (err)
7646 return err;
7648 if (spawn_editor(editor, path) == -1) {
7649 err = got_error_from_errno("failed spawning editor");
7650 goto done;
7653 f = fopen(path, "r");
7654 if (f == NULL) {
7655 err = got_error_from_errno("fopen");
7656 goto done;
7658 err = histedit_parse_list(histedit_cmds, f, repo);
7659 if (err)
7660 goto done;
7662 err = histedit_check_script(histedit_cmds, commits, repo);
7663 done:
7664 if (f && fclose(f) != 0 && err == NULL)
7665 err = got_error_from_errno("fclose");
7666 free(editor);
7667 return err;
7670 static const struct got_error *
7671 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
7672 struct got_object_id_queue *, const char *, const char *,
7673 struct got_repository *);
7675 static const struct got_error *
7676 histedit_edit_script(struct got_histedit_list *histedit_cmds,
7677 struct got_object_id_queue *commits, const char *branch_name,
7678 int edit_logmsg_only, struct got_repository *repo)
7680 const struct got_error *err;
7681 FILE *f = NULL;
7682 char *path = NULL;
7684 err = got_opentemp_named(&path, &f, "got-histedit");
7685 if (err)
7686 return err;
7688 err = write_cmd_list(f, branch_name, commits);
7689 if (err)
7690 goto done;
7692 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
7693 if (err)
7694 goto done;
7696 if (edit_logmsg_only) {
7697 rewind(f);
7698 err = histedit_parse_list(histedit_cmds, f, repo);
7699 } else {
7700 if (fclose(f) != 0) {
7701 err = got_error_from_errno("fclose");
7702 goto done;
7704 f = NULL;
7705 err = histedit_run_editor(histedit_cmds, path, commits, repo);
7706 if (err) {
7707 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7708 err->code != GOT_ERR_HISTEDIT_CMD)
7709 goto done;
7710 err = histedit_edit_list_retry(histedit_cmds, err,
7711 commits, path, branch_name, repo);
7714 done:
7715 if (f && fclose(f) != 0 && err == NULL)
7716 err = got_error_from_errno("fclose");
7717 if (path && unlink(path) != 0 && err == NULL)
7718 err = got_error_from_errno2("unlink", path);
7719 free(path);
7720 return err;
7723 static const struct got_error *
7724 histedit_save_list(struct got_histedit_list *histedit_cmds,
7725 struct got_worktree *worktree, struct got_repository *repo)
7727 const struct got_error *err = NULL;
7728 char *path = NULL;
7729 FILE *f = NULL;
7730 struct got_histedit_list_entry *hle;
7731 struct got_commit_object *commit = NULL;
7733 err = got_worktree_get_histedit_script_path(&path, worktree);
7734 if (err)
7735 return err;
7737 f = fopen(path, "w");
7738 if (f == NULL) {
7739 err = got_error_from_errno2("fopen", path);
7740 goto done;
7742 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7743 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
7744 repo);
7745 if (err)
7746 break;
7748 if (hle->logmsg) {
7749 int n = fprintf(f, "%c %s\n",
7750 GOT_HISTEDIT_MESG, hle->logmsg);
7751 if (n < 0) {
7752 err = got_ferror(f, GOT_ERR_IO);
7753 break;
7757 done:
7758 if (f && fclose(f) != 0 && err == NULL)
7759 err = got_error_from_errno("fclose");
7760 free(path);
7761 if (commit)
7762 got_object_commit_close(commit);
7763 return err;
7766 void
7767 histedit_free_list(struct got_histedit_list *histedit_cmds)
7769 struct got_histedit_list_entry *hle;
7771 while ((hle = TAILQ_FIRST(histedit_cmds))) {
7772 TAILQ_REMOVE(histedit_cmds, hle, entry);
7773 free(hle);
7777 static const struct got_error *
7778 histedit_load_list(struct got_histedit_list *histedit_cmds,
7779 const char *path, struct got_repository *repo)
7781 const struct got_error *err = NULL;
7782 FILE *f = NULL;
7784 f = fopen(path, "r");
7785 if (f == NULL) {
7786 err = got_error_from_errno2("fopen", path);
7787 goto done;
7790 err = histedit_parse_list(histedit_cmds, f, repo);
7791 done:
7792 if (f && fclose(f) != 0 && err == NULL)
7793 err = got_error_from_errno("fclose");
7794 return err;
7797 static const struct got_error *
7798 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
7799 const struct got_error *edit_err, struct got_object_id_queue *commits,
7800 const char *path, const char *branch_name, struct got_repository *repo)
7802 const struct got_error *err = NULL, *prev_err = edit_err;
7803 int resp = ' ';
7805 while (resp != 'c' && resp != 'r' && resp != 'a') {
7806 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
7807 "or (a)bort: ", getprogname(), prev_err->msg);
7808 resp = getchar();
7809 if (resp == '\n')
7810 resp = getchar();
7811 if (resp == 'c') {
7812 histedit_free_list(histedit_cmds);
7813 err = histedit_run_editor(histedit_cmds, path, commits,
7814 repo);
7815 if (err) {
7816 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7817 err->code != GOT_ERR_HISTEDIT_CMD)
7818 break;
7819 prev_err = err;
7820 resp = ' ';
7821 continue;
7823 break;
7824 } else if (resp == 'r') {
7825 histedit_free_list(histedit_cmds);
7826 err = histedit_edit_script(histedit_cmds,
7827 commits, branch_name, 0, repo);
7828 if (err) {
7829 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7830 err->code != GOT_ERR_HISTEDIT_CMD)
7831 break;
7832 prev_err = err;
7833 resp = ' ';
7834 continue;
7836 break;
7837 } else if (resp == 'a') {
7838 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
7839 break;
7840 } else
7841 printf("invalid response '%c'\n", resp);
7844 return err;
7847 static const struct got_error *
7848 histedit_complete(struct got_worktree *worktree,
7849 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
7850 struct got_reference *branch, struct got_repository *repo)
7852 printf("Switching work tree to %s\n",
7853 got_ref_get_symref_target(branch));
7854 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
7855 branch, repo);
7858 static const struct got_error *
7859 show_histedit_progress(struct got_commit_object *commit,
7860 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
7862 const struct got_error *err;
7863 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7865 err = got_object_id_str(&old_id_str, hle->commit_id);
7866 if (err)
7867 goto done;
7869 if (new_id) {
7870 err = got_object_id_str(&new_id_str, new_id);
7871 if (err)
7872 goto done;
7875 old_id_str[12] = '\0';
7876 if (new_id_str)
7877 new_id_str[12] = '\0';
7879 if (hle->logmsg) {
7880 logmsg = strdup(hle->logmsg);
7881 if (logmsg == NULL) {
7882 err = got_error_from_errno("strdup");
7883 goto done;
7885 trim_logmsg(logmsg, 42);
7886 } else {
7887 err = get_short_logmsg(&logmsg, 42, commit);
7888 if (err)
7889 goto done;
7892 switch (hle->cmd->code) {
7893 case GOT_HISTEDIT_PICK:
7894 case GOT_HISTEDIT_EDIT:
7895 printf("%s -> %s: %s\n", old_id_str,
7896 new_id_str ? new_id_str : "no-op change", logmsg);
7897 break;
7898 case GOT_HISTEDIT_DROP:
7899 case GOT_HISTEDIT_FOLD:
7900 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
7901 logmsg);
7902 break;
7903 default:
7904 break;
7906 done:
7907 free(old_id_str);
7908 free(new_id_str);
7909 return err;
7912 static const struct got_error *
7913 histedit_commit(struct got_pathlist_head *merged_paths,
7914 struct got_worktree *worktree, struct got_fileindex *fileindex,
7915 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
7916 struct got_repository *repo)
7918 const struct got_error *err;
7919 struct got_commit_object *commit;
7920 struct got_object_id *new_commit_id;
7922 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
7923 && hle->logmsg == NULL) {
7924 err = histedit_edit_logmsg(hle, repo);
7925 if (err)
7926 return err;
7929 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7930 if (err)
7931 return err;
7933 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
7934 worktree, fileindex, tmp_branch, commit, hle->commit_id,
7935 hle->logmsg, repo);
7936 if (err) {
7937 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
7938 goto done;
7939 err = show_histedit_progress(commit, hle, NULL);
7940 } else {
7941 err = show_histedit_progress(commit, hle, new_commit_id);
7942 free(new_commit_id);
7944 done:
7945 got_object_commit_close(commit);
7946 return err;
7949 static const struct got_error *
7950 histedit_skip_commit(struct got_histedit_list_entry *hle,
7951 struct got_worktree *worktree, struct got_repository *repo)
7953 const struct got_error *error;
7954 struct got_commit_object *commit;
7956 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
7957 repo);
7958 if (error)
7959 return error;
7961 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
7962 if (error)
7963 return error;
7965 error = show_histedit_progress(commit, hle, NULL);
7966 got_object_commit_close(commit);
7967 return error;
7970 static const struct got_error *
7971 check_local_changes(void *arg, unsigned char status,
7972 unsigned char staged_status, const char *path,
7973 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
7974 struct got_object_id *commit_id, int dirfd, const char *de_name)
7976 int *have_local_changes = arg;
7978 switch (status) {
7979 case GOT_STATUS_ADD:
7980 case GOT_STATUS_DELETE:
7981 case GOT_STATUS_MODIFY:
7982 case GOT_STATUS_CONFLICT:
7983 *have_local_changes = 1;
7984 return got_error(GOT_ERR_CANCELLED);
7985 default:
7986 break;
7989 switch (staged_status) {
7990 case GOT_STATUS_ADD:
7991 case GOT_STATUS_DELETE:
7992 case GOT_STATUS_MODIFY:
7993 *have_local_changes = 1;
7994 return got_error(GOT_ERR_CANCELLED);
7995 default:
7996 break;
7999 return NULL;
8002 static const struct got_error *
8003 cmd_histedit(int argc, char *argv[])
8005 const struct got_error *error = NULL;
8006 struct got_worktree *worktree = NULL;
8007 struct got_fileindex *fileindex = NULL;
8008 struct got_repository *repo = NULL;
8009 char *cwd = NULL;
8010 struct got_reference *branch = NULL;
8011 struct got_reference *tmp_branch = NULL;
8012 struct got_object_id *resume_commit_id = NULL;
8013 struct got_object_id *base_commit_id = NULL;
8014 struct got_object_id *head_commit_id = NULL;
8015 struct got_commit_object *commit = NULL;
8016 int ch, rebase_in_progress = 0;
8017 struct got_update_progress_arg upa;
8018 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8019 int edit_logmsg_only = 0;
8020 const char *edit_script_path = NULL;
8021 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8022 struct got_object_id_queue commits;
8023 struct got_pathlist_head merged_paths;
8024 const struct got_object_id_queue *parent_ids;
8025 struct got_object_qid *pid;
8026 struct got_histedit_list histedit_cmds;
8027 struct got_histedit_list_entry *hle;
8029 SIMPLEQ_INIT(&commits);
8030 TAILQ_INIT(&histedit_cmds);
8031 TAILQ_INIT(&merged_paths);
8032 memset(&upa, 0, sizeof(upa));
8034 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
8035 switch (ch) {
8036 case 'a':
8037 abort_edit = 1;
8038 break;
8039 case 'c':
8040 continue_edit = 1;
8041 break;
8042 case 'F':
8043 edit_script_path = optarg;
8044 break;
8045 case 'm':
8046 edit_logmsg_only = 1;
8047 break;
8048 default:
8049 usage_histedit();
8050 /* NOTREACHED */
8054 argc -= optind;
8055 argv += optind;
8057 #ifndef PROFILE
8058 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8059 "unveil", NULL) == -1)
8060 err(1, "pledge");
8061 #endif
8062 if (abort_edit && continue_edit)
8063 errx(1, "histedit's -a and -c options are mutually exclusive");
8064 if (edit_script_path && edit_logmsg_only)
8065 errx(1, "histedit's -F and -m options are mutually exclusive");
8066 if (abort_edit && edit_logmsg_only)
8067 errx(1, "histedit's -a and -m options are mutually exclusive");
8068 if (continue_edit && edit_logmsg_only)
8069 errx(1, "histedit's -c and -m options are mutually exclusive");
8070 if (argc != 0)
8071 usage_histedit();
8074 * This command cannot apply unveil(2) in all cases because the
8075 * user may choose to run an editor to edit the histedit script
8076 * and to edit individual commit log messages.
8077 * unveil(2) traverses exec(2); if an editor is used we have to
8078 * apply unveil after edit script and log messages have been written.
8079 * XXX TODO: Make use of unveil(2) where possible.
8082 cwd = getcwd(NULL, 0);
8083 if (cwd == NULL) {
8084 error = got_error_from_errno("getcwd");
8085 goto done;
8087 error = got_worktree_open(&worktree, cwd);
8088 if (error) {
8089 if (error->code == GOT_ERR_NOT_WORKTREE)
8090 error = wrap_not_worktree_error(error, "histedit", cwd);
8091 goto done;
8094 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8095 NULL);
8096 if (error != NULL)
8097 goto done;
8099 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8100 if (error)
8101 goto done;
8102 if (rebase_in_progress) {
8103 error = got_error(GOT_ERR_REBASING);
8104 goto done;
8107 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8108 if (error)
8109 goto done;
8111 if (edit_in_progress && edit_logmsg_only) {
8112 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8113 "histedit operation is in progress in this "
8114 "work tree and must be continued or aborted "
8115 "before the -m option can be used");
8116 goto done;
8119 if (edit_in_progress && abort_edit) {
8120 error = got_worktree_histedit_continue(&resume_commit_id,
8121 &tmp_branch, &branch, &base_commit_id, &fileindex,
8122 worktree, repo);
8123 if (error)
8124 goto done;
8125 printf("Switching work tree to %s\n",
8126 got_ref_get_symref_target(branch));
8127 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8128 branch, base_commit_id, update_progress, &upa);
8129 if (error)
8130 goto done;
8131 printf("Histedit of %s aborted\n",
8132 got_ref_get_symref_target(branch));
8133 print_update_progress_stats(&upa);
8134 goto done; /* nothing else to do */
8135 } else if (abort_edit) {
8136 error = got_error(GOT_ERR_NOT_HISTEDIT);
8137 goto done;
8140 if (continue_edit) {
8141 char *path;
8143 if (!edit_in_progress) {
8144 error = got_error(GOT_ERR_NOT_HISTEDIT);
8145 goto done;
8148 error = got_worktree_get_histedit_script_path(&path, worktree);
8149 if (error)
8150 goto done;
8152 error = histedit_load_list(&histedit_cmds, path, repo);
8153 free(path);
8154 if (error)
8155 goto done;
8157 error = got_worktree_histedit_continue(&resume_commit_id,
8158 &tmp_branch, &branch, &base_commit_id, &fileindex,
8159 worktree, repo);
8160 if (error)
8161 goto done;
8163 error = got_ref_resolve(&head_commit_id, repo, branch);
8164 if (error)
8165 goto done;
8167 error = got_object_open_as_commit(&commit, repo,
8168 head_commit_id);
8169 if (error)
8170 goto done;
8171 parent_ids = got_object_commit_get_parent_ids(commit);
8172 pid = SIMPLEQ_FIRST(parent_ids);
8173 if (pid == NULL) {
8174 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8175 goto done;
8177 error = collect_commits(&commits, head_commit_id, pid->id,
8178 base_commit_id, got_worktree_get_path_prefix(worktree),
8179 GOT_ERR_HISTEDIT_PATH, repo);
8180 got_object_commit_close(commit);
8181 commit = NULL;
8182 if (error)
8183 goto done;
8184 } else {
8185 if (edit_in_progress) {
8186 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8187 goto done;
8190 error = got_ref_open(&branch, repo,
8191 got_worktree_get_head_ref_name(worktree), 0);
8192 if (error != NULL)
8193 goto done;
8195 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8196 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8197 "will not edit commit history of a branch outside "
8198 "the \"refs/heads/\" reference namespace");
8199 goto done;
8202 error = got_ref_resolve(&head_commit_id, repo, branch);
8203 got_ref_close(branch);
8204 branch = NULL;
8205 if (error)
8206 goto done;
8208 error = got_object_open_as_commit(&commit, repo,
8209 head_commit_id);
8210 if (error)
8211 goto done;
8212 parent_ids = got_object_commit_get_parent_ids(commit);
8213 pid = SIMPLEQ_FIRST(parent_ids);
8214 if (pid == NULL) {
8215 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8216 goto done;
8218 error = collect_commits(&commits, head_commit_id, pid->id,
8219 got_worktree_get_base_commit_id(worktree),
8220 got_worktree_get_path_prefix(worktree),
8221 GOT_ERR_HISTEDIT_PATH, repo);
8222 got_object_commit_close(commit);
8223 commit = NULL;
8224 if (error)
8225 goto done;
8227 if (SIMPLEQ_EMPTY(&commits)) {
8228 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8229 goto done;
8232 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8233 &base_commit_id, &fileindex, worktree, repo);
8234 if (error)
8235 goto done;
8237 if (edit_script_path) {
8238 error = histedit_load_list(&histedit_cmds,
8239 edit_script_path, repo);
8240 if (error) {
8241 got_worktree_histedit_abort(worktree, fileindex,
8242 repo, branch, base_commit_id,
8243 update_progress, &upa);
8244 print_update_progress_stats(&upa);
8245 goto done;
8247 } else {
8248 const char *branch_name;
8249 branch_name = got_ref_get_symref_target(branch);
8250 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8251 branch_name += 11;
8252 error = histedit_edit_script(&histedit_cmds, &commits,
8253 branch_name, edit_logmsg_only, repo);
8254 if (error) {
8255 got_worktree_histedit_abort(worktree, fileindex,
8256 repo, branch, base_commit_id,
8257 update_progress, &upa);
8258 print_update_progress_stats(&upa);
8259 goto done;
8264 error = histedit_save_list(&histedit_cmds, worktree,
8265 repo);
8266 if (error) {
8267 got_worktree_histedit_abort(worktree, fileindex,
8268 repo, branch, base_commit_id,
8269 update_progress, &upa);
8270 print_update_progress_stats(&upa);
8271 goto done;
8276 error = histedit_check_script(&histedit_cmds, &commits, repo);
8277 if (error)
8278 goto done;
8280 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8281 if (resume_commit_id) {
8282 if (got_object_id_cmp(hle->commit_id,
8283 resume_commit_id) != 0)
8284 continue;
8286 resume_commit_id = NULL;
8287 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8288 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8289 error = histedit_skip_commit(hle, worktree,
8290 repo);
8291 if (error)
8292 goto done;
8293 } else {
8294 struct got_pathlist_head paths;
8295 int have_changes = 0;
8297 TAILQ_INIT(&paths);
8298 error = got_pathlist_append(&paths, "", NULL);
8299 if (error)
8300 goto done;
8301 error = got_worktree_status(worktree, &paths,
8302 repo, check_local_changes, &have_changes,
8303 check_cancelled, NULL);
8304 got_pathlist_free(&paths);
8305 if (error) {
8306 if (error->code != GOT_ERR_CANCELLED)
8307 goto done;
8308 if (sigint_received || sigpipe_received)
8309 goto done;
8311 if (have_changes) {
8312 error = histedit_commit(NULL, worktree,
8313 fileindex, tmp_branch, hle, repo);
8314 if (error)
8315 goto done;
8316 } else {
8317 error = got_object_open_as_commit(
8318 &commit, repo, hle->commit_id);
8319 if (error)
8320 goto done;
8321 error = show_histedit_progress(commit,
8322 hle, NULL);
8323 got_object_commit_close(commit);
8324 commit = NULL;
8325 if (error)
8326 goto done;
8329 continue;
8332 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8333 error = histedit_skip_commit(hle, worktree, repo);
8334 if (error)
8335 goto done;
8336 continue;
8339 error = got_object_open_as_commit(&commit, repo,
8340 hle->commit_id);
8341 if (error)
8342 goto done;
8343 parent_ids = got_object_commit_get_parent_ids(commit);
8344 pid = SIMPLEQ_FIRST(parent_ids);
8346 error = got_worktree_histedit_merge_files(&merged_paths,
8347 worktree, fileindex, pid->id, hle->commit_id, repo,
8348 update_progress, &upa, check_cancelled, NULL);
8349 if (error)
8350 goto done;
8351 got_object_commit_close(commit);
8352 commit = NULL;
8354 print_update_progress_stats(&upa);
8355 if (upa.conflicts > 0)
8356 rebase_status = GOT_STATUS_CONFLICT;
8358 if (rebase_status == GOT_STATUS_CONFLICT) {
8359 error = show_rebase_merge_conflict(hle->commit_id,
8360 repo);
8361 if (error)
8362 goto done;
8363 got_worktree_rebase_pathlist_free(&merged_paths);
8364 break;
8367 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8368 char *id_str;
8369 error = got_object_id_str(&id_str, hle->commit_id);
8370 if (error)
8371 goto done;
8372 printf("Stopping histedit for amending commit %s\n",
8373 id_str);
8374 free(id_str);
8375 got_worktree_rebase_pathlist_free(&merged_paths);
8376 error = got_worktree_histedit_postpone(worktree,
8377 fileindex);
8378 goto done;
8381 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8382 error = histedit_skip_commit(hle, worktree, repo);
8383 if (error)
8384 goto done;
8385 continue;
8388 error = histedit_commit(&merged_paths, worktree, fileindex,
8389 tmp_branch, hle, repo);
8390 got_worktree_rebase_pathlist_free(&merged_paths);
8391 if (error)
8392 goto done;
8395 if (rebase_status == GOT_STATUS_CONFLICT) {
8396 error = got_worktree_histedit_postpone(worktree, fileindex);
8397 if (error)
8398 goto done;
8399 error = got_error_msg(GOT_ERR_CONFLICTS,
8400 "conflicts must be resolved before histedit can continue");
8401 } else
8402 error = histedit_complete(worktree, fileindex, tmp_branch,
8403 branch, repo);
8404 done:
8405 got_object_id_queue_free(&commits);
8406 histedit_free_list(&histedit_cmds);
8407 free(head_commit_id);
8408 free(base_commit_id);
8409 free(resume_commit_id);
8410 if (commit)
8411 got_object_commit_close(commit);
8412 if (branch)
8413 got_ref_close(branch);
8414 if (tmp_branch)
8415 got_ref_close(tmp_branch);
8416 if (worktree)
8417 got_worktree_close(worktree);
8418 if (repo)
8419 got_repo_close(repo);
8420 return error;
8423 __dead static void
8424 usage_integrate(void)
8426 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
8427 exit(1);
8430 static const struct got_error *
8431 cmd_integrate(int argc, char *argv[])
8433 const struct got_error *error = NULL;
8434 struct got_repository *repo = NULL;
8435 struct got_worktree *worktree = NULL;
8436 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
8437 const char *branch_arg = NULL;
8438 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
8439 struct got_fileindex *fileindex = NULL;
8440 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
8441 int ch;
8442 struct got_update_progress_arg upa;
8444 while ((ch = getopt(argc, argv, "")) != -1) {
8445 switch (ch) {
8446 default:
8447 usage_integrate();
8448 /* NOTREACHED */
8452 argc -= optind;
8453 argv += optind;
8455 if (argc != 1)
8456 usage_integrate();
8457 branch_arg = argv[0];
8459 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8460 "unveil", NULL) == -1)
8461 err(1, "pledge");
8463 cwd = getcwd(NULL, 0);
8464 if (cwd == NULL) {
8465 error = got_error_from_errno("getcwd");
8466 goto done;
8469 error = got_worktree_open(&worktree, cwd);
8470 if (error) {
8471 if (error->code == GOT_ERR_NOT_WORKTREE)
8472 error = wrap_not_worktree_error(error, "integrate",
8473 cwd);
8474 goto done;
8477 error = check_rebase_or_histedit_in_progress(worktree);
8478 if (error)
8479 goto done;
8481 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8482 NULL);
8483 if (error != NULL)
8484 goto done;
8486 error = apply_unveil(got_repo_get_path(repo), 0,
8487 got_worktree_get_root_path(worktree));
8488 if (error)
8489 goto done;
8491 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
8492 error = got_error_from_errno("asprintf");
8493 goto done;
8496 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
8497 &base_branch_ref, worktree, refname, repo);
8498 if (error)
8499 goto done;
8501 refname = strdup(got_ref_get_name(branch_ref));
8502 if (refname == NULL) {
8503 error = got_error_from_errno("strdup");
8504 got_worktree_integrate_abort(worktree, fileindex, repo,
8505 branch_ref, base_branch_ref);
8506 goto done;
8508 base_refname = strdup(got_ref_get_name(base_branch_ref));
8509 if (base_refname == NULL) {
8510 error = got_error_from_errno("strdup");
8511 got_worktree_integrate_abort(worktree, fileindex, repo,
8512 branch_ref, base_branch_ref);
8513 goto done;
8516 error = got_ref_resolve(&commit_id, repo, branch_ref);
8517 if (error)
8518 goto done;
8520 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
8521 if (error)
8522 goto done;
8524 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
8525 error = got_error_msg(GOT_ERR_SAME_BRANCH,
8526 "specified branch has already been integrated");
8527 got_worktree_integrate_abort(worktree, fileindex, repo,
8528 branch_ref, base_branch_ref);
8529 goto done;
8532 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
8533 if (error) {
8534 if (error->code == GOT_ERR_ANCESTRY)
8535 error = got_error(GOT_ERR_REBASE_REQUIRED);
8536 got_worktree_integrate_abort(worktree, fileindex, repo,
8537 branch_ref, base_branch_ref);
8538 goto done;
8541 memset(&upa, 0, sizeof(upa));
8542 error = got_worktree_integrate_continue(worktree, fileindex, repo,
8543 branch_ref, base_branch_ref, update_progress, &upa,
8544 check_cancelled, NULL);
8545 if (error)
8546 goto done;
8548 printf("Integrated %s into %s\n", refname, base_refname);
8549 print_update_progress_stats(&upa);
8550 done:
8551 if (repo)
8552 got_repo_close(repo);
8553 if (worktree)
8554 got_worktree_close(worktree);
8555 free(cwd);
8556 free(base_commit_id);
8557 free(commit_id);
8558 free(refname);
8559 free(base_refname);
8560 return error;
8563 __dead static void
8564 usage_stage(void)
8566 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
8567 "[file-path ...]\n",
8568 getprogname());
8569 exit(1);
8572 static const struct got_error *
8573 print_stage(void *arg, unsigned char status, unsigned char staged_status,
8574 const char *path, struct got_object_id *blob_id,
8575 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
8576 int dirfd, const char *de_name)
8578 const struct got_error *err = NULL;
8579 char *id_str = NULL;
8581 if (staged_status != GOT_STATUS_ADD &&
8582 staged_status != GOT_STATUS_MODIFY &&
8583 staged_status != GOT_STATUS_DELETE)
8584 return NULL;
8586 if (staged_status == GOT_STATUS_ADD ||
8587 staged_status == GOT_STATUS_MODIFY)
8588 err = got_object_id_str(&id_str, staged_blob_id);
8589 else
8590 err = got_object_id_str(&id_str, blob_id);
8591 if (err)
8592 return err;
8594 printf("%s %c %s\n", id_str, staged_status, path);
8595 free(id_str);
8596 return NULL;
8599 static const struct got_error *
8600 cmd_stage(int argc, char *argv[])
8602 const struct got_error *error = NULL;
8603 struct got_repository *repo = NULL;
8604 struct got_worktree *worktree = NULL;
8605 char *cwd = NULL;
8606 struct got_pathlist_head paths;
8607 struct got_pathlist_entry *pe;
8608 int ch, list_stage = 0, pflag = 0;
8609 FILE *patch_script_file = NULL;
8610 const char *patch_script_path = NULL;
8611 struct choose_patch_arg cpa;
8613 TAILQ_INIT(&paths);
8615 while ((ch = getopt(argc, argv, "lpF:")) != -1) {
8616 switch (ch) {
8617 case 'l':
8618 list_stage = 1;
8619 break;
8620 case 'p':
8621 pflag = 1;
8622 break;
8623 case 'F':
8624 patch_script_path = optarg;
8625 break;
8626 default:
8627 usage_stage();
8628 /* NOTREACHED */
8632 argc -= optind;
8633 argv += optind;
8635 #ifndef PROFILE
8636 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8637 "unveil", NULL) == -1)
8638 err(1, "pledge");
8639 #endif
8640 if (list_stage && (pflag || patch_script_path))
8641 errx(1, "-l option cannot be used with other options");
8642 if (patch_script_path && !pflag)
8643 errx(1, "-F option can only be used together with -p option");
8645 cwd = getcwd(NULL, 0);
8646 if (cwd == NULL) {
8647 error = got_error_from_errno("getcwd");
8648 goto done;
8651 error = got_worktree_open(&worktree, cwd);
8652 if (error) {
8653 if (error->code == GOT_ERR_NOT_WORKTREE)
8654 error = wrap_not_worktree_error(error, "stage", cwd);
8655 goto done;
8658 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8659 NULL);
8660 if (error != NULL)
8661 goto done;
8663 if (patch_script_path) {
8664 patch_script_file = fopen(patch_script_path, "r");
8665 if (patch_script_file == NULL) {
8666 error = got_error_from_errno2("fopen",
8667 patch_script_path);
8668 goto done;
8671 error = apply_unveil(got_repo_get_path(repo), 0,
8672 got_worktree_get_root_path(worktree));
8673 if (error)
8674 goto done;
8676 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8677 if (error)
8678 goto done;
8680 if (list_stage)
8681 error = got_worktree_status(worktree, &paths, repo,
8682 print_stage, NULL, check_cancelled, NULL);
8683 else {
8684 cpa.patch_script_file = patch_script_file;
8685 cpa.action = "stage";
8686 error = got_worktree_stage(worktree, &paths,
8687 pflag ? NULL : print_status, NULL,
8688 pflag ? choose_patch : NULL, &cpa, repo);
8690 done:
8691 if (patch_script_file && fclose(patch_script_file) == EOF &&
8692 error == NULL)
8693 error = got_error_from_errno2("fclose", patch_script_path);
8694 if (repo)
8695 got_repo_close(repo);
8696 if (worktree)
8697 got_worktree_close(worktree);
8698 TAILQ_FOREACH(pe, &paths, entry)
8699 free((char *)pe->path);
8700 got_pathlist_free(&paths);
8701 free(cwd);
8702 return error;
8705 __dead static void
8706 usage_unstage(void)
8708 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
8709 "[file-path ...]\n",
8710 getprogname());
8711 exit(1);
8715 static const struct got_error *
8716 cmd_unstage(int argc, char *argv[])
8718 const struct got_error *error = NULL;
8719 struct got_repository *repo = NULL;
8720 struct got_worktree *worktree = NULL;
8721 char *cwd = NULL;
8722 struct got_pathlist_head paths;
8723 struct got_pathlist_entry *pe;
8724 int ch, pflag = 0;
8725 struct got_update_progress_arg upa;
8726 FILE *patch_script_file = NULL;
8727 const char *patch_script_path = NULL;
8728 struct choose_patch_arg cpa;
8730 TAILQ_INIT(&paths);
8732 while ((ch = getopt(argc, argv, "pF:")) != -1) {
8733 switch (ch) {
8734 case 'p':
8735 pflag = 1;
8736 break;
8737 case 'F':
8738 patch_script_path = optarg;
8739 break;
8740 default:
8741 usage_unstage();
8742 /* NOTREACHED */
8746 argc -= optind;
8747 argv += optind;
8749 #ifndef PROFILE
8750 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8751 "unveil", NULL) == -1)
8752 err(1, "pledge");
8753 #endif
8754 if (patch_script_path && !pflag)
8755 errx(1, "-F option can only be used together with -p option");
8757 cwd = getcwd(NULL, 0);
8758 if (cwd == NULL) {
8759 error = got_error_from_errno("getcwd");
8760 goto done;
8763 error = got_worktree_open(&worktree, cwd);
8764 if (error) {
8765 if (error->code == GOT_ERR_NOT_WORKTREE)
8766 error = wrap_not_worktree_error(error, "unstage", cwd);
8767 goto done;
8770 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8771 NULL);
8772 if (error != NULL)
8773 goto done;
8775 if (patch_script_path) {
8776 patch_script_file = fopen(patch_script_path, "r");
8777 if (patch_script_file == NULL) {
8778 error = got_error_from_errno2("fopen",
8779 patch_script_path);
8780 goto done;
8784 error = apply_unveil(got_repo_get_path(repo), 0,
8785 got_worktree_get_root_path(worktree));
8786 if (error)
8787 goto done;
8789 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8790 if (error)
8791 goto done;
8793 cpa.patch_script_file = patch_script_file;
8794 cpa.action = "unstage";
8795 memset(&upa, 0, sizeof(upa));
8796 error = got_worktree_unstage(worktree, &paths, update_progress,
8797 &upa, pflag ? choose_patch : NULL, &cpa, repo);
8798 if (!error)
8799 print_update_progress_stats(&upa);
8800 done:
8801 if (patch_script_file && fclose(patch_script_file) == EOF &&
8802 error == NULL)
8803 error = got_error_from_errno2("fclose", patch_script_path);
8804 if (repo)
8805 got_repo_close(repo);
8806 if (worktree)
8807 got_worktree_close(worktree);
8808 TAILQ_FOREACH(pe, &paths, entry)
8809 free((char *)pe->path);
8810 got_pathlist_free(&paths);
8811 free(cwd);
8812 return error;
8815 __dead static void
8816 usage_cat(void)
8818 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
8819 "arg1 [arg2 ...]\n", getprogname());
8820 exit(1);
8823 static const struct got_error *
8824 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8826 const struct got_error *err;
8827 struct got_blob_object *blob;
8829 err = got_object_open_as_blob(&blob, repo, id, 8192);
8830 if (err)
8831 return err;
8833 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
8834 got_object_blob_close(blob);
8835 return err;
8838 static const struct got_error *
8839 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8841 const struct got_error *err;
8842 struct got_tree_object *tree;
8843 int nentries, i;
8845 err = got_object_open_as_tree(&tree, repo, id);
8846 if (err)
8847 return err;
8849 nentries = got_object_tree_get_nentries(tree);
8850 for (i = 0; i < nentries; i++) {
8851 struct got_tree_entry *te;
8852 char *id_str;
8853 if (sigint_received || sigpipe_received)
8854 break;
8855 te = got_object_tree_get_entry(tree, i);
8856 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
8857 if (err)
8858 break;
8859 fprintf(outfile, "%s %.7o %s\n", id_str,
8860 got_tree_entry_get_mode(te),
8861 got_tree_entry_get_name(te));
8862 free(id_str);
8865 got_object_tree_close(tree);
8866 return err;
8869 static const struct got_error *
8870 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8872 const struct got_error *err;
8873 struct got_commit_object *commit;
8874 const struct got_object_id_queue *parent_ids;
8875 struct got_object_qid *pid;
8876 char *id_str = NULL;
8877 const char *logmsg = NULL;
8879 err = got_object_open_as_commit(&commit, repo, id);
8880 if (err)
8881 return err;
8883 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
8884 if (err)
8885 goto done;
8887 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
8888 parent_ids = got_object_commit_get_parent_ids(commit);
8889 fprintf(outfile, "numparents %d\n",
8890 got_object_commit_get_nparents(commit));
8891 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
8892 char *pid_str;
8893 err = got_object_id_str(&pid_str, pid->id);
8894 if (err)
8895 goto done;
8896 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
8897 free(pid_str);
8899 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
8900 got_object_commit_get_author(commit),
8901 got_object_commit_get_author_time(commit));
8903 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
8904 got_object_commit_get_author(commit),
8905 got_object_commit_get_committer_time(commit));
8907 logmsg = got_object_commit_get_logmsg_raw(commit);
8908 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
8909 fprintf(outfile, "%s", logmsg);
8910 done:
8911 free(id_str);
8912 got_object_commit_close(commit);
8913 return err;
8916 static const struct got_error *
8917 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8919 const struct got_error *err;
8920 struct got_tag_object *tag;
8921 char *id_str = NULL;
8922 const char *tagmsg = NULL;
8924 err = got_object_open_as_tag(&tag, repo, id);
8925 if (err)
8926 return err;
8928 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
8929 if (err)
8930 goto done;
8932 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
8934 switch (got_object_tag_get_object_type(tag)) {
8935 case GOT_OBJ_TYPE_BLOB:
8936 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8937 GOT_OBJ_LABEL_BLOB);
8938 break;
8939 case GOT_OBJ_TYPE_TREE:
8940 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8941 GOT_OBJ_LABEL_TREE);
8942 break;
8943 case GOT_OBJ_TYPE_COMMIT:
8944 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8945 GOT_OBJ_LABEL_COMMIT);
8946 break;
8947 case GOT_OBJ_TYPE_TAG:
8948 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8949 GOT_OBJ_LABEL_TAG);
8950 break;
8951 default:
8952 break;
8955 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
8956 got_object_tag_get_name(tag));
8958 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
8959 got_object_tag_get_tagger(tag),
8960 got_object_tag_get_tagger_time(tag));
8962 tagmsg = got_object_tag_get_message(tag);
8963 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
8964 fprintf(outfile, "%s", tagmsg);
8965 done:
8966 free(id_str);
8967 got_object_tag_close(tag);
8968 return err;
8971 static const struct got_error *
8972 cmd_cat(int argc, char *argv[])
8974 const struct got_error *error;
8975 struct got_repository *repo = NULL;
8976 struct got_worktree *worktree = NULL;
8977 char *cwd = NULL, *repo_path = NULL, *label = NULL;
8978 const char *commit_id_str = NULL;
8979 struct got_object_id *id = NULL, *commit_id = NULL;
8980 int ch, obj_type, i, force_path = 0;
8982 #ifndef PROFILE
8983 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8984 NULL) == -1)
8985 err(1, "pledge");
8986 #endif
8988 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
8989 switch (ch) {
8990 case 'c':
8991 commit_id_str = optarg;
8992 break;
8993 case 'r':
8994 repo_path = realpath(optarg, NULL);
8995 if (repo_path == NULL)
8996 return got_error_from_errno2("realpath",
8997 optarg);
8998 got_path_strip_trailing_slashes(repo_path);
8999 break;
9000 case 'P':
9001 force_path = 1;
9002 break;
9003 default:
9004 usage_cat();
9005 /* NOTREACHED */
9009 argc -= optind;
9010 argv += optind;
9012 cwd = getcwd(NULL, 0);
9013 if (cwd == NULL) {
9014 error = got_error_from_errno("getcwd");
9015 goto done;
9017 error = got_worktree_open(&worktree, cwd);
9018 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9019 goto done;
9020 if (worktree) {
9021 if (repo_path == NULL) {
9022 repo_path = strdup(
9023 got_worktree_get_repo_path(worktree));
9024 if (repo_path == NULL) {
9025 error = got_error_from_errno("strdup");
9026 goto done;
9031 if (repo_path == NULL) {
9032 repo_path = getcwd(NULL, 0);
9033 if (repo_path == NULL)
9034 return got_error_from_errno("getcwd");
9037 error = got_repo_open(&repo, repo_path, NULL);
9038 free(repo_path);
9039 if (error != NULL)
9040 goto done;
9042 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9043 if (error)
9044 goto done;
9046 if (commit_id_str == NULL)
9047 commit_id_str = GOT_REF_HEAD;
9048 error = got_repo_match_object_id(&commit_id, NULL,
9049 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
9050 if (error)
9051 goto done;
9053 for (i = 0; i < argc; i++) {
9054 if (force_path) {
9055 error = got_object_id_by_path(&id, repo, commit_id,
9056 argv[i]);
9057 if (error)
9058 break;
9059 } else {
9060 error = got_repo_match_object_id(&id, &label, argv[i],
9061 GOT_OBJ_TYPE_ANY, 0, repo);
9062 if (error) {
9063 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9064 error->code != GOT_ERR_NOT_REF)
9065 break;
9066 error = got_object_id_by_path(&id, repo,
9067 commit_id, argv[i]);
9068 if (error)
9069 break;
9073 error = got_object_get_type(&obj_type, repo, id);
9074 if (error)
9075 break;
9077 switch (obj_type) {
9078 case GOT_OBJ_TYPE_BLOB:
9079 error = cat_blob(id, repo, stdout);
9080 break;
9081 case GOT_OBJ_TYPE_TREE:
9082 error = cat_tree(id, repo, stdout);
9083 break;
9084 case GOT_OBJ_TYPE_COMMIT:
9085 error = cat_commit(id, repo, stdout);
9086 break;
9087 case GOT_OBJ_TYPE_TAG:
9088 error = cat_tag(id, repo, stdout);
9089 break;
9090 default:
9091 error = got_error(GOT_ERR_OBJ_TYPE);
9092 break;
9094 if (error)
9095 break;
9096 free(label);
9097 label = NULL;
9098 free(id);
9099 id = NULL;
9101 done:
9102 free(label);
9103 free(id);
9104 free(commit_id);
9105 if (worktree)
9106 got_worktree_close(worktree);
9107 if (repo) {
9108 const struct got_error *repo_error;
9109 repo_error = got_repo_close(repo);
9110 if (error == NULL)
9111 error = repo_error;
9113 return error;