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 __dead static void
1506 usage_fetch(void)
1508 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1509 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1510 "[remote-repository-name]\n",
1511 getprogname());
1512 exit(1);
1515 static const struct got_error *
1516 delete_missing_refs(struct got_pathlist_head *their_refs,
1517 int verbosity, struct got_repository *repo)
1519 const struct got_error *err = NULL;
1520 struct got_reflist_head my_refs;
1521 struct got_reflist_entry *re;
1522 struct got_pathlist_entry *pe;
1523 struct got_object_id *id;
1524 char *id_str;
1526 SIMPLEQ_INIT(&my_refs);
1528 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1529 if (err)
1530 return err;
1532 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1533 const char *refname = got_ref_get_name(re->ref);
1535 if (strncmp(refname, "refs/heads/", 11) != 0 &&
1536 strncmp(refname, "refs/tags/", 10) != 0)
1537 continue;
1539 TAILQ_FOREACH(pe, their_refs, entry) {
1540 if (strcmp(refname, pe->path) == 0)
1541 break;
1543 if (pe != NULL)
1544 continue;
1546 err = got_ref_resolve(&id, repo, re->ref);
1547 if (err)
1548 break;
1549 err = got_object_id_str(&id_str, id);
1550 free(id);
1551 if (err)
1552 break;
1554 free(id_str);
1555 err = got_ref_delete(re->ref, repo);
1556 if (err)
1557 break;
1558 if (verbosity >= 0) {
1559 printf("Deleted reference %s: %s\n",
1560 got_ref_get_name(re->ref), id_str);
1564 return err;
1567 static const struct got_error *
1568 update_wanted_ref(const char *refname, struct got_object_id *id,
1569 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1571 const struct got_error *err, *unlock_err;
1572 char *remote_refname;
1573 struct got_reference *ref;
1575 if (strncmp("refs/", refname, 5) == 0)
1576 refname += 5;
1578 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1579 remote_repo_name, refname) == -1)
1580 return got_error_from_errno("asprintf");
1582 err = got_ref_open(&ref, repo, remote_refname, 1);
1583 if (err) {
1584 if (err->code != GOT_ERR_NOT_REF)
1585 goto done;
1586 err = create_ref(remote_refname, id, verbosity, repo);
1587 } else {
1588 err = update_ref(ref, id, 0, verbosity, repo);
1589 unlock_err = got_ref_unlock(ref);
1590 if (unlock_err && err == NULL)
1591 err = unlock_err;
1592 got_ref_close(ref);
1594 done:
1595 free(remote_refname);
1596 return err;
1599 static const struct got_error *
1600 cmd_fetch(int argc, char *argv[])
1602 const struct got_error *error = NULL, *unlock_err;
1603 char *cwd = NULL, *repo_path = NULL;
1604 const char *remote_name;
1605 char *proto = NULL, *host = NULL, *port = NULL;
1606 char *repo_name = NULL, *server_path = NULL;
1607 struct got_remote_repo *remotes, *remote = NULL;
1608 int nremotes;
1609 char *id_str = NULL;
1610 struct got_repository *repo = NULL;
1611 struct got_worktree *worktree = NULL;
1612 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1613 struct got_pathlist_entry *pe;
1614 struct got_object_id *pack_hash = NULL;
1615 int i, ch, fetchfd = -1, fetchstatus;
1616 pid_t fetchpid = -1;
1617 struct got_fetch_progress_arg fpa;
1618 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
1619 int delete_refs = 0, replace_tags = 0;
1621 TAILQ_INIT(&refs);
1622 TAILQ_INIT(&symrefs);
1623 TAILQ_INIT(&wanted_branches);
1624 TAILQ_INIT(&wanted_refs);
1626 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
1627 switch (ch) {
1628 case 'a':
1629 fetch_all_branches = 1;
1630 break;
1631 case 'b':
1632 error = got_pathlist_append(&wanted_branches,
1633 optarg, NULL);
1634 if (error)
1635 return error;
1636 break;
1637 case 'd':
1638 delete_refs = 1;
1639 break;
1640 case 'l':
1641 list_refs_only = 1;
1642 break;
1643 case 'r':
1644 repo_path = realpath(optarg, NULL);
1645 if (repo_path == NULL)
1646 return got_error_from_errno2("realpath",
1647 optarg);
1648 got_path_strip_trailing_slashes(repo_path);
1649 break;
1650 case 't':
1651 replace_tags = 1;
1652 break;
1653 case 'v':
1654 if (verbosity < 0)
1655 verbosity = 0;
1656 else if (verbosity < 3)
1657 verbosity++;
1658 break;
1659 case 'q':
1660 verbosity = -1;
1661 break;
1662 case 'R':
1663 error = got_pathlist_append(&wanted_refs,
1664 optarg, NULL);
1665 if (error)
1666 return error;
1667 break;
1668 default:
1669 usage_fetch();
1670 break;
1673 argc -= optind;
1674 argv += optind;
1676 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1677 errx(1, "-a and -b options are mutually exclusive");
1678 if (list_refs_only) {
1679 if (!TAILQ_EMPTY(&wanted_branches))
1680 errx(1, "-l and -b options are mutually exclusive");
1681 if (fetch_all_branches)
1682 errx(1, "-l and -a options are mutually exclusive");
1683 if (delete_refs)
1684 errx(1, "-l and -d options are mutually exclusive");
1685 if (verbosity == -1)
1686 errx(1, "-l and -q options are mutually exclusive");
1689 if (argc == 0)
1690 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
1691 else if (argc == 1)
1692 remote_name = argv[0];
1693 else
1694 usage_fetch();
1696 cwd = getcwd(NULL, 0);
1697 if (cwd == NULL) {
1698 error = got_error_from_errno("getcwd");
1699 goto done;
1702 if (repo_path == NULL) {
1703 error = got_worktree_open(&worktree, cwd);
1704 if (error && error->code != GOT_ERR_NOT_WORKTREE)
1705 goto done;
1706 else
1707 error = NULL;
1708 if (worktree) {
1709 repo_path =
1710 strdup(got_worktree_get_repo_path(worktree));
1711 if (repo_path == NULL)
1712 error = got_error_from_errno("strdup");
1713 if (error)
1714 goto done;
1715 } else {
1716 repo_path = strdup(cwd);
1717 if (repo_path == NULL) {
1718 error = got_error_from_errno("strdup");
1719 goto done;
1724 error = got_repo_open(&repo, repo_path, NULL);
1725 if (error)
1726 goto done;
1728 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
1729 for (i = 0; i < nremotes; i++) {
1730 remote = &remotes[i];
1731 if (strcmp(remote->name, remote_name) == 0)
1732 break;
1734 if (i == nremotes) {
1735 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
1736 goto done;
1739 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1740 &repo_name, remote->url);
1741 if (error)
1742 goto done;
1744 if (strcmp(proto, "git") == 0) {
1745 #ifndef PROFILE
1746 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1747 "sendfd dns inet unveil", NULL) == -1)
1748 err(1, "pledge");
1749 #endif
1750 } else if (strcmp(proto, "git+ssh") == 0 ||
1751 strcmp(proto, "ssh") == 0) {
1752 #ifndef PROFILE
1753 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1754 "sendfd unveil", NULL) == -1)
1755 err(1, "pledge");
1756 #endif
1757 } else if (strcmp(proto, "http") == 0 ||
1758 strcmp(proto, "git+http") == 0) {
1759 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1760 goto done;
1761 } else {
1762 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1763 goto done;
1766 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1767 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1768 error = got_error_from_errno2("unveil",
1769 GOT_FETCH_PATH_SSH);
1770 goto done;
1773 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
1774 if (error)
1775 goto done;
1777 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1778 server_path, verbosity);
1779 if (error)
1780 goto done;
1782 if (verbosity >= 0)
1783 printf("Connected to \"%s\" %s%s%s\n", remote->name, host,
1784 port ? ":" : "", port ? port : "");
1786 fpa.last_scaled_size[0] = '\0';
1787 fpa.last_p_indexed = -1;
1788 fpa.last_p_resolved = -1;
1789 fpa.verbosity = verbosity;
1790 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
1791 remote->mirror_references, fetch_all_branches, &wanted_branches,
1792 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
1793 fetch_progress, &fpa);
1794 if (error)
1795 goto done;
1797 if (list_refs_only) {
1798 error = list_remote_refs(&symrefs, &refs);
1799 goto done;
1802 if (pack_hash == NULL) {
1803 if (verbosity >= 0)
1804 printf("Already up-to-date\n");
1805 if (delete_refs)
1806 error = delete_missing_refs(&refs, verbosity, repo);
1807 goto done;
1810 if (verbosity >= 0) {
1811 error = got_object_id_str(&id_str, pack_hash);
1812 if (error)
1813 goto done;
1814 printf("\nFetched %s.pack\n", id_str);
1815 free(id_str);
1816 id_str = NULL;
1819 /* Update references provided with the pack file. */
1820 TAILQ_FOREACH(pe, &refs, entry) {
1821 const char *refname = pe->path;
1822 struct got_object_id *id = pe->data;
1823 struct got_reference *ref;
1824 char *remote_refname;
1826 if (is_wanted_ref(&wanted_refs, refname) &&
1827 !remote->mirror_references) {
1828 error = update_wanted_ref(refname, id,
1829 remote->name, verbosity, repo);
1830 if (error)
1831 goto done;
1832 continue;
1835 if (remote->mirror_references ||
1836 strncmp("refs/tags/", refname, 10) == 0) {
1837 error = got_ref_open(&ref, repo, refname, 1);
1838 if (error) {
1839 if (error->code != GOT_ERR_NOT_REF)
1840 goto done;
1841 error = create_ref(refname, id, verbosity,
1842 repo);
1843 if (error)
1844 goto done;
1845 } else {
1846 error = update_ref(ref, id, replace_tags,
1847 verbosity, repo);
1848 unlock_err = got_ref_unlock(ref);
1849 if (unlock_err && error == NULL)
1850 error = unlock_err;
1851 got_ref_close(ref);
1852 if (error)
1853 goto done;
1855 } else if (strncmp("refs/heads/", refname, 11) == 0) {
1856 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1857 remote_name, refname + 11) == -1) {
1858 error = got_error_from_errno("asprintf");
1859 goto done;
1862 error = got_ref_open(&ref, repo, remote_refname, 1);
1863 if (error) {
1864 if (error->code != GOT_ERR_NOT_REF)
1865 goto done;
1866 error = create_ref(remote_refname, id,
1867 verbosity, repo);
1868 if (error)
1869 goto done;
1870 } else {
1871 error = update_ref(ref, id, replace_tags,
1872 verbosity, repo);
1873 unlock_err = got_ref_unlock(ref);
1874 if (unlock_err && error == NULL)
1875 error = unlock_err;
1876 got_ref_close(ref);
1877 if (error)
1878 goto done;
1881 /* Also create a local branch if none exists yet. */
1882 error = got_ref_open(&ref, repo, refname, 1);
1883 if (error) {
1884 if (error->code != GOT_ERR_NOT_REF)
1885 goto done;
1886 error = create_ref(refname, id, verbosity,
1887 repo);
1888 if (error)
1889 goto done;
1890 } else {
1891 unlock_err = got_ref_unlock(ref);
1892 if (unlock_err && error == NULL)
1893 error = unlock_err;
1894 got_ref_close(ref);
1898 if (delete_refs)
1899 error = delete_missing_refs(&refs, verbosity, repo);
1900 done:
1901 if (fetchpid > 0) {
1902 if (kill(fetchpid, SIGTERM) == -1)
1903 error = got_error_from_errno("kill");
1904 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1905 error = got_error_from_errno("waitpid");
1907 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1908 error = got_error_from_errno("close");
1909 if (repo)
1910 got_repo_close(repo);
1911 if (worktree)
1912 got_worktree_close(worktree);
1913 TAILQ_FOREACH(pe, &refs, entry) {
1914 free((void *)pe->path);
1915 free(pe->data);
1917 got_pathlist_free(&refs);
1918 TAILQ_FOREACH(pe, &symrefs, entry) {
1919 free((void *)pe->path);
1920 free(pe->data);
1922 got_pathlist_free(&symrefs);
1923 got_pathlist_free(&wanted_branches);
1924 got_pathlist_free(&wanted_refs);
1925 free(id_str);
1926 free(cwd);
1927 free(repo_path);
1928 free(pack_hash);
1929 free(proto);
1930 free(host);
1931 free(port);
1932 free(server_path);
1933 free(repo_name);
1934 return error;
1938 __dead static void
1939 usage_checkout(void)
1941 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
1942 "[-p prefix] repository-path [worktree-path]\n", getprogname());
1943 exit(1);
1946 static void
1947 show_worktree_base_ref_warning(void)
1949 fprintf(stderr, "%s: warning: could not create a reference "
1950 "to the work tree's base commit; the commit could be "
1951 "garbage-collected by Git; making the repository "
1952 "writable and running 'got update' will prevent this\n",
1953 getprogname());
1956 struct got_checkout_progress_arg {
1957 const char *worktree_path;
1958 int had_base_commit_ref_error;
1961 static const struct got_error *
1962 checkout_progress(void *arg, unsigned char status, const char *path)
1964 struct got_checkout_progress_arg *a = arg;
1966 /* Base commit bump happens silently. */
1967 if (status == GOT_STATUS_BUMP_BASE)
1968 return NULL;
1970 if (status == GOT_STATUS_BASE_REF_ERR) {
1971 a->had_base_commit_ref_error = 1;
1972 return NULL;
1975 while (path[0] == '/')
1976 path++;
1978 printf("%c %s/%s\n", status, a->worktree_path, path);
1979 return NULL;
1982 static const struct got_error *
1983 check_cancelled(void *arg)
1985 if (sigint_received || sigpipe_received)
1986 return got_error(GOT_ERR_CANCELLED);
1987 return NULL;
1990 static const struct got_error *
1991 check_linear_ancestry(struct got_object_id *commit_id,
1992 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
1993 struct got_repository *repo)
1995 const struct got_error *err = NULL;
1996 struct got_object_id *yca_id;
1998 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
1999 commit_id, base_commit_id, repo, check_cancelled, NULL);
2000 if (err)
2001 return err;
2003 if (yca_id == NULL)
2004 return got_error(GOT_ERR_ANCESTRY);
2007 * Require a straight line of history between the target commit
2008 * and the work tree's base commit.
2010 * Non-linear situations such as this require a rebase:
2012 * (commit) D F (base_commit)
2013 * \ /
2014 * C E
2015 * \ /
2016 * B (yca)
2017 * |
2018 * A
2020 * 'got update' only handles linear cases:
2021 * Update forwards in time: A (base/yca) - B - C - D (commit)
2022 * Update backwards in time: D (base) - C - B - A (commit/yca)
2024 if (allow_forwards_in_time_only) {
2025 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2026 return got_error(GOT_ERR_ANCESTRY);
2027 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2028 got_object_id_cmp(base_commit_id, yca_id) != 0)
2029 return got_error(GOT_ERR_ANCESTRY);
2031 free(yca_id);
2032 return NULL;
2035 static const struct got_error *
2036 check_same_branch(struct got_object_id *commit_id,
2037 struct got_reference *head_ref, struct got_object_id *yca_id,
2038 struct got_repository *repo)
2040 const struct got_error *err = NULL;
2041 struct got_commit_graph *graph = NULL;
2042 struct got_object_id *head_commit_id = NULL;
2043 int is_same_branch = 0;
2045 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2046 if (err)
2047 goto done;
2049 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2050 is_same_branch = 1;
2051 goto done;
2053 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2054 is_same_branch = 1;
2055 goto done;
2058 err = got_commit_graph_open(&graph, "/", 1);
2059 if (err)
2060 goto done;
2062 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2063 check_cancelled, NULL);
2064 if (err)
2065 goto done;
2067 for (;;) {
2068 struct got_object_id *id;
2069 err = got_commit_graph_iter_next(&id, graph, repo,
2070 check_cancelled, NULL);
2071 if (err) {
2072 if (err->code == GOT_ERR_ITER_COMPLETED)
2073 err = NULL;
2074 break;
2077 if (id) {
2078 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2079 break;
2080 if (got_object_id_cmp(id, commit_id) == 0) {
2081 is_same_branch = 1;
2082 break;
2086 done:
2087 if (graph)
2088 got_commit_graph_close(graph);
2089 free(head_commit_id);
2090 if (!err && !is_same_branch)
2091 err = got_error(GOT_ERR_ANCESTRY);
2092 return err;
2095 static const struct got_error *
2096 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2098 static char msg[512];
2099 const char *branch_name;
2101 if (got_ref_is_symbolic(ref))
2102 branch_name = got_ref_get_symref_target(ref);
2103 else
2104 branch_name = got_ref_get_name(ref);
2106 if (strncmp("refs/heads/", branch_name, 11) == 0)
2107 branch_name += 11;
2109 snprintf(msg, sizeof(msg),
2110 "target commit is not contained in branch '%s'; "
2111 "the branch to use must be specified with -b; "
2112 "if necessary a new branch can be created for "
2113 "this commit with 'got branch -c %s BRANCH_NAME'",
2114 branch_name, commit_id_str);
2116 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2119 static const struct got_error *
2120 cmd_checkout(int argc, char *argv[])
2122 const struct got_error *error = NULL;
2123 struct got_repository *repo = NULL;
2124 struct got_reference *head_ref = NULL;
2125 struct got_worktree *worktree = NULL;
2126 char *repo_path = NULL;
2127 char *worktree_path = NULL;
2128 const char *path_prefix = "";
2129 const char *branch_name = GOT_REF_HEAD;
2130 char *commit_id_str = NULL;
2131 int ch, same_path_prefix, allow_nonempty = 0;
2132 struct got_pathlist_head paths;
2133 struct got_checkout_progress_arg cpa;
2135 TAILQ_INIT(&paths);
2137 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2138 switch (ch) {
2139 case 'b':
2140 branch_name = optarg;
2141 break;
2142 case 'c':
2143 commit_id_str = strdup(optarg);
2144 if (commit_id_str == NULL)
2145 return got_error_from_errno("strdup");
2146 break;
2147 case 'E':
2148 allow_nonempty = 1;
2149 break;
2150 case 'p':
2151 path_prefix = optarg;
2152 break;
2153 default:
2154 usage_checkout();
2155 /* NOTREACHED */
2159 argc -= optind;
2160 argv += optind;
2162 #ifndef PROFILE
2163 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2164 "unveil", NULL) == -1)
2165 err(1, "pledge");
2166 #endif
2167 if (argc == 1) {
2168 char *cwd, *base, *dotgit;
2169 repo_path = realpath(argv[0], NULL);
2170 if (repo_path == NULL)
2171 return got_error_from_errno2("realpath", argv[0]);
2172 cwd = getcwd(NULL, 0);
2173 if (cwd == NULL) {
2174 error = got_error_from_errno("getcwd");
2175 goto done;
2177 if (path_prefix[0]) {
2178 base = basename(path_prefix);
2179 if (base == NULL) {
2180 error = got_error_from_errno2("basename",
2181 path_prefix);
2182 goto done;
2184 } else {
2185 base = basename(repo_path);
2186 if (base == NULL) {
2187 error = got_error_from_errno2("basename",
2188 repo_path);
2189 goto done;
2192 dotgit = strstr(base, ".git");
2193 if (dotgit)
2194 *dotgit = '\0';
2195 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2196 error = got_error_from_errno("asprintf");
2197 free(cwd);
2198 goto done;
2200 free(cwd);
2201 } else if (argc == 2) {
2202 repo_path = realpath(argv[0], NULL);
2203 if (repo_path == NULL) {
2204 error = got_error_from_errno2("realpath", argv[0]);
2205 goto done;
2207 worktree_path = realpath(argv[1], NULL);
2208 if (worktree_path == NULL) {
2209 if (errno != ENOENT) {
2210 error = got_error_from_errno2("realpath",
2211 argv[1]);
2212 goto done;
2214 worktree_path = strdup(argv[1]);
2215 if (worktree_path == NULL) {
2216 error = got_error_from_errno("strdup");
2217 goto done;
2220 } else
2221 usage_checkout();
2223 got_path_strip_trailing_slashes(repo_path);
2224 got_path_strip_trailing_slashes(worktree_path);
2226 error = got_repo_open(&repo, repo_path, NULL);
2227 if (error != NULL)
2228 goto done;
2230 /* Pre-create work tree path for unveil(2) */
2231 error = got_path_mkdir(worktree_path);
2232 if (error) {
2233 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2234 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2235 goto done;
2236 if (!allow_nonempty &&
2237 !got_path_dir_is_empty(worktree_path)) {
2238 error = got_error_path(worktree_path,
2239 GOT_ERR_DIR_NOT_EMPTY);
2240 goto done;
2244 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2245 if (error)
2246 goto done;
2248 error = got_ref_open(&head_ref, repo, branch_name, 0);
2249 if (error != NULL)
2250 goto done;
2252 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2253 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2254 goto done;
2256 error = got_worktree_open(&worktree, worktree_path);
2257 if (error != NULL)
2258 goto done;
2260 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2261 path_prefix);
2262 if (error != NULL)
2263 goto done;
2264 if (!same_path_prefix) {
2265 error = got_error(GOT_ERR_PATH_PREFIX);
2266 goto done;
2269 if (commit_id_str) {
2270 struct got_object_id *commit_id;
2271 error = got_repo_match_object_id(&commit_id, NULL,
2272 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2273 if (error)
2274 goto done;
2275 error = check_linear_ancestry(commit_id,
2276 got_worktree_get_base_commit_id(worktree), 0, repo);
2277 if (error != NULL) {
2278 free(commit_id);
2279 if (error->code == GOT_ERR_ANCESTRY) {
2280 error = checkout_ancestry_error(
2281 head_ref, commit_id_str);
2283 goto done;
2285 error = check_same_branch(commit_id, head_ref, NULL, repo);
2286 if (error) {
2287 if (error->code == GOT_ERR_ANCESTRY) {
2288 error = checkout_ancestry_error(
2289 head_ref, commit_id_str);
2291 goto done;
2293 error = got_worktree_set_base_commit_id(worktree, repo,
2294 commit_id);
2295 free(commit_id);
2296 if (error)
2297 goto done;
2300 error = got_pathlist_append(&paths, "", NULL);
2301 if (error)
2302 goto done;
2303 cpa.worktree_path = worktree_path;
2304 cpa.had_base_commit_ref_error = 0;
2305 error = got_worktree_checkout_files(worktree, &paths, repo,
2306 checkout_progress, &cpa, check_cancelled, NULL);
2307 if (error != NULL)
2308 goto done;
2310 printf("Now shut up and hack\n");
2311 if (cpa.had_base_commit_ref_error)
2312 show_worktree_base_ref_warning();
2313 done:
2314 got_pathlist_free(&paths);
2315 free(commit_id_str);
2316 free(repo_path);
2317 free(worktree_path);
2318 return error;
2321 __dead static void
2322 usage_update(void)
2324 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2325 getprogname());
2326 exit(1);
2329 static const struct got_error *
2330 update_progress(void *arg, unsigned char status, const char *path)
2332 int *did_something = arg;
2334 if (status == GOT_STATUS_EXISTS ||
2335 status == GOT_STATUS_BASE_REF_ERR)
2336 return NULL;
2338 *did_something = 1;
2340 /* Base commit bump happens silently. */
2341 if (status == GOT_STATUS_BUMP_BASE)
2342 return NULL;
2344 while (path[0] == '/')
2345 path++;
2346 printf("%c %s\n", status, path);
2347 return NULL;
2350 static const struct got_error *
2351 switch_head_ref(struct got_reference *head_ref,
2352 struct got_object_id *commit_id, struct got_worktree *worktree,
2353 struct got_repository *repo)
2355 const struct got_error *err = NULL;
2356 char *base_id_str;
2357 int ref_has_moved = 0;
2359 /* Trivial case: switching between two different references. */
2360 if (strcmp(got_ref_get_name(head_ref),
2361 got_worktree_get_head_ref_name(worktree)) != 0) {
2362 printf("Switching work tree from %s to %s\n",
2363 got_worktree_get_head_ref_name(worktree),
2364 got_ref_get_name(head_ref));
2365 return got_worktree_set_head_ref(worktree, head_ref);
2368 err = check_linear_ancestry(commit_id,
2369 got_worktree_get_base_commit_id(worktree), 0, repo);
2370 if (err) {
2371 if (err->code != GOT_ERR_ANCESTRY)
2372 return err;
2373 ref_has_moved = 1;
2375 if (!ref_has_moved)
2376 return NULL;
2378 /* Switching to a rebased branch with the same reference name. */
2379 err = got_object_id_str(&base_id_str,
2380 got_worktree_get_base_commit_id(worktree));
2381 if (err)
2382 return err;
2383 printf("Reference %s now points at a different branch\n",
2384 got_worktree_get_head_ref_name(worktree));
2385 printf("Switching work tree from %s to %s\n", base_id_str,
2386 got_worktree_get_head_ref_name(worktree));
2387 return NULL;
2390 static const struct got_error *
2391 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2393 const struct got_error *err;
2394 int in_progress;
2396 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2397 if (err)
2398 return err;
2399 if (in_progress)
2400 return got_error(GOT_ERR_REBASING);
2402 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2403 if (err)
2404 return err;
2405 if (in_progress)
2406 return got_error(GOT_ERR_HISTEDIT_BUSY);
2408 return NULL;
2411 static const struct got_error *
2412 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2413 char *argv[], struct got_worktree *worktree)
2415 const struct got_error *err = NULL;
2416 char *path;
2417 int i;
2419 if (argc == 0) {
2420 path = strdup("");
2421 if (path == NULL)
2422 return got_error_from_errno("strdup");
2423 return got_pathlist_append(paths, path, NULL);
2426 for (i = 0; i < argc; i++) {
2427 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2428 if (err)
2429 break;
2430 err = got_pathlist_append(paths, path, NULL);
2431 if (err) {
2432 free(path);
2433 break;
2437 return err;
2440 static const struct got_error *
2441 cmd_update(int argc, char *argv[])
2443 const struct got_error *error = NULL;
2444 struct got_repository *repo = NULL;
2445 struct got_worktree *worktree = NULL;
2446 char *worktree_path = NULL;
2447 struct got_object_id *commit_id = NULL;
2448 char *commit_id_str = NULL;
2449 const char *branch_name = NULL;
2450 struct got_reference *head_ref = NULL;
2451 struct got_pathlist_head paths;
2452 struct got_pathlist_entry *pe;
2453 int ch, did_something = 0;
2455 TAILQ_INIT(&paths);
2457 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2458 switch (ch) {
2459 case 'b':
2460 branch_name = optarg;
2461 break;
2462 case 'c':
2463 commit_id_str = strdup(optarg);
2464 if (commit_id_str == NULL)
2465 return got_error_from_errno("strdup");
2466 break;
2467 default:
2468 usage_update();
2469 /* NOTREACHED */
2473 argc -= optind;
2474 argv += optind;
2476 #ifndef PROFILE
2477 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2478 "unveil", NULL) == -1)
2479 err(1, "pledge");
2480 #endif
2481 worktree_path = getcwd(NULL, 0);
2482 if (worktree_path == NULL) {
2483 error = got_error_from_errno("getcwd");
2484 goto done;
2486 error = got_worktree_open(&worktree, worktree_path);
2487 if (error)
2488 goto done;
2490 error = check_rebase_or_histedit_in_progress(worktree);
2491 if (error)
2492 goto done;
2494 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
2495 NULL);
2496 if (error != NULL)
2497 goto done;
2499 error = apply_unveil(got_repo_get_path(repo), 0,
2500 got_worktree_get_root_path(worktree));
2501 if (error)
2502 goto done;
2504 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2505 if (error)
2506 goto done;
2508 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
2509 got_worktree_get_head_ref_name(worktree), 0);
2510 if (error != NULL)
2511 goto done;
2512 if (commit_id_str == NULL) {
2513 error = got_ref_resolve(&commit_id, repo, head_ref);
2514 if (error != NULL)
2515 goto done;
2516 error = got_object_id_str(&commit_id_str, commit_id);
2517 if (error != NULL)
2518 goto done;
2519 } else {
2520 error = got_repo_match_object_id(&commit_id, NULL,
2521 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2522 free(commit_id_str);
2523 commit_id_str = NULL;
2524 if (error)
2525 goto done;
2526 error = got_object_id_str(&commit_id_str, commit_id);
2527 if (error)
2528 goto done;
2531 if (branch_name) {
2532 struct got_object_id *head_commit_id;
2533 TAILQ_FOREACH(pe, &paths, entry) {
2534 if (pe->path_len == 0)
2535 continue;
2536 error = got_error_msg(GOT_ERR_BAD_PATH,
2537 "switching between branches requires that "
2538 "the entire work tree gets updated");
2539 goto done;
2541 error = got_ref_resolve(&head_commit_id, repo, head_ref);
2542 if (error)
2543 goto done;
2544 error = check_linear_ancestry(commit_id, head_commit_id, 0,
2545 repo);
2546 free(head_commit_id);
2547 if (error != NULL)
2548 goto done;
2549 error = check_same_branch(commit_id, head_ref, NULL, repo);
2550 if (error)
2551 goto done;
2552 error = switch_head_ref(head_ref, commit_id, worktree, repo);
2553 if (error)
2554 goto done;
2555 } else {
2556 error = check_linear_ancestry(commit_id,
2557 got_worktree_get_base_commit_id(worktree), 0, repo);
2558 if (error != NULL) {
2559 if (error->code == GOT_ERR_ANCESTRY)
2560 error = got_error(GOT_ERR_BRANCH_MOVED);
2561 goto done;
2563 error = check_same_branch(commit_id, head_ref, NULL, repo);
2564 if (error)
2565 goto done;
2568 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
2569 commit_id) != 0) {
2570 error = got_worktree_set_base_commit_id(worktree, repo,
2571 commit_id);
2572 if (error)
2573 goto done;
2576 error = got_worktree_checkout_files(worktree, &paths, repo,
2577 update_progress, &did_something, check_cancelled, NULL);
2578 if (error != NULL)
2579 goto done;
2581 if (did_something)
2582 printf("Updated to commit %s\n", commit_id_str);
2583 else
2584 printf("Already up-to-date\n");
2585 done:
2586 free(worktree_path);
2587 TAILQ_FOREACH(pe, &paths, entry)
2588 free((char *)pe->path);
2589 got_pathlist_free(&paths);
2590 free(commit_id);
2591 free(commit_id_str);
2592 return error;
2595 static const struct got_error *
2596 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
2597 const char *path, int diff_context, int ignore_whitespace,
2598 struct got_repository *repo)
2600 const struct got_error *err = NULL;
2601 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
2603 if (blob_id1) {
2604 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
2605 if (err)
2606 goto done;
2609 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
2610 if (err)
2611 goto done;
2613 while (path[0] == '/')
2614 path++;
2615 err = got_diff_blob(blob1, blob2, path, path, diff_context,
2616 ignore_whitespace, stdout);
2617 done:
2618 if (blob1)
2619 got_object_blob_close(blob1);
2620 got_object_blob_close(blob2);
2621 return err;
2624 static const struct got_error *
2625 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
2626 const char *path, int diff_context, int ignore_whitespace,
2627 struct got_repository *repo)
2629 const struct got_error *err = NULL;
2630 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
2631 struct got_diff_blob_output_unidiff_arg arg;
2633 if (tree_id1) {
2634 err = got_object_open_as_tree(&tree1, repo, tree_id1);
2635 if (err)
2636 goto done;
2639 err = got_object_open_as_tree(&tree2, repo, tree_id2);
2640 if (err)
2641 goto done;
2643 arg.diff_context = diff_context;
2644 arg.ignore_whitespace = ignore_whitespace;
2645 arg.outfile = stdout;
2646 while (path[0] == '/')
2647 path++;
2648 err = got_diff_tree(tree1, tree2, path, path, repo,
2649 got_diff_blob_output_unidiff, &arg, 1);
2650 done:
2651 if (tree1)
2652 got_object_tree_close(tree1);
2653 if (tree2)
2654 got_object_tree_close(tree2);
2655 return err;
2658 static const struct got_error *
2659 print_patch(struct got_commit_object *commit, struct got_object_id *id,
2660 const char *path, int diff_context, struct got_repository *repo)
2662 const struct got_error *err = NULL;
2663 struct got_commit_object *pcommit = NULL;
2664 char *id_str1 = NULL, *id_str2 = NULL;
2665 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
2666 struct got_object_qid *qid;
2668 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
2669 if (qid != NULL) {
2670 err = got_object_open_as_commit(&pcommit, repo,
2671 qid->id);
2672 if (err)
2673 return err;
2676 if (path && path[0] != '\0') {
2677 int obj_type;
2678 err = got_object_id_by_path(&obj_id2, repo, id, path);
2679 if (err)
2680 goto done;
2681 err = got_object_id_str(&id_str2, obj_id2);
2682 if (err) {
2683 free(obj_id2);
2684 goto done;
2686 if (pcommit) {
2687 err = got_object_id_by_path(&obj_id1, repo,
2688 qid->id, path);
2689 if (err) {
2690 free(obj_id2);
2691 goto done;
2693 err = got_object_id_str(&id_str1, obj_id1);
2694 if (err) {
2695 free(obj_id2);
2696 goto done;
2699 err = got_object_get_type(&obj_type, repo, obj_id2);
2700 if (err) {
2701 free(obj_id2);
2702 goto done;
2704 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2705 switch (obj_type) {
2706 case GOT_OBJ_TYPE_BLOB:
2707 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
2708 0, repo);
2709 break;
2710 case GOT_OBJ_TYPE_TREE:
2711 err = diff_trees(obj_id1, obj_id2, path, diff_context,
2712 0, repo);
2713 break;
2714 default:
2715 err = got_error(GOT_ERR_OBJ_TYPE);
2716 break;
2718 free(obj_id1);
2719 free(obj_id2);
2720 } else {
2721 obj_id2 = got_object_commit_get_tree_id(commit);
2722 err = got_object_id_str(&id_str2, obj_id2);
2723 if (err)
2724 goto done;
2725 obj_id1 = got_object_commit_get_tree_id(pcommit);
2726 err = got_object_id_str(&id_str1, obj_id1);
2727 if (err)
2728 goto done;
2729 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2730 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
2732 done:
2733 free(id_str1);
2734 free(id_str2);
2735 if (pcommit)
2736 got_object_commit_close(pcommit);
2737 return err;
2740 static char *
2741 get_datestr(time_t *time, char *datebuf)
2743 struct tm mytm, *tm;
2744 char *p, *s;
2746 tm = gmtime_r(time, &mytm);
2747 if (tm == NULL)
2748 return NULL;
2749 s = asctime_r(tm, datebuf);
2750 if (s == NULL)
2751 return NULL;
2752 p = strchr(s, '\n');
2753 if (p)
2754 *p = '\0';
2755 return s;
2758 static const struct got_error *
2759 match_logmsg(int *have_match, struct got_object_id *id,
2760 struct got_commit_object *commit, regex_t *regex)
2762 const struct got_error *err = NULL;
2763 regmatch_t regmatch;
2764 char *id_str = NULL, *logmsg = NULL;
2766 *have_match = 0;
2768 err = got_object_id_str(&id_str, id);
2769 if (err)
2770 return err;
2772 err = got_object_commit_get_logmsg(&logmsg, commit);
2773 if (err)
2774 goto done;
2776 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2777 *have_match = 1;
2778 done:
2779 free(id_str);
2780 free(logmsg);
2781 return err;
2784 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
2786 static const struct got_error *
2787 print_commit(struct got_commit_object *commit, struct got_object_id *id,
2788 struct got_repository *repo, const char *path, int show_patch,
2789 int diff_context, struct got_reflist_head *refs)
2791 const struct got_error *err = NULL;
2792 char *id_str, *datestr, *logmsg0, *logmsg, *line;
2793 char datebuf[26];
2794 time_t committer_time;
2795 const char *author, *committer;
2796 char *refs_str = NULL;
2797 struct got_reflist_entry *re;
2799 SIMPLEQ_FOREACH(re, refs, entry) {
2800 char *s;
2801 const char *name;
2802 struct got_tag_object *tag = NULL;
2803 int cmp;
2805 name = got_ref_get_name(re->ref);
2806 if (strcmp(name, GOT_REF_HEAD) == 0)
2807 continue;
2808 if (strncmp(name, "refs/", 5) == 0)
2809 name += 5;
2810 if (strncmp(name, "got/", 4) == 0)
2811 continue;
2812 if (strncmp(name, "heads/", 6) == 0)
2813 name += 6;
2814 if (strncmp(name, "remotes/", 8) == 0)
2815 name += 8;
2816 if (strncmp(name, "tags/", 5) == 0) {
2817 err = got_object_open_as_tag(&tag, repo, re->id);
2818 if (err) {
2819 if (err->code != GOT_ERR_OBJ_TYPE)
2820 return err;
2821 /* Ref points at something other than a tag. */
2822 err = NULL;
2823 tag = NULL;
2826 cmp = got_object_id_cmp(tag ?
2827 got_object_tag_get_object_id(tag) : re->id, id);
2828 if (tag)
2829 got_object_tag_close(tag);
2830 if (cmp != 0)
2831 continue;
2832 s = refs_str;
2833 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
2834 name) == -1) {
2835 err = got_error_from_errno("asprintf");
2836 free(s);
2837 return err;
2839 free(s);
2841 err = got_object_id_str(&id_str, id);
2842 if (err)
2843 return err;
2845 printf(GOT_COMMIT_SEP_STR);
2846 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
2847 refs_str ? refs_str : "", refs_str ? ")" : "");
2848 free(id_str);
2849 id_str = NULL;
2850 free(refs_str);
2851 refs_str = NULL;
2852 printf("from: %s\n", got_object_commit_get_author(commit));
2853 committer_time = got_object_commit_get_committer_time(commit);
2854 datestr = get_datestr(&committer_time, datebuf);
2855 if (datestr)
2856 printf("date: %s UTC\n", datestr);
2857 author = got_object_commit_get_author(commit);
2858 committer = got_object_commit_get_committer(commit);
2859 if (strcmp(author, committer) != 0)
2860 printf("via: %s\n", committer);
2861 if (got_object_commit_get_nparents(commit) > 1) {
2862 const struct got_object_id_queue *parent_ids;
2863 struct got_object_qid *qid;
2864 int n = 1;
2865 parent_ids = got_object_commit_get_parent_ids(commit);
2866 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
2867 err = got_object_id_str(&id_str, qid->id);
2868 if (err)
2869 return err;
2870 printf("parent %d: %s\n", n++, id_str);
2871 free(id_str);
2875 err = got_object_commit_get_logmsg(&logmsg0, commit);
2876 if (err)
2877 return err;
2879 logmsg = logmsg0;
2880 do {
2881 line = strsep(&logmsg, "\n");
2882 if (line)
2883 printf(" %s\n", line);
2884 } while (line);
2885 free(logmsg0);
2887 if (show_patch) {
2888 err = print_patch(commit, id, path, diff_context, repo);
2889 if (err == 0)
2890 printf("\n");
2893 if (fflush(stdout) != 0 && err == NULL)
2894 err = got_error_from_errno("fflush");
2895 return err;
2898 static const struct got_error *
2899 print_commits(struct got_object_id *root_id, struct got_repository *repo,
2900 const char *path, int show_patch, const char *search_pattern,
2901 int diff_context, int limit, int log_branches,
2902 struct got_reflist_head *refs)
2904 const struct got_error *err;
2905 struct got_commit_graph *graph;
2906 regex_t regex;
2907 int have_match;
2909 if (search_pattern &&
2910 regcomp(&regex, search_pattern, REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
2911 return got_error_msg(GOT_ERR_REGEX, search_pattern);
2913 err = got_commit_graph_open(&graph, path, !log_branches);
2914 if (err)
2915 return err;
2916 err = got_commit_graph_iter_start(graph, root_id, repo,
2917 check_cancelled, NULL);
2918 if (err)
2919 goto done;
2920 for (;;) {
2921 struct got_commit_object *commit;
2922 struct got_object_id *id;
2924 if (sigint_received || sigpipe_received)
2925 break;
2927 err = got_commit_graph_iter_next(&id, graph, repo,
2928 check_cancelled, NULL);
2929 if (err) {
2930 if (err->code == GOT_ERR_ITER_COMPLETED)
2931 err = NULL;
2932 break;
2934 if (id == NULL)
2935 break;
2937 err = got_object_open_as_commit(&commit, repo, id);
2938 if (err)
2939 break;
2941 if (search_pattern) {
2942 err = match_logmsg(&have_match, id, commit, &regex);
2943 if (err) {
2944 got_object_commit_close(commit);
2945 break;
2947 if (have_match == 0) {
2948 got_object_commit_close(commit);
2949 continue;
2953 err = print_commit(commit, id, repo, path, show_patch,
2954 diff_context, refs);
2955 got_object_commit_close(commit);
2956 if (err || (limit && --limit == 0))
2957 break;
2959 done:
2960 if (search_pattern)
2961 regfree(&regex);
2962 got_commit_graph_close(graph);
2963 return err;
2966 __dead static void
2967 usage_log(void)
2969 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] [-p] "
2970 "[-s search-pattern] [-r repository-path] [path]\n", getprogname());
2971 exit(1);
2974 static int
2975 get_default_log_limit(void)
2977 const char *got_default_log_limit;
2978 long long n;
2979 const char *errstr;
2981 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
2982 if (got_default_log_limit == NULL)
2983 return 0;
2984 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
2985 if (errstr != NULL)
2986 return 0;
2987 return n;
2990 static const struct got_error *
2991 cmd_log(int argc, char *argv[])
2993 const struct got_error *error;
2994 struct got_repository *repo = NULL;
2995 struct got_worktree *worktree = NULL;
2996 struct got_commit_object *commit = NULL;
2997 struct got_object_id *id = NULL;
2998 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
2999 const char *start_commit = NULL, *search_pattern = NULL;
3000 int diff_context = -1, ch;
3001 int show_patch = 0, limit = 0, log_branches = 0;
3002 const char *errstr;
3003 struct got_reflist_head refs;
3005 SIMPLEQ_INIT(&refs);
3007 #ifndef PROFILE
3008 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3009 NULL)
3010 == -1)
3011 err(1, "pledge");
3012 #endif
3014 limit = get_default_log_limit();
3016 while ((ch = getopt(argc, argv, "bpc:C:l:r:s:")) != -1) {
3017 switch (ch) {
3018 case 'p':
3019 show_patch = 1;
3020 break;
3021 case 'c':
3022 start_commit = optarg;
3023 break;
3024 case 'C':
3025 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3026 &errstr);
3027 if (errstr != NULL)
3028 err(1, "-C option %s", errstr);
3029 break;
3030 case 'l':
3031 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3032 if (errstr != NULL)
3033 err(1, "-l option %s", errstr);
3034 break;
3035 case 'b':
3036 log_branches = 1;
3037 break;
3038 case 'r':
3039 repo_path = realpath(optarg, NULL);
3040 if (repo_path == NULL)
3041 return got_error_from_errno2("realpath",
3042 optarg);
3043 got_path_strip_trailing_slashes(repo_path);
3044 break;
3045 case 's':
3046 search_pattern = optarg;
3047 break;
3048 default:
3049 usage_log();
3050 /* NOTREACHED */
3054 argc -= optind;
3055 argv += optind;
3057 if (diff_context == -1)
3058 diff_context = 3;
3059 else if (!show_patch)
3060 errx(1, "-C reguires -p");
3062 cwd = getcwd(NULL, 0);
3063 if (cwd == NULL) {
3064 error = got_error_from_errno("getcwd");
3065 goto done;
3068 error = got_worktree_open(&worktree, cwd);
3069 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3070 goto done;
3071 error = NULL;
3073 if (argc == 0) {
3074 path = strdup("");
3075 if (path == NULL) {
3076 error = got_error_from_errno("strdup");
3077 goto done;
3079 } else if (argc == 1) {
3080 if (worktree) {
3081 error = got_worktree_resolve_path(&path, worktree,
3082 argv[0]);
3083 if (error)
3084 goto done;
3085 } else {
3086 path = strdup(argv[0]);
3087 if (path == NULL) {
3088 error = got_error_from_errno("strdup");
3089 goto done;
3092 } else
3093 usage_log();
3095 if (repo_path == NULL) {
3096 repo_path = worktree ?
3097 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3099 if (repo_path == NULL) {
3100 error = got_error_from_errno("strdup");
3101 goto done;
3104 error = got_repo_open(&repo, repo_path, NULL);
3105 if (error != NULL)
3106 goto done;
3108 error = apply_unveil(got_repo_get_path(repo), 1,
3109 worktree ? got_worktree_get_root_path(worktree) : NULL);
3110 if (error)
3111 goto done;
3113 if (start_commit == NULL) {
3114 struct got_reference *head_ref;
3115 error = got_ref_open(&head_ref, repo,
3116 worktree ? got_worktree_get_head_ref_name(worktree)
3117 : GOT_REF_HEAD, 0);
3118 if (error != NULL)
3119 return error;
3120 error = got_ref_resolve(&id, repo, head_ref);
3121 got_ref_close(head_ref);
3122 if (error != NULL)
3123 return error;
3124 error = got_object_open_as_commit(&commit, repo, id);
3125 } else {
3126 struct got_reference *ref;
3127 error = got_ref_open(&ref, repo, start_commit, 0);
3128 if (error == NULL) {
3129 int obj_type;
3130 error = got_ref_resolve(&id, repo, ref);
3131 got_ref_close(ref);
3132 if (error != NULL)
3133 goto done;
3134 error = got_object_get_type(&obj_type, repo, id);
3135 if (error != NULL)
3136 goto done;
3137 if (obj_type == GOT_OBJ_TYPE_TAG) {
3138 struct got_tag_object *tag;
3139 error = got_object_open_as_tag(&tag, repo, id);
3140 if (error != NULL)
3141 goto done;
3142 if (got_object_tag_get_object_type(tag) !=
3143 GOT_OBJ_TYPE_COMMIT) {
3144 got_object_tag_close(tag);
3145 error = got_error(GOT_ERR_OBJ_TYPE);
3146 goto done;
3148 free(id);
3149 id = got_object_id_dup(
3150 got_object_tag_get_object_id(tag));
3151 if (id == NULL)
3152 error = got_error_from_errno(
3153 "got_object_id_dup");
3154 got_object_tag_close(tag);
3155 if (error)
3156 goto done;
3157 } else if (obj_type != GOT_OBJ_TYPE_COMMIT) {
3158 error = got_error(GOT_ERR_OBJ_TYPE);
3159 goto done;
3161 error = got_object_open_as_commit(&commit, repo, id);
3162 if (error != NULL)
3163 goto done;
3165 if (commit == NULL) {
3166 error = got_repo_match_object_id_prefix(&id,
3167 start_commit, GOT_OBJ_TYPE_COMMIT, repo);
3168 if (error != NULL)
3169 return error;
3172 if (error != NULL)
3173 goto done;
3175 if (worktree) {
3176 const char *prefix = got_worktree_get_path_prefix(worktree);
3177 char *p;
3178 if (asprintf(&p, "%s%s%s", prefix,
3179 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3180 error = got_error_from_errno("asprintf");
3181 goto done;
3183 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3184 free(p);
3185 } else
3186 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3187 if (error != NULL)
3188 goto done;
3189 if (in_repo_path) {
3190 free(path);
3191 path = in_repo_path;
3194 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3195 if (error)
3196 goto done;
3198 error = print_commits(id, repo, path, show_patch, search_pattern,
3199 diff_context, limit, log_branches, &refs);
3200 done:
3201 free(path);
3202 free(repo_path);
3203 free(cwd);
3204 free(id);
3205 if (worktree)
3206 got_worktree_close(worktree);
3207 if (repo) {
3208 const struct got_error *repo_error;
3209 repo_error = got_repo_close(repo);
3210 if (error == NULL)
3211 error = repo_error;
3213 got_ref_list_free(&refs);
3214 return error;
3217 __dead static void
3218 usage_diff(void)
3220 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3221 "[-w] [object1 object2 | path]\n", getprogname());
3222 exit(1);
3225 struct print_diff_arg {
3226 struct got_repository *repo;
3227 struct got_worktree *worktree;
3228 int diff_context;
3229 const char *id_str;
3230 int header_shown;
3231 int diff_staged;
3232 int ignore_whitespace;
3235 static const struct got_error *
3236 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3237 const char *path, struct got_object_id *blob_id,
3238 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3239 int dirfd, const char *de_name)
3241 struct print_diff_arg *a = arg;
3242 const struct got_error *err = NULL;
3243 struct got_blob_object *blob1 = NULL;
3244 int fd = -1;
3245 FILE *f2 = NULL;
3246 char *abspath = NULL, *label1 = NULL;
3247 struct stat sb;
3249 if (a->diff_staged) {
3250 if (staged_status != GOT_STATUS_MODIFY &&
3251 staged_status != GOT_STATUS_ADD &&
3252 staged_status != GOT_STATUS_DELETE)
3253 return NULL;
3254 } else {
3255 if (staged_status == GOT_STATUS_DELETE)
3256 return NULL;
3257 if (status == GOT_STATUS_NONEXISTENT)
3258 return got_error_set_errno(ENOENT, path);
3259 if (status != GOT_STATUS_MODIFY &&
3260 status != GOT_STATUS_ADD &&
3261 status != GOT_STATUS_DELETE &&
3262 status != GOT_STATUS_CONFLICT)
3263 return NULL;
3266 if (!a->header_shown) {
3267 printf("diff %s %s%s\n", a->id_str,
3268 got_worktree_get_root_path(a->worktree),
3269 a->diff_staged ? " (staged changes)" : "");
3270 a->header_shown = 1;
3273 if (a->diff_staged) {
3274 const char *label1 = NULL, *label2 = NULL;
3275 switch (staged_status) {
3276 case GOT_STATUS_MODIFY:
3277 label1 = path;
3278 label2 = path;
3279 break;
3280 case GOT_STATUS_ADD:
3281 label2 = path;
3282 break;
3283 case GOT_STATUS_DELETE:
3284 label1 = path;
3285 break;
3286 default:
3287 return got_error(GOT_ERR_FILE_STATUS);
3289 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
3290 label1, label2, a->diff_context, a->ignore_whitespace,
3291 a->repo, stdout);
3294 if (staged_status == GOT_STATUS_ADD ||
3295 staged_status == GOT_STATUS_MODIFY) {
3296 char *id_str;
3297 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
3298 8192);
3299 if (err)
3300 goto done;
3301 err = got_object_id_str(&id_str, staged_blob_id);
3302 if (err)
3303 goto done;
3304 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
3305 err = got_error_from_errno("asprintf");
3306 free(id_str);
3307 goto done;
3309 free(id_str);
3310 } else if (status != GOT_STATUS_ADD) {
3311 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
3312 if (err)
3313 goto done;
3316 if (status != GOT_STATUS_DELETE) {
3317 if (asprintf(&abspath, "%s/%s",
3318 got_worktree_get_root_path(a->worktree), path) == -1) {
3319 err = got_error_from_errno("asprintf");
3320 goto done;
3323 if (dirfd != -1) {
3324 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
3325 if (fd == -1) {
3326 err = got_error_from_errno2("openat", abspath);
3327 goto done;
3329 } else {
3330 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
3331 if (fd == -1) {
3332 err = got_error_from_errno2("open", abspath);
3333 goto done;
3336 if (fstat(fd, &sb) == -1) {
3337 err = got_error_from_errno2("fstat", abspath);
3338 goto done;
3340 f2 = fdopen(fd, "r");
3341 if (f2 == NULL) {
3342 err = got_error_from_errno2("fdopen", abspath);
3343 goto done;
3345 fd = -1;
3346 } else
3347 sb.st_size = 0;
3349 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
3350 a->diff_context, a->ignore_whitespace, stdout);
3351 done:
3352 if (blob1)
3353 got_object_blob_close(blob1);
3354 if (f2 && fclose(f2) == EOF && err == NULL)
3355 err = got_error_from_errno("fclose");
3356 if (fd != -1 && close(fd) == -1 && err == NULL)
3357 err = got_error_from_errno("close");
3358 free(abspath);
3359 return err;
3362 static const struct got_error *
3363 cmd_diff(int argc, char *argv[])
3365 const struct got_error *error;
3366 struct got_repository *repo = NULL;
3367 struct got_worktree *worktree = NULL;
3368 char *cwd = NULL, *repo_path = NULL;
3369 struct got_object_id *id1 = NULL, *id2 = NULL;
3370 const char *id_str1 = NULL, *id_str2 = NULL;
3371 char *label1 = NULL, *label2 = NULL;
3372 int type1, type2;
3373 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
3374 const char *errstr;
3375 char *path = NULL;
3377 #ifndef PROFILE
3378 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3379 NULL) == -1)
3380 err(1, "pledge");
3381 #endif
3383 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
3384 switch (ch) {
3385 case 'C':
3386 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3387 &errstr);
3388 if (errstr != NULL)
3389 err(1, "-C option %s", errstr);
3390 break;
3391 case 'r':
3392 repo_path = realpath(optarg, NULL);
3393 if (repo_path == NULL)
3394 return got_error_from_errno2("realpath",
3395 optarg);
3396 got_path_strip_trailing_slashes(repo_path);
3397 break;
3398 case 's':
3399 diff_staged = 1;
3400 break;
3401 case 'w':
3402 ignore_whitespace = 1;
3403 break;
3404 default:
3405 usage_diff();
3406 /* NOTREACHED */
3410 argc -= optind;
3411 argv += optind;
3413 cwd = getcwd(NULL, 0);
3414 if (cwd == NULL) {
3415 error = got_error_from_errno("getcwd");
3416 goto done;
3418 if (argc <= 1) {
3419 if (repo_path)
3420 errx(1,
3421 "-r option can't be used when diffing a work tree");
3422 error = got_worktree_open(&worktree, cwd);
3423 if (error)
3424 goto done;
3425 repo_path = strdup(got_worktree_get_repo_path(worktree));
3426 if (repo_path == NULL) {
3427 error = got_error_from_errno("strdup");
3428 goto done;
3430 if (argc == 1) {
3431 error = got_worktree_resolve_path(&path, worktree,
3432 argv[0]);
3433 if (error)
3434 goto done;
3435 } else {
3436 path = strdup("");
3437 if (path == NULL) {
3438 error = got_error_from_errno("strdup");
3439 goto done;
3442 } else if (argc == 2) {
3443 if (diff_staged)
3444 errx(1, "-s option can't be used when diffing "
3445 "objects in repository");
3446 id_str1 = argv[0];
3447 id_str2 = argv[1];
3448 if (repo_path == NULL) {
3449 error = got_worktree_open(&worktree, cwd);
3450 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3451 goto done;
3452 if (worktree) {
3453 repo_path = strdup(
3454 got_worktree_get_repo_path(worktree));
3455 if (repo_path == NULL) {
3456 error = got_error_from_errno("strdup");
3457 goto done;
3459 } else {
3460 repo_path = strdup(cwd);
3461 if (repo_path == NULL) {
3462 error = got_error_from_errno("strdup");
3463 goto done;
3467 } else
3468 usage_diff();
3470 error = got_repo_open(&repo, repo_path, NULL);
3471 free(repo_path);
3472 if (error != NULL)
3473 goto done;
3475 error = apply_unveil(got_repo_get_path(repo), 1,
3476 worktree ? got_worktree_get_root_path(worktree) : NULL);
3477 if (error)
3478 goto done;
3480 if (argc <= 1) {
3481 struct print_diff_arg arg;
3482 struct got_pathlist_head paths;
3483 char *id_str;
3485 TAILQ_INIT(&paths);
3487 error = got_object_id_str(&id_str,
3488 got_worktree_get_base_commit_id(worktree));
3489 if (error)
3490 goto done;
3491 arg.repo = repo;
3492 arg.worktree = worktree;
3493 arg.diff_context = diff_context;
3494 arg.id_str = id_str;
3495 arg.header_shown = 0;
3496 arg.diff_staged = diff_staged;
3497 arg.ignore_whitespace = ignore_whitespace;
3499 error = got_pathlist_append(&paths, path, NULL);
3500 if (error)
3501 goto done;
3503 error = got_worktree_status(worktree, &paths, repo, print_diff,
3504 &arg, check_cancelled, NULL);
3505 free(id_str);
3506 got_pathlist_free(&paths);
3507 goto done;
3510 error = got_repo_match_object_id(&id1, &label1, id_str1,
3511 GOT_OBJ_TYPE_ANY, 1, repo);
3512 if (error)
3513 goto done;
3515 error = got_repo_match_object_id(&id2, &label2, id_str2,
3516 GOT_OBJ_TYPE_ANY, 1, repo);
3517 if (error)
3518 goto done;
3520 error = got_object_get_type(&type1, repo, id1);
3521 if (error)
3522 goto done;
3524 error = got_object_get_type(&type2, repo, id2);
3525 if (error)
3526 goto done;
3528 if (type1 != type2) {
3529 error = got_error(GOT_ERR_OBJ_TYPE);
3530 goto done;
3533 switch (type1) {
3534 case GOT_OBJ_TYPE_BLOB:
3535 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
3536 diff_context, ignore_whitespace, repo, stdout);
3537 break;
3538 case GOT_OBJ_TYPE_TREE:
3539 error = got_diff_objects_as_trees(id1, id2, "", "",
3540 diff_context, ignore_whitespace, repo, stdout);
3541 break;
3542 case GOT_OBJ_TYPE_COMMIT:
3543 printf("diff %s %s\n", label1, label2);
3544 error = got_diff_objects_as_commits(id1, id2, diff_context,
3545 ignore_whitespace, repo, stdout);
3546 break;
3547 default:
3548 error = got_error(GOT_ERR_OBJ_TYPE);
3550 done:
3551 free(label1);
3552 free(label2);
3553 free(id1);
3554 free(id2);
3555 free(path);
3556 if (worktree)
3557 got_worktree_close(worktree);
3558 if (repo) {
3559 const struct got_error *repo_error;
3560 repo_error = got_repo_close(repo);
3561 if (error == NULL)
3562 error = repo_error;
3564 return error;
3567 __dead static void
3568 usage_blame(void)
3570 fprintf(stderr,
3571 "usage: %s blame [-c commit] [-r repository-path] path\n",
3572 getprogname());
3573 exit(1);
3576 struct blame_line {
3577 int annotated;
3578 char *id_str;
3579 char *committer;
3580 char datebuf[11]; /* YYYY-MM-DD + NUL */
3583 struct blame_cb_args {
3584 struct blame_line *lines;
3585 int nlines;
3586 int nlines_prec;
3587 int lineno_cur;
3588 off_t *line_offsets;
3589 FILE *f;
3590 struct got_repository *repo;
3593 static const struct got_error *
3594 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
3596 const struct got_error *err = NULL;
3597 struct blame_cb_args *a = arg;
3598 struct blame_line *bline;
3599 char *line = NULL;
3600 size_t linesize = 0;
3601 struct got_commit_object *commit = NULL;
3602 off_t offset;
3603 struct tm tm;
3604 time_t committer_time;
3606 if (nlines != a->nlines ||
3607 (lineno != -1 && lineno < 1) || lineno > a->nlines)
3608 return got_error(GOT_ERR_RANGE);
3610 if (sigint_received)
3611 return got_error(GOT_ERR_ITER_COMPLETED);
3613 if (lineno == -1)
3614 return NULL; /* no change in this commit */
3616 /* Annotate this line. */
3617 bline = &a->lines[lineno - 1];
3618 if (bline->annotated)
3619 return NULL;
3620 err = got_object_id_str(&bline->id_str, id);
3621 if (err)
3622 return err;
3624 err = got_object_open_as_commit(&commit, a->repo, id);
3625 if (err)
3626 goto done;
3628 bline->committer = strdup(got_object_commit_get_committer(commit));
3629 if (bline->committer == NULL) {
3630 err = got_error_from_errno("strdup");
3631 goto done;
3634 committer_time = got_object_commit_get_committer_time(commit);
3635 if (localtime_r(&committer_time, &tm) == NULL)
3636 return got_error_from_errno("localtime_r");
3637 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
3638 &tm) >= sizeof(bline->datebuf)) {
3639 err = got_error(GOT_ERR_NO_SPACE);
3640 goto done;
3642 bline->annotated = 1;
3644 /* Print lines annotated so far. */
3645 bline = &a->lines[a->lineno_cur - 1];
3646 if (!bline->annotated)
3647 goto done;
3649 offset = a->line_offsets[a->lineno_cur - 1];
3650 if (fseeko(a->f, offset, SEEK_SET) == -1) {
3651 err = got_error_from_errno("fseeko");
3652 goto done;
3655 while (bline->annotated) {
3656 char *smallerthan, *at, *nl, *committer;
3657 size_t len;
3659 if (getline(&line, &linesize, a->f) == -1) {
3660 if (ferror(a->f))
3661 err = got_error_from_errno("getline");
3662 break;
3665 committer = bline->committer;
3666 smallerthan = strchr(committer, '<');
3667 if (smallerthan && smallerthan[1] != '\0')
3668 committer = smallerthan + 1;
3669 at = strchr(committer, '@');
3670 if (at)
3671 *at = '\0';
3672 len = strlen(committer);
3673 if (len >= 9)
3674 committer[8] = '\0';
3676 nl = strchr(line, '\n');
3677 if (nl)
3678 *nl = '\0';
3679 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
3680 bline->id_str, bline->datebuf, committer, line);
3682 a->lineno_cur++;
3683 bline = &a->lines[a->lineno_cur - 1];
3685 done:
3686 if (commit)
3687 got_object_commit_close(commit);
3688 free(line);
3689 return err;
3692 static const struct got_error *
3693 cmd_blame(int argc, char *argv[])
3695 const struct got_error *error;
3696 struct got_repository *repo = NULL;
3697 struct got_worktree *worktree = NULL;
3698 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
3699 struct got_object_id *obj_id = NULL;
3700 struct got_object_id *commit_id = NULL;
3701 struct got_blob_object *blob = NULL;
3702 char *commit_id_str = NULL;
3703 struct blame_cb_args bca;
3704 int ch, obj_type, i;
3705 size_t filesize;
3707 memset(&bca, 0, sizeof(bca));
3709 #ifndef PROFILE
3710 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3711 NULL) == -1)
3712 err(1, "pledge");
3713 #endif
3715 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
3716 switch (ch) {
3717 case 'c':
3718 commit_id_str = optarg;
3719 break;
3720 case 'r':
3721 repo_path = realpath(optarg, NULL);
3722 if (repo_path == NULL)
3723 return got_error_from_errno2("realpath",
3724 optarg);
3725 got_path_strip_trailing_slashes(repo_path);
3726 break;
3727 default:
3728 usage_blame();
3729 /* NOTREACHED */
3733 argc -= optind;
3734 argv += optind;
3736 if (argc == 1)
3737 path = argv[0];
3738 else
3739 usage_blame();
3741 cwd = getcwd(NULL, 0);
3742 if (cwd == NULL) {
3743 error = got_error_from_errno("getcwd");
3744 goto done;
3746 if (repo_path == NULL) {
3747 error = got_worktree_open(&worktree, cwd);
3748 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3749 goto done;
3750 else
3751 error = NULL;
3752 if (worktree) {
3753 repo_path =
3754 strdup(got_worktree_get_repo_path(worktree));
3755 if (repo_path == NULL) {
3756 error = got_error_from_errno("strdup");
3757 if (error)
3758 goto done;
3760 } else {
3761 repo_path = strdup(cwd);
3762 if (repo_path == NULL) {
3763 error = got_error_from_errno("strdup");
3764 goto done;
3769 error = got_repo_open(&repo, repo_path, NULL);
3770 if (error != NULL)
3771 goto done;
3773 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
3774 if (error)
3775 goto done;
3777 if (worktree) {
3778 const char *prefix = got_worktree_get_path_prefix(worktree);
3779 char *p, *worktree_subdir = cwd +
3780 strlen(got_worktree_get_root_path(worktree));
3781 if (asprintf(&p, "%s%s%s%s%s",
3782 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
3783 worktree_subdir, worktree_subdir[0] ? "/" : "",
3784 path) == -1) {
3785 error = got_error_from_errno("asprintf");
3786 goto done;
3788 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3789 free(p);
3790 } else {
3791 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3793 if (error)
3794 goto done;
3796 if (commit_id_str == NULL) {
3797 struct got_reference *head_ref;
3798 error = got_ref_open(&head_ref, repo, worktree ?
3799 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
3800 if (error != NULL)
3801 goto done;
3802 error = got_ref_resolve(&commit_id, repo, head_ref);
3803 got_ref_close(head_ref);
3804 if (error != NULL)
3805 goto done;
3806 } else {
3807 error = got_repo_match_object_id(&commit_id, NULL,
3808 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
3809 if (error)
3810 goto done;
3813 error = got_object_id_by_path(&obj_id, repo, commit_id, in_repo_path);
3814 if (error)
3815 goto done;
3817 error = got_object_get_type(&obj_type, repo, obj_id);
3818 if (error)
3819 goto done;
3821 if (obj_type != GOT_OBJ_TYPE_BLOB) {
3822 error = got_error(GOT_ERR_OBJ_TYPE);
3823 goto done;
3826 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
3827 if (error)
3828 goto done;
3829 bca.f = got_opentemp();
3830 if (bca.f == NULL) {
3831 error = got_error_from_errno("got_opentemp");
3832 goto done;
3834 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
3835 &bca.line_offsets, bca.f, blob);
3836 if (error || bca.nlines == 0)
3837 goto done;
3839 /* Don't include \n at EOF in the blame line count. */
3840 if (bca.line_offsets[bca.nlines - 1] == filesize)
3841 bca.nlines--;
3843 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
3844 if (bca.lines == NULL) {
3845 error = got_error_from_errno("calloc");
3846 goto done;
3848 bca.lineno_cur = 1;
3849 bca.nlines_prec = 0;
3850 i = bca.nlines;
3851 while (i > 0) {
3852 i /= 10;
3853 bca.nlines_prec++;
3855 bca.repo = repo;
3857 error = got_blame(in_repo_path, commit_id, repo, blame_cb, &bca,
3858 check_cancelled, NULL);
3859 done:
3860 free(in_repo_path);
3861 free(repo_path);
3862 free(cwd);
3863 free(commit_id);
3864 free(obj_id);
3865 if (blob)
3866 got_object_blob_close(blob);
3867 if (worktree)
3868 got_worktree_close(worktree);
3869 if (repo) {
3870 const struct got_error *repo_error;
3871 repo_error = got_repo_close(repo);
3872 if (error == NULL)
3873 error = repo_error;
3875 if (bca.lines) {
3876 for (i = 0; i < bca.nlines; i++) {
3877 struct blame_line *bline = &bca.lines[i];
3878 free(bline->id_str);
3879 free(bline->committer);
3881 free(bca.lines);
3883 free(bca.line_offsets);
3884 if (bca.f && fclose(bca.f) == EOF && error == NULL)
3885 error = got_error_from_errno("fclose");
3886 return error;
3889 __dead static void
3890 usage_tree(void)
3892 fprintf(stderr,
3893 "usage: %s tree [-c commit] [-r repository-path] [-iR] path\n",
3894 getprogname());
3895 exit(1);
3898 static void
3899 print_entry(struct got_tree_entry *te, const char *id, const char *path,
3900 const char *root_path)
3902 int is_root_path = (strcmp(path, root_path) == 0);
3903 const char *modestr = "";
3904 mode_t mode = got_tree_entry_get_mode(te);
3906 path += strlen(root_path);
3907 while (path[0] == '/')
3908 path++;
3910 if (got_object_tree_entry_is_submodule(te))
3911 modestr = "$";
3912 else if (S_ISLNK(mode))
3913 modestr = "@";
3914 else if (S_ISDIR(mode))
3915 modestr = "/";
3916 else if (mode & S_IXUSR)
3917 modestr = "*";
3919 printf("%s%s%s%s%s\n", id ? id : "", path,
3920 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr);
3923 static const struct got_error *
3924 print_tree(const char *path, struct got_object_id *commit_id,
3925 int show_ids, int recurse, const char *root_path,
3926 struct got_repository *repo)
3928 const struct got_error *err = NULL;
3929 struct got_object_id *tree_id = NULL;
3930 struct got_tree_object *tree = NULL;
3931 int nentries, i;
3933 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
3934 if (err)
3935 goto done;
3937 err = got_object_open_as_tree(&tree, repo, tree_id);
3938 if (err)
3939 goto done;
3940 nentries = got_object_tree_get_nentries(tree);
3941 for (i = 0; i < nentries; i++) {
3942 struct got_tree_entry *te;
3943 char *id = NULL;
3945 if (sigint_received || sigpipe_received)
3946 break;
3948 te = got_object_tree_get_entry(tree, i);
3949 if (show_ids) {
3950 char *id_str;
3951 err = got_object_id_str(&id_str,
3952 got_tree_entry_get_id(te));
3953 if (err)
3954 goto done;
3955 if (asprintf(&id, "%s ", id_str) == -1) {
3956 err = got_error_from_errno("asprintf");
3957 free(id_str);
3958 goto done;
3960 free(id_str);
3962 print_entry(te, id, path, root_path);
3963 free(id);
3965 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
3966 char *child_path;
3967 if (asprintf(&child_path, "%s%s%s", path,
3968 path[0] == '/' && path[1] == '\0' ? "" : "/",
3969 got_tree_entry_get_name(te)) == -1) {
3970 err = got_error_from_errno("asprintf");
3971 goto done;
3973 err = print_tree(child_path, commit_id, show_ids, 1,
3974 root_path, repo);
3975 free(child_path);
3976 if (err)
3977 goto done;
3980 done:
3981 if (tree)
3982 got_object_tree_close(tree);
3983 free(tree_id);
3984 return err;
3987 static const struct got_error *
3988 cmd_tree(int argc, char *argv[])
3990 const struct got_error *error;
3991 struct got_repository *repo = NULL;
3992 struct got_worktree *worktree = NULL;
3993 const char *path, *refname = NULL;
3994 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
3995 struct got_object_id *commit_id = NULL;
3996 char *commit_id_str = NULL;
3997 int show_ids = 0, recurse = 0;
3998 int ch;
4000 #ifndef PROFILE
4001 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4002 NULL) == -1)
4003 err(1, "pledge");
4004 #endif
4006 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4007 switch (ch) {
4008 case 'c':
4009 commit_id_str = optarg;
4010 break;
4011 case 'r':
4012 repo_path = realpath(optarg, NULL);
4013 if (repo_path == NULL)
4014 return got_error_from_errno2("realpath",
4015 optarg);
4016 got_path_strip_trailing_slashes(repo_path);
4017 break;
4018 case 'i':
4019 show_ids = 1;
4020 break;
4021 case 'R':
4022 recurse = 1;
4023 break;
4024 default:
4025 usage_tree();
4026 /* NOTREACHED */
4030 argc -= optind;
4031 argv += optind;
4033 if (argc == 1)
4034 path = argv[0];
4035 else if (argc > 1)
4036 usage_tree();
4037 else
4038 path = NULL;
4040 cwd = getcwd(NULL, 0);
4041 if (cwd == NULL) {
4042 error = got_error_from_errno("getcwd");
4043 goto done;
4045 if (repo_path == NULL) {
4046 error = got_worktree_open(&worktree, cwd);
4047 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4048 goto done;
4049 else
4050 error = NULL;
4051 if (worktree) {
4052 repo_path =
4053 strdup(got_worktree_get_repo_path(worktree));
4054 if (repo_path == NULL)
4055 error = got_error_from_errno("strdup");
4056 if (error)
4057 goto done;
4058 } else {
4059 repo_path = strdup(cwd);
4060 if (repo_path == NULL) {
4061 error = got_error_from_errno("strdup");
4062 goto done;
4067 error = got_repo_open(&repo, repo_path, NULL);
4068 if (error != NULL)
4069 goto done;
4071 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4072 if (error)
4073 goto done;
4075 if (path == NULL) {
4076 if (worktree) {
4077 char *p, *worktree_subdir = cwd +
4078 strlen(got_worktree_get_root_path(worktree));
4079 if (asprintf(&p, "%s/%s",
4080 got_worktree_get_path_prefix(worktree),
4081 worktree_subdir) == -1) {
4082 error = got_error_from_errno("asprintf");
4083 goto done;
4085 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4086 free(p);
4087 if (error)
4088 goto done;
4089 } else
4090 path = "/";
4092 if (in_repo_path == NULL) {
4093 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4094 if (error != NULL)
4095 goto done;
4098 if (commit_id_str == NULL) {
4099 struct got_reference *head_ref;
4100 if (worktree)
4101 refname = got_worktree_get_head_ref_name(worktree);
4102 else
4103 refname = GOT_REF_HEAD;
4104 error = got_ref_open(&head_ref, repo, refname, 0);
4105 if (error != NULL)
4106 goto done;
4107 error = got_ref_resolve(&commit_id, repo, head_ref);
4108 got_ref_close(head_ref);
4109 if (error != NULL)
4110 goto done;
4111 } else {
4112 error = got_repo_match_object_id(&commit_id, NULL,
4113 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4114 if (error)
4115 goto done;
4118 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4119 in_repo_path, repo);
4120 done:
4121 free(in_repo_path);
4122 free(repo_path);
4123 free(cwd);
4124 free(commit_id);
4125 if (worktree)
4126 got_worktree_close(worktree);
4127 if (repo) {
4128 const struct got_error *repo_error;
4129 repo_error = got_repo_close(repo);
4130 if (error == NULL)
4131 error = repo_error;
4133 return error;
4136 __dead static void
4137 usage_status(void)
4139 fprintf(stderr, "usage: %s status [path ...]\n", getprogname());
4140 exit(1);
4143 static const struct got_error *
4144 print_status(void *arg, unsigned char status, unsigned char staged_status,
4145 const char *path, struct got_object_id *blob_id,
4146 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4147 int dirfd, const char *de_name)
4149 if (status == staged_status && (status == GOT_STATUS_DELETE))
4150 status = GOT_STATUS_NO_CHANGE;
4151 printf("%c%c %s\n", status, staged_status, path);
4152 return NULL;
4155 static const struct got_error *
4156 cmd_status(int argc, char *argv[])
4158 const struct got_error *error = NULL;
4159 struct got_repository *repo = NULL;
4160 struct got_worktree *worktree = NULL;
4161 char *cwd = NULL;
4162 struct got_pathlist_head paths;
4163 struct got_pathlist_entry *pe;
4164 int ch;
4166 TAILQ_INIT(&paths);
4168 while ((ch = getopt(argc, argv, "")) != -1) {
4169 switch (ch) {
4170 default:
4171 usage_status();
4172 /* NOTREACHED */
4176 argc -= optind;
4177 argv += optind;
4179 #ifndef PROFILE
4180 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4181 NULL) == -1)
4182 err(1, "pledge");
4183 #endif
4184 cwd = getcwd(NULL, 0);
4185 if (cwd == NULL) {
4186 error = got_error_from_errno("getcwd");
4187 goto done;
4190 error = got_worktree_open(&worktree, cwd);
4191 if (error != NULL)
4192 goto done;
4194 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4195 NULL);
4196 if (error != NULL)
4197 goto done;
4199 error = apply_unveil(got_repo_get_path(repo), 1,
4200 got_worktree_get_root_path(worktree));
4201 if (error)
4202 goto done;
4204 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
4205 if (error)
4206 goto done;
4208 error = got_worktree_status(worktree, &paths, repo, print_status, NULL,
4209 check_cancelled, NULL);
4210 done:
4211 TAILQ_FOREACH(pe, &paths, entry)
4212 free((char *)pe->path);
4213 got_pathlist_free(&paths);
4214 free(cwd);
4215 return error;
4218 __dead static void
4219 usage_ref(void)
4221 fprintf(stderr,
4222 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
4223 "[-d] [name]\n",
4224 getprogname());
4225 exit(1);
4228 static const struct got_error *
4229 list_refs(struct got_repository *repo, const char *refname)
4231 static const struct got_error *err = NULL;
4232 struct got_reflist_head refs;
4233 struct got_reflist_entry *re;
4235 SIMPLEQ_INIT(&refs);
4236 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
4237 if (err)
4238 return err;
4240 SIMPLEQ_FOREACH(re, &refs, entry) {
4241 char *refstr;
4242 refstr = got_ref_to_str(re->ref);
4243 if (refstr == NULL)
4244 return got_error_from_errno("got_ref_to_str");
4245 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
4246 free(refstr);
4249 got_ref_list_free(&refs);
4250 return NULL;
4253 static const struct got_error *
4254 delete_ref(struct got_repository *repo, const char *refname)
4256 const struct got_error *err = NULL;
4257 struct got_reference *ref;
4259 err = got_ref_open(&ref, repo, refname, 0);
4260 if (err)
4261 return err;
4263 err = got_ref_delete(ref, repo);
4264 got_ref_close(ref);
4265 return err;
4268 static const struct got_error *
4269 add_ref(struct got_repository *repo, const char *refname, const char *target)
4271 const struct got_error *err = NULL;
4272 struct got_object_id *id;
4273 struct got_reference *ref = NULL;
4276 * Don't let the user create a reference name with a leading '-'.
4277 * While technically a valid reference name, this case is usually
4278 * an unintended typo.
4280 if (refname[0] == '-')
4281 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4283 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
4284 repo);
4285 if (err) {
4286 struct got_reference *target_ref;
4288 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
4289 return err;
4290 err = got_ref_open(&target_ref, repo, target, 0);
4291 if (err)
4292 return err;
4293 err = got_ref_resolve(&id, repo, target_ref);
4294 got_ref_close(target_ref);
4295 if (err)
4296 return err;
4299 err = got_ref_alloc(&ref, refname, id);
4300 if (err)
4301 goto done;
4303 err = got_ref_write(ref, repo);
4304 done:
4305 if (ref)
4306 got_ref_close(ref);
4307 free(id);
4308 return err;
4311 static const struct got_error *
4312 add_symref(struct got_repository *repo, const char *refname, const char *target)
4314 const struct got_error *err = NULL;
4315 struct got_reference *ref = NULL;
4316 struct got_reference *target_ref = NULL;
4319 * Don't let the user create a reference name with a leading '-'.
4320 * While technically a valid reference name, this case is usually
4321 * an unintended typo.
4323 if (refname[0] == '-')
4324 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4326 err = got_ref_open(&target_ref, repo, target, 0);
4327 if (err)
4328 return err;
4330 err = got_ref_alloc_symref(&ref, refname, target_ref);
4331 if (err)
4332 goto done;
4334 err = got_ref_write(ref, repo);
4335 done:
4336 if (target_ref)
4337 got_ref_close(target_ref);
4338 if (ref)
4339 got_ref_close(ref);
4340 return err;
4343 static const struct got_error *
4344 cmd_ref(int argc, char *argv[])
4346 const struct got_error *error = NULL;
4347 struct got_repository *repo = NULL;
4348 struct got_worktree *worktree = NULL;
4349 char *cwd = NULL, *repo_path = NULL;
4350 int ch, do_list = 0, do_delete = 0;
4351 const char *obj_arg = NULL, *symref_target= NULL;
4352 char *refname = NULL;
4354 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
4355 switch (ch) {
4356 case 'c':
4357 obj_arg = optarg;
4358 break;
4359 case 'd':
4360 do_delete = 1;
4361 break;
4362 case 'r':
4363 repo_path = realpath(optarg, NULL);
4364 if (repo_path == NULL)
4365 return got_error_from_errno2("realpath",
4366 optarg);
4367 got_path_strip_trailing_slashes(repo_path);
4368 break;
4369 case 'l':
4370 do_list = 1;
4371 break;
4372 case 's':
4373 symref_target = optarg;
4374 break;
4375 default:
4376 usage_ref();
4377 /* NOTREACHED */
4381 if (obj_arg && do_list)
4382 errx(1, "-c and -l options are mutually exclusive");
4383 if (obj_arg && do_delete)
4384 errx(1, "-c and -d options are mutually exclusive");
4385 if (obj_arg && symref_target)
4386 errx(1, "-c and -s options are mutually exclusive");
4387 if (symref_target && do_delete)
4388 errx(1, "-s and -d options are mutually exclusive");
4389 if (symref_target && do_list)
4390 errx(1, "-s and -l options are mutually exclusive");
4391 if (do_delete && do_list)
4392 errx(1, "-d and -l options are mutually exclusive");
4394 argc -= optind;
4395 argv += optind;
4397 if (do_list) {
4398 if (argc != 0 && argc != 1)
4399 usage_ref();
4400 if (argc == 1) {
4401 refname = strdup(argv[0]);
4402 if (refname == NULL) {
4403 error = got_error_from_errno("strdup");
4404 goto done;
4407 } else {
4408 if (argc != 1)
4409 usage_ref();
4410 refname = strdup(argv[0]);
4411 if (refname == NULL) {
4412 error = got_error_from_errno("strdup");
4413 goto done;
4417 if (refname)
4418 got_path_strip_trailing_slashes(refname);
4420 #ifndef PROFILE
4421 if (do_list) {
4422 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4423 NULL) == -1)
4424 err(1, "pledge");
4425 } else {
4426 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4427 "sendfd unveil", NULL) == -1)
4428 err(1, "pledge");
4430 #endif
4431 cwd = getcwd(NULL, 0);
4432 if (cwd == NULL) {
4433 error = got_error_from_errno("getcwd");
4434 goto done;
4437 if (repo_path == NULL) {
4438 error = got_worktree_open(&worktree, cwd);
4439 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4440 goto done;
4441 else
4442 error = NULL;
4443 if (worktree) {
4444 repo_path =
4445 strdup(got_worktree_get_repo_path(worktree));
4446 if (repo_path == NULL)
4447 error = got_error_from_errno("strdup");
4448 if (error)
4449 goto done;
4450 } else {
4451 repo_path = strdup(cwd);
4452 if (repo_path == NULL) {
4453 error = got_error_from_errno("strdup");
4454 goto done;
4459 error = got_repo_open(&repo, repo_path, NULL);
4460 if (error != NULL)
4461 goto done;
4463 error = apply_unveil(got_repo_get_path(repo), do_list,
4464 worktree ? got_worktree_get_root_path(worktree) : NULL);
4465 if (error)
4466 goto done;
4468 if (do_list)
4469 error = list_refs(repo, refname);
4470 else if (do_delete)
4471 error = delete_ref(repo, refname);
4472 else if (symref_target)
4473 error = add_symref(repo, refname, symref_target);
4474 else {
4475 if (obj_arg == NULL)
4476 usage_ref();
4477 error = add_ref(repo, refname, obj_arg);
4479 done:
4480 free(refname);
4481 if (repo)
4482 got_repo_close(repo);
4483 if (worktree)
4484 got_worktree_close(worktree);
4485 free(cwd);
4486 free(repo_path);
4487 return error;
4490 __dead static void
4491 usage_branch(void)
4493 fprintf(stderr,
4494 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
4495 "[name]\n", getprogname());
4496 exit(1);
4499 static const struct got_error *
4500 list_branch(struct got_repository *repo, struct got_worktree *worktree,
4501 struct got_reference *ref)
4503 const struct got_error *err = NULL;
4504 const char *refname, *marker = " ";
4505 char *refstr;
4507 refname = got_ref_get_name(ref);
4508 if (worktree && strcmp(refname,
4509 got_worktree_get_head_ref_name(worktree)) == 0) {
4510 struct got_object_id *id = NULL;
4512 err = got_ref_resolve(&id, repo, ref);
4513 if (err)
4514 return err;
4515 if (got_object_id_cmp(id,
4516 got_worktree_get_base_commit_id(worktree)) == 0)
4517 marker = "* ";
4518 else
4519 marker = "~ ";
4520 free(id);
4523 if (strncmp(refname, "refs/heads/", 11) == 0)
4524 refname += 11;
4525 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4526 refname += 18;
4528 refstr = got_ref_to_str(ref);
4529 if (refstr == NULL)
4530 return got_error_from_errno("got_ref_to_str");
4532 printf("%s%s: %s\n", marker, refname, refstr);
4533 free(refstr);
4534 return NULL;
4537 static const struct got_error *
4538 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
4540 const char *refname;
4542 if (worktree == NULL)
4543 return got_error(GOT_ERR_NOT_WORKTREE);
4545 refname = got_worktree_get_head_ref_name(worktree);
4547 if (strncmp(refname, "refs/heads/", 11) == 0)
4548 refname += 11;
4549 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4550 refname += 18;
4552 printf("%s\n", refname);
4554 return NULL;
4557 static const struct got_error *
4558 list_branches(struct got_repository *repo, struct got_worktree *worktree)
4560 static const struct got_error *err = NULL;
4561 struct got_reflist_head refs;
4562 struct got_reflist_entry *re;
4563 struct got_reference *temp_ref = NULL;
4564 int rebase_in_progress, histedit_in_progress;
4566 SIMPLEQ_INIT(&refs);
4568 if (worktree) {
4569 err = got_worktree_rebase_in_progress(&rebase_in_progress,
4570 worktree);
4571 if (err)
4572 return err;
4574 err = got_worktree_histedit_in_progress(&histedit_in_progress,
4575 worktree);
4576 if (err)
4577 return err;
4579 if (rebase_in_progress || histedit_in_progress) {
4580 err = got_ref_open(&temp_ref, repo,
4581 got_worktree_get_head_ref_name(worktree), 0);
4582 if (err)
4583 return err;
4584 list_branch(repo, worktree, temp_ref);
4585 got_ref_close(temp_ref);
4589 err = got_ref_list(&refs, repo, "refs/heads",
4590 got_ref_cmp_by_name, NULL);
4591 if (err)
4592 return err;
4594 SIMPLEQ_FOREACH(re, &refs, entry)
4595 list_branch(repo, worktree, re->ref);
4597 got_ref_list_free(&refs);
4598 return NULL;
4601 static const struct got_error *
4602 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
4603 const char *branch_name)
4605 const struct got_error *err = NULL;
4606 struct got_reference *ref = NULL;
4607 char *refname;
4609 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
4610 return got_error_from_errno("asprintf");
4612 err = got_ref_open(&ref, repo, refname, 0);
4613 if (err)
4614 goto done;
4616 if (worktree &&
4617 strcmp(got_worktree_get_head_ref_name(worktree),
4618 got_ref_get_name(ref)) == 0) {
4619 err = got_error_msg(GOT_ERR_SAME_BRANCH,
4620 "will not delete this work tree's current branch");
4621 goto done;
4624 err = got_ref_delete(ref, repo);
4625 done:
4626 if (ref)
4627 got_ref_close(ref);
4628 free(refname);
4629 return err;
4632 static const struct got_error *
4633 add_branch(struct got_repository *repo, const char *branch_name,
4634 struct got_object_id *base_commit_id)
4636 const struct got_error *err = NULL;
4637 struct got_reference *ref = NULL;
4638 char *base_refname = NULL, *refname = NULL;
4641 * Don't let the user create a branch name with a leading '-'.
4642 * While technically a valid reference name, this case is usually
4643 * an unintended typo.
4645 if (branch_name[0] == '-')
4646 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
4648 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
4649 err = got_error_from_errno("asprintf");
4650 goto done;
4653 err = got_ref_open(&ref, repo, refname, 0);
4654 if (err == NULL) {
4655 err = got_error(GOT_ERR_BRANCH_EXISTS);
4656 goto done;
4657 } else if (err->code != GOT_ERR_NOT_REF)
4658 goto done;
4660 err = got_ref_alloc(&ref, refname, base_commit_id);
4661 if (err)
4662 goto done;
4664 err = got_ref_write(ref, repo);
4665 done:
4666 if (ref)
4667 got_ref_close(ref);
4668 free(base_refname);
4669 free(refname);
4670 return err;
4673 static const struct got_error *
4674 cmd_branch(int argc, char *argv[])
4676 const struct got_error *error = NULL;
4677 struct got_repository *repo = NULL;
4678 struct got_worktree *worktree = NULL;
4679 char *cwd = NULL, *repo_path = NULL;
4680 int ch, do_list = 0, do_show = 0, do_update = 1;
4681 const char *delref = NULL, *commit_id_arg = NULL;
4682 struct got_reference *ref = NULL;
4683 struct got_pathlist_head paths;
4684 struct got_pathlist_entry *pe;
4685 struct got_object_id *commit_id = NULL;
4686 char *commit_id_str = NULL;
4688 TAILQ_INIT(&paths);
4690 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
4691 switch (ch) {
4692 case 'c':
4693 commit_id_arg = optarg;
4694 break;
4695 case 'd':
4696 delref = optarg;
4697 break;
4698 case 'r':
4699 repo_path = realpath(optarg, NULL);
4700 if (repo_path == NULL)
4701 return got_error_from_errno2("realpath",
4702 optarg);
4703 got_path_strip_trailing_slashes(repo_path);
4704 break;
4705 case 'l':
4706 do_list = 1;
4707 break;
4708 case 'n':
4709 do_update = 0;
4710 break;
4711 default:
4712 usage_branch();
4713 /* NOTREACHED */
4717 if (do_list && delref)
4718 errx(1, "-l and -d options are mutually exclusive");
4720 argc -= optind;
4721 argv += optind;
4723 if (!do_list && !delref && argc == 0)
4724 do_show = 1;
4726 if ((do_list || delref || do_show) && commit_id_arg != NULL)
4727 errx(1, "-c option can only be used when creating a branch");
4729 if (do_list || delref) {
4730 if (argc > 0)
4731 usage_branch();
4732 } else if (!do_show && argc != 1)
4733 usage_branch();
4735 #ifndef PROFILE
4736 if (do_list || do_show) {
4737 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4738 NULL) == -1)
4739 err(1, "pledge");
4740 } else {
4741 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4742 "sendfd unveil", NULL) == -1)
4743 err(1, "pledge");
4745 #endif
4746 cwd = getcwd(NULL, 0);
4747 if (cwd == NULL) {
4748 error = got_error_from_errno("getcwd");
4749 goto done;
4752 if (repo_path == NULL) {
4753 error = got_worktree_open(&worktree, cwd);
4754 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4755 goto done;
4756 else
4757 error = NULL;
4758 if (worktree) {
4759 repo_path =
4760 strdup(got_worktree_get_repo_path(worktree));
4761 if (repo_path == NULL)
4762 error = got_error_from_errno("strdup");
4763 if (error)
4764 goto done;
4765 } else {
4766 repo_path = strdup(cwd);
4767 if (repo_path == NULL) {
4768 error = got_error_from_errno("strdup");
4769 goto done;
4774 error = got_repo_open(&repo, repo_path, NULL);
4775 if (error != NULL)
4776 goto done;
4778 error = apply_unveil(got_repo_get_path(repo), do_list,
4779 worktree ? got_worktree_get_root_path(worktree) : NULL);
4780 if (error)
4781 goto done;
4783 if (do_show)
4784 error = show_current_branch(repo, worktree);
4785 else if (do_list)
4786 error = list_branches(repo, worktree);
4787 else if (delref)
4788 error = delete_branch(repo, worktree, delref);
4789 else {
4790 if (commit_id_arg == NULL)
4791 commit_id_arg = worktree ?
4792 got_worktree_get_head_ref_name(worktree) :
4793 GOT_REF_HEAD;
4794 error = got_repo_match_object_id(&commit_id, NULL,
4795 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
4796 if (error)
4797 goto done;
4798 error = add_branch(repo, argv[0], commit_id);
4799 if (error)
4800 goto done;
4801 if (worktree && do_update) {
4802 int did_something = 0;
4803 char *branch_refname = NULL;
4805 error = got_object_id_str(&commit_id_str, commit_id);
4806 if (error)
4807 goto done;
4808 error = get_worktree_paths_from_argv(&paths, 0, NULL,
4809 worktree);
4810 if (error)
4811 goto done;
4812 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
4813 == -1) {
4814 error = got_error_from_errno("asprintf");
4815 goto done;
4817 error = got_ref_open(&ref, repo, branch_refname, 0);
4818 free(branch_refname);
4819 if (error)
4820 goto done;
4821 error = switch_head_ref(ref, commit_id, worktree,
4822 repo);
4823 if (error)
4824 goto done;
4825 error = got_worktree_set_base_commit_id(worktree, repo,
4826 commit_id);
4827 if (error)
4828 goto done;
4829 error = got_worktree_checkout_files(worktree, &paths,
4830 repo, update_progress, &did_something,
4831 check_cancelled, NULL);
4832 if (error)
4833 goto done;
4834 if (did_something)
4835 printf("Updated to commit %s\n", commit_id_str);
4838 done:
4839 if (ref)
4840 got_ref_close(ref);
4841 if (repo)
4842 got_repo_close(repo);
4843 if (worktree)
4844 got_worktree_close(worktree);
4845 free(cwd);
4846 free(repo_path);
4847 free(commit_id);
4848 free(commit_id_str);
4849 TAILQ_FOREACH(pe, &paths, entry)
4850 free((char *)pe->path);
4851 got_pathlist_free(&paths);
4852 return error;
4856 __dead static void
4857 usage_tag(void)
4859 fprintf(stderr,
4860 "usage: %s tag [-c commit] [-r repository] [-l] "
4861 "[-m message] name\n", getprogname());
4862 exit(1);
4865 #if 0
4866 static const struct got_error *
4867 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
4869 const struct got_error *err = NULL;
4870 struct got_reflist_entry *re, *se, *new;
4871 struct got_object_id *re_id, *se_id;
4872 struct got_tag_object *re_tag, *se_tag;
4873 time_t re_time, se_time;
4875 SIMPLEQ_FOREACH(re, tags, entry) {
4876 se = SIMPLEQ_FIRST(sorted);
4877 if (se == NULL) {
4878 err = got_reflist_entry_dup(&new, re);
4879 if (err)
4880 return err;
4881 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
4882 continue;
4883 } else {
4884 err = got_ref_resolve(&re_id, repo, re->ref);
4885 if (err)
4886 break;
4887 err = got_object_open_as_tag(&re_tag, repo, re_id);
4888 free(re_id);
4889 if (err)
4890 break;
4891 re_time = got_object_tag_get_tagger_time(re_tag);
4892 got_object_tag_close(re_tag);
4895 while (se) {
4896 err = got_ref_resolve(&se_id, repo, re->ref);
4897 if (err)
4898 break;
4899 err = got_object_open_as_tag(&se_tag, repo, se_id);
4900 free(se_id);
4901 if (err)
4902 break;
4903 se_time = got_object_tag_get_tagger_time(se_tag);
4904 got_object_tag_close(se_tag);
4906 if (se_time > re_time) {
4907 err = got_reflist_entry_dup(&new, re);
4908 if (err)
4909 return err;
4910 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
4911 break;
4913 se = SIMPLEQ_NEXT(se, entry);
4914 continue;
4917 done:
4918 return err;
4920 #endif
4922 static const struct got_error *
4923 list_tags(struct got_repository *repo, struct got_worktree *worktree)
4925 static const struct got_error *err = NULL;
4926 struct got_reflist_head refs;
4927 struct got_reflist_entry *re;
4929 SIMPLEQ_INIT(&refs);
4931 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
4932 if (err)
4933 return err;
4935 SIMPLEQ_FOREACH(re, &refs, entry) {
4936 const char *refname;
4937 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
4938 char datebuf[26];
4939 const char *tagger;
4940 time_t tagger_time;
4941 struct got_object_id *id;
4942 struct got_tag_object *tag;
4943 struct got_commit_object *commit = NULL;
4945 refname = got_ref_get_name(re->ref);
4946 if (strncmp(refname, "refs/tags/", 10) != 0)
4947 continue;
4948 refname += 10;
4949 refstr = got_ref_to_str(re->ref);
4950 if (refstr == NULL) {
4951 err = got_error_from_errno("got_ref_to_str");
4952 break;
4954 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
4955 free(refstr);
4957 err = got_ref_resolve(&id, repo, re->ref);
4958 if (err)
4959 break;
4960 err = got_object_open_as_tag(&tag, repo, id);
4961 if (err) {
4962 if (err->code != GOT_ERR_OBJ_TYPE) {
4963 free(id);
4964 break;
4966 /* "lightweight" tag */
4967 err = got_object_open_as_commit(&commit, repo, id);
4968 if (err) {
4969 free(id);
4970 break;
4972 tagger = got_object_commit_get_committer(commit);
4973 tagger_time =
4974 got_object_commit_get_committer_time(commit);
4975 err = got_object_id_str(&id_str, id);
4976 free(id);
4977 if (err)
4978 break;
4979 } else {
4980 free(id);
4981 tagger = got_object_tag_get_tagger(tag);
4982 tagger_time = got_object_tag_get_tagger_time(tag);
4983 err = got_object_id_str(&id_str,
4984 got_object_tag_get_object_id(tag));
4985 if (err)
4986 break;
4988 printf("from: %s\n", tagger);
4989 datestr = get_datestr(&tagger_time, datebuf);
4990 if (datestr)
4991 printf("date: %s UTC\n", datestr);
4992 if (commit)
4993 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
4994 else {
4995 switch (got_object_tag_get_object_type(tag)) {
4996 case GOT_OBJ_TYPE_BLOB:
4997 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
4998 id_str);
4999 break;
5000 case GOT_OBJ_TYPE_TREE:
5001 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5002 id_str);
5003 break;
5004 case GOT_OBJ_TYPE_COMMIT:
5005 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5006 id_str);
5007 break;
5008 case GOT_OBJ_TYPE_TAG:
5009 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5010 id_str);
5011 break;
5012 default:
5013 break;
5016 free(id_str);
5017 if (commit) {
5018 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5019 if (err)
5020 break;
5021 got_object_commit_close(commit);
5022 } else {
5023 tagmsg0 = strdup(got_object_tag_get_message(tag));
5024 got_object_tag_close(tag);
5025 if (tagmsg0 == NULL) {
5026 err = got_error_from_errno("strdup");
5027 break;
5031 tagmsg = tagmsg0;
5032 do {
5033 line = strsep(&tagmsg, "\n");
5034 if (line)
5035 printf(" %s\n", line);
5036 } while (line);
5037 free(tagmsg0);
5040 got_ref_list_free(&refs);
5041 return NULL;
5044 static const struct got_error *
5045 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5046 const char *tag_name, const char *repo_path)
5048 const struct got_error *err = NULL;
5049 char *template = NULL, *initial_content = NULL;
5050 char *editor = NULL;
5051 int fd = -1;
5053 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5054 err = got_error_from_errno("asprintf");
5055 goto done;
5058 if (asprintf(&initial_content, "\n# tagging commit %s as %s\n",
5059 commit_id_str, tag_name) == -1) {
5060 err = got_error_from_errno("asprintf");
5061 goto done;
5064 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5065 if (err)
5066 goto done;
5068 dprintf(fd, initial_content);
5069 close(fd);
5071 err = get_editor(&editor);
5072 if (err)
5073 goto done;
5074 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
5075 done:
5076 free(initial_content);
5077 free(template);
5078 free(editor);
5080 /* Editor is done; we can now apply unveil(2) */
5081 if (err == NULL) {
5082 err = apply_unveil(repo_path, 0, NULL);
5083 if (err) {
5084 free(*tagmsg);
5085 *tagmsg = NULL;
5088 return err;
5091 static const struct got_error *
5092 add_tag(struct got_repository *repo, const char *tag_name,
5093 const char *commit_arg, const char *tagmsg_arg)
5095 const struct got_error *err = NULL;
5096 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5097 char *label = NULL, *commit_id_str = NULL;
5098 struct got_reference *ref = NULL;
5099 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5100 char *tagmsg_path = NULL, *tag_id_str = NULL;
5101 int preserve_tagmsg = 0;
5104 * Don't let the user create a tag name with a leading '-'.
5105 * While technically a valid reference name, this case is usually
5106 * an unintended typo.
5108 if (tag_name[0] == '-')
5109 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5111 err = get_author(&tagger, repo);
5112 if (err)
5113 return err;
5115 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5116 GOT_OBJ_TYPE_COMMIT, 1, repo);
5117 if (err)
5118 goto done;
5120 err = got_object_id_str(&commit_id_str, commit_id);
5121 if (err)
5122 goto done;
5124 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5125 refname = strdup(tag_name);
5126 if (refname == NULL) {
5127 err = got_error_from_errno("strdup");
5128 goto done;
5130 tag_name += 10;
5131 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5132 err = got_error_from_errno("asprintf");
5133 goto done;
5136 err = got_ref_open(&ref, repo, refname, 0);
5137 if (err == NULL) {
5138 err = got_error(GOT_ERR_TAG_EXISTS);
5139 goto done;
5140 } else if (err->code != GOT_ERR_NOT_REF)
5141 goto done;
5143 if (tagmsg_arg == NULL) {
5144 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5145 tag_name, got_repo_get_path(repo));
5146 if (err) {
5147 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5148 tagmsg_path != NULL)
5149 preserve_tagmsg = 1;
5150 goto done;
5154 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5155 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5156 if (err) {
5157 if (tagmsg_path)
5158 preserve_tagmsg = 1;
5159 goto done;
5162 err = got_ref_alloc(&ref, refname, tag_id);
5163 if (err) {
5164 if (tagmsg_path)
5165 preserve_tagmsg = 1;
5166 goto done;
5169 err = got_ref_write(ref, repo);
5170 if (err) {
5171 if (tagmsg_path)
5172 preserve_tagmsg = 1;
5173 goto done;
5176 err = got_object_id_str(&tag_id_str, tag_id);
5177 if (err) {
5178 if (tagmsg_path)
5179 preserve_tagmsg = 1;
5180 goto done;
5182 printf("Created tag %s\n", tag_id_str);
5183 done:
5184 if (preserve_tagmsg) {
5185 fprintf(stderr, "%s: tag message preserved in %s\n",
5186 getprogname(), tagmsg_path);
5187 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
5188 err = got_error_from_errno2("unlink", tagmsg_path);
5189 free(tag_id_str);
5190 if (ref)
5191 got_ref_close(ref);
5192 free(commit_id);
5193 free(commit_id_str);
5194 free(refname);
5195 free(tagmsg);
5196 free(tagmsg_path);
5197 free(tagger);
5198 return err;
5201 static const struct got_error *
5202 cmd_tag(int argc, char *argv[])
5204 const struct got_error *error = NULL;
5205 struct got_repository *repo = NULL;
5206 struct got_worktree *worktree = NULL;
5207 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
5208 char *gitconfig_path = NULL;
5209 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
5210 int ch, do_list = 0;
5212 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
5213 switch (ch) {
5214 case 'c':
5215 commit_id_arg = optarg;
5216 break;
5217 case 'm':
5218 tagmsg = optarg;
5219 break;
5220 case 'r':
5221 repo_path = realpath(optarg, NULL);
5222 if (repo_path == NULL)
5223 return got_error_from_errno2("realpath",
5224 optarg);
5225 got_path_strip_trailing_slashes(repo_path);
5226 break;
5227 case 'l':
5228 do_list = 1;
5229 break;
5230 default:
5231 usage_tag();
5232 /* NOTREACHED */
5236 argc -= optind;
5237 argv += optind;
5239 if (do_list) {
5240 if (commit_id_arg != NULL)
5241 errx(1,
5242 "-c option can only be used when creating a tag");
5243 if (tagmsg)
5244 errx(1, "-l and -m options are mutually exclusive");
5245 if (argc > 0)
5246 usage_tag();
5247 } else if (argc != 1)
5248 usage_tag();
5250 tag_name = argv[0];
5252 #ifndef PROFILE
5253 if (do_list) {
5254 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5255 NULL) == -1)
5256 err(1, "pledge");
5257 } else {
5258 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5259 "sendfd unveil", NULL) == -1)
5260 err(1, "pledge");
5262 #endif
5263 cwd = getcwd(NULL, 0);
5264 if (cwd == NULL) {
5265 error = got_error_from_errno("getcwd");
5266 goto done;
5269 if (repo_path == NULL) {
5270 error = got_worktree_open(&worktree, cwd);
5271 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5272 goto done;
5273 else
5274 error = NULL;
5275 if (worktree) {
5276 repo_path =
5277 strdup(got_worktree_get_repo_path(worktree));
5278 if (repo_path == NULL)
5279 error = got_error_from_errno("strdup");
5280 if (error)
5281 goto done;
5282 } else {
5283 repo_path = strdup(cwd);
5284 if (repo_path == NULL) {
5285 error = got_error_from_errno("strdup");
5286 goto done;
5291 if (do_list) {
5292 error = got_repo_open(&repo, repo_path, NULL);
5293 if (error != NULL)
5294 goto done;
5295 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5296 if (error)
5297 goto done;
5298 error = list_tags(repo, worktree);
5299 } else {
5300 error = get_gitconfig_path(&gitconfig_path);
5301 if (error)
5302 goto done;
5303 error = got_repo_open(&repo, repo_path, gitconfig_path);
5304 if (error != NULL)
5305 goto done;
5307 if (tagmsg) {
5308 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5309 if (error)
5310 goto done;
5313 if (commit_id_arg == NULL) {
5314 struct got_reference *head_ref;
5315 struct got_object_id *commit_id;
5316 error = got_ref_open(&head_ref, repo,
5317 worktree ? got_worktree_get_head_ref_name(worktree)
5318 : GOT_REF_HEAD, 0);
5319 if (error)
5320 goto done;
5321 error = got_ref_resolve(&commit_id, repo, head_ref);
5322 got_ref_close(head_ref);
5323 if (error)
5324 goto done;
5325 error = got_object_id_str(&commit_id_str, commit_id);
5326 free(commit_id);
5327 if (error)
5328 goto done;
5331 error = add_tag(repo, tag_name,
5332 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
5334 done:
5335 if (repo)
5336 got_repo_close(repo);
5337 if (worktree)
5338 got_worktree_close(worktree);
5339 free(cwd);
5340 free(repo_path);
5341 free(gitconfig_path);
5342 free(commit_id_str);
5343 return error;
5346 __dead static void
5347 usage_add(void)
5349 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
5350 getprogname());
5351 exit(1);
5354 static const struct got_error *
5355 add_progress(void *arg, unsigned char status, const char *path)
5357 while (path[0] == '/')
5358 path++;
5359 printf("%c %s\n", status, path);
5360 return NULL;
5363 static const struct got_error *
5364 cmd_add(int argc, char *argv[])
5366 const struct got_error *error = NULL;
5367 struct got_repository *repo = NULL;
5368 struct got_worktree *worktree = NULL;
5369 char *cwd = NULL;
5370 struct got_pathlist_head paths;
5371 struct got_pathlist_entry *pe;
5372 int ch, can_recurse = 0, no_ignores = 0;
5374 TAILQ_INIT(&paths);
5376 while ((ch = getopt(argc, argv, "IR")) != -1) {
5377 switch (ch) {
5378 case 'I':
5379 no_ignores = 1;
5380 break;
5381 case 'R':
5382 can_recurse = 1;
5383 break;
5384 default:
5385 usage_add();
5386 /* NOTREACHED */
5390 argc -= optind;
5391 argv += optind;
5393 #ifndef PROFILE
5394 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5395 NULL) == -1)
5396 err(1, "pledge");
5397 #endif
5398 if (argc < 1)
5399 usage_add();
5401 cwd = getcwd(NULL, 0);
5402 if (cwd == NULL) {
5403 error = got_error_from_errno("getcwd");
5404 goto done;
5407 error = got_worktree_open(&worktree, cwd);
5408 if (error)
5409 goto done;
5411 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5412 NULL);
5413 if (error != NULL)
5414 goto done;
5416 error = apply_unveil(got_repo_get_path(repo), 1,
5417 got_worktree_get_root_path(worktree));
5418 if (error)
5419 goto done;
5421 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5422 if (error)
5423 goto done;
5425 if (!can_recurse && no_ignores) {
5426 error = got_error_msg(GOT_ERR_BAD_PATH,
5427 "disregarding ignores requires -R option");
5428 goto done;
5432 if (!can_recurse) {
5433 char *ondisk_path;
5434 struct stat sb;
5435 TAILQ_FOREACH(pe, &paths, entry) {
5436 if (asprintf(&ondisk_path, "%s/%s",
5437 got_worktree_get_root_path(worktree),
5438 pe->path) == -1) {
5439 error = got_error_from_errno("asprintf");
5440 goto done;
5442 if (lstat(ondisk_path, &sb) == -1) {
5443 if (errno == ENOENT) {
5444 free(ondisk_path);
5445 continue;
5447 error = got_error_from_errno2("lstat",
5448 ondisk_path);
5449 free(ondisk_path);
5450 goto done;
5452 free(ondisk_path);
5453 if (S_ISDIR(sb.st_mode)) {
5454 error = got_error_msg(GOT_ERR_BAD_PATH,
5455 "adding directories requires -R option");
5456 goto done;
5461 error = got_worktree_schedule_add(worktree, &paths, add_progress,
5462 NULL, repo, no_ignores);
5463 done:
5464 if (repo)
5465 got_repo_close(repo);
5466 if (worktree)
5467 got_worktree_close(worktree);
5468 TAILQ_FOREACH(pe, &paths, entry)
5469 free((char *)pe->path);
5470 got_pathlist_free(&paths);
5471 free(cwd);
5472 return error;
5475 __dead static void
5476 usage_remove(void)
5478 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] path ...\n",
5479 getprogname());
5480 exit(1);
5483 static const struct got_error *
5484 print_remove_status(void *arg, unsigned char status,
5485 unsigned char staged_status, const char *path)
5487 while (path[0] == '/')
5488 path++;
5489 if (status == GOT_STATUS_NONEXISTENT)
5490 return NULL;
5491 if (status == staged_status && (status == GOT_STATUS_DELETE))
5492 status = GOT_STATUS_NO_CHANGE;
5493 printf("%c%c %s\n", status, staged_status, path);
5494 return NULL;
5497 static const struct got_error *
5498 cmd_remove(int argc, char *argv[])
5500 const struct got_error *error = NULL;
5501 struct got_worktree *worktree = NULL;
5502 struct got_repository *repo = NULL;
5503 char *cwd = NULL;
5504 struct got_pathlist_head paths;
5505 struct got_pathlist_entry *pe;
5506 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0;
5508 TAILQ_INIT(&paths);
5510 while ((ch = getopt(argc, argv, "fkR")) != -1) {
5511 switch (ch) {
5512 case 'f':
5513 delete_local_mods = 1;
5514 break;
5515 case 'k':
5516 keep_on_disk = 1;
5517 break;
5518 case 'R':
5519 can_recurse = 1;
5520 break;
5521 default:
5522 usage_remove();
5523 /* NOTREACHED */
5527 argc -= optind;
5528 argv += optind;
5530 #ifndef PROFILE
5531 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5532 NULL) == -1)
5533 err(1, "pledge");
5534 #endif
5535 if (argc < 1)
5536 usage_remove();
5538 cwd = getcwd(NULL, 0);
5539 if (cwd == NULL) {
5540 error = got_error_from_errno("getcwd");
5541 goto done;
5543 error = got_worktree_open(&worktree, cwd);
5544 if (error)
5545 goto done;
5547 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5548 NULL);
5549 if (error)
5550 goto done;
5552 error = apply_unveil(got_repo_get_path(repo), 1,
5553 got_worktree_get_root_path(worktree));
5554 if (error)
5555 goto done;
5557 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5558 if (error)
5559 goto done;
5561 if (!can_recurse) {
5562 char *ondisk_path;
5563 struct stat sb;
5564 TAILQ_FOREACH(pe, &paths, entry) {
5565 if (asprintf(&ondisk_path, "%s/%s",
5566 got_worktree_get_root_path(worktree),
5567 pe->path) == -1) {
5568 error = got_error_from_errno("asprintf");
5569 goto done;
5571 if (lstat(ondisk_path, &sb) == -1) {
5572 if (errno == ENOENT) {
5573 free(ondisk_path);
5574 continue;
5576 error = got_error_from_errno2("lstat",
5577 ondisk_path);
5578 free(ondisk_path);
5579 goto done;
5581 free(ondisk_path);
5582 if (S_ISDIR(sb.st_mode)) {
5583 error = got_error_msg(GOT_ERR_BAD_PATH,
5584 "removing directories requires -R option");
5585 goto done;
5590 error = got_worktree_schedule_delete(worktree, &paths,
5591 delete_local_mods, print_remove_status, NULL, repo, keep_on_disk);
5592 done:
5593 if (repo)
5594 got_repo_close(repo);
5595 if (worktree)
5596 got_worktree_close(worktree);
5597 TAILQ_FOREACH(pe, &paths, entry)
5598 free((char *)pe->path);
5599 got_pathlist_free(&paths);
5600 free(cwd);
5601 return error;
5604 __dead static void
5605 usage_revert(void)
5607 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
5608 "path ...\n", getprogname());
5609 exit(1);
5612 static const struct got_error *
5613 revert_progress(void *arg, unsigned char status, const char *path)
5615 if (status == GOT_STATUS_UNVERSIONED)
5616 return NULL;
5618 while (path[0] == '/')
5619 path++;
5620 printf("%c %s\n", status, path);
5621 return NULL;
5624 struct choose_patch_arg {
5625 FILE *patch_script_file;
5626 const char *action;
5629 static const struct got_error *
5630 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
5631 int nchanges, const char *action)
5633 char *line = NULL;
5634 size_t linesize = 0;
5635 ssize_t linelen;
5637 switch (status) {
5638 case GOT_STATUS_ADD:
5639 printf("A %s\n%s this addition? [y/n] ", path, action);
5640 break;
5641 case GOT_STATUS_DELETE:
5642 printf("D %s\n%s this deletion? [y/n] ", path, action);
5643 break;
5644 case GOT_STATUS_MODIFY:
5645 if (fseek(patch_file, 0L, SEEK_SET) == -1)
5646 return got_error_from_errno("fseek");
5647 printf(GOT_COMMIT_SEP_STR);
5648 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
5649 printf("%s", line);
5650 if (ferror(patch_file))
5651 return got_error_from_errno("getline");
5652 printf(GOT_COMMIT_SEP_STR);
5653 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
5654 path, n, nchanges, action);
5655 break;
5656 default:
5657 return got_error_path(path, GOT_ERR_FILE_STATUS);
5660 return NULL;
5663 static const struct got_error *
5664 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
5665 FILE *patch_file, int n, int nchanges)
5667 const struct got_error *err = NULL;
5668 char *line = NULL;
5669 size_t linesize = 0;
5670 ssize_t linelen;
5671 int resp = ' ';
5672 struct choose_patch_arg *a = arg;
5674 *choice = GOT_PATCH_CHOICE_NONE;
5676 if (a->patch_script_file) {
5677 char *nl;
5678 err = show_change(status, path, patch_file, n, nchanges,
5679 a->action);
5680 if (err)
5681 return err;
5682 linelen = getline(&line, &linesize, a->patch_script_file);
5683 if (linelen == -1) {
5684 if (ferror(a->patch_script_file))
5685 return got_error_from_errno("getline");
5686 return NULL;
5688 nl = strchr(line, '\n');
5689 if (nl)
5690 *nl = '\0';
5691 if (strcmp(line, "y") == 0) {
5692 *choice = GOT_PATCH_CHOICE_YES;
5693 printf("y\n");
5694 } else if (strcmp(line, "n") == 0) {
5695 *choice = GOT_PATCH_CHOICE_NO;
5696 printf("n\n");
5697 } else if (strcmp(line, "q") == 0 &&
5698 status == GOT_STATUS_MODIFY) {
5699 *choice = GOT_PATCH_CHOICE_QUIT;
5700 printf("q\n");
5701 } else
5702 printf("invalid response '%s'\n", line);
5703 free(line);
5704 return NULL;
5707 while (resp != 'y' && resp != 'n' && resp != 'q') {
5708 err = show_change(status, path, patch_file, n, nchanges,
5709 a->action);
5710 if (err)
5711 return err;
5712 resp = getchar();
5713 if (resp == '\n')
5714 resp = getchar();
5715 if (status == GOT_STATUS_MODIFY) {
5716 if (resp != 'y' && resp != 'n' && resp != 'q') {
5717 printf("invalid response '%c'\n", resp);
5718 resp = ' ';
5720 } else if (resp != 'y' && resp != 'n') {
5721 printf("invalid response '%c'\n", resp);
5722 resp = ' ';
5726 if (resp == 'y')
5727 *choice = GOT_PATCH_CHOICE_YES;
5728 else if (resp == 'n')
5729 *choice = GOT_PATCH_CHOICE_NO;
5730 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
5731 *choice = GOT_PATCH_CHOICE_QUIT;
5733 return NULL;
5737 static const struct got_error *
5738 cmd_revert(int argc, char *argv[])
5740 const struct got_error *error = NULL;
5741 struct got_worktree *worktree = NULL;
5742 struct got_repository *repo = NULL;
5743 char *cwd = NULL, *path = NULL;
5744 struct got_pathlist_head paths;
5745 struct got_pathlist_entry *pe;
5746 int ch, can_recurse = 0, pflag = 0;
5747 FILE *patch_script_file = NULL;
5748 const char *patch_script_path = NULL;
5749 struct choose_patch_arg cpa;
5751 TAILQ_INIT(&paths);
5753 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
5754 switch (ch) {
5755 case 'p':
5756 pflag = 1;
5757 break;
5758 case 'F':
5759 patch_script_path = optarg;
5760 break;
5761 case 'R':
5762 can_recurse = 1;
5763 break;
5764 default:
5765 usage_revert();
5766 /* NOTREACHED */
5770 argc -= optind;
5771 argv += optind;
5773 #ifndef PROFILE
5774 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
5775 "unveil", NULL) == -1)
5776 err(1, "pledge");
5777 #endif
5778 if (argc < 1)
5779 usage_revert();
5780 if (patch_script_path && !pflag)
5781 errx(1, "-F option can only be used together with -p option");
5783 cwd = getcwd(NULL, 0);
5784 if (cwd == NULL) {
5785 error = got_error_from_errno("getcwd");
5786 goto done;
5788 error = got_worktree_open(&worktree, cwd);
5789 if (error)
5790 goto done;
5792 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5793 NULL);
5794 if (error != NULL)
5795 goto done;
5797 if (patch_script_path) {
5798 patch_script_file = fopen(patch_script_path, "r");
5799 if (patch_script_file == NULL) {
5800 error = got_error_from_errno2("fopen",
5801 patch_script_path);
5802 goto done;
5805 error = apply_unveil(got_repo_get_path(repo), 1,
5806 got_worktree_get_root_path(worktree));
5807 if (error)
5808 goto done;
5810 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5811 if (error)
5812 goto done;
5814 if (!can_recurse) {
5815 char *ondisk_path;
5816 struct stat sb;
5817 TAILQ_FOREACH(pe, &paths, entry) {
5818 if (asprintf(&ondisk_path, "%s/%s",
5819 got_worktree_get_root_path(worktree),
5820 pe->path) == -1) {
5821 error = got_error_from_errno("asprintf");
5822 goto done;
5824 if (lstat(ondisk_path, &sb) == -1) {
5825 if (errno == ENOENT) {
5826 free(ondisk_path);
5827 continue;
5829 error = got_error_from_errno2("lstat",
5830 ondisk_path);
5831 free(ondisk_path);
5832 goto done;
5834 free(ondisk_path);
5835 if (S_ISDIR(sb.st_mode)) {
5836 error = got_error_msg(GOT_ERR_BAD_PATH,
5837 "reverting directories requires -R option");
5838 goto done;
5843 cpa.patch_script_file = patch_script_file;
5844 cpa.action = "revert";
5845 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
5846 pflag ? choose_patch : NULL, &cpa, repo);
5847 done:
5848 if (patch_script_file && fclose(patch_script_file) == EOF &&
5849 error == NULL)
5850 error = got_error_from_errno2("fclose", patch_script_path);
5851 if (repo)
5852 got_repo_close(repo);
5853 if (worktree)
5854 got_worktree_close(worktree);
5855 free(path);
5856 free(cwd);
5857 return error;
5860 __dead static void
5861 usage_commit(void)
5863 fprintf(stderr, "usage: %s commit [-m msg] [path ...]\n",
5864 getprogname());
5865 exit(1);
5868 struct collect_commit_logmsg_arg {
5869 const char *cmdline_log;
5870 const char *editor;
5871 const char *worktree_path;
5872 const char *branch_name;
5873 const char *repo_path;
5874 char *logmsg_path;
5878 static const struct got_error *
5879 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
5880 void *arg)
5882 char *initial_content = NULL;
5883 struct got_pathlist_entry *pe;
5884 const struct got_error *err = NULL;
5885 char *template = NULL;
5886 struct collect_commit_logmsg_arg *a = arg;
5887 int fd;
5888 size_t len;
5890 /* if a message was specified on the command line, just use it */
5891 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
5892 len = strlen(a->cmdline_log) + 1;
5893 *logmsg = malloc(len + 1);
5894 if (*logmsg == NULL)
5895 return got_error_from_errno("malloc");
5896 strlcpy(*logmsg, a->cmdline_log, len);
5897 return NULL;
5900 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
5901 return got_error_from_errno("asprintf");
5903 if (asprintf(&initial_content,
5904 "\n# changes to be committed on branch %s:\n",
5905 a->branch_name) == -1)
5906 return got_error_from_errno("asprintf");
5908 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
5909 if (err)
5910 goto done;
5912 dprintf(fd, initial_content);
5914 TAILQ_FOREACH(pe, commitable_paths, entry) {
5915 struct got_commitable *ct = pe->data;
5916 dprintf(fd, "# %c %s\n",
5917 got_commitable_get_status(ct),
5918 got_commitable_get_path(ct));
5920 close(fd);
5922 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
5923 done:
5924 free(initial_content);
5925 free(template);
5927 /* Editor is done; we can now apply unveil(2) */
5928 if (err == NULL) {
5929 err = apply_unveil(a->repo_path, 0, a->worktree_path);
5930 if (err) {
5931 free(*logmsg);
5932 *logmsg = NULL;
5935 return err;
5938 static const struct got_error *
5939 cmd_commit(int argc, char *argv[])
5941 const struct got_error *error = NULL;
5942 struct got_worktree *worktree = NULL;
5943 struct got_repository *repo = NULL;
5944 char *cwd = NULL, *id_str = NULL;
5945 struct got_object_id *id = NULL;
5946 const char *logmsg = NULL;
5947 struct collect_commit_logmsg_arg cl_arg;
5948 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
5949 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
5950 struct got_pathlist_head paths;
5952 TAILQ_INIT(&paths);
5953 cl_arg.logmsg_path = NULL;
5955 while ((ch = getopt(argc, argv, "m:")) != -1) {
5956 switch (ch) {
5957 case 'm':
5958 logmsg = optarg;
5959 break;
5960 default:
5961 usage_commit();
5962 /* NOTREACHED */
5966 argc -= optind;
5967 argv += optind;
5969 #ifndef PROFILE
5970 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
5971 "unveil", NULL) == -1)
5972 err(1, "pledge");
5973 #endif
5974 cwd = getcwd(NULL, 0);
5975 if (cwd == NULL) {
5976 error = got_error_from_errno("getcwd");
5977 goto done;
5979 error = got_worktree_open(&worktree, cwd);
5980 if (error)
5981 goto done;
5983 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
5984 if (error)
5985 goto done;
5986 if (rebase_in_progress) {
5987 error = got_error(GOT_ERR_REBASING);
5988 goto done;
5991 error = got_worktree_histedit_in_progress(&histedit_in_progress,
5992 worktree);
5993 if (error)
5994 goto done;
5996 error = get_gitconfig_path(&gitconfig_path);
5997 if (error)
5998 goto done;
5999 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6000 gitconfig_path);
6001 if (error != NULL)
6002 goto done;
6004 error = get_author(&author, repo);
6005 if (error)
6006 return error;
6009 * unveil(2) traverses exec(2); if an editor is used we have
6010 * to apply unveil after the log message has been written.
6012 if (logmsg == NULL || strlen(logmsg) == 0)
6013 error = get_editor(&editor);
6014 else
6015 error = apply_unveil(got_repo_get_path(repo), 0,
6016 got_worktree_get_root_path(worktree));
6017 if (error)
6018 goto done;
6020 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6021 if (error)
6022 goto done;
6024 cl_arg.editor = editor;
6025 cl_arg.cmdline_log = logmsg;
6026 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6027 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6028 if (!histedit_in_progress) {
6029 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6030 error = got_error(GOT_ERR_COMMIT_BRANCH);
6031 goto done;
6033 cl_arg.branch_name += 11;
6035 cl_arg.repo_path = got_repo_get_path(repo);
6036 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6037 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
6038 if (error) {
6039 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6040 cl_arg.logmsg_path != NULL)
6041 preserve_logmsg = 1;
6042 goto done;
6045 error = got_object_id_str(&id_str, id);
6046 if (error)
6047 goto done;
6048 printf("Created commit %s\n", id_str);
6049 done:
6050 if (preserve_logmsg) {
6051 fprintf(stderr, "%s: log message preserved in %s\n",
6052 getprogname(), cl_arg.logmsg_path);
6053 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6054 error == NULL)
6055 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6056 free(cl_arg.logmsg_path);
6057 if (repo)
6058 got_repo_close(repo);
6059 if (worktree)
6060 got_worktree_close(worktree);
6061 free(cwd);
6062 free(id_str);
6063 free(gitconfig_path);
6064 free(editor);
6065 free(author);
6066 return error;
6069 __dead static void
6070 usage_cherrypick(void)
6072 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6073 exit(1);
6076 static const struct got_error *
6077 cmd_cherrypick(int argc, char *argv[])
6079 const struct got_error *error = NULL;
6080 struct got_worktree *worktree = NULL;
6081 struct got_repository *repo = NULL;
6082 char *cwd = NULL, *commit_id_str = NULL;
6083 struct got_object_id *commit_id = NULL;
6084 struct got_commit_object *commit = NULL;
6085 struct got_object_qid *pid;
6086 struct got_reference *head_ref = NULL;
6087 int ch, did_something = 0;
6089 while ((ch = getopt(argc, argv, "")) != -1) {
6090 switch (ch) {
6091 default:
6092 usage_cherrypick();
6093 /* NOTREACHED */
6097 argc -= optind;
6098 argv += optind;
6100 #ifndef PROFILE
6101 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6102 "unveil", NULL) == -1)
6103 err(1, "pledge");
6104 #endif
6105 if (argc != 1)
6106 usage_cherrypick();
6108 cwd = getcwd(NULL, 0);
6109 if (cwd == NULL) {
6110 error = got_error_from_errno("getcwd");
6111 goto done;
6113 error = got_worktree_open(&worktree, cwd);
6114 if (error)
6115 goto done;
6117 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6118 NULL);
6119 if (error != NULL)
6120 goto done;
6122 error = apply_unveil(got_repo_get_path(repo), 0,
6123 got_worktree_get_root_path(worktree));
6124 if (error)
6125 goto done;
6127 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6128 GOT_OBJ_TYPE_COMMIT, repo);
6129 if (error != NULL) {
6130 struct got_reference *ref;
6131 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6132 goto done;
6133 error = got_ref_open(&ref, repo, argv[0], 0);
6134 if (error != NULL)
6135 goto done;
6136 error = got_ref_resolve(&commit_id, repo, ref);
6137 got_ref_close(ref);
6138 if (error != NULL)
6139 goto done;
6141 error = got_object_id_str(&commit_id_str, commit_id);
6142 if (error)
6143 goto done;
6145 error = got_ref_open(&head_ref, repo,
6146 got_worktree_get_head_ref_name(worktree), 0);
6147 if (error != NULL)
6148 goto done;
6150 error = check_same_branch(commit_id, head_ref, NULL, repo);
6151 if (error) {
6152 if (error->code != GOT_ERR_ANCESTRY)
6153 goto done;
6154 error = NULL;
6155 } else {
6156 error = got_error(GOT_ERR_SAME_BRANCH);
6157 goto done;
6160 error = got_object_open_as_commit(&commit, repo, commit_id);
6161 if (error)
6162 goto done;
6163 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6164 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
6165 commit_id, repo, update_progress, &did_something, check_cancelled,
6166 NULL);
6167 if (error != NULL)
6168 goto done;
6170 if (did_something)
6171 printf("Merged commit %s\n", commit_id_str);
6172 done:
6173 if (commit)
6174 got_object_commit_close(commit);
6175 free(commit_id_str);
6176 if (head_ref)
6177 got_ref_close(head_ref);
6178 if (worktree)
6179 got_worktree_close(worktree);
6180 if (repo)
6181 got_repo_close(repo);
6182 return error;
6185 __dead static void
6186 usage_backout(void)
6188 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
6189 exit(1);
6192 static const struct got_error *
6193 cmd_backout(int argc, char *argv[])
6195 const struct got_error *error = NULL;
6196 struct got_worktree *worktree = NULL;
6197 struct got_repository *repo = NULL;
6198 char *cwd = NULL, *commit_id_str = NULL;
6199 struct got_object_id *commit_id = NULL;
6200 struct got_commit_object *commit = NULL;
6201 struct got_object_qid *pid;
6202 struct got_reference *head_ref = NULL;
6203 int ch, did_something = 0;
6205 while ((ch = getopt(argc, argv, "")) != -1) {
6206 switch (ch) {
6207 default:
6208 usage_backout();
6209 /* NOTREACHED */
6213 argc -= optind;
6214 argv += optind;
6216 #ifndef PROFILE
6217 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6218 "unveil", NULL) == -1)
6219 err(1, "pledge");
6220 #endif
6221 if (argc != 1)
6222 usage_backout();
6224 cwd = getcwd(NULL, 0);
6225 if (cwd == NULL) {
6226 error = got_error_from_errno("getcwd");
6227 goto done;
6229 error = got_worktree_open(&worktree, cwd);
6230 if (error)
6231 goto done;
6233 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6234 NULL);
6235 if (error != NULL)
6236 goto done;
6238 error = apply_unveil(got_repo_get_path(repo), 0,
6239 got_worktree_get_root_path(worktree));
6240 if (error)
6241 goto done;
6243 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6244 GOT_OBJ_TYPE_COMMIT, repo);
6245 if (error != NULL) {
6246 struct got_reference *ref;
6247 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6248 goto done;
6249 error = got_ref_open(&ref, repo, argv[0], 0);
6250 if (error != NULL)
6251 goto done;
6252 error = got_ref_resolve(&commit_id, repo, ref);
6253 got_ref_close(ref);
6254 if (error != NULL)
6255 goto done;
6257 error = got_object_id_str(&commit_id_str, commit_id);
6258 if (error)
6259 goto done;
6261 error = got_ref_open(&head_ref, repo,
6262 got_worktree_get_head_ref_name(worktree), 0);
6263 if (error != NULL)
6264 goto done;
6266 error = check_same_branch(commit_id, head_ref, NULL, repo);
6267 if (error)
6268 goto done;
6270 error = got_object_open_as_commit(&commit, repo, commit_id);
6271 if (error)
6272 goto done;
6273 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6274 if (pid == NULL) {
6275 error = got_error(GOT_ERR_ROOT_COMMIT);
6276 goto done;
6279 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
6280 update_progress, &did_something, check_cancelled, NULL);
6281 if (error != NULL)
6282 goto done;
6284 if (did_something)
6285 printf("Backed out commit %s\n", commit_id_str);
6286 done:
6287 if (commit)
6288 got_object_commit_close(commit);
6289 free(commit_id_str);
6290 if (head_ref)
6291 got_ref_close(head_ref);
6292 if (worktree)
6293 got_worktree_close(worktree);
6294 if (repo)
6295 got_repo_close(repo);
6296 return error;
6299 __dead static void
6300 usage_rebase(void)
6302 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
6303 getprogname());
6304 exit(1);
6307 void
6308 trim_logmsg(char *logmsg, int limit)
6310 char *nl;
6311 size_t len;
6313 len = strlen(logmsg);
6314 if (len > limit)
6315 len = limit;
6316 logmsg[len] = '\0';
6317 nl = strchr(logmsg, '\n');
6318 if (nl)
6319 *nl = '\0';
6322 static const struct got_error *
6323 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
6325 const struct got_error *err;
6326 char *logmsg0 = NULL;
6327 const char *s;
6329 err = got_object_commit_get_logmsg(&logmsg0, commit);
6330 if (err)
6331 return err;
6333 s = logmsg0;
6334 while (isspace((unsigned char)s[0]))
6335 s++;
6337 *logmsg = strdup(s);
6338 if (*logmsg == NULL) {
6339 err = got_error_from_errno("strdup");
6340 goto done;
6343 trim_logmsg(*logmsg, limit);
6344 done:
6345 free(logmsg0);
6346 return err;
6349 static const struct got_error *
6350 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
6352 const struct got_error *err;
6353 struct got_commit_object *commit = NULL;
6354 char *id_str = NULL, *logmsg = NULL;
6356 err = got_object_open_as_commit(&commit, repo, id);
6357 if (err)
6358 return err;
6360 err = got_object_id_str(&id_str, id);
6361 if (err)
6362 goto done;
6364 id_str[12] = '\0';
6366 err = get_short_logmsg(&logmsg, 42, commit);
6367 if (err)
6368 goto done;
6370 printf("%s -> merge conflict: %s\n", id_str, logmsg);
6371 done:
6372 free(id_str);
6373 got_object_commit_close(commit);
6374 free(logmsg);
6375 return err;
6378 static const struct got_error *
6379 show_rebase_progress(struct got_commit_object *commit,
6380 struct got_object_id *old_id, struct got_object_id *new_id)
6382 const struct got_error *err;
6383 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
6385 err = got_object_id_str(&old_id_str, old_id);
6386 if (err)
6387 goto done;
6389 if (new_id) {
6390 err = got_object_id_str(&new_id_str, new_id);
6391 if (err)
6392 goto done;
6395 old_id_str[12] = '\0';
6396 if (new_id_str)
6397 new_id_str[12] = '\0';
6399 err = get_short_logmsg(&logmsg, 42, commit);
6400 if (err)
6401 goto done;
6403 printf("%s -> %s: %s\n", old_id_str,
6404 new_id_str ? new_id_str : "no-op change", logmsg);
6405 done:
6406 free(old_id_str);
6407 free(new_id_str);
6408 free(logmsg);
6409 return err;
6412 static const struct got_error *
6413 rebase_progress(void *arg, unsigned char status, const char *path)
6415 unsigned char *rebase_status = arg;
6417 while (path[0] == '/')
6418 path++;
6419 printf("%c %s\n", status, path);
6421 if (*rebase_status == GOT_STATUS_CONFLICT)
6422 return NULL;
6423 if (status == GOT_STATUS_CONFLICT || status == GOT_STATUS_MERGE)
6424 *rebase_status = status;
6425 return NULL;
6428 static const struct got_error *
6429 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
6430 struct got_reference *branch, struct got_reference *new_base_branch,
6431 struct got_reference *tmp_branch, struct got_repository *repo)
6433 printf("Switching work tree to %s\n", got_ref_get_name(branch));
6434 return got_worktree_rebase_complete(worktree, fileindex,
6435 new_base_branch, tmp_branch, branch, repo);
6438 static const struct got_error *
6439 rebase_commit(struct got_pathlist_head *merged_paths,
6440 struct got_worktree *worktree, struct got_fileindex *fileindex,
6441 struct got_reference *tmp_branch,
6442 struct got_object_id *commit_id, struct got_repository *repo)
6444 const struct got_error *error;
6445 struct got_commit_object *commit;
6446 struct got_object_id *new_commit_id;
6448 error = got_object_open_as_commit(&commit, repo, commit_id);
6449 if (error)
6450 return error;
6452 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
6453 worktree, fileindex, tmp_branch, commit, commit_id, repo);
6454 if (error) {
6455 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
6456 goto done;
6457 error = show_rebase_progress(commit, commit_id, NULL);
6458 } else {
6459 error = show_rebase_progress(commit, commit_id, new_commit_id);
6460 free(new_commit_id);
6462 done:
6463 got_object_commit_close(commit);
6464 return error;
6467 struct check_path_prefix_arg {
6468 const char *path_prefix;
6469 size_t len;
6470 int errcode;
6473 static const struct got_error *
6474 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
6475 struct got_blob_object *blob2, struct got_object_id *id1,
6476 struct got_object_id *id2, const char *path1, const char *path2,
6477 mode_t mode1, mode_t mode2, struct got_repository *repo)
6479 struct check_path_prefix_arg *a = arg;
6481 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
6482 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
6483 return got_error(a->errcode);
6485 return NULL;
6488 static const struct got_error *
6489 check_path_prefix(struct got_object_id *parent_id,
6490 struct got_object_id *commit_id, const char *path_prefix,
6491 int errcode, struct got_repository *repo)
6493 const struct got_error *err;
6494 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
6495 struct got_commit_object *commit = NULL, *parent_commit = NULL;
6496 struct check_path_prefix_arg cpp_arg;
6498 if (got_path_is_root_dir(path_prefix))
6499 return NULL;
6501 err = got_object_open_as_commit(&commit, repo, commit_id);
6502 if (err)
6503 goto done;
6505 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
6506 if (err)
6507 goto done;
6509 err = got_object_open_as_tree(&tree1, repo,
6510 got_object_commit_get_tree_id(parent_commit));
6511 if (err)
6512 goto done;
6514 err = got_object_open_as_tree(&tree2, repo,
6515 got_object_commit_get_tree_id(commit));
6516 if (err)
6517 goto done;
6519 cpp_arg.path_prefix = path_prefix;
6520 while (cpp_arg.path_prefix[0] == '/')
6521 cpp_arg.path_prefix++;
6522 cpp_arg.len = strlen(cpp_arg.path_prefix);
6523 cpp_arg.errcode = errcode;
6524 err = got_diff_tree(tree1, tree2, "", "", repo,
6525 check_path_prefix_in_diff, &cpp_arg, 0);
6526 done:
6527 if (tree1)
6528 got_object_tree_close(tree1);
6529 if (tree2)
6530 got_object_tree_close(tree2);
6531 if (commit)
6532 got_object_commit_close(commit);
6533 if (parent_commit)
6534 got_object_commit_close(parent_commit);
6535 return err;
6538 static const struct got_error *
6539 collect_commits(struct got_object_id_queue *commits,
6540 struct got_object_id *initial_commit_id,
6541 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
6542 const char *path_prefix, int path_prefix_errcode,
6543 struct got_repository *repo)
6545 const struct got_error *err = NULL;
6546 struct got_commit_graph *graph = NULL;
6547 struct got_object_id *parent_id = NULL;
6548 struct got_object_qid *qid;
6549 struct got_object_id *commit_id = initial_commit_id;
6551 err = got_commit_graph_open(&graph, "/", 1);
6552 if (err)
6553 return err;
6555 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
6556 check_cancelled, NULL);
6557 if (err)
6558 goto done;
6559 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
6560 err = got_commit_graph_iter_next(&parent_id, graph, repo,
6561 check_cancelled, NULL);
6562 if (err) {
6563 if (err->code == GOT_ERR_ITER_COMPLETED) {
6564 err = got_error_msg(GOT_ERR_ANCESTRY,
6565 "ran out of commits to rebase before "
6566 "youngest common ancestor commit has "
6567 "been reached?!?");
6569 goto done;
6570 } else {
6571 err = check_path_prefix(parent_id, commit_id,
6572 path_prefix, path_prefix_errcode, repo);
6573 if (err)
6574 goto done;
6576 err = got_object_qid_alloc(&qid, commit_id);
6577 if (err)
6578 goto done;
6579 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
6580 commit_id = parent_id;
6583 done:
6584 got_commit_graph_close(graph);
6585 return err;
6588 static const struct got_error *
6589 cmd_rebase(int argc, char *argv[])
6591 const struct got_error *error = NULL;
6592 struct got_worktree *worktree = NULL;
6593 struct got_repository *repo = NULL;
6594 struct got_fileindex *fileindex = NULL;
6595 char *cwd = NULL;
6596 struct got_reference *branch = NULL;
6597 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
6598 struct got_object_id *commit_id = NULL, *parent_id = NULL;
6599 struct got_object_id *resume_commit_id = NULL;
6600 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
6601 struct got_commit_object *commit = NULL;
6602 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
6603 int histedit_in_progress = 0;
6604 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
6605 struct got_object_id_queue commits;
6606 struct got_pathlist_head merged_paths;
6607 const struct got_object_id_queue *parent_ids;
6608 struct got_object_qid *qid, *pid;
6610 SIMPLEQ_INIT(&commits);
6611 TAILQ_INIT(&merged_paths);
6613 while ((ch = getopt(argc, argv, "ac")) != -1) {
6614 switch (ch) {
6615 case 'a':
6616 abort_rebase = 1;
6617 break;
6618 case 'c':
6619 continue_rebase = 1;
6620 break;
6621 default:
6622 usage_rebase();
6623 /* NOTREACHED */
6627 argc -= optind;
6628 argv += optind;
6630 #ifndef PROFILE
6631 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6632 "unveil", NULL) == -1)
6633 err(1, "pledge");
6634 #endif
6635 if (abort_rebase && continue_rebase)
6636 usage_rebase();
6637 else if (abort_rebase || continue_rebase) {
6638 if (argc != 0)
6639 usage_rebase();
6640 } else if (argc != 1)
6641 usage_rebase();
6643 cwd = getcwd(NULL, 0);
6644 if (cwd == NULL) {
6645 error = got_error_from_errno("getcwd");
6646 goto done;
6648 error = got_worktree_open(&worktree, cwd);
6649 if (error)
6650 goto done;
6652 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6653 NULL);
6654 if (error != NULL)
6655 goto done;
6657 error = apply_unveil(got_repo_get_path(repo), 0,
6658 got_worktree_get_root_path(worktree));
6659 if (error)
6660 goto done;
6662 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6663 worktree);
6664 if (error)
6665 goto done;
6666 if (histedit_in_progress) {
6667 error = got_error(GOT_ERR_HISTEDIT_BUSY);
6668 goto done;
6671 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6672 if (error)
6673 goto done;
6675 if (abort_rebase) {
6676 int did_something;
6677 if (!rebase_in_progress) {
6678 error = got_error(GOT_ERR_NOT_REBASING);
6679 goto done;
6681 error = got_worktree_rebase_continue(&resume_commit_id,
6682 &new_base_branch, &tmp_branch, &branch, &fileindex,
6683 worktree, repo);
6684 if (error)
6685 goto done;
6686 printf("Switching work tree to %s\n",
6687 got_ref_get_symref_target(new_base_branch));
6688 error = got_worktree_rebase_abort(worktree, fileindex, repo,
6689 new_base_branch, update_progress, &did_something);
6690 if (error)
6691 goto done;
6692 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
6693 goto done; /* nothing else to do */
6696 if (continue_rebase) {
6697 if (!rebase_in_progress) {
6698 error = got_error(GOT_ERR_NOT_REBASING);
6699 goto done;
6701 error = got_worktree_rebase_continue(&resume_commit_id,
6702 &new_base_branch, &tmp_branch, &branch, &fileindex,
6703 worktree, repo);
6704 if (error)
6705 goto done;
6707 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
6708 resume_commit_id, repo);
6709 if (error)
6710 goto done;
6712 yca_id = got_object_id_dup(resume_commit_id);
6713 if (yca_id == NULL) {
6714 error = got_error_from_errno("got_object_id_dup");
6715 goto done;
6717 } else {
6718 error = got_ref_open(&branch, repo, argv[0], 0);
6719 if (error != NULL)
6720 goto done;
6723 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
6724 if (error)
6725 goto done;
6727 if (!continue_rebase) {
6728 struct got_object_id *base_commit_id;
6730 base_commit_id = got_worktree_get_base_commit_id(worktree);
6731 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
6732 base_commit_id, branch_head_commit_id, repo,
6733 check_cancelled, NULL);
6734 if (error)
6735 goto done;
6736 if (yca_id == NULL) {
6737 error = got_error_msg(GOT_ERR_ANCESTRY,
6738 "specified branch shares no common ancestry "
6739 "with work tree's branch");
6740 goto done;
6743 error = check_same_branch(base_commit_id, branch, yca_id, repo);
6744 if (error) {
6745 if (error->code != GOT_ERR_ANCESTRY)
6746 goto done;
6747 error = NULL;
6748 } else {
6749 error = got_error_msg(GOT_ERR_SAME_BRANCH,
6750 "specified branch resolves to a commit which "
6751 "is already contained in work tree's branch");
6752 goto done;
6754 error = got_worktree_rebase_prepare(&new_base_branch,
6755 &tmp_branch, &fileindex, worktree, branch, repo);
6756 if (error)
6757 goto done;
6760 commit_id = branch_head_commit_id;
6761 error = got_object_open_as_commit(&commit, repo, commit_id);
6762 if (error)
6763 goto done;
6765 parent_ids = got_object_commit_get_parent_ids(commit);
6766 pid = SIMPLEQ_FIRST(parent_ids);
6767 if (pid == NULL) {
6768 if (!continue_rebase) {
6769 int did_something;
6770 error = got_worktree_rebase_abort(worktree, fileindex,
6771 repo, new_base_branch, update_progress,
6772 &did_something);
6773 if (error)
6774 goto done;
6775 printf("Rebase of %s aborted\n",
6776 got_ref_get_name(branch));
6778 error = got_error(GOT_ERR_EMPTY_REBASE);
6779 goto done;
6781 error = collect_commits(&commits, commit_id, pid->id,
6782 yca_id, got_worktree_get_path_prefix(worktree),
6783 GOT_ERR_REBASE_PATH, repo);
6784 got_object_commit_close(commit);
6785 commit = NULL;
6786 if (error)
6787 goto done;
6789 if (SIMPLEQ_EMPTY(&commits)) {
6790 if (continue_rebase) {
6791 error = rebase_complete(worktree, fileindex,
6792 branch, new_base_branch, tmp_branch, repo);
6793 goto done;
6794 } else {
6795 /* Fast-forward the reference of the branch. */
6796 struct got_object_id *new_head_commit_id;
6797 char *id_str;
6798 error = got_ref_resolve(&new_head_commit_id, repo,
6799 new_base_branch);
6800 if (error)
6801 goto done;
6802 error = got_object_id_str(&id_str, new_head_commit_id);
6803 printf("Forwarding %s to commit %s\n",
6804 got_ref_get_name(branch), id_str);
6805 free(id_str);
6806 error = got_ref_change_ref(branch,
6807 new_head_commit_id);
6808 if (error)
6809 goto done;
6813 pid = NULL;
6814 SIMPLEQ_FOREACH(qid, &commits, entry) {
6815 commit_id = qid->id;
6816 parent_id = pid ? pid->id : yca_id;
6817 pid = qid;
6819 error = got_worktree_rebase_merge_files(&merged_paths,
6820 worktree, fileindex, parent_id, commit_id, repo,
6821 rebase_progress, &rebase_status, check_cancelled, NULL);
6822 if (error)
6823 goto done;
6825 if (rebase_status == GOT_STATUS_CONFLICT) {
6826 error = show_rebase_merge_conflict(qid->id, repo);
6827 if (error)
6828 goto done;
6829 got_worktree_rebase_pathlist_free(&merged_paths);
6830 break;
6833 error = rebase_commit(&merged_paths, worktree, fileindex,
6834 tmp_branch, commit_id, repo);
6835 got_worktree_rebase_pathlist_free(&merged_paths);
6836 if (error)
6837 goto done;
6840 if (rebase_status == GOT_STATUS_CONFLICT) {
6841 error = got_worktree_rebase_postpone(worktree, fileindex);
6842 if (error)
6843 goto done;
6844 error = got_error_msg(GOT_ERR_CONFLICTS,
6845 "conflicts must be resolved before rebasing can continue");
6846 } else
6847 error = rebase_complete(worktree, fileindex, branch,
6848 new_base_branch, tmp_branch, repo);
6849 done:
6850 got_object_id_queue_free(&commits);
6851 free(branch_head_commit_id);
6852 free(resume_commit_id);
6853 free(yca_id);
6854 if (commit)
6855 got_object_commit_close(commit);
6856 if (branch)
6857 got_ref_close(branch);
6858 if (new_base_branch)
6859 got_ref_close(new_base_branch);
6860 if (tmp_branch)
6861 got_ref_close(tmp_branch);
6862 if (worktree)
6863 got_worktree_close(worktree);
6864 if (repo)
6865 got_repo_close(repo);
6866 return error;
6869 __dead static void
6870 usage_histedit(void)
6872 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
6873 getprogname());
6874 exit(1);
6877 #define GOT_HISTEDIT_PICK 'p'
6878 #define GOT_HISTEDIT_EDIT 'e'
6879 #define GOT_HISTEDIT_FOLD 'f'
6880 #define GOT_HISTEDIT_DROP 'd'
6881 #define GOT_HISTEDIT_MESG 'm'
6883 static struct got_histedit_cmd {
6884 unsigned char code;
6885 const char *name;
6886 const char *desc;
6887 } got_histedit_cmds[] = {
6888 { GOT_HISTEDIT_PICK, "pick", "use commit" },
6889 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
6890 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
6891 "be used" },
6892 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
6893 { GOT_HISTEDIT_MESG, "mesg",
6894 "single-line log message for commit above (open editor if empty)" },
6897 struct got_histedit_list_entry {
6898 TAILQ_ENTRY(got_histedit_list_entry) entry;
6899 struct got_object_id *commit_id;
6900 const struct got_histedit_cmd *cmd;
6901 char *logmsg;
6903 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
6905 static const struct got_error *
6906 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
6907 FILE *f, struct got_repository *repo)
6909 const struct got_error *err = NULL;
6910 char *logmsg = NULL, *id_str = NULL;
6911 struct got_commit_object *commit = NULL;
6912 int n;
6914 err = got_object_open_as_commit(&commit, repo, commit_id);
6915 if (err)
6916 goto done;
6918 err = get_short_logmsg(&logmsg, 34, commit);
6919 if (err)
6920 goto done;
6922 err = got_object_id_str(&id_str, commit_id);
6923 if (err)
6924 goto done;
6926 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
6927 if (n < 0)
6928 err = got_ferror(f, GOT_ERR_IO);
6929 done:
6930 if (commit)
6931 got_object_commit_close(commit);
6932 free(id_str);
6933 free(logmsg);
6934 return err;
6937 static const struct got_error *
6938 histedit_write_commit_list(struct got_object_id_queue *commits,
6939 FILE *f, int edit_logmsg_only, struct got_repository *repo)
6941 const struct got_error *err = NULL;
6942 struct got_object_qid *qid;
6944 if (SIMPLEQ_EMPTY(commits))
6945 return got_error(GOT_ERR_EMPTY_HISTEDIT);
6947 SIMPLEQ_FOREACH(qid, commits, entry) {
6948 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
6949 f, repo);
6950 if (err)
6951 break;
6952 if (edit_logmsg_only) {
6953 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
6954 if (n < 0) {
6955 err = got_ferror(f, GOT_ERR_IO);
6956 break;
6961 return err;
6964 static const struct got_error *
6965 write_cmd_list(FILE *f, const char *branch_name,
6966 struct got_object_id_queue *commits)
6968 const struct got_error *err = NULL;
6969 int n, i;
6970 char *id_str;
6971 struct got_object_qid *qid;
6973 qid = SIMPLEQ_FIRST(commits);
6974 err = got_object_id_str(&id_str, qid->id);
6975 if (err)
6976 return err;
6978 n = fprintf(f,
6979 "# Editing the history of branch '%s' starting at\n"
6980 "# commit %s\n"
6981 "# Commits will be processed in order from top to "
6982 "bottom of this file.\n", branch_name, id_str);
6983 if (n < 0) {
6984 err = got_ferror(f, GOT_ERR_IO);
6985 goto done;
6988 n = fprintf(f, "# Available histedit commands:\n");
6989 if (n < 0) {
6990 err = got_ferror(f, GOT_ERR_IO);
6991 goto done;
6994 for (i = 0; i < nitems(got_histedit_cmds); i++) {
6995 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
6996 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
6997 cmd->desc);
6998 if (n < 0) {
6999 err = got_ferror(f, GOT_ERR_IO);
7000 break;
7003 done:
7004 free(id_str);
7005 return err;
7008 static const struct got_error *
7009 histedit_syntax_error(int lineno)
7011 static char msg[42];
7012 int ret;
7014 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7015 lineno);
7016 if (ret == -1 || ret >= sizeof(msg))
7017 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7019 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7022 static const struct got_error *
7023 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7024 char *logmsg, struct got_repository *repo)
7026 const struct got_error *err;
7027 struct got_commit_object *folded_commit = NULL;
7028 char *id_str, *folded_logmsg = NULL;
7030 err = got_object_id_str(&id_str, hle->commit_id);
7031 if (err)
7032 return err;
7034 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7035 if (err)
7036 goto done;
7038 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7039 if (err)
7040 goto done;
7041 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7042 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7043 folded_logmsg) == -1) {
7044 err = got_error_from_errno("asprintf");
7046 done:
7047 if (folded_commit)
7048 got_object_commit_close(folded_commit);
7049 free(id_str);
7050 free(folded_logmsg);
7051 return err;
7054 static struct got_histedit_list_entry *
7055 get_folded_commits(struct got_histedit_list_entry *hle)
7057 struct got_histedit_list_entry *prev, *folded = NULL;
7059 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7060 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7061 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7062 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7063 folded = prev;
7064 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7067 return folded;
7070 static const struct got_error *
7071 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7072 struct got_repository *repo)
7074 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7075 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7076 const struct got_error *err = NULL;
7077 struct got_commit_object *commit = NULL;
7078 int fd;
7079 struct got_histedit_list_entry *folded = NULL;
7081 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7082 if (err)
7083 return err;
7085 folded = get_folded_commits(hle);
7086 if (folded) {
7087 while (folded != hle) {
7088 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7089 folded = TAILQ_NEXT(folded, entry);
7090 continue;
7092 err = append_folded_commit_msg(&new_msg, folded,
7093 logmsg, repo);
7094 if (err)
7095 goto done;
7096 free(logmsg);
7097 logmsg = new_msg;
7098 folded = TAILQ_NEXT(folded, entry);
7102 err = got_object_id_str(&id_str, hle->commit_id);
7103 if (err)
7104 goto done;
7105 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7106 if (err)
7107 goto done;
7108 if (asprintf(&new_msg,
7109 "%s\n# original log message of commit %s: %s",
7110 logmsg ? logmsg : "", id_str, orig_logmsg) == -1) {
7111 err = got_error_from_errno("asprintf");
7112 goto done;
7114 free(logmsg);
7115 logmsg = new_msg;
7117 err = got_object_id_str(&id_str, hle->commit_id);
7118 if (err)
7119 goto done;
7121 err = got_opentemp_named_fd(&logmsg_path, &fd,
7122 GOT_TMPDIR_STR "/got-logmsg");
7123 if (err)
7124 goto done;
7126 dprintf(fd, logmsg);
7127 close(fd);
7129 err = get_editor(&editor);
7130 if (err)
7131 goto done;
7133 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
7134 if (err) {
7135 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
7136 goto done;
7137 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
7139 done:
7140 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
7141 err = got_error_from_errno2("unlink", logmsg_path);
7142 free(logmsg_path);
7143 free(logmsg);
7144 free(orig_logmsg);
7145 free(editor);
7146 if (commit)
7147 got_object_commit_close(commit);
7148 return err;
7151 static const struct got_error *
7152 histedit_parse_list(struct got_histedit_list *histedit_cmds,
7153 FILE *f, struct got_repository *repo)
7155 const struct got_error *err = NULL;
7156 char *line = NULL, *p, *end;
7157 size_t size;
7158 ssize_t len;
7159 int lineno = 0, i;
7160 const struct got_histedit_cmd *cmd;
7161 struct got_object_id *commit_id = NULL;
7162 struct got_histedit_list_entry *hle = NULL;
7164 for (;;) {
7165 len = getline(&line, &size, f);
7166 if (len == -1) {
7167 const struct got_error *getline_err;
7168 if (feof(f))
7169 break;
7170 getline_err = got_error_from_errno("getline");
7171 err = got_ferror(f, getline_err->code);
7172 break;
7174 lineno++;
7175 p = line;
7176 while (isspace((unsigned char)p[0]))
7177 p++;
7178 if (p[0] == '#' || p[0] == '\0') {
7179 free(line);
7180 line = NULL;
7181 continue;
7183 cmd = NULL;
7184 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7185 cmd = &got_histedit_cmds[i];
7186 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
7187 isspace((unsigned char)p[strlen(cmd->name)])) {
7188 p += strlen(cmd->name);
7189 break;
7191 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
7192 p++;
7193 break;
7196 if (i == nitems(got_histedit_cmds)) {
7197 err = histedit_syntax_error(lineno);
7198 break;
7200 while (isspace((unsigned char)p[0]))
7201 p++;
7202 if (cmd->code == GOT_HISTEDIT_MESG) {
7203 if (hle == NULL || hle->logmsg != NULL) {
7204 err = got_error(GOT_ERR_HISTEDIT_CMD);
7205 break;
7207 if (p[0] == '\0') {
7208 err = histedit_edit_logmsg(hle, repo);
7209 if (err)
7210 break;
7211 } else {
7212 hle->logmsg = strdup(p);
7213 if (hle->logmsg == NULL) {
7214 err = got_error_from_errno("strdup");
7215 break;
7218 free(line);
7219 line = NULL;
7220 continue;
7221 } else {
7222 end = p;
7223 while (end[0] && !isspace((unsigned char)end[0]))
7224 end++;
7225 *end = '\0';
7227 err = got_object_resolve_id_str(&commit_id, repo, p);
7228 if (err) {
7229 /* override error code */
7230 err = histedit_syntax_error(lineno);
7231 break;
7234 hle = malloc(sizeof(*hle));
7235 if (hle == NULL) {
7236 err = got_error_from_errno("malloc");
7237 break;
7239 hle->cmd = cmd;
7240 hle->commit_id = commit_id;
7241 hle->logmsg = NULL;
7242 commit_id = NULL;
7243 free(line);
7244 line = NULL;
7245 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
7248 free(line);
7249 free(commit_id);
7250 return err;
7253 static const struct got_error *
7254 histedit_check_script(struct got_histedit_list *histedit_cmds,
7255 struct got_object_id_queue *commits, struct got_repository *repo)
7257 const struct got_error *err = NULL;
7258 struct got_object_qid *qid;
7259 struct got_histedit_list_entry *hle;
7260 static char msg[92];
7261 char *id_str;
7263 if (TAILQ_EMPTY(histedit_cmds))
7264 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
7265 "histedit script contains no commands");
7266 if (SIMPLEQ_EMPTY(commits))
7267 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7269 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7270 struct got_histedit_list_entry *hle2;
7271 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
7272 if (hle == hle2)
7273 continue;
7274 if (got_object_id_cmp(hle->commit_id,
7275 hle2->commit_id) != 0)
7276 continue;
7277 err = got_object_id_str(&id_str, hle->commit_id);
7278 if (err)
7279 return err;
7280 snprintf(msg, sizeof(msg), "commit %s is listed "
7281 "more than once in histedit script", id_str);
7282 free(id_str);
7283 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7287 SIMPLEQ_FOREACH(qid, commits, entry) {
7288 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7289 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
7290 break;
7292 if (hle == NULL) {
7293 err = got_object_id_str(&id_str, qid->id);
7294 if (err)
7295 return err;
7296 snprintf(msg, sizeof(msg),
7297 "commit %s missing from histedit script", id_str);
7298 free(id_str);
7299 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7303 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
7304 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
7305 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
7306 "last commit in histedit script cannot be folded");
7308 return NULL;
7311 static const struct got_error *
7312 histedit_run_editor(struct got_histedit_list *histedit_cmds,
7313 const char *path, struct got_object_id_queue *commits,
7314 struct got_repository *repo)
7316 const struct got_error *err = NULL;
7317 char *editor;
7318 FILE *f = NULL;
7320 err = get_editor(&editor);
7321 if (err)
7322 return err;
7324 if (spawn_editor(editor, path) == -1) {
7325 err = got_error_from_errno("failed spawning editor");
7326 goto done;
7329 f = fopen(path, "r");
7330 if (f == NULL) {
7331 err = got_error_from_errno("fopen");
7332 goto done;
7334 err = histedit_parse_list(histedit_cmds, f, repo);
7335 if (err)
7336 goto done;
7338 err = histedit_check_script(histedit_cmds, commits, repo);
7339 done:
7340 if (f && fclose(f) != 0 && err == NULL)
7341 err = got_error_from_errno("fclose");
7342 free(editor);
7343 return err;
7346 static const struct got_error *
7347 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
7348 struct got_object_id_queue *, const char *, const char *,
7349 struct got_repository *);
7351 static const struct got_error *
7352 histedit_edit_script(struct got_histedit_list *histedit_cmds,
7353 struct got_object_id_queue *commits, const char *branch_name,
7354 int edit_logmsg_only, struct got_repository *repo)
7356 const struct got_error *err;
7357 FILE *f = NULL;
7358 char *path = NULL;
7360 err = got_opentemp_named(&path, &f, "got-histedit");
7361 if (err)
7362 return err;
7364 err = write_cmd_list(f, branch_name, commits);
7365 if (err)
7366 goto done;
7368 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
7369 if (err)
7370 goto done;
7372 if (edit_logmsg_only) {
7373 rewind(f);
7374 err = histedit_parse_list(histedit_cmds, f, repo);
7375 } else {
7376 if (fclose(f) != 0) {
7377 err = got_error_from_errno("fclose");
7378 goto done;
7380 f = NULL;
7381 err = histedit_run_editor(histedit_cmds, path, commits, repo);
7382 if (err) {
7383 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7384 err->code != GOT_ERR_HISTEDIT_CMD)
7385 goto done;
7386 err = histedit_edit_list_retry(histedit_cmds, err,
7387 commits, path, branch_name, repo);
7390 done:
7391 if (f && fclose(f) != 0 && err == NULL)
7392 err = got_error_from_errno("fclose");
7393 if (path && unlink(path) != 0 && err == NULL)
7394 err = got_error_from_errno2("unlink", path);
7395 free(path);
7396 return err;
7399 static const struct got_error *
7400 histedit_save_list(struct got_histedit_list *histedit_cmds,
7401 struct got_worktree *worktree, struct got_repository *repo)
7403 const struct got_error *err = NULL;
7404 char *path = NULL;
7405 FILE *f = NULL;
7406 struct got_histedit_list_entry *hle;
7407 struct got_commit_object *commit = NULL;
7409 err = got_worktree_get_histedit_script_path(&path, worktree);
7410 if (err)
7411 return err;
7413 f = fopen(path, "w");
7414 if (f == NULL) {
7415 err = got_error_from_errno2("fopen", path);
7416 goto done;
7418 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7419 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
7420 repo);
7421 if (err)
7422 break;
7424 if (hle->logmsg) {
7425 int n = fprintf(f, "%c %s\n",
7426 GOT_HISTEDIT_MESG, hle->logmsg);
7427 if (n < 0) {
7428 err = got_ferror(f, GOT_ERR_IO);
7429 break;
7433 done:
7434 if (f && fclose(f) != 0 && err == NULL)
7435 err = got_error_from_errno("fclose");
7436 free(path);
7437 if (commit)
7438 got_object_commit_close(commit);
7439 return err;
7442 void
7443 histedit_free_list(struct got_histedit_list *histedit_cmds)
7445 struct got_histedit_list_entry *hle;
7447 while ((hle = TAILQ_FIRST(histedit_cmds))) {
7448 TAILQ_REMOVE(histedit_cmds, hle, entry);
7449 free(hle);
7453 static const struct got_error *
7454 histedit_load_list(struct got_histedit_list *histedit_cmds,
7455 const char *path, struct got_repository *repo)
7457 const struct got_error *err = NULL;
7458 FILE *f = NULL;
7460 f = fopen(path, "r");
7461 if (f == NULL) {
7462 err = got_error_from_errno2("fopen", path);
7463 goto done;
7466 err = histedit_parse_list(histedit_cmds, f, repo);
7467 done:
7468 if (f && fclose(f) != 0 && err == NULL)
7469 err = got_error_from_errno("fclose");
7470 return err;
7473 static const struct got_error *
7474 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
7475 const struct got_error *edit_err, struct got_object_id_queue *commits,
7476 const char *path, const char *branch_name, struct got_repository *repo)
7478 const struct got_error *err = NULL, *prev_err = edit_err;
7479 int resp = ' ';
7481 while (resp != 'c' && resp != 'r' && resp != 'a') {
7482 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
7483 "or (a)bort: ", getprogname(), prev_err->msg);
7484 resp = getchar();
7485 if (resp == '\n')
7486 resp = getchar();
7487 if (resp == 'c') {
7488 histedit_free_list(histedit_cmds);
7489 err = histedit_run_editor(histedit_cmds, path, commits,
7490 repo);
7491 if (err) {
7492 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7493 err->code != GOT_ERR_HISTEDIT_CMD)
7494 break;
7495 prev_err = err;
7496 resp = ' ';
7497 continue;
7499 break;
7500 } else if (resp == 'r') {
7501 histedit_free_list(histedit_cmds);
7502 err = histedit_edit_script(histedit_cmds,
7503 commits, branch_name, 0, repo);
7504 if (err) {
7505 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7506 err->code != GOT_ERR_HISTEDIT_CMD)
7507 break;
7508 prev_err = err;
7509 resp = ' ';
7510 continue;
7512 break;
7513 } else if (resp == 'a') {
7514 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
7515 break;
7516 } else
7517 printf("invalid response '%c'\n", resp);
7520 return err;
7523 static const struct got_error *
7524 histedit_complete(struct got_worktree *worktree,
7525 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
7526 struct got_reference *branch, struct got_repository *repo)
7528 printf("Switching work tree to %s\n",
7529 got_ref_get_symref_target(branch));
7530 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
7531 branch, repo);
7534 static const struct got_error *
7535 show_histedit_progress(struct got_commit_object *commit,
7536 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
7538 const struct got_error *err;
7539 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7541 err = got_object_id_str(&old_id_str, hle->commit_id);
7542 if (err)
7543 goto done;
7545 if (new_id) {
7546 err = got_object_id_str(&new_id_str, new_id);
7547 if (err)
7548 goto done;
7551 old_id_str[12] = '\0';
7552 if (new_id_str)
7553 new_id_str[12] = '\0';
7555 if (hle->logmsg) {
7556 logmsg = strdup(hle->logmsg);
7557 if (logmsg == NULL) {
7558 err = got_error_from_errno("strdup");
7559 goto done;
7561 trim_logmsg(logmsg, 42);
7562 } else {
7563 err = get_short_logmsg(&logmsg, 42, commit);
7564 if (err)
7565 goto done;
7568 switch (hle->cmd->code) {
7569 case GOT_HISTEDIT_PICK:
7570 case GOT_HISTEDIT_EDIT:
7571 printf("%s -> %s: %s\n", old_id_str,
7572 new_id_str ? new_id_str : "no-op change", logmsg);
7573 break;
7574 case GOT_HISTEDIT_DROP:
7575 case GOT_HISTEDIT_FOLD:
7576 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
7577 logmsg);
7578 break;
7579 default:
7580 break;
7582 done:
7583 free(old_id_str);
7584 free(new_id_str);
7585 return err;
7588 static const struct got_error *
7589 histedit_commit(struct got_pathlist_head *merged_paths,
7590 struct got_worktree *worktree, struct got_fileindex *fileindex,
7591 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
7592 struct got_repository *repo)
7594 const struct got_error *err;
7595 struct got_commit_object *commit;
7596 struct got_object_id *new_commit_id;
7598 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
7599 && hle->logmsg == NULL) {
7600 err = histedit_edit_logmsg(hle, repo);
7601 if (err)
7602 return err;
7605 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7606 if (err)
7607 return err;
7609 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
7610 worktree, fileindex, tmp_branch, commit, hle->commit_id,
7611 hle->logmsg, repo);
7612 if (err) {
7613 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
7614 goto done;
7615 err = show_histedit_progress(commit, hle, NULL);
7616 } else {
7617 err = show_histedit_progress(commit, hle, new_commit_id);
7618 free(new_commit_id);
7620 done:
7621 got_object_commit_close(commit);
7622 return err;
7625 static const struct got_error *
7626 histedit_skip_commit(struct got_histedit_list_entry *hle,
7627 struct got_worktree *worktree, struct got_repository *repo)
7629 const struct got_error *error;
7630 struct got_commit_object *commit;
7632 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
7633 repo);
7634 if (error)
7635 return error;
7637 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
7638 if (error)
7639 return error;
7641 error = show_histedit_progress(commit, hle, NULL);
7642 got_object_commit_close(commit);
7643 return error;
7646 static const struct got_error *
7647 check_local_changes(void *arg, unsigned char status,
7648 unsigned char staged_status, const char *path,
7649 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
7650 struct got_object_id *commit_id, int dirfd, const char *de_name)
7652 int *have_local_changes = arg;
7654 switch (status) {
7655 case GOT_STATUS_ADD:
7656 case GOT_STATUS_DELETE:
7657 case GOT_STATUS_MODIFY:
7658 case GOT_STATUS_CONFLICT:
7659 *have_local_changes = 1;
7660 return got_error(GOT_ERR_CANCELLED);
7661 default:
7662 break;
7665 switch (staged_status) {
7666 case GOT_STATUS_ADD:
7667 case GOT_STATUS_DELETE:
7668 case GOT_STATUS_MODIFY:
7669 *have_local_changes = 1;
7670 return got_error(GOT_ERR_CANCELLED);
7671 default:
7672 break;
7675 return NULL;
7678 static const struct got_error *
7679 cmd_histedit(int argc, char *argv[])
7681 const struct got_error *error = NULL;
7682 struct got_worktree *worktree = NULL;
7683 struct got_fileindex *fileindex = NULL;
7684 struct got_repository *repo = NULL;
7685 char *cwd = NULL;
7686 struct got_reference *branch = NULL;
7687 struct got_reference *tmp_branch = NULL;
7688 struct got_object_id *resume_commit_id = NULL;
7689 struct got_object_id *base_commit_id = NULL;
7690 struct got_object_id *head_commit_id = NULL;
7691 struct got_commit_object *commit = NULL;
7692 int ch, rebase_in_progress = 0, did_something;
7693 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
7694 int edit_logmsg_only = 0;
7695 const char *edit_script_path = NULL;
7696 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7697 struct got_object_id_queue commits;
7698 struct got_pathlist_head merged_paths;
7699 const struct got_object_id_queue *parent_ids;
7700 struct got_object_qid *pid;
7701 struct got_histedit_list histedit_cmds;
7702 struct got_histedit_list_entry *hle;
7704 SIMPLEQ_INIT(&commits);
7705 TAILQ_INIT(&histedit_cmds);
7706 TAILQ_INIT(&merged_paths);
7708 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
7709 switch (ch) {
7710 case 'a':
7711 abort_edit = 1;
7712 break;
7713 case 'c':
7714 continue_edit = 1;
7715 break;
7716 case 'F':
7717 edit_script_path = optarg;
7718 break;
7719 case 'm':
7720 edit_logmsg_only = 1;
7721 break;
7722 default:
7723 usage_histedit();
7724 /* NOTREACHED */
7728 argc -= optind;
7729 argv += optind;
7731 #ifndef PROFILE
7732 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7733 "unveil", NULL) == -1)
7734 err(1, "pledge");
7735 #endif
7736 if (abort_edit && continue_edit)
7737 errx(1, "histedit's -a and -c options are mutually exclusive");
7738 if (edit_script_path && edit_logmsg_only)
7739 errx(1, "histedit's -F and -m options are mutually exclusive");
7740 if (abort_edit && edit_logmsg_only)
7741 errx(1, "histedit's -a and -m options are mutually exclusive");
7742 if (continue_edit && edit_logmsg_only)
7743 errx(1, "histedit's -c and -m options are mutually exclusive");
7744 if (argc != 0)
7745 usage_histedit();
7748 * This command cannot apply unveil(2) in all cases because the
7749 * user may choose to run an editor to edit the histedit script
7750 * and to edit individual commit log messages.
7751 * unveil(2) traverses exec(2); if an editor is used we have to
7752 * apply unveil after edit script and log messages have been written.
7753 * XXX TODO: Make use of unveil(2) where possible.
7756 cwd = getcwd(NULL, 0);
7757 if (cwd == NULL) {
7758 error = got_error_from_errno("getcwd");
7759 goto done;
7761 error = got_worktree_open(&worktree, cwd);
7762 if (error)
7763 goto done;
7765 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7766 NULL);
7767 if (error != NULL)
7768 goto done;
7770 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7771 if (error)
7772 goto done;
7773 if (rebase_in_progress) {
7774 error = got_error(GOT_ERR_REBASING);
7775 goto done;
7778 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
7779 if (error)
7780 goto done;
7782 if (edit_in_progress && edit_logmsg_only) {
7783 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
7784 "histedit operation is in progress in this "
7785 "work tree and must be continued or aborted "
7786 "before the -m option can be used");
7787 goto done;
7790 if (edit_in_progress && abort_edit) {
7791 error = got_worktree_histedit_continue(&resume_commit_id,
7792 &tmp_branch, &branch, &base_commit_id, &fileindex,
7793 worktree, repo);
7794 if (error)
7795 goto done;
7796 printf("Switching work tree to %s\n",
7797 got_ref_get_symref_target(branch));
7798 error = got_worktree_histedit_abort(worktree, fileindex, repo,
7799 branch, base_commit_id, update_progress, &did_something);
7800 if (error)
7801 goto done;
7802 printf("Histedit of %s aborted\n",
7803 got_ref_get_symref_target(branch));
7804 goto done; /* nothing else to do */
7805 } else if (abort_edit) {
7806 error = got_error(GOT_ERR_NOT_HISTEDIT);
7807 goto done;
7810 if (continue_edit) {
7811 char *path;
7813 if (!edit_in_progress) {
7814 error = got_error(GOT_ERR_NOT_HISTEDIT);
7815 goto done;
7818 error = got_worktree_get_histedit_script_path(&path, worktree);
7819 if (error)
7820 goto done;
7822 error = histedit_load_list(&histedit_cmds, path, repo);
7823 free(path);
7824 if (error)
7825 goto done;
7827 error = got_worktree_histedit_continue(&resume_commit_id,
7828 &tmp_branch, &branch, &base_commit_id, &fileindex,
7829 worktree, repo);
7830 if (error)
7831 goto done;
7833 error = got_ref_resolve(&head_commit_id, repo, branch);
7834 if (error)
7835 goto done;
7837 error = got_object_open_as_commit(&commit, repo,
7838 head_commit_id);
7839 if (error)
7840 goto done;
7841 parent_ids = got_object_commit_get_parent_ids(commit);
7842 pid = SIMPLEQ_FIRST(parent_ids);
7843 if (pid == NULL) {
7844 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
7845 goto done;
7847 error = collect_commits(&commits, head_commit_id, pid->id,
7848 base_commit_id, got_worktree_get_path_prefix(worktree),
7849 GOT_ERR_HISTEDIT_PATH, repo);
7850 got_object_commit_close(commit);
7851 commit = NULL;
7852 if (error)
7853 goto done;
7854 } else {
7855 if (edit_in_progress) {
7856 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7857 goto done;
7860 error = got_ref_open(&branch, repo,
7861 got_worktree_get_head_ref_name(worktree), 0);
7862 if (error != NULL)
7863 goto done;
7865 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
7866 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
7867 "will not edit commit history of a branch outside "
7868 "the \"refs/heads/\" reference namespace");
7869 goto done;
7872 error = got_ref_resolve(&head_commit_id, repo, branch);
7873 got_ref_close(branch);
7874 branch = NULL;
7875 if (error)
7876 goto done;
7878 error = got_object_open_as_commit(&commit, repo,
7879 head_commit_id);
7880 if (error)
7881 goto done;
7882 parent_ids = got_object_commit_get_parent_ids(commit);
7883 pid = SIMPLEQ_FIRST(parent_ids);
7884 if (pid == NULL) {
7885 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
7886 goto done;
7888 error = collect_commits(&commits, head_commit_id, pid->id,
7889 got_worktree_get_base_commit_id(worktree),
7890 got_worktree_get_path_prefix(worktree),
7891 GOT_ERR_HISTEDIT_PATH, repo);
7892 got_object_commit_close(commit);
7893 commit = NULL;
7894 if (error)
7895 goto done;
7897 if (SIMPLEQ_EMPTY(&commits)) {
7898 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
7899 goto done;
7902 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
7903 &base_commit_id, &fileindex, worktree, repo);
7904 if (error)
7905 goto done;
7907 if (edit_script_path) {
7908 error = histedit_load_list(&histedit_cmds,
7909 edit_script_path, repo);
7910 if (error) {
7911 got_worktree_histedit_abort(worktree, fileindex,
7912 repo, branch, base_commit_id,
7913 update_progress, &did_something);
7914 goto done;
7916 } else {
7917 const char *branch_name;
7918 branch_name = got_ref_get_symref_target(branch);
7919 if (strncmp(branch_name, "refs/heads/", 11) == 0)
7920 branch_name += 11;
7921 error = histedit_edit_script(&histedit_cmds, &commits,
7922 branch_name, edit_logmsg_only, repo);
7923 if (error) {
7924 got_worktree_histedit_abort(worktree, fileindex,
7925 repo, branch, base_commit_id,
7926 update_progress, &did_something);
7927 goto done;
7932 error = histedit_save_list(&histedit_cmds, worktree,
7933 repo);
7934 if (error) {
7935 got_worktree_histedit_abort(worktree, fileindex,
7936 repo, branch, base_commit_id,
7937 update_progress, &did_something);
7938 goto done;
7943 error = histedit_check_script(&histedit_cmds, &commits, repo);
7944 if (error)
7945 goto done;
7947 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
7948 if (resume_commit_id) {
7949 if (got_object_id_cmp(hle->commit_id,
7950 resume_commit_id) != 0)
7951 continue;
7953 resume_commit_id = NULL;
7954 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
7955 hle->cmd->code == GOT_HISTEDIT_FOLD) {
7956 error = histedit_skip_commit(hle, worktree,
7957 repo);
7958 if (error)
7959 goto done;
7960 } else {
7961 struct got_pathlist_head paths;
7962 int have_changes = 0;
7964 TAILQ_INIT(&paths);
7965 error = got_pathlist_append(&paths, "", NULL);
7966 if (error)
7967 goto done;
7968 error = got_worktree_status(worktree, &paths,
7969 repo, check_local_changes, &have_changes,
7970 check_cancelled, NULL);
7971 got_pathlist_free(&paths);
7972 if (error) {
7973 if (error->code != GOT_ERR_CANCELLED)
7974 goto done;
7975 if (sigint_received || sigpipe_received)
7976 goto done;
7978 if (have_changes) {
7979 error = histedit_commit(NULL, worktree,
7980 fileindex, tmp_branch, hle, repo);
7981 if (error)
7982 goto done;
7983 } else {
7984 error = got_object_open_as_commit(
7985 &commit, repo, hle->commit_id);
7986 if (error)
7987 goto done;
7988 error = show_histedit_progress(commit,
7989 hle, NULL);
7990 got_object_commit_close(commit);
7991 commit = NULL;
7992 if (error)
7993 goto done;
7996 continue;
7999 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8000 error = histedit_skip_commit(hle, worktree, repo);
8001 if (error)
8002 goto done;
8003 continue;
8006 error = got_object_open_as_commit(&commit, repo,
8007 hle->commit_id);
8008 if (error)
8009 goto done;
8010 parent_ids = got_object_commit_get_parent_ids(commit);
8011 pid = SIMPLEQ_FIRST(parent_ids);
8013 error = got_worktree_histedit_merge_files(&merged_paths,
8014 worktree, fileindex, pid->id, hle->commit_id, repo,
8015 rebase_progress, &rebase_status, check_cancelled, NULL);
8016 if (error)
8017 goto done;
8018 got_object_commit_close(commit);
8019 commit = NULL;
8021 if (rebase_status == GOT_STATUS_CONFLICT) {
8022 error = show_rebase_merge_conflict(hle->commit_id,
8023 repo);
8024 if (error)
8025 goto done;
8026 got_worktree_rebase_pathlist_free(&merged_paths);
8027 break;
8030 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8031 char *id_str;
8032 error = got_object_id_str(&id_str, hle->commit_id);
8033 if (error)
8034 goto done;
8035 printf("Stopping histedit for amending commit %s\n",
8036 id_str);
8037 free(id_str);
8038 got_worktree_rebase_pathlist_free(&merged_paths);
8039 error = got_worktree_histedit_postpone(worktree,
8040 fileindex);
8041 goto done;
8044 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8045 error = histedit_skip_commit(hle, worktree, repo);
8046 if (error)
8047 goto done;
8048 continue;
8051 error = histedit_commit(&merged_paths, worktree, fileindex,
8052 tmp_branch, hle, repo);
8053 got_worktree_rebase_pathlist_free(&merged_paths);
8054 if (error)
8055 goto done;
8058 if (rebase_status == GOT_STATUS_CONFLICT) {
8059 error = got_worktree_histedit_postpone(worktree, fileindex);
8060 if (error)
8061 goto done;
8062 error = got_error_msg(GOT_ERR_CONFLICTS,
8063 "conflicts must be resolved before histedit can continue");
8064 } else
8065 error = histedit_complete(worktree, fileindex, tmp_branch,
8066 branch, repo);
8067 done:
8068 got_object_id_queue_free(&commits);
8069 histedit_free_list(&histedit_cmds);
8070 free(head_commit_id);
8071 free(base_commit_id);
8072 free(resume_commit_id);
8073 if (commit)
8074 got_object_commit_close(commit);
8075 if (branch)
8076 got_ref_close(branch);
8077 if (tmp_branch)
8078 got_ref_close(tmp_branch);
8079 if (worktree)
8080 got_worktree_close(worktree);
8081 if (repo)
8082 got_repo_close(repo);
8083 return error;
8086 __dead static void
8087 usage_integrate(void)
8089 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
8090 exit(1);
8093 static const struct got_error *
8094 cmd_integrate(int argc, char *argv[])
8096 const struct got_error *error = NULL;
8097 struct got_repository *repo = NULL;
8098 struct got_worktree *worktree = NULL;
8099 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
8100 const char *branch_arg = NULL;
8101 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
8102 struct got_fileindex *fileindex = NULL;
8103 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
8104 int ch, did_something = 0;
8106 while ((ch = getopt(argc, argv, "")) != -1) {
8107 switch (ch) {
8108 default:
8109 usage_integrate();
8110 /* NOTREACHED */
8114 argc -= optind;
8115 argv += optind;
8117 if (argc != 1)
8118 usage_integrate();
8119 branch_arg = argv[0];
8121 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8122 "unveil", NULL) == -1)
8123 err(1, "pledge");
8125 cwd = getcwd(NULL, 0);
8126 if (cwd == NULL) {
8127 error = got_error_from_errno("getcwd");
8128 goto done;
8131 error = got_worktree_open(&worktree, cwd);
8132 if (error)
8133 goto done;
8135 error = check_rebase_or_histedit_in_progress(worktree);
8136 if (error)
8137 goto done;
8139 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8140 NULL);
8141 if (error != NULL)
8142 goto done;
8144 error = apply_unveil(got_repo_get_path(repo), 0,
8145 got_worktree_get_root_path(worktree));
8146 if (error)
8147 goto done;
8149 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
8150 error = got_error_from_errno("asprintf");
8151 goto done;
8154 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
8155 &base_branch_ref, worktree, refname, repo);
8156 if (error)
8157 goto done;
8159 refname = strdup(got_ref_get_name(branch_ref));
8160 if (refname == NULL) {
8161 error = got_error_from_errno("strdup");
8162 got_worktree_integrate_abort(worktree, fileindex, repo,
8163 branch_ref, base_branch_ref);
8164 goto done;
8166 base_refname = strdup(got_ref_get_name(base_branch_ref));
8167 if (base_refname == NULL) {
8168 error = got_error_from_errno("strdup");
8169 got_worktree_integrate_abort(worktree, fileindex, repo,
8170 branch_ref, base_branch_ref);
8171 goto done;
8174 error = got_ref_resolve(&commit_id, repo, branch_ref);
8175 if (error)
8176 goto done;
8178 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
8179 if (error)
8180 goto done;
8182 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
8183 error = got_error_msg(GOT_ERR_SAME_BRANCH,
8184 "specified branch has already been integrated");
8185 got_worktree_integrate_abort(worktree, fileindex, repo,
8186 branch_ref, base_branch_ref);
8187 goto done;
8190 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
8191 if (error) {
8192 if (error->code == GOT_ERR_ANCESTRY)
8193 error = got_error(GOT_ERR_REBASE_REQUIRED);
8194 got_worktree_integrate_abort(worktree, fileindex, repo,
8195 branch_ref, base_branch_ref);
8196 goto done;
8199 error = got_worktree_integrate_continue(worktree, fileindex, repo,
8200 branch_ref, base_branch_ref, update_progress, &did_something,
8201 check_cancelled, NULL);
8202 if (error)
8203 goto done;
8205 printf("Integrated %s into %s\n", refname, base_refname);
8206 done:
8207 if (repo)
8208 got_repo_close(repo);
8209 if (worktree)
8210 got_worktree_close(worktree);
8211 free(cwd);
8212 free(base_commit_id);
8213 free(commit_id);
8214 free(refname);
8215 free(base_refname);
8216 return error;
8219 __dead static void
8220 usage_stage(void)
8222 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
8223 "[file-path ...]\n",
8224 getprogname());
8225 exit(1);
8228 static const struct got_error *
8229 print_stage(void *arg, unsigned char status, unsigned char staged_status,
8230 const char *path, struct got_object_id *blob_id,
8231 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
8232 int dirfd, const char *de_name)
8234 const struct got_error *err = NULL;
8235 char *id_str = NULL;
8237 if (staged_status != GOT_STATUS_ADD &&
8238 staged_status != GOT_STATUS_MODIFY &&
8239 staged_status != GOT_STATUS_DELETE)
8240 return NULL;
8242 if (staged_status == GOT_STATUS_ADD ||
8243 staged_status == GOT_STATUS_MODIFY)
8244 err = got_object_id_str(&id_str, staged_blob_id);
8245 else
8246 err = got_object_id_str(&id_str, blob_id);
8247 if (err)
8248 return err;
8250 printf("%s %c %s\n", id_str, staged_status, path);
8251 free(id_str);
8252 return NULL;
8255 static const struct got_error *
8256 cmd_stage(int argc, char *argv[])
8258 const struct got_error *error = NULL;
8259 struct got_repository *repo = NULL;
8260 struct got_worktree *worktree = NULL;
8261 char *cwd = NULL;
8262 struct got_pathlist_head paths;
8263 struct got_pathlist_entry *pe;
8264 int ch, list_stage = 0, pflag = 0;
8265 FILE *patch_script_file = NULL;
8266 const char *patch_script_path = NULL;
8267 struct choose_patch_arg cpa;
8269 TAILQ_INIT(&paths);
8271 while ((ch = getopt(argc, argv, "lpF:")) != -1) {
8272 switch (ch) {
8273 case 'l':
8274 list_stage = 1;
8275 break;
8276 case 'p':
8277 pflag = 1;
8278 break;
8279 case 'F':
8280 patch_script_path = optarg;
8281 break;
8282 default:
8283 usage_stage();
8284 /* NOTREACHED */
8288 argc -= optind;
8289 argv += optind;
8291 #ifndef PROFILE
8292 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8293 "unveil", NULL) == -1)
8294 err(1, "pledge");
8295 #endif
8296 if (list_stage && (pflag || patch_script_path))
8297 errx(1, "-l option cannot be used with other options");
8298 if (patch_script_path && !pflag)
8299 errx(1, "-F option can only be used together with -p option");
8301 cwd = getcwd(NULL, 0);
8302 if (cwd == NULL) {
8303 error = got_error_from_errno("getcwd");
8304 goto done;
8307 error = got_worktree_open(&worktree, cwd);
8308 if (error)
8309 goto done;
8311 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8312 NULL);
8313 if (error != NULL)
8314 goto done;
8316 if (patch_script_path) {
8317 patch_script_file = fopen(patch_script_path, "r");
8318 if (patch_script_file == NULL) {
8319 error = got_error_from_errno2("fopen",
8320 patch_script_path);
8321 goto done;
8324 error = apply_unveil(got_repo_get_path(repo), 0,
8325 got_worktree_get_root_path(worktree));
8326 if (error)
8327 goto done;
8329 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8330 if (error)
8331 goto done;
8333 if (list_stage)
8334 error = got_worktree_status(worktree, &paths, repo,
8335 print_stage, NULL, check_cancelled, NULL);
8336 else {
8337 cpa.patch_script_file = patch_script_file;
8338 cpa.action = "stage";
8339 error = got_worktree_stage(worktree, &paths,
8340 pflag ? NULL : print_status, NULL,
8341 pflag ? choose_patch : NULL, &cpa, repo);
8343 done:
8344 if (patch_script_file && fclose(patch_script_file) == EOF &&
8345 error == NULL)
8346 error = got_error_from_errno2("fclose", patch_script_path);
8347 if (repo)
8348 got_repo_close(repo);
8349 if (worktree)
8350 got_worktree_close(worktree);
8351 TAILQ_FOREACH(pe, &paths, entry)
8352 free((char *)pe->path);
8353 got_pathlist_free(&paths);
8354 free(cwd);
8355 return error;
8358 __dead static void
8359 usage_unstage(void)
8361 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
8362 "[file-path ...]\n",
8363 getprogname());
8364 exit(1);
8368 static const struct got_error *
8369 cmd_unstage(int argc, char *argv[])
8371 const struct got_error *error = NULL;
8372 struct got_repository *repo = NULL;
8373 struct got_worktree *worktree = NULL;
8374 char *cwd = NULL;
8375 struct got_pathlist_head paths;
8376 struct got_pathlist_entry *pe;
8377 int ch, did_something = 0, pflag = 0;
8378 FILE *patch_script_file = NULL;
8379 const char *patch_script_path = NULL;
8380 struct choose_patch_arg cpa;
8382 TAILQ_INIT(&paths);
8384 while ((ch = getopt(argc, argv, "pF:")) != -1) {
8385 switch (ch) {
8386 case 'p':
8387 pflag = 1;
8388 break;
8389 case 'F':
8390 patch_script_path = optarg;
8391 break;
8392 default:
8393 usage_unstage();
8394 /* NOTREACHED */
8398 argc -= optind;
8399 argv += optind;
8401 #ifndef PROFILE
8402 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8403 "unveil", NULL) == -1)
8404 err(1, "pledge");
8405 #endif
8406 if (patch_script_path && !pflag)
8407 errx(1, "-F option can only be used together with -p option");
8409 cwd = getcwd(NULL, 0);
8410 if (cwd == NULL) {
8411 error = got_error_from_errno("getcwd");
8412 goto done;
8415 error = got_worktree_open(&worktree, cwd);
8416 if (error)
8417 goto done;
8419 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8420 NULL);
8421 if (error != NULL)
8422 goto done;
8424 if (patch_script_path) {
8425 patch_script_file = fopen(patch_script_path, "r");
8426 if (patch_script_file == NULL) {
8427 error = got_error_from_errno2("fopen",
8428 patch_script_path);
8429 goto done;
8433 error = apply_unveil(got_repo_get_path(repo), 0,
8434 got_worktree_get_root_path(worktree));
8435 if (error)
8436 goto done;
8438 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8439 if (error)
8440 goto done;
8442 cpa.patch_script_file = patch_script_file;
8443 cpa.action = "unstage";
8444 error = got_worktree_unstage(worktree, &paths, update_progress,
8445 &did_something, pflag ? choose_patch : NULL, &cpa, repo);
8446 done:
8447 if (patch_script_file && fclose(patch_script_file) == EOF &&
8448 error == NULL)
8449 error = got_error_from_errno2("fclose", patch_script_path);
8450 if (repo)
8451 got_repo_close(repo);
8452 if (worktree)
8453 got_worktree_close(worktree);
8454 TAILQ_FOREACH(pe, &paths, entry)
8455 free((char *)pe->path);
8456 got_pathlist_free(&paths);
8457 free(cwd);
8458 return error;
8461 __dead static void
8462 usage_cat(void)
8464 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
8465 "arg1 [arg2 ...]\n", getprogname());
8466 exit(1);
8469 static const struct got_error *
8470 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8472 const struct got_error *err;
8473 struct got_blob_object *blob;
8475 err = got_object_open_as_blob(&blob, repo, id, 8192);
8476 if (err)
8477 return err;
8479 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
8480 got_object_blob_close(blob);
8481 return err;
8484 static const struct got_error *
8485 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8487 const struct got_error *err;
8488 struct got_tree_object *tree;
8489 int nentries, i;
8491 err = got_object_open_as_tree(&tree, repo, id);
8492 if (err)
8493 return err;
8495 nentries = got_object_tree_get_nentries(tree);
8496 for (i = 0; i < nentries; i++) {
8497 struct got_tree_entry *te;
8498 char *id_str;
8499 if (sigint_received || sigpipe_received)
8500 break;
8501 te = got_object_tree_get_entry(tree, i);
8502 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
8503 if (err)
8504 break;
8505 fprintf(outfile, "%s %.7o %s\n", id_str,
8506 got_tree_entry_get_mode(te),
8507 got_tree_entry_get_name(te));
8508 free(id_str);
8511 got_object_tree_close(tree);
8512 return err;
8515 static const struct got_error *
8516 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8518 const struct got_error *err;
8519 struct got_commit_object *commit;
8520 const struct got_object_id_queue *parent_ids;
8521 struct got_object_qid *pid;
8522 char *id_str = NULL;
8523 const char *logmsg = NULL;
8525 err = got_object_open_as_commit(&commit, repo, id);
8526 if (err)
8527 return err;
8529 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
8530 if (err)
8531 goto done;
8533 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
8534 parent_ids = got_object_commit_get_parent_ids(commit);
8535 fprintf(outfile, "numparents %d\n",
8536 got_object_commit_get_nparents(commit));
8537 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
8538 char *pid_str;
8539 err = got_object_id_str(&pid_str, pid->id);
8540 if (err)
8541 goto done;
8542 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
8543 free(pid_str);
8545 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
8546 got_object_commit_get_author(commit),
8547 got_object_commit_get_author_time(commit));
8549 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
8550 got_object_commit_get_author(commit),
8551 got_object_commit_get_committer_time(commit));
8553 logmsg = got_object_commit_get_logmsg_raw(commit);
8554 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
8555 fprintf(outfile, "%s", logmsg);
8556 done:
8557 free(id_str);
8558 got_object_commit_close(commit);
8559 return err;
8562 static const struct got_error *
8563 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8565 const struct got_error *err;
8566 struct got_tag_object *tag;
8567 char *id_str = NULL;
8568 const char *tagmsg = NULL;
8570 err = got_object_open_as_tag(&tag, repo, id);
8571 if (err)
8572 return err;
8574 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
8575 if (err)
8576 goto done;
8578 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
8580 switch (got_object_tag_get_object_type(tag)) {
8581 case GOT_OBJ_TYPE_BLOB:
8582 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8583 GOT_OBJ_LABEL_BLOB);
8584 break;
8585 case GOT_OBJ_TYPE_TREE:
8586 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8587 GOT_OBJ_LABEL_TREE);
8588 break;
8589 case GOT_OBJ_TYPE_COMMIT:
8590 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8591 GOT_OBJ_LABEL_COMMIT);
8592 break;
8593 case GOT_OBJ_TYPE_TAG:
8594 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8595 GOT_OBJ_LABEL_TAG);
8596 break;
8597 default:
8598 break;
8601 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
8602 got_object_tag_get_name(tag));
8604 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
8605 got_object_tag_get_tagger(tag),
8606 got_object_tag_get_tagger_time(tag));
8608 tagmsg = got_object_tag_get_message(tag);
8609 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
8610 fprintf(outfile, "%s", tagmsg);
8611 done:
8612 free(id_str);
8613 got_object_tag_close(tag);
8614 return err;
8617 static const struct got_error *
8618 cmd_cat(int argc, char *argv[])
8620 const struct got_error *error;
8621 struct got_repository *repo = NULL;
8622 struct got_worktree *worktree = NULL;
8623 char *cwd = NULL, *repo_path = NULL, *label = NULL;
8624 const char *commit_id_str = NULL;
8625 struct got_object_id *id = NULL, *commit_id = NULL;
8626 int ch, obj_type, i, force_path = 0;
8628 #ifndef PROFILE
8629 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8630 NULL) == -1)
8631 err(1, "pledge");
8632 #endif
8634 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
8635 switch (ch) {
8636 case 'c':
8637 commit_id_str = optarg;
8638 break;
8639 case 'r':
8640 repo_path = realpath(optarg, NULL);
8641 if (repo_path == NULL)
8642 return got_error_from_errno2("realpath",
8643 optarg);
8644 got_path_strip_trailing_slashes(repo_path);
8645 break;
8646 case 'P':
8647 force_path = 1;
8648 break;
8649 default:
8650 usage_cat();
8651 /* NOTREACHED */
8655 argc -= optind;
8656 argv += optind;
8658 cwd = getcwd(NULL, 0);
8659 if (cwd == NULL) {
8660 error = got_error_from_errno("getcwd");
8661 goto done;
8663 error = got_worktree_open(&worktree, cwd);
8664 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8665 goto done;
8666 if (worktree) {
8667 if (repo_path == NULL) {
8668 repo_path = strdup(
8669 got_worktree_get_repo_path(worktree));
8670 if (repo_path == NULL) {
8671 error = got_error_from_errno("strdup");
8672 goto done;
8677 if (repo_path == NULL) {
8678 repo_path = getcwd(NULL, 0);
8679 if (repo_path == NULL)
8680 return got_error_from_errno("getcwd");
8683 error = got_repo_open(&repo, repo_path, NULL);
8684 free(repo_path);
8685 if (error != NULL)
8686 goto done;
8688 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
8689 if (error)
8690 goto done;
8692 if (commit_id_str == NULL)
8693 commit_id_str = GOT_REF_HEAD;
8694 error = got_repo_match_object_id(&commit_id, NULL,
8695 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
8696 if (error)
8697 goto done;
8699 for (i = 0; i < argc; i++) {
8700 if (force_path) {
8701 error = got_object_id_by_path(&id, repo, commit_id,
8702 argv[i]);
8703 if (error)
8704 break;
8705 } else {
8706 error = got_repo_match_object_id(&id, &label, argv[i],
8707 GOT_OBJ_TYPE_ANY, 0, repo);
8708 if (error) {
8709 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
8710 error->code != GOT_ERR_NOT_REF)
8711 break;
8712 error = got_object_id_by_path(&id, repo,
8713 commit_id, argv[i]);
8714 if (error)
8715 break;
8719 error = got_object_get_type(&obj_type, repo, id);
8720 if (error)
8721 break;
8723 switch (obj_type) {
8724 case GOT_OBJ_TYPE_BLOB:
8725 error = cat_blob(id, repo, stdout);
8726 break;
8727 case GOT_OBJ_TYPE_TREE:
8728 error = cat_tree(id, repo, stdout);
8729 break;
8730 case GOT_OBJ_TYPE_COMMIT:
8731 error = cat_commit(id, repo, stdout);
8732 break;
8733 case GOT_OBJ_TYPE_TAG:
8734 error = cat_tag(id, repo, stdout);
8735 break;
8736 default:
8737 error = got_error(GOT_ERR_OBJ_TYPE);
8738 break;
8740 if (error)
8741 break;
8742 free(label);
8743 label = NULL;
8744 free(id);
8745 id = NULL;
8747 done:
8748 free(label);
8749 free(id);
8750 free(commit_id);
8751 if (worktree)
8752 got_worktree_close(worktree);
8753 if (repo) {
8754 const struct got_error *repo_error;
8755 repo_error = got_repo_close(repo);
8756 if (error == NULL)
8757 error = repo_error;
8759 return error;