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 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1181 server_path, verbosity);
1182 if (error)
1183 goto done;
1185 if (verbosity >= 0)
1186 printf("Connected to %s%s%s\n", host,
1187 port ? ":" : "", port ? port : "");
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 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1909 server_path, verbosity);
1910 if (error)
1911 goto done;
1913 if (verbosity >= 0)
1914 printf("Connected to \"%s\" %s%s%s\n", remote->name, host,
1915 port ? ":" : "", port ? port : "");
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 __dead static void
2499 usage_update(void)
2501 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2502 getprogname());
2503 exit(1);
2506 static const struct got_error *
2507 update_progress(void *arg, unsigned char status, const char *path)
2509 int *did_something = arg;
2511 if (status == GOT_STATUS_EXISTS ||
2512 status == GOT_STATUS_BASE_REF_ERR)
2513 return NULL;
2515 *did_something = 1;
2517 /* Base commit bump happens silently. */
2518 if (status == GOT_STATUS_BUMP_BASE)
2519 return NULL;
2521 while (path[0] == '/')
2522 path++;
2523 printf("%c %s\n", status, path);
2524 return NULL;
2527 static const struct got_error *
2528 switch_head_ref(struct got_reference *head_ref,
2529 struct got_object_id *commit_id, struct got_worktree *worktree,
2530 struct got_repository *repo)
2532 const struct got_error *err = NULL;
2533 char *base_id_str;
2534 int ref_has_moved = 0;
2536 /* Trivial case: switching between two different references. */
2537 if (strcmp(got_ref_get_name(head_ref),
2538 got_worktree_get_head_ref_name(worktree)) != 0) {
2539 printf("Switching work tree from %s to %s\n",
2540 got_worktree_get_head_ref_name(worktree),
2541 got_ref_get_name(head_ref));
2542 return got_worktree_set_head_ref(worktree, head_ref);
2545 err = check_linear_ancestry(commit_id,
2546 got_worktree_get_base_commit_id(worktree), 0, repo);
2547 if (err) {
2548 if (err->code != GOT_ERR_ANCESTRY)
2549 return err;
2550 ref_has_moved = 1;
2552 if (!ref_has_moved)
2553 return NULL;
2555 /* Switching to a rebased branch with the same reference name. */
2556 err = got_object_id_str(&base_id_str,
2557 got_worktree_get_base_commit_id(worktree));
2558 if (err)
2559 return err;
2560 printf("Reference %s now points at a different branch\n",
2561 got_worktree_get_head_ref_name(worktree));
2562 printf("Switching work tree from %s to %s\n", base_id_str,
2563 got_worktree_get_head_ref_name(worktree));
2564 return NULL;
2567 static const struct got_error *
2568 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2570 const struct got_error *err;
2571 int in_progress;
2573 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2574 if (err)
2575 return err;
2576 if (in_progress)
2577 return got_error(GOT_ERR_REBASING);
2579 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2580 if (err)
2581 return err;
2582 if (in_progress)
2583 return got_error(GOT_ERR_HISTEDIT_BUSY);
2585 return NULL;
2588 static const struct got_error *
2589 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2590 char *argv[], struct got_worktree *worktree)
2592 const struct got_error *err = NULL;
2593 char *path;
2594 int i;
2596 if (argc == 0) {
2597 path = strdup("");
2598 if (path == NULL)
2599 return got_error_from_errno("strdup");
2600 return got_pathlist_append(paths, path, NULL);
2603 for (i = 0; i < argc; i++) {
2604 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2605 if (err)
2606 break;
2607 err = got_pathlist_append(paths, path, NULL);
2608 if (err) {
2609 free(path);
2610 break;
2614 return err;
2617 static const struct got_error *
2618 cmd_update(int argc, char *argv[])
2620 const struct got_error *error = NULL;
2621 struct got_repository *repo = NULL;
2622 struct got_worktree *worktree = NULL;
2623 char *worktree_path = NULL;
2624 struct got_object_id *commit_id = NULL;
2625 char *commit_id_str = NULL;
2626 const char *branch_name = NULL;
2627 struct got_reference *head_ref = NULL;
2628 struct got_pathlist_head paths;
2629 struct got_pathlist_entry *pe;
2630 int ch, did_something = 0;
2632 TAILQ_INIT(&paths);
2634 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2635 switch (ch) {
2636 case 'b':
2637 branch_name = optarg;
2638 break;
2639 case 'c':
2640 commit_id_str = strdup(optarg);
2641 if (commit_id_str == NULL)
2642 return got_error_from_errno("strdup");
2643 break;
2644 default:
2645 usage_update();
2646 /* NOTREACHED */
2650 argc -= optind;
2651 argv += optind;
2653 #ifndef PROFILE
2654 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2655 "unveil", NULL) == -1)
2656 err(1, "pledge");
2657 #endif
2658 worktree_path = getcwd(NULL, 0);
2659 if (worktree_path == NULL) {
2660 error = got_error_from_errno("getcwd");
2661 goto done;
2663 error = got_worktree_open(&worktree, worktree_path);
2664 if (error)
2665 goto done;
2667 error = check_rebase_or_histedit_in_progress(worktree);
2668 if (error)
2669 goto done;
2671 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
2672 NULL);
2673 if (error != NULL)
2674 goto done;
2676 error = apply_unveil(got_repo_get_path(repo), 0,
2677 got_worktree_get_root_path(worktree));
2678 if (error)
2679 goto done;
2681 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2682 if (error)
2683 goto done;
2685 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
2686 got_worktree_get_head_ref_name(worktree), 0);
2687 if (error != NULL)
2688 goto done;
2689 if (commit_id_str == NULL) {
2690 error = got_ref_resolve(&commit_id, repo, head_ref);
2691 if (error != NULL)
2692 goto done;
2693 error = got_object_id_str(&commit_id_str, commit_id);
2694 if (error != NULL)
2695 goto done;
2696 } else {
2697 error = got_repo_match_object_id(&commit_id, NULL,
2698 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2699 free(commit_id_str);
2700 commit_id_str = NULL;
2701 if (error)
2702 goto done;
2703 error = got_object_id_str(&commit_id_str, commit_id);
2704 if (error)
2705 goto done;
2708 if (branch_name) {
2709 struct got_object_id *head_commit_id;
2710 TAILQ_FOREACH(pe, &paths, entry) {
2711 if (pe->path_len == 0)
2712 continue;
2713 error = got_error_msg(GOT_ERR_BAD_PATH,
2714 "switching between branches requires that "
2715 "the entire work tree gets updated");
2716 goto done;
2718 error = got_ref_resolve(&head_commit_id, repo, head_ref);
2719 if (error)
2720 goto done;
2721 error = check_linear_ancestry(commit_id, head_commit_id, 0,
2722 repo);
2723 free(head_commit_id);
2724 if (error != NULL)
2725 goto done;
2726 error = check_same_branch(commit_id, head_ref, NULL, repo);
2727 if (error)
2728 goto done;
2729 error = switch_head_ref(head_ref, commit_id, worktree, repo);
2730 if (error)
2731 goto done;
2732 } else {
2733 error = check_linear_ancestry(commit_id,
2734 got_worktree_get_base_commit_id(worktree), 0, repo);
2735 if (error != NULL) {
2736 if (error->code == GOT_ERR_ANCESTRY)
2737 error = got_error(GOT_ERR_BRANCH_MOVED);
2738 goto done;
2740 error = check_same_branch(commit_id, head_ref, NULL, repo);
2741 if (error)
2742 goto done;
2745 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
2746 commit_id) != 0) {
2747 error = got_worktree_set_base_commit_id(worktree, repo,
2748 commit_id);
2749 if (error)
2750 goto done;
2753 error = got_worktree_checkout_files(worktree, &paths, repo,
2754 update_progress, &did_something, check_cancelled, NULL);
2755 if (error != NULL)
2756 goto done;
2758 if (did_something)
2759 printf("Updated to commit %s\n", commit_id_str);
2760 else
2761 printf("Already up-to-date\n");
2762 done:
2763 free(worktree_path);
2764 TAILQ_FOREACH(pe, &paths, entry)
2765 free((char *)pe->path);
2766 got_pathlist_free(&paths);
2767 free(commit_id);
2768 free(commit_id_str);
2769 return error;
2772 static const struct got_error *
2773 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
2774 const char *path, int diff_context, int ignore_whitespace,
2775 struct got_repository *repo)
2777 const struct got_error *err = NULL;
2778 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
2780 if (blob_id1) {
2781 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
2782 if (err)
2783 goto done;
2786 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
2787 if (err)
2788 goto done;
2790 while (path[0] == '/')
2791 path++;
2792 err = got_diff_blob(blob1, blob2, path, path, diff_context,
2793 ignore_whitespace, stdout);
2794 done:
2795 if (blob1)
2796 got_object_blob_close(blob1);
2797 got_object_blob_close(blob2);
2798 return err;
2801 static const struct got_error *
2802 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
2803 const char *path, int diff_context, int ignore_whitespace,
2804 struct got_repository *repo)
2806 const struct got_error *err = NULL;
2807 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
2808 struct got_diff_blob_output_unidiff_arg arg;
2810 if (tree_id1) {
2811 err = got_object_open_as_tree(&tree1, repo, tree_id1);
2812 if (err)
2813 goto done;
2816 err = got_object_open_as_tree(&tree2, repo, tree_id2);
2817 if (err)
2818 goto done;
2820 arg.diff_context = diff_context;
2821 arg.ignore_whitespace = ignore_whitespace;
2822 arg.outfile = stdout;
2823 while (path[0] == '/')
2824 path++;
2825 err = got_diff_tree(tree1, tree2, path, path, repo,
2826 got_diff_blob_output_unidiff, &arg, 1);
2827 done:
2828 if (tree1)
2829 got_object_tree_close(tree1);
2830 if (tree2)
2831 got_object_tree_close(tree2);
2832 return err;
2835 static const struct got_error *
2836 print_patch(struct got_commit_object *commit, struct got_object_id *id,
2837 const char *path, int diff_context, struct got_repository *repo)
2839 const struct got_error *err = NULL;
2840 struct got_commit_object *pcommit = NULL;
2841 char *id_str1 = NULL, *id_str2 = NULL;
2842 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
2843 struct got_object_qid *qid;
2845 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
2846 if (qid != NULL) {
2847 err = got_object_open_as_commit(&pcommit, repo,
2848 qid->id);
2849 if (err)
2850 return err;
2853 if (path && path[0] != '\0') {
2854 int obj_type;
2855 err = got_object_id_by_path(&obj_id2, repo, id, path);
2856 if (err)
2857 goto done;
2858 err = got_object_id_str(&id_str2, obj_id2);
2859 if (err) {
2860 free(obj_id2);
2861 goto done;
2863 if (pcommit) {
2864 err = got_object_id_by_path(&obj_id1, repo,
2865 qid->id, path);
2866 if (err) {
2867 free(obj_id2);
2868 goto done;
2870 err = got_object_id_str(&id_str1, obj_id1);
2871 if (err) {
2872 free(obj_id2);
2873 goto done;
2876 err = got_object_get_type(&obj_type, repo, obj_id2);
2877 if (err) {
2878 free(obj_id2);
2879 goto done;
2881 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2882 switch (obj_type) {
2883 case GOT_OBJ_TYPE_BLOB:
2884 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
2885 0, repo);
2886 break;
2887 case GOT_OBJ_TYPE_TREE:
2888 err = diff_trees(obj_id1, obj_id2, path, diff_context,
2889 0, repo);
2890 break;
2891 default:
2892 err = got_error(GOT_ERR_OBJ_TYPE);
2893 break;
2895 free(obj_id1);
2896 free(obj_id2);
2897 } else {
2898 obj_id2 = got_object_commit_get_tree_id(commit);
2899 err = got_object_id_str(&id_str2, obj_id2);
2900 if (err)
2901 goto done;
2902 obj_id1 = got_object_commit_get_tree_id(pcommit);
2903 err = got_object_id_str(&id_str1, obj_id1);
2904 if (err)
2905 goto done;
2906 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2907 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
2909 done:
2910 free(id_str1);
2911 free(id_str2);
2912 if (pcommit)
2913 got_object_commit_close(pcommit);
2914 return err;
2917 static char *
2918 get_datestr(time_t *time, char *datebuf)
2920 struct tm mytm, *tm;
2921 char *p, *s;
2923 tm = gmtime_r(time, &mytm);
2924 if (tm == NULL)
2925 return NULL;
2926 s = asctime_r(tm, datebuf);
2927 if (s == NULL)
2928 return NULL;
2929 p = strchr(s, '\n');
2930 if (p)
2931 *p = '\0';
2932 return s;
2935 static const struct got_error *
2936 match_logmsg(int *have_match, struct got_object_id *id,
2937 struct got_commit_object *commit, regex_t *regex)
2939 const struct got_error *err = NULL;
2940 regmatch_t regmatch;
2941 char *id_str = NULL, *logmsg = NULL;
2943 *have_match = 0;
2945 err = got_object_id_str(&id_str, id);
2946 if (err)
2947 return err;
2949 err = got_object_commit_get_logmsg(&logmsg, commit);
2950 if (err)
2951 goto done;
2953 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2954 *have_match = 1;
2955 done:
2956 free(id_str);
2957 free(logmsg);
2958 return err;
2961 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
2963 static const struct got_error *
2964 print_commit(struct got_commit_object *commit, struct got_object_id *id,
2965 struct got_repository *repo, const char *path, int show_patch,
2966 int diff_context, struct got_reflist_head *refs)
2968 const struct got_error *err = NULL;
2969 char *id_str, *datestr, *logmsg0, *logmsg, *line;
2970 char datebuf[26];
2971 time_t committer_time;
2972 const char *author, *committer;
2973 char *refs_str = NULL;
2974 struct got_reflist_entry *re;
2976 SIMPLEQ_FOREACH(re, refs, entry) {
2977 char *s;
2978 const char *name;
2979 struct got_tag_object *tag = NULL;
2980 int cmp;
2982 name = got_ref_get_name(re->ref);
2983 if (strcmp(name, GOT_REF_HEAD) == 0)
2984 continue;
2985 if (strncmp(name, "refs/", 5) == 0)
2986 name += 5;
2987 if (strncmp(name, "got/", 4) == 0)
2988 continue;
2989 if (strncmp(name, "heads/", 6) == 0)
2990 name += 6;
2991 if (strncmp(name, "remotes/", 8) == 0)
2992 name += 8;
2993 if (strncmp(name, "tags/", 5) == 0) {
2994 err = got_object_open_as_tag(&tag, repo, re->id);
2995 if (err) {
2996 if (err->code != GOT_ERR_OBJ_TYPE)
2997 return err;
2998 /* Ref points at something other than a tag. */
2999 err = NULL;
3000 tag = NULL;
3003 cmp = got_object_id_cmp(tag ?
3004 got_object_tag_get_object_id(tag) : re->id, id);
3005 if (tag)
3006 got_object_tag_close(tag);
3007 if (cmp != 0)
3008 continue;
3009 s = refs_str;
3010 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3011 name) == -1) {
3012 err = got_error_from_errno("asprintf");
3013 free(s);
3014 return err;
3016 free(s);
3018 err = got_object_id_str(&id_str, id);
3019 if (err)
3020 return err;
3022 printf(GOT_COMMIT_SEP_STR);
3023 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3024 refs_str ? refs_str : "", refs_str ? ")" : "");
3025 free(id_str);
3026 id_str = NULL;
3027 free(refs_str);
3028 refs_str = NULL;
3029 printf("from: %s\n", got_object_commit_get_author(commit));
3030 committer_time = got_object_commit_get_committer_time(commit);
3031 datestr = get_datestr(&committer_time, datebuf);
3032 if (datestr)
3033 printf("date: %s UTC\n", datestr);
3034 author = got_object_commit_get_author(commit);
3035 committer = got_object_commit_get_committer(commit);
3036 if (strcmp(author, committer) != 0)
3037 printf("via: %s\n", committer);
3038 if (got_object_commit_get_nparents(commit) > 1) {
3039 const struct got_object_id_queue *parent_ids;
3040 struct got_object_qid *qid;
3041 int n = 1;
3042 parent_ids = got_object_commit_get_parent_ids(commit);
3043 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3044 err = got_object_id_str(&id_str, qid->id);
3045 if (err)
3046 return err;
3047 printf("parent %d: %s\n", n++, id_str);
3048 free(id_str);
3052 err = got_object_commit_get_logmsg(&logmsg0, commit);
3053 if (err)
3054 return err;
3056 logmsg = logmsg0;
3057 do {
3058 line = strsep(&logmsg, "\n");
3059 if (line)
3060 printf(" %s\n", line);
3061 } while (line);
3062 free(logmsg0);
3064 if (show_patch) {
3065 err = print_patch(commit, id, path, diff_context, repo);
3066 if (err == 0)
3067 printf("\n");
3070 if (fflush(stdout) != 0 && err == NULL)
3071 err = got_error_from_errno("fflush");
3072 return err;
3075 static const struct got_error *
3076 print_commits(struct got_object_id *root_id, struct got_repository *repo,
3077 const char *path, int show_patch, const char *search_pattern,
3078 int diff_context, int limit, int log_branches,
3079 struct got_reflist_head *refs)
3081 const struct got_error *err;
3082 struct got_commit_graph *graph;
3083 regex_t regex;
3084 int have_match;
3086 if (search_pattern &&
3087 regcomp(&regex, search_pattern, REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3088 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3090 err = got_commit_graph_open(&graph, path, !log_branches);
3091 if (err)
3092 return err;
3093 err = got_commit_graph_iter_start(graph, root_id, repo,
3094 check_cancelled, NULL);
3095 if (err)
3096 goto done;
3097 for (;;) {
3098 struct got_commit_object *commit;
3099 struct got_object_id *id;
3101 if (sigint_received || sigpipe_received)
3102 break;
3104 err = got_commit_graph_iter_next(&id, graph, repo,
3105 check_cancelled, NULL);
3106 if (err) {
3107 if (err->code == GOT_ERR_ITER_COMPLETED)
3108 err = NULL;
3109 break;
3111 if (id == NULL)
3112 break;
3114 err = got_object_open_as_commit(&commit, repo, id);
3115 if (err)
3116 break;
3118 if (search_pattern) {
3119 err = match_logmsg(&have_match, id, commit, &regex);
3120 if (err) {
3121 got_object_commit_close(commit);
3122 break;
3124 if (have_match == 0) {
3125 got_object_commit_close(commit);
3126 continue;
3130 err = print_commit(commit, id, repo, path, show_patch,
3131 diff_context, refs);
3132 got_object_commit_close(commit);
3133 if (err || (limit && --limit == 0))
3134 break;
3136 done:
3137 if (search_pattern)
3138 regfree(&regex);
3139 got_commit_graph_close(graph);
3140 return err;
3143 __dead static void
3144 usage_log(void)
3146 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] [-p] "
3147 "[-s search-pattern] [-r repository-path] [path]\n", getprogname());
3148 exit(1);
3151 static int
3152 get_default_log_limit(void)
3154 const char *got_default_log_limit;
3155 long long n;
3156 const char *errstr;
3158 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3159 if (got_default_log_limit == NULL)
3160 return 0;
3161 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3162 if (errstr != NULL)
3163 return 0;
3164 return n;
3167 static const struct got_error *
3168 cmd_log(int argc, char *argv[])
3170 const struct got_error *error;
3171 struct got_repository *repo = NULL;
3172 struct got_worktree *worktree = NULL;
3173 struct got_commit_object *commit = NULL;
3174 struct got_object_id *id = NULL;
3175 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3176 const char *start_commit = NULL, *search_pattern = NULL;
3177 int diff_context = -1, ch;
3178 int show_patch = 0, limit = 0, log_branches = 0;
3179 const char *errstr;
3180 struct got_reflist_head refs;
3182 SIMPLEQ_INIT(&refs);
3184 #ifndef PROFILE
3185 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3186 NULL)
3187 == -1)
3188 err(1, "pledge");
3189 #endif
3191 limit = get_default_log_limit();
3193 while ((ch = getopt(argc, argv, "bpc:C:l:r:s:")) != -1) {
3194 switch (ch) {
3195 case 'p':
3196 show_patch = 1;
3197 break;
3198 case 'c':
3199 start_commit = optarg;
3200 break;
3201 case 'C':
3202 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3203 &errstr);
3204 if (errstr != NULL)
3205 err(1, "-C option %s", errstr);
3206 break;
3207 case 'l':
3208 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3209 if (errstr != NULL)
3210 err(1, "-l option %s", errstr);
3211 break;
3212 case 'b':
3213 log_branches = 1;
3214 break;
3215 case 'r':
3216 repo_path = realpath(optarg, NULL);
3217 if (repo_path == NULL)
3218 return got_error_from_errno2("realpath",
3219 optarg);
3220 got_path_strip_trailing_slashes(repo_path);
3221 break;
3222 case 's':
3223 search_pattern = optarg;
3224 break;
3225 default:
3226 usage_log();
3227 /* NOTREACHED */
3231 argc -= optind;
3232 argv += optind;
3234 if (diff_context == -1)
3235 diff_context = 3;
3236 else if (!show_patch)
3237 errx(1, "-C reguires -p");
3239 cwd = getcwd(NULL, 0);
3240 if (cwd == NULL) {
3241 error = got_error_from_errno("getcwd");
3242 goto done;
3245 error = got_worktree_open(&worktree, cwd);
3246 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3247 goto done;
3248 error = NULL;
3250 if (argc == 0) {
3251 path = strdup("");
3252 if (path == NULL) {
3253 error = got_error_from_errno("strdup");
3254 goto done;
3256 } else if (argc == 1) {
3257 if (worktree) {
3258 error = got_worktree_resolve_path(&path, worktree,
3259 argv[0]);
3260 if (error)
3261 goto done;
3262 } else {
3263 path = strdup(argv[0]);
3264 if (path == NULL) {
3265 error = got_error_from_errno("strdup");
3266 goto done;
3269 } else
3270 usage_log();
3272 if (repo_path == NULL) {
3273 repo_path = worktree ?
3274 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3276 if (repo_path == NULL) {
3277 error = got_error_from_errno("strdup");
3278 goto done;
3281 error = got_repo_open(&repo, repo_path, NULL);
3282 if (error != NULL)
3283 goto done;
3285 error = apply_unveil(got_repo_get_path(repo), 1,
3286 worktree ? got_worktree_get_root_path(worktree) : NULL);
3287 if (error)
3288 goto done;
3290 if (start_commit == NULL) {
3291 struct got_reference *head_ref;
3292 error = got_ref_open(&head_ref, repo,
3293 worktree ? got_worktree_get_head_ref_name(worktree)
3294 : GOT_REF_HEAD, 0);
3295 if (error != NULL)
3296 return error;
3297 error = got_ref_resolve(&id, repo, head_ref);
3298 got_ref_close(head_ref);
3299 if (error != NULL)
3300 return error;
3301 error = got_object_open_as_commit(&commit, repo, id);
3302 } else {
3303 struct got_reference *ref;
3304 error = got_ref_open(&ref, repo, start_commit, 0);
3305 if (error == NULL) {
3306 int obj_type;
3307 error = got_ref_resolve(&id, repo, ref);
3308 got_ref_close(ref);
3309 if (error != NULL)
3310 goto done;
3311 error = got_object_get_type(&obj_type, repo, id);
3312 if (error != NULL)
3313 goto done;
3314 if (obj_type == GOT_OBJ_TYPE_TAG) {
3315 struct got_tag_object *tag;
3316 error = got_object_open_as_tag(&tag, repo, id);
3317 if (error != NULL)
3318 goto done;
3319 if (got_object_tag_get_object_type(tag) !=
3320 GOT_OBJ_TYPE_COMMIT) {
3321 got_object_tag_close(tag);
3322 error = got_error(GOT_ERR_OBJ_TYPE);
3323 goto done;
3325 free(id);
3326 id = got_object_id_dup(
3327 got_object_tag_get_object_id(tag));
3328 if (id == NULL)
3329 error = got_error_from_errno(
3330 "got_object_id_dup");
3331 got_object_tag_close(tag);
3332 if (error)
3333 goto done;
3334 } else if (obj_type != GOT_OBJ_TYPE_COMMIT) {
3335 error = got_error(GOT_ERR_OBJ_TYPE);
3336 goto done;
3338 error = got_object_open_as_commit(&commit, repo, id);
3339 if (error != NULL)
3340 goto done;
3342 if (commit == NULL) {
3343 error = got_repo_match_object_id_prefix(&id,
3344 start_commit, GOT_OBJ_TYPE_COMMIT, repo);
3345 if (error != NULL)
3346 return error;
3349 if (error != NULL)
3350 goto done;
3352 if (worktree) {
3353 const char *prefix = got_worktree_get_path_prefix(worktree);
3354 char *p;
3355 if (asprintf(&p, "%s%s%s", prefix,
3356 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3357 error = got_error_from_errno("asprintf");
3358 goto done;
3360 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3361 free(p);
3362 } else
3363 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3364 if (error != NULL)
3365 goto done;
3366 if (in_repo_path) {
3367 free(path);
3368 path = in_repo_path;
3371 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3372 if (error)
3373 goto done;
3375 error = print_commits(id, repo, path, show_patch, search_pattern,
3376 diff_context, limit, log_branches, &refs);
3377 done:
3378 free(path);
3379 free(repo_path);
3380 free(cwd);
3381 free(id);
3382 if (worktree)
3383 got_worktree_close(worktree);
3384 if (repo) {
3385 const struct got_error *repo_error;
3386 repo_error = got_repo_close(repo);
3387 if (error == NULL)
3388 error = repo_error;
3390 got_ref_list_free(&refs);
3391 return error;
3394 __dead static void
3395 usage_diff(void)
3397 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3398 "[-w] [object1 object2 | path]\n", getprogname());
3399 exit(1);
3402 struct print_diff_arg {
3403 struct got_repository *repo;
3404 struct got_worktree *worktree;
3405 int diff_context;
3406 const char *id_str;
3407 int header_shown;
3408 int diff_staged;
3409 int ignore_whitespace;
3412 static const struct got_error *
3413 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3414 const char *path, struct got_object_id *blob_id,
3415 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3416 int dirfd, const char *de_name)
3418 struct print_diff_arg *a = arg;
3419 const struct got_error *err = NULL;
3420 struct got_blob_object *blob1 = NULL;
3421 int fd = -1;
3422 FILE *f2 = NULL;
3423 char *abspath = NULL, *label1 = NULL;
3424 struct stat sb;
3426 if (a->diff_staged) {
3427 if (staged_status != GOT_STATUS_MODIFY &&
3428 staged_status != GOT_STATUS_ADD &&
3429 staged_status != GOT_STATUS_DELETE)
3430 return NULL;
3431 } else {
3432 if (staged_status == GOT_STATUS_DELETE)
3433 return NULL;
3434 if (status == GOT_STATUS_NONEXISTENT)
3435 return got_error_set_errno(ENOENT, path);
3436 if (status != GOT_STATUS_MODIFY &&
3437 status != GOT_STATUS_ADD &&
3438 status != GOT_STATUS_DELETE &&
3439 status != GOT_STATUS_CONFLICT)
3440 return NULL;
3443 if (!a->header_shown) {
3444 printf("diff %s %s%s\n", a->id_str,
3445 got_worktree_get_root_path(a->worktree),
3446 a->diff_staged ? " (staged changes)" : "");
3447 a->header_shown = 1;
3450 if (a->diff_staged) {
3451 const char *label1 = NULL, *label2 = NULL;
3452 switch (staged_status) {
3453 case GOT_STATUS_MODIFY:
3454 label1 = path;
3455 label2 = path;
3456 break;
3457 case GOT_STATUS_ADD:
3458 label2 = path;
3459 break;
3460 case GOT_STATUS_DELETE:
3461 label1 = path;
3462 break;
3463 default:
3464 return got_error(GOT_ERR_FILE_STATUS);
3466 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
3467 label1, label2, a->diff_context, a->ignore_whitespace,
3468 a->repo, stdout);
3471 if (staged_status == GOT_STATUS_ADD ||
3472 staged_status == GOT_STATUS_MODIFY) {
3473 char *id_str;
3474 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
3475 8192);
3476 if (err)
3477 goto done;
3478 err = got_object_id_str(&id_str, staged_blob_id);
3479 if (err)
3480 goto done;
3481 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
3482 err = got_error_from_errno("asprintf");
3483 free(id_str);
3484 goto done;
3486 free(id_str);
3487 } else if (status != GOT_STATUS_ADD) {
3488 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
3489 if (err)
3490 goto done;
3493 if (status != GOT_STATUS_DELETE) {
3494 if (asprintf(&abspath, "%s/%s",
3495 got_worktree_get_root_path(a->worktree), path) == -1) {
3496 err = got_error_from_errno("asprintf");
3497 goto done;
3500 if (dirfd != -1) {
3501 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
3502 if (fd == -1) {
3503 err = got_error_from_errno2("openat", abspath);
3504 goto done;
3506 } else {
3507 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
3508 if (fd == -1) {
3509 err = got_error_from_errno2("open", abspath);
3510 goto done;
3513 if (fstat(fd, &sb) == -1) {
3514 err = got_error_from_errno2("fstat", abspath);
3515 goto done;
3517 f2 = fdopen(fd, "r");
3518 if (f2 == NULL) {
3519 err = got_error_from_errno2("fdopen", abspath);
3520 goto done;
3522 fd = -1;
3523 } else
3524 sb.st_size = 0;
3526 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
3527 a->diff_context, a->ignore_whitespace, stdout);
3528 done:
3529 if (blob1)
3530 got_object_blob_close(blob1);
3531 if (f2 && fclose(f2) == EOF && err == NULL)
3532 err = got_error_from_errno("fclose");
3533 if (fd != -1 && close(fd) == -1 && err == NULL)
3534 err = got_error_from_errno("close");
3535 free(abspath);
3536 return err;
3539 static const struct got_error *
3540 cmd_diff(int argc, char *argv[])
3542 const struct got_error *error;
3543 struct got_repository *repo = NULL;
3544 struct got_worktree *worktree = NULL;
3545 char *cwd = NULL, *repo_path = NULL;
3546 struct got_object_id *id1 = NULL, *id2 = NULL;
3547 const char *id_str1 = NULL, *id_str2 = NULL;
3548 char *label1 = NULL, *label2 = NULL;
3549 int type1, type2;
3550 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
3551 const char *errstr;
3552 char *path = NULL;
3554 #ifndef PROFILE
3555 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3556 NULL) == -1)
3557 err(1, "pledge");
3558 #endif
3560 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
3561 switch (ch) {
3562 case 'C':
3563 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3564 &errstr);
3565 if (errstr != NULL)
3566 err(1, "-C option %s", errstr);
3567 break;
3568 case 'r':
3569 repo_path = realpath(optarg, NULL);
3570 if (repo_path == NULL)
3571 return got_error_from_errno2("realpath",
3572 optarg);
3573 got_path_strip_trailing_slashes(repo_path);
3574 break;
3575 case 's':
3576 diff_staged = 1;
3577 break;
3578 case 'w':
3579 ignore_whitespace = 1;
3580 break;
3581 default:
3582 usage_diff();
3583 /* NOTREACHED */
3587 argc -= optind;
3588 argv += optind;
3590 cwd = getcwd(NULL, 0);
3591 if (cwd == NULL) {
3592 error = got_error_from_errno("getcwd");
3593 goto done;
3595 if (argc <= 1) {
3596 if (repo_path)
3597 errx(1,
3598 "-r option can't be used when diffing a work tree");
3599 error = got_worktree_open(&worktree, cwd);
3600 if (error)
3601 goto done;
3602 repo_path = strdup(got_worktree_get_repo_path(worktree));
3603 if (repo_path == NULL) {
3604 error = got_error_from_errno("strdup");
3605 goto done;
3607 if (argc == 1) {
3608 error = got_worktree_resolve_path(&path, worktree,
3609 argv[0]);
3610 if (error)
3611 goto done;
3612 } else {
3613 path = strdup("");
3614 if (path == NULL) {
3615 error = got_error_from_errno("strdup");
3616 goto done;
3619 } else if (argc == 2) {
3620 if (diff_staged)
3621 errx(1, "-s option can't be used when diffing "
3622 "objects in repository");
3623 id_str1 = argv[0];
3624 id_str2 = argv[1];
3625 if (repo_path == NULL) {
3626 error = got_worktree_open(&worktree, cwd);
3627 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3628 goto done;
3629 if (worktree) {
3630 repo_path = strdup(
3631 got_worktree_get_repo_path(worktree));
3632 if (repo_path == NULL) {
3633 error = got_error_from_errno("strdup");
3634 goto done;
3636 } else {
3637 repo_path = strdup(cwd);
3638 if (repo_path == NULL) {
3639 error = got_error_from_errno("strdup");
3640 goto done;
3644 } else
3645 usage_diff();
3647 error = got_repo_open(&repo, repo_path, NULL);
3648 free(repo_path);
3649 if (error != NULL)
3650 goto done;
3652 error = apply_unveil(got_repo_get_path(repo), 1,
3653 worktree ? got_worktree_get_root_path(worktree) : NULL);
3654 if (error)
3655 goto done;
3657 if (argc <= 1) {
3658 struct print_diff_arg arg;
3659 struct got_pathlist_head paths;
3660 char *id_str;
3662 TAILQ_INIT(&paths);
3664 error = got_object_id_str(&id_str,
3665 got_worktree_get_base_commit_id(worktree));
3666 if (error)
3667 goto done;
3668 arg.repo = repo;
3669 arg.worktree = worktree;
3670 arg.diff_context = diff_context;
3671 arg.id_str = id_str;
3672 arg.header_shown = 0;
3673 arg.diff_staged = diff_staged;
3674 arg.ignore_whitespace = ignore_whitespace;
3676 error = got_pathlist_append(&paths, path, NULL);
3677 if (error)
3678 goto done;
3680 error = got_worktree_status(worktree, &paths, repo, print_diff,
3681 &arg, check_cancelled, NULL);
3682 free(id_str);
3683 got_pathlist_free(&paths);
3684 goto done;
3687 error = got_repo_match_object_id(&id1, &label1, id_str1,
3688 GOT_OBJ_TYPE_ANY, 1, repo);
3689 if (error)
3690 goto done;
3692 error = got_repo_match_object_id(&id2, &label2, id_str2,
3693 GOT_OBJ_TYPE_ANY, 1, repo);
3694 if (error)
3695 goto done;
3697 error = got_object_get_type(&type1, repo, id1);
3698 if (error)
3699 goto done;
3701 error = got_object_get_type(&type2, repo, id2);
3702 if (error)
3703 goto done;
3705 if (type1 != type2) {
3706 error = got_error(GOT_ERR_OBJ_TYPE);
3707 goto done;
3710 switch (type1) {
3711 case GOT_OBJ_TYPE_BLOB:
3712 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
3713 diff_context, ignore_whitespace, repo, stdout);
3714 break;
3715 case GOT_OBJ_TYPE_TREE:
3716 error = got_diff_objects_as_trees(id1, id2, "", "",
3717 diff_context, ignore_whitespace, repo, stdout);
3718 break;
3719 case GOT_OBJ_TYPE_COMMIT:
3720 printf("diff %s %s\n", label1, label2);
3721 error = got_diff_objects_as_commits(id1, id2, diff_context,
3722 ignore_whitespace, repo, stdout);
3723 break;
3724 default:
3725 error = got_error(GOT_ERR_OBJ_TYPE);
3727 done:
3728 free(label1);
3729 free(label2);
3730 free(id1);
3731 free(id2);
3732 free(path);
3733 if (worktree)
3734 got_worktree_close(worktree);
3735 if (repo) {
3736 const struct got_error *repo_error;
3737 repo_error = got_repo_close(repo);
3738 if (error == NULL)
3739 error = repo_error;
3741 return error;
3744 __dead static void
3745 usage_blame(void)
3747 fprintf(stderr,
3748 "usage: %s blame [-c commit] [-r repository-path] path\n",
3749 getprogname());
3750 exit(1);
3753 struct blame_line {
3754 int annotated;
3755 char *id_str;
3756 char *committer;
3757 char datebuf[11]; /* YYYY-MM-DD + NUL */
3760 struct blame_cb_args {
3761 struct blame_line *lines;
3762 int nlines;
3763 int nlines_prec;
3764 int lineno_cur;
3765 off_t *line_offsets;
3766 FILE *f;
3767 struct got_repository *repo;
3770 static const struct got_error *
3771 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
3773 const struct got_error *err = NULL;
3774 struct blame_cb_args *a = arg;
3775 struct blame_line *bline;
3776 char *line = NULL;
3777 size_t linesize = 0;
3778 struct got_commit_object *commit = NULL;
3779 off_t offset;
3780 struct tm tm;
3781 time_t committer_time;
3783 if (nlines != a->nlines ||
3784 (lineno != -1 && lineno < 1) || lineno > a->nlines)
3785 return got_error(GOT_ERR_RANGE);
3787 if (sigint_received)
3788 return got_error(GOT_ERR_ITER_COMPLETED);
3790 if (lineno == -1)
3791 return NULL; /* no change in this commit */
3793 /* Annotate this line. */
3794 bline = &a->lines[lineno - 1];
3795 if (bline->annotated)
3796 return NULL;
3797 err = got_object_id_str(&bline->id_str, id);
3798 if (err)
3799 return err;
3801 err = got_object_open_as_commit(&commit, a->repo, id);
3802 if (err)
3803 goto done;
3805 bline->committer = strdup(got_object_commit_get_committer(commit));
3806 if (bline->committer == NULL) {
3807 err = got_error_from_errno("strdup");
3808 goto done;
3811 committer_time = got_object_commit_get_committer_time(commit);
3812 if (localtime_r(&committer_time, &tm) == NULL)
3813 return got_error_from_errno("localtime_r");
3814 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
3815 &tm) >= sizeof(bline->datebuf)) {
3816 err = got_error(GOT_ERR_NO_SPACE);
3817 goto done;
3819 bline->annotated = 1;
3821 /* Print lines annotated so far. */
3822 bline = &a->lines[a->lineno_cur - 1];
3823 if (!bline->annotated)
3824 goto done;
3826 offset = a->line_offsets[a->lineno_cur - 1];
3827 if (fseeko(a->f, offset, SEEK_SET) == -1) {
3828 err = got_error_from_errno("fseeko");
3829 goto done;
3832 while (bline->annotated) {
3833 char *smallerthan, *at, *nl, *committer;
3834 size_t len;
3836 if (getline(&line, &linesize, a->f) == -1) {
3837 if (ferror(a->f))
3838 err = got_error_from_errno("getline");
3839 break;
3842 committer = bline->committer;
3843 smallerthan = strchr(committer, '<');
3844 if (smallerthan && smallerthan[1] != '\0')
3845 committer = smallerthan + 1;
3846 at = strchr(committer, '@');
3847 if (at)
3848 *at = '\0';
3849 len = strlen(committer);
3850 if (len >= 9)
3851 committer[8] = '\0';
3853 nl = strchr(line, '\n');
3854 if (nl)
3855 *nl = '\0';
3856 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
3857 bline->id_str, bline->datebuf, committer, line);
3859 a->lineno_cur++;
3860 bline = &a->lines[a->lineno_cur - 1];
3862 done:
3863 if (commit)
3864 got_object_commit_close(commit);
3865 free(line);
3866 return err;
3869 static const struct got_error *
3870 cmd_blame(int argc, char *argv[])
3872 const struct got_error *error;
3873 struct got_repository *repo = NULL;
3874 struct got_worktree *worktree = NULL;
3875 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
3876 struct got_object_id *obj_id = NULL;
3877 struct got_object_id *commit_id = NULL;
3878 struct got_blob_object *blob = NULL;
3879 char *commit_id_str = NULL;
3880 struct blame_cb_args bca;
3881 int ch, obj_type, i;
3882 size_t filesize;
3884 memset(&bca, 0, sizeof(bca));
3886 #ifndef PROFILE
3887 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3888 NULL) == -1)
3889 err(1, "pledge");
3890 #endif
3892 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
3893 switch (ch) {
3894 case 'c':
3895 commit_id_str = optarg;
3896 break;
3897 case 'r':
3898 repo_path = realpath(optarg, NULL);
3899 if (repo_path == NULL)
3900 return got_error_from_errno2("realpath",
3901 optarg);
3902 got_path_strip_trailing_slashes(repo_path);
3903 break;
3904 default:
3905 usage_blame();
3906 /* NOTREACHED */
3910 argc -= optind;
3911 argv += optind;
3913 if (argc == 1)
3914 path = argv[0];
3915 else
3916 usage_blame();
3918 cwd = getcwd(NULL, 0);
3919 if (cwd == NULL) {
3920 error = got_error_from_errno("getcwd");
3921 goto done;
3923 if (repo_path == NULL) {
3924 error = got_worktree_open(&worktree, cwd);
3925 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3926 goto done;
3927 else
3928 error = NULL;
3929 if (worktree) {
3930 repo_path =
3931 strdup(got_worktree_get_repo_path(worktree));
3932 if (repo_path == NULL) {
3933 error = got_error_from_errno("strdup");
3934 if (error)
3935 goto done;
3937 } else {
3938 repo_path = strdup(cwd);
3939 if (repo_path == NULL) {
3940 error = got_error_from_errno("strdup");
3941 goto done;
3946 error = got_repo_open(&repo, repo_path, NULL);
3947 if (error != NULL)
3948 goto done;
3950 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
3951 if (error)
3952 goto done;
3954 if (worktree) {
3955 const char *prefix = got_worktree_get_path_prefix(worktree);
3956 char *p, *worktree_subdir = cwd +
3957 strlen(got_worktree_get_root_path(worktree));
3958 if (asprintf(&p, "%s%s%s%s%s",
3959 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
3960 worktree_subdir, worktree_subdir[0] ? "/" : "",
3961 path) == -1) {
3962 error = got_error_from_errno("asprintf");
3963 goto done;
3965 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3966 free(p);
3967 } else {
3968 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3970 if (error)
3971 goto done;
3973 if (commit_id_str == NULL) {
3974 struct got_reference *head_ref;
3975 error = got_ref_open(&head_ref, repo, worktree ?
3976 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
3977 if (error != NULL)
3978 goto done;
3979 error = got_ref_resolve(&commit_id, repo, head_ref);
3980 got_ref_close(head_ref);
3981 if (error != NULL)
3982 goto done;
3983 } else {
3984 error = got_repo_match_object_id(&commit_id, NULL,
3985 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
3986 if (error)
3987 goto done;
3990 error = got_object_id_by_path(&obj_id, repo, commit_id, in_repo_path);
3991 if (error)
3992 goto done;
3994 error = got_object_get_type(&obj_type, repo, obj_id);
3995 if (error)
3996 goto done;
3998 if (obj_type != GOT_OBJ_TYPE_BLOB) {
3999 error = got_error(GOT_ERR_OBJ_TYPE);
4000 goto done;
4003 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4004 if (error)
4005 goto done;
4006 bca.f = got_opentemp();
4007 if (bca.f == NULL) {
4008 error = got_error_from_errno("got_opentemp");
4009 goto done;
4011 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4012 &bca.line_offsets, bca.f, blob);
4013 if (error || bca.nlines == 0)
4014 goto done;
4016 /* Don't include \n at EOF in the blame line count. */
4017 if (bca.line_offsets[bca.nlines - 1] == filesize)
4018 bca.nlines--;
4020 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4021 if (bca.lines == NULL) {
4022 error = got_error_from_errno("calloc");
4023 goto done;
4025 bca.lineno_cur = 1;
4026 bca.nlines_prec = 0;
4027 i = bca.nlines;
4028 while (i > 0) {
4029 i /= 10;
4030 bca.nlines_prec++;
4032 bca.repo = repo;
4034 error = got_blame(in_repo_path, commit_id, repo, blame_cb, &bca,
4035 check_cancelled, NULL);
4036 done:
4037 free(in_repo_path);
4038 free(repo_path);
4039 free(cwd);
4040 free(commit_id);
4041 free(obj_id);
4042 if (blob)
4043 got_object_blob_close(blob);
4044 if (worktree)
4045 got_worktree_close(worktree);
4046 if (repo) {
4047 const struct got_error *repo_error;
4048 repo_error = got_repo_close(repo);
4049 if (error == NULL)
4050 error = repo_error;
4052 if (bca.lines) {
4053 for (i = 0; i < bca.nlines; i++) {
4054 struct blame_line *bline = &bca.lines[i];
4055 free(bline->id_str);
4056 free(bline->committer);
4058 free(bca.lines);
4060 free(bca.line_offsets);
4061 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4062 error = got_error_from_errno("fclose");
4063 return error;
4066 __dead static void
4067 usage_tree(void)
4069 fprintf(stderr,
4070 "usage: %s tree [-c commit] [-r repository-path] [-iR] path\n",
4071 getprogname());
4072 exit(1);
4075 static void
4076 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4077 const char *root_path)
4079 int is_root_path = (strcmp(path, root_path) == 0);
4080 const char *modestr = "";
4081 mode_t mode = got_tree_entry_get_mode(te);
4083 path += strlen(root_path);
4084 while (path[0] == '/')
4085 path++;
4087 if (got_object_tree_entry_is_submodule(te))
4088 modestr = "$";
4089 else if (S_ISLNK(mode))
4090 modestr = "@";
4091 else if (S_ISDIR(mode))
4092 modestr = "/";
4093 else if (mode & S_IXUSR)
4094 modestr = "*";
4096 printf("%s%s%s%s%s\n", id ? id : "", path,
4097 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr);
4100 static const struct got_error *
4101 print_tree(const char *path, struct got_object_id *commit_id,
4102 int show_ids, int recurse, const char *root_path,
4103 struct got_repository *repo)
4105 const struct got_error *err = NULL;
4106 struct got_object_id *tree_id = NULL;
4107 struct got_tree_object *tree = NULL;
4108 int nentries, i;
4110 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4111 if (err)
4112 goto done;
4114 err = got_object_open_as_tree(&tree, repo, tree_id);
4115 if (err)
4116 goto done;
4117 nentries = got_object_tree_get_nentries(tree);
4118 for (i = 0; i < nentries; i++) {
4119 struct got_tree_entry *te;
4120 char *id = NULL;
4122 if (sigint_received || sigpipe_received)
4123 break;
4125 te = got_object_tree_get_entry(tree, i);
4126 if (show_ids) {
4127 char *id_str;
4128 err = got_object_id_str(&id_str,
4129 got_tree_entry_get_id(te));
4130 if (err)
4131 goto done;
4132 if (asprintf(&id, "%s ", id_str) == -1) {
4133 err = got_error_from_errno("asprintf");
4134 free(id_str);
4135 goto done;
4137 free(id_str);
4139 print_entry(te, id, path, root_path);
4140 free(id);
4142 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4143 char *child_path;
4144 if (asprintf(&child_path, "%s%s%s", path,
4145 path[0] == '/' && path[1] == '\0' ? "" : "/",
4146 got_tree_entry_get_name(te)) == -1) {
4147 err = got_error_from_errno("asprintf");
4148 goto done;
4150 err = print_tree(child_path, commit_id, show_ids, 1,
4151 root_path, repo);
4152 free(child_path);
4153 if (err)
4154 goto done;
4157 done:
4158 if (tree)
4159 got_object_tree_close(tree);
4160 free(tree_id);
4161 return err;
4164 static const struct got_error *
4165 cmd_tree(int argc, char *argv[])
4167 const struct got_error *error;
4168 struct got_repository *repo = NULL;
4169 struct got_worktree *worktree = NULL;
4170 const char *path, *refname = NULL;
4171 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4172 struct got_object_id *commit_id = NULL;
4173 char *commit_id_str = NULL;
4174 int show_ids = 0, recurse = 0;
4175 int ch;
4177 #ifndef PROFILE
4178 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4179 NULL) == -1)
4180 err(1, "pledge");
4181 #endif
4183 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4184 switch (ch) {
4185 case 'c':
4186 commit_id_str = optarg;
4187 break;
4188 case 'r':
4189 repo_path = realpath(optarg, NULL);
4190 if (repo_path == NULL)
4191 return got_error_from_errno2("realpath",
4192 optarg);
4193 got_path_strip_trailing_slashes(repo_path);
4194 break;
4195 case 'i':
4196 show_ids = 1;
4197 break;
4198 case 'R':
4199 recurse = 1;
4200 break;
4201 default:
4202 usage_tree();
4203 /* NOTREACHED */
4207 argc -= optind;
4208 argv += optind;
4210 if (argc == 1)
4211 path = argv[0];
4212 else if (argc > 1)
4213 usage_tree();
4214 else
4215 path = NULL;
4217 cwd = getcwd(NULL, 0);
4218 if (cwd == NULL) {
4219 error = got_error_from_errno("getcwd");
4220 goto done;
4222 if (repo_path == NULL) {
4223 error = got_worktree_open(&worktree, cwd);
4224 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4225 goto done;
4226 else
4227 error = NULL;
4228 if (worktree) {
4229 repo_path =
4230 strdup(got_worktree_get_repo_path(worktree));
4231 if (repo_path == NULL)
4232 error = got_error_from_errno("strdup");
4233 if (error)
4234 goto done;
4235 } else {
4236 repo_path = strdup(cwd);
4237 if (repo_path == NULL) {
4238 error = got_error_from_errno("strdup");
4239 goto done;
4244 error = got_repo_open(&repo, repo_path, NULL);
4245 if (error != NULL)
4246 goto done;
4248 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4249 if (error)
4250 goto done;
4252 if (path == NULL) {
4253 if (worktree) {
4254 char *p, *worktree_subdir = cwd +
4255 strlen(got_worktree_get_root_path(worktree));
4256 if (asprintf(&p, "%s/%s",
4257 got_worktree_get_path_prefix(worktree),
4258 worktree_subdir) == -1) {
4259 error = got_error_from_errno("asprintf");
4260 goto done;
4262 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4263 free(p);
4264 if (error)
4265 goto done;
4266 } else
4267 path = "/";
4269 if (in_repo_path == NULL) {
4270 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4271 if (error != NULL)
4272 goto done;
4275 if (commit_id_str == NULL) {
4276 struct got_reference *head_ref;
4277 if (worktree)
4278 refname = got_worktree_get_head_ref_name(worktree);
4279 else
4280 refname = GOT_REF_HEAD;
4281 error = got_ref_open(&head_ref, repo, refname, 0);
4282 if (error != NULL)
4283 goto done;
4284 error = got_ref_resolve(&commit_id, repo, head_ref);
4285 got_ref_close(head_ref);
4286 if (error != NULL)
4287 goto done;
4288 } else {
4289 error = got_repo_match_object_id(&commit_id, NULL,
4290 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4291 if (error)
4292 goto done;
4295 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4296 in_repo_path, repo);
4297 done:
4298 free(in_repo_path);
4299 free(repo_path);
4300 free(cwd);
4301 free(commit_id);
4302 if (worktree)
4303 got_worktree_close(worktree);
4304 if (repo) {
4305 const struct got_error *repo_error;
4306 repo_error = got_repo_close(repo);
4307 if (error == NULL)
4308 error = repo_error;
4310 return error;
4313 __dead static void
4314 usage_status(void)
4316 fprintf(stderr, "usage: %s status [path ...]\n", getprogname());
4317 exit(1);
4320 static const struct got_error *
4321 print_status(void *arg, unsigned char status, unsigned char staged_status,
4322 const char *path, struct got_object_id *blob_id,
4323 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4324 int dirfd, const char *de_name)
4326 if (status == staged_status && (status == GOT_STATUS_DELETE))
4327 status = GOT_STATUS_NO_CHANGE;
4328 printf("%c%c %s\n", status, staged_status, path);
4329 return NULL;
4332 static const struct got_error *
4333 cmd_status(int argc, char *argv[])
4335 const struct got_error *error = NULL;
4336 struct got_repository *repo = NULL;
4337 struct got_worktree *worktree = NULL;
4338 char *cwd = NULL;
4339 struct got_pathlist_head paths;
4340 struct got_pathlist_entry *pe;
4341 int ch;
4343 TAILQ_INIT(&paths);
4345 while ((ch = getopt(argc, argv, "")) != -1) {
4346 switch (ch) {
4347 default:
4348 usage_status();
4349 /* NOTREACHED */
4353 argc -= optind;
4354 argv += optind;
4356 #ifndef PROFILE
4357 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4358 NULL) == -1)
4359 err(1, "pledge");
4360 #endif
4361 cwd = getcwd(NULL, 0);
4362 if (cwd == NULL) {
4363 error = got_error_from_errno("getcwd");
4364 goto done;
4367 error = got_worktree_open(&worktree, cwd);
4368 if (error != NULL)
4369 goto done;
4371 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4372 NULL);
4373 if (error != NULL)
4374 goto done;
4376 error = apply_unveil(got_repo_get_path(repo), 1,
4377 got_worktree_get_root_path(worktree));
4378 if (error)
4379 goto done;
4381 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
4382 if (error)
4383 goto done;
4385 error = got_worktree_status(worktree, &paths, repo, print_status, NULL,
4386 check_cancelled, NULL);
4387 done:
4388 TAILQ_FOREACH(pe, &paths, entry)
4389 free((char *)pe->path);
4390 got_pathlist_free(&paths);
4391 free(cwd);
4392 return error;
4395 __dead static void
4396 usage_ref(void)
4398 fprintf(stderr,
4399 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
4400 "[-d] [name]\n",
4401 getprogname());
4402 exit(1);
4405 static const struct got_error *
4406 list_refs(struct got_repository *repo, const char *refname)
4408 static const struct got_error *err = NULL;
4409 struct got_reflist_head refs;
4410 struct got_reflist_entry *re;
4412 SIMPLEQ_INIT(&refs);
4413 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
4414 if (err)
4415 return err;
4417 SIMPLEQ_FOREACH(re, &refs, entry) {
4418 char *refstr;
4419 refstr = got_ref_to_str(re->ref);
4420 if (refstr == NULL)
4421 return got_error_from_errno("got_ref_to_str");
4422 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
4423 free(refstr);
4426 got_ref_list_free(&refs);
4427 return NULL;
4430 static const struct got_error *
4431 delete_ref(struct got_repository *repo, const char *refname)
4433 const struct got_error *err = NULL;
4434 struct got_reference *ref;
4436 err = got_ref_open(&ref, repo, refname, 0);
4437 if (err)
4438 return err;
4440 err = got_ref_delete(ref, repo);
4441 got_ref_close(ref);
4442 return err;
4445 static const struct got_error *
4446 add_ref(struct got_repository *repo, const char *refname, const char *target)
4448 const struct got_error *err = NULL;
4449 struct got_object_id *id;
4450 struct got_reference *ref = NULL;
4453 * Don't let the user create a reference name with a leading '-'.
4454 * While technically a valid reference name, this case is usually
4455 * an unintended typo.
4457 if (refname[0] == '-')
4458 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4460 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
4461 repo);
4462 if (err) {
4463 struct got_reference *target_ref;
4465 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
4466 return err;
4467 err = got_ref_open(&target_ref, repo, target, 0);
4468 if (err)
4469 return err;
4470 err = got_ref_resolve(&id, repo, target_ref);
4471 got_ref_close(target_ref);
4472 if (err)
4473 return err;
4476 err = got_ref_alloc(&ref, refname, id);
4477 if (err)
4478 goto done;
4480 err = got_ref_write(ref, repo);
4481 done:
4482 if (ref)
4483 got_ref_close(ref);
4484 free(id);
4485 return err;
4488 static const struct got_error *
4489 add_symref(struct got_repository *repo, const char *refname, const char *target)
4491 const struct got_error *err = NULL;
4492 struct got_reference *ref = NULL;
4493 struct got_reference *target_ref = NULL;
4496 * Don't let the user create a reference name with a leading '-'.
4497 * While technically a valid reference name, this case is usually
4498 * an unintended typo.
4500 if (refname[0] == '-')
4501 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4503 err = got_ref_open(&target_ref, repo, target, 0);
4504 if (err)
4505 return err;
4507 err = got_ref_alloc_symref(&ref, refname, target_ref);
4508 if (err)
4509 goto done;
4511 err = got_ref_write(ref, repo);
4512 done:
4513 if (target_ref)
4514 got_ref_close(target_ref);
4515 if (ref)
4516 got_ref_close(ref);
4517 return err;
4520 static const struct got_error *
4521 cmd_ref(int argc, char *argv[])
4523 const struct got_error *error = NULL;
4524 struct got_repository *repo = NULL;
4525 struct got_worktree *worktree = NULL;
4526 char *cwd = NULL, *repo_path = NULL;
4527 int ch, do_list = 0, do_delete = 0;
4528 const char *obj_arg = NULL, *symref_target= NULL;
4529 char *refname = NULL;
4531 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
4532 switch (ch) {
4533 case 'c':
4534 obj_arg = optarg;
4535 break;
4536 case 'd':
4537 do_delete = 1;
4538 break;
4539 case 'r':
4540 repo_path = realpath(optarg, NULL);
4541 if (repo_path == NULL)
4542 return got_error_from_errno2("realpath",
4543 optarg);
4544 got_path_strip_trailing_slashes(repo_path);
4545 break;
4546 case 'l':
4547 do_list = 1;
4548 break;
4549 case 's':
4550 symref_target = optarg;
4551 break;
4552 default:
4553 usage_ref();
4554 /* NOTREACHED */
4558 if (obj_arg && do_list)
4559 errx(1, "-c and -l options are mutually exclusive");
4560 if (obj_arg && do_delete)
4561 errx(1, "-c and -d options are mutually exclusive");
4562 if (obj_arg && symref_target)
4563 errx(1, "-c and -s options are mutually exclusive");
4564 if (symref_target && do_delete)
4565 errx(1, "-s and -d options are mutually exclusive");
4566 if (symref_target && do_list)
4567 errx(1, "-s and -l options are mutually exclusive");
4568 if (do_delete && do_list)
4569 errx(1, "-d and -l options are mutually exclusive");
4571 argc -= optind;
4572 argv += optind;
4574 if (do_list) {
4575 if (argc != 0 && argc != 1)
4576 usage_ref();
4577 if (argc == 1) {
4578 refname = strdup(argv[0]);
4579 if (refname == NULL) {
4580 error = got_error_from_errno("strdup");
4581 goto done;
4584 } else {
4585 if (argc != 1)
4586 usage_ref();
4587 refname = strdup(argv[0]);
4588 if (refname == NULL) {
4589 error = got_error_from_errno("strdup");
4590 goto done;
4594 if (refname)
4595 got_path_strip_trailing_slashes(refname);
4597 #ifndef PROFILE
4598 if (do_list) {
4599 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4600 NULL) == -1)
4601 err(1, "pledge");
4602 } else {
4603 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4604 "sendfd unveil", NULL) == -1)
4605 err(1, "pledge");
4607 #endif
4608 cwd = getcwd(NULL, 0);
4609 if (cwd == NULL) {
4610 error = got_error_from_errno("getcwd");
4611 goto done;
4614 if (repo_path == NULL) {
4615 error = got_worktree_open(&worktree, cwd);
4616 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4617 goto done;
4618 else
4619 error = NULL;
4620 if (worktree) {
4621 repo_path =
4622 strdup(got_worktree_get_repo_path(worktree));
4623 if (repo_path == NULL)
4624 error = got_error_from_errno("strdup");
4625 if (error)
4626 goto done;
4627 } else {
4628 repo_path = strdup(cwd);
4629 if (repo_path == NULL) {
4630 error = got_error_from_errno("strdup");
4631 goto done;
4636 error = got_repo_open(&repo, repo_path, NULL);
4637 if (error != NULL)
4638 goto done;
4640 error = apply_unveil(got_repo_get_path(repo), do_list,
4641 worktree ? got_worktree_get_root_path(worktree) : NULL);
4642 if (error)
4643 goto done;
4645 if (do_list)
4646 error = list_refs(repo, refname);
4647 else if (do_delete)
4648 error = delete_ref(repo, refname);
4649 else if (symref_target)
4650 error = add_symref(repo, refname, symref_target);
4651 else {
4652 if (obj_arg == NULL)
4653 usage_ref();
4654 error = add_ref(repo, refname, obj_arg);
4656 done:
4657 free(refname);
4658 if (repo)
4659 got_repo_close(repo);
4660 if (worktree)
4661 got_worktree_close(worktree);
4662 free(cwd);
4663 free(repo_path);
4664 return error;
4667 __dead static void
4668 usage_branch(void)
4670 fprintf(stderr,
4671 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
4672 "[name]\n", getprogname());
4673 exit(1);
4676 static const struct got_error *
4677 list_branch(struct got_repository *repo, struct got_worktree *worktree,
4678 struct got_reference *ref)
4680 const struct got_error *err = NULL;
4681 const char *refname, *marker = " ";
4682 char *refstr;
4684 refname = got_ref_get_name(ref);
4685 if (worktree && strcmp(refname,
4686 got_worktree_get_head_ref_name(worktree)) == 0) {
4687 struct got_object_id *id = NULL;
4689 err = got_ref_resolve(&id, repo, ref);
4690 if (err)
4691 return err;
4692 if (got_object_id_cmp(id,
4693 got_worktree_get_base_commit_id(worktree)) == 0)
4694 marker = "* ";
4695 else
4696 marker = "~ ";
4697 free(id);
4700 if (strncmp(refname, "refs/heads/", 11) == 0)
4701 refname += 11;
4702 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4703 refname += 18;
4705 refstr = got_ref_to_str(ref);
4706 if (refstr == NULL)
4707 return got_error_from_errno("got_ref_to_str");
4709 printf("%s%s: %s\n", marker, refname, refstr);
4710 free(refstr);
4711 return NULL;
4714 static const struct got_error *
4715 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
4717 const char *refname;
4719 if (worktree == NULL)
4720 return got_error(GOT_ERR_NOT_WORKTREE);
4722 refname = got_worktree_get_head_ref_name(worktree);
4724 if (strncmp(refname, "refs/heads/", 11) == 0)
4725 refname += 11;
4726 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4727 refname += 18;
4729 printf("%s\n", refname);
4731 return NULL;
4734 static const struct got_error *
4735 list_branches(struct got_repository *repo, struct got_worktree *worktree)
4737 static const struct got_error *err = NULL;
4738 struct got_reflist_head refs;
4739 struct got_reflist_entry *re;
4740 struct got_reference *temp_ref = NULL;
4741 int rebase_in_progress, histedit_in_progress;
4743 SIMPLEQ_INIT(&refs);
4745 if (worktree) {
4746 err = got_worktree_rebase_in_progress(&rebase_in_progress,
4747 worktree);
4748 if (err)
4749 return err;
4751 err = got_worktree_histedit_in_progress(&histedit_in_progress,
4752 worktree);
4753 if (err)
4754 return err;
4756 if (rebase_in_progress || histedit_in_progress) {
4757 err = got_ref_open(&temp_ref, repo,
4758 got_worktree_get_head_ref_name(worktree), 0);
4759 if (err)
4760 return err;
4761 list_branch(repo, worktree, temp_ref);
4762 got_ref_close(temp_ref);
4766 err = got_ref_list(&refs, repo, "refs/heads",
4767 got_ref_cmp_by_name, NULL);
4768 if (err)
4769 return err;
4771 SIMPLEQ_FOREACH(re, &refs, entry)
4772 list_branch(repo, worktree, re->ref);
4774 got_ref_list_free(&refs);
4775 return NULL;
4778 static const struct got_error *
4779 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
4780 const char *branch_name)
4782 const struct got_error *err = NULL;
4783 struct got_reference *ref = NULL;
4784 char *refname;
4786 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
4787 return got_error_from_errno("asprintf");
4789 err = got_ref_open(&ref, repo, refname, 0);
4790 if (err)
4791 goto done;
4793 if (worktree &&
4794 strcmp(got_worktree_get_head_ref_name(worktree),
4795 got_ref_get_name(ref)) == 0) {
4796 err = got_error_msg(GOT_ERR_SAME_BRANCH,
4797 "will not delete this work tree's current branch");
4798 goto done;
4801 err = got_ref_delete(ref, repo);
4802 done:
4803 if (ref)
4804 got_ref_close(ref);
4805 free(refname);
4806 return err;
4809 static const struct got_error *
4810 add_branch(struct got_repository *repo, const char *branch_name,
4811 struct got_object_id *base_commit_id)
4813 const struct got_error *err = NULL;
4814 struct got_reference *ref = NULL;
4815 char *base_refname = NULL, *refname = NULL;
4818 * Don't let the user create a branch name with a leading '-'.
4819 * While technically a valid reference name, this case is usually
4820 * an unintended typo.
4822 if (branch_name[0] == '-')
4823 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
4825 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
4826 err = got_error_from_errno("asprintf");
4827 goto done;
4830 err = got_ref_open(&ref, repo, refname, 0);
4831 if (err == NULL) {
4832 err = got_error(GOT_ERR_BRANCH_EXISTS);
4833 goto done;
4834 } else if (err->code != GOT_ERR_NOT_REF)
4835 goto done;
4837 err = got_ref_alloc(&ref, refname, base_commit_id);
4838 if (err)
4839 goto done;
4841 err = got_ref_write(ref, repo);
4842 done:
4843 if (ref)
4844 got_ref_close(ref);
4845 free(base_refname);
4846 free(refname);
4847 return err;
4850 static const struct got_error *
4851 cmd_branch(int argc, char *argv[])
4853 const struct got_error *error = NULL;
4854 struct got_repository *repo = NULL;
4855 struct got_worktree *worktree = NULL;
4856 char *cwd = NULL, *repo_path = NULL;
4857 int ch, do_list = 0, do_show = 0, do_update = 1;
4858 const char *delref = NULL, *commit_id_arg = NULL;
4859 struct got_reference *ref = NULL;
4860 struct got_pathlist_head paths;
4861 struct got_pathlist_entry *pe;
4862 struct got_object_id *commit_id = NULL;
4863 char *commit_id_str = NULL;
4865 TAILQ_INIT(&paths);
4867 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
4868 switch (ch) {
4869 case 'c':
4870 commit_id_arg = optarg;
4871 break;
4872 case 'd':
4873 delref = optarg;
4874 break;
4875 case 'r':
4876 repo_path = realpath(optarg, NULL);
4877 if (repo_path == NULL)
4878 return got_error_from_errno2("realpath",
4879 optarg);
4880 got_path_strip_trailing_slashes(repo_path);
4881 break;
4882 case 'l':
4883 do_list = 1;
4884 break;
4885 case 'n':
4886 do_update = 0;
4887 break;
4888 default:
4889 usage_branch();
4890 /* NOTREACHED */
4894 if (do_list && delref)
4895 errx(1, "-l and -d options are mutually exclusive");
4897 argc -= optind;
4898 argv += optind;
4900 if (!do_list && !delref && argc == 0)
4901 do_show = 1;
4903 if ((do_list || delref || do_show) && commit_id_arg != NULL)
4904 errx(1, "-c option can only be used when creating a branch");
4906 if (do_list || delref) {
4907 if (argc > 0)
4908 usage_branch();
4909 } else if (!do_show && argc != 1)
4910 usage_branch();
4912 #ifndef PROFILE
4913 if (do_list || do_show) {
4914 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4915 NULL) == -1)
4916 err(1, "pledge");
4917 } else {
4918 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4919 "sendfd unveil", NULL) == -1)
4920 err(1, "pledge");
4922 #endif
4923 cwd = getcwd(NULL, 0);
4924 if (cwd == NULL) {
4925 error = got_error_from_errno("getcwd");
4926 goto done;
4929 if (repo_path == NULL) {
4930 error = got_worktree_open(&worktree, cwd);
4931 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4932 goto done;
4933 else
4934 error = NULL;
4935 if (worktree) {
4936 repo_path =
4937 strdup(got_worktree_get_repo_path(worktree));
4938 if (repo_path == NULL)
4939 error = got_error_from_errno("strdup");
4940 if (error)
4941 goto done;
4942 } else {
4943 repo_path = strdup(cwd);
4944 if (repo_path == NULL) {
4945 error = got_error_from_errno("strdup");
4946 goto done;
4951 error = got_repo_open(&repo, repo_path, NULL);
4952 if (error != NULL)
4953 goto done;
4955 error = apply_unveil(got_repo_get_path(repo), do_list,
4956 worktree ? got_worktree_get_root_path(worktree) : NULL);
4957 if (error)
4958 goto done;
4960 if (do_show)
4961 error = show_current_branch(repo, worktree);
4962 else if (do_list)
4963 error = list_branches(repo, worktree);
4964 else if (delref)
4965 error = delete_branch(repo, worktree, delref);
4966 else {
4967 if (commit_id_arg == NULL)
4968 commit_id_arg = worktree ?
4969 got_worktree_get_head_ref_name(worktree) :
4970 GOT_REF_HEAD;
4971 error = got_repo_match_object_id(&commit_id, NULL,
4972 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
4973 if (error)
4974 goto done;
4975 error = add_branch(repo, argv[0], commit_id);
4976 if (error)
4977 goto done;
4978 if (worktree && do_update) {
4979 int did_something = 0;
4980 char *branch_refname = NULL;
4982 error = got_object_id_str(&commit_id_str, commit_id);
4983 if (error)
4984 goto done;
4985 error = get_worktree_paths_from_argv(&paths, 0, NULL,
4986 worktree);
4987 if (error)
4988 goto done;
4989 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
4990 == -1) {
4991 error = got_error_from_errno("asprintf");
4992 goto done;
4994 error = got_ref_open(&ref, repo, branch_refname, 0);
4995 free(branch_refname);
4996 if (error)
4997 goto done;
4998 error = switch_head_ref(ref, commit_id, worktree,
4999 repo);
5000 if (error)
5001 goto done;
5002 error = got_worktree_set_base_commit_id(worktree, repo,
5003 commit_id);
5004 if (error)
5005 goto done;
5006 error = got_worktree_checkout_files(worktree, &paths,
5007 repo, update_progress, &did_something,
5008 check_cancelled, NULL);
5009 if (error)
5010 goto done;
5011 if (did_something)
5012 printf("Updated to commit %s\n", commit_id_str);
5015 done:
5016 if (ref)
5017 got_ref_close(ref);
5018 if (repo)
5019 got_repo_close(repo);
5020 if (worktree)
5021 got_worktree_close(worktree);
5022 free(cwd);
5023 free(repo_path);
5024 free(commit_id);
5025 free(commit_id_str);
5026 TAILQ_FOREACH(pe, &paths, entry)
5027 free((char *)pe->path);
5028 got_pathlist_free(&paths);
5029 return error;
5033 __dead static void
5034 usage_tag(void)
5036 fprintf(stderr,
5037 "usage: %s tag [-c commit] [-r repository] [-l] "
5038 "[-m message] name\n", getprogname());
5039 exit(1);
5042 #if 0
5043 static const struct got_error *
5044 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5046 const struct got_error *err = NULL;
5047 struct got_reflist_entry *re, *se, *new;
5048 struct got_object_id *re_id, *se_id;
5049 struct got_tag_object *re_tag, *se_tag;
5050 time_t re_time, se_time;
5052 SIMPLEQ_FOREACH(re, tags, entry) {
5053 se = SIMPLEQ_FIRST(sorted);
5054 if (se == NULL) {
5055 err = got_reflist_entry_dup(&new, re);
5056 if (err)
5057 return err;
5058 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5059 continue;
5060 } else {
5061 err = got_ref_resolve(&re_id, repo, re->ref);
5062 if (err)
5063 break;
5064 err = got_object_open_as_tag(&re_tag, repo, re_id);
5065 free(re_id);
5066 if (err)
5067 break;
5068 re_time = got_object_tag_get_tagger_time(re_tag);
5069 got_object_tag_close(re_tag);
5072 while (se) {
5073 err = got_ref_resolve(&se_id, repo, re->ref);
5074 if (err)
5075 break;
5076 err = got_object_open_as_tag(&se_tag, repo, se_id);
5077 free(se_id);
5078 if (err)
5079 break;
5080 se_time = got_object_tag_get_tagger_time(se_tag);
5081 got_object_tag_close(se_tag);
5083 if (se_time > re_time) {
5084 err = got_reflist_entry_dup(&new, re);
5085 if (err)
5086 return err;
5087 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5088 break;
5090 se = SIMPLEQ_NEXT(se, entry);
5091 continue;
5094 done:
5095 return err;
5097 #endif
5099 static const struct got_error *
5100 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5102 static const struct got_error *err = NULL;
5103 struct got_reflist_head refs;
5104 struct got_reflist_entry *re;
5106 SIMPLEQ_INIT(&refs);
5108 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5109 if (err)
5110 return err;
5112 SIMPLEQ_FOREACH(re, &refs, entry) {
5113 const char *refname;
5114 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5115 char datebuf[26];
5116 const char *tagger;
5117 time_t tagger_time;
5118 struct got_object_id *id;
5119 struct got_tag_object *tag;
5120 struct got_commit_object *commit = NULL;
5122 refname = got_ref_get_name(re->ref);
5123 if (strncmp(refname, "refs/tags/", 10) != 0)
5124 continue;
5125 refname += 10;
5126 refstr = got_ref_to_str(re->ref);
5127 if (refstr == NULL) {
5128 err = got_error_from_errno("got_ref_to_str");
5129 break;
5131 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5132 free(refstr);
5134 err = got_ref_resolve(&id, repo, re->ref);
5135 if (err)
5136 break;
5137 err = got_object_open_as_tag(&tag, repo, id);
5138 if (err) {
5139 if (err->code != GOT_ERR_OBJ_TYPE) {
5140 free(id);
5141 break;
5143 /* "lightweight" tag */
5144 err = got_object_open_as_commit(&commit, repo, id);
5145 if (err) {
5146 free(id);
5147 break;
5149 tagger = got_object_commit_get_committer(commit);
5150 tagger_time =
5151 got_object_commit_get_committer_time(commit);
5152 err = got_object_id_str(&id_str, id);
5153 free(id);
5154 if (err)
5155 break;
5156 } else {
5157 free(id);
5158 tagger = got_object_tag_get_tagger(tag);
5159 tagger_time = got_object_tag_get_tagger_time(tag);
5160 err = got_object_id_str(&id_str,
5161 got_object_tag_get_object_id(tag));
5162 if (err)
5163 break;
5165 printf("from: %s\n", tagger);
5166 datestr = get_datestr(&tagger_time, datebuf);
5167 if (datestr)
5168 printf("date: %s UTC\n", datestr);
5169 if (commit)
5170 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5171 else {
5172 switch (got_object_tag_get_object_type(tag)) {
5173 case GOT_OBJ_TYPE_BLOB:
5174 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5175 id_str);
5176 break;
5177 case GOT_OBJ_TYPE_TREE:
5178 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5179 id_str);
5180 break;
5181 case GOT_OBJ_TYPE_COMMIT:
5182 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5183 id_str);
5184 break;
5185 case GOT_OBJ_TYPE_TAG:
5186 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5187 id_str);
5188 break;
5189 default:
5190 break;
5193 free(id_str);
5194 if (commit) {
5195 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5196 if (err)
5197 break;
5198 got_object_commit_close(commit);
5199 } else {
5200 tagmsg0 = strdup(got_object_tag_get_message(tag));
5201 got_object_tag_close(tag);
5202 if (tagmsg0 == NULL) {
5203 err = got_error_from_errno("strdup");
5204 break;
5208 tagmsg = tagmsg0;
5209 do {
5210 line = strsep(&tagmsg, "\n");
5211 if (line)
5212 printf(" %s\n", line);
5213 } while (line);
5214 free(tagmsg0);
5217 got_ref_list_free(&refs);
5218 return NULL;
5221 static const struct got_error *
5222 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5223 const char *tag_name, const char *repo_path)
5225 const struct got_error *err = NULL;
5226 char *template = NULL, *initial_content = NULL;
5227 char *editor = NULL;
5228 int fd = -1;
5230 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5231 err = got_error_from_errno("asprintf");
5232 goto done;
5235 if (asprintf(&initial_content, "\n# tagging commit %s as %s\n",
5236 commit_id_str, tag_name) == -1) {
5237 err = got_error_from_errno("asprintf");
5238 goto done;
5241 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5242 if (err)
5243 goto done;
5245 dprintf(fd, initial_content);
5246 close(fd);
5248 err = get_editor(&editor);
5249 if (err)
5250 goto done;
5251 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
5252 done:
5253 free(initial_content);
5254 free(template);
5255 free(editor);
5257 /* Editor is done; we can now apply unveil(2) */
5258 if (err == NULL) {
5259 err = apply_unveil(repo_path, 0, NULL);
5260 if (err) {
5261 free(*tagmsg);
5262 *tagmsg = NULL;
5265 return err;
5268 static const struct got_error *
5269 add_tag(struct got_repository *repo, const char *tag_name,
5270 const char *commit_arg, const char *tagmsg_arg)
5272 const struct got_error *err = NULL;
5273 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5274 char *label = NULL, *commit_id_str = NULL;
5275 struct got_reference *ref = NULL;
5276 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5277 char *tagmsg_path = NULL, *tag_id_str = NULL;
5278 int preserve_tagmsg = 0;
5281 * Don't let the user create a tag name with a leading '-'.
5282 * While technically a valid reference name, this case is usually
5283 * an unintended typo.
5285 if (tag_name[0] == '-')
5286 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5288 err = get_author(&tagger, repo);
5289 if (err)
5290 return err;
5292 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5293 GOT_OBJ_TYPE_COMMIT, 1, repo);
5294 if (err)
5295 goto done;
5297 err = got_object_id_str(&commit_id_str, commit_id);
5298 if (err)
5299 goto done;
5301 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5302 refname = strdup(tag_name);
5303 if (refname == NULL) {
5304 err = got_error_from_errno("strdup");
5305 goto done;
5307 tag_name += 10;
5308 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5309 err = got_error_from_errno("asprintf");
5310 goto done;
5313 err = got_ref_open(&ref, repo, refname, 0);
5314 if (err == NULL) {
5315 err = got_error(GOT_ERR_TAG_EXISTS);
5316 goto done;
5317 } else if (err->code != GOT_ERR_NOT_REF)
5318 goto done;
5320 if (tagmsg_arg == NULL) {
5321 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5322 tag_name, got_repo_get_path(repo));
5323 if (err) {
5324 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5325 tagmsg_path != NULL)
5326 preserve_tagmsg = 1;
5327 goto done;
5331 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5332 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5333 if (err) {
5334 if (tagmsg_path)
5335 preserve_tagmsg = 1;
5336 goto done;
5339 err = got_ref_alloc(&ref, refname, tag_id);
5340 if (err) {
5341 if (tagmsg_path)
5342 preserve_tagmsg = 1;
5343 goto done;
5346 err = got_ref_write(ref, repo);
5347 if (err) {
5348 if (tagmsg_path)
5349 preserve_tagmsg = 1;
5350 goto done;
5353 err = got_object_id_str(&tag_id_str, tag_id);
5354 if (err) {
5355 if (tagmsg_path)
5356 preserve_tagmsg = 1;
5357 goto done;
5359 printf("Created tag %s\n", tag_id_str);
5360 done:
5361 if (preserve_tagmsg) {
5362 fprintf(stderr, "%s: tag message preserved in %s\n",
5363 getprogname(), tagmsg_path);
5364 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
5365 err = got_error_from_errno2("unlink", tagmsg_path);
5366 free(tag_id_str);
5367 if (ref)
5368 got_ref_close(ref);
5369 free(commit_id);
5370 free(commit_id_str);
5371 free(refname);
5372 free(tagmsg);
5373 free(tagmsg_path);
5374 free(tagger);
5375 return err;
5378 static const struct got_error *
5379 cmd_tag(int argc, char *argv[])
5381 const struct got_error *error = NULL;
5382 struct got_repository *repo = NULL;
5383 struct got_worktree *worktree = NULL;
5384 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
5385 char *gitconfig_path = NULL;
5386 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
5387 int ch, do_list = 0;
5389 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
5390 switch (ch) {
5391 case 'c':
5392 commit_id_arg = optarg;
5393 break;
5394 case 'm':
5395 tagmsg = optarg;
5396 break;
5397 case 'r':
5398 repo_path = realpath(optarg, NULL);
5399 if (repo_path == NULL)
5400 return got_error_from_errno2("realpath",
5401 optarg);
5402 got_path_strip_trailing_slashes(repo_path);
5403 break;
5404 case 'l':
5405 do_list = 1;
5406 break;
5407 default:
5408 usage_tag();
5409 /* NOTREACHED */
5413 argc -= optind;
5414 argv += optind;
5416 if (do_list) {
5417 if (commit_id_arg != NULL)
5418 errx(1,
5419 "-c option can only be used when creating a tag");
5420 if (tagmsg)
5421 errx(1, "-l and -m options are mutually exclusive");
5422 if (argc > 0)
5423 usage_tag();
5424 } else if (argc != 1)
5425 usage_tag();
5427 tag_name = argv[0];
5429 #ifndef PROFILE
5430 if (do_list) {
5431 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5432 NULL) == -1)
5433 err(1, "pledge");
5434 } else {
5435 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5436 "sendfd unveil", NULL) == -1)
5437 err(1, "pledge");
5439 #endif
5440 cwd = getcwd(NULL, 0);
5441 if (cwd == NULL) {
5442 error = got_error_from_errno("getcwd");
5443 goto done;
5446 if (repo_path == NULL) {
5447 error = got_worktree_open(&worktree, cwd);
5448 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5449 goto done;
5450 else
5451 error = NULL;
5452 if (worktree) {
5453 repo_path =
5454 strdup(got_worktree_get_repo_path(worktree));
5455 if (repo_path == NULL)
5456 error = got_error_from_errno("strdup");
5457 if (error)
5458 goto done;
5459 } else {
5460 repo_path = strdup(cwd);
5461 if (repo_path == NULL) {
5462 error = got_error_from_errno("strdup");
5463 goto done;
5468 if (do_list) {
5469 error = got_repo_open(&repo, repo_path, NULL);
5470 if (error != NULL)
5471 goto done;
5472 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5473 if (error)
5474 goto done;
5475 error = list_tags(repo, worktree);
5476 } else {
5477 error = get_gitconfig_path(&gitconfig_path);
5478 if (error)
5479 goto done;
5480 error = got_repo_open(&repo, repo_path, gitconfig_path);
5481 if (error != NULL)
5482 goto done;
5484 if (tagmsg) {
5485 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5486 if (error)
5487 goto done;
5490 if (commit_id_arg == NULL) {
5491 struct got_reference *head_ref;
5492 struct got_object_id *commit_id;
5493 error = got_ref_open(&head_ref, repo,
5494 worktree ? got_worktree_get_head_ref_name(worktree)
5495 : GOT_REF_HEAD, 0);
5496 if (error)
5497 goto done;
5498 error = got_ref_resolve(&commit_id, repo, head_ref);
5499 got_ref_close(head_ref);
5500 if (error)
5501 goto done;
5502 error = got_object_id_str(&commit_id_str, commit_id);
5503 free(commit_id);
5504 if (error)
5505 goto done;
5508 error = add_tag(repo, tag_name,
5509 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
5511 done:
5512 if (repo)
5513 got_repo_close(repo);
5514 if (worktree)
5515 got_worktree_close(worktree);
5516 free(cwd);
5517 free(repo_path);
5518 free(gitconfig_path);
5519 free(commit_id_str);
5520 return error;
5523 __dead static void
5524 usage_add(void)
5526 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
5527 getprogname());
5528 exit(1);
5531 static const struct got_error *
5532 add_progress(void *arg, unsigned char status, const char *path)
5534 while (path[0] == '/')
5535 path++;
5536 printf("%c %s\n", status, path);
5537 return NULL;
5540 static const struct got_error *
5541 cmd_add(int argc, char *argv[])
5543 const struct got_error *error = NULL;
5544 struct got_repository *repo = NULL;
5545 struct got_worktree *worktree = NULL;
5546 char *cwd = NULL;
5547 struct got_pathlist_head paths;
5548 struct got_pathlist_entry *pe;
5549 int ch, can_recurse = 0, no_ignores = 0;
5551 TAILQ_INIT(&paths);
5553 while ((ch = getopt(argc, argv, "IR")) != -1) {
5554 switch (ch) {
5555 case 'I':
5556 no_ignores = 1;
5557 break;
5558 case 'R':
5559 can_recurse = 1;
5560 break;
5561 default:
5562 usage_add();
5563 /* NOTREACHED */
5567 argc -= optind;
5568 argv += optind;
5570 #ifndef PROFILE
5571 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5572 NULL) == -1)
5573 err(1, "pledge");
5574 #endif
5575 if (argc < 1)
5576 usage_add();
5578 cwd = getcwd(NULL, 0);
5579 if (cwd == NULL) {
5580 error = got_error_from_errno("getcwd");
5581 goto done;
5584 error = got_worktree_open(&worktree, cwd);
5585 if (error)
5586 goto done;
5588 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5589 NULL);
5590 if (error != NULL)
5591 goto done;
5593 error = apply_unveil(got_repo_get_path(repo), 1,
5594 got_worktree_get_root_path(worktree));
5595 if (error)
5596 goto done;
5598 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5599 if (error)
5600 goto done;
5602 if (!can_recurse && no_ignores) {
5603 error = got_error_msg(GOT_ERR_BAD_PATH,
5604 "disregarding ignores requires -R option");
5605 goto done;
5609 if (!can_recurse) {
5610 char *ondisk_path;
5611 struct stat sb;
5612 TAILQ_FOREACH(pe, &paths, entry) {
5613 if (asprintf(&ondisk_path, "%s/%s",
5614 got_worktree_get_root_path(worktree),
5615 pe->path) == -1) {
5616 error = got_error_from_errno("asprintf");
5617 goto done;
5619 if (lstat(ondisk_path, &sb) == -1) {
5620 if (errno == ENOENT) {
5621 free(ondisk_path);
5622 continue;
5624 error = got_error_from_errno2("lstat",
5625 ondisk_path);
5626 free(ondisk_path);
5627 goto done;
5629 free(ondisk_path);
5630 if (S_ISDIR(sb.st_mode)) {
5631 error = got_error_msg(GOT_ERR_BAD_PATH,
5632 "adding directories requires -R option");
5633 goto done;
5638 error = got_worktree_schedule_add(worktree, &paths, add_progress,
5639 NULL, repo, no_ignores);
5640 done:
5641 if (repo)
5642 got_repo_close(repo);
5643 if (worktree)
5644 got_worktree_close(worktree);
5645 TAILQ_FOREACH(pe, &paths, entry)
5646 free((char *)pe->path);
5647 got_pathlist_free(&paths);
5648 free(cwd);
5649 return error;
5652 __dead static void
5653 usage_remove(void)
5655 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] path ...\n",
5656 getprogname());
5657 exit(1);
5660 static const struct got_error *
5661 print_remove_status(void *arg, unsigned char status,
5662 unsigned char staged_status, const char *path)
5664 while (path[0] == '/')
5665 path++;
5666 if (status == GOT_STATUS_NONEXISTENT)
5667 return NULL;
5668 if (status == staged_status && (status == GOT_STATUS_DELETE))
5669 status = GOT_STATUS_NO_CHANGE;
5670 printf("%c%c %s\n", status, staged_status, path);
5671 return NULL;
5674 static const struct got_error *
5675 cmd_remove(int argc, char *argv[])
5677 const struct got_error *error = NULL;
5678 struct got_worktree *worktree = NULL;
5679 struct got_repository *repo = NULL;
5680 char *cwd = NULL;
5681 struct got_pathlist_head paths;
5682 struct got_pathlist_entry *pe;
5683 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0;
5685 TAILQ_INIT(&paths);
5687 while ((ch = getopt(argc, argv, "fkR")) != -1) {
5688 switch (ch) {
5689 case 'f':
5690 delete_local_mods = 1;
5691 break;
5692 case 'k':
5693 keep_on_disk = 1;
5694 break;
5695 case 'R':
5696 can_recurse = 1;
5697 break;
5698 default:
5699 usage_remove();
5700 /* NOTREACHED */
5704 argc -= optind;
5705 argv += optind;
5707 #ifndef PROFILE
5708 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5709 NULL) == -1)
5710 err(1, "pledge");
5711 #endif
5712 if (argc < 1)
5713 usage_remove();
5715 cwd = getcwd(NULL, 0);
5716 if (cwd == NULL) {
5717 error = got_error_from_errno("getcwd");
5718 goto done;
5720 error = got_worktree_open(&worktree, cwd);
5721 if (error)
5722 goto done;
5724 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5725 NULL);
5726 if (error)
5727 goto done;
5729 error = apply_unveil(got_repo_get_path(repo), 1,
5730 got_worktree_get_root_path(worktree));
5731 if (error)
5732 goto done;
5734 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5735 if (error)
5736 goto done;
5738 if (!can_recurse) {
5739 char *ondisk_path;
5740 struct stat sb;
5741 TAILQ_FOREACH(pe, &paths, entry) {
5742 if (asprintf(&ondisk_path, "%s/%s",
5743 got_worktree_get_root_path(worktree),
5744 pe->path) == -1) {
5745 error = got_error_from_errno("asprintf");
5746 goto done;
5748 if (lstat(ondisk_path, &sb) == -1) {
5749 if (errno == ENOENT) {
5750 free(ondisk_path);
5751 continue;
5753 error = got_error_from_errno2("lstat",
5754 ondisk_path);
5755 free(ondisk_path);
5756 goto done;
5758 free(ondisk_path);
5759 if (S_ISDIR(sb.st_mode)) {
5760 error = got_error_msg(GOT_ERR_BAD_PATH,
5761 "removing directories requires -R option");
5762 goto done;
5767 error = got_worktree_schedule_delete(worktree, &paths,
5768 delete_local_mods, print_remove_status, NULL, repo, keep_on_disk);
5769 done:
5770 if (repo)
5771 got_repo_close(repo);
5772 if (worktree)
5773 got_worktree_close(worktree);
5774 TAILQ_FOREACH(pe, &paths, entry)
5775 free((char *)pe->path);
5776 got_pathlist_free(&paths);
5777 free(cwd);
5778 return error;
5781 __dead static void
5782 usage_revert(void)
5784 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
5785 "path ...\n", getprogname());
5786 exit(1);
5789 static const struct got_error *
5790 revert_progress(void *arg, unsigned char status, const char *path)
5792 if (status == GOT_STATUS_UNVERSIONED)
5793 return NULL;
5795 while (path[0] == '/')
5796 path++;
5797 printf("%c %s\n", status, path);
5798 return NULL;
5801 struct choose_patch_arg {
5802 FILE *patch_script_file;
5803 const char *action;
5806 static const struct got_error *
5807 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
5808 int nchanges, const char *action)
5810 char *line = NULL;
5811 size_t linesize = 0;
5812 ssize_t linelen;
5814 switch (status) {
5815 case GOT_STATUS_ADD:
5816 printf("A %s\n%s this addition? [y/n] ", path, action);
5817 break;
5818 case GOT_STATUS_DELETE:
5819 printf("D %s\n%s this deletion? [y/n] ", path, action);
5820 break;
5821 case GOT_STATUS_MODIFY:
5822 if (fseek(patch_file, 0L, SEEK_SET) == -1)
5823 return got_error_from_errno("fseek");
5824 printf(GOT_COMMIT_SEP_STR);
5825 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
5826 printf("%s", line);
5827 if (ferror(patch_file))
5828 return got_error_from_errno("getline");
5829 printf(GOT_COMMIT_SEP_STR);
5830 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
5831 path, n, nchanges, action);
5832 break;
5833 default:
5834 return got_error_path(path, GOT_ERR_FILE_STATUS);
5837 return NULL;
5840 static const struct got_error *
5841 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
5842 FILE *patch_file, int n, int nchanges)
5844 const struct got_error *err = NULL;
5845 char *line = NULL;
5846 size_t linesize = 0;
5847 ssize_t linelen;
5848 int resp = ' ';
5849 struct choose_patch_arg *a = arg;
5851 *choice = GOT_PATCH_CHOICE_NONE;
5853 if (a->patch_script_file) {
5854 char *nl;
5855 err = show_change(status, path, patch_file, n, nchanges,
5856 a->action);
5857 if (err)
5858 return err;
5859 linelen = getline(&line, &linesize, a->patch_script_file);
5860 if (linelen == -1) {
5861 if (ferror(a->patch_script_file))
5862 return got_error_from_errno("getline");
5863 return NULL;
5865 nl = strchr(line, '\n');
5866 if (nl)
5867 *nl = '\0';
5868 if (strcmp(line, "y") == 0) {
5869 *choice = GOT_PATCH_CHOICE_YES;
5870 printf("y\n");
5871 } else if (strcmp(line, "n") == 0) {
5872 *choice = GOT_PATCH_CHOICE_NO;
5873 printf("n\n");
5874 } else if (strcmp(line, "q") == 0 &&
5875 status == GOT_STATUS_MODIFY) {
5876 *choice = GOT_PATCH_CHOICE_QUIT;
5877 printf("q\n");
5878 } else
5879 printf("invalid response '%s'\n", line);
5880 free(line);
5881 return NULL;
5884 while (resp != 'y' && resp != 'n' && resp != 'q') {
5885 err = show_change(status, path, patch_file, n, nchanges,
5886 a->action);
5887 if (err)
5888 return err;
5889 resp = getchar();
5890 if (resp == '\n')
5891 resp = getchar();
5892 if (status == GOT_STATUS_MODIFY) {
5893 if (resp != 'y' && resp != 'n' && resp != 'q') {
5894 printf("invalid response '%c'\n", resp);
5895 resp = ' ';
5897 } else if (resp != 'y' && resp != 'n') {
5898 printf("invalid response '%c'\n", resp);
5899 resp = ' ';
5903 if (resp == 'y')
5904 *choice = GOT_PATCH_CHOICE_YES;
5905 else if (resp == 'n')
5906 *choice = GOT_PATCH_CHOICE_NO;
5907 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
5908 *choice = GOT_PATCH_CHOICE_QUIT;
5910 return NULL;
5914 static const struct got_error *
5915 cmd_revert(int argc, char *argv[])
5917 const struct got_error *error = NULL;
5918 struct got_worktree *worktree = NULL;
5919 struct got_repository *repo = NULL;
5920 char *cwd = NULL, *path = NULL;
5921 struct got_pathlist_head paths;
5922 struct got_pathlist_entry *pe;
5923 int ch, can_recurse = 0, pflag = 0;
5924 FILE *patch_script_file = NULL;
5925 const char *patch_script_path = NULL;
5926 struct choose_patch_arg cpa;
5928 TAILQ_INIT(&paths);
5930 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
5931 switch (ch) {
5932 case 'p':
5933 pflag = 1;
5934 break;
5935 case 'F':
5936 patch_script_path = optarg;
5937 break;
5938 case 'R':
5939 can_recurse = 1;
5940 break;
5941 default:
5942 usage_revert();
5943 /* NOTREACHED */
5947 argc -= optind;
5948 argv += optind;
5950 #ifndef PROFILE
5951 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
5952 "unveil", NULL) == -1)
5953 err(1, "pledge");
5954 #endif
5955 if (argc < 1)
5956 usage_revert();
5957 if (patch_script_path && !pflag)
5958 errx(1, "-F option can only be used together with -p option");
5960 cwd = getcwd(NULL, 0);
5961 if (cwd == NULL) {
5962 error = got_error_from_errno("getcwd");
5963 goto done;
5965 error = got_worktree_open(&worktree, cwd);
5966 if (error)
5967 goto done;
5969 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5970 NULL);
5971 if (error != NULL)
5972 goto done;
5974 if (patch_script_path) {
5975 patch_script_file = fopen(patch_script_path, "r");
5976 if (patch_script_file == NULL) {
5977 error = got_error_from_errno2("fopen",
5978 patch_script_path);
5979 goto done;
5982 error = apply_unveil(got_repo_get_path(repo), 1,
5983 got_worktree_get_root_path(worktree));
5984 if (error)
5985 goto done;
5987 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5988 if (error)
5989 goto done;
5991 if (!can_recurse) {
5992 char *ondisk_path;
5993 struct stat sb;
5994 TAILQ_FOREACH(pe, &paths, entry) {
5995 if (asprintf(&ondisk_path, "%s/%s",
5996 got_worktree_get_root_path(worktree),
5997 pe->path) == -1) {
5998 error = got_error_from_errno("asprintf");
5999 goto done;
6001 if (lstat(ondisk_path, &sb) == -1) {
6002 if (errno == ENOENT) {
6003 free(ondisk_path);
6004 continue;
6006 error = got_error_from_errno2("lstat",
6007 ondisk_path);
6008 free(ondisk_path);
6009 goto done;
6011 free(ondisk_path);
6012 if (S_ISDIR(sb.st_mode)) {
6013 error = got_error_msg(GOT_ERR_BAD_PATH,
6014 "reverting directories requires -R option");
6015 goto done;
6020 cpa.patch_script_file = patch_script_file;
6021 cpa.action = "revert";
6022 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6023 pflag ? choose_patch : NULL, &cpa, repo);
6024 done:
6025 if (patch_script_file && fclose(patch_script_file) == EOF &&
6026 error == NULL)
6027 error = got_error_from_errno2("fclose", patch_script_path);
6028 if (repo)
6029 got_repo_close(repo);
6030 if (worktree)
6031 got_worktree_close(worktree);
6032 free(path);
6033 free(cwd);
6034 return error;
6037 __dead static void
6038 usage_commit(void)
6040 fprintf(stderr, "usage: %s commit [-m msg] [path ...]\n",
6041 getprogname());
6042 exit(1);
6045 struct collect_commit_logmsg_arg {
6046 const char *cmdline_log;
6047 const char *editor;
6048 const char *worktree_path;
6049 const char *branch_name;
6050 const char *repo_path;
6051 char *logmsg_path;
6055 static const struct got_error *
6056 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6057 void *arg)
6059 char *initial_content = NULL;
6060 struct got_pathlist_entry *pe;
6061 const struct got_error *err = NULL;
6062 char *template = NULL;
6063 struct collect_commit_logmsg_arg *a = arg;
6064 int fd;
6065 size_t len;
6067 /* if a message was specified on the command line, just use it */
6068 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6069 len = strlen(a->cmdline_log) + 1;
6070 *logmsg = malloc(len + 1);
6071 if (*logmsg == NULL)
6072 return got_error_from_errno("malloc");
6073 strlcpy(*logmsg, a->cmdline_log, len);
6074 return NULL;
6077 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6078 return got_error_from_errno("asprintf");
6080 if (asprintf(&initial_content,
6081 "\n# changes to be committed on branch %s:\n",
6082 a->branch_name) == -1)
6083 return got_error_from_errno("asprintf");
6085 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6086 if (err)
6087 goto done;
6089 dprintf(fd, initial_content);
6091 TAILQ_FOREACH(pe, commitable_paths, entry) {
6092 struct got_commitable *ct = pe->data;
6093 dprintf(fd, "# %c %s\n",
6094 got_commitable_get_status(ct),
6095 got_commitable_get_path(ct));
6097 close(fd);
6099 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
6100 done:
6101 free(initial_content);
6102 free(template);
6104 /* Editor is done; we can now apply unveil(2) */
6105 if (err == NULL) {
6106 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6107 if (err) {
6108 free(*logmsg);
6109 *logmsg = NULL;
6112 return err;
6115 static const struct got_error *
6116 cmd_commit(int argc, char *argv[])
6118 const struct got_error *error = NULL;
6119 struct got_worktree *worktree = NULL;
6120 struct got_repository *repo = NULL;
6121 char *cwd = NULL, *id_str = NULL;
6122 struct got_object_id *id = NULL;
6123 const char *logmsg = NULL;
6124 struct collect_commit_logmsg_arg cl_arg;
6125 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6126 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6127 struct got_pathlist_head paths;
6129 TAILQ_INIT(&paths);
6130 cl_arg.logmsg_path = NULL;
6132 while ((ch = getopt(argc, argv, "m:")) != -1) {
6133 switch (ch) {
6134 case 'm':
6135 logmsg = optarg;
6136 break;
6137 default:
6138 usage_commit();
6139 /* NOTREACHED */
6143 argc -= optind;
6144 argv += optind;
6146 #ifndef PROFILE
6147 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6148 "unveil", NULL) == -1)
6149 err(1, "pledge");
6150 #endif
6151 cwd = getcwd(NULL, 0);
6152 if (cwd == NULL) {
6153 error = got_error_from_errno("getcwd");
6154 goto done;
6156 error = got_worktree_open(&worktree, cwd);
6157 if (error)
6158 goto done;
6160 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6161 if (error)
6162 goto done;
6163 if (rebase_in_progress) {
6164 error = got_error(GOT_ERR_REBASING);
6165 goto done;
6168 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6169 worktree);
6170 if (error)
6171 goto done;
6173 error = get_gitconfig_path(&gitconfig_path);
6174 if (error)
6175 goto done;
6176 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6177 gitconfig_path);
6178 if (error != NULL)
6179 goto done;
6181 error = get_author(&author, repo);
6182 if (error)
6183 return error;
6186 * unveil(2) traverses exec(2); if an editor is used we have
6187 * to apply unveil after the log message has been written.
6189 if (logmsg == NULL || strlen(logmsg) == 0)
6190 error = get_editor(&editor);
6191 else
6192 error = apply_unveil(got_repo_get_path(repo), 0,
6193 got_worktree_get_root_path(worktree));
6194 if (error)
6195 goto done;
6197 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6198 if (error)
6199 goto done;
6201 cl_arg.editor = editor;
6202 cl_arg.cmdline_log = logmsg;
6203 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6204 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6205 if (!histedit_in_progress) {
6206 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6207 error = got_error(GOT_ERR_COMMIT_BRANCH);
6208 goto done;
6210 cl_arg.branch_name += 11;
6212 cl_arg.repo_path = got_repo_get_path(repo);
6213 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6214 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
6215 if (error) {
6216 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6217 cl_arg.logmsg_path != NULL)
6218 preserve_logmsg = 1;
6219 goto done;
6222 error = got_object_id_str(&id_str, id);
6223 if (error)
6224 goto done;
6225 printf("Created commit %s\n", id_str);
6226 done:
6227 if (preserve_logmsg) {
6228 fprintf(stderr, "%s: log message preserved in %s\n",
6229 getprogname(), cl_arg.logmsg_path);
6230 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6231 error == NULL)
6232 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6233 free(cl_arg.logmsg_path);
6234 if (repo)
6235 got_repo_close(repo);
6236 if (worktree)
6237 got_worktree_close(worktree);
6238 free(cwd);
6239 free(id_str);
6240 free(gitconfig_path);
6241 free(editor);
6242 free(author);
6243 return error;
6246 __dead static void
6247 usage_cherrypick(void)
6249 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6250 exit(1);
6253 static const struct got_error *
6254 cmd_cherrypick(int argc, char *argv[])
6256 const struct got_error *error = NULL;
6257 struct got_worktree *worktree = NULL;
6258 struct got_repository *repo = NULL;
6259 char *cwd = NULL, *commit_id_str = NULL;
6260 struct got_object_id *commit_id = NULL;
6261 struct got_commit_object *commit = NULL;
6262 struct got_object_qid *pid;
6263 struct got_reference *head_ref = NULL;
6264 int ch, did_something = 0;
6266 while ((ch = getopt(argc, argv, "")) != -1) {
6267 switch (ch) {
6268 default:
6269 usage_cherrypick();
6270 /* NOTREACHED */
6274 argc -= optind;
6275 argv += optind;
6277 #ifndef PROFILE
6278 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6279 "unveil", NULL) == -1)
6280 err(1, "pledge");
6281 #endif
6282 if (argc != 1)
6283 usage_cherrypick();
6285 cwd = getcwd(NULL, 0);
6286 if (cwd == NULL) {
6287 error = got_error_from_errno("getcwd");
6288 goto done;
6290 error = got_worktree_open(&worktree, cwd);
6291 if (error)
6292 goto done;
6294 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6295 NULL);
6296 if (error != NULL)
6297 goto done;
6299 error = apply_unveil(got_repo_get_path(repo), 0,
6300 got_worktree_get_root_path(worktree));
6301 if (error)
6302 goto done;
6304 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6305 GOT_OBJ_TYPE_COMMIT, repo);
6306 if (error != NULL) {
6307 struct got_reference *ref;
6308 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6309 goto done;
6310 error = got_ref_open(&ref, repo, argv[0], 0);
6311 if (error != NULL)
6312 goto done;
6313 error = got_ref_resolve(&commit_id, repo, ref);
6314 got_ref_close(ref);
6315 if (error != NULL)
6316 goto done;
6318 error = got_object_id_str(&commit_id_str, commit_id);
6319 if (error)
6320 goto done;
6322 error = got_ref_open(&head_ref, repo,
6323 got_worktree_get_head_ref_name(worktree), 0);
6324 if (error != NULL)
6325 goto done;
6327 error = check_same_branch(commit_id, head_ref, NULL, repo);
6328 if (error) {
6329 if (error->code != GOT_ERR_ANCESTRY)
6330 goto done;
6331 error = NULL;
6332 } else {
6333 error = got_error(GOT_ERR_SAME_BRANCH);
6334 goto done;
6337 error = got_object_open_as_commit(&commit, repo, commit_id);
6338 if (error)
6339 goto done;
6340 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6341 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
6342 commit_id, repo, update_progress, &did_something, check_cancelled,
6343 NULL);
6344 if (error != NULL)
6345 goto done;
6347 if (did_something)
6348 printf("Merged commit %s\n", commit_id_str);
6349 done:
6350 if (commit)
6351 got_object_commit_close(commit);
6352 free(commit_id_str);
6353 if (head_ref)
6354 got_ref_close(head_ref);
6355 if (worktree)
6356 got_worktree_close(worktree);
6357 if (repo)
6358 got_repo_close(repo);
6359 return error;
6362 __dead static void
6363 usage_backout(void)
6365 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
6366 exit(1);
6369 static const struct got_error *
6370 cmd_backout(int argc, char *argv[])
6372 const struct got_error *error = NULL;
6373 struct got_worktree *worktree = NULL;
6374 struct got_repository *repo = NULL;
6375 char *cwd = NULL, *commit_id_str = NULL;
6376 struct got_object_id *commit_id = NULL;
6377 struct got_commit_object *commit = NULL;
6378 struct got_object_qid *pid;
6379 struct got_reference *head_ref = NULL;
6380 int ch, did_something = 0;
6382 while ((ch = getopt(argc, argv, "")) != -1) {
6383 switch (ch) {
6384 default:
6385 usage_backout();
6386 /* NOTREACHED */
6390 argc -= optind;
6391 argv += optind;
6393 #ifndef PROFILE
6394 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6395 "unveil", NULL) == -1)
6396 err(1, "pledge");
6397 #endif
6398 if (argc != 1)
6399 usage_backout();
6401 cwd = getcwd(NULL, 0);
6402 if (cwd == NULL) {
6403 error = got_error_from_errno("getcwd");
6404 goto done;
6406 error = got_worktree_open(&worktree, cwd);
6407 if (error)
6408 goto done;
6410 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6411 NULL);
6412 if (error != NULL)
6413 goto done;
6415 error = apply_unveil(got_repo_get_path(repo), 0,
6416 got_worktree_get_root_path(worktree));
6417 if (error)
6418 goto done;
6420 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6421 GOT_OBJ_TYPE_COMMIT, repo);
6422 if (error != NULL) {
6423 struct got_reference *ref;
6424 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6425 goto done;
6426 error = got_ref_open(&ref, repo, argv[0], 0);
6427 if (error != NULL)
6428 goto done;
6429 error = got_ref_resolve(&commit_id, repo, ref);
6430 got_ref_close(ref);
6431 if (error != NULL)
6432 goto done;
6434 error = got_object_id_str(&commit_id_str, commit_id);
6435 if (error)
6436 goto done;
6438 error = got_ref_open(&head_ref, repo,
6439 got_worktree_get_head_ref_name(worktree), 0);
6440 if (error != NULL)
6441 goto done;
6443 error = check_same_branch(commit_id, head_ref, NULL, repo);
6444 if (error)
6445 goto done;
6447 error = got_object_open_as_commit(&commit, repo, commit_id);
6448 if (error)
6449 goto done;
6450 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6451 if (pid == NULL) {
6452 error = got_error(GOT_ERR_ROOT_COMMIT);
6453 goto done;
6456 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
6457 update_progress, &did_something, check_cancelled, NULL);
6458 if (error != NULL)
6459 goto done;
6461 if (did_something)
6462 printf("Backed out commit %s\n", commit_id_str);
6463 done:
6464 if (commit)
6465 got_object_commit_close(commit);
6466 free(commit_id_str);
6467 if (head_ref)
6468 got_ref_close(head_ref);
6469 if (worktree)
6470 got_worktree_close(worktree);
6471 if (repo)
6472 got_repo_close(repo);
6473 return error;
6476 __dead static void
6477 usage_rebase(void)
6479 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
6480 getprogname());
6481 exit(1);
6484 void
6485 trim_logmsg(char *logmsg, int limit)
6487 char *nl;
6488 size_t len;
6490 len = strlen(logmsg);
6491 if (len > limit)
6492 len = limit;
6493 logmsg[len] = '\0';
6494 nl = strchr(logmsg, '\n');
6495 if (nl)
6496 *nl = '\0';
6499 static const struct got_error *
6500 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
6502 const struct got_error *err;
6503 char *logmsg0 = NULL;
6504 const char *s;
6506 err = got_object_commit_get_logmsg(&logmsg0, commit);
6507 if (err)
6508 return err;
6510 s = logmsg0;
6511 while (isspace((unsigned char)s[0]))
6512 s++;
6514 *logmsg = strdup(s);
6515 if (*logmsg == NULL) {
6516 err = got_error_from_errno("strdup");
6517 goto done;
6520 trim_logmsg(*logmsg, limit);
6521 done:
6522 free(logmsg0);
6523 return err;
6526 static const struct got_error *
6527 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
6529 const struct got_error *err;
6530 struct got_commit_object *commit = NULL;
6531 char *id_str = NULL, *logmsg = NULL;
6533 err = got_object_open_as_commit(&commit, repo, id);
6534 if (err)
6535 return err;
6537 err = got_object_id_str(&id_str, id);
6538 if (err)
6539 goto done;
6541 id_str[12] = '\0';
6543 err = get_short_logmsg(&logmsg, 42, commit);
6544 if (err)
6545 goto done;
6547 printf("%s -> merge conflict: %s\n", id_str, logmsg);
6548 done:
6549 free(id_str);
6550 got_object_commit_close(commit);
6551 free(logmsg);
6552 return err;
6555 static const struct got_error *
6556 show_rebase_progress(struct got_commit_object *commit,
6557 struct got_object_id *old_id, struct got_object_id *new_id)
6559 const struct got_error *err;
6560 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
6562 err = got_object_id_str(&old_id_str, old_id);
6563 if (err)
6564 goto done;
6566 if (new_id) {
6567 err = got_object_id_str(&new_id_str, new_id);
6568 if (err)
6569 goto done;
6572 old_id_str[12] = '\0';
6573 if (new_id_str)
6574 new_id_str[12] = '\0';
6576 err = get_short_logmsg(&logmsg, 42, commit);
6577 if (err)
6578 goto done;
6580 printf("%s -> %s: %s\n", old_id_str,
6581 new_id_str ? new_id_str : "no-op change", logmsg);
6582 done:
6583 free(old_id_str);
6584 free(new_id_str);
6585 free(logmsg);
6586 return err;
6589 static const struct got_error *
6590 rebase_progress(void *arg, unsigned char status, const char *path)
6592 unsigned char *rebase_status = arg;
6594 while (path[0] == '/')
6595 path++;
6596 printf("%c %s\n", status, path);
6598 if (*rebase_status == GOT_STATUS_CONFLICT)
6599 return NULL;
6600 if (status == GOT_STATUS_CONFLICT || status == GOT_STATUS_MERGE)
6601 *rebase_status = status;
6602 return NULL;
6605 static const struct got_error *
6606 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
6607 struct got_reference *branch, struct got_reference *new_base_branch,
6608 struct got_reference *tmp_branch, struct got_repository *repo)
6610 printf("Switching work tree to %s\n", got_ref_get_name(branch));
6611 return got_worktree_rebase_complete(worktree, fileindex,
6612 new_base_branch, tmp_branch, branch, repo);
6615 static const struct got_error *
6616 rebase_commit(struct got_pathlist_head *merged_paths,
6617 struct got_worktree *worktree, struct got_fileindex *fileindex,
6618 struct got_reference *tmp_branch,
6619 struct got_object_id *commit_id, struct got_repository *repo)
6621 const struct got_error *error;
6622 struct got_commit_object *commit;
6623 struct got_object_id *new_commit_id;
6625 error = got_object_open_as_commit(&commit, repo, commit_id);
6626 if (error)
6627 return error;
6629 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
6630 worktree, fileindex, tmp_branch, commit, commit_id, repo);
6631 if (error) {
6632 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
6633 goto done;
6634 error = show_rebase_progress(commit, commit_id, NULL);
6635 } else {
6636 error = show_rebase_progress(commit, commit_id, new_commit_id);
6637 free(new_commit_id);
6639 done:
6640 got_object_commit_close(commit);
6641 return error;
6644 struct check_path_prefix_arg {
6645 const char *path_prefix;
6646 size_t len;
6647 int errcode;
6650 static const struct got_error *
6651 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
6652 struct got_blob_object *blob2, struct got_object_id *id1,
6653 struct got_object_id *id2, const char *path1, const char *path2,
6654 mode_t mode1, mode_t mode2, struct got_repository *repo)
6656 struct check_path_prefix_arg *a = arg;
6658 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
6659 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
6660 return got_error(a->errcode);
6662 return NULL;
6665 static const struct got_error *
6666 check_path_prefix(struct got_object_id *parent_id,
6667 struct got_object_id *commit_id, const char *path_prefix,
6668 int errcode, struct got_repository *repo)
6670 const struct got_error *err;
6671 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
6672 struct got_commit_object *commit = NULL, *parent_commit = NULL;
6673 struct check_path_prefix_arg cpp_arg;
6675 if (got_path_is_root_dir(path_prefix))
6676 return NULL;
6678 err = got_object_open_as_commit(&commit, repo, commit_id);
6679 if (err)
6680 goto done;
6682 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
6683 if (err)
6684 goto done;
6686 err = got_object_open_as_tree(&tree1, repo,
6687 got_object_commit_get_tree_id(parent_commit));
6688 if (err)
6689 goto done;
6691 err = got_object_open_as_tree(&tree2, repo,
6692 got_object_commit_get_tree_id(commit));
6693 if (err)
6694 goto done;
6696 cpp_arg.path_prefix = path_prefix;
6697 while (cpp_arg.path_prefix[0] == '/')
6698 cpp_arg.path_prefix++;
6699 cpp_arg.len = strlen(cpp_arg.path_prefix);
6700 cpp_arg.errcode = errcode;
6701 err = got_diff_tree(tree1, tree2, "", "", repo,
6702 check_path_prefix_in_diff, &cpp_arg, 0);
6703 done:
6704 if (tree1)
6705 got_object_tree_close(tree1);
6706 if (tree2)
6707 got_object_tree_close(tree2);
6708 if (commit)
6709 got_object_commit_close(commit);
6710 if (parent_commit)
6711 got_object_commit_close(parent_commit);
6712 return err;
6715 static const struct got_error *
6716 collect_commits(struct got_object_id_queue *commits,
6717 struct got_object_id *initial_commit_id,
6718 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
6719 const char *path_prefix, int path_prefix_errcode,
6720 struct got_repository *repo)
6722 const struct got_error *err = NULL;
6723 struct got_commit_graph *graph = NULL;
6724 struct got_object_id *parent_id = NULL;
6725 struct got_object_qid *qid;
6726 struct got_object_id *commit_id = initial_commit_id;
6728 err = got_commit_graph_open(&graph, "/", 1);
6729 if (err)
6730 return err;
6732 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
6733 check_cancelled, NULL);
6734 if (err)
6735 goto done;
6736 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
6737 err = got_commit_graph_iter_next(&parent_id, graph, repo,
6738 check_cancelled, NULL);
6739 if (err) {
6740 if (err->code == GOT_ERR_ITER_COMPLETED) {
6741 err = got_error_msg(GOT_ERR_ANCESTRY,
6742 "ran out of commits to rebase before "
6743 "youngest common ancestor commit has "
6744 "been reached?!?");
6746 goto done;
6747 } else {
6748 err = check_path_prefix(parent_id, commit_id,
6749 path_prefix, path_prefix_errcode, repo);
6750 if (err)
6751 goto done;
6753 err = got_object_qid_alloc(&qid, commit_id);
6754 if (err)
6755 goto done;
6756 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
6757 commit_id = parent_id;
6760 done:
6761 got_commit_graph_close(graph);
6762 return err;
6765 static const struct got_error *
6766 cmd_rebase(int argc, char *argv[])
6768 const struct got_error *error = NULL;
6769 struct got_worktree *worktree = NULL;
6770 struct got_repository *repo = NULL;
6771 struct got_fileindex *fileindex = NULL;
6772 char *cwd = NULL;
6773 struct got_reference *branch = NULL;
6774 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
6775 struct got_object_id *commit_id = NULL, *parent_id = NULL;
6776 struct got_object_id *resume_commit_id = NULL;
6777 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
6778 struct got_commit_object *commit = NULL;
6779 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
6780 int histedit_in_progress = 0;
6781 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
6782 struct got_object_id_queue commits;
6783 struct got_pathlist_head merged_paths;
6784 const struct got_object_id_queue *parent_ids;
6785 struct got_object_qid *qid, *pid;
6787 SIMPLEQ_INIT(&commits);
6788 TAILQ_INIT(&merged_paths);
6790 while ((ch = getopt(argc, argv, "ac")) != -1) {
6791 switch (ch) {
6792 case 'a':
6793 abort_rebase = 1;
6794 break;
6795 case 'c':
6796 continue_rebase = 1;
6797 break;
6798 default:
6799 usage_rebase();
6800 /* NOTREACHED */
6804 argc -= optind;
6805 argv += optind;
6807 #ifndef PROFILE
6808 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6809 "unveil", NULL) == -1)
6810 err(1, "pledge");
6811 #endif
6812 if (abort_rebase && continue_rebase)
6813 usage_rebase();
6814 else if (abort_rebase || continue_rebase) {
6815 if (argc != 0)
6816 usage_rebase();
6817 } else if (argc != 1)
6818 usage_rebase();
6820 cwd = getcwd(NULL, 0);
6821 if (cwd == NULL) {
6822 error = got_error_from_errno("getcwd");
6823 goto done;
6825 error = got_worktree_open(&worktree, cwd);
6826 if (error)
6827 goto done;
6829 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6830 NULL);
6831 if (error != NULL)
6832 goto done;
6834 error = apply_unveil(got_repo_get_path(repo), 0,
6835 got_worktree_get_root_path(worktree));
6836 if (error)
6837 goto done;
6839 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6840 worktree);
6841 if (error)
6842 goto done;
6843 if (histedit_in_progress) {
6844 error = got_error(GOT_ERR_HISTEDIT_BUSY);
6845 goto done;
6848 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6849 if (error)
6850 goto done;
6852 if (abort_rebase) {
6853 int did_something;
6854 if (!rebase_in_progress) {
6855 error = got_error(GOT_ERR_NOT_REBASING);
6856 goto done;
6858 error = got_worktree_rebase_continue(&resume_commit_id,
6859 &new_base_branch, &tmp_branch, &branch, &fileindex,
6860 worktree, repo);
6861 if (error)
6862 goto done;
6863 printf("Switching work tree to %s\n",
6864 got_ref_get_symref_target(new_base_branch));
6865 error = got_worktree_rebase_abort(worktree, fileindex, repo,
6866 new_base_branch, update_progress, &did_something);
6867 if (error)
6868 goto done;
6869 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
6870 goto done; /* nothing else to do */
6873 if (continue_rebase) {
6874 if (!rebase_in_progress) {
6875 error = got_error(GOT_ERR_NOT_REBASING);
6876 goto done;
6878 error = got_worktree_rebase_continue(&resume_commit_id,
6879 &new_base_branch, &tmp_branch, &branch, &fileindex,
6880 worktree, repo);
6881 if (error)
6882 goto done;
6884 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
6885 resume_commit_id, repo);
6886 if (error)
6887 goto done;
6889 yca_id = got_object_id_dup(resume_commit_id);
6890 if (yca_id == NULL) {
6891 error = got_error_from_errno("got_object_id_dup");
6892 goto done;
6894 } else {
6895 error = got_ref_open(&branch, repo, argv[0], 0);
6896 if (error != NULL)
6897 goto done;
6900 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
6901 if (error)
6902 goto done;
6904 if (!continue_rebase) {
6905 struct got_object_id *base_commit_id;
6907 base_commit_id = got_worktree_get_base_commit_id(worktree);
6908 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
6909 base_commit_id, branch_head_commit_id, repo,
6910 check_cancelled, NULL);
6911 if (error)
6912 goto done;
6913 if (yca_id == NULL) {
6914 error = got_error_msg(GOT_ERR_ANCESTRY,
6915 "specified branch shares no common ancestry "
6916 "with work tree's branch");
6917 goto done;
6920 error = check_same_branch(base_commit_id, branch, yca_id, repo);
6921 if (error) {
6922 if (error->code != GOT_ERR_ANCESTRY)
6923 goto done;
6924 error = NULL;
6925 } else {
6926 error = got_error_msg(GOT_ERR_SAME_BRANCH,
6927 "specified branch resolves to a commit which "
6928 "is already contained in work tree's branch");
6929 goto done;
6931 error = got_worktree_rebase_prepare(&new_base_branch,
6932 &tmp_branch, &fileindex, worktree, branch, repo);
6933 if (error)
6934 goto done;
6937 commit_id = branch_head_commit_id;
6938 error = got_object_open_as_commit(&commit, repo, commit_id);
6939 if (error)
6940 goto done;
6942 parent_ids = got_object_commit_get_parent_ids(commit);
6943 pid = SIMPLEQ_FIRST(parent_ids);
6944 if (pid == NULL) {
6945 if (!continue_rebase) {
6946 int did_something;
6947 error = got_worktree_rebase_abort(worktree, fileindex,
6948 repo, new_base_branch, update_progress,
6949 &did_something);
6950 if (error)
6951 goto done;
6952 printf("Rebase of %s aborted\n",
6953 got_ref_get_name(branch));
6955 error = got_error(GOT_ERR_EMPTY_REBASE);
6956 goto done;
6958 error = collect_commits(&commits, commit_id, pid->id,
6959 yca_id, got_worktree_get_path_prefix(worktree),
6960 GOT_ERR_REBASE_PATH, repo);
6961 got_object_commit_close(commit);
6962 commit = NULL;
6963 if (error)
6964 goto done;
6966 if (SIMPLEQ_EMPTY(&commits)) {
6967 if (continue_rebase) {
6968 error = rebase_complete(worktree, fileindex,
6969 branch, new_base_branch, tmp_branch, repo);
6970 goto done;
6971 } else {
6972 /* Fast-forward the reference of the branch. */
6973 struct got_object_id *new_head_commit_id;
6974 char *id_str;
6975 error = got_ref_resolve(&new_head_commit_id, repo,
6976 new_base_branch);
6977 if (error)
6978 goto done;
6979 error = got_object_id_str(&id_str, new_head_commit_id);
6980 printf("Forwarding %s to commit %s\n",
6981 got_ref_get_name(branch), id_str);
6982 free(id_str);
6983 error = got_ref_change_ref(branch,
6984 new_head_commit_id);
6985 if (error)
6986 goto done;
6990 pid = NULL;
6991 SIMPLEQ_FOREACH(qid, &commits, entry) {
6992 commit_id = qid->id;
6993 parent_id = pid ? pid->id : yca_id;
6994 pid = qid;
6996 error = got_worktree_rebase_merge_files(&merged_paths,
6997 worktree, fileindex, parent_id, commit_id, repo,
6998 rebase_progress, &rebase_status, check_cancelled, NULL);
6999 if (error)
7000 goto done;
7002 if (rebase_status == GOT_STATUS_CONFLICT) {
7003 error = show_rebase_merge_conflict(qid->id, repo);
7004 if (error)
7005 goto done;
7006 got_worktree_rebase_pathlist_free(&merged_paths);
7007 break;
7010 error = rebase_commit(&merged_paths, worktree, fileindex,
7011 tmp_branch, commit_id, repo);
7012 got_worktree_rebase_pathlist_free(&merged_paths);
7013 if (error)
7014 goto done;
7017 if (rebase_status == GOT_STATUS_CONFLICT) {
7018 error = got_worktree_rebase_postpone(worktree, fileindex);
7019 if (error)
7020 goto done;
7021 error = got_error_msg(GOT_ERR_CONFLICTS,
7022 "conflicts must be resolved before rebasing can continue");
7023 } else
7024 error = rebase_complete(worktree, fileindex, branch,
7025 new_base_branch, tmp_branch, repo);
7026 done:
7027 got_object_id_queue_free(&commits);
7028 free(branch_head_commit_id);
7029 free(resume_commit_id);
7030 free(yca_id);
7031 if (commit)
7032 got_object_commit_close(commit);
7033 if (branch)
7034 got_ref_close(branch);
7035 if (new_base_branch)
7036 got_ref_close(new_base_branch);
7037 if (tmp_branch)
7038 got_ref_close(tmp_branch);
7039 if (worktree)
7040 got_worktree_close(worktree);
7041 if (repo)
7042 got_repo_close(repo);
7043 return error;
7046 __dead static void
7047 usage_histedit(void)
7049 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
7050 getprogname());
7051 exit(1);
7054 #define GOT_HISTEDIT_PICK 'p'
7055 #define GOT_HISTEDIT_EDIT 'e'
7056 #define GOT_HISTEDIT_FOLD 'f'
7057 #define GOT_HISTEDIT_DROP 'd'
7058 #define GOT_HISTEDIT_MESG 'm'
7060 static struct got_histedit_cmd {
7061 unsigned char code;
7062 const char *name;
7063 const char *desc;
7064 } got_histedit_cmds[] = {
7065 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7066 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7067 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7068 "be used" },
7069 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7070 { GOT_HISTEDIT_MESG, "mesg",
7071 "single-line log message for commit above (open editor if empty)" },
7074 struct got_histedit_list_entry {
7075 TAILQ_ENTRY(got_histedit_list_entry) entry;
7076 struct got_object_id *commit_id;
7077 const struct got_histedit_cmd *cmd;
7078 char *logmsg;
7080 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7082 static const struct got_error *
7083 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7084 FILE *f, struct got_repository *repo)
7086 const struct got_error *err = NULL;
7087 char *logmsg = NULL, *id_str = NULL;
7088 struct got_commit_object *commit = NULL;
7089 int n;
7091 err = got_object_open_as_commit(&commit, repo, commit_id);
7092 if (err)
7093 goto done;
7095 err = get_short_logmsg(&logmsg, 34, commit);
7096 if (err)
7097 goto done;
7099 err = got_object_id_str(&id_str, commit_id);
7100 if (err)
7101 goto done;
7103 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7104 if (n < 0)
7105 err = got_ferror(f, GOT_ERR_IO);
7106 done:
7107 if (commit)
7108 got_object_commit_close(commit);
7109 free(id_str);
7110 free(logmsg);
7111 return err;
7114 static const struct got_error *
7115 histedit_write_commit_list(struct got_object_id_queue *commits,
7116 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7118 const struct got_error *err = NULL;
7119 struct got_object_qid *qid;
7121 if (SIMPLEQ_EMPTY(commits))
7122 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7124 SIMPLEQ_FOREACH(qid, commits, entry) {
7125 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7126 f, repo);
7127 if (err)
7128 break;
7129 if (edit_logmsg_only) {
7130 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7131 if (n < 0) {
7132 err = got_ferror(f, GOT_ERR_IO);
7133 break;
7138 return err;
7141 static const struct got_error *
7142 write_cmd_list(FILE *f, const char *branch_name,
7143 struct got_object_id_queue *commits)
7145 const struct got_error *err = NULL;
7146 int n, i;
7147 char *id_str;
7148 struct got_object_qid *qid;
7150 qid = SIMPLEQ_FIRST(commits);
7151 err = got_object_id_str(&id_str, qid->id);
7152 if (err)
7153 return err;
7155 n = fprintf(f,
7156 "# Editing the history of branch '%s' starting at\n"
7157 "# commit %s\n"
7158 "# Commits will be processed in order from top to "
7159 "bottom of this file.\n", branch_name, id_str);
7160 if (n < 0) {
7161 err = got_ferror(f, GOT_ERR_IO);
7162 goto done;
7165 n = fprintf(f, "# Available histedit commands:\n");
7166 if (n < 0) {
7167 err = got_ferror(f, GOT_ERR_IO);
7168 goto done;
7171 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7172 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7173 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7174 cmd->desc);
7175 if (n < 0) {
7176 err = got_ferror(f, GOT_ERR_IO);
7177 break;
7180 done:
7181 free(id_str);
7182 return err;
7185 static const struct got_error *
7186 histedit_syntax_error(int lineno)
7188 static char msg[42];
7189 int ret;
7191 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7192 lineno);
7193 if (ret == -1 || ret >= sizeof(msg))
7194 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7196 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7199 static const struct got_error *
7200 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7201 char *logmsg, struct got_repository *repo)
7203 const struct got_error *err;
7204 struct got_commit_object *folded_commit = NULL;
7205 char *id_str, *folded_logmsg = NULL;
7207 err = got_object_id_str(&id_str, hle->commit_id);
7208 if (err)
7209 return err;
7211 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7212 if (err)
7213 goto done;
7215 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7216 if (err)
7217 goto done;
7218 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7219 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7220 folded_logmsg) == -1) {
7221 err = got_error_from_errno("asprintf");
7223 done:
7224 if (folded_commit)
7225 got_object_commit_close(folded_commit);
7226 free(id_str);
7227 free(folded_logmsg);
7228 return err;
7231 static struct got_histedit_list_entry *
7232 get_folded_commits(struct got_histedit_list_entry *hle)
7234 struct got_histedit_list_entry *prev, *folded = NULL;
7236 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7237 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7238 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7239 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7240 folded = prev;
7241 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7244 return folded;
7247 static const struct got_error *
7248 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7249 struct got_repository *repo)
7251 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7252 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7253 const struct got_error *err = NULL;
7254 struct got_commit_object *commit = NULL;
7255 int fd;
7256 struct got_histedit_list_entry *folded = NULL;
7258 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7259 if (err)
7260 return err;
7262 folded = get_folded_commits(hle);
7263 if (folded) {
7264 while (folded != hle) {
7265 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7266 folded = TAILQ_NEXT(folded, entry);
7267 continue;
7269 err = append_folded_commit_msg(&new_msg, folded,
7270 logmsg, repo);
7271 if (err)
7272 goto done;
7273 free(logmsg);
7274 logmsg = new_msg;
7275 folded = TAILQ_NEXT(folded, entry);
7279 err = got_object_id_str(&id_str, hle->commit_id);
7280 if (err)
7281 goto done;
7282 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7283 if (err)
7284 goto done;
7285 if (asprintf(&new_msg,
7286 "%s\n# original log message of commit %s: %s",
7287 logmsg ? logmsg : "", id_str, orig_logmsg) == -1) {
7288 err = got_error_from_errno("asprintf");
7289 goto done;
7291 free(logmsg);
7292 logmsg = new_msg;
7294 err = got_object_id_str(&id_str, hle->commit_id);
7295 if (err)
7296 goto done;
7298 err = got_opentemp_named_fd(&logmsg_path, &fd,
7299 GOT_TMPDIR_STR "/got-logmsg");
7300 if (err)
7301 goto done;
7303 dprintf(fd, logmsg);
7304 close(fd);
7306 err = get_editor(&editor);
7307 if (err)
7308 goto done;
7310 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
7311 if (err) {
7312 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
7313 goto done;
7314 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
7316 done:
7317 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
7318 err = got_error_from_errno2("unlink", logmsg_path);
7319 free(logmsg_path);
7320 free(logmsg);
7321 free(orig_logmsg);
7322 free(editor);
7323 if (commit)
7324 got_object_commit_close(commit);
7325 return err;
7328 static const struct got_error *
7329 histedit_parse_list(struct got_histedit_list *histedit_cmds,
7330 FILE *f, struct got_repository *repo)
7332 const struct got_error *err = NULL;
7333 char *line = NULL, *p, *end;
7334 size_t size;
7335 ssize_t len;
7336 int lineno = 0, i;
7337 const struct got_histedit_cmd *cmd;
7338 struct got_object_id *commit_id = NULL;
7339 struct got_histedit_list_entry *hle = NULL;
7341 for (;;) {
7342 len = getline(&line, &size, f);
7343 if (len == -1) {
7344 const struct got_error *getline_err;
7345 if (feof(f))
7346 break;
7347 getline_err = got_error_from_errno("getline");
7348 err = got_ferror(f, getline_err->code);
7349 break;
7351 lineno++;
7352 p = line;
7353 while (isspace((unsigned char)p[0]))
7354 p++;
7355 if (p[0] == '#' || p[0] == '\0') {
7356 free(line);
7357 line = NULL;
7358 continue;
7360 cmd = NULL;
7361 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7362 cmd = &got_histedit_cmds[i];
7363 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
7364 isspace((unsigned char)p[strlen(cmd->name)])) {
7365 p += strlen(cmd->name);
7366 break;
7368 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
7369 p++;
7370 break;
7373 if (i == nitems(got_histedit_cmds)) {
7374 err = histedit_syntax_error(lineno);
7375 break;
7377 while (isspace((unsigned char)p[0]))
7378 p++;
7379 if (cmd->code == GOT_HISTEDIT_MESG) {
7380 if (hle == NULL || hle->logmsg != NULL) {
7381 err = got_error(GOT_ERR_HISTEDIT_CMD);
7382 break;
7384 if (p[0] == '\0') {
7385 err = histedit_edit_logmsg(hle, repo);
7386 if (err)
7387 break;
7388 } else {
7389 hle->logmsg = strdup(p);
7390 if (hle->logmsg == NULL) {
7391 err = got_error_from_errno("strdup");
7392 break;
7395 free(line);
7396 line = NULL;
7397 continue;
7398 } else {
7399 end = p;
7400 while (end[0] && !isspace((unsigned char)end[0]))
7401 end++;
7402 *end = '\0';
7404 err = got_object_resolve_id_str(&commit_id, repo, p);
7405 if (err) {
7406 /* override error code */
7407 err = histedit_syntax_error(lineno);
7408 break;
7411 hle = malloc(sizeof(*hle));
7412 if (hle == NULL) {
7413 err = got_error_from_errno("malloc");
7414 break;
7416 hle->cmd = cmd;
7417 hle->commit_id = commit_id;
7418 hle->logmsg = NULL;
7419 commit_id = NULL;
7420 free(line);
7421 line = NULL;
7422 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
7425 free(line);
7426 free(commit_id);
7427 return err;
7430 static const struct got_error *
7431 histedit_check_script(struct got_histedit_list *histedit_cmds,
7432 struct got_object_id_queue *commits, struct got_repository *repo)
7434 const struct got_error *err = NULL;
7435 struct got_object_qid *qid;
7436 struct got_histedit_list_entry *hle;
7437 static char msg[92];
7438 char *id_str;
7440 if (TAILQ_EMPTY(histedit_cmds))
7441 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
7442 "histedit script contains no commands");
7443 if (SIMPLEQ_EMPTY(commits))
7444 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7446 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7447 struct got_histedit_list_entry *hle2;
7448 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
7449 if (hle == hle2)
7450 continue;
7451 if (got_object_id_cmp(hle->commit_id,
7452 hle2->commit_id) != 0)
7453 continue;
7454 err = got_object_id_str(&id_str, hle->commit_id);
7455 if (err)
7456 return err;
7457 snprintf(msg, sizeof(msg), "commit %s is listed "
7458 "more than once in histedit script", id_str);
7459 free(id_str);
7460 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7464 SIMPLEQ_FOREACH(qid, commits, entry) {
7465 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7466 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
7467 break;
7469 if (hle == NULL) {
7470 err = got_object_id_str(&id_str, qid->id);
7471 if (err)
7472 return err;
7473 snprintf(msg, sizeof(msg),
7474 "commit %s missing from histedit script", id_str);
7475 free(id_str);
7476 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7480 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
7481 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
7482 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
7483 "last commit in histedit script cannot be folded");
7485 return NULL;
7488 static const struct got_error *
7489 histedit_run_editor(struct got_histedit_list *histedit_cmds,
7490 const char *path, struct got_object_id_queue *commits,
7491 struct got_repository *repo)
7493 const struct got_error *err = NULL;
7494 char *editor;
7495 FILE *f = NULL;
7497 err = get_editor(&editor);
7498 if (err)
7499 return err;
7501 if (spawn_editor(editor, path) == -1) {
7502 err = got_error_from_errno("failed spawning editor");
7503 goto done;
7506 f = fopen(path, "r");
7507 if (f == NULL) {
7508 err = got_error_from_errno("fopen");
7509 goto done;
7511 err = histedit_parse_list(histedit_cmds, f, repo);
7512 if (err)
7513 goto done;
7515 err = histedit_check_script(histedit_cmds, commits, repo);
7516 done:
7517 if (f && fclose(f) != 0 && err == NULL)
7518 err = got_error_from_errno("fclose");
7519 free(editor);
7520 return err;
7523 static const struct got_error *
7524 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
7525 struct got_object_id_queue *, const char *, const char *,
7526 struct got_repository *);
7528 static const struct got_error *
7529 histedit_edit_script(struct got_histedit_list *histedit_cmds,
7530 struct got_object_id_queue *commits, const char *branch_name,
7531 int edit_logmsg_only, struct got_repository *repo)
7533 const struct got_error *err;
7534 FILE *f = NULL;
7535 char *path = NULL;
7537 err = got_opentemp_named(&path, &f, "got-histedit");
7538 if (err)
7539 return err;
7541 err = write_cmd_list(f, branch_name, commits);
7542 if (err)
7543 goto done;
7545 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
7546 if (err)
7547 goto done;
7549 if (edit_logmsg_only) {
7550 rewind(f);
7551 err = histedit_parse_list(histedit_cmds, f, repo);
7552 } else {
7553 if (fclose(f) != 0) {
7554 err = got_error_from_errno("fclose");
7555 goto done;
7557 f = NULL;
7558 err = histedit_run_editor(histedit_cmds, path, commits, repo);
7559 if (err) {
7560 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7561 err->code != GOT_ERR_HISTEDIT_CMD)
7562 goto done;
7563 err = histedit_edit_list_retry(histedit_cmds, err,
7564 commits, path, branch_name, repo);
7567 done:
7568 if (f && fclose(f) != 0 && err == NULL)
7569 err = got_error_from_errno("fclose");
7570 if (path && unlink(path) != 0 && err == NULL)
7571 err = got_error_from_errno2("unlink", path);
7572 free(path);
7573 return err;
7576 static const struct got_error *
7577 histedit_save_list(struct got_histedit_list *histedit_cmds,
7578 struct got_worktree *worktree, struct got_repository *repo)
7580 const struct got_error *err = NULL;
7581 char *path = NULL;
7582 FILE *f = NULL;
7583 struct got_histedit_list_entry *hle;
7584 struct got_commit_object *commit = NULL;
7586 err = got_worktree_get_histedit_script_path(&path, worktree);
7587 if (err)
7588 return err;
7590 f = fopen(path, "w");
7591 if (f == NULL) {
7592 err = got_error_from_errno2("fopen", path);
7593 goto done;
7595 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7596 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
7597 repo);
7598 if (err)
7599 break;
7601 if (hle->logmsg) {
7602 int n = fprintf(f, "%c %s\n",
7603 GOT_HISTEDIT_MESG, hle->logmsg);
7604 if (n < 0) {
7605 err = got_ferror(f, GOT_ERR_IO);
7606 break;
7610 done:
7611 if (f && fclose(f) != 0 && err == NULL)
7612 err = got_error_from_errno("fclose");
7613 free(path);
7614 if (commit)
7615 got_object_commit_close(commit);
7616 return err;
7619 void
7620 histedit_free_list(struct got_histedit_list *histedit_cmds)
7622 struct got_histedit_list_entry *hle;
7624 while ((hle = TAILQ_FIRST(histedit_cmds))) {
7625 TAILQ_REMOVE(histedit_cmds, hle, entry);
7626 free(hle);
7630 static const struct got_error *
7631 histedit_load_list(struct got_histedit_list *histedit_cmds,
7632 const char *path, struct got_repository *repo)
7634 const struct got_error *err = NULL;
7635 FILE *f = NULL;
7637 f = fopen(path, "r");
7638 if (f == NULL) {
7639 err = got_error_from_errno2("fopen", path);
7640 goto done;
7643 err = histedit_parse_list(histedit_cmds, f, repo);
7644 done:
7645 if (f && fclose(f) != 0 && err == NULL)
7646 err = got_error_from_errno("fclose");
7647 return err;
7650 static const struct got_error *
7651 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
7652 const struct got_error *edit_err, struct got_object_id_queue *commits,
7653 const char *path, const char *branch_name, struct got_repository *repo)
7655 const struct got_error *err = NULL, *prev_err = edit_err;
7656 int resp = ' ';
7658 while (resp != 'c' && resp != 'r' && resp != 'a') {
7659 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
7660 "or (a)bort: ", getprogname(), prev_err->msg);
7661 resp = getchar();
7662 if (resp == '\n')
7663 resp = getchar();
7664 if (resp == 'c') {
7665 histedit_free_list(histedit_cmds);
7666 err = histedit_run_editor(histedit_cmds, path, commits,
7667 repo);
7668 if (err) {
7669 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7670 err->code != GOT_ERR_HISTEDIT_CMD)
7671 break;
7672 prev_err = err;
7673 resp = ' ';
7674 continue;
7676 break;
7677 } else if (resp == 'r') {
7678 histedit_free_list(histedit_cmds);
7679 err = histedit_edit_script(histedit_cmds,
7680 commits, branch_name, 0, repo);
7681 if (err) {
7682 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7683 err->code != GOT_ERR_HISTEDIT_CMD)
7684 break;
7685 prev_err = err;
7686 resp = ' ';
7687 continue;
7689 break;
7690 } else if (resp == 'a') {
7691 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
7692 break;
7693 } else
7694 printf("invalid response '%c'\n", resp);
7697 return err;
7700 static const struct got_error *
7701 histedit_complete(struct got_worktree *worktree,
7702 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
7703 struct got_reference *branch, struct got_repository *repo)
7705 printf("Switching work tree to %s\n",
7706 got_ref_get_symref_target(branch));
7707 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
7708 branch, repo);
7711 static const struct got_error *
7712 show_histedit_progress(struct got_commit_object *commit,
7713 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
7715 const struct got_error *err;
7716 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7718 err = got_object_id_str(&old_id_str, hle->commit_id);
7719 if (err)
7720 goto done;
7722 if (new_id) {
7723 err = got_object_id_str(&new_id_str, new_id);
7724 if (err)
7725 goto done;
7728 old_id_str[12] = '\0';
7729 if (new_id_str)
7730 new_id_str[12] = '\0';
7732 if (hle->logmsg) {
7733 logmsg = strdup(hle->logmsg);
7734 if (logmsg == NULL) {
7735 err = got_error_from_errno("strdup");
7736 goto done;
7738 trim_logmsg(logmsg, 42);
7739 } else {
7740 err = get_short_logmsg(&logmsg, 42, commit);
7741 if (err)
7742 goto done;
7745 switch (hle->cmd->code) {
7746 case GOT_HISTEDIT_PICK:
7747 case GOT_HISTEDIT_EDIT:
7748 printf("%s -> %s: %s\n", old_id_str,
7749 new_id_str ? new_id_str : "no-op change", logmsg);
7750 break;
7751 case GOT_HISTEDIT_DROP:
7752 case GOT_HISTEDIT_FOLD:
7753 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
7754 logmsg);
7755 break;
7756 default:
7757 break;
7759 done:
7760 free(old_id_str);
7761 free(new_id_str);
7762 return err;
7765 static const struct got_error *
7766 histedit_commit(struct got_pathlist_head *merged_paths,
7767 struct got_worktree *worktree, struct got_fileindex *fileindex,
7768 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
7769 struct got_repository *repo)
7771 const struct got_error *err;
7772 struct got_commit_object *commit;
7773 struct got_object_id *new_commit_id;
7775 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
7776 && hle->logmsg == NULL) {
7777 err = histedit_edit_logmsg(hle, repo);
7778 if (err)
7779 return err;
7782 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7783 if (err)
7784 return err;
7786 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
7787 worktree, fileindex, tmp_branch, commit, hle->commit_id,
7788 hle->logmsg, repo);
7789 if (err) {
7790 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
7791 goto done;
7792 err = show_histedit_progress(commit, hle, NULL);
7793 } else {
7794 err = show_histedit_progress(commit, hle, new_commit_id);
7795 free(new_commit_id);
7797 done:
7798 got_object_commit_close(commit);
7799 return err;
7802 static const struct got_error *
7803 histedit_skip_commit(struct got_histedit_list_entry *hle,
7804 struct got_worktree *worktree, struct got_repository *repo)
7806 const struct got_error *error;
7807 struct got_commit_object *commit;
7809 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
7810 repo);
7811 if (error)
7812 return error;
7814 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
7815 if (error)
7816 return error;
7818 error = show_histedit_progress(commit, hle, NULL);
7819 got_object_commit_close(commit);
7820 return error;
7823 static const struct got_error *
7824 check_local_changes(void *arg, unsigned char status,
7825 unsigned char staged_status, const char *path,
7826 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
7827 struct got_object_id *commit_id, int dirfd, const char *de_name)
7829 int *have_local_changes = arg;
7831 switch (status) {
7832 case GOT_STATUS_ADD:
7833 case GOT_STATUS_DELETE:
7834 case GOT_STATUS_MODIFY:
7835 case GOT_STATUS_CONFLICT:
7836 *have_local_changes = 1;
7837 return got_error(GOT_ERR_CANCELLED);
7838 default:
7839 break;
7842 switch (staged_status) {
7843 case GOT_STATUS_ADD:
7844 case GOT_STATUS_DELETE:
7845 case GOT_STATUS_MODIFY:
7846 *have_local_changes = 1;
7847 return got_error(GOT_ERR_CANCELLED);
7848 default:
7849 break;
7852 return NULL;
7855 static const struct got_error *
7856 cmd_histedit(int argc, char *argv[])
7858 const struct got_error *error = NULL;
7859 struct got_worktree *worktree = NULL;
7860 struct got_fileindex *fileindex = NULL;
7861 struct got_repository *repo = NULL;
7862 char *cwd = NULL;
7863 struct got_reference *branch = NULL;
7864 struct got_reference *tmp_branch = NULL;
7865 struct got_object_id *resume_commit_id = NULL;
7866 struct got_object_id *base_commit_id = NULL;
7867 struct got_object_id *head_commit_id = NULL;
7868 struct got_commit_object *commit = NULL;
7869 int ch, rebase_in_progress = 0, did_something;
7870 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
7871 int edit_logmsg_only = 0;
7872 const char *edit_script_path = NULL;
7873 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7874 struct got_object_id_queue commits;
7875 struct got_pathlist_head merged_paths;
7876 const struct got_object_id_queue *parent_ids;
7877 struct got_object_qid *pid;
7878 struct got_histedit_list histedit_cmds;
7879 struct got_histedit_list_entry *hle;
7881 SIMPLEQ_INIT(&commits);
7882 TAILQ_INIT(&histedit_cmds);
7883 TAILQ_INIT(&merged_paths);
7885 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
7886 switch (ch) {
7887 case 'a':
7888 abort_edit = 1;
7889 break;
7890 case 'c':
7891 continue_edit = 1;
7892 break;
7893 case 'F':
7894 edit_script_path = optarg;
7895 break;
7896 case 'm':
7897 edit_logmsg_only = 1;
7898 break;
7899 default:
7900 usage_histedit();
7901 /* NOTREACHED */
7905 argc -= optind;
7906 argv += optind;
7908 #ifndef PROFILE
7909 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7910 "unveil", NULL) == -1)
7911 err(1, "pledge");
7912 #endif
7913 if (abort_edit && continue_edit)
7914 errx(1, "histedit's -a and -c options are mutually exclusive");
7915 if (edit_script_path && edit_logmsg_only)
7916 errx(1, "histedit's -F and -m options are mutually exclusive");
7917 if (abort_edit && edit_logmsg_only)
7918 errx(1, "histedit's -a and -m options are mutually exclusive");
7919 if (continue_edit && edit_logmsg_only)
7920 errx(1, "histedit's -c and -m options are mutually exclusive");
7921 if (argc != 0)
7922 usage_histedit();
7925 * This command cannot apply unveil(2) in all cases because the
7926 * user may choose to run an editor to edit the histedit script
7927 * and to edit individual commit log messages.
7928 * unveil(2) traverses exec(2); if an editor is used we have to
7929 * apply unveil after edit script and log messages have been written.
7930 * XXX TODO: Make use of unveil(2) where possible.
7933 cwd = getcwd(NULL, 0);
7934 if (cwd == NULL) {
7935 error = got_error_from_errno("getcwd");
7936 goto done;
7938 error = got_worktree_open(&worktree, cwd);
7939 if (error)
7940 goto done;
7942 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7943 NULL);
7944 if (error != NULL)
7945 goto done;
7947 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7948 if (error)
7949 goto done;
7950 if (rebase_in_progress) {
7951 error = got_error(GOT_ERR_REBASING);
7952 goto done;
7955 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
7956 if (error)
7957 goto done;
7959 if (edit_in_progress && edit_logmsg_only) {
7960 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
7961 "histedit operation is in progress in this "
7962 "work tree and must be continued or aborted "
7963 "before the -m option can be used");
7964 goto done;
7967 if (edit_in_progress && abort_edit) {
7968 error = got_worktree_histedit_continue(&resume_commit_id,
7969 &tmp_branch, &branch, &base_commit_id, &fileindex,
7970 worktree, repo);
7971 if (error)
7972 goto done;
7973 printf("Switching work tree to %s\n",
7974 got_ref_get_symref_target(branch));
7975 error = got_worktree_histedit_abort(worktree, fileindex, repo,
7976 branch, base_commit_id, update_progress, &did_something);
7977 if (error)
7978 goto done;
7979 printf("Histedit of %s aborted\n",
7980 got_ref_get_symref_target(branch));
7981 goto done; /* nothing else to do */
7982 } else if (abort_edit) {
7983 error = got_error(GOT_ERR_NOT_HISTEDIT);
7984 goto done;
7987 if (continue_edit) {
7988 char *path;
7990 if (!edit_in_progress) {
7991 error = got_error(GOT_ERR_NOT_HISTEDIT);
7992 goto done;
7995 error = got_worktree_get_histedit_script_path(&path, worktree);
7996 if (error)
7997 goto done;
7999 error = histedit_load_list(&histedit_cmds, path, repo);
8000 free(path);
8001 if (error)
8002 goto done;
8004 error = got_worktree_histedit_continue(&resume_commit_id,
8005 &tmp_branch, &branch, &base_commit_id, &fileindex,
8006 worktree, repo);
8007 if (error)
8008 goto done;
8010 error = got_ref_resolve(&head_commit_id, repo, branch);
8011 if (error)
8012 goto done;
8014 error = got_object_open_as_commit(&commit, repo,
8015 head_commit_id);
8016 if (error)
8017 goto done;
8018 parent_ids = got_object_commit_get_parent_ids(commit);
8019 pid = SIMPLEQ_FIRST(parent_ids);
8020 if (pid == NULL) {
8021 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8022 goto done;
8024 error = collect_commits(&commits, head_commit_id, pid->id,
8025 base_commit_id, got_worktree_get_path_prefix(worktree),
8026 GOT_ERR_HISTEDIT_PATH, repo);
8027 got_object_commit_close(commit);
8028 commit = NULL;
8029 if (error)
8030 goto done;
8031 } else {
8032 if (edit_in_progress) {
8033 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8034 goto done;
8037 error = got_ref_open(&branch, repo,
8038 got_worktree_get_head_ref_name(worktree), 0);
8039 if (error != NULL)
8040 goto done;
8042 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8043 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8044 "will not edit commit history of a branch outside "
8045 "the \"refs/heads/\" reference namespace");
8046 goto done;
8049 error = got_ref_resolve(&head_commit_id, repo, branch);
8050 got_ref_close(branch);
8051 branch = NULL;
8052 if (error)
8053 goto done;
8055 error = got_object_open_as_commit(&commit, repo,
8056 head_commit_id);
8057 if (error)
8058 goto done;
8059 parent_ids = got_object_commit_get_parent_ids(commit);
8060 pid = SIMPLEQ_FIRST(parent_ids);
8061 if (pid == NULL) {
8062 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8063 goto done;
8065 error = collect_commits(&commits, head_commit_id, pid->id,
8066 got_worktree_get_base_commit_id(worktree),
8067 got_worktree_get_path_prefix(worktree),
8068 GOT_ERR_HISTEDIT_PATH, repo);
8069 got_object_commit_close(commit);
8070 commit = NULL;
8071 if (error)
8072 goto done;
8074 if (SIMPLEQ_EMPTY(&commits)) {
8075 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8076 goto done;
8079 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8080 &base_commit_id, &fileindex, worktree, repo);
8081 if (error)
8082 goto done;
8084 if (edit_script_path) {
8085 error = histedit_load_list(&histedit_cmds,
8086 edit_script_path, repo);
8087 if (error) {
8088 got_worktree_histedit_abort(worktree, fileindex,
8089 repo, branch, base_commit_id,
8090 update_progress, &did_something);
8091 goto done;
8093 } else {
8094 const char *branch_name;
8095 branch_name = got_ref_get_symref_target(branch);
8096 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8097 branch_name += 11;
8098 error = histedit_edit_script(&histedit_cmds, &commits,
8099 branch_name, edit_logmsg_only, repo);
8100 if (error) {
8101 got_worktree_histedit_abort(worktree, fileindex,
8102 repo, branch, base_commit_id,
8103 update_progress, &did_something);
8104 goto done;
8109 error = histedit_save_list(&histedit_cmds, worktree,
8110 repo);
8111 if (error) {
8112 got_worktree_histedit_abort(worktree, fileindex,
8113 repo, branch, base_commit_id,
8114 update_progress, &did_something);
8115 goto done;
8120 error = histedit_check_script(&histedit_cmds, &commits, repo);
8121 if (error)
8122 goto done;
8124 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8125 if (resume_commit_id) {
8126 if (got_object_id_cmp(hle->commit_id,
8127 resume_commit_id) != 0)
8128 continue;
8130 resume_commit_id = NULL;
8131 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8132 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8133 error = histedit_skip_commit(hle, worktree,
8134 repo);
8135 if (error)
8136 goto done;
8137 } else {
8138 struct got_pathlist_head paths;
8139 int have_changes = 0;
8141 TAILQ_INIT(&paths);
8142 error = got_pathlist_append(&paths, "", NULL);
8143 if (error)
8144 goto done;
8145 error = got_worktree_status(worktree, &paths,
8146 repo, check_local_changes, &have_changes,
8147 check_cancelled, NULL);
8148 got_pathlist_free(&paths);
8149 if (error) {
8150 if (error->code != GOT_ERR_CANCELLED)
8151 goto done;
8152 if (sigint_received || sigpipe_received)
8153 goto done;
8155 if (have_changes) {
8156 error = histedit_commit(NULL, worktree,
8157 fileindex, tmp_branch, hle, repo);
8158 if (error)
8159 goto done;
8160 } else {
8161 error = got_object_open_as_commit(
8162 &commit, repo, hle->commit_id);
8163 if (error)
8164 goto done;
8165 error = show_histedit_progress(commit,
8166 hle, NULL);
8167 got_object_commit_close(commit);
8168 commit = NULL;
8169 if (error)
8170 goto done;
8173 continue;
8176 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8177 error = histedit_skip_commit(hle, worktree, repo);
8178 if (error)
8179 goto done;
8180 continue;
8183 error = got_object_open_as_commit(&commit, repo,
8184 hle->commit_id);
8185 if (error)
8186 goto done;
8187 parent_ids = got_object_commit_get_parent_ids(commit);
8188 pid = SIMPLEQ_FIRST(parent_ids);
8190 error = got_worktree_histedit_merge_files(&merged_paths,
8191 worktree, fileindex, pid->id, hle->commit_id, repo,
8192 rebase_progress, &rebase_status, check_cancelled, NULL);
8193 if (error)
8194 goto done;
8195 got_object_commit_close(commit);
8196 commit = NULL;
8198 if (rebase_status == GOT_STATUS_CONFLICT) {
8199 error = show_rebase_merge_conflict(hle->commit_id,
8200 repo);
8201 if (error)
8202 goto done;
8203 got_worktree_rebase_pathlist_free(&merged_paths);
8204 break;
8207 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8208 char *id_str;
8209 error = got_object_id_str(&id_str, hle->commit_id);
8210 if (error)
8211 goto done;
8212 printf("Stopping histedit for amending commit %s\n",
8213 id_str);
8214 free(id_str);
8215 got_worktree_rebase_pathlist_free(&merged_paths);
8216 error = got_worktree_histedit_postpone(worktree,
8217 fileindex);
8218 goto done;
8221 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8222 error = histedit_skip_commit(hle, worktree, repo);
8223 if (error)
8224 goto done;
8225 continue;
8228 error = histedit_commit(&merged_paths, worktree, fileindex,
8229 tmp_branch, hle, repo);
8230 got_worktree_rebase_pathlist_free(&merged_paths);
8231 if (error)
8232 goto done;
8235 if (rebase_status == GOT_STATUS_CONFLICT) {
8236 error = got_worktree_histedit_postpone(worktree, fileindex);
8237 if (error)
8238 goto done;
8239 error = got_error_msg(GOT_ERR_CONFLICTS,
8240 "conflicts must be resolved before histedit can continue");
8241 } else
8242 error = histedit_complete(worktree, fileindex, tmp_branch,
8243 branch, repo);
8244 done:
8245 got_object_id_queue_free(&commits);
8246 histedit_free_list(&histedit_cmds);
8247 free(head_commit_id);
8248 free(base_commit_id);
8249 free(resume_commit_id);
8250 if (commit)
8251 got_object_commit_close(commit);
8252 if (branch)
8253 got_ref_close(branch);
8254 if (tmp_branch)
8255 got_ref_close(tmp_branch);
8256 if (worktree)
8257 got_worktree_close(worktree);
8258 if (repo)
8259 got_repo_close(repo);
8260 return error;
8263 __dead static void
8264 usage_integrate(void)
8266 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
8267 exit(1);
8270 static const struct got_error *
8271 cmd_integrate(int argc, char *argv[])
8273 const struct got_error *error = NULL;
8274 struct got_repository *repo = NULL;
8275 struct got_worktree *worktree = NULL;
8276 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
8277 const char *branch_arg = NULL;
8278 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
8279 struct got_fileindex *fileindex = NULL;
8280 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
8281 int ch, did_something = 0;
8283 while ((ch = getopt(argc, argv, "")) != -1) {
8284 switch (ch) {
8285 default:
8286 usage_integrate();
8287 /* NOTREACHED */
8291 argc -= optind;
8292 argv += optind;
8294 if (argc != 1)
8295 usage_integrate();
8296 branch_arg = argv[0];
8298 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8299 "unveil", NULL) == -1)
8300 err(1, "pledge");
8302 cwd = getcwd(NULL, 0);
8303 if (cwd == NULL) {
8304 error = got_error_from_errno("getcwd");
8305 goto done;
8308 error = got_worktree_open(&worktree, cwd);
8309 if (error)
8310 goto done;
8312 error = check_rebase_or_histedit_in_progress(worktree);
8313 if (error)
8314 goto done;
8316 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8317 NULL);
8318 if (error != NULL)
8319 goto done;
8321 error = apply_unveil(got_repo_get_path(repo), 0,
8322 got_worktree_get_root_path(worktree));
8323 if (error)
8324 goto done;
8326 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
8327 error = got_error_from_errno("asprintf");
8328 goto done;
8331 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
8332 &base_branch_ref, worktree, refname, repo);
8333 if (error)
8334 goto done;
8336 refname = strdup(got_ref_get_name(branch_ref));
8337 if (refname == NULL) {
8338 error = got_error_from_errno("strdup");
8339 got_worktree_integrate_abort(worktree, fileindex, repo,
8340 branch_ref, base_branch_ref);
8341 goto done;
8343 base_refname = strdup(got_ref_get_name(base_branch_ref));
8344 if (base_refname == NULL) {
8345 error = got_error_from_errno("strdup");
8346 got_worktree_integrate_abort(worktree, fileindex, repo,
8347 branch_ref, base_branch_ref);
8348 goto done;
8351 error = got_ref_resolve(&commit_id, repo, branch_ref);
8352 if (error)
8353 goto done;
8355 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
8356 if (error)
8357 goto done;
8359 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
8360 error = got_error_msg(GOT_ERR_SAME_BRANCH,
8361 "specified branch has already been integrated");
8362 got_worktree_integrate_abort(worktree, fileindex, repo,
8363 branch_ref, base_branch_ref);
8364 goto done;
8367 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
8368 if (error) {
8369 if (error->code == GOT_ERR_ANCESTRY)
8370 error = got_error(GOT_ERR_REBASE_REQUIRED);
8371 got_worktree_integrate_abort(worktree, fileindex, repo,
8372 branch_ref, base_branch_ref);
8373 goto done;
8376 error = got_worktree_integrate_continue(worktree, fileindex, repo,
8377 branch_ref, base_branch_ref, update_progress, &did_something,
8378 check_cancelled, NULL);
8379 if (error)
8380 goto done;
8382 printf("Integrated %s into %s\n", refname, base_refname);
8383 done:
8384 if (repo)
8385 got_repo_close(repo);
8386 if (worktree)
8387 got_worktree_close(worktree);
8388 free(cwd);
8389 free(base_commit_id);
8390 free(commit_id);
8391 free(refname);
8392 free(base_refname);
8393 return error;
8396 __dead static void
8397 usage_stage(void)
8399 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
8400 "[file-path ...]\n",
8401 getprogname());
8402 exit(1);
8405 static const struct got_error *
8406 print_stage(void *arg, unsigned char status, unsigned char staged_status,
8407 const char *path, struct got_object_id *blob_id,
8408 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
8409 int dirfd, const char *de_name)
8411 const struct got_error *err = NULL;
8412 char *id_str = NULL;
8414 if (staged_status != GOT_STATUS_ADD &&
8415 staged_status != GOT_STATUS_MODIFY &&
8416 staged_status != GOT_STATUS_DELETE)
8417 return NULL;
8419 if (staged_status == GOT_STATUS_ADD ||
8420 staged_status == GOT_STATUS_MODIFY)
8421 err = got_object_id_str(&id_str, staged_blob_id);
8422 else
8423 err = got_object_id_str(&id_str, blob_id);
8424 if (err)
8425 return err;
8427 printf("%s %c %s\n", id_str, staged_status, path);
8428 free(id_str);
8429 return NULL;
8432 static const struct got_error *
8433 cmd_stage(int argc, char *argv[])
8435 const struct got_error *error = NULL;
8436 struct got_repository *repo = NULL;
8437 struct got_worktree *worktree = NULL;
8438 char *cwd = NULL;
8439 struct got_pathlist_head paths;
8440 struct got_pathlist_entry *pe;
8441 int ch, list_stage = 0, pflag = 0;
8442 FILE *patch_script_file = NULL;
8443 const char *patch_script_path = NULL;
8444 struct choose_patch_arg cpa;
8446 TAILQ_INIT(&paths);
8448 while ((ch = getopt(argc, argv, "lpF:")) != -1) {
8449 switch (ch) {
8450 case 'l':
8451 list_stage = 1;
8452 break;
8453 case 'p':
8454 pflag = 1;
8455 break;
8456 case 'F':
8457 patch_script_path = optarg;
8458 break;
8459 default:
8460 usage_stage();
8461 /* NOTREACHED */
8465 argc -= optind;
8466 argv += optind;
8468 #ifndef PROFILE
8469 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8470 "unveil", NULL) == -1)
8471 err(1, "pledge");
8472 #endif
8473 if (list_stage && (pflag || patch_script_path))
8474 errx(1, "-l option cannot be used with other options");
8475 if (patch_script_path && !pflag)
8476 errx(1, "-F option can only be used together with -p option");
8478 cwd = getcwd(NULL, 0);
8479 if (cwd == NULL) {
8480 error = got_error_from_errno("getcwd");
8481 goto done;
8484 error = got_worktree_open(&worktree, cwd);
8485 if (error)
8486 goto done;
8488 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8489 NULL);
8490 if (error != NULL)
8491 goto done;
8493 if (patch_script_path) {
8494 patch_script_file = fopen(patch_script_path, "r");
8495 if (patch_script_file == NULL) {
8496 error = got_error_from_errno2("fopen",
8497 patch_script_path);
8498 goto done;
8501 error = apply_unveil(got_repo_get_path(repo), 0,
8502 got_worktree_get_root_path(worktree));
8503 if (error)
8504 goto done;
8506 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8507 if (error)
8508 goto done;
8510 if (list_stage)
8511 error = got_worktree_status(worktree, &paths, repo,
8512 print_stage, NULL, check_cancelled, NULL);
8513 else {
8514 cpa.patch_script_file = patch_script_file;
8515 cpa.action = "stage";
8516 error = got_worktree_stage(worktree, &paths,
8517 pflag ? NULL : print_status, NULL,
8518 pflag ? choose_patch : NULL, &cpa, repo);
8520 done:
8521 if (patch_script_file && fclose(patch_script_file) == EOF &&
8522 error == NULL)
8523 error = got_error_from_errno2("fclose", patch_script_path);
8524 if (repo)
8525 got_repo_close(repo);
8526 if (worktree)
8527 got_worktree_close(worktree);
8528 TAILQ_FOREACH(pe, &paths, entry)
8529 free((char *)pe->path);
8530 got_pathlist_free(&paths);
8531 free(cwd);
8532 return error;
8535 __dead static void
8536 usage_unstage(void)
8538 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
8539 "[file-path ...]\n",
8540 getprogname());
8541 exit(1);
8545 static const struct got_error *
8546 cmd_unstage(int argc, char *argv[])
8548 const struct got_error *error = NULL;
8549 struct got_repository *repo = NULL;
8550 struct got_worktree *worktree = NULL;
8551 char *cwd = NULL;
8552 struct got_pathlist_head paths;
8553 struct got_pathlist_entry *pe;
8554 int ch, did_something = 0, pflag = 0;
8555 FILE *patch_script_file = NULL;
8556 const char *patch_script_path = NULL;
8557 struct choose_patch_arg cpa;
8559 TAILQ_INIT(&paths);
8561 while ((ch = getopt(argc, argv, "pF:")) != -1) {
8562 switch (ch) {
8563 case 'p':
8564 pflag = 1;
8565 break;
8566 case 'F':
8567 patch_script_path = optarg;
8568 break;
8569 default:
8570 usage_unstage();
8571 /* NOTREACHED */
8575 argc -= optind;
8576 argv += optind;
8578 #ifndef PROFILE
8579 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8580 "unveil", NULL) == -1)
8581 err(1, "pledge");
8582 #endif
8583 if (patch_script_path && !pflag)
8584 errx(1, "-F option can only be used together with -p option");
8586 cwd = getcwd(NULL, 0);
8587 if (cwd == NULL) {
8588 error = got_error_from_errno("getcwd");
8589 goto done;
8592 error = got_worktree_open(&worktree, cwd);
8593 if (error)
8594 goto done;
8596 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8597 NULL);
8598 if (error != NULL)
8599 goto done;
8601 if (patch_script_path) {
8602 patch_script_file = fopen(patch_script_path, "r");
8603 if (patch_script_file == NULL) {
8604 error = got_error_from_errno2("fopen",
8605 patch_script_path);
8606 goto done;
8610 error = apply_unveil(got_repo_get_path(repo), 0,
8611 got_worktree_get_root_path(worktree));
8612 if (error)
8613 goto done;
8615 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8616 if (error)
8617 goto done;
8619 cpa.patch_script_file = patch_script_file;
8620 cpa.action = "unstage";
8621 error = got_worktree_unstage(worktree, &paths, update_progress,
8622 &did_something, pflag ? choose_patch : NULL, &cpa, repo);
8623 done:
8624 if (patch_script_file && fclose(patch_script_file) == EOF &&
8625 error == NULL)
8626 error = got_error_from_errno2("fclose", patch_script_path);
8627 if (repo)
8628 got_repo_close(repo);
8629 if (worktree)
8630 got_worktree_close(worktree);
8631 TAILQ_FOREACH(pe, &paths, entry)
8632 free((char *)pe->path);
8633 got_pathlist_free(&paths);
8634 free(cwd);
8635 return error;
8638 __dead static void
8639 usage_cat(void)
8641 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
8642 "arg1 [arg2 ...]\n", getprogname());
8643 exit(1);
8646 static const struct got_error *
8647 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8649 const struct got_error *err;
8650 struct got_blob_object *blob;
8652 err = got_object_open_as_blob(&blob, repo, id, 8192);
8653 if (err)
8654 return err;
8656 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
8657 got_object_blob_close(blob);
8658 return err;
8661 static const struct got_error *
8662 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8664 const struct got_error *err;
8665 struct got_tree_object *tree;
8666 int nentries, i;
8668 err = got_object_open_as_tree(&tree, repo, id);
8669 if (err)
8670 return err;
8672 nentries = got_object_tree_get_nentries(tree);
8673 for (i = 0; i < nentries; i++) {
8674 struct got_tree_entry *te;
8675 char *id_str;
8676 if (sigint_received || sigpipe_received)
8677 break;
8678 te = got_object_tree_get_entry(tree, i);
8679 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
8680 if (err)
8681 break;
8682 fprintf(outfile, "%s %.7o %s\n", id_str,
8683 got_tree_entry_get_mode(te),
8684 got_tree_entry_get_name(te));
8685 free(id_str);
8688 got_object_tree_close(tree);
8689 return err;
8692 static const struct got_error *
8693 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8695 const struct got_error *err;
8696 struct got_commit_object *commit;
8697 const struct got_object_id_queue *parent_ids;
8698 struct got_object_qid *pid;
8699 char *id_str = NULL;
8700 const char *logmsg = NULL;
8702 err = got_object_open_as_commit(&commit, repo, id);
8703 if (err)
8704 return err;
8706 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
8707 if (err)
8708 goto done;
8710 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
8711 parent_ids = got_object_commit_get_parent_ids(commit);
8712 fprintf(outfile, "numparents %d\n",
8713 got_object_commit_get_nparents(commit));
8714 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
8715 char *pid_str;
8716 err = got_object_id_str(&pid_str, pid->id);
8717 if (err)
8718 goto done;
8719 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
8720 free(pid_str);
8722 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
8723 got_object_commit_get_author(commit),
8724 got_object_commit_get_author_time(commit));
8726 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
8727 got_object_commit_get_author(commit),
8728 got_object_commit_get_committer_time(commit));
8730 logmsg = got_object_commit_get_logmsg_raw(commit);
8731 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
8732 fprintf(outfile, "%s", logmsg);
8733 done:
8734 free(id_str);
8735 got_object_commit_close(commit);
8736 return err;
8739 static const struct got_error *
8740 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8742 const struct got_error *err;
8743 struct got_tag_object *tag;
8744 char *id_str = NULL;
8745 const char *tagmsg = NULL;
8747 err = got_object_open_as_tag(&tag, repo, id);
8748 if (err)
8749 return err;
8751 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
8752 if (err)
8753 goto done;
8755 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
8757 switch (got_object_tag_get_object_type(tag)) {
8758 case GOT_OBJ_TYPE_BLOB:
8759 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8760 GOT_OBJ_LABEL_BLOB);
8761 break;
8762 case GOT_OBJ_TYPE_TREE:
8763 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8764 GOT_OBJ_LABEL_TREE);
8765 break;
8766 case GOT_OBJ_TYPE_COMMIT:
8767 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8768 GOT_OBJ_LABEL_COMMIT);
8769 break;
8770 case GOT_OBJ_TYPE_TAG:
8771 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8772 GOT_OBJ_LABEL_TAG);
8773 break;
8774 default:
8775 break;
8778 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
8779 got_object_tag_get_name(tag));
8781 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
8782 got_object_tag_get_tagger(tag),
8783 got_object_tag_get_tagger_time(tag));
8785 tagmsg = got_object_tag_get_message(tag);
8786 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
8787 fprintf(outfile, "%s", tagmsg);
8788 done:
8789 free(id_str);
8790 got_object_tag_close(tag);
8791 return err;
8794 static const struct got_error *
8795 cmd_cat(int argc, char *argv[])
8797 const struct got_error *error;
8798 struct got_repository *repo = NULL;
8799 struct got_worktree *worktree = NULL;
8800 char *cwd = NULL, *repo_path = NULL, *label = NULL;
8801 const char *commit_id_str = NULL;
8802 struct got_object_id *id = NULL, *commit_id = NULL;
8803 int ch, obj_type, i, force_path = 0;
8805 #ifndef PROFILE
8806 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8807 NULL) == -1)
8808 err(1, "pledge");
8809 #endif
8811 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
8812 switch (ch) {
8813 case 'c':
8814 commit_id_str = optarg;
8815 break;
8816 case 'r':
8817 repo_path = realpath(optarg, NULL);
8818 if (repo_path == NULL)
8819 return got_error_from_errno2("realpath",
8820 optarg);
8821 got_path_strip_trailing_slashes(repo_path);
8822 break;
8823 case 'P':
8824 force_path = 1;
8825 break;
8826 default:
8827 usage_cat();
8828 /* NOTREACHED */
8832 argc -= optind;
8833 argv += optind;
8835 cwd = getcwd(NULL, 0);
8836 if (cwd == NULL) {
8837 error = got_error_from_errno("getcwd");
8838 goto done;
8840 error = got_worktree_open(&worktree, cwd);
8841 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8842 goto done;
8843 if (worktree) {
8844 if (repo_path == NULL) {
8845 repo_path = strdup(
8846 got_worktree_get_repo_path(worktree));
8847 if (repo_path == NULL) {
8848 error = got_error_from_errno("strdup");
8849 goto done;
8854 if (repo_path == NULL) {
8855 repo_path = getcwd(NULL, 0);
8856 if (repo_path == NULL)
8857 return got_error_from_errno("getcwd");
8860 error = got_repo_open(&repo, repo_path, NULL);
8861 free(repo_path);
8862 if (error != NULL)
8863 goto done;
8865 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
8866 if (error)
8867 goto done;
8869 if (commit_id_str == NULL)
8870 commit_id_str = GOT_REF_HEAD;
8871 error = got_repo_match_object_id(&commit_id, NULL,
8872 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
8873 if (error)
8874 goto done;
8876 for (i = 0; i < argc; i++) {
8877 if (force_path) {
8878 error = got_object_id_by_path(&id, repo, commit_id,
8879 argv[i]);
8880 if (error)
8881 break;
8882 } else {
8883 error = got_repo_match_object_id(&id, &label, argv[i],
8884 GOT_OBJ_TYPE_ANY, 0, repo);
8885 if (error) {
8886 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
8887 error->code != GOT_ERR_NOT_REF)
8888 break;
8889 error = got_object_id_by_path(&id, repo,
8890 commit_id, argv[i]);
8891 if (error)
8892 break;
8896 error = got_object_get_type(&obj_type, repo, id);
8897 if (error)
8898 break;
8900 switch (obj_type) {
8901 case GOT_OBJ_TYPE_BLOB:
8902 error = cat_blob(id, repo, stdout);
8903 break;
8904 case GOT_OBJ_TYPE_TREE:
8905 error = cat_tree(id, repo, stdout);
8906 break;
8907 case GOT_OBJ_TYPE_COMMIT:
8908 error = cat_commit(id, repo, stdout);
8909 break;
8910 case GOT_OBJ_TYPE_TAG:
8911 error = cat_tag(id, repo, stdout);
8912 break;
8913 default:
8914 error = got_error(GOT_ERR_OBJ_TYPE);
8915 break;
8917 if (error)
8918 break;
8919 free(label);
8920 label = NULL;
8921 free(id);
8922 id = NULL;
8924 done:
8925 free(label);
8926 free(id);
8927 free(commit_id);
8928 if (worktree)
8929 got_worktree_close(worktree);
8930 if (repo) {
8931 const struct got_error *repo_error;
8932 repo_error = got_repo_close(repo);
8933 if (error == NULL)
8934 error = repo_error;
8936 return error;