Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/param.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
41 #include <util.h>
43 #include "got_version.h"
44 #include "got_error.h"
45 #include "got_object.h"
46 #include "got_reference.h"
47 #include "got_repository.h"
48 #include "got_path.h"
49 #include "got_cancel.h"
50 #include "got_worktree.h"
51 #include "got_diff.h"
52 #include "got_commit_graph.h"
53 #include "got_fetch.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_opentemp.h"
58 #ifndef nitems
59 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
60 #endif
62 static volatile sig_atomic_t sigint_received;
63 static volatile sig_atomic_t sigpipe_received;
65 static void
66 catch_sigint(int signo)
67 {
68 sigint_received = 1;
69 }
71 static void
72 catch_sigpipe(int signo)
73 {
74 sigpipe_received = 1;
75 }
78 struct got_cmd {
79 const char *cmd_name;
80 const struct got_error *(*cmd_main)(int, char *[]);
81 void (*cmd_usage)(void);
82 const char *cmd_alias;
83 };
85 __dead static void usage(int);
86 __dead static void usage_init(void);
87 __dead static void usage_import(void);
88 __dead static void usage_clone(void);
89 __dead static void usage_fetch(void);
90 __dead static void usage_checkout(void);
91 __dead static void usage_update(void);
92 __dead static void usage_log(void);
93 __dead static void usage_diff(void);
94 __dead static void usage_blame(void);
95 __dead static void usage_tree(void);
96 __dead static void usage_status(void);
97 __dead static void usage_ref(void);
98 __dead static void usage_branch(void);
99 __dead static void usage_tag(void);
100 __dead static void usage_add(void);
101 __dead static void usage_remove(void);
102 __dead static void usage_revert(void);
103 __dead static void usage_commit(void);
104 __dead static void usage_cherrypick(void);
105 __dead static void usage_backout(void);
106 __dead static void usage_rebase(void);
107 __dead static void usage_histedit(void);
108 __dead static void usage_integrate(void);
109 __dead static void usage_stage(void);
110 __dead static void usage_unstage(void);
111 __dead static void usage_cat(void);
113 static const struct got_error* cmd_init(int, char *[]);
114 static const struct got_error* cmd_import(int, char *[]);
115 static const struct got_error* cmd_clone(int, char *[]);
116 static const struct got_error* cmd_fetch(int, char *[]);
117 static const struct got_error* cmd_checkout(int, char *[]);
118 static const struct got_error* cmd_update(int, char *[]);
119 static const struct got_error* cmd_log(int, char *[]);
120 static const struct got_error* cmd_diff(int, char *[]);
121 static const struct got_error* cmd_blame(int, char *[]);
122 static const struct got_error* cmd_tree(int, char *[]);
123 static const struct got_error* cmd_status(int, char *[]);
124 static const struct got_error* cmd_ref(int, char *[]);
125 static const struct got_error* cmd_branch(int, char *[]);
126 static const struct got_error* cmd_tag(int, char *[]);
127 static const struct got_error* cmd_add(int, char *[]);
128 static const struct got_error* cmd_remove(int, char *[]);
129 static const struct got_error* cmd_revert(int, char *[]);
130 static const struct got_error* cmd_commit(int, char *[]);
131 static const struct got_error* cmd_cherrypick(int, char *[]);
132 static const struct got_error* cmd_backout(int, char *[]);
133 static const struct got_error* cmd_rebase(int, char *[]);
134 static const struct got_error* cmd_histedit(int, char *[]);
135 static const struct got_error* cmd_integrate(int, char *[]);
136 static const struct got_error* cmd_stage(int, char *[]);
137 static const struct got_error* cmd_unstage(int, char *[]);
138 static const struct got_error* cmd_cat(int, char *[]);
140 static struct got_cmd got_commands[] = {
141 { "init", cmd_init, usage_init, "in" },
142 { "import", cmd_import, usage_import, "im" },
143 { "clone", cmd_clone, usage_clone, "cl" },
144 { "fetch", cmd_fetch, usage_fetch, "fe" },
145 { "checkout", cmd_checkout, usage_checkout, "co" },
146 { "update", cmd_update, usage_update, "up" },
147 { "log", cmd_log, usage_log, "" },
148 { "diff", cmd_diff, usage_diff, "di" },
149 { "blame", cmd_blame, usage_blame, "bl" },
150 { "tree", cmd_tree, usage_tree, "tr" },
151 { "status", cmd_status, usage_status, "st" },
152 { "ref", cmd_ref, usage_ref, "" },
153 { "branch", cmd_branch, usage_branch, "br" },
154 { "tag", cmd_tag, usage_tag, "" },
155 { "add", cmd_add, usage_add, "" },
156 { "remove", cmd_remove, usage_remove, "rm" },
157 { "revert", cmd_revert, usage_revert, "rv" },
158 { "commit", cmd_commit, usage_commit, "ci" },
159 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
160 { "backout", cmd_backout, usage_backout, "bo" },
161 { "rebase", cmd_rebase, usage_rebase, "rb" },
162 { "histedit", cmd_histedit, usage_histedit, "he" },
163 { "integrate", cmd_integrate, usage_integrate,"ig" },
164 { "stage", cmd_stage, usage_stage, "sg" },
165 { "unstage", cmd_unstage, usage_unstage, "ug" },
166 { "cat", cmd_cat, usage_cat, "" },
167 };
169 static void
170 list_commands(void)
172 int i;
174 fprintf(stderr, "commands:");
175 for (i = 0; i < nitems(got_commands); i++) {
176 struct got_cmd *cmd = &got_commands[i];
177 fprintf(stderr, " %s", cmd->cmd_name);
179 fputc('\n', stderr);
182 int
183 main(int argc, char *argv[])
185 struct got_cmd *cmd;
186 unsigned int i;
187 int ch;
188 int hflag = 0, Vflag = 0;
189 static struct option longopts[] = {
190 { "version", no_argument, NULL, 'V' },
191 { NULL, 0, NULL, 0}
192 };
194 setlocale(LC_CTYPE, "");
196 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
197 switch (ch) {
198 case 'h':
199 hflag = 1;
200 break;
201 case 'V':
202 Vflag = 1;
203 break;
204 default:
205 usage(hflag);
206 /* NOTREACHED */
210 argc -= optind;
211 argv += optind;
212 optind = 0;
214 if (Vflag) {
215 got_version_print_str();
216 return 1;
219 if (argc <= 0)
220 usage(hflag);
222 signal(SIGINT, catch_sigint);
223 signal(SIGPIPE, catch_sigpipe);
225 for (i = 0; i < nitems(got_commands); i++) {
226 const struct got_error *error;
228 cmd = &got_commands[i];
230 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
231 strcmp(cmd->cmd_alias, argv[0]) != 0)
232 continue;
234 if (hflag)
235 got_commands[i].cmd_usage();
237 error = got_commands[i].cmd_main(argc, argv);
238 if (error && error->code != GOT_ERR_CANCELLED &&
239 error->code != GOT_ERR_PRIVSEP_EXIT &&
240 !(sigpipe_received &&
241 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
242 !(sigint_received &&
243 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
244 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
245 return 1;
248 return 0;
251 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
252 list_commands();
253 return 1;
256 __dead static void
257 usage(int hflag)
259 fprintf(stderr, "usage: %s [-h] [-V | --version] command [arg ...]\n",
260 getprogname());
261 if (hflag)
262 list_commands();
263 exit(1);
266 static const struct got_error *
267 get_editor(char **abspath)
269 const struct got_error *err = NULL;
270 const char *editor;
272 *abspath = NULL;
274 editor = getenv("VISUAL");
275 if (editor == NULL)
276 editor = getenv("EDITOR");
278 if (editor) {
279 err = got_path_find_prog(abspath, editor);
280 if (err)
281 return err;
284 if (*abspath == NULL) {
285 *abspath = strdup("/bin/ed");
286 if (*abspath == NULL)
287 return got_error_from_errno("strdup");
290 return NULL;
293 static const struct got_error *
294 apply_unveil(const char *repo_path, int repo_read_only,
295 const char *worktree_path)
297 const struct got_error *err;
299 #ifdef PROFILE
300 if (unveil("gmon.out", "rwc") != 0)
301 return got_error_from_errno2("unveil", "gmon.out");
302 #endif
303 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
304 return got_error_from_errno2("unveil", repo_path);
306 if (worktree_path && unveil(worktree_path, "rwc") != 0)
307 return got_error_from_errno2("unveil", worktree_path);
309 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
310 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
312 err = got_privsep_unveil_exec_helpers();
313 if (err != NULL)
314 return err;
316 if (unveil(NULL, NULL) != 0)
317 return got_error_from_errno("unveil");
319 return NULL;
322 __dead static void
323 usage_init(void)
325 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
326 exit(1);
329 static const struct got_error *
330 cmd_init(int argc, char *argv[])
332 const struct got_error *error = NULL;
333 char *repo_path = NULL;
334 int ch;
336 while ((ch = getopt(argc, argv, "")) != -1) {
337 switch (ch) {
338 default:
339 usage_init();
340 /* NOTREACHED */
344 argc -= optind;
345 argv += optind;
347 #ifndef PROFILE
348 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
349 err(1, "pledge");
350 #endif
351 if (argc != 1)
352 usage_init();
354 repo_path = strdup(argv[0]);
355 if (repo_path == NULL)
356 return got_error_from_errno("strdup");
358 got_path_strip_trailing_slashes(repo_path);
360 error = got_path_mkdir(repo_path);
361 if (error &&
362 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
363 goto done;
365 error = apply_unveil(repo_path, 0, NULL);
366 if (error)
367 goto done;
369 error = got_repo_init(repo_path);
370 done:
371 free(repo_path);
372 return error;
375 __dead static void
376 usage_import(void)
378 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
379 "[-r repository-path] [-I pattern] path\n", getprogname());
380 exit(1);
383 int
384 spawn_editor(const char *editor, const char *file)
386 pid_t pid;
387 sig_t sighup, sigint, sigquit;
388 int st = -1;
390 sighup = signal(SIGHUP, SIG_IGN);
391 sigint = signal(SIGINT, SIG_IGN);
392 sigquit = signal(SIGQUIT, SIG_IGN);
394 switch (pid = fork()) {
395 case -1:
396 goto doneediting;
397 case 0:
398 execl(editor, editor, file, (char *)NULL);
399 _exit(127);
402 while (waitpid(pid, &st, 0) == -1)
403 if (errno != EINTR)
404 break;
406 doneediting:
407 (void)signal(SIGHUP, sighup);
408 (void)signal(SIGINT, sigint);
409 (void)signal(SIGQUIT, sigquit);
411 if (!WIFEXITED(st)) {
412 errno = EINTR;
413 return -1;
416 return WEXITSTATUS(st);
419 static const struct got_error *
420 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
421 const char *initial_content)
423 const struct got_error *err = NULL;
424 char buf[1024];
425 struct stat st, st2;
426 FILE *fp;
427 int content_changed = 0;
428 size_t len;
430 *logmsg = NULL;
432 if (stat(logmsg_path, &st) == -1)
433 return got_error_from_errno2("stat", logmsg_path);
435 if (spawn_editor(editor, logmsg_path) == -1)
436 return got_error_from_errno("failed spawning editor");
438 if (stat(logmsg_path, &st2) == -1)
439 return got_error_from_errno("stat");
441 if (st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
442 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
443 "no changes made to commit message, aborting");
445 *logmsg = malloc(st2.st_size + 1);
446 if (*logmsg == NULL)
447 return got_error_from_errno("malloc");
448 (*logmsg)[0] = '\0';
449 len = 0;
451 fp = fopen(logmsg_path, "r");
452 if (fp == NULL) {
453 err = got_error_from_errno("fopen");
454 goto done;
456 while (fgets(buf, sizeof(buf), fp) != NULL) {
457 if (!content_changed && strcmp(buf, initial_content) != 0)
458 content_changed = 1;
459 if (buf[0] == '#' || (len == 0 && buf[0] == '\n'))
460 continue; /* remove comments and leading empty lines */
461 len = strlcat(*logmsg, buf, st2.st_size);
463 fclose(fp);
465 while (len > 0 && (*logmsg)[len - 1] == '\n') {
466 (*logmsg)[len - 1] = '\0';
467 len--;
470 if (len == 0 || !content_changed)
471 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
472 "commit message cannot be empty, aborting");
473 done:
474 if (err) {
475 free(*logmsg);
476 *logmsg = NULL;
478 return err;
481 static const struct got_error *
482 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
483 const char *path_dir, const char *branch_name)
485 char *initial_content = NULL;
486 const struct got_error *err = NULL;
487 int fd;
489 if (asprintf(&initial_content,
490 "\n# %s to be imported to branch %s\n", path_dir,
491 branch_name) == -1)
492 return got_error_from_errno("asprintf");
494 err = got_opentemp_named_fd(logmsg_path, &fd,
495 GOT_TMPDIR_STR "/got-importmsg");
496 if (err)
497 goto done;
499 dprintf(fd, initial_content);
500 close(fd);
502 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content);
503 done:
504 free(initial_content);
505 return err;
508 static const struct got_error *
509 import_progress(void *arg, const char *path)
511 printf("A %s\n", path);
512 return NULL;
515 static const struct got_error *
516 get_author(char **author, struct got_repository *repo)
518 const struct got_error *err = NULL;
519 const char *got_author, *name, *email;
521 *author = NULL;
523 name = got_repo_get_gitconfig_author_name(repo);
524 email = got_repo_get_gitconfig_author_email(repo);
525 if (name && email) {
526 if (asprintf(author, "%s <%s>", name, email) == -1)
527 return got_error_from_errno("asprintf");
528 return NULL;
531 got_author = getenv("GOT_AUTHOR");
532 if (got_author == NULL) {
533 name = got_repo_get_global_gitconfig_author_name(repo);
534 email = got_repo_get_global_gitconfig_author_email(repo);
535 if (name && email) {
536 if (asprintf(author, "%s <%s>", name, email) == -1)
537 return got_error_from_errno("asprintf");
538 return NULL;
540 /* TODO: Look up user in password database? */
541 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
544 *author = strdup(got_author);
545 if (*author == NULL)
546 return got_error_from_errno("strdup");
548 /*
549 * Really dumb email address check; we're only doing this to
550 * avoid git's object parser breaking on commits we create.
551 */
552 while (*got_author && *got_author != '<')
553 got_author++;
554 if (*got_author != '<') {
555 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
556 goto done;
558 while (*got_author && *got_author != '@')
559 got_author++;
560 if (*got_author != '@') {
561 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
562 goto done;
564 while (*got_author && *got_author != '>')
565 got_author++;
566 if (*got_author != '>')
567 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
568 done:
569 if (err) {
570 free(*author);
571 *author = NULL;
573 return err;
576 static const struct got_error *
577 get_gitconfig_path(char **gitconfig_path)
579 const char *homedir = getenv("HOME");
581 *gitconfig_path = NULL;
582 if (homedir) {
583 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
584 return got_error_from_errno("asprintf");
587 return NULL;
590 static const struct got_error *
591 cmd_import(int argc, char *argv[])
593 const struct got_error *error = NULL;
594 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
595 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
596 const char *branch_name = "main";
597 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
598 struct got_repository *repo = NULL;
599 struct got_reference *branch_ref = NULL, *head_ref = NULL;
600 struct got_object_id *new_commit_id = NULL;
601 int ch;
602 struct got_pathlist_head ignores;
603 struct got_pathlist_entry *pe;
604 int preserve_logmsg = 0;
606 TAILQ_INIT(&ignores);
608 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
609 switch (ch) {
610 case 'b':
611 branch_name = optarg;
612 break;
613 case 'm':
614 logmsg = strdup(optarg);
615 if (logmsg == NULL) {
616 error = got_error_from_errno("strdup");
617 goto done;
619 break;
620 case 'r':
621 repo_path = realpath(optarg, NULL);
622 if (repo_path == NULL) {
623 error = got_error_from_errno2("realpath",
624 optarg);
625 goto done;
627 break;
628 case 'I':
629 if (optarg[0] == '\0')
630 break;
631 error = got_pathlist_insert(&pe, &ignores, optarg,
632 NULL);
633 if (error)
634 goto done;
635 break;
636 default:
637 usage_import();
638 /* NOTREACHED */
642 argc -= optind;
643 argv += optind;
645 #ifndef PROFILE
646 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
647 "unveil",
648 NULL) == -1)
649 err(1, "pledge");
650 #endif
651 if (argc != 1)
652 usage_import();
654 if (repo_path == NULL) {
655 repo_path = getcwd(NULL, 0);
656 if (repo_path == NULL)
657 return got_error_from_errno("getcwd");
659 got_path_strip_trailing_slashes(repo_path);
660 error = get_gitconfig_path(&gitconfig_path);
661 if (error)
662 goto done;
663 error = got_repo_open(&repo, repo_path, gitconfig_path);
664 if (error)
665 goto done;
667 error = get_author(&author, repo);
668 if (error)
669 return error;
671 /*
672 * Don't let the user create a branch name with a leading '-'.
673 * While technically a valid reference name, this case is usually
674 * an unintended typo.
675 */
676 if (branch_name[0] == '-')
677 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
679 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
680 error = got_error_from_errno("asprintf");
681 goto done;
684 error = got_ref_open(&branch_ref, repo, refname, 0);
685 if (error) {
686 if (error->code != GOT_ERR_NOT_REF)
687 goto done;
688 } else {
689 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
690 "import target branch already exists");
691 goto done;
694 path_dir = realpath(argv[0], NULL);
695 if (path_dir == NULL) {
696 error = got_error_from_errno2("realpath", argv[0]);
697 goto done;
699 got_path_strip_trailing_slashes(path_dir);
701 /*
702 * unveil(2) traverses exec(2); if an editor is used we have
703 * to apply unveil after the log message has been written.
704 */
705 if (logmsg == NULL || strlen(logmsg) == 0) {
706 error = get_editor(&editor);
707 if (error)
708 goto done;
709 free(logmsg);
710 error = collect_import_msg(&logmsg, &logmsg_path, editor,
711 path_dir, refname);
712 if (error) {
713 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
714 logmsg_path != NULL)
715 preserve_logmsg = 1;
716 goto done;
720 if (unveil(path_dir, "r") != 0) {
721 error = got_error_from_errno2("unveil", path_dir);
722 if (logmsg_path)
723 preserve_logmsg = 1;
724 goto done;
727 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
728 if (error) {
729 if (logmsg_path)
730 preserve_logmsg = 1;
731 goto done;
734 error = got_repo_import(&new_commit_id, path_dir, logmsg,
735 author, &ignores, repo, import_progress, NULL);
736 if (error) {
737 if (logmsg_path)
738 preserve_logmsg = 1;
739 goto done;
742 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
743 if (error) {
744 if (logmsg_path)
745 preserve_logmsg = 1;
746 goto done;
749 error = got_ref_write(branch_ref, repo);
750 if (error) {
751 if (logmsg_path)
752 preserve_logmsg = 1;
753 goto done;
756 error = got_object_id_str(&id_str, new_commit_id);
757 if (error) {
758 if (logmsg_path)
759 preserve_logmsg = 1;
760 goto done;
763 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
764 if (error) {
765 if (error->code != GOT_ERR_NOT_REF) {
766 if (logmsg_path)
767 preserve_logmsg = 1;
768 goto done;
771 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
772 branch_ref);
773 if (error) {
774 if (logmsg_path)
775 preserve_logmsg = 1;
776 goto done;
779 error = got_ref_write(head_ref, repo);
780 if (error) {
781 if (logmsg_path)
782 preserve_logmsg = 1;
783 goto done;
787 printf("Created branch %s with commit %s\n",
788 got_ref_get_name(branch_ref), id_str);
789 done:
790 if (preserve_logmsg) {
791 fprintf(stderr, "%s: log message preserved in %s\n",
792 getprogname(), logmsg_path);
793 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
794 error = got_error_from_errno2("unlink", logmsg_path);
795 free(logmsg);
796 free(logmsg_path);
797 free(repo_path);
798 free(editor);
799 free(refname);
800 free(new_commit_id);
801 free(id_str);
802 free(author);
803 free(gitconfig_path);
804 if (branch_ref)
805 got_ref_close(branch_ref);
806 if (head_ref)
807 got_ref_close(head_ref);
808 return error;
811 __dead static void
812 usage_clone(void)
814 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
815 "[-R reference] repository-url [directory]\n", getprogname());
816 exit(1);
819 struct got_fetch_progress_arg {
820 char last_scaled_size[FMT_SCALED_STRSIZE];
821 int last_p_indexed;
822 int last_p_resolved;
823 int verbosity;
824 };
826 static const struct got_error *
827 fetch_progress(void *arg, const char *message, off_t packfile_size,
828 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
830 struct got_fetch_progress_arg *a = arg;
831 char scaled_size[FMT_SCALED_STRSIZE];
832 int p_indexed, p_resolved;
833 int print_size = 0, print_indexed = 0, print_resolved = 0;
835 if (a->verbosity < 0)
836 return NULL;
838 if (message && message[0] != '\0') {
839 printf("\rserver: %s", message);
840 fflush(stdout);
841 return NULL;
844 if (packfile_size > 0 || nobj_indexed > 0) {
845 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
846 (a->last_scaled_size[0] == '\0' ||
847 strcmp(scaled_size, a->last_scaled_size)) != 0) {
848 print_size = 1;
849 if (strlcpy(a->last_scaled_size, scaled_size,
850 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
851 return got_error(GOT_ERR_NO_SPACE);
853 if (nobj_indexed > 0) {
854 p_indexed = (nobj_indexed * 100) / nobj_total;
855 if (p_indexed != a->last_p_indexed) {
856 a->last_p_indexed = p_indexed;
857 print_indexed = 1;
858 print_size = 1;
861 if (nobj_resolved > 0) {
862 p_resolved = (nobj_resolved * 100) /
863 (nobj_total - nobj_loose);
864 if (p_resolved != a->last_p_resolved) {
865 a->last_p_resolved = p_resolved;
866 print_resolved = 1;
867 print_indexed = 1;
868 print_size = 1;
873 if (print_size || print_indexed || print_resolved)
874 printf("\r");
875 if (print_size)
876 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
877 if (print_indexed)
878 printf("; indexing %d%%", p_indexed);
879 if (print_resolved)
880 printf("; resolving deltas %d%%", p_resolved);
881 if (print_size || print_indexed || print_resolved)
882 fflush(stdout);
884 return NULL;
887 static const struct got_error *
888 create_symref(const char *refname, struct got_reference *target_ref,
889 int verbosity, struct got_repository *repo)
891 const struct got_error *err;
892 struct got_reference *head_symref;
894 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
895 if (err)
896 return err;
898 err = got_ref_write(head_symref, repo);
899 got_ref_close(head_symref);
900 if (err == NULL && verbosity > 0) {
901 printf("Created reference %s: %s\n", GOT_REF_HEAD,
902 got_ref_get_name(target_ref));
904 return err;
907 static const struct got_error *
908 list_remote_refs(struct got_pathlist_head *symrefs,
909 struct got_pathlist_head *refs)
911 const struct got_error *err;
912 struct got_pathlist_entry *pe;
914 TAILQ_FOREACH(pe, symrefs, entry) {
915 const char *refname = pe->path;
916 const char *targetref = pe->data;
918 printf("%s: %s\n", refname, targetref);
921 TAILQ_FOREACH(pe, refs, entry) {
922 const char *refname = pe->path;
923 struct got_object_id *id = pe->data;
924 char *id_str;
926 err = got_object_id_str(&id_str, id);
927 if (err)
928 return err;
929 printf("%s: %s\n", refname, id_str);
930 free(id_str);
933 return NULL;
936 static const struct got_error *
937 create_ref(const char *refname, struct got_object_id *id,
938 int verbosity, struct got_repository *repo)
940 const struct got_error *err = NULL;
941 struct got_reference *ref;
942 char *id_str;
944 err = got_object_id_str(&id_str, id);
945 if (err)
946 return err;
948 err = got_ref_alloc(&ref, refname, id);
949 if (err)
950 goto done;
952 err = got_ref_write(ref, repo);
953 got_ref_close(ref);
955 if (err == NULL && verbosity >= 0)
956 printf("Created reference %s: %s\n", refname, id_str);
957 done:
958 free(id_str);
959 return err;
962 static int
963 match_wanted_ref(const char *refname, const char *wanted_ref)
965 if (strncmp(refname, "refs/", 5) != 0)
966 return 0;
967 refname += 5;
969 /*
970 * Prevent fetching of references that won't make any
971 * sense outside of the remote repository's context.
972 */
973 if (strncmp(refname, "got/", 4) == 0)
974 return 0;
975 if (strncmp(refname, "remotes/", 8) == 0)
976 return 0;
978 if (strncmp(wanted_ref, "refs/", 5) == 0)
979 wanted_ref += 5;
981 /* Allow prefix match. */
982 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
983 return 1;
985 /* Allow exact match. */
986 return (strcmp(refname, wanted_ref) == 0);
989 static int
990 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
992 struct got_pathlist_entry *pe;
994 TAILQ_FOREACH(pe, wanted_refs, entry) {
995 if (match_wanted_ref(refname, pe->path))
996 return 1;
999 return 0;
1002 static const struct got_error *
1003 create_wanted_ref(const char *refname, struct got_object_id *id,
1004 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1006 const struct got_error *err;
1007 char *remote_refname;
1009 if (strncmp("refs/", refname, 5) == 0)
1010 refname += 5;
1012 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1013 remote_repo_name, refname) == -1)
1014 return got_error_from_errno("asprintf");
1016 err = create_ref(remote_refname, id, verbosity, repo);
1017 free(remote_refname);
1018 return err;
1021 static const struct got_error *
1022 cmd_clone(int argc, char *argv[])
1024 const struct got_error *error = NULL;
1025 const char *uri, *dirname;
1026 char *proto, *host, *port, *repo_name, *server_path;
1027 char *default_destdir = NULL, *id_str = NULL;
1028 const char *repo_path;
1029 struct got_repository *repo = NULL;
1030 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1031 struct got_pathlist_entry *pe;
1032 struct got_object_id *pack_hash = NULL;
1033 int ch, fetchfd = -1, fetchstatus;
1034 pid_t fetchpid = -1;
1035 struct got_fetch_progress_arg fpa;
1036 char *git_url = NULL;
1037 char *gitconfig_path = NULL;
1038 char *gitconfig = NULL;
1039 FILE *gitconfig_file = NULL;
1040 ssize_t n;
1041 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1042 int list_refs_only = 0;
1043 struct got_reference *head_symref = NULL;
1045 TAILQ_INIT(&refs);
1046 TAILQ_INIT(&symrefs);
1047 TAILQ_INIT(&wanted_branches);
1048 TAILQ_INIT(&wanted_refs);
1050 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1051 switch (ch) {
1052 case 'a':
1053 fetch_all_branches = 1;
1054 break;
1055 case 'b':
1056 error = got_pathlist_append(&wanted_branches,
1057 optarg, NULL);
1058 if (error)
1059 return error;
1060 break;
1061 case 'l':
1062 list_refs_only = 1;
1063 break;
1064 case 'm':
1065 mirror_references = 1;
1066 break;
1067 case 'v':
1068 if (verbosity < 0)
1069 verbosity = 0;
1070 else if (verbosity < 3)
1071 verbosity++;
1072 break;
1073 case 'q':
1074 verbosity = -1;
1075 break;
1076 case 'R':
1077 error = got_pathlist_append(&wanted_refs,
1078 optarg, NULL);
1079 if (error)
1080 return error;
1081 break;
1082 default:
1083 usage_clone();
1084 break;
1087 argc -= optind;
1088 argv += optind;
1090 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1091 errx(1, "-a and -b options are mutually exclusive");
1092 if (list_refs_only) {
1093 if (!TAILQ_EMPTY(&wanted_branches))
1094 errx(1, "-l and -b options are mutually exclusive");
1095 if (fetch_all_branches)
1096 errx(1, "-l and -a options are mutually exclusive");
1097 if (mirror_references)
1098 errx(1, "-l and -m options are mutually exclusive");
1099 if (verbosity == -1)
1100 errx(1, "-l and -q options are mutually exclusive");
1101 if (!TAILQ_EMPTY(&wanted_refs))
1102 errx(1, "-l and -R options are mutually exclusive");
1105 uri = argv[0];
1107 if (argc == 1)
1108 dirname = NULL;
1109 else if (argc == 2)
1110 dirname = argv[1];
1111 else
1112 usage_clone();
1114 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1115 &repo_name, argv[0]);
1116 if (error)
1117 goto done;
1119 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1120 host, port ? ":" : "", port ? port : "",
1121 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1122 error = got_error_from_errno("asprintf");
1123 goto done;
1126 if (strcmp(proto, "git") == 0) {
1127 #ifndef PROFILE
1128 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1129 "sendfd dns inet unveil", NULL) == -1)
1130 err(1, "pledge");
1131 #endif
1132 } else if (strcmp(proto, "git+ssh") == 0 ||
1133 strcmp(proto, "ssh") == 0) {
1134 #ifndef PROFILE
1135 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1136 "sendfd unveil", NULL) == -1)
1137 err(1, "pledge");
1138 #endif
1139 } else if (strcmp(proto, "http") == 0 ||
1140 strcmp(proto, "git+http") == 0) {
1141 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1142 goto done;
1143 } else {
1144 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1145 goto done;
1147 if (dirname == NULL) {
1148 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1149 error = got_error_from_errno("asprintf");
1150 goto done;
1152 repo_path = default_destdir;
1153 } else
1154 repo_path = dirname;
1156 if (!list_refs_only) {
1157 error = got_path_mkdir(repo_path);
1158 if (error)
1159 goto done;
1161 error = got_repo_init(repo_path);
1162 if (error)
1163 goto done;
1164 error = got_repo_open(&repo, repo_path, NULL);
1165 if (error)
1166 goto done;
1169 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1170 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1171 error = got_error_from_errno2("unveil",
1172 GOT_FETCH_PATH_SSH);
1173 goto done;
1176 error = apply_unveil(repo ? got_repo_get_path(repo) : NULL, 0, NULL);
1177 if (error)
1178 goto done;
1180 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1181 server_path, verbosity);
1182 if (error)
1183 goto done;
1185 if (verbosity >= 0)
1186 printf("Connected to %s%s%s\n", host,
1187 port ? ":" : "", port ? port : "");
1189 fpa.last_scaled_size[0] = '\0';
1190 fpa.last_p_indexed = -1;
1191 fpa.last_p_resolved = -1;
1192 fpa.verbosity = verbosity;
1193 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1194 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1195 fetch_all_branches, &wanted_branches, &wanted_refs,
1196 list_refs_only, verbosity, fetchfd, repo,
1197 fetch_progress, &fpa);
1198 if (error)
1199 goto done;
1201 if (list_refs_only) {
1202 error = list_remote_refs(&symrefs, &refs);
1203 goto done;
1206 error = got_object_id_str(&id_str, pack_hash);
1207 if (error)
1208 goto done;
1209 if (verbosity >= 0)
1210 printf("\nFetched %s.pack\n", id_str);
1211 free(id_str);
1213 /* Set up references provided with the pack file. */
1214 TAILQ_FOREACH(pe, &refs, entry) {
1215 const char *refname = pe->path;
1216 struct got_object_id *id = pe->data;
1217 char *remote_refname;
1219 if (is_wanted_ref(&wanted_refs, refname) &&
1220 !mirror_references) {
1221 error = create_wanted_ref(refname, id,
1222 GOT_FETCH_DEFAULT_REMOTE_NAME,
1223 verbosity - 1, repo);
1224 if (error)
1225 goto done;
1226 continue;
1229 error = create_ref(refname, id, verbosity - 1, repo);
1230 if (error)
1231 goto done;
1233 if (mirror_references)
1234 continue;
1236 if (strncmp("refs/heads/", refname, 11) != 0)
1237 continue;
1239 if (asprintf(&remote_refname,
1240 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1241 refname + 11) == -1) {
1242 error = got_error_from_errno("asprintf");
1243 goto done;
1245 error = create_ref(remote_refname, id, verbosity - 1, repo);
1246 free(remote_refname);
1247 if (error)
1248 goto done;
1251 /* Set the HEAD reference if the server provided one. */
1252 TAILQ_FOREACH(pe, &symrefs, entry) {
1253 struct got_reference *target_ref;
1254 const char *refname = pe->path;
1255 const char *target = pe->data;
1256 char *remote_refname = NULL, *remote_target = NULL;
1258 if (strcmp(refname, GOT_REF_HEAD) != 0)
1259 continue;
1261 error = got_ref_open(&target_ref, repo, target, 0);
1262 if (error) {
1263 if (error->code == GOT_ERR_NOT_REF) {
1264 error = NULL;
1265 continue;
1267 goto done;
1270 error = create_symref(refname, target_ref, verbosity, repo);
1271 got_ref_close(target_ref);
1272 if (error)
1273 goto done;
1275 if (mirror_references)
1276 continue;
1278 if (strncmp("refs/heads/", target, 11) != 0)
1279 continue;
1281 if (asprintf(&remote_refname,
1282 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1283 refname) == -1) {
1284 error = got_error_from_errno("asprintf");
1285 goto done;
1287 if (asprintf(&remote_target,
1288 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1289 target + 11) == -1) {
1290 error = got_error_from_errno("asprintf");
1291 free(remote_refname);
1292 goto done;
1294 error = got_ref_open(&target_ref, repo, remote_target, 0);
1295 if (error) {
1296 free(remote_refname);
1297 free(remote_target);
1298 if (error->code == GOT_ERR_NOT_REF) {
1299 error = NULL;
1300 continue;
1302 goto done;
1304 error = create_symref(remote_refname, target_ref,
1305 verbosity - 1, repo);
1306 free(remote_refname);
1307 free(remote_target);
1308 got_ref_close(target_ref);
1309 if (error)
1310 goto done;
1312 if (pe == NULL) {
1314 * We failed to set the HEAD reference. If we asked for
1315 * a set of wanted branches use the first of one of those
1316 * which could be fetched instead.
1318 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1319 const char *target = pe->path;
1320 struct got_reference *target_ref;
1322 error = got_ref_open(&target_ref, repo, target, 0);
1323 if (error) {
1324 if (error->code == GOT_ERR_NOT_REF) {
1325 error = NULL;
1326 continue;
1328 goto done;
1331 error = create_symref(GOT_REF_HEAD, target_ref,
1332 verbosity, repo);
1333 got_ref_close(target_ref);
1334 if (error)
1335 goto done;
1336 break;
1340 /* Create a config file git-fetch(1) can understand. */
1341 gitconfig_path = got_repo_get_path_gitconfig(repo);
1342 if (gitconfig_path == NULL) {
1343 error = got_error_from_errno("got_repo_get_path_gitconfig");
1344 goto done;
1346 gitconfig_file = fopen(gitconfig_path, "a");
1347 if (gitconfig_file == NULL) {
1348 error = got_error_from_errno2("fopen", gitconfig_path);
1349 goto done;
1351 if (mirror_references) {
1352 if (asprintf(&gitconfig,
1353 "[remote \"%s\"]\n"
1354 "\turl = %s\n"
1355 "\tfetch = +refs/*:refs/*\n"
1356 "\tmirror = true\n",
1357 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1358 error = got_error_from_errno("asprintf");
1359 goto done;
1361 } else if (fetch_all_branches) {
1362 if (asprintf(&gitconfig,
1363 "[remote \"%s\"]\n"
1364 "\turl = %s\n"
1365 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1366 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1367 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1368 error = got_error_from_errno("asprintf");
1369 goto done;
1371 } else {
1372 const char *branchname;
1375 * If the server specified a default branch, use just that one.
1376 * Otherwise fall back to fetching all branches on next fetch.
1378 if (head_symref) {
1379 branchname = got_ref_get_symref_target(head_symref);
1380 if (strncmp(branchname, "refs/heads/", 11) == 0)
1381 branchname += 11;
1382 } else
1383 branchname = "*"; /* fall back to all branches */
1384 if (asprintf(&gitconfig,
1385 "[remote \"%s\"]\n"
1386 "\turl = %s\n"
1387 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1388 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1389 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1390 branchname) == -1) {
1391 error = got_error_from_errno("asprintf");
1392 goto done;
1395 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1396 if (n != strlen(gitconfig)) {
1397 error = got_ferror(gitconfig_file, GOT_ERR_IO);
1398 goto done;
1401 if (verbosity >= 0)
1402 printf("Created %s repository '%s'\n",
1403 mirror_references ? "mirrored" : "cloned", repo_path);
1404 done:
1405 if (fetchpid > 0) {
1406 if (kill(fetchpid, SIGTERM) == -1)
1407 error = got_error_from_errno("kill");
1408 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1409 error = got_error_from_errno("waitpid");
1411 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1412 error = got_error_from_errno("close");
1413 if (gitconfig_file && fclose(gitconfig_file) == EOF && error == NULL)
1414 error = got_error_from_errno("fclose");
1415 if (repo)
1416 got_repo_close(repo);
1417 if (head_symref)
1418 got_ref_close(head_symref);
1419 TAILQ_FOREACH(pe, &refs, entry) {
1420 free((void *)pe->path);
1421 free(pe->data);
1423 got_pathlist_free(&refs);
1424 TAILQ_FOREACH(pe, &symrefs, entry) {
1425 free((void *)pe->path);
1426 free(pe->data);
1428 got_pathlist_free(&symrefs);
1429 got_pathlist_free(&wanted_branches);
1430 got_pathlist_free(&wanted_refs);
1431 free(pack_hash);
1432 free(proto);
1433 free(host);
1434 free(port);
1435 free(server_path);
1436 free(repo_name);
1437 free(default_destdir);
1438 free(gitconfig_path);
1439 free(git_url);
1440 return error;
1443 static const struct got_error *
1444 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1445 int replace_tags, int verbosity, struct got_repository *repo)
1447 const struct got_error *err = NULL;
1448 char *new_id_str = NULL;
1449 struct got_object_id *old_id = NULL;
1451 err = got_object_id_str(&new_id_str, new_id);
1452 if (err)
1453 goto done;
1455 if (!replace_tags &&
1456 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1457 err = got_ref_resolve(&old_id, repo, ref);
1458 if (err)
1459 goto done;
1460 if (got_object_id_cmp(old_id, new_id) == 0)
1461 goto done;
1462 if (verbosity >= 0) {
1463 printf("Rejecting update of existing tag %s: %s\n",
1464 got_ref_get_name(ref), new_id_str);
1466 goto done;
1469 if (got_ref_is_symbolic(ref)) {
1470 if (verbosity >= 0) {
1471 printf("Replacing reference %s: %s\n",
1472 got_ref_get_name(ref),
1473 got_ref_get_symref_target(ref));
1475 err = got_ref_change_symref_to_ref(ref, new_id);
1476 if (err)
1477 goto done;
1478 err = got_ref_write(ref, repo);
1479 if (err)
1480 goto done;
1481 } else {
1482 err = got_ref_resolve(&old_id, repo, ref);
1483 if (err)
1484 goto done;
1485 if (got_object_id_cmp(old_id, new_id) == 0)
1486 goto done;
1488 err = got_ref_change_ref(ref, new_id);
1489 if (err)
1490 goto done;
1491 err = got_ref_write(ref, repo);
1492 if (err)
1493 goto done;
1496 if (verbosity >= 0)
1497 printf("Updated reference %s: %s\n", got_ref_get_name(ref),
1498 new_id_str);
1499 done:
1500 free(old_id);
1501 free(new_id_str);
1502 return err;
1505 static const struct got_error *
1506 update_symref(const char *refname, struct got_reference *target_ref,
1507 int verbosity, struct got_repository *repo)
1509 const struct got_error *err = NULL, *unlock_err;
1510 struct got_reference *symref;
1512 err = got_ref_open(&symref, repo, refname, 1);
1513 if (err)
1514 return err;
1516 if (strcmp(got_ref_get_symref_target(symref),
1517 got_ref_get_name(target_ref)) == 0)
1518 goto done;
1520 err = got_ref_change_symref(symref, got_ref_get_name(target_ref));
1521 if (err)
1522 goto done;
1524 err = got_ref_write(symref, repo);
1525 if (err)
1526 goto done;
1528 if (verbosity >= 0)
1529 printf("Updated reference %s: %s\n", got_ref_get_name(symref),
1530 got_ref_get_symref_target(symref));
1531 done:
1532 unlock_err = got_ref_unlock(symref);
1533 if (unlock_err && err == NULL)
1534 err = unlock_err;
1535 got_ref_close(symref);
1536 return err;
1537 return NULL;
1540 __dead static void
1541 usage_fetch(void)
1543 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1544 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1545 "[remote-repository-name]\n",
1546 getprogname());
1547 exit(1);
1550 static const struct got_error *
1551 delete_missing_refs(struct got_pathlist_head *their_refs,
1552 int verbosity, struct got_repository *repo)
1554 const struct got_error *err = NULL;
1555 struct got_reflist_head my_refs;
1556 struct got_reflist_entry *re;
1557 struct got_pathlist_entry *pe;
1558 struct got_object_id *id;
1559 char *id_str;
1561 SIMPLEQ_INIT(&my_refs);
1563 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1564 if (err)
1565 return err;
1567 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1568 const char *refname = got_ref_get_name(re->ref);
1570 if (strncmp(refname, "refs/heads/", 11) != 0 &&
1571 strncmp(refname, "refs/tags/", 10) != 0)
1572 continue;
1574 TAILQ_FOREACH(pe, their_refs, entry) {
1575 if (strcmp(refname, pe->path) == 0)
1576 break;
1578 if (pe != NULL)
1579 continue;
1581 err = got_ref_resolve(&id, repo, re->ref);
1582 if (err)
1583 break;
1584 err = got_object_id_str(&id_str, id);
1585 free(id);
1586 if (err)
1587 break;
1589 free(id_str);
1590 err = got_ref_delete(re->ref, repo);
1591 if (err)
1592 break;
1593 if (verbosity >= 0) {
1594 printf("Deleted reference %s: %s\n",
1595 got_ref_get_name(re->ref), id_str);
1599 return err;
1602 static const struct got_error *
1603 update_wanted_ref(const char *refname, struct got_object_id *id,
1604 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1606 const struct got_error *err, *unlock_err;
1607 char *remote_refname;
1608 struct got_reference *ref;
1610 if (strncmp("refs/", refname, 5) == 0)
1611 refname += 5;
1613 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1614 remote_repo_name, refname) == -1)
1615 return got_error_from_errno("asprintf");
1617 err = got_ref_open(&ref, repo, remote_refname, 1);
1618 if (err) {
1619 if (err->code != GOT_ERR_NOT_REF)
1620 goto done;
1621 err = create_ref(remote_refname, id, verbosity, repo);
1622 } else {
1623 err = update_ref(ref, id, 0, verbosity, repo);
1624 unlock_err = got_ref_unlock(ref);
1625 if (unlock_err && err == NULL)
1626 err = unlock_err;
1627 got_ref_close(ref);
1629 done:
1630 free(remote_refname);
1631 return err;
1634 static const struct got_error *
1635 cmd_fetch(int argc, char *argv[])
1637 const struct got_error *error = NULL, *unlock_err;
1638 char *cwd = NULL, *repo_path = NULL;
1639 const char *remote_name;
1640 char *proto = NULL, *host = NULL, *port = NULL;
1641 char *repo_name = NULL, *server_path = NULL;
1642 struct got_remote_repo *remotes, *remote = NULL;
1643 int nremotes;
1644 char *id_str = NULL;
1645 struct got_repository *repo = NULL;
1646 struct got_worktree *worktree = NULL;
1647 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1648 struct got_pathlist_entry *pe;
1649 struct got_object_id *pack_hash = NULL;
1650 int i, ch, fetchfd = -1, fetchstatus;
1651 pid_t fetchpid = -1;
1652 struct got_fetch_progress_arg fpa;
1653 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
1654 int delete_refs = 0, replace_tags = 0;
1656 TAILQ_INIT(&refs);
1657 TAILQ_INIT(&symrefs);
1658 TAILQ_INIT(&wanted_branches);
1659 TAILQ_INIT(&wanted_refs);
1661 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
1662 switch (ch) {
1663 case 'a':
1664 fetch_all_branches = 1;
1665 break;
1666 case 'b':
1667 error = got_pathlist_append(&wanted_branches,
1668 optarg, NULL);
1669 if (error)
1670 return error;
1671 break;
1672 case 'd':
1673 delete_refs = 1;
1674 break;
1675 case 'l':
1676 list_refs_only = 1;
1677 break;
1678 case 'r':
1679 repo_path = realpath(optarg, NULL);
1680 if (repo_path == NULL)
1681 return got_error_from_errno2("realpath",
1682 optarg);
1683 got_path_strip_trailing_slashes(repo_path);
1684 break;
1685 case 't':
1686 replace_tags = 1;
1687 break;
1688 case 'v':
1689 if (verbosity < 0)
1690 verbosity = 0;
1691 else if (verbosity < 3)
1692 verbosity++;
1693 break;
1694 case 'q':
1695 verbosity = -1;
1696 break;
1697 case 'R':
1698 error = got_pathlist_append(&wanted_refs,
1699 optarg, NULL);
1700 if (error)
1701 return error;
1702 break;
1703 default:
1704 usage_fetch();
1705 break;
1708 argc -= optind;
1709 argv += optind;
1711 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1712 errx(1, "-a and -b options are mutually exclusive");
1713 if (list_refs_only) {
1714 if (!TAILQ_EMPTY(&wanted_branches))
1715 errx(1, "-l and -b options are mutually exclusive");
1716 if (fetch_all_branches)
1717 errx(1, "-l and -a options are mutually exclusive");
1718 if (delete_refs)
1719 errx(1, "-l and -d options are mutually exclusive");
1720 if (verbosity == -1)
1721 errx(1, "-l and -q options are mutually exclusive");
1724 if (argc == 0)
1725 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
1726 else if (argc == 1)
1727 remote_name = argv[0];
1728 else
1729 usage_fetch();
1731 cwd = getcwd(NULL, 0);
1732 if (cwd == NULL) {
1733 error = got_error_from_errno("getcwd");
1734 goto done;
1737 if (repo_path == NULL) {
1738 error = got_worktree_open(&worktree, cwd);
1739 if (error && error->code != GOT_ERR_NOT_WORKTREE)
1740 goto done;
1741 else
1742 error = NULL;
1743 if (worktree) {
1744 repo_path =
1745 strdup(got_worktree_get_repo_path(worktree));
1746 if (repo_path == NULL)
1747 error = got_error_from_errno("strdup");
1748 if (error)
1749 goto done;
1750 } else {
1751 repo_path = strdup(cwd);
1752 if (repo_path == NULL) {
1753 error = got_error_from_errno("strdup");
1754 goto done;
1759 error = got_repo_open(&repo, repo_path, NULL);
1760 if (error)
1761 goto done;
1763 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
1764 for (i = 0; i < nremotes; i++) {
1765 remote = &remotes[i];
1766 if (strcmp(remote->name, remote_name) == 0)
1767 break;
1769 if (i == nremotes) {
1770 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
1771 goto done;
1774 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1775 &repo_name, remote->url);
1776 if (error)
1777 goto done;
1779 if (strcmp(proto, "git") == 0) {
1780 #ifndef PROFILE
1781 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1782 "sendfd dns inet unveil", NULL) == -1)
1783 err(1, "pledge");
1784 #endif
1785 } else if (strcmp(proto, "git+ssh") == 0 ||
1786 strcmp(proto, "ssh") == 0) {
1787 #ifndef PROFILE
1788 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1789 "sendfd unveil", NULL) == -1)
1790 err(1, "pledge");
1791 #endif
1792 } else if (strcmp(proto, "http") == 0 ||
1793 strcmp(proto, "git+http") == 0) {
1794 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1795 goto done;
1796 } else {
1797 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1798 goto done;
1801 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1802 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1803 error = got_error_from_errno2("unveil",
1804 GOT_FETCH_PATH_SSH);
1805 goto done;
1808 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
1809 if (error)
1810 goto done;
1812 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1813 server_path, verbosity);
1814 if (error)
1815 goto done;
1817 if (verbosity >= 0)
1818 printf("Connected to \"%s\" %s%s%s\n", remote->name, host,
1819 port ? ":" : "", port ? port : "");
1821 fpa.last_scaled_size[0] = '\0';
1822 fpa.last_p_indexed = -1;
1823 fpa.last_p_resolved = -1;
1824 fpa.verbosity = verbosity;
1825 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
1826 remote->mirror_references, fetch_all_branches, &wanted_branches,
1827 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
1828 fetch_progress, &fpa);
1829 if (error)
1830 goto done;
1832 if (list_refs_only) {
1833 error = list_remote_refs(&symrefs, &refs);
1834 goto done;
1837 if (pack_hash == NULL) {
1838 if (verbosity >= 0)
1839 printf("Already up-to-date\n");
1840 if (delete_refs)
1841 error = delete_missing_refs(&refs, verbosity, repo);
1842 goto done;
1845 if (verbosity >= 0) {
1846 error = got_object_id_str(&id_str, pack_hash);
1847 if (error)
1848 goto done;
1849 printf("\nFetched %s.pack\n", id_str);
1850 free(id_str);
1851 id_str = NULL;
1854 /* Update references provided with the pack file. */
1855 TAILQ_FOREACH(pe, &refs, entry) {
1856 const char *refname = pe->path;
1857 struct got_object_id *id = pe->data;
1858 struct got_reference *ref;
1859 char *remote_refname;
1861 if (is_wanted_ref(&wanted_refs, refname) &&
1862 !remote->mirror_references) {
1863 error = update_wanted_ref(refname, id,
1864 remote->name, verbosity, repo);
1865 if (error)
1866 goto done;
1867 continue;
1870 if (remote->mirror_references ||
1871 strncmp("refs/tags/", refname, 10) == 0) {
1872 error = got_ref_open(&ref, repo, refname, 1);
1873 if (error) {
1874 if (error->code != GOT_ERR_NOT_REF)
1875 goto done;
1876 error = create_ref(refname, id, verbosity,
1877 repo);
1878 if (error)
1879 goto done;
1880 } else {
1881 error = update_ref(ref, id, replace_tags,
1882 verbosity, repo);
1883 unlock_err = got_ref_unlock(ref);
1884 if (unlock_err && error == NULL)
1885 error = unlock_err;
1886 got_ref_close(ref);
1887 if (error)
1888 goto done;
1890 } else if (strncmp("refs/heads/", refname, 11) == 0) {
1891 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1892 remote_name, refname + 11) == -1) {
1893 error = got_error_from_errno("asprintf");
1894 goto done;
1897 error = got_ref_open(&ref, repo, remote_refname, 1);
1898 if (error) {
1899 if (error->code != GOT_ERR_NOT_REF)
1900 goto done;
1901 error = create_ref(remote_refname, id,
1902 verbosity, repo);
1903 if (error)
1904 goto done;
1905 } else {
1906 error = update_ref(ref, id, replace_tags,
1907 verbosity, repo);
1908 unlock_err = got_ref_unlock(ref);
1909 if (unlock_err && error == NULL)
1910 error = unlock_err;
1911 got_ref_close(ref);
1912 if (error)
1913 goto done;
1916 /* Also create a local branch if none exists yet. */
1917 error = got_ref_open(&ref, repo, refname, 1);
1918 if (error) {
1919 if (error->code != GOT_ERR_NOT_REF)
1920 goto done;
1921 error = create_ref(refname, id, verbosity,
1922 repo);
1923 if (error)
1924 goto done;
1925 } else {
1926 unlock_err = got_ref_unlock(ref);
1927 if (unlock_err && error == NULL)
1928 error = unlock_err;
1929 got_ref_close(ref);
1933 if (delete_refs) {
1934 error = delete_missing_refs(&refs, verbosity, repo);
1935 if (error)
1936 goto done;
1939 if (!remote->mirror_references) {
1940 /* Update remote HEAD reference if the server provided one. */
1941 TAILQ_FOREACH(pe, &symrefs, entry) {
1942 struct got_reference *target_ref;
1943 const char *refname = pe->path;
1944 const char *target = pe->data;
1945 char *remote_refname = NULL, *remote_target = NULL;
1947 if (strcmp(refname, GOT_REF_HEAD) != 0)
1948 continue;
1950 if (strncmp("refs/heads/", target, 11) != 0)
1951 continue;
1953 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1954 remote->name, refname) == -1) {
1955 error = got_error_from_errno("asprintf");
1956 goto done;
1958 if (asprintf(&remote_target, "refs/remotes/%s/%s",
1959 remote->name, target + 11) == -1) {
1960 error = got_error_from_errno("asprintf");
1961 free(remote_refname);
1962 goto done;
1965 error = got_ref_open(&target_ref, repo, remote_target,
1966 0);
1967 if (error) {
1968 free(remote_refname);
1969 free(remote_target);
1970 if (error->code == GOT_ERR_NOT_REF) {
1971 error = NULL;
1972 continue;
1974 goto done;
1976 error = update_symref(remote_refname, target_ref,
1977 verbosity, repo);
1978 free(remote_refname);
1979 free(remote_target);
1980 got_ref_close(target_ref);
1981 if (error)
1982 goto done;
1985 done:
1986 if (fetchpid > 0) {
1987 if (kill(fetchpid, SIGTERM) == -1)
1988 error = got_error_from_errno("kill");
1989 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1990 error = got_error_from_errno("waitpid");
1992 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1993 error = got_error_from_errno("close");
1994 if (repo)
1995 got_repo_close(repo);
1996 if (worktree)
1997 got_worktree_close(worktree);
1998 TAILQ_FOREACH(pe, &refs, entry) {
1999 free((void *)pe->path);
2000 free(pe->data);
2002 got_pathlist_free(&refs);
2003 TAILQ_FOREACH(pe, &symrefs, entry) {
2004 free((void *)pe->path);
2005 free(pe->data);
2007 got_pathlist_free(&symrefs);
2008 got_pathlist_free(&wanted_branches);
2009 got_pathlist_free(&wanted_refs);
2010 free(id_str);
2011 free(cwd);
2012 free(repo_path);
2013 free(pack_hash);
2014 free(proto);
2015 free(host);
2016 free(port);
2017 free(server_path);
2018 free(repo_name);
2019 return error;
2023 __dead static void
2024 usage_checkout(void)
2026 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2027 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2028 exit(1);
2031 static void
2032 show_worktree_base_ref_warning(void)
2034 fprintf(stderr, "%s: warning: could not create a reference "
2035 "to the work tree's base commit; the commit could be "
2036 "garbage-collected by Git; making the repository "
2037 "writable and running 'got update' will prevent this\n",
2038 getprogname());
2041 struct got_checkout_progress_arg {
2042 const char *worktree_path;
2043 int had_base_commit_ref_error;
2046 static const struct got_error *
2047 checkout_progress(void *arg, unsigned char status, const char *path)
2049 struct got_checkout_progress_arg *a = arg;
2051 /* Base commit bump happens silently. */
2052 if (status == GOT_STATUS_BUMP_BASE)
2053 return NULL;
2055 if (status == GOT_STATUS_BASE_REF_ERR) {
2056 a->had_base_commit_ref_error = 1;
2057 return NULL;
2060 while (path[0] == '/')
2061 path++;
2063 printf("%c %s/%s\n", status, a->worktree_path, path);
2064 return NULL;
2067 static const struct got_error *
2068 check_cancelled(void *arg)
2070 if (sigint_received || sigpipe_received)
2071 return got_error(GOT_ERR_CANCELLED);
2072 return NULL;
2075 static const struct got_error *
2076 check_linear_ancestry(struct got_object_id *commit_id,
2077 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2078 struct got_repository *repo)
2080 const struct got_error *err = NULL;
2081 struct got_object_id *yca_id;
2083 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2084 commit_id, base_commit_id, repo, check_cancelled, NULL);
2085 if (err)
2086 return err;
2088 if (yca_id == NULL)
2089 return got_error(GOT_ERR_ANCESTRY);
2092 * Require a straight line of history between the target commit
2093 * and the work tree's base commit.
2095 * Non-linear situations such as this require a rebase:
2097 * (commit) D F (base_commit)
2098 * \ /
2099 * C E
2100 * \ /
2101 * B (yca)
2102 * |
2103 * A
2105 * 'got update' only handles linear cases:
2106 * Update forwards in time: A (base/yca) - B - C - D (commit)
2107 * Update backwards in time: D (base) - C - B - A (commit/yca)
2109 if (allow_forwards_in_time_only) {
2110 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2111 return got_error(GOT_ERR_ANCESTRY);
2112 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2113 got_object_id_cmp(base_commit_id, yca_id) != 0)
2114 return got_error(GOT_ERR_ANCESTRY);
2116 free(yca_id);
2117 return NULL;
2120 static const struct got_error *
2121 check_same_branch(struct got_object_id *commit_id,
2122 struct got_reference *head_ref, struct got_object_id *yca_id,
2123 struct got_repository *repo)
2125 const struct got_error *err = NULL;
2126 struct got_commit_graph *graph = NULL;
2127 struct got_object_id *head_commit_id = NULL;
2128 int is_same_branch = 0;
2130 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2131 if (err)
2132 goto done;
2134 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2135 is_same_branch = 1;
2136 goto done;
2138 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2139 is_same_branch = 1;
2140 goto done;
2143 err = got_commit_graph_open(&graph, "/", 1);
2144 if (err)
2145 goto done;
2147 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2148 check_cancelled, NULL);
2149 if (err)
2150 goto done;
2152 for (;;) {
2153 struct got_object_id *id;
2154 err = got_commit_graph_iter_next(&id, graph, repo,
2155 check_cancelled, NULL);
2156 if (err) {
2157 if (err->code == GOT_ERR_ITER_COMPLETED)
2158 err = NULL;
2159 break;
2162 if (id) {
2163 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2164 break;
2165 if (got_object_id_cmp(id, commit_id) == 0) {
2166 is_same_branch = 1;
2167 break;
2171 done:
2172 if (graph)
2173 got_commit_graph_close(graph);
2174 free(head_commit_id);
2175 if (!err && !is_same_branch)
2176 err = got_error(GOT_ERR_ANCESTRY);
2177 return err;
2180 static const struct got_error *
2181 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2183 static char msg[512];
2184 const char *branch_name;
2186 if (got_ref_is_symbolic(ref))
2187 branch_name = got_ref_get_symref_target(ref);
2188 else
2189 branch_name = got_ref_get_name(ref);
2191 if (strncmp("refs/heads/", branch_name, 11) == 0)
2192 branch_name += 11;
2194 snprintf(msg, sizeof(msg),
2195 "target commit is not contained in branch '%s'; "
2196 "the branch to use must be specified with -b; "
2197 "if necessary a new branch can be created for "
2198 "this commit with 'got branch -c %s BRANCH_NAME'",
2199 branch_name, commit_id_str);
2201 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2204 static const struct got_error *
2205 cmd_checkout(int argc, char *argv[])
2207 const struct got_error *error = NULL;
2208 struct got_repository *repo = NULL;
2209 struct got_reference *head_ref = NULL;
2210 struct got_worktree *worktree = NULL;
2211 char *repo_path = NULL;
2212 char *worktree_path = NULL;
2213 const char *path_prefix = "";
2214 const char *branch_name = GOT_REF_HEAD;
2215 char *commit_id_str = NULL;
2216 int ch, same_path_prefix, allow_nonempty = 0;
2217 struct got_pathlist_head paths;
2218 struct got_checkout_progress_arg cpa;
2220 TAILQ_INIT(&paths);
2222 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2223 switch (ch) {
2224 case 'b':
2225 branch_name = optarg;
2226 break;
2227 case 'c':
2228 commit_id_str = strdup(optarg);
2229 if (commit_id_str == NULL)
2230 return got_error_from_errno("strdup");
2231 break;
2232 case 'E':
2233 allow_nonempty = 1;
2234 break;
2235 case 'p':
2236 path_prefix = optarg;
2237 break;
2238 default:
2239 usage_checkout();
2240 /* NOTREACHED */
2244 argc -= optind;
2245 argv += optind;
2247 #ifndef PROFILE
2248 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2249 "unveil", NULL) == -1)
2250 err(1, "pledge");
2251 #endif
2252 if (argc == 1) {
2253 char *cwd, *base, *dotgit;
2254 repo_path = realpath(argv[0], NULL);
2255 if (repo_path == NULL)
2256 return got_error_from_errno2("realpath", argv[0]);
2257 cwd = getcwd(NULL, 0);
2258 if (cwd == NULL) {
2259 error = got_error_from_errno("getcwd");
2260 goto done;
2262 if (path_prefix[0]) {
2263 base = basename(path_prefix);
2264 if (base == NULL) {
2265 error = got_error_from_errno2("basename",
2266 path_prefix);
2267 goto done;
2269 } else {
2270 base = basename(repo_path);
2271 if (base == NULL) {
2272 error = got_error_from_errno2("basename",
2273 repo_path);
2274 goto done;
2277 dotgit = strstr(base, ".git");
2278 if (dotgit)
2279 *dotgit = '\0';
2280 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2281 error = got_error_from_errno("asprintf");
2282 free(cwd);
2283 goto done;
2285 free(cwd);
2286 } else if (argc == 2) {
2287 repo_path = realpath(argv[0], NULL);
2288 if (repo_path == NULL) {
2289 error = got_error_from_errno2("realpath", argv[0]);
2290 goto done;
2292 worktree_path = realpath(argv[1], NULL);
2293 if (worktree_path == NULL) {
2294 if (errno != ENOENT) {
2295 error = got_error_from_errno2("realpath",
2296 argv[1]);
2297 goto done;
2299 worktree_path = strdup(argv[1]);
2300 if (worktree_path == NULL) {
2301 error = got_error_from_errno("strdup");
2302 goto done;
2305 } else
2306 usage_checkout();
2308 got_path_strip_trailing_slashes(repo_path);
2309 got_path_strip_trailing_slashes(worktree_path);
2311 error = got_repo_open(&repo, repo_path, NULL);
2312 if (error != NULL)
2313 goto done;
2315 /* Pre-create work tree path for unveil(2) */
2316 error = got_path_mkdir(worktree_path);
2317 if (error) {
2318 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2319 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2320 goto done;
2321 if (!allow_nonempty &&
2322 !got_path_dir_is_empty(worktree_path)) {
2323 error = got_error_path(worktree_path,
2324 GOT_ERR_DIR_NOT_EMPTY);
2325 goto done;
2329 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2330 if (error)
2331 goto done;
2333 error = got_ref_open(&head_ref, repo, branch_name, 0);
2334 if (error != NULL)
2335 goto done;
2337 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2338 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2339 goto done;
2341 error = got_worktree_open(&worktree, worktree_path);
2342 if (error != NULL)
2343 goto done;
2345 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2346 path_prefix);
2347 if (error != NULL)
2348 goto done;
2349 if (!same_path_prefix) {
2350 error = got_error(GOT_ERR_PATH_PREFIX);
2351 goto done;
2354 if (commit_id_str) {
2355 struct got_object_id *commit_id;
2356 error = got_repo_match_object_id(&commit_id, NULL,
2357 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2358 if (error)
2359 goto done;
2360 error = check_linear_ancestry(commit_id,
2361 got_worktree_get_base_commit_id(worktree), 0, repo);
2362 if (error != NULL) {
2363 free(commit_id);
2364 if (error->code == GOT_ERR_ANCESTRY) {
2365 error = checkout_ancestry_error(
2366 head_ref, commit_id_str);
2368 goto done;
2370 error = check_same_branch(commit_id, head_ref, NULL, repo);
2371 if (error) {
2372 if (error->code == GOT_ERR_ANCESTRY) {
2373 error = checkout_ancestry_error(
2374 head_ref, commit_id_str);
2376 goto done;
2378 error = got_worktree_set_base_commit_id(worktree, repo,
2379 commit_id);
2380 free(commit_id);
2381 if (error)
2382 goto done;
2385 error = got_pathlist_append(&paths, "", NULL);
2386 if (error)
2387 goto done;
2388 cpa.worktree_path = worktree_path;
2389 cpa.had_base_commit_ref_error = 0;
2390 error = got_worktree_checkout_files(worktree, &paths, repo,
2391 checkout_progress, &cpa, check_cancelled, NULL);
2392 if (error != NULL)
2393 goto done;
2395 printf("Now shut up and hack\n");
2396 if (cpa.had_base_commit_ref_error)
2397 show_worktree_base_ref_warning();
2398 done:
2399 got_pathlist_free(&paths);
2400 free(commit_id_str);
2401 free(repo_path);
2402 free(worktree_path);
2403 return error;
2406 __dead static void
2407 usage_update(void)
2409 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2410 getprogname());
2411 exit(1);
2414 static const struct got_error *
2415 update_progress(void *arg, unsigned char status, const char *path)
2417 int *did_something = arg;
2419 if (status == GOT_STATUS_EXISTS ||
2420 status == GOT_STATUS_BASE_REF_ERR)
2421 return NULL;
2423 *did_something = 1;
2425 /* Base commit bump happens silently. */
2426 if (status == GOT_STATUS_BUMP_BASE)
2427 return NULL;
2429 while (path[0] == '/')
2430 path++;
2431 printf("%c %s\n", status, path);
2432 return NULL;
2435 static const struct got_error *
2436 switch_head_ref(struct got_reference *head_ref,
2437 struct got_object_id *commit_id, struct got_worktree *worktree,
2438 struct got_repository *repo)
2440 const struct got_error *err = NULL;
2441 char *base_id_str;
2442 int ref_has_moved = 0;
2444 /* Trivial case: switching between two different references. */
2445 if (strcmp(got_ref_get_name(head_ref),
2446 got_worktree_get_head_ref_name(worktree)) != 0) {
2447 printf("Switching work tree from %s to %s\n",
2448 got_worktree_get_head_ref_name(worktree),
2449 got_ref_get_name(head_ref));
2450 return got_worktree_set_head_ref(worktree, head_ref);
2453 err = check_linear_ancestry(commit_id,
2454 got_worktree_get_base_commit_id(worktree), 0, repo);
2455 if (err) {
2456 if (err->code != GOT_ERR_ANCESTRY)
2457 return err;
2458 ref_has_moved = 1;
2460 if (!ref_has_moved)
2461 return NULL;
2463 /* Switching to a rebased branch with the same reference name. */
2464 err = got_object_id_str(&base_id_str,
2465 got_worktree_get_base_commit_id(worktree));
2466 if (err)
2467 return err;
2468 printf("Reference %s now points at a different branch\n",
2469 got_worktree_get_head_ref_name(worktree));
2470 printf("Switching work tree from %s to %s\n", base_id_str,
2471 got_worktree_get_head_ref_name(worktree));
2472 return NULL;
2475 static const struct got_error *
2476 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2478 const struct got_error *err;
2479 int in_progress;
2481 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2482 if (err)
2483 return err;
2484 if (in_progress)
2485 return got_error(GOT_ERR_REBASING);
2487 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2488 if (err)
2489 return err;
2490 if (in_progress)
2491 return got_error(GOT_ERR_HISTEDIT_BUSY);
2493 return NULL;
2496 static const struct got_error *
2497 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2498 char *argv[], struct got_worktree *worktree)
2500 const struct got_error *err = NULL;
2501 char *path;
2502 int i;
2504 if (argc == 0) {
2505 path = strdup("");
2506 if (path == NULL)
2507 return got_error_from_errno("strdup");
2508 return got_pathlist_append(paths, path, NULL);
2511 for (i = 0; i < argc; i++) {
2512 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2513 if (err)
2514 break;
2515 err = got_pathlist_append(paths, path, NULL);
2516 if (err) {
2517 free(path);
2518 break;
2522 return err;
2525 static const struct got_error *
2526 cmd_update(int argc, char *argv[])
2528 const struct got_error *error = NULL;
2529 struct got_repository *repo = NULL;
2530 struct got_worktree *worktree = NULL;
2531 char *worktree_path = NULL;
2532 struct got_object_id *commit_id = NULL;
2533 char *commit_id_str = NULL;
2534 const char *branch_name = NULL;
2535 struct got_reference *head_ref = NULL;
2536 struct got_pathlist_head paths;
2537 struct got_pathlist_entry *pe;
2538 int ch, did_something = 0;
2540 TAILQ_INIT(&paths);
2542 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2543 switch (ch) {
2544 case 'b':
2545 branch_name = optarg;
2546 break;
2547 case 'c':
2548 commit_id_str = strdup(optarg);
2549 if (commit_id_str == NULL)
2550 return got_error_from_errno("strdup");
2551 break;
2552 default:
2553 usage_update();
2554 /* NOTREACHED */
2558 argc -= optind;
2559 argv += optind;
2561 #ifndef PROFILE
2562 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2563 "unveil", NULL) == -1)
2564 err(1, "pledge");
2565 #endif
2566 worktree_path = getcwd(NULL, 0);
2567 if (worktree_path == NULL) {
2568 error = got_error_from_errno("getcwd");
2569 goto done;
2571 error = got_worktree_open(&worktree, worktree_path);
2572 if (error)
2573 goto done;
2575 error = check_rebase_or_histedit_in_progress(worktree);
2576 if (error)
2577 goto done;
2579 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
2580 NULL);
2581 if (error != NULL)
2582 goto done;
2584 error = apply_unveil(got_repo_get_path(repo), 0,
2585 got_worktree_get_root_path(worktree));
2586 if (error)
2587 goto done;
2589 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2590 if (error)
2591 goto done;
2593 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
2594 got_worktree_get_head_ref_name(worktree), 0);
2595 if (error != NULL)
2596 goto done;
2597 if (commit_id_str == NULL) {
2598 error = got_ref_resolve(&commit_id, repo, head_ref);
2599 if (error != NULL)
2600 goto done;
2601 error = got_object_id_str(&commit_id_str, commit_id);
2602 if (error != NULL)
2603 goto done;
2604 } else {
2605 error = got_repo_match_object_id(&commit_id, NULL,
2606 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2607 free(commit_id_str);
2608 commit_id_str = NULL;
2609 if (error)
2610 goto done;
2611 error = got_object_id_str(&commit_id_str, commit_id);
2612 if (error)
2613 goto done;
2616 if (branch_name) {
2617 struct got_object_id *head_commit_id;
2618 TAILQ_FOREACH(pe, &paths, entry) {
2619 if (pe->path_len == 0)
2620 continue;
2621 error = got_error_msg(GOT_ERR_BAD_PATH,
2622 "switching between branches requires that "
2623 "the entire work tree gets updated");
2624 goto done;
2626 error = got_ref_resolve(&head_commit_id, repo, head_ref);
2627 if (error)
2628 goto done;
2629 error = check_linear_ancestry(commit_id, head_commit_id, 0,
2630 repo);
2631 free(head_commit_id);
2632 if (error != NULL)
2633 goto done;
2634 error = check_same_branch(commit_id, head_ref, NULL, repo);
2635 if (error)
2636 goto done;
2637 error = switch_head_ref(head_ref, commit_id, worktree, repo);
2638 if (error)
2639 goto done;
2640 } else {
2641 error = check_linear_ancestry(commit_id,
2642 got_worktree_get_base_commit_id(worktree), 0, repo);
2643 if (error != NULL) {
2644 if (error->code == GOT_ERR_ANCESTRY)
2645 error = got_error(GOT_ERR_BRANCH_MOVED);
2646 goto done;
2648 error = check_same_branch(commit_id, head_ref, NULL, repo);
2649 if (error)
2650 goto done;
2653 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
2654 commit_id) != 0) {
2655 error = got_worktree_set_base_commit_id(worktree, repo,
2656 commit_id);
2657 if (error)
2658 goto done;
2661 error = got_worktree_checkout_files(worktree, &paths, repo,
2662 update_progress, &did_something, check_cancelled, NULL);
2663 if (error != NULL)
2664 goto done;
2666 if (did_something)
2667 printf("Updated to commit %s\n", commit_id_str);
2668 else
2669 printf("Already up-to-date\n");
2670 done:
2671 free(worktree_path);
2672 TAILQ_FOREACH(pe, &paths, entry)
2673 free((char *)pe->path);
2674 got_pathlist_free(&paths);
2675 free(commit_id);
2676 free(commit_id_str);
2677 return error;
2680 static const struct got_error *
2681 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
2682 const char *path, int diff_context, int ignore_whitespace,
2683 struct got_repository *repo)
2685 const struct got_error *err = NULL;
2686 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
2688 if (blob_id1) {
2689 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
2690 if (err)
2691 goto done;
2694 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
2695 if (err)
2696 goto done;
2698 while (path[0] == '/')
2699 path++;
2700 err = got_diff_blob(blob1, blob2, path, path, diff_context,
2701 ignore_whitespace, stdout);
2702 done:
2703 if (blob1)
2704 got_object_blob_close(blob1);
2705 got_object_blob_close(blob2);
2706 return err;
2709 static const struct got_error *
2710 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
2711 const char *path, int diff_context, int ignore_whitespace,
2712 struct got_repository *repo)
2714 const struct got_error *err = NULL;
2715 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
2716 struct got_diff_blob_output_unidiff_arg arg;
2718 if (tree_id1) {
2719 err = got_object_open_as_tree(&tree1, repo, tree_id1);
2720 if (err)
2721 goto done;
2724 err = got_object_open_as_tree(&tree2, repo, tree_id2);
2725 if (err)
2726 goto done;
2728 arg.diff_context = diff_context;
2729 arg.ignore_whitespace = ignore_whitespace;
2730 arg.outfile = stdout;
2731 while (path[0] == '/')
2732 path++;
2733 err = got_diff_tree(tree1, tree2, path, path, repo,
2734 got_diff_blob_output_unidiff, &arg, 1);
2735 done:
2736 if (tree1)
2737 got_object_tree_close(tree1);
2738 if (tree2)
2739 got_object_tree_close(tree2);
2740 return err;
2743 static const struct got_error *
2744 print_patch(struct got_commit_object *commit, struct got_object_id *id,
2745 const char *path, int diff_context, struct got_repository *repo)
2747 const struct got_error *err = NULL;
2748 struct got_commit_object *pcommit = NULL;
2749 char *id_str1 = NULL, *id_str2 = NULL;
2750 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
2751 struct got_object_qid *qid;
2753 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
2754 if (qid != NULL) {
2755 err = got_object_open_as_commit(&pcommit, repo,
2756 qid->id);
2757 if (err)
2758 return err;
2761 if (path && path[0] != '\0') {
2762 int obj_type;
2763 err = got_object_id_by_path(&obj_id2, repo, id, path);
2764 if (err)
2765 goto done;
2766 err = got_object_id_str(&id_str2, obj_id2);
2767 if (err) {
2768 free(obj_id2);
2769 goto done;
2771 if (pcommit) {
2772 err = got_object_id_by_path(&obj_id1, repo,
2773 qid->id, path);
2774 if (err) {
2775 free(obj_id2);
2776 goto done;
2778 err = got_object_id_str(&id_str1, obj_id1);
2779 if (err) {
2780 free(obj_id2);
2781 goto done;
2784 err = got_object_get_type(&obj_type, repo, obj_id2);
2785 if (err) {
2786 free(obj_id2);
2787 goto done;
2789 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2790 switch (obj_type) {
2791 case GOT_OBJ_TYPE_BLOB:
2792 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
2793 0, repo);
2794 break;
2795 case GOT_OBJ_TYPE_TREE:
2796 err = diff_trees(obj_id1, obj_id2, path, diff_context,
2797 0, repo);
2798 break;
2799 default:
2800 err = got_error(GOT_ERR_OBJ_TYPE);
2801 break;
2803 free(obj_id1);
2804 free(obj_id2);
2805 } else {
2806 obj_id2 = got_object_commit_get_tree_id(commit);
2807 err = got_object_id_str(&id_str2, obj_id2);
2808 if (err)
2809 goto done;
2810 obj_id1 = got_object_commit_get_tree_id(pcommit);
2811 err = got_object_id_str(&id_str1, obj_id1);
2812 if (err)
2813 goto done;
2814 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2815 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
2817 done:
2818 free(id_str1);
2819 free(id_str2);
2820 if (pcommit)
2821 got_object_commit_close(pcommit);
2822 return err;
2825 static char *
2826 get_datestr(time_t *time, char *datebuf)
2828 struct tm mytm, *tm;
2829 char *p, *s;
2831 tm = gmtime_r(time, &mytm);
2832 if (tm == NULL)
2833 return NULL;
2834 s = asctime_r(tm, datebuf);
2835 if (s == NULL)
2836 return NULL;
2837 p = strchr(s, '\n');
2838 if (p)
2839 *p = '\0';
2840 return s;
2843 static const struct got_error *
2844 match_logmsg(int *have_match, struct got_object_id *id,
2845 struct got_commit_object *commit, regex_t *regex)
2847 const struct got_error *err = NULL;
2848 regmatch_t regmatch;
2849 char *id_str = NULL, *logmsg = NULL;
2851 *have_match = 0;
2853 err = got_object_id_str(&id_str, id);
2854 if (err)
2855 return err;
2857 err = got_object_commit_get_logmsg(&logmsg, commit);
2858 if (err)
2859 goto done;
2861 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2862 *have_match = 1;
2863 done:
2864 free(id_str);
2865 free(logmsg);
2866 return err;
2869 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
2871 static const struct got_error *
2872 print_commit(struct got_commit_object *commit, struct got_object_id *id,
2873 struct got_repository *repo, const char *path, int show_patch,
2874 int diff_context, struct got_reflist_head *refs)
2876 const struct got_error *err = NULL;
2877 char *id_str, *datestr, *logmsg0, *logmsg, *line;
2878 char datebuf[26];
2879 time_t committer_time;
2880 const char *author, *committer;
2881 char *refs_str = NULL;
2882 struct got_reflist_entry *re;
2884 SIMPLEQ_FOREACH(re, refs, entry) {
2885 char *s;
2886 const char *name;
2887 struct got_tag_object *tag = NULL;
2888 int cmp;
2890 name = got_ref_get_name(re->ref);
2891 if (strcmp(name, GOT_REF_HEAD) == 0)
2892 continue;
2893 if (strncmp(name, "refs/", 5) == 0)
2894 name += 5;
2895 if (strncmp(name, "got/", 4) == 0)
2896 continue;
2897 if (strncmp(name, "heads/", 6) == 0)
2898 name += 6;
2899 if (strncmp(name, "remotes/", 8) == 0)
2900 name += 8;
2901 if (strncmp(name, "tags/", 5) == 0) {
2902 err = got_object_open_as_tag(&tag, repo, re->id);
2903 if (err) {
2904 if (err->code != GOT_ERR_OBJ_TYPE)
2905 return err;
2906 /* Ref points at something other than a tag. */
2907 err = NULL;
2908 tag = NULL;
2911 cmp = got_object_id_cmp(tag ?
2912 got_object_tag_get_object_id(tag) : re->id, id);
2913 if (tag)
2914 got_object_tag_close(tag);
2915 if (cmp != 0)
2916 continue;
2917 s = refs_str;
2918 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
2919 name) == -1) {
2920 err = got_error_from_errno("asprintf");
2921 free(s);
2922 return err;
2924 free(s);
2926 err = got_object_id_str(&id_str, id);
2927 if (err)
2928 return err;
2930 printf(GOT_COMMIT_SEP_STR);
2931 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
2932 refs_str ? refs_str : "", refs_str ? ")" : "");
2933 free(id_str);
2934 id_str = NULL;
2935 free(refs_str);
2936 refs_str = NULL;
2937 printf("from: %s\n", got_object_commit_get_author(commit));
2938 committer_time = got_object_commit_get_committer_time(commit);
2939 datestr = get_datestr(&committer_time, datebuf);
2940 if (datestr)
2941 printf("date: %s UTC\n", datestr);
2942 author = got_object_commit_get_author(commit);
2943 committer = got_object_commit_get_committer(commit);
2944 if (strcmp(author, committer) != 0)
2945 printf("via: %s\n", committer);
2946 if (got_object_commit_get_nparents(commit) > 1) {
2947 const struct got_object_id_queue *parent_ids;
2948 struct got_object_qid *qid;
2949 int n = 1;
2950 parent_ids = got_object_commit_get_parent_ids(commit);
2951 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
2952 err = got_object_id_str(&id_str, qid->id);
2953 if (err)
2954 return err;
2955 printf("parent %d: %s\n", n++, id_str);
2956 free(id_str);
2960 err = got_object_commit_get_logmsg(&logmsg0, commit);
2961 if (err)
2962 return err;
2964 logmsg = logmsg0;
2965 do {
2966 line = strsep(&logmsg, "\n");
2967 if (line)
2968 printf(" %s\n", line);
2969 } while (line);
2970 free(logmsg0);
2972 if (show_patch) {
2973 err = print_patch(commit, id, path, diff_context, repo);
2974 if (err == 0)
2975 printf("\n");
2978 if (fflush(stdout) != 0 && err == NULL)
2979 err = got_error_from_errno("fflush");
2980 return err;
2983 static const struct got_error *
2984 print_commits(struct got_object_id *root_id, struct got_repository *repo,
2985 const char *path, int show_patch, const char *search_pattern,
2986 int diff_context, int limit, int log_branches,
2987 struct got_reflist_head *refs)
2989 const struct got_error *err;
2990 struct got_commit_graph *graph;
2991 regex_t regex;
2992 int have_match;
2994 if (search_pattern &&
2995 regcomp(&regex, search_pattern, REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
2996 return got_error_msg(GOT_ERR_REGEX, search_pattern);
2998 err = got_commit_graph_open(&graph, path, !log_branches);
2999 if (err)
3000 return err;
3001 err = got_commit_graph_iter_start(graph, root_id, repo,
3002 check_cancelled, NULL);
3003 if (err)
3004 goto done;
3005 for (;;) {
3006 struct got_commit_object *commit;
3007 struct got_object_id *id;
3009 if (sigint_received || sigpipe_received)
3010 break;
3012 err = got_commit_graph_iter_next(&id, graph, repo,
3013 check_cancelled, NULL);
3014 if (err) {
3015 if (err->code == GOT_ERR_ITER_COMPLETED)
3016 err = NULL;
3017 break;
3019 if (id == NULL)
3020 break;
3022 err = got_object_open_as_commit(&commit, repo, id);
3023 if (err)
3024 break;
3026 if (search_pattern) {
3027 err = match_logmsg(&have_match, id, commit, &regex);
3028 if (err) {
3029 got_object_commit_close(commit);
3030 break;
3032 if (have_match == 0) {
3033 got_object_commit_close(commit);
3034 continue;
3038 err = print_commit(commit, id, repo, path, show_patch,
3039 diff_context, refs);
3040 got_object_commit_close(commit);
3041 if (err || (limit && --limit == 0))
3042 break;
3044 done:
3045 if (search_pattern)
3046 regfree(&regex);
3047 got_commit_graph_close(graph);
3048 return err;
3051 __dead static void
3052 usage_log(void)
3054 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] [-p] "
3055 "[-s search-pattern] [-r repository-path] [path]\n", getprogname());
3056 exit(1);
3059 static int
3060 get_default_log_limit(void)
3062 const char *got_default_log_limit;
3063 long long n;
3064 const char *errstr;
3066 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3067 if (got_default_log_limit == NULL)
3068 return 0;
3069 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3070 if (errstr != NULL)
3071 return 0;
3072 return n;
3075 static const struct got_error *
3076 cmd_log(int argc, char *argv[])
3078 const struct got_error *error;
3079 struct got_repository *repo = NULL;
3080 struct got_worktree *worktree = NULL;
3081 struct got_commit_object *commit = NULL;
3082 struct got_object_id *id = NULL;
3083 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3084 const char *start_commit = NULL, *search_pattern = NULL;
3085 int diff_context = -1, ch;
3086 int show_patch = 0, limit = 0, log_branches = 0;
3087 const char *errstr;
3088 struct got_reflist_head refs;
3090 SIMPLEQ_INIT(&refs);
3092 #ifndef PROFILE
3093 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3094 NULL)
3095 == -1)
3096 err(1, "pledge");
3097 #endif
3099 limit = get_default_log_limit();
3101 while ((ch = getopt(argc, argv, "bpc:C:l:r:s:")) != -1) {
3102 switch (ch) {
3103 case 'p':
3104 show_patch = 1;
3105 break;
3106 case 'c':
3107 start_commit = optarg;
3108 break;
3109 case 'C':
3110 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3111 &errstr);
3112 if (errstr != NULL)
3113 err(1, "-C option %s", errstr);
3114 break;
3115 case 'l':
3116 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3117 if (errstr != NULL)
3118 err(1, "-l option %s", errstr);
3119 break;
3120 case 'b':
3121 log_branches = 1;
3122 break;
3123 case 'r':
3124 repo_path = realpath(optarg, NULL);
3125 if (repo_path == NULL)
3126 return got_error_from_errno2("realpath",
3127 optarg);
3128 got_path_strip_trailing_slashes(repo_path);
3129 break;
3130 case 's':
3131 search_pattern = optarg;
3132 break;
3133 default:
3134 usage_log();
3135 /* NOTREACHED */
3139 argc -= optind;
3140 argv += optind;
3142 if (diff_context == -1)
3143 diff_context = 3;
3144 else if (!show_patch)
3145 errx(1, "-C reguires -p");
3147 cwd = getcwd(NULL, 0);
3148 if (cwd == NULL) {
3149 error = got_error_from_errno("getcwd");
3150 goto done;
3153 error = got_worktree_open(&worktree, cwd);
3154 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3155 goto done;
3156 error = NULL;
3158 if (argc == 0) {
3159 path = strdup("");
3160 if (path == NULL) {
3161 error = got_error_from_errno("strdup");
3162 goto done;
3164 } else if (argc == 1) {
3165 if (worktree) {
3166 error = got_worktree_resolve_path(&path, worktree,
3167 argv[0]);
3168 if (error)
3169 goto done;
3170 } else {
3171 path = strdup(argv[0]);
3172 if (path == NULL) {
3173 error = got_error_from_errno("strdup");
3174 goto done;
3177 } else
3178 usage_log();
3180 if (repo_path == NULL) {
3181 repo_path = worktree ?
3182 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3184 if (repo_path == NULL) {
3185 error = got_error_from_errno("strdup");
3186 goto done;
3189 error = got_repo_open(&repo, repo_path, NULL);
3190 if (error != NULL)
3191 goto done;
3193 error = apply_unveil(got_repo_get_path(repo), 1,
3194 worktree ? got_worktree_get_root_path(worktree) : NULL);
3195 if (error)
3196 goto done;
3198 if (start_commit == NULL) {
3199 struct got_reference *head_ref;
3200 error = got_ref_open(&head_ref, repo,
3201 worktree ? got_worktree_get_head_ref_name(worktree)
3202 : GOT_REF_HEAD, 0);
3203 if (error != NULL)
3204 return error;
3205 error = got_ref_resolve(&id, repo, head_ref);
3206 got_ref_close(head_ref);
3207 if (error != NULL)
3208 return error;
3209 error = got_object_open_as_commit(&commit, repo, id);
3210 } else {
3211 struct got_reference *ref;
3212 error = got_ref_open(&ref, repo, start_commit, 0);
3213 if (error == NULL) {
3214 int obj_type;
3215 error = got_ref_resolve(&id, repo, ref);
3216 got_ref_close(ref);
3217 if (error != NULL)
3218 goto done;
3219 error = got_object_get_type(&obj_type, repo, id);
3220 if (error != NULL)
3221 goto done;
3222 if (obj_type == GOT_OBJ_TYPE_TAG) {
3223 struct got_tag_object *tag;
3224 error = got_object_open_as_tag(&tag, repo, id);
3225 if (error != NULL)
3226 goto done;
3227 if (got_object_tag_get_object_type(tag) !=
3228 GOT_OBJ_TYPE_COMMIT) {
3229 got_object_tag_close(tag);
3230 error = got_error(GOT_ERR_OBJ_TYPE);
3231 goto done;
3233 free(id);
3234 id = got_object_id_dup(
3235 got_object_tag_get_object_id(tag));
3236 if (id == NULL)
3237 error = got_error_from_errno(
3238 "got_object_id_dup");
3239 got_object_tag_close(tag);
3240 if (error)
3241 goto done;
3242 } else if (obj_type != GOT_OBJ_TYPE_COMMIT) {
3243 error = got_error(GOT_ERR_OBJ_TYPE);
3244 goto done;
3246 error = got_object_open_as_commit(&commit, repo, id);
3247 if (error != NULL)
3248 goto done;
3250 if (commit == NULL) {
3251 error = got_repo_match_object_id_prefix(&id,
3252 start_commit, GOT_OBJ_TYPE_COMMIT, repo);
3253 if (error != NULL)
3254 return error;
3257 if (error != NULL)
3258 goto done;
3260 if (worktree) {
3261 const char *prefix = got_worktree_get_path_prefix(worktree);
3262 char *p;
3263 if (asprintf(&p, "%s%s%s", prefix,
3264 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3265 error = got_error_from_errno("asprintf");
3266 goto done;
3268 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3269 free(p);
3270 } else
3271 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3272 if (error != NULL)
3273 goto done;
3274 if (in_repo_path) {
3275 free(path);
3276 path = in_repo_path;
3279 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3280 if (error)
3281 goto done;
3283 error = print_commits(id, repo, path, show_patch, search_pattern,
3284 diff_context, limit, log_branches, &refs);
3285 done:
3286 free(path);
3287 free(repo_path);
3288 free(cwd);
3289 free(id);
3290 if (worktree)
3291 got_worktree_close(worktree);
3292 if (repo) {
3293 const struct got_error *repo_error;
3294 repo_error = got_repo_close(repo);
3295 if (error == NULL)
3296 error = repo_error;
3298 got_ref_list_free(&refs);
3299 return error;
3302 __dead static void
3303 usage_diff(void)
3305 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3306 "[-w] [object1 object2 | path]\n", getprogname());
3307 exit(1);
3310 struct print_diff_arg {
3311 struct got_repository *repo;
3312 struct got_worktree *worktree;
3313 int diff_context;
3314 const char *id_str;
3315 int header_shown;
3316 int diff_staged;
3317 int ignore_whitespace;
3320 static const struct got_error *
3321 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3322 const char *path, struct got_object_id *blob_id,
3323 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3324 int dirfd, const char *de_name)
3326 struct print_diff_arg *a = arg;
3327 const struct got_error *err = NULL;
3328 struct got_blob_object *blob1 = NULL;
3329 int fd = -1;
3330 FILE *f2 = NULL;
3331 char *abspath = NULL, *label1 = NULL;
3332 struct stat sb;
3334 if (a->diff_staged) {
3335 if (staged_status != GOT_STATUS_MODIFY &&
3336 staged_status != GOT_STATUS_ADD &&
3337 staged_status != GOT_STATUS_DELETE)
3338 return NULL;
3339 } else {
3340 if (staged_status == GOT_STATUS_DELETE)
3341 return NULL;
3342 if (status == GOT_STATUS_NONEXISTENT)
3343 return got_error_set_errno(ENOENT, path);
3344 if (status != GOT_STATUS_MODIFY &&
3345 status != GOT_STATUS_ADD &&
3346 status != GOT_STATUS_DELETE &&
3347 status != GOT_STATUS_CONFLICT)
3348 return NULL;
3351 if (!a->header_shown) {
3352 printf("diff %s %s%s\n", a->id_str,
3353 got_worktree_get_root_path(a->worktree),
3354 a->diff_staged ? " (staged changes)" : "");
3355 a->header_shown = 1;
3358 if (a->diff_staged) {
3359 const char *label1 = NULL, *label2 = NULL;
3360 switch (staged_status) {
3361 case GOT_STATUS_MODIFY:
3362 label1 = path;
3363 label2 = path;
3364 break;
3365 case GOT_STATUS_ADD:
3366 label2 = path;
3367 break;
3368 case GOT_STATUS_DELETE:
3369 label1 = path;
3370 break;
3371 default:
3372 return got_error(GOT_ERR_FILE_STATUS);
3374 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
3375 label1, label2, a->diff_context, a->ignore_whitespace,
3376 a->repo, stdout);
3379 if (staged_status == GOT_STATUS_ADD ||
3380 staged_status == GOT_STATUS_MODIFY) {
3381 char *id_str;
3382 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
3383 8192);
3384 if (err)
3385 goto done;
3386 err = got_object_id_str(&id_str, staged_blob_id);
3387 if (err)
3388 goto done;
3389 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
3390 err = got_error_from_errno("asprintf");
3391 free(id_str);
3392 goto done;
3394 free(id_str);
3395 } else if (status != GOT_STATUS_ADD) {
3396 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
3397 if (err)
3398 goto done;
3401 if (status != GOT_STATUS_DELETE) {
3402 if (asprintf(&abspath, "%s/%s",
3403 got_worktree_get_root_path(a->worktree), path) == -1) {
3404 err = got_error_from_errno("asprintf");
3405 goto done;
3408 if (dirfd != -1) {
3409 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
3410 if (fd == -1) {
3411 err = got_error_from_errno2("openat", abspath);
3412 goto done;
3414 } else {
3415 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
3416 if (fd == -1) {
3417 err = got_error_from_errno2("open", abspath);
3418 goto done;
3421 if (fstat(fd, &sb) == -1) {
3422 err = got_error_from_errno2("fstat", abspath);
3423 goto done;
3425 f2 = fdopen(fd, "r");
3426 if (f2 == NULL) {
3427 err = got_error_from_errno2("fdopen", abspath);
3428 goto done;
3430 fd = -1;
3431 } else
3432 sb.st_size = 0;
3434 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
3435 a->diff_context, a->ignore_whitespace, stdout);
3436 done:
3437 if (blob1)
3438 got_object_blob_close(blob1);
3439 if (f2 && fclose(f2) == EOF && err == NULL)
3440 err = got_error_from_errno("fclose");
3441 if (fd != -1 && close(fd) == -1 && err == NULL)
3442 err = got_error_from_errno("close");
3443 free(abspath);
3444 return err;
3447 static const struct got_error *
3448 cmd_diff(int argc, char *argv[])
3450 const struct got_error *error;
3451 struct got_repository *repo = NULL;
3452 struct got_worktree *worktree = NULL;
3453 char *cwd = NULL, *repo_path = NULL;
3454 struct got_object_id *id1 = NULL, *id2 = NULL;
3455 const char *id_str1 = NULL, *id_str2 = NULL;
3456 char *label1 = NULL, *label2 = NULL;
3457 int type1, type2;
3458 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
3459 const char *errstr;
3460 char *path = NULL;
3462 #ifndef PROFILE
3463 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3464 NULL) == -1)
3465 err(1, "pledge");
3466 #endif
3468 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
3469 switch (ch) {
3470 case 'C':
3471 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3472 &errstr);
3473 if (errstr != NULL)
3474 err(1, "-C option %s", errstr);
3475 break;
3476 case 'r':
3477 repo_path = realpath(optarg, NULL);
3478 if (repo_path == NULL)
3479 return got_error_from_errno2("realpath",
3480 optarg);
3481 got_path_strip_trailing_slashes(repo_path);
3482 break;
3483 case 's':
3484 diff_staged = 1;
3485 break;
3486 case 'w':
3487 ignore_whitespace = 1;
3488 break;
3489 default:
3490 usage_diff();
3491 /* NOTREACHED */
3495 argc -= optind;
3496 argv += optind;
3498 cwd = getcwd(NULL, 0);
3499 if (cwd == NULL) {
3500 error = got_error_from_errno("getcwd");
3501 goto done;
3503 if (argc <= 1) {
3504 if (repo_path)
3505 errx(1,
3506 "-r option can't be used when diffing a work tree");
3507 error = got_worktree_open(&worktree, cwd);
3508 if (error)
3509 goto done;
3510 repo_path = strdup(got_worktree_get_repo_path(worktree));
3511 if (repo_path == NULL) {
3512 error = got_error_from_errno("strdup");
3513 goto done;
3515 if (argc == 1) {
3516 error = got_worktree_resolve_path(&path, worktree,
3517 argv[0]);
3518 if (error)
3519 goto done;
3520 } else {
3521 path = strdup("");
3522 if (path == NULL) {
3523 error = got_error_from_errno("strdup");
3524 goto done;
3527 } else if (argc == 2) {
3528 if (diff_staged)
3529 errx(1, "-s option can't be used when diffing "
3530 "objects in repository");
3531 id_str1 = argv[0];
3532 id_str2 = argv[1];
3533 if (repo_path == NULL) {
3534 error = got_worktree_open(&worktree, cwd);
3535 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3536 goto done;
3537 if (worktree) {
3538 repo_path = strdup(
3539 got_worktree_get_repo_path(worktree));
3540 if (repo_path == NULL) {
3541 error = got_error_from_errno("strdup");
3542 goto done;
3544 } else {
3545 repo_path = strdup(cwd);
3546 if (repo_path == NULL) {
3547 error = got_error_from_errno("strdup");
3548 goto done;
3552 } else
3553 usage_diff();
3555 error = got_repo_open(&repo, repo_path, NULL);
3556 free(repo_path);
3557 if (error != NULL)
3558 goto done;
3560 error = apply_unveil(got_repo_get_path(repo), 1,
3561 worktree ? got_worktree_get_root_path(worktree) : NULL);
3562 if (error)
3563 goto done;
3565 if (argc <= 1) {
3566 struct print_diff_arg arg;
3567 struct got_pathlist_head paths;
3568 char *id_str;
3570 TAILQ_INIT(&paths);
3572 error = got_object_id_str(&id_str,
3573 got_worktree_get_base_commit_id(worktree));
3574 if (error)
3575 goto done;
3576 arg.repo = repo;
3577 arg.worktree = worktree;
3578 arg.diff_context = diff_context;
3579 arg.id_str = id_str;
3580 arg.header_shown = 0;
3581 arg.diff_staged = diff_staged;
3582 arg.ignore_whitespace = ignore_whitespace;
3584 error = got_pathlist_append(&paths, path, NULL);
3585 if (error)
3586 goto done;
3588 error = got_worktree_status(worktree, &paths, repo, print_diff,
3589 &arg, check_cancelled, NULL);
3590 free(id_str);
3591 got_pathlist_free(&paths);
3592 goto done;
3595 error = got_repo_match_object_id(&id1, &label1, id_str1,
3596 GOT_OBJ_TYPE_ANY, 1, repo);
3597 if (error)
3598 goto done;
3600 error = got_repo_match_object_id(&id2, &label2, id_str2,
3601 GOT_OBJ_TYPE_ANY, 1, repo);
3602 if (error)
3603 goto done;
3605 error = got_object_get_type(&type1, repo, id1);
3606 if (error)
3607 goto done;
3609 error = got_object_get_type(&type2, repo, id2);
3610 if (error)
3611 goto done;
3613 if (type1 != type2) {
3614 error = got_error(GOT_ERR_OBJ_TYPE);
3615 goto done;
3618 switch (type1) {
3619 case GOT_OBJ_TYPE_BLOB:
3620 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
3621 diff_context, ignore_whitespace, repo, stdout);
3622 break;
3623 case GOT_OBJ_TYPE_TREE:
3624 error = got_diff_objects_as_trees(id1, id2, "", "",
3625 diff_context, ignore_whitespace, repo, stdout);
3626 break;
3627 case GOT_OBJ_TYPE_COMMIT:
3628 printf("diff %s %s\n", label1, label2);
3629 error = got_diff_objects_as_commits(id1, id2, diff_context,
3630 ignore_whitespace, repo, stdout);
3631 break;
3632 default:
3633 error = got_error(GOT_ERR_OBJ_TYPE);
3635 done:
3636 free(label1);
3637 free(label2);
3638 free(id1);
3639 free(id2);
3640 free(path);
3641 if (worktree)
3642 got_worktree_close(worktree);
3643 if (repo) {
3644 const struct got_error *repo_error;
3645 repo_error = got_repo_close(repo);
3646 if (error == NULL)
3647 error = repo_error;
3649 return error;
3652 __dead static void
3653 usage_blame(void)
3655 fprintf(stderr,
3656 "usage: %s blame [-c commit] [-r repository-path] path\n",
3657 getprogname());
3658 exit(1);
3661 struct blame_line {
3662 int annotated;
3663 char *id_str;
3664 char *committer;
3665 char datebuf[11]; /* YYYY-MM-DD + NUL */
3668 struct blame_cb_args {
3669 struct blame_line *lines;
3670 int nlines;
3671 int nlines_prec;
3672 int lineno_cur;
3673 off_t *line_offsets;
3674 FILE *f;
3675 struct got_repository *repo;
3678 static const struct got_error *
3679 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
3681 const struct got_error *err = NULL;
3682 struct blame_cb_args *a = arg;
3683 struct blame_line *bline;
3684 char *line = NULL;
3685 size_t linesize = 0;
3686 struct got_commit_object *commit = NULL;
3687 off_t offset;
3688 struct tm tm;
3689 time_t committer_time;
3691 if (nlines != a->nlines ||
3692 (lineno != -1 && lineno < 1) || lineno > a->nlines)
3693 return got_error(GOT_ERR_RANGE);
3695 if (sigint_received)
3696 return got_error(GOT_ERR_ITER_COMPLETED);
3698 if (lineno == -1)
3699 return NULL; /* no change in this commit */
3701 /* Annotate this line. */
3702 bline = &a->lines[lineno - 1];
3703 if (bline->annotated)
3704 return NULL;
3705 err = got_object_id_str(&bline->id_str, id);
3706 if (err)
3707 return err;
3709 err = got_object_open_as_commit(&commit, a->repo, id);
3710 if (err)
3711 goto done;
3713 bline->committer = strdup(got_object_commit_get_committer(commit));
3714 if (bline->committer == NULL) {
3715 err = got_error_from_errno("strdup");
3716 goto done;
3719 committer_time = got_object_commit_get_committer_time(commit);
3720 if (localtime_r(&committer_time, &tm) == NULL)
3721 return got_error_from_errno("localtime_r");
3722 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
3723 &tm) >= sizeof(bline->datebuf)) {
3724 err = got_error(GOT_ERR_NO_SPACE);
3725 goto done;
3727 bline->annotated = 1;
3729 /* Print lines annotated so far. */
3730 bline = &a->lines[a->lineno_cur - 1];
3731 if (!bline->annotated)
3732 goto done;
3734 offset = a->line_offsets[a->lineno_cur - 1];
3735 if (fseeko(a->f, offset, SEEK_SET) == -1) {
3736 err = got_error_from_errno("fseeko");
3737 goto done;
3740 while (bline->annotated) {
3741 char *smallerthan, *at, *nl, *committer;
3742 size_t len;
3744 if (getline(&line, &linesize, a->f) == -1) {
3745 if (ferror(a->f))
3746 err = got_error_from_errno("getline");
3747 break;
3750 committer = bline->committer;
3751 smallerthan = strchr(committer, '<');
3752 if (smallerthan && smallerthan[1] != '\0')
3753 committer = smallerthan + 1;
3754 at = strchr(committer, '@');
3755 if (at)
3756 *at = '\0';
3757 len = strlen(committer);
3758 if (len >= 9)
3759 committer[8] = '\0';
3761 nl = strchr(line, '\n');
3762 if (nl)
3763 *nl = '\0';
3764 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
3765 bline->id_str, bline->datebuf, committer, line);
3767 a->lineno_cur++;
3768 bline = &a->lines[a->lineno_cur - 1];
3770 done:
3771 if (commit)
3772 got_object_commit_close(commit);
3773 free(line);
3774 return err;
3777 static const struct got_error *
3778 cmd_blame(int argc, char *argv[])
3780 const struct got_error *error;
3781 struct got_repository *repo = NULL;
3782 struct got_worktree *worktree = NULL;
3783 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
3784 struct got_object_id *obj_id = NULL;
3785 struct got_object_id *commit_id = NULL;
3786 struct got_blob_object *blob = NULL;
3787 char *commit_id_str = NULL;
3788 struct blame_cb_args bca;
3789 int ch, obj_type, i;
3790 size_t filesize;
3792 memset(&bca, 0, sizeof(bca));
3794 #ifndef PROFILE
3795 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3796 NULL) == -1)
3797 err(1, "pledge");
3798 #endif
3800 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
3801 switch (ch) {
3802 case 'c':
3803 commit_id_str = optarg;
3804 break;
3805 case 'r':
3806 repo_path = realpath(optarg, NULL);
3807 if (repo_path == NULL)
3808 return got_error_from_errno2("realpath",
3809 optarg);
3810 got_path_strip_trailing_slashes(repo_path);
3811 break;
3812 default:
3813 usage_blame();
3814 /* NOTREACHED */
3818 argc -= optind;
3819 argv += optind;
3821 if (argc == 1)
3822 path = argv[0];
3823 else
3824 usage_blame();
3826 cwd = getcwd(NULL, 0);
3827 if (cwd == NULL) {
3828 error = got_error_from_errno("getcwd");
3829 goto done;
3831 if (repo_path == NULL) {
3832 error = got_worktree_open(&worktree, cwd);
3833 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3834 goto done;
3835 else
3836 error = NULL;
3837 if (worktree) {
3838 repo_path =
3839 strdup(got_worktree_get_repo_path(worktree));
3840 if (repo_path == NULL) {
3841 error = got_error_from_errno("strdup");
3842 if (error)
3843 goto done;
3845 } else {
3846 repo_path = strdup(cwd);
3847 if (repo_path == NULL) {
3848 error = got_error_from_errno("strdup");
3849 goto done;
3854 error = got_repo_open(&repo, repo_path, NULL);
3855 if (error != NULL)
3856 goto done;
3858 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
3859 if (error)
3860 goto done;
3862 if (worktree) {
3863 const char *prefix = got_worktree_get_path_prefix(worktree);
3864 char *p, *worktree_subdir = cwd +
3865 strlen(got_worktree_get_root_path(worktree));
3866 if (asprintf(&p, "%s%s%s%s%s",
3867 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
3868 worktree_subdir, worktree_subdir[0] ? "/" : "",
3869 path) == -1) {
3870 error = got_error_from_errno("asprintf");
3871 goto done;
3873 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3874 free(p);
3875 } else {
3876 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3878 if (error)
3879 goto done;
3881 if (commit_id_str == NULL) {
3882 struct got_reference *head_ref;
3883 error = got_ref_open(&head_ref, repo, worktree ?
3884 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
3885 if (error != NULL)
3886 goto done;
3887 error = got_ref_resolve(&commit_id, repo, head_ref);
3888 got_ref_close(head_ref);
3889 if (error != NULL)
3890 goto done;
3891 } else {
3892 error = got_repo_match_object_id(&commit_id, NULL,
3893 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
3894 if (error)
3895 goto done;
3898 error = got_object_id_by_path(&obj_id, repo, commit_id, in_repo_path);
3899 if (error)
3900 goto done;
3902 error = got_object_get_type(&obj_type, repo, obj_id);
3903 if (error)
3904 goto done;
3906 if (obj_type != GOT_OBJ_TYPE_BLOB) {
3907 error = got_error(GOT_ERR_OBJ_TYPE);
3908 goto done;
3911 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
3912 if (error)
3913 goto done;
3914 bca.f = got_opentemp();
3915 if (bca.f == NULL) {
3916 error = got_error_from_errno("got_opentemp");
3917 goto done;
3919 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
3920 &bca.line_offsets, bca.f, blob);
3921 if (error || bca.nlines == 0)
3922 goto done;
3924 /* Don't include \n at EOF in the blame line count. */
3925 if (bca.line_offsets[bca.nlines - 1] == filesize)
3926 bca.nlines--;
3928 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
3929 if (bca.lines == NULL) {
3930 error = got_error_from_errno("calloc");
3931 goto done;
3933 bca.lineno_cur = 1;
3934 bca.nlines_prec = 0;
3935 i = bca.nlines;
3936 while (i > 0) {
3937 i /= 10;
3938 bca.nlines_prec++;
3940 bca.repo = repo;
3942 error = got_blame(in_repo_path, commit_id, repo, blame_cb, &bca,
3943 check_cancelled, NULL);
3944 done:
3945 free(in_repo_path);
3946 free(repo_path);
3947 free(cwd);
3948 free(commit_id);
3949 free(obj_id);
3950 if (blob)
3951 got_object_blob_close(blob);
3952 if (worktree)
3953 got_worktree_close(worktree);
3954 if (repo) {
3955 const struct got_error *repo_error;
3956 repo_error = got_repo_close(repo);
3957 if (error == NULL)
3958 error = repo_error;
3960 if (bca.lines) {
3961 for (i = 0; i < bca.nlines; i++) {
3962 struct blame_line *bline = &bca.lines[i];
3963 free(bline->id_str);
3964 free(bline->committer);
3966 free(bca.lines);
3968 free(bca.line_offsets);
3969 if (bca.f && fclose(bca.f) == EOF && error == NULL)
3970 error = got_error_from_errno("fclose");
3971 return error;
3974 __dead static void
3975 usage_tree(void)
3977 fprintf(stderr,
3978 "usage: %s tree [-c commit] [-r repository-path] [-iR] path\n",
3979 getprogname());
3980 exit(1);
3983 static void
3984 print_entry(struct got_tree_entry *te, const char *id, const char *path,
3985 const char *root_path)
3987 int is_root_path = (strcmp(path, root_path) == 0);
3988 const char *modestr = "";
3989 mode_t mode = got_tree_entry_get_mode(te);
3991 path += strlen(root_path);
3992 while (path[0] == '/')
3993 path++;
3995 if (got_object_tree_entry_is_submodule(te))
3996 modestr = "$";
3997 else if (S_ISLNK(mode))
3998 modestr = "@";
3999 else if (S_ISDIR(mode))
4000 modestr = "/";
4001 else if (mode & S_IXUSR)
4002 modestr = "*";
4004 printf("%s%s%s%s%s\n", id ? id : "", path,
4005 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr);
4008 static const struct got_error *
4009 print_tree(const char *path, struct got_object_id *commit_id,
4010 int show_ids, int recurse, const char *root_path,
4011 struct got_repository *repo)
4013 const struct got_error *err = NULL;
4014 struct got_object_id *tree_id = NULL;
4015 struct got_tree_object *tree = NULL;
4016 int nentries, i;
4018 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4019 if (err)
4020 goto done;
4022 err = got_object_open_as_tree(&tree, repo, tree_id);
4023 if (err)
4024 goto done;
4025 nentries = got_object_tree_get_nentries(tree);
4026 for (i = 0; i < nentries; i++) {
4027 struct got_tree_entry *te;
4028 char *id = NULL;
4030 if (sigint_received || sigpipe_received)
4031 break;
4033 te = got_object_tree_get_entry(tree, i);
4034 if (show_ids) {
4035 char *id_str;
4036 err = got_object_id_str(&id_str,
4037 got_tree_entry_get_id(te));
4038 if (err)
4039 goto done;
4040 if (asprintf(&id, "%s ", id_str) == -1) {
4041 err = got_error_from_errno("asprintf");
4042 free(id_str);
4043 goto done;
4045 free(id_str);
4047 print_entry(te, id, path, root_path);
4048 free(id);
4050 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4051 char *child_path;
4052 if (asprintf(&child_path, "%s%s%s", path,
4053 path[0] == '/' && path[1] == '\0' ? "" : "/",
4054 got_tree_entry_get_name(te)) == -1) {
4055 err = got_error_from_errno("asprintf");
4056 goto done;
4058 err = print_tree(child_path, commit_id, show_ids, 1,
4059 root_path, repo);
4060 free(child_path);
4061 if (err)
4062 goto done;
4065 done:
4066 if (tree)
4067 got_object_tree_close(tree);
4068 free(tree_id);
4069 return err;
4072 static const struct got_error *
4073 cmd_tree(int argc, char *argv[])
4075 const struct got_error *error;
4076 struct got_repository *repo = NULL;
4077 struct got_worktree *worktree = NULL;
4078 const char *path, *refname = NULL;
4079 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4080 struct got_object_id *commit_id = NULL;
4081 char *commit_id_str = NULL;
4082 int show_ids = 0, recurse = 0;
4083 int ch;
4085 #ifndef PROFILE
4086 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4087 NULL) == -1)
4088 err(1, "pledge");
4089 #endif
4091 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4092 switch (ch) {
4093 case 'c':
4094 commit_id_str = optarg;
4095 break;
4096 case 'r':
4097 repo_path = realpath(optarg, NULL);
4098 if (repo_path == NULL)
4099 return got_error_from_errno2("realpath",
4100 optarg);
4101 got_path_strip_trailing_slashes(repo_path);
4102 break;
4103 case 'i':
4104 show_ids = 1;
4105 break;
4106 case 'R':
4107 recurse = 1;
4108 break;
4109 default:
4110 usage_tree();
4111 /* NOTREACHED */
4115 argc -= optind;
4116 argv += optind;
4118 if (argc == 1)
4119 path = argv[0];
4120 else if (argc > 1)
4121 usage_tree();
4122 else
4123 path = NULL;
4125 cwd = getcwd(NULL, 0);
4126 if (cwd == NULL) {
4127 error = got_error_from_errno("getcwd");
4128 goto done;
4130 if (repo_path == NULL) {
4131 error = got_worktree_open(&worktree, cwd);
4132 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4133 goto done;
4134 else
4135 error = NULL;
4136 if (worktree) {
4137 repo_path =
4138 strdup(got_worktree_get_repo_path(worktree));
4139 if (repo_path == NULL)
4140 error = got_error_from_errno("strdup");
4141 if (error)
4142 goto done;
4143 } else {
4144 repo_path = strdup(cwd);
4145 if (repo_path == NULL) {
4146 error = got_error_from_errno("strdup");
4147 goto done;
4152 error = got_repo_open(&repo, repo_path, NULL);
4153 if (error != NULL)
4154 goto done;
4156 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4157 if (error)
4158 goto done;
4160 if (path == NULL) {
4161 if (worktree) {
4162 char *p, *worktree_subdir = cwd +
4163 strlen(got_worktree_get_root_path(worktree));
4164 if (asprintf(&p, "%s/%s",
4165 got_worktree_get_path_prefix(worktree),
4166 worktree_subdir) == -1) {
4167 error = got_error_from_errno("asprintf");
4168 goto done;
4170 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4171 free(p);
4172 if (error)
4173 goto done;
4174 } else
4175 path = "/";
4177 if (in_repo_path == NULL) {
4178 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4179 if (error != NULL)
4180 goto done;
4183 if (commit_id_str == NULL) {
4184 struct got_reference *head_ref;
4185 if (worktree)
4186 refname = got_worktree_get_head_ref_name(worktree);
4187 else
4188 refname = GOT_REF_HEAD;
4189 error = got_ref_open(&head_ref, repo, refname, 0);
4190 if (error != NULL)
4191 goto done;
4192 error = got_ref_resolve(&commit_id, repo, head_ref);
4193 got_ref_close(head_ref);
4194 if (error != NULL)
4195 goto done;
4196 } else {
4197 error = got_repo_match_object_id(&commit_id, NULL,
4198 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4199 if (error)
4200 goto done;
4203 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4204 in_repo_path, repo);
4205 done:
4206 free(in_repo_path);
4207 free(repo_path);
4208 free(cwd);
4209 free(commit_id);
4210 if (worktree)
4211 got_worktree_close(worktree);
4212 if (repo) {
4213 const struct got_error *repo_error;
4214 repo_error = got_repo_close(repo);
4215 if (error == NULL)
4216 error = repo_error;
4218 return error;
4221 __dead static void
4222 usage_status(void)
4224 fprintf(stderr, "usage: %s status [path ...]\n", getprogname());
4225 exit(1);
4228 static const struct got_error *
4229 print_status(void *arg, unsigned char status, unsigned char staged_status,
4230 const char *path, struct got_object_id *blob_id,
4231 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4232 int dirfd, const char *de_name)
4234 if (status == staged_status && (status == GOT_STATUS_DELETE))
4235 status = GOT_STATUS_NO_CHANGE;
4236 printf("%c%c %s\n", status, staged_status, path);
4237 return NULL;
4240 static const struct got_error *
4241 cmd_status(int argc, char *argv[])
4243 const struct got_error *error = NULL;
4244 struct got_repository *repo = NULL;
4245 struct got_worktree *worktree = NULL;
4246 char *cwd = NULL;
4247 struct got_pathlist_head paths;
4248 struct got_pathlist_entry *pe;
4249 int ch;
4251 TAILQ_INIT(&paths);
4253 while ((ch = getopt(argc, argv, "")) != -1) {
4254 switch (ch) {
4255 default:
4256 usage_status();
4257 /* NOTREACHED */
4261 argc -= optind;
4262 argv += optind;
4264 #ifndef PROFILE
4265 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4266 NULL) == -1)
4267 err(1, "pledge");
4268 #endif
4269 cwd = getcwd(NULL, 0);
4270 if (cwd == NULL) {
4271 error = got_error_from_errno("getcwd");
4272 goto done;
4275 error = got_worktree_open(&worktree, cwd);
4276 if (error != NULL)
4277 goto done;
4279 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4280 NULL);
4281 if (error != NULL)
4282 goto done;
4284 error = apply_unveil(got_repo_get_path(repo), 1,
4285 got_worktree_get_root_path(worktree));
4286 if (error)
4287 goto done;
4289 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
4290 if (error)
4291 goto done;
4293 error = got_worktree_status(worktree, &paths, repo, print_status, NULL,
4294 check_cancelled, NULL);
4295 done:
4296 TAILQ_FOREACH(pe, &paths, entry)
4297 free((char *)pe->path);
4298 got_pathlist_free(&paths);
4299 free(cwd);
4300 return error;
4303 __dead static void
4304 usage_ref(void)
4306 fprintf(stderr,
4307 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
4308 "[-d] [name]\n",
4309 getprogname());
4310 exit(1);
4313 static const struct got_error *
4314 list_refs(struct got_repository *repo, const char *refname)
4316 static const struct got_error *err = NULL;
4317 struct got_reflist_head refs;
4318 struct got_reflist_entry *re;
4320 SIMPLEQ_INIT(&refs);
4321 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
4322 if (err)
4323 return err;
4325 SIMPLEQ_FOREACH(re, &refs, entry) {
4326 char *refstr;
4327 refstr = got_ref_to_str(re->ref);
4328 if (refstr == NULL)
4329 return got_error_from_errno("got_ref_to_str");
4330 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
4331 free(refstr);
4334 got_ref_list_free(&refs);
4335 return NULL;
4338 static const struct got_error *
4339 delete_ref(struct got_repository *repo, const char *refname)
4341 const struct got_error *err = NULL;
4342 struct got_reference *ref;
4344 err = got_ref_open(&ref, repo, refname, 0);
4345 if (err)
4346 return err;
4348 err = got_ref_delete(ref, repo);
4349 got_ref_close(ref);
4350 return err;
4353 static const struct got_error *
4354 add_ref(struct got_repository *repo, const char *refname, const char *target)
4356 const struct got_error *err = NULL;
4357 struct got_object_id *id;
4358 struct got_reference *ref = NULL;
4361 * Don't let the user create a reference name with a leading '-'.
4362 * While technically a valid reference name, this case is usually
4363 * an unintended typo.
4365 if (refname[0] == '-')
4366 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4368 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
4369 repo);
4370 if (err) {
4371 struct got_reference *target_ref;
4373 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
4374 return err;
4375 err = got_ref_open(&target_ref, repo, target, 0);
4376 if (err)
4377 return err;
4378 err = got_ref_resolve(&id, repo, target_ref);
4379 got_ref_close(target_ref);
4380 if (err)
4381 return err;
4384 err = got_ref_alloc(&ref, refname, id);
4385 if (err)
4386 goto done;
4388 err = got_ref_write(ref, repo);
4389 done:
4390 if (ref)
4391 got_ref_close(ref);
4392 free(id);
4393 return err;
4396 static const struct got_error *
4397 add_symref(struct got_repository *repo, const char *refname, const char *target)
4399 const struct got_error *err = NULL;
4400 struct got_reference *ref = NULL;
4401 struct got_reference *target_ref = NULL;
4404 * Don't let the user create a reference name with a leading '-'.
4405 * While technically a valid reference name, this case is usually
4406 * an unintended typo.
4408 if (refname[0] == '-')
4409 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4411 err = got_ref_open(&target_ref, repo, target, 0);
4412 if (err)
4413 return err;
4415 err = got_ref_alloc_symref(&ref, refname, target_ref);
4416 if (err)
4417 goto done;
4419 err = got_ref_write(ref, repo);
4420 done:
4421 if (target_ref)
4422 got_ref_close(target_ref);
4423 if (ref)
4424 got_ref_close(ref);
4425 return err;
4428 static const struct got_error *
4429 cmd_ref(int argc, char *argv[])
4431 const struct got_error *error = NULL;
4432 struct got_repository *repo = NULL;
4433 struct got_worktree *worktree = NULL;
4434 char *cwd = NULL, *repo_path = NULL;
4435 int ch, do_list = 0, do_delete = 0;
4436 const char *obj_arg = NULL, *symref_target= NULL;
4437 char *refname = NULL;
4439 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
4440 switch (ch) {
4441 case 'c':
4442 obj_arg = optarg;
4443 break;
4444 case 'd':
4445 do_delete = 1;
4446 break;
4447 case 'r':
4448 repo_path = realpath(optarg, NULL);
4449 if (repo_path == NULL)
4450 return got_error_from_errno2("realpath",
4451 optarg);
4452 got_path_strip_trailing_slashes(repo_path);
4453 break;
4454 case 'l':
4455 do_list = 1;
4456 break;
4457 case 's':
4458 symref_target = optarg;
4459 break;
4460 default:
4461 usage_ref();
4462 /* NOTREACHED */
4466 if (obj_arg && do_list)
4467 errx(1, "-c and -l options are mutually exclusive");
4468 if (obj_arg && do_delete)
4469 errx(1, "-c and -d options are mutually exclusive");
4470 if (obj_arg && symref_target)
4471 errx(1, "-c and -s options are mutually exclusive");
4472 if (symref_target && do_delete)
4473 errx(1, "-s and -d options are mutually exclusive");
4474 if (symref_target && do_list)
4475 errx(1, "-s and -l options are mutually exclusive");
4476 if (do_delete && do_list)
4477 errx(1, "-d and -l options are mutually exclusive");
4479 argc -= optind;
4480 argv += optind;
4482 if (do_list) {
4483 if (argc != 0 && argc != 1)
4484 usage_ref();
4485 if (argc == 1) {
4486 refname = strdup(argv[0]);
4487 if (refname == NULL) {
4488 error = got_error_from_errno("strdup");
4489 goto done;
4492 } else {
4493 if (argc != 1)
4494 usage_ref();
4495 refname = strdup(argv[0]);
4496 if (refname == NULL) {
4497 error = got_error_from_errno("strdup");
4498 goto done;
4502 if (refname)
4503 got_path_strip_trailing_slashes(refname);
4505 #ifndef PROFILE
4506 if (do_list) {
4507 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4508 NULL) == -1)
4509 err(1, "pledge");
4510 } else {
4511 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4512 "sendfd unveil", NULL) == -1)
4513 err(1, "pledge");
4515 #endif
4516 cwd = getcwd(NULL, 0);
4517 if (cwd == NULL) {
4518 error = got_error_from_errno("getcwd");
4519 goto done;
4522 if (repo_path == NULL) {
4523 error = got_worktree_open(&worktree, cwd);
4524 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4525 goto done;
4526 else
4527 error = NULL;
4528 if (worktree) {
4529 repo_path =
4530 strdup(got_worktree_get_repo_path(worktree));
4531 if (repo_path == NULL)
4532 error = got_error_from_errno("strdup");
4533 if (error)
4534 goto done;
4535 } else {
4536 repo_path = strdup(cwd);
4537 if (repo_path == NULL) {
4538 error = got_error_from_errno("strdup");
4539 goto done;
4544 error = got_repo_open(&repo, repo_path, NULL);
4545 if (error != NULL)
4546 goto done;
4548 error = apply_unveil(got_repo_get_path(repo), do_list,
4549 worktree ? got_worktree_get_root_path(worktree) : NULL);
4550 if (error)
4551 goto done;
4553 if (do_list)
4554 error = list_refs(repo, refname);
4555 else if (do_delete)
4556 error = delete_ref(repo, refname);
4557 else if (symref_target)
4558 error = add_symref(repo, refname, symref_target);
4559 else {
4560 if (obj_arg == NULL)
4561 usage_ref();
4562 error = add_ref(repo, refname, obj_arg);
4564 done:
4565 free(refname);
4566 if (repo)
4567 got_repo_close(repo);
4568 if (worktree)
4569 got_worktree_close(worktree);
4570 free(cwd);
4571 free(repo_path);
4572 return error;
4575 __dead static void
4576 usage_branch(void)
4578 fprintf(stderr,
4579 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
4580 "[name]\n", getprogname());
4581 exit(1);
4584 static const struct got_error *
4585 list_branch(struct got_repository *repo, struct got_worktree *worktree,
4586 struct got_reference *ref)
4588 const struct got_error *err = NULL;
4589 const char *refname, *marker = " ";
4590 char *refstr;
4592 refname = got_ref_get_name(ref);
4593 if (worktree && strcmp(refname,
4594 got_worktree_get_head_ref_name(worktree)) == 0) {
4595 struct got_object_id *id = NULL;
4597 err = got_ref_resolve(&id, repo, ref);
4598 if (err)
4599 return err;
4600 if (got_object_id_cmp(id,
4601 got_worktree_get_base_commit_id(worktree)) == 0)
4602 marker = "* ";
4603 else
4604 marker = "~ ";
4605 free(id);
4608 if (strncmp(refname, "refs/heads/", 11) == 0)
4609 refname += 11;
4610 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4611 refname += 18;
4613 refstr = got_ref_to_str(ref);
4614 if (refstr == NULL)
4615 return got_error_from_errno("got_ref_to_str");
4617 printf("%s%s: %s\n", marker, refname, refstr);
4618 free(refstr);
4619 return NULL;
4622 static const struct got_error *
4623 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
4625 const char *refname;
4627 if (worktree == NULL)
4628 return got_error(GOT_ERR_NOT_WORKTREE);
4630 refname = got_worktree_get_head_ref_name(worktree);
4632 if (strncmp(refname, "refs/heads/", 11) == 0)
4633 refname += 11;
4634 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4635 refname += 18;
4637 printf("%s\n", refname);
4639 return NULL;
4642 static const struct got_error *
4643 list_branches(struct got_repository *repo, struct got_worktree *worktree)
4645 static const struct got_error *err = NULL;
4646 struct got_reflist_head refs;
4647 struct got_reflist_entry *re;
4648 struct got_reference *temp_ref = NULL;
4649 int rebase_in_progress, histedit_in_progress;
4651 SIMPLEQ_INIT(&refs);
4653 if (worktree) {
4654 err = got_worktree_rebase_in_progress(&rebase_in_progress,
4655 worktree);
4656 if (err)
4657 return err;
4659 err = got_worktree_histedit_in_progress(&histedit_in_progress,
4660 worktree);
4661 if (err)
4662 return err;
4664 if (rebase_in_progress || histedit_in_progress) {
4665 err = got_ref_open(&temp_ref, repo,
4666 got_worktree_get_head_ref_name(worktree), 0);
4667 if (err)
4668 return err;
4669 list_branch(repo, worktree, temp_ref);
4670 got_ref_close(temp_ref);
4674 err = got_ref_list(&refs, repo, "refs/heads",
4675 got_ref_cmp_by_name, NULL);
4676 if (err)
4677 return err;
4679 SIMPLEQ_FOREACH(re, &refs, entry)
4680 list_branch(repo, worktree, re->ref);
4682 got_ref_list_free(&refs);
4683 return NULL;
4686 static const struct got_error *
4687 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
4688 const char *branch_name)
4690 const struct got_error *err = NULL;
4691 struct got_reference *ref = NULL;
4692 char *refname;
4694 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
4695 return got_error_from_errno("asprintf");
4697 err = got_ref_open(&ref, repo, refname, 0);
4698 if (err)
4699 goto done;
4701 if (worktree &&
4702 strcmp(got_worktree_get_head_ref_name(worktree),
4703 got_ref_get_name(ref)) == 0) {
4704 err = got_error_msg(GOT_ERR_SAME_BRANCH,
4705 "will not delete this work tree's current branch");
4706 goto done;
4709 err = got_ref_delete(ref, repo);
4710 done:
4711 if (ref)
4712 got_ref_close(ref);
4713 free(refname);
4714 return err;
4717 static const struct got_error *
4718 add_branch(struct got_repository *repo, const char *branch_name,
4719 struct got_object_id *base_commit_id)
4721 const struct got_error *err = NULL;
4722 struct got_reference *ref = NULL;
4723 char *base_refname = NULL, *refname = NULL;
4726 * Don't let the user create a branch name with a leading '-'.
4727 * While technically a valid reference name, this case is usually
4728 * an unintended typo.
4730 if (branch_name[0] == '-')
4731 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
4733 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
4734 err = got_error_from_errno("asprintf");
4735 goto done;
4738 err = got_ref_open(&ref, repo, refname, 0);
4739 if (err == NULL) {
4740 err = got_error(GOT_ERR_BRANCH_EXISTS);
4741 goto done;
4742 } else if (err->code != GOT_ERR_NOT_REF)
4743 goto done;
4745 err = got_ref_alloc(&ref, refname, base_commit_id);
4746 if (err)
4747 goto done;
4749 err = got_ref_write(ref, repo);
4750 done:
4751 if (ref)
4752 got_ref_close(ref);
4753 free(base_refname);
4754 free(refname);
4755 return err;
4758 static const struct got_error *
4759 cmd_branch(int argc, char *argv[])
4761 const struct got_error *error = NULL;
4762 struct got_repository *repo = NULL;
4763 struct got_worktree *worktree = NULL;
4764 char *cwd = NULL, *repo_path = NULL;
4765 int ch, do_list = 0, do_show = 0, do_update = 1;
4766 const char *delref = NULL, *commit_id_arg = NULL;
4767 struct got_reference *ref = NULL;
4768 struct got_pathlist_head paths;
4769 struct got_pathlist_entry *pe;
4770 struct got_object_id *commit_id = NULL;
4771 char *commit_id_str = NULL;
4773 TAILQ_INIT(&paths);
4775 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
4776 switch (ch) {
4777 case 'c':
4778 commit_id_arg = optarg;
4779 break;
4780 case 'd':
4781 delref = optarg;
4782 break;
4783 case 'r':
4784 repo_path = realpath(optarg, NULL);
4785 if (repo_path == NULL)
4786 return got_error_from_errno2("realpath",
4787 optarg);
4788 got_path_strip_trailing_slashes(repo_path);
4789 break;
4790 case 'l':
4791 do_list = 1;
4792 break;
4793 case 'n':
4794 do_update = 0;
4795 break;
4796 default:
4797 usage_branch();
4798 /* NOTREACHED */
4802 if (do_list && delref)
4803 errx(1, "-l and -d options are mutually exclusive");
4805 argc -= optind;
4806 argv += optind;
4808 if (!do_list && !delref && argc == 0)
4809 do_show = 1;
4811 if ((do_list || delref || do_show) && commit_id_arg != NULL)
4812 errx(1, "-c option can only be used when creating a branch");
4814 if (do_list || delref) {
4815 if (argc > 0)
4816 usage_branch();
4817 } else if (!do_show && argc != 1)
4818 usage_branch();
4820 #ifndef PROFILE
4821 if (do_list || do_show) {
4822 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4823 NULL) == -1)
4824 err(1, "pledge");
4825 } else {
4826 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4827 "sendfd unveil", NULL) == -1)
4828 err(1, "pledge");
4830 #endif
4831 cwd = getcwd(NULL, 0);
4832 if (cwd == NULL) {
4833 error = got_error_from_errno("getcwd");
4834 goto done;
4837 if (repo_path == NULL) {
4838 error = got_worktree_open(&worktree, cwd);
4839 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4840 goto done;
4841 else
4842 error = NULL;
4843 if (worktree) {
4844 repo_path =
4845 strdup(got_worktree_get_repo_path(worktree));
4846 if (repo_path == NULL)
4847 error = got_error_from_errno("strdup");
4848 if (error)
4849 goto done;
4850 } else {
4851 repo_path = strdup(cwd);
4852 if (repo_path == NULL) {
4853 error = got_error_from_errno("strdup");
4854 goto done;
4859 error = got_repo_open(&repo, repo_path, NULL);
4860 if (error != NULL)
4861 goto done;
4863 error = apply_unveil(got_repo_get_path(repo), do_list,
4864 worktree ? got_worktree_get_root_path(worktree) : NULL);
4865 if (error)
4866 goto done;
4868 if (do_show)
4869 error = show_current_branch(repo, worktree);
4870 else if (do_list)
4871 error = list_branches(repo, worktree);
4872 else if (delref)
4873 error = delete_branch(repo, worktree, delref);
4874 else {
4875 if (commit_id_arg == NULL)
4876 commit_id_arg = worktree ?
4877 got_worktree_get_head_ref_name(worktree) :
4878 GOT_REF_HEAD;
4879 error = got_repo_match_object_id(&commit_id, NULL,
4880 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
4881 if (error)
4882 goto done;
4883 error = add_branch(repo, argv[0], commit_id);
4884 if (error)
4885 goto done;
4886 if (worktree && do_update) {
4887 int did_something = 0;
4888 char *branch_refname = NULL;
4890 error = got_object_id_str(&commit_id_str, commit_id);
4891 if (error)
4892 goto done;
4893 error = get_worktree_paths_from_argv(&paths, 0, NULL,
4894 worktree);
4895 if (error)
4896 goto done;
4897 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
4898 == -1) {
4899 error = got_error_from_errno("asprintf");
4900 goto done;
4902 error = got_ref_open(&ref, repo, branch_refname, 0);
4903 free(branch_refname);
4904 if (error)
4905 goto done;
4906 error = switch_head_ref(ref, commit_id, worktree,
4907 repo);
4908 if (error)
4909 goto done;
4910 error = got_worktree_set_base_commit_id(worktree, repo,
4911 commit_id);
4912 if (error)
4913 goto done;
4914 error = got_worktree_checkout_files(worktree, &paths,
4915 repo, update_progress, &did_something,
4916 check_cancelled, NULL);
4917 if (error)
4918 goto done;
4919 if (did_something)
4920 printf("Updated to commit %s\n", commit_id_str);
4923 done:
4924 if (ref)
4925 got_ref_close(ref);
4926 if (repo)
4927 got_repo_close(repo);
4928 if (worktree)
4929 got_worktree_close(worktree);
4930 free(cwd);
4931 free(repo_path);
4932 free(commit_id);
4933 free(commit_id_str);
4934 TAILQ_FOREACH(pe, &paths, entry)
4935 free((char *)pe->path);
4936 got_pathlist_free(&paths);
4937 return error;
4941 __dead static void
4942 usage_tag(void)
4944 fprintf(stderr,
4945 "usage: %s tag [-c commit] [-r repository] [-l] "
4946 "[-m message] name\n", getprogname());
4947 exit(1);
4950 #if 0
4951 static const struct got_error *
4952 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
4954 const struct got_error *err = NULL;
4955 struct got_reflist_entry *re, *se, *new;
4956 struct got_object_id *re_id, *se_id;
4957 struct got_tag_object *re_tag, *se_tag;
4958 time_t re_time, se_time;
4960 SIMPLEQ_FOREACH(re, tags, entry) {
4961 se = SIMPLEQ_FIRST(sorted);
4962 if (se == NULL) {
4963 err = got_reflist_entry_dup(&new, re);
4964 if (err)
4965 return err;
4966 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
4967 continue;
4968 } else {
4969 err = got_ref_resolve(&re_id, repo, re->ref);
4970 if (err)
4971 break;
4972 err = got_object_open_as_tag(&re_tag, repo, re_id);
4973 free(re_id);
4974 if (err)
4975 break;
4976 re_time = got_object_tag_get_tagger_time(re_tag);
4977 got_object_tag_close(re_tag);
4980 while (se) {
4981 err = got_ref_resolve(&se_id, repo, re->ref);
4982 if (err)
4983 break;
4984 err = got_object_open_as_tag(&se_tag, repo, se_id);
4985 free(se_id);
4986 if (err)
4987 break;
4988 se_time = got_object_tag_get_tagger_time(se_tag);
4989 got_object_tag_close(se_tag);
4991 if (se_time > re_time) {
4992 err = got_reflist_entry_dup(&new, re);
4993 if (err)
4994 return err;
4995 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
4996 break;
4998 se = SIMPLEQ_NEXT(se, entry);
4999 continue;
5002 done:
5003 return err;
5005 #endif
5007 static const struct got_error *
5008 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5010 static const struct got_error *err = NULL;
5011 struct got_reflist_head refs;
5012 struct got_reflist_entry *re;
5014 SIMPLEQ_INIT(&refs);
5016 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5017 if (err)
5018 return err;
5020 SIMPLEQ_FOREACH(re, &refs, entry) {
5021 const char *refname;
5022 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5023 char datebuf[26];
5024 const char *tagger;
5025 time_t tagger_time;
5026 struct got_object_id *id;
5027 struct got_tag_object *tag;
5028 struct got_commit_object *commit = NULL;
5030 refname = got_ref_get_name(re->ref);
5031 if (strncmp(refname, "refs/tags/", 10) != 0)
5032 continue;
5033 refname += 10;
5034 refstr = got_ref_to_str(re->ref);
5035 if (refstr == NULL) {
5036 err = got_error_from_errno("got_ref_to_str");
5037 break;
5039 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5040 free(refstr);
5042 err = got_ref_resolve(&id, repo, re->ref);
5043 if (err)
5044 break;
5045 err = got_object_open_as_tag(&tag, repo, id);
5046 if (err) {
5047 if (err->code != GOT_ERR_OBJ_TYPE) {
5048 free(id);
5049 break;
5051 /* "lightweight" tag */
5052 err = got_object_open_as_commit(&commit, repo, id);
5053 if (err) {
5054 free(id);
5055 break;
5057 tagger = got_object_commit_get_committer(commit);
5058 tagger_time =
5059 got_object_commit_get_committer_time(commit);
5060 err = got_object_id_str(&id_str, id);
5061 free(id);
5062 if (err)
5063 break;
5064 } else {
5065 free(id);
5066 tagger = got_object_tag_get_tagger(tag);
5067 tagger_time = got_object_tag_get_tagger_time(tag);
5068 err = got_object_id_str(&id_str,
5069 got_object_tag_get_object_id(tag));
5070 if (err)
5071 break;
5073 printf("from: %s\n", tagger);
5074 datestr = get_datestr(&tagger_time, datebuf);
5075 if (datestr)
5076 printf("date: %s UTC\n", datestr);
5077 if (commit)
5078 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5079 else {
5080 switch (got_object_tag_get_object_type(tag)) {
5081 case GOT_OBJ_TYPE_BLOB:
5082 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5083 id_str);
5084 break;
5085 case GOT_OBJ_TYPE_TREE:
5086 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5087 id_str);
5088 break;
5089 case GOT_OBJ_TYPE_COMMIT:
5090 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5091 id_str);
5092 break;
5093 case GOT_OBJ_TYPE_TAG:
5094 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5095 id_str);
5096 break;
5097 default:
5098 break;
5101 free(id_str);
5102 if (commit) {
5103 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5104 if (err)
5105 break;
5106 got_object_commit_close(commit);
5107 } else {
5108 tagmsg0 = strdup(got_object_tag_get_message(tag));
5109 got_object_tag_close(tag);
5110 if (tagmsg0 == NULL) {
5111 err = got_error_from_errno("strdup");
5112 break;
5116 tagmsg = tagmsg0;
5117 do {
5118 line = strsep(&tagmsg, "\n");
5119 if (line)
5120 printf(" %s\n", line);
5121 } while (line);
5122 free(tagmsg0);
5125 got_ref_list_free(&refs);
5126 return NULL;
5129 static const struct got_error *
5130 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5131 const char *tag_name, const char *repo_path)
5133 const struct got_error *err = NULL;
5134 char *template = NULL, *initial_content = NULL;
5135 char *editor = NULL;
5136 int fd = -1;
5138 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5139 err = got_error_from_errno("asprintf");
5140 goto done;
5143 if (asprintf(&initial_content, "\n# tagging commit %s as %s\n",
5144 commit_id_str, tag_name) == -1) {
5145 err = got_error_from_errno("asprintf");
5146 goto done;
5149 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5150 if (err)
5151 goto done;
5153 dprintf(fd, initial_content);
5154 close(fd);
5156 err = get_editor(&editor);
5157 if (err)
5158 goto done;
5159 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
5160 done:
5161 free(initial_content);
5162 free(template);
5163 free(editor);
5165 /* Editor is done; we can now apply unveil(2) */
5166 if (err == NULL) {
5167 err = apply_unveil(repo_path, 0, NULL);
5168 if (err) {
5169 free(*tagmsg);
5170 *tagmsg = NULL;
5173 return err;
5176 static const struct got_error *
5177 add_tag(struct got_repository *repo, const char *tag_name,
5178 const char *commit_arg, const char *tagmsg_arg)
5180 const struct got_error *err = NULL;
5181 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5182 char *label = NULL, *commit_id_str = NULL;
5183 struct got_reference *ref = NULL;
5184 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5185 char *tagmsg_path = NULL, *tag_id_str = NULL;
5186 int preserve_tagmsg = 0;
5189 * Don't let the user create a tag name with a leading '-'.
5190 * While technically a valid reference name, this case is usually
5191 * an unintended typo.
5193 if (tag_name[0] == '-')
5194 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5196 err = get_author(&tagger, repo);
5197 if (err)
5198 return err;
5200 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5201 GOT_OBJ_TYPE_COMMIT, 1, repo);
5202 if (err)
5203 goto done;
5205 err = got_object_id_str(&commit_id_str, commit_id);
5206 if (err)
5207 goto done;
5209 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5210 refname = strdup(tag_name);
5211 if (refname == NULL) {
5212 err = got_error_from_errno("strdup");
5213 goto done;
5215 tag_name += 10;
5216 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5217 err = got_error_from_errno("asprintf");
5218 goto done;
5221 err = got_ref_open(&ref, repo, refname, 0);
5222 if (err == NULL) {
5223 err = got_error(GOT_ERR_TAG_EXISTS);
5224 goto done;
5225 } else if (err->code != GOT_ERR_NOT_REF)
5226 goto done;
5228 if (tagmsg_arg == NULL) {
5229 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5230 tag_name, got_repo_get_path(repo));
5231 if (err) {
5232 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5233 tagmsg_path != NULL)
5234 preserve_tagmsg = 1;
5235 goto done;
5239 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5240 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5241 if (err) {
5242 if (tagmsg_path)
5243 preserve_tagmsg = 1;
5244 goto done;
5247 err = got_ref_alloc(&ref, refname, tag_id);
5248 if (err) {
5249 if (tagmsg_path)
5250 preserve_tagmsg = 1;
5251 goto done;
5254 err = got_ref_write(ref, repo);
5255 if (err) {
5256 if (tagmsg_path)
5257 preserve_tagmsg = 1;
5258 goto done;
5261 err = got_object_id_str(&tag_id_str, tag_id);
5262 if (err) {
5263 if (tagmsg_path)
5264 preserve_tagmsg = 1;
5265 goto done;
5267 printf("Created tag %s\n", tag_id_str);
5268 done:
5269 if (preserve_tagmsg) {
5270 fprintf(stderr, "%s: tag message preserved in %s\n",
5271 getprogname(), tagmsg_path);
5272 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
5273 err = got_error_from_errno2("unlink", tagmsg_path);
5274 free(tag_id_str);
5275 if (ref)
5276 got_ref_close(ref);
5277 free(commit_id);
5278 free(commit_id_str);
5279 free(refname);
5280 free(tagmsg);
5281 free(tagmsg_path);
5282 free(tagger);
5283 return err;
5286 static const struct got_error *
5287 cmd_tag(int argc, char *argv[])
5289 const struct got_error *error = NULL;
5290 struct got_repository *repo = NULL;
5291 struct got_worktree *worktree = NULL;
5292 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
5293 char *gitconfig_path = NULL;
5294 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
5295 int ch, do_list = 0;
5297 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
5298 switch (ch) {
5299 case 'c':
5300 commit_id_arg = optarg;
5301 break;
5302 case 'm':
5303 tagmsg = optarg;
5304 break;
5305 case 'r':
5306 repo_path = realpath(optarg, NULL);
5307 if (repo_path == NULL)
5308 return got_error_from_errno2("realpath",
5309 optarg);
5310 got_path_strip_trailing_slashes(repo_path);
5311 break;
5312 case 'l':
5313 do_list = 1;
5314 break;
5315 default:
5316 usage_tag();
5317 /* NOTREACHED */
5321 argc -= optind;
5322 argv += optind;
5324 if (do_list) {
5325 if (commit_id_arg != NULL)
5326 errx(1,
5327 "-c option can only be used when creating a tag");
5328 if (tagmsg)
5329 errx(1, "-l and -m options are mutually exclusive");
5330 if (argc > 0)
5331 usage_tag();
5332 } else if (argc != 1)
5333 usage_tag();
5335 tag_name = argv[0];
5337 #ifndef PROFILE
5338 if (do_list) {
5339 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5340 NULL) == -1)
5341 err(1, "pledge");
5342 } else {
5343 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5344 "sendfd unveil", NULL) == -1)
5345 err(1, "pledge");
5347 #endif
5348 cwd = getcwd(NULL, 0);
5349 if (cwd == NULL) {
5350 error = got_error_from_errno("getcwd");
5351 goto done;
5354 if (repo_path == NULL) {
5355 error = got_worktree_open(&worktree, cwd);
5356 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5357 goto done;
5358 else
5359 error = NULL;
5360 if (worktree) {
5361 repo_path =
5362 strdup(got_worktree_get_repo_path(worktree));
5363 if (repo_path == NULL)
5364 error = got_error_from_errno("strdup");
5365 if (error)
5366 goto done;
5367 } else {
5368 repo_path = strdup(cwd);
5369 if (repo_path == NULL) {
5370 error = got_error_from_errno("strdup");
5371 goto done;
5376 if (do_list) {
5377 error = got_repo_open(&repo, repo_path, NULL);
5378 if (error != NULL)
5379 goto done;
5380 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5381 if (error)
5382 goto done;
5383 error = list_tags(repo, worktree);
5384 } else {
5385 error = get_gitconfig_path(&gitconfig_path);
5386 if (error)
5387 goto done;
5388 error = got_repo_open(&repo, repo_path, gitconfig_path);
5389 if (error != NULL)
5390 goto done;
5392 if (tagmsg) {
5393 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5394 if (error)
5395 goto done;
5398 if (commit_id_arg == NULL) {
5399 struct got_reference *head_ref;
5400 struct got_object_id *commit_id;
5401 error = got_ref_open(&head_ref, repo,
5402 worktree ? got_worktree_get_head_ref_name(worktree)
5403 : GOT_REF_HEAD, 0);
5404 if (error)
5405 goto done;
5406 error = got_ref_resolve(&commit_id, repo, head_ref);
5407 got_ref_close(head_ref);
5408 if (error)
5409 goto done;
5410 error = got_object_id_str(&commit_id_str, commit_id);
5411 free(commit_id);
5412 if (error)
5413 goto done;
5416 error = add_tag(repo, tag_name,
5417 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
5419 done:
5420 if (repo)
5421 got_repo_close(repo);
5422 if (worktree)
5423 got_worktree_close(worktree);
5424 free(cwd);
5425 free(repo_path);
5426 free(gitconfig_path);
5427 free(commit_id_str);
5428 return error;
5431 __dead static void
5432 usage_add(void)
5434 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
5435 getprogname());
5436 exit(1);
5439 static const struct got_error *
5440 add_progress(void *arg, unsigned char status, const char *path)
5442 while (path[0] == '/')
5443 path++;
5444 printf("%c %s\n", status, path);
5445 return NULL;
5448 static const struct got_error *
5449 cmd_add(int argc, char *argv[])
5451 const struct got_error *error = NULL;
5452 struct got_repository *repo = NULL;
5453 struct got_worktree *worktree = NULL;
5454 char *cwd = NULL;
5455 struct got_pathlist_head paths;
5456 struct got_pathlist_entry *pe;
5457 int ch, can_recurse = 0, no_ignores = 0;
5459 TAILQ_INIT(&paths);
5461 while ((ch = getopt(argc, argv, "IR")) != -1) {
5462 switch (ch) {
5463 case 'I':
5464 no_ignores = 1;
5465 break;
5466 case 'R':
5467 can_recurse = 1;
5468 break;
5469 default:
5470 usage_add();
5471 /* NOTREACHED */
5475 argc -= optind;
5476 argv += optind;
5478 #ifndef PROFILE
5479 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5480 NULL) == -1)
5481 err(1, "pledge");
5482 #endif
5483 if (argc < 1)
5484 usage_add();
5486 cwd = getcwd(NULL, 0);
5487 if (cwd == NULL) {
5488 error = got_error_from_errno("getcwd");
5489 goto done;
5492 error = got_worktree_open(&worktree, cwd);
5493 if (error)
5494 goto done;
5496 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5497 NULL);
5498 if (error != NULL)
5499 goto done;
5501 error = apply_unveil(got_repo_get_path(repo), 1,
5502 got_worktree_get_root_path(worktree));
5503 if (error)
5504 goto done;
5506 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5507 if (error)
5508 goto done;
5510 if (!can_recurse && no_ignores) {
5511 error = got_error_msg(GOT_ERR_BAD_PATH,
5512 "disregarding ignores requires -R option");
5513 goto done;
5517 if (!can_recurse) {
5518 char *ondisk_path;
5519 struct stat sb;
5520 TAILQ_FOREACH(pe, &paths, entry) {
5521 if (asprintf(&ondisk_path, "%s/%s",
5522 got_worktree_get_root_path(worktree),
5523 pe->path) == -1) {
5524 error = got_error_from_errno("asprintf");
5525 goto done;
5527 if (lstat(ondisk_path, &sb) == -1) {
5528 if (errno == ENOENT) {
5529 free(ondisk_path);
5530 continue;
5532 error = got_error_from_errno2("lstat",
5533 ondisk_path);
5534 free(ondisk_path);
5535 goto done;
5537 free(ondisk_path);
5538 if (S_ISDIR(sb.st_mode)) {
5539 error = got_error_msg(GOT_ERR_BAD_PATH,
5540 "adding directories requires -R option");
5541 goto done;
5546 error = got_worktree_schedule_add(worktree, &paths, add_progress,
5547 NULL, repo, no_ignores);
5548 done:
5549 if (repo)
5550 got_repo_close(repo);
5551 if (worktree)
5552 got_worktree_close(worktree);
5553 TAILQ_FOREACH(pe, &paths, entry)
5554 free((char *)pe->path);
5555 got_pathlist_free(&paths);
5556 free(cwd);
5557 return error;
5560 __dead static void
5561 usage_remove(void)
5563 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] path ...\n",
5564 getprogname());
5565 exit(1);
5568 static const struct got_error *
5569 print_remove_status(void *arg, unsigned char status,
5570 unsigned char staged_status, const char *path)
5572 while (path[0] == '/')
5573 path++;
5574 if (status == GOT_STATUS_NONEXISTENT)
5575 return NULL;
5576 if (status == staged_status && (status == GOT_STATUS_DELETE))
5577 status = GOT_STATUS_NO_CHANGE;
5578 printf("%c%c %s\n", status, staged_status, path);
5579 return NULL;
5582 static const struct got_error *
5583 cmd_remove(int argc, char *argv[])
5585 const struct got_error *error = NULL;
5586 struct got_worktree *worktree = NULL;
5587 struct got_repository *repo = NULL;
5588 char *cwd = NULL;
5589 struct got_pathlist_head paths;
5590 struct got_pathlist_entry *pe;
5591 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0;
5593 TAILQ_INIT(&paths);
5595 while ((ch = getopt(argc, argv, "fkR")) != -1) {
5596 switch (ch) {
5597 case 'f':
5598 delete_local_mods = 1;
5599 break;
5600 case 'k':
5601 keep_on_disk = 1;
5602 break;
5603 case 'R':
5604 can_recurse = 1;
5605 break;
5606 default:
5607 usage_remove();
5608 /* NOTREACHED */
5612 argc -= optind;
5613 argv += optind;
5615 #ifndef PROFILE
5616 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5617 NULL) == -1)
5618 err(1, "pledge");
5619 #endif
5620 if (argc < 1)
5621 usage_remove();
5623 cwd = getcwd(NULL, 0);
5624 if (cwd == NULL) {
5625 error = got_error_from_errno("getcwd");
5626 goto done;
5628 error = got_worktree_open(&worktree, cwd);
5629 if (error)
5630 goto done;
5632 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5633 NULL);
5634 if (error)
5635 goto done;
5637 error = apply_unveil(got_repo_get_path(repo), 1,
5638 got_worktree_get_root_path(worktree));
5639 if (error)
5640 goto done;
5642 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5643 if (error)
5644 goto done;
5646 if (!can_recurse) {
5647 char *ondisk_path;
5648 struct stat sb;
5649 TAILQ_FOREACH(pe, &paths, entry) {
5650 if (asprintf(&ondisk_path, "%s/%s",
5651 got_worktree_get_root_path(worktree),
5652 pe->path) == -1) {
5653 error = got_error_from_errno("asprintf");
5654 goto done;
5656 if (lstat(ondisk_path, &sb) == -1) {
5657 if (errno == ENOENT) {
5658 free(ondisk_path);
5659 continue;
5661 error = got_error_from_errno2("lstat",
5662 ondisk_path);
5663 free(ondisk_path);
5664 goto done;
5666 free(ondisk_path);
5667 if (S_ISDIR(sb.st_mode)) {
5668 error = got_error_msg(GOT_ERR_BAD_PATH,
5669 "removing directories requires -R option");
5670 goto done;
5675 error = got_worktree_schedule_delete(worktree, &paths,
5676 delete_local_mods, print_remove_status, NULL, repo, keep_on_disk);
5677 done:
5678 if (repo)
5679 got_repo_close(repo);
5680 if (worktree)
5681 got_worktree_close(worktree);
5682 TAILQ_FOREACH(pe, &paths, entry)
5683 free((char *)pe->path);
5684 got_pathlist_free(&paths);
5685 free(cwd);
5686 return error;
5689 __dead static void
5690 usage_revert(void)
5692 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
5693 "path ...\n", getprogname());
5694 exit(1);
5697 static const struct got_error *
5698 revert_progress(void *arg, unsigned char status, const char *path)
5700 if (status == GOT_STATUS_UNVERSIONED)
5701 return NULL;
5703 while (path[0] == '/')
5704 path++;
5705 printf("%c %s\n", status, path);
5706 return NULL;
5709 struct choose_patch_arg {
5710 FILE *patch_script_file;
5711 const char *action;
5714 static const struct got_error *
5715 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
5716 int nchanges, const char *action)
5718 char *line = NULL;
5719 size_t linesize = 0;
5720 ssize_t linelen;
5722 switch (status) {
5723 case GOT_STATUS_ADD:
5724 printf("A %s\n%s this addition? [y/n] ", path, action);
5725 break;
5726 case GOT_STATUS_DELETE:
5727 printf("D %s\n%s this deletion? [y/n] ", path, action);
5728 break;
5729 case GOT_STATUS_MODIFY:
5730 if (fseek(patch_file, 0L, SEEK_SET) == -1)
5731 return got_error_from_errno("fseek");
5732 printf(GOT_COMMIT_SEP_STR);
5733 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
5734 printf("%s", line);
5735 if (ferror(patch_file))
5736 return got_error_from_errno("getline");
5737 printf(GOT_COMMIT_SEP_STR);
5738 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
5739 path, n, nchanges, action);
5740 break;
5741 default:
5742 return got_error_path(path, GOT_ERR_FILE_STATUS);
5745 return NULL;
5748 static const struct got_error *
5749 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
5750 FILE *patch_file, int n, int nchanges)
5752 const struct got_error *err = NULL;
5753 char *line = NULL;
5754 size_t linesize = 0;
5755 ssize_t linelen;
5756 int resp = ' ';
5757 struct choose_patch_arg *a = arg;
5759 *choice = GOT_PATCH_CHOICE_NONE;
5761 if (a->patch_script_file) {
5762 char *nl;
5763 err = show_change(status, path, patch_file, n, nchanges,
5764 a->action);
5765 if (err)
5766 return err;
5767 linelen = getline(&line, &linesize, a->patch_script_file);
5768 if (linelen == -1) {
5769 if (ferror(a->patch_script_file))
5770 return got_error_from_errno("getline");
5771 return NULL;
5773 nl = strchr(line, '\n');
5774 if (nl)
5775 *nl = '\0';
5776 if (strcmp(line, "y") == 0) {
5777 *choice = GOT_PATCH_CHOICE_YES;
5778 printf("y\n");
5779 } else if (strcmp(line, "n") == 0) {
5780 *choice = GOT_PATCH_CHOICE_NO;
5781 printf("n\n");
5782 } else if (strcmp(line, "q") == 0 &&
5783 status == GOT_STATUS_MODIFY) {
5784 *choice = GOT_PATCH_CHOICE_QUIT;
5785 printf("q\n");
5786 } else
5787 printf("invalid response '%s'\n", line);
5788 free(line);
5789 return NULL;
5792 while (resp != 'y' && resp != 'n' && resp != 'q') {
5793 err = show_change(status, path, patch_file, n, nchanges,
5794 a->action);
5795 if (err)
5796 return err;
5797 resp = getchar();
5798 if (resp == '\n')
5799 resp = getchar();
5800 if (status == GOT_STATUS_MODIFY) {
5801 if (resp != 'y' && resp != 'n' && resp != 'q') {
5802 printf("invalid response '%c'\n", resp);
5803 resp = ' ';
5805 } else if (resp != 'y' && resp != 'n') {
5806 printf("invalid response '%c'\n", resp);
5807 resp = ' ';
5811 if (resp == 'y')
5812 *choice = GOT_PATCH_CHOICE_YES;
5813 else if (resp == 'n')
5814 *choice = GOT_PATCH_CHOICE_NO;
5815 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
5816 *choice = GOT_PATCH_CHOICE_QUIT;
5818 return NULL;
5822 static const struct got_error *
5823 cmd_revert(int argc, char *argv[])
5825 const struct got_error *error = NULL;
5826 struct got_worktree *worktree = NULL;
5827 struct got_repository *repo = NULL;
5828 char *cwd = NULL, *path = NULL;
5829 struct got_pathlist_head paths;
5830 struct got_pathlist_entry *pe;
5831 int ch, can_recurse = 0, pflag = 0;
5832 FILE *patch_script_file = NULL;
5833 const char *patch_script_path = NULL;
5834 struct choose_patch_arg cpa;
5836 TAILQ_INIT(&paths);
5838 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
5839 switch (ch) {
5840 case 'p':
5841 pflag = 1;
5842 break;
5843 case 'F':
5844 patch_script_path = optarg;
5845 break;
5846 case 'R':
5847 can_recurse = 1;
5848 break;
5849 default:
5850 usage_revert();
5851 /* NOTREACHED */
5855 argc -= optind;
5856 argv += optind;
5858 #ifndef PROFILE
5859 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
5860 "unveil", NULL) == -1)
5861 err(1, "pledge");
5862 #endif
5863 if (argc < 1)
5864 usage_revert();
5865 if (patch_script_path && !pflag)
5866 errx(1, "-F option can only be used together with -p option");
5868 cwd = getcwd(NULL, 0);
5869 if (cwd == NULL) {
5870 error = got_error_from_errno("getcwd");
5871 goto done;
5873 error = got_worktree_open(&worktree, cwd);
5874 if (error)
5875 goto done;
5877 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5878 NULL);
5879 if (error != NULL)
5880 goto done;
5882 if (patch_script_path) {
5883 patch_script_file = fopen(patch_script_path, "r");
5884 if (patch_script_file == NULL) {
5885 error = got_error_from_errno2("fopen",
5886 patch_script_path);
5887 goto done;
5890 error = apply_unveil(got_repo_get_path(repo), 1,
5891 got_worktree_get_root_path(worktree));
5892 if (error)
5893 goto done;
5895 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5896 if (error)
5897 goto done;
5899 if (!can_recurse) {
5900 char *ondisk_path;
5901 struct stat sb;
5902 TAILQ_FOREACH(pe, &paths, entry) {
5903 if (asprintf(&ondisk_path, "%s/%s",
5904 got_worktree_get_root_path(worktree),
5905 pe->path) == -1) {
5906 error = got_error_from_errno("asprintf");
5907 goto done;
5909 if (lstat(ondisk_path, &sb) == -1) {
5910 if (errno == ENOENT) {
5911 free(ondisk_path);
5912 continue;
5914 error = got_error_from_errno2("lstat",
5915 ondisk_path);
5916 free(ondisk_path);
5917 goto done;
5919 free(ondisk_path);
5920 if (S_ISDIR(sb.st_mode)) {
5921 error = got_error_msg(GOT_ERR_BAD_PATH,
5922 "reverting directories requires -R option");
5923 goto done;
5928 cpa.patch_script_file = patch_script_file;
5929 cpa.action = "revert";
5930 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
5931 pflag ? choose_patch : NULL, &cpa, repo);
5932 done:
5933 if (patch_script_file && fclose(patch_script_file) == EOF &&
5934 error == NULL)
5935 error = got_error_from_errno2("fclose", patch_script_path);
5936 if (repo)
5937 got_repo_close(repo);
5938 if (worktree)
5939 got_worktree_close(worktree);
5940 free(path);
5941 free(cwd);
5942 return error;
5945 __dead static void
5946 usage_commit(void)
5948 fprintf(stderr, "usage: %s commit [-m msg] [path ...]\n",
5949 getprogname());
5950 exit(1);
5953 struct collect_commit_logmsg_arg {
5954 const char *cmdline_log;
5955 const char *editor;
5956 const char *worktree_path;
5957 const char *branch_name;
5958 const char *repo_path;
5959 char *logmsg_path;
5963 static const struct got_error *
5964 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
5965 void *arg)
5967 char *initial_content = NULL;
5968 struct got_pathlist_entry *pe;
5969 const struct got_error *err = NULL;
5970 char *template = NULL;
5971 struct collect_commit_logmsg_arg *a = arg;
5972 int fd;
5973 size_t len;
5975 /* if a message was specified on the command line, just use it */
5976 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
5977 len = strlen(a->cmdline_log) + 1;
5978 *logmsg = malloc(len + 1);
5979 if (*logmsg == NULL)
5980 return got_error_from_errno("malloc");
5981 strlcpy(*logmsg, a->cmdline_log, len);
5982 return NULL;
5985 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
5986 return got_error_from_errno("asprintf");
5988 if (asprintf(&initial_content,
5989 "\n# changes to be committed on branch %s:\n",
5990 a->branch_name) == -1)
5991 return got_error_from_errno("asprintf");
5993 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
5994 if (err)
5995 goto done;
5997 dprintf(fd, initial_content);
5999 TAILQ_FOREACH(pe, commitable_paths, entry) {
6000 struct got_commitable *ct = pe->data;
6001 dprintf(fd, "# %c %s\n",
6002 got_commitable_get_status(ct),
6003 got_commitable_get_path(ct));
6005 close(fd);
6007 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
6008 done:
6009 free(initial_content);
6010 free(template);
6012 /* Editor is done; we can now apply unveil(2) */
6013 if (err == NULL) {
6014 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6015 if (err) {
6016 free(*logmsg);
6017 *logmsg = NULL;
6020 return err;
6023 static const struct got_error *
6024 cmd_commit(int argc, char *argv[])
6026 const struct got_error *error = NULL;
6027 struct got_worktree *worktree = NULL;
6028 struct got_repository *repo = NULL;
6029 char *cwd = NULL, *id_str = NULL;
6030 struct got_object_id *id = NULL;
6031 const char *logmsg = NULL;
6032 struct collect_commit_logmsg_arg cl_arg;
6033 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6034 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6035 struct got_pathlist_head paths;
6037 TAILQ_INIT(&paths);
6038 cl_arg.logmsg_path = NULL;
6040 while ((ch = getopt(argc, argv, "m:")) != -1) {
6041 switch (ch) {
6042 case 'm':
6043 logmsg = optarg;
6044 break;
6045 default:
6046 usage_commit();
6047 /* NOTREACHED */
6051 argc -= optind;
6052 argv += optind;
6054 #ifndef PROFILE
6055 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6056 "unveil", NULL) == -1)
6057 err(1, "pledge");
6058 #endif
6059 cwd = getcwd(NULL, 0);
6060 if (cwd == NULL) {
6061 error = got_error_from_errno("getcwd");
6062 goto done;
6064 error = got_worktree_open(&worktree, cwd);
6065 if (error)
6066 goto done;
6068 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6069 if (error)
6070 goto done;
6071 if (rebase_in_progress) {
6072 error = got_error(GOT_ERR_REBASING);
6073 goto done;
6076 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6077 worktree);
6078 if (error)
6079 goto done;
6081 error = get_gitconfig_path(&gitconfig_path);
6082 if (error)
6083 goto done;
6084 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6085 gitconfig_path);
6086 if (error != NULL)
6087 goto done;
6089 error = get_author(&author, repo);
6090 if (error)
6091 return error;
6094 * unveil(2) traverses exec(2); if an editor is used we have
6095 * to apply unveil after the log message has been written.
6097 if (logmsg == NULL || strlen(logmsg) == 0)
6098 error = get_editor(&editor);
6099 else
6100 error = apply_unveil(got_repo_get_path(repo), 0,
6101 got_worktree_get_root_path(worktree));
6102 if (error)
6103 goto done;
6105 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6106 if (error)
6107 goto done;
6109 cl_arg.editor = editor;
6110 cl_arg.cmdline_log = logmsg;
6111 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6112 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6113 if (!histedit_in_progress) {
6114 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6115 error = got_error(GOT_ERR_COMMIT_BRANCH);
6116 goto done;
6118 cl_arg.branch_name += 11;
6120 cl_arg.repo_path = got_repo_get_path(repo);
6121 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6122 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
6123 if (error) {
6124 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6125 cl_arg.logmsg_path != NULL)
6126 preserve_logmsg = 1;
6127 goto done;
6130 error = got_object_id_str(&id_str, id);
6131 if (error)
6132 goto done;
6133 printf("Created commit %s\n", id_str);
6134 done:
6135 if (preserve_logmsg) {
6136 fprintf(stderr, "%s: log message preserved in %s\n",
6137 getprogname(), cl_arg.logmsg_path);
6138 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6139 error == NULL)
6140 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6141 free(cl_arg.logmsg_path);
6142 if (repo)
6143 got_repo_close(repo);
6144 if (worktree)
6145 got_worktree_close(worktree);
6146 free(cwd);
6147 free(id_str);
6148 free(gitconfig_path);
6149 free(editor);
6150 free(author);
6151 return error;
6154 __dead static void
6155 usage_cherrypick(void)
6157 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6158 exit(1);
6161 static const struct got_error *
6162 cmd_cherrypick(int argc, char *argv[])
6164 const struct got_error *error = NULL;
6165 struct got_worktree *worktree = NULL;
6166 struct got_repository *repo = NULL;
6167 char *cwd = NULL, *commit_id_str = NULL;
6168 struct got_object_id *commit_id = NULL;
6169 struct got_commit_object *commit = NULL;
6170 struct got_object_qid *pid;
6171 struct got_reference *head_ref = NULL;
6172 int ch, did_something = 0;
6174 while ((ch = getopt(argc, argv, "")) != -1) {
6175 switch (ch) {
6176 default:
6177 usage_cherrypick();
6178 /* NOTREACHED */
6182 argc -= optind;
6183 argv += optind;
6185 #ifndef PROFILE
6186 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6187 "unveil", NULL) == -1)
6188 err(1, "pledge");
6189 #endif
6190 if (argc != 1)
6191 usage_cherrypick();
6193 cwd = getcwd(NULL, 0);
6194 if (cwd == NULL) {
6195 error = got_error_from_errno("getcwd");
6196 goto done;
6198 error = got_worktree_open(&worktree, cwd);
6199 if (error)
6200 goto done;
6202 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6203 NULL);
6204 if (error != NULL)
6205 goto done;
6207 error = apply_unveil(got_repo_get_path(repo), 0,
6208 got_worktree_get_root_path(worktree));
6209 if (error)
6210 goto done;
6212 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6213 GOT_OBJ_TYPE_COMMIT, repo);
6214 if (error != NULL) {
6215 struct got_reference *ref;
6216 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6217 goto done;
6218 error = got_ref_open(&ref, repo, argv[0], 0);
6219 if (error != NULL)
6220 goto done;
6221 error = got_ref_resolve(&commit_id, repo, ref);
6222 got_ref_close(ref);
6223 if (error != NULL)
6224 goto done;
6226 error = got_object_id_str(&commit_id_str, commit_id);
6227 if (error)
6228 goto done;
6230 error = got_ref_open(&head_ref, repo,
6231 got_worktree_get_head_ref_name(worktree), 0);
6232 if (error != NULL)
6233 goto done;
6235 error = check_same_branch(commit_id, head_ref, NULL, repo);
6236 if (error) {
6237 if (error->code != GOT_ERR_ANCESTRY)
6238 goto done;
6239 error = NULL;
6240 } else {
6241 error = got_error(GOT_ERR_SAME_BRANCH);
6242 goto done;
6245 error = got_object_open_as_commit(&commit, repo, commit_id);
6246 if (error)
6247 goto done;
6248 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6249 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
6250 commit_id, repo, update_progress, &did_something, check_cancelled,
6251 NULL);
6252 if (error != NULL)
6253 goto done;
6255 if (did_something)
6256 printf("Merged commit %s\n", commit_id_str);
6257 done:
6258 if (commit)
6259 got_object_commit_close(commit);
6260 free(commit_id_str);
6261 if (head_ref)
6262 got_ref_close(head_ref);
6263 if (worktree)
6264 got_worktree_close(worktree);
6265 if (repo)
6266 got_repo_close(repo);
6267 return error;
6270 __dead static void
6271 usage_backout(void)
6273 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
6274 exit(1);
6277 static const struct got_error *
6278 cmd_backout(int argc, char *argv[])
6280 const struct got_error *error = NULL;
6281 struct got_worktree *worktree = NULL;
6282 struct got_repository *repo = NULL;
6283 char *cwd = NULL, *commit_id_str = NULL;
6284 struct got_object_id *commit_id = NULL;
6285 struct got_commit_object *commit = NULL;
6286 struct got_object_qid *pid;
6287 struct got_reference *head_ref = NULL;
6288 int ch, did_something = 0;
6290 while ((ch = getopt(argc, argv, "")) != -1) {
6291 switch (ch) {
6292 default:
6293 usage_backout();
6294 /* NOTREACHED */
6298 argc -= optind;
6299 argv += optind;
6301 #ifndef PROFILE
6302 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6303 "unveil", NULL) == -1)
6304 err(1, "pledge");
6305 #endif
6306 if (argc != 1)
6307 usage_backout();
6309 cwd = getcwd(NULL, 0);
6310 if (cwd == NULL) {
6311 error = got_error_from_errno("getcwd");
6312 goto done;
6314 error = got_worktree_open(&worktree, cwd);
6315 if (error)
6316 goto done;
6318 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6319 NULL);
6320 if (error != NULL)
6321 goto done;
6323 error = apply_unveil(got_repo_get_path(repo), 0,
6324 got_worktree_get_root_path(worktree));
6325 if (error)
6326 goto done;
6328 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6329 GOT_OBJ_TYPE_COMMIT, repo);
6330 if (error != NULL) {
6331 struct got_reference *ref;
6332 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6333 goto done;
6334 error = got_ref_open(&ref, repo, argv[0], 0);
6335 if (error != NULL)
6336 goto done;
6337 error = got_ref_resolve(&commit_id, repo, ref);
6338 got_ref_close(ref);
6339 if (error != NULL)
6340 goto done;
6342 error = got_object_id_str(&commit_id_str, commit_id);
6343 if (error)
6344 goto done;
6346 error = got_ref_open(&head_ref, repo,
6347 got_worktree_get_head_ref_name(worktree), 0);
6348 if (error != NULL)
6349 goto done;
6351 error = check_same_branch(commit_id, head_ref, NULL, repo);
6352 if (error)
6353 goto done;
6355 error = got_object_open_as_commit(&commit, repo, commit_id);
6356 if (error)
6357 goto done;
6358 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6359 if (pid == NULL) {
6360 error = got_error(GOT_ERR_ROOT_COMMIT);
6361 goto done;
6364 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
6365 update_progress, &did_something, check_cancelled, NULL);
6366 if (error != NULL)
6367 goto done;
6369 if (did_something)
6370 printf("Backed out commit %s\n", commit_id_str);
6371 done:
6372 if (commit)
6373 got_object_commit_close(commit);
6374 free(commit_id_str);
6375 if (head_ref)
6376 got_ref_close(head_ref);
6377 if (worktree)
6378 got_worktree_close(worktree);
6379 if (repo)
6380 got_repo_close(repo);
6381 return error;
6384 __dead static void
6385 usage_rebase(void)
6387 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
6388 getprogname());
6389 exit(1);
6392 void
6393 trim_logmsg(char *logmsg, int limit)
6395 char *nl;
6396 size_t len;
6398 len = strlen(logmsg);
6399 if (len > limit)
6400 len = limit;
6401 logmsg[len] = '\0';
6402 nl = strchr(logmsg, '\n');
6403 if (nl)
6404 *nl = '\0';
6407 static const struct got_error *
6408 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
6410 const struct got_error *err;
6411 char *logmsg0 = NULL;
6412 const char *s;
6414 err = got_object_commit_get_logmsg(&logmsg0, commit);
6415 if (err)
6416 return err;
6418 s = logmsg0;
6419 while (isspace((unsigned char)s[0]))
6420 s++;
6422 *logmsg = strdup(s);
6423 if (*logmsg == NULL) {
6424 err = got_error_from_errno("strdup");
6425 goto done;
6428 trim_logmsg(*logmsg, limit);
6429 done:
6430 free(logmsg0);
6431 return err;
6434 static const struct got_error *
6435 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
6437 const struct got_error *err;
6438 struct got_commit_object *commit = NULL;
6439 char *id_str = NULL, *logmsg = NULL;
6441 err = got_object_open_as_commit(&commit, repo, id);
6442 if (err)
6443 return err;
6445 err = got_object_id_str(&id_str, id);
6446 if (err)
6447 goto done;
6449 id_str[12] = '\0';
6451 err = get_short_logmsg(&logmsg, 42, commit);
6452 if (err)
6453 goto done;
6455 printf("%s -> merge conflict: %s\n", id_str, logmsg);
6456 done:
6457 free(id_str);
6458 got_object_commit_close(commit);
6459 free(logmsg);
6460 return err;
6463 static const struct got_error *
6464 show_rebase_progress(struct got_commit_object *commit,
6465 struct got_object_id *old_id, struct got_object_id *new_id)
6467 const struct got_error *err;
6468 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
6470 err = got_object_id_str(&old_id_str, old_id);
6471 if (err)
6472 goto done;
6474 if (new_id) {
6475 err = got_object_id_str(&new_id_str, new_id);
6476 if (err)
6477 goto done;
6480 old_id_str[12] = '\0';
6481 if (new_id_str)
6482 new_id_str[12] = '\0';
6484 err = get_short_logmsg(&logmsg, 42, commit);
6485 if (err)
6486 goto done;
6488 printf("%s -> %s: %s\n", old_id_str,
6489 new_id_str ? new_id_str : "no-op change", logmsg);
6490 done:
6491 free(old_id_str);
6492 free(new_id_str);
6493 free(logmsg);
6494 return err;
6497 static const struct got_error *
6498 rebase_progress(void *arg, unsigned char status, const char *path)
6500 unsigned char *rebase_status = arg;
6502 while (path[0] == '/')
6503 path++;
6504 printf("%c %s\n", status, path);
6506 if (*rebase_status == GOT_STATUS_CONFLICT)
6507 return NULL;
6508 if (status == GOT_STATUS_CONFLICT || status == GOT_STATUS_MERGE)
6509 *rebase_status = status;
6510 return NULL;
6513 static const struct got_error *
6514 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
6515 struct got_reference *branch, struct got_reference *new_base_branch,
6516 struct got_reference *tmp_branch, struct got_repository *repo)
6518 printf("Switching work tree to %s\n", got_ref_get_name(branch));
6519 return got_worktree_rebase_complete(worktree, fileindex,
6520 new_base_branch, tmp_branch, branch, repo);
6523 static const struct got_error *
6524 rebase_commit(struct got_pathlist_head *merged_paths,
6525 struct got_worktree *worktree, struct got_fileindex *fileindex,
6526 struct got_reference *tmp_branch,
6527 struct got_object_id *commit_id, struct got_repository *repo)
6529 const struct got_error *error;
6530 struct got_commit_object *commit;
6531 struct got_object_id *new_commit_id;
6533 error = got_object_open_as_commit(&commit, repo, commit_id);
6534 if (error)
6535 return error;
6537 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
6538 worktree, fileindex, tmp_branch, commit, commit_id, repo);
6539 if (error) {
6540 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
6541 goto done;
6542 error = show_rebase_progress(commit, commit_id, NULL);
6543 } else {
6544 error = show_rebase_progress(commit, commit_id, new_commit_id);
6545 free(new_commit_id);
6547 done:
6548 got_object_commit_close(commit);
6549 return error;
6552 struct check_path_prefix_arg {
6553 const char *path_prefix;
6554 size_t len;
6555 int errcode;
6558 static const struct got_error *
6559 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
6560 struct got_blob_object *blob2, struct got_object_id *id1,
6561 struct got_object_id *id2, const char *path1, const char *path2,
6562 mode_t mode1, mode_t mode2, struct got_repository *repo)
6564 struct check_path_prefix_arg *a = arg;
6566 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
6567 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
6568 return got_error(a->errcode);
6570 return NULL;
6573 static const struct got_error *
6574 check_path_prefix(struct got_object_id *parent_id,
6575 struct got_object_id *commit_id, const char *path_prefix,
6576 int errcode, struct got_repository *repo)
6578 const struct got_error *err;
6579 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
6580 struct got_commit_object *commit = NULL, *parent_commit = NULL;
6581 struct check_path_prefix_arg cpp_arg;
6583 if (got_path_is_root_dir(path_prefix))
6584 return NULL;
6586 err = got_object_open_as_commit(&commit, repo, commit_id);
6587 if (err)
6588 goto done;
6590 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
6591 if (err)
6592 goto done;
6594 err = got_object_open_as_tree(&tree1, repo,
6595 got_object_commit_get_tree_id(parent_commit));
6596 if (err)
6597 goto done;
6599 err = got_object_open_as_tree(&tree2, repo,
6600 got_object_commit_get_tree_id(commit));
6601 if (err)
6602 goto done;
6604 cpp_arg.path_prefix = path_prefix;
6605 while (cpp_arg.path_prefix[0] == '/')
6606 cpp_arg.path_prefix++;
6607 cpp_arg.len = strlen(cpp_arg.path_prefix);
6608 cpp_arg.errcode = errcode;
6609 err = got_diff_tree(tree1, tree2, "", "", repo,
6610 check_path_prefix_in_diff, &cpp_arg, 0);
6611 done:
6612 if (tree1)
6613 got_object_tree_close(tree1);
6614 if (tree2)
6615 got_object_tree_close(tree2);
6616 if (commit)
6617 got_object_commit_close(commit);
6618 if (parent_commit)
6619 got_object_commit_close(parent_commit);
6620 return err;
6623 static const struct got_error *
6624 collect_commits(struct got_object_id_queue *commits,
6625 struct got_object_id *initial_commit_id,
6626 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
6627 const char *path_prefix, int path_prefix_errcode,
6628 struct got_repository *repo)
6630 const struct got_error *err = NULL;
6631 struct got_commit_graph *graph = NULL;
6632 struct got_object_id *parent_id = NULL;
6633 struct got_object_qid *qid;
6634 struct got_object_id *commit_id = initial_commit_id;
6636 err = got_commit_graph_open(&graph, "/", 1);
6637 if (err)
6638 return err;
6640 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
6641 check_cancelled, NULL);
6642 if (err)
6643 goto done;
6644 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
6645 err = got_commit_graph_iter_next(&parent_id, graph, repo,
6646 check_cancelled, NULL);
6647 if (err) {
6648 if (err->code == GOT_ERR_ITER_COMPLETED) {
6649 err = got_error_msg(GOT_ERR_ANCESTRY,
6650 "ran out of commits to rebase before "
6651 "youngest common ancestor commit has "
6652 "been reached?!?");
6654 goto done;
6655 } else {
6656 err = check_path_prefix(parent_id, commit_id,
6657 path_prefix, path_prefix_errcode, repo);
6658 if (err)
6659 goto done;
6661 err = got_object_qid_alloc(&qid, commit_id);
6662 if (err)
6663 goto done;
6664 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
6665 commit_id = parent_id;
6668 done:
6669 got_commit_graph_close(graph);
6670 return err;
6673 static const struct got_error *
6674 cmd_rebase(int argc, char *argv[])
6676 const struct got_error *error = NULL;
6677 struct got_worktree *worktree = NULL;
6678 struct got_repository *repo = NULL;
6679 struct got_fileindex *fileindex = NULL;
6680 char *cwd = NULL;
6681 struct got_reference *branch = NULL;
6682 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
6683 struct got_object_id *commit_id = NULL, *parent_id = NULL;
6684 struct got_object_id *resume_commit_id = NULL;
6685 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
6686 struct got_commit_object *commit = NULL;
6687 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
6688 int histedit_in_progress = 0;
6689 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
6690 struct got_object_id_queue commits;
6691 struct got_pathlist_head merged_paths;
6692 const struct got_object_id_queue *parent_ids;
6693 struct got_object_qid *qid, *pid;
6695 SIMPLEQ_INIT(&commits);
6696 TAILQ_INIT(&merged_paths);
6698 while ((ch = getopt(argc, argv, "ac")) != -1) {
6699 switch (ch) {
6700 case 'a':
6701 abort_rebase = 1;
6702 break;
6703 case 'c':
6704 continue_rebase = 1;
6705 break;
6706 default:
6707 usage_rebase();
6708 /* NOTREACHED */
6712 argc -= optind;
6713 argv += optind;
6715 #ifndef PROFILE
6716 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6717 "unveil", NULL) == -1)
6718 err(1, "pledge");
6719 #endif
6720 if (abort_rebase && continue_rebase)
6721 usage_rebase();
6722 else if (abort_rebase || continue_rebase) {
6723 if (argc != 0)
6724 usage_rebase();
6725 } else if (argc != 1)
6726 usage_rebase();
6728 cwd = getcwd(NULL, 0);
6729 if (cwd == NULL) {
6730 error = got_error_from_errno("getcwd");
6731 goto done;
6733 error = got_worktree_open(&worktree, cwd);
6734 if (error)
6735 goto done;
6737 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6738 NULL);
6739 if (error != NULL)
6740 goto done;
6742 error = apply_unveil(got_repo_get_path(repo), 0,
6743 got_worktree_get_root_path(worktree));
6744 if (error)
6745 goto done;
6747 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6748 worktree);
6749 if (error)
6750 goto done;
6751 if (histedit_in_progress) {
6752 error = got_error(GOT_ERR_HISTEDIT_BUSY);
6753 goto done;
6756 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6757 if (error)
6758 goto done;
6760 if (abort_rebase) {
6761 int did_something;
6762 if (!rebase_in_progress) {
6763 error = got_error(GOT_ERR_NOT_REBASING);
6764 goto done;
6766 error = got_worktree_rebase_continue(&resume_commit_id,
6767 &new_base_branch, &tmp_branch, &branch, &fileindex,
6768 worktree, repo);
6769 if (error)
6770 goto done;
6771 printf("Switching work tree to %s\n",
6772 got_ref_get_symref_target(new_base_branch));
6773 error = got_worktree_rebase_abort(worktree, fileindex, repo,
6774 new_base_branch, update_progress, &did_something);
6775 if (error)
6776 goto done;
6777 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
6778 goto done; /* nothing else to do */
6781 if (continue_rebase) {
6782 if (!rebase_in_progress) {
6783 error = got_error(GOT_ERR_NOT_REBASING);
6784 goto done;
6786 error = got_worktree_rebase_continue(&resume_commit_id,
6787 &new_base_branch, &tmp_branch, &branch, &fileindex,
6788 worktree, repo);
6789 if (error)
6790 goto done;
6792 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
6793 resume_commit_id, repo);
6794 if (error)
6795 goto done;
6797 yca_id = got_object_id_dup(resume_commit_id);
6798 if (yca_id == NULL) {
6799 error = got_error_from_errno("got_object_id_dup");
6800 goto done;
6802 } else {
6803 error = got_ref_open(&branch, repo, argv[0], 0);
6804 if (error != NULL)
6805 goto done;
6808 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
6809 if (error)
6810 goto done;
6812 if (!continue_rebase) {
6813 struct got_object_id *base_commit_id;
6815 base_commit_id = got_worktree_get_base_commit_id(worktree);
6816 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
6817 base_commit_id, branch_head_commit_id, repo,
6818 check_cancelled, NULL);
6819 if (error)
6820 goto done;
6821 if (yca_id == NULL) {
6822 error = got_error_msg(GOT_ERR_ANCESTRY,
6823 "specified branch shares no common ancestry "
6824 "with work tree's branch");
6825 goto done;
6828 error = check_same_branch(base_commit_id, branch, yca_id, repo);
6829 if (error) {
6830 if (error->code != GOT_ERR_ANCESTRY)
6831 goto done;
6832 error = NULL;
6833 } else {
6834 error = got_error_msg(GOT_ERR_SAME_BRANCH,
6835 "specified branch resolves to a commit which "
6836 "is already contained in work tree's branch");
6837 goto done;
6839 error = got_worktree_rebase_prepare(&new_base_branch,
6840 &tmp_branch, &fileindex, worktree, branch, repo);
6841 if (error)
6842 goto done;
6845 commit_id = branch_head_commit_id;
6846 error = got_object_open_as_commit(&commit, repo, commit_id);
6847 if (error)
6848 goto done;
6850 parent_ids = got_object_commit_get_parent_ids(commit);
6851 pid = SIMPLEQ_FIRST(parent_ids);
6852 if (pid == NULL) {
6853 if (!continue_rebase) {
6854 int did_something;
6855 error = got_worktree_rebase_abort(worktree, fileindex,
6856 repo, new_base_branch, update_progress,
6857 &did_something);
6858 if (error)
6859 goto done;
6860 printf("Rebase of %s aborted\n",
6861 got_ref_get_name(branch));
6863 error = got_error(GOT_ERR_EMPTY_REBASE);
6864 goto done;
6866 error = collect_commits(&commits, commit_id, pid->id,
6867 yca_id, got_worktree_get_path_prefix(worktree),
6868 GOT_ERR_REBASE_PATH, repo);
6869 got_object_commit_close(commit);
6870 commit = NULL;
6871 if (error)
6872 goto done;
6874 if (SIMPLEQ_EMPTY(&commits)) {
6875 if (continue_rebase) {
6876 error = rebase_complete(worktree, fileindex,
6877 branch, new_base_branch, tmp_branch, repo);
6878 goto done;
6879 } else {
6880 /* Fast-forward the reference of the branch. */
6881 struct got_object_id *new_head_commit_id;
6882 char *id_str;
6883 error = got_ref_resolve(&new_head_commit_id, repo,
6884 new_base_branch);
6885 if (error)
6886 goto done;
6887 error = got_object_id_str(&id_str, new_head_commit_id);
6888 printf("Forwarding %s to commit %s\n",
6889 got_ref_get_name(branch), id_str);
6890 free(id_str);
6891 error = got_ref_change_ref(branch,
6892 new_head_commit_id);
6893 if (error)
6894 goto done;
6898 pid = NULL;
6899 SIMPLEQ_FOREACH(qid, &commits, entry) {
6900 commit_id = qid->id;
6901 parent_id = pid ? pid->id : yca_id;
6902 pid = qid;
6904 error = got_worktree_rebase_merge_files(&merged_paths,
6905 worktree, fileindex, parent_id, commit_id, repo,
6906 rebase_progress, &rebase_status, check_cancelled, NULL);
6907 if (error)
6908 goto done;
6910 if (rebase_status == GOT_STATUS_CONFLICT) {
6911 error = show_rebase_merge_conflict(qid->id, repo);
6912 if (error)
6913 goto done;
6914 got_worktree_rebase_pathlist_free(&merged_paths);
6915 break;
6918 error = rebase_commit(&merged_paths, worktree, fileindex,
6919 tmp_branch, commit_id, repo);
6920 got_worktree_rebase_pathlist_free(&merged_paths);
6921 if (error)
6922 goto done;
6925 if (rebase_status == GOT_STATUS_CONFLICT) {
6926 error = got_worktree_rebase_postpone(worktree, fileindex);
6927 if (error)
6928 goto done;
6929 error = got_error_msg(GOT_ERR_CONFLICTS,
6930 "conflicts must be resolved before rebasing can continue");
6931 } else
6932 error = rebase_complete(worktree, fileindex, branch,
6933 new_base_branch, tmp_branch, repo);
6934 done:
6935 got_object_id_queue_free(&commits);
6936 free(branch_head_commit_id);
6937 free(resume_commit_id);
6938 free(yca_id);
6939 if (commit)
6940 got_object_commit_close(commit);
6941 if (branch)
6942 got_ref_close(branch);
6943 if (new_base_branch)
6944 got_ref_close(new_base_branch);
6945 if (tmp_branch)
6946 got_ref_close(tmp_branch);
6947 if (worktree)
6948 got_worktree_close(worktree);
6949 if (repo)
6950 got_repo_close(repo);
6951 return error;
6954 __dead static void
6955 usage_histedit(void)
6957 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
6958 getprogname());
6959 exit(1);
6962 #define GOT_HISTEDIT_PICK 'p'
6963 #define GOT_HISTEDIT_EDIT 'e'
6964 #define GOT_HISTEDIT_FOLD 'f'
6965 #define GOT_HISTEDIT_DROP 'd'
6966 #define GOT_HISTEDIT_MESG 'm'
6968 static struct got_histedit_cmd {
6969 unsigned char code;
6970 const char *name;
6971 const char *desc;
6972 } got_histedit_cmds[] = {
6973 { GOT_HISTEDIT_PICK, "pick", "use commit" },
6974 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
6975 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
6976 "be used" },
6977 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
6978 { GOT_HISTEDIT_MESG, "mesg",
6979 "single-line log message for commit above (open editor if empty)" },
6982 struct got_histedit_list_entry {
6983 TAILQ_ENTRY(got_histedit_list_entry) entry;
6984 struct got_object_id *commit_id;
6985 const struct got_histedit_cmd *cmd;
6986 char *logmsg;
6988 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
6990 static const struct got_error *
6991 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
6992 FILE *f, struct got_repository *repo)
6994 const struct got_error *err = NULL;
6995 char *logmsg = NULL, *id_str = NULL;
6996 struct got_commit_object *commit = NULL;
6997 int n;
6999 err = got_object_open_as_commit(&commit, repo, commit_id);
7000 if (err)
7001 goto done;
7003 err = get_short_logmsg(&logmsg, 34, commit);
7004 if (err)
7005 goto done;
7007 err = got_object_id_str(&id_str, commit_id);
7008 if (err)
7009 goto done;
7011 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7012 if (n < 0)
7013 err = got_ferror(f, GOT_ERR_IO);
7014 done:
7015 if (commit)
7016 got_object_commit_close(commit);
7017 free(id_str);
7018 free(logmsg);
7019 return err;
7022 static const struct got_error *
7023 histedit_write_commit_list(struct got_object_id_queue *commits,
7024 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7026 const struct got_error *err = NULL;
7027 struct got_object_qid *qid;
7029 if (SIMPLEQ_EMPTY(commits))
7030 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7032 SIMPLEQ_FOREACH(qid, commits, entry) {
7033 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7034 f, repo);
7035 if (err)
7036 break;
7037 if (edit_logmsg_only) {
7038 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7039 if (n < 0) {
7040 err = got_ferror(f, GOT_ERR_IO);
7041 break;
7046 return err;
7049 static const struct got_error *
7050 write_cmd_list(FILE *f, const char *branch_name,
7051 struct got_object_id_queue *commits)
7053 const struct got_error *err = NULL;
7054 int n, i;
7055 char *id_str;
7056 struct got_object_qid *qid;
7058 qid = SIMPLEQ_FIRST(commits);
7059 err = got_object_id_str(&id_str, qid->id);
7060 if (err)
7061 return err;
7063 n = fprintf(f,
7064 "# Editing the history of branch '%s' starting at\n"
7065 "# commit %s\n"
7066 "# Commits will be processed in order from top to "
7067 "bottom of this file.\n", branch_name, id_str);
7068 if (n < 0) {
7069 err = got_ferror(f, GOT_ERR_IO);
7070 goto done;
7073 n = fprintf(f, "# Available histedit commands:\n");
7074 if (n < 0) {
7075 err = got_ferror(f, GOT_ERR_IO);
7076 goto done;
7079 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7080 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7081 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7082 cmd->desc);
7083 if (n < 0) {
7084 err = got_ferror(f, GOT_ERR_IO);
7085 break;
7088 done:
7089 free(id_str);
7090 return err;
7093 static const struct got_error *
7094 histedit_syntax_error(int lineno)
7096 static char msg[42];
7097 int ret;
7099 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7100 lineno);
7101 if (ret == -1 || ret >= sizeof(msg))
7102 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7104 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7107 static const struct got_error *
7108 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7109 char *logmsg, struct got_repository *repo)
7111 const struct got_error *err;
7112 struct got_commit_object *folded_commit = NULL;
7113 char *id_str, *folded_logmsg = NULL;
7115 err = got_object_id_str(&id_str, hle->commit_id);
7116 if (err)
7117 return err;
7119 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7120 if (err)
7121 goto done;
7123 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7124 if (err)
7125 goto done;
7126 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7127 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7128 folded_logmsg) == -1) {
7129 err = got_error_from_errno("asprintf");
7131 done:
7132 if (folded_commit)
7133 got_object_commit_close(folded_commit);
7134 free(id_str);
7135 free(folded_logmsg);
7136 return err;
7139 static struct got_histedit_list_entry *
7140 get_folded_commits(struct got_histedit_list_entry *hle)
7142 struct got_histedit_list_entry *prev, *folded = NULL;
7144 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7145 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7146 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7147 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7148 folded = prev;
7149 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7152 return folded;
7155 static const struct got_error *
7156 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7157 struct got_repository *repo)
7159 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7160 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7161 const struct got_error *err = NULL;
7162 struct got_commit_object *commit = NULL;
7163 int fd;
7164 struct got_histedit_list_entry *folded = NULL;
7166 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7167 if (err)
7168 return err;
7170 folded = get_folded_commits(hle);
7171 if (folded) {
7172 while (folded != hle) {
7173 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7174 folded = TAILQ_NEXT(folded, entry);
7175 continue;
7177 err = append_folded_commit_msg(&new_msg, folded,
7178 logmsg, repo);
7179 if (err)
7180 goto done;
7181 free(logmsg);
7182 logmsg = new_msg;
7183 folded = TAILQ_NEXT(folded, entry);
7187 err = got_object_id_str(&id_str, hle->commit_id);
7188 if (err)
7189 goto done;
7190 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7191 if (err)
7192 goto done;
7193 if (asprintf(&new_msg,
7194 "%s\n# original log message of commit %s: %s",
7195 logmsg ? logmsg : "", id_str, orig_logmsg) == -1) {
7196 err = got_error_from_errno("asprintf");
7197 goto done;
7199 free(logmsg);
7200 logmsg = new_msg;
7202 err = got_object_id_str(&id_str, hle->commit_id);
7203 if (err)
7204 goto done;
7206 err = got_opentemp_named_fd(&logmsg_path, &fd,
7207 GOT_TMPDIR_STR "/got-logmsg");
7208 if (err)
7209 goto done;
7211 dprintf(fd, logmsg);
7212 close(fd);
7214 err = get_editor(&editor);
7215 if (err)
7216 goto done;
7218 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
7219 if (err) {
7220 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
7221 goto done;
7222 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
7224 done:
7225 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
7226 err = got_error_from_errno2("unlink", logmsg_path);
7227 free(logmsg_path);
7228 free(logmsg);
7229 free(orig_logmsg);
7230 free(editor);
7231 if (commit)
7232 got_object_commit_close(commit);
7233 return err;
7236 static const struct got_error *
7237 histedit_parse_list(struct got_histedit_list *histedit_cmds,
7238 FILE *f, struct got_repository *repo)
7240 const struct got_error *err = NULL;
7241 char *line = NULL, *p, *end;
7242 size_t size;
7243 ssize_t len;
7244 int lineno = 0, i;
7245 const struct got_histedit_cmd *cmd;
7246 struct got_object_id *commit_id = NULL;
7247 struct got_histedit_list_entry *hle = NULL;
7249 for (;;) {
7250 len = getline(&line, &size, f);
7251 if (len == -1) {
7252 const struct got_error *getline_err;
7253 if (feof(f))
7254 break;
7255 getline_err = got_error_from_errno("getline");
7256 err = got_ferror(f, getline_err->code);
7257 break;
7259 lineno++;
7260 p = line;
7261 while (isspace((unsigned char)p[0]))
7262 p++;
7263 if (p[0] == '#' || p[0] == '\0') {
7264 free(line);
7265 line = NULL;
7266 continue;
7268 cmd = NULL;
7269 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7270 cmd = &got_histedit_cmds[i];
7271 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
7272 isspace((unsigned char)p[strlen(cmd->name)])) {
7273 p += strlen(cmd->name);
7274 break;
7276 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
7277 p++;
7278 break;
7281 if (i == nitems(got_histedit_cmds)) {
7282 err = histedit_syntax_error(lineno);
7283 break;
7285 while (isspace((unsigned char)p[0]))
7286 p++;
7287 if (cmd->code == GOT_HISTEDIT_MESG) {
7288 if (hle == NULL || hle->logmsg != NULL) {
7289 err = got_error(GOT_ERR_HISTEDIT_CMD);
7290 break;
7292 if (p[0] == '\0') {
7293 err = histedit_edit_logmsg(hle, repo);
7294 if (err)
7295 break;
7296 } else {
7297 hle->logmsg = strdup(p);
7298 if (hle->logmsg == NULL) {
7299 err = got_error_from_errno("strdup");
7300 break;
7303 free(line);
7304 line = NULL;
7305 continue;
7306 } else {
7307 end = p;
7308 while (end[0] && !isspace((unsigned char)end[0]))
7309 end++;
7310 *end = '\0';
7312 err = got_object_resolve_id_str(&commit_id, repo, p);
7313 if (err) {
7314 /* override error code */
7315 err = histedit_syntax_error(lineno);
7316 break;
7319 hle = malloc(sizeof(*hle));
7320 if (hle == NULL) {
7321 err = got_error_from_errno("malloc");
7322 break;
7324 hle->cmd = cmd;
7325 hle->commit_id = commit_id;
7326 hle->logmsg = NULL;
7327 commit_id = NULL;
7328 free(line);
7329 line = NULL;
7330 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
7333 free(line);
7334 free(commit_id);
7335 return err;
7338 static const struct got_error *
7339 histedit_check_script(struct got_histedit_list *histedit_cmds,
7340 struct got_object_id_queue *commits, struct got_repository *repo)
7342 const struct got_error *err = NULL;
7343 struct got_object_qid *qid;
7344 struct got_histedit_list_entry *hle;
7345 static char msg[92];
7346 char *id_str;
7348 if (TAILQ_EMPTY(histedit_cmds))
7349 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
7350 "histedit script contains no commands");
7351 if (SIMPLEQ_EMPTY(commits))
7352 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7354 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7355 struct got_histedit_list_entry *hle2;
7356 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
7357 if (hle == hle2)
7358 continue;
7359 if (got_object_id_cmp(hle->commit_id,
7360 hle2->commit_id) != 0)
7361 continue;
7362 err = got_object_id_str(&id_str, hle->commit_id);
7363 if (err)
7364 return err;
7365 snprintf(msg, sizeof(msg), "commit %s is listed "
7366 "more than once in histedit script", id_str);
7367 free(id_str);
7368 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7372 SIMPLEQ_FOREACH(qid, commits, entry) {
7373 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7374 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
7375 break;
7377 if (hle == NULL) {
7378 err = got_object_id_str(&id_str, qid->id);
7379 if (err)
7380 return err;
7381 snprintf(msg, sizeof(msg),
7382 "commit %s missing from histedit script", id_str);
7383 free(id_str);
7384 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7388 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
7389 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
7390 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
7391 "last commit in histedit script cannot be folded");
7393 return NULL;
7396 static const struct got_error *
7397 histedit_run_editor(struct got_histedit_list *histedit_cmds,
7398 const char *path, struct got_object_id_queue *commits,
7399 struct got_repository *repo)
7401 const struct got_error *err = NULL;
7402 char *editor;
7403 FILE *f = NULL;
7405 err = get_editor(&editor);
7406 if (err)
7407 return err;
7409 if (spawn_editor(editor, path) == -1) {
7410 err = got_error_from_errno("failed spawning editor");
7411 goto done;
7414 f = fopen(path, "r");
7415 if (f == NULL) {
7416 err = got_error_from_errno("fopen");
7417 goto done;
7419 err = histedit_parse_list(histedit_cmds, f, repo);
7420 if (err)
7421 goto done;
7423 err = histedit_check_script(histedit_cmds, commits, repo);
7424 done:
7425 if (f && fclose(f) != 0 && err == NULL)
7426 err = got_error_from_errno("fclose");
7427 free(editor);
7428 return err;
7431 static const struct got_error *
7432 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
7433 struct got_object_id_queue *, const char *, const char *,
7434 struct got_repository *);
7436 static const struct got_error *
7437 histedit_edit_script(struct got_histedit_list *histedit_cmds,
7438 struct got_object_id_queue *commits, const char *branch_name,
7439 int edit_logmsg_only, struct got_repository *repo)
7441 const struct got_error *err;
7442 FILE *f = NULL;
7443 char *path = NULL;
7445 err = got_opentemp_named(&path, &f, "got-histedit");
7446 if (err)
7447 return err;
7449 err = write_cmd_list(f, branch_name, commits);
7450 if (err)
7451 goto done;
7453 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
7454 if (err)
7455 goto done;
7457 if (edit_logmsg_only) {
7458 rewind(f);
7459 err = histedit_parse_list(histedit_cmds, f, repo);
7460 } else {
7461 if (fclose(f) != 0) {
7462 err = got_error_from_errno("fclose");
7463 goto done;
7465 f = NULL;
7466 err = histedit_run_editor(histedit_cmds, path, commits, repo);
7467 if (err) {
7468 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7469 err->code != GOT_ERR_HISTEDIT_CMD)
7470 goto done;
7471 err = histedit_edit_list_retry(histedit_cmds, err,
7472 commits, path, branch_name, repo);
7475 done:
7476 if (f && fclose(f) != 0 && err == NULL)
7477 err = got_error_from_errno("fclose");
7478 if (path && unlink(path) != 0 && err == NULL)
7479 err = got_error_from_errno2("unlink", path);
7480 free(path);
7481 return err;
7484 static const struct got_error *
7485 histedit_save_list(struct got_histedit_list *histedit_cmds,
7486 struct got_worktree *worktree, struct got_repository *repo)
7488 const struct got_error *err = NULL;
7489 char *path = NULL;
7490 FILE *f = NULL;
7491 struct got_histedit_list_entry *hle;
7492 struct got_commit_object *commit = NULL;
7494 err = got_worktree_get_histedit_script_path(&path, worktree);
7495 if (err)
7496 return err;
7498 f = fopen(path, "w");
7499 if (f == NULL) {
7500 err = got_error_from_errno2("fopen", path);
7501 goto done;
7503 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7504 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
7505 repo);
7506 if (err)
7507 break;
7509 if (hle->logmsg) {
7510 int n = fprintf(f, "%c %s\n",
7511 GOT_HISTEDIT_MESG, hle->logmsg);
7512 if (n < 0) {
7513 err = got_ferror(f, GOT_ERR_IO);
7514 break;
7518 done:
7519 if (f && fclose(f) != 0 && err == NULL)
7520 err = got_error_from_errno("fclose");
7521 free(path);
7522 if (commit)
7523 got_object_commit_close(commit);
7524 return err;
7527 void
7528 histedit_free_list(struct got_histedit_list *histedit_cmds)
7530 struct got_histedit_list_entry *hle;
7532 while ((hle = TAILQ_FIRST(histedit_cmds))) {
7533 TAILQ_REMOVE(histedit_cmds, hle, entry);
7534 free(hle);
7538 static const struct got_error *
7539 histedit_load_list(struct got_histedit_list *histedit_cmds,
7540 const char *path, struct got_repository *repo)
7542 const struct got_error *err = NULL;
7543 FILE *f = NULL;
7545 f = fopen(path, "r");
7546 if (f == NULL) {
7547 err = got_error_from_errno2("fopen", path);
7548 goto done;
7551 err = histedit_parse_list(histedit_cmds, f, repo);
7552 done:
7553 if (f && fclose(f) != 0 && err == NULL)
7554 err = got_error_from_errno("fclose");
7555 return err;
7558 static const struct got_error *
7559 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
7560 const struct got_error *edit_err, struct got_object_id_queue *commits,
7561 const char *path, const char *branch_name, struct got_repository *repo)
7563 const struct got_error *err = NULL, *prev_err = edit_err;
7564 int resp = ' ';
7566 while (resp != 'c' && resp != 'r' && resp != 'a') {
7567 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
7568 "or (a)bort: ", getprogname(), prev_err->msg);
7569 resp = getchar();
7570 if (resp == '\n')
7571 resp = getchar();
7572 if (resp == 'c') {
7573 histedit_free_list(histedit_cmds);
7574 err = histedit_run_editor(histedit_cmds, path, commits,
7575 repo);
7576 if (err) {
7577 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7578 err->code != GOT_ERR_HISTEDIT_CMD)
7579 break;
7580 prev_err = err;
7581 resp = ' ';
7582 continue;
7584 break;
7585 } else if (resp == 'r') {
7586 histedit_free_list(histedit_cmds);
7587 err = histedit_edit_script(histedit_cmds,
7588 commits, branch_name, 0, repo);
7589 if (err) {
7590 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7591 err->code != GOT_ERR_HISTEDIT_CMD)
7592 break;
7593 prev_err = err;
7594 resp = ' ';
7595 continue;
7597 break;
7598 } else if (resp == 'a') {
7599 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
7600 break;
7601 } else
7602 printf("invalid response '%c'\n", resp);
7605 return err;
7608 static const struct got_error *
7609 histedit_complete(struct got_worktree *worktree,
7610 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
7611 struct got_reference *branch, struct got_repository *repo)
7613 printf("Switching work tree to %s\n",
7614 got_ref_get_symref_target(branch));
7615 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
7616 branch, repo);
7619 static const struct got_error *
7620 show_histedit_progress(struct got_commit_object *commit,
7621 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
7623 const struct got_error *err;
7624 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7626 err = got_object_id_str(&old_id_str, hle->commit_id);
7627 if (err)
7628 goto done;
7630 if (new_id) {
7631 err = got_object_id_str(&new_id_str, new_id);
7632 if (err)
7633 goto done;
7636 old_id_str[12] = '\0';
7637 if (new_id_str)
7638 new_id_str[12] = '\0';
7640 if (hle->logmsg) {
7641 logmsg = strdup(hle->logmsg);
7642 if (logmsg == NULL) {
7643 err = got_error_from_errno("strdup");
7644 goto done;
7646 trim_logmsg(logmsg, 42);
7647 } else {
7648 err = get_short_logmsg(&logmsg, 42, commit);
7649 if (err)
7650 goto done;
7653 switch (hle->cmd->code) {
7654 case GOT_HISTEDIT_PICK:
7655 case GOT_HISTEDIT_EDIT:
7656 printf("%s -> %s: %s\n", old_id_str,
7657 new_id_str ? new_id_str : "no-op change", logmsg);
7658 break;
7659 case GOT_HISTEDIT_DROP:
7660 case GOT_HISTEDIT_FOLD:
7661 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
7662 logmsg);
7663 break;
7664 default:
7665 break;
7667 done:
7668 free(old_id_str);
7669 free(new_id_str);
7670 return err;
7673 static const struct got_error *
7674 histedit_commit(struct got_pathlist_head *merged_paths,
7675 struct got_worktree *worktree, struct got_fileindex *fileindex,
7676 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
7677 struct got_repository *repo)
7679 const struct got_error *err;
7680 struct got_commit_object *commit;
7681 struct got_object_id *new_commit_id;
7683 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
7684 && hle->logmsg == NULL) {
7685 err = histedit_edit_logmsg(hle, repo);
7686 if (err)
7687 return err;
7690 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7691 if (err)
7692 return err;
7694 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
7695 worktree, fileindex, tmp_branch, commit, hle->commit_id,
7696 hle->logmsg, repo);
7697 if (err) {
7698 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
7699 goto done;
7700 err = show_histedit_progress(commit, hle, NULL);
7701 } else {
7702 err = show_histedit_progress(commit, hle, new_commit_id);
7703 free(new_commit_id);
7705 done:
7706 got_object_commit_close(commit);
7707 return err;
7710 static const struct got_error *
7711 histedit_skip_commit(struct got_histedit_list_entry *hle,
7712 struct got_worktree *worktree, struct got_repository *repo)
7714 const struct got_error *error;
7715 struct got_commit_object *commit;
7717 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
7718 repo);
7719 if (error)
7720 return error;
7722 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
7723 if (error)
7724 return error;
7726 error = show_histedit_progress(commit, hle, NULL);
7727 got_object_commit_close(commit);
7728 return error;
7731 static const struct got_error *
7732 check_local_changes(void *arg, unsigned char status,
7733 unsigned char staged_status, const char *path,
7734 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
7735 struct got_object_id *commit_id, int dirfd, const char *de_name)
7737 int *have_local_changes = arg;
7739 switch (status) {
7740 case GOT_STATUS_ADD:
7741 case GOT_STATUS_DELETE:
7742 case GOT_STATUS_MODIFY:
7743 case GOT_STATUS_CONFLICT:
7744 *have_local_changes = 1;
7745 return got_error(GOT_ERR_CANCELLED);
7746 default:
7747 break;
7750 switch (staged_status) {
7751 case GOT_STATUS_ADD:
7752 case GOT_STATUS_DELETE:
7753 case GOT_STATUS_MODIFY:
7754 *have_local_changes = 1;
7755 return got_error(GOT_ERR_CANCELLED);
7756 default:
7757 break;
7760 return NULL;
7763 static const struct got_error *
7764 cmd_histedit(int argc, char *argv[])
7766 const struct got_error *error = NULL;
7767 struct got_worktree *worktree = NULL;
7768 struct got_fileindex *fileindex = NULL;
7769 struct got_repository *repo = NULL;
7770 char *cwd = NULL;
7771 struct got_reference *branch = NULL;
7772 struct got_reference *tmp_branch = NULL;
7773 struct got_object_id *resume_commit_id = NULL;
7774 struct got_object_id *base_commit_id = NULL;
7775 struct got_object_id *head_commit_id = NULL;
7776 struct got_commit_object *commit = NULL;
7777 int ch, rebase_in_progress = 0, did_something;
7778 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
7779 int edit_logmsg_only = 0;
7780 const char *edit_script_path = NULL;
7781 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7782 struct got_object_id_queue commits;
7783 struct got_pathlist_head merged_paths;
7784 const struct got_object_id_queue *parent_ids;
7785 struct got_object_qid *pid;
7786 struct got_histedit_list histedit_cmds;
7787 struct got_histedit_list_entry *hle;
7789 SIMPLEQ_INIT(&commits);
7790 TAILQ_INIT(&histedit_cmds);
7791 TAILQ_INIT(&merged_paths);
7793 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
7794 switch (ch) {
7795 case 'a':
7796 abort_edit = 1;
7797 break;
7798 case 'c':
7799 continue_edit = 1;
7800 break;
7801 case 'F':
7802 edit_script_path = optarg;
7803 break;
7804 case 'm':
7805 edit_logmsg_only = 1;
7806 break;
7807 default:
7808 usage_histedit();
7809 /* NOTREACHED */
7813 argc -= optind;
7814 argv += optind;
7816 #ifndef PROFILE
7817 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7818 "unveil", NULL) == -1)
7819 err(1, "pledge");
7820 #endif
7821 if (abort_edit && continue_edit)
7822 errx(1, "histedit's -a and -c options are mutually exclusive");
7823 if (edit_script_path && edit_logmsg_only)
7824 errx(1, "histedit's -F and -m options are mutually exclusive");
7825 if (abort_edit && edit_logmsg_only)
7826 errx(1, "histedit's -a and -m options are mutually exclusive");
7827 if (continue_edit && edit_logmsg_only)
7828 errx(1, "histedit's -c and -m options are mutually exclusive");
7829 if (argc != 0)
7830 usage_histedit();
7833 * This command cannot apply unveil(2) in all cases because the
7834 * user may choose to run an editor to edit the histedit script
7835 * and to edit individual commit log messages.
7836 * unveil(2) traverses exec(2); if an editor is used we have to
7837 * apply unveil after edit script and log messages have been written.
7838 * XXX TODO: Make use of unveil(2) where possible.
7841 cwd = getcwd(NULL, 0);
7842 if (cwd == NULL) {
7843 error = got_error_from_errno("getcwd");
7844 goto done;
7846 error = got_worktree_open(&worktree, cwd);
7847 if (error)
7848 goto done;
7850 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7851 NULL);
7852 if (error != NULL)
7853 goto done;
7855 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7856 if (error)
7857 goto done;
7858 if (rebase_in_progress) {
7859 error = got_error(GOT_ERR_REBASING);
7860 goto done;
7863 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
7864 if (error)
7865 goto done;
7867 if (edit_in_progress && edit_logmsg_only) {
7868 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
7869 "histedit operation is in progress in this "
7870 "work tree and must be continued or aborted "
7871 "before the -m option can be used");
7872 goto done;
7875 if (edit_in_progress && abort_edit) {
7876 error = got_worktree_histedit_continue(&resume_commit_id,
7877 &tmp_branch, &branch, &base_commit_id, &fileindex,
7878 worktree, repo);
7879 if (error)
7880 goto done;
7881 printf("Switching work tree to %s\n",
7882 got_ref_get_symref_target(branch));
7883 error = got_worktree_histedit_abort(worktree, fileindex, repo,
7884 branch, base_commit_id, update_progress, &did_something);
7885 if (error)
7886 goto done;
7887 printf("Histedit of %s aborted\n",
7888 got_ref_get_symref_target(branch));
7889 goto done; /* nothing else to do */
7890 } else if (abort_edit) {
7891 error = got_error(GOT_ERR_NOT_HISTEDIT);
7892 goto done;
7895 if (continue_edit) {
7896 char *path;
7898 if (!edit_in_progress) {
7899 error = got_error(GOT_ERR_NOT_HISTEDIT);
7900 goto done;
7903 error = got_worktree_get_histedit_script_path(&path, worktree);
7904 if (error)
7905 goto done;
7907 error = histedit_load_list(&histedit_cmds, path, repo);
7908 free(path);
7909 if (error)
7910 goto done;
7912 error = got_worktree_histedit_continue(&resume_commit_id,
7913 &tmp_branch, &branch, &base_commit_id, &fileindex,
7914 worktree, repo);
7915 if (error)
7916 goto done;
7918 error = got_ref_resolve(&head_commit_id, repo, branch);
7919 if (error)
7920 goto done;
7922 error = got_object_open_as_commit(&commit, repo,
7923 head_commit_id);
7924 if (error)
7925 goto done;
7926 parent_ids = got_object_commit_get_parent_ids(commit);
7927 pid = SIMPLEQ_FIRST(parent_ids);
7928 if (pid == NULL) {
7929 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
7930 goto done;
7932 error = collect_commits(&commits, head_commit_id, pid->id,
7933 base_commit_id, got_worktree_get_path_prefix(worktree),
7934 GOT_ERR_HISTEDIT_PATH, repo);
7935 got_object_commit_close(commit);
7936 commit = NULL;
7937 if (error)
7938 goto done;
7939 } else {
7940 if (edit_in_progress) {
7941 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7942 goto done;
7945 error = got_ref_open(&branch, repo,
7946 got_worktree_get_head_ref_name(worktree), 0);
7947 if (error != NULL)
7948 goto done;
7950 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
7951 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
7952 "will not edit commit history of a branch outside "
7953 "the \"refs/heads/\" reference namespace");
7954 goto done;
7957 error = got_ref_resolve(&head_commit_id, repo, branch);
7958 got_ref_close(branch);
7959 branch = NULL;
7960 if (error)
7961 goto done;
7963 error = got_object_open_as_commit(&commit, repo,
7964 head_commit_id);
7965 if (error)
7966 goto done;
7967 parent_ids = got_object_commit_get_parent_ids(commit);
7968 pid = SIMPLEQ_FIRST(parent_ids);
7969 if (pid == NULL) {
7970 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
7971 goto done;
7973 error = collect_commits(&commits, head_commit_id, pid->id,
7974 got_worktree_get_base_commit_id(worktree),
7975 got_worktree_get_path_prefix(worktree),
7976 GOT_ERR_HISTEDIT_PATH, repo);
7977 got_object_commit_close(commit);
7978 commit = NULL;
7979 if (error)
7980 goto done;
7982 if (SIMPLEQ_EMPTY(&commits)) {
7983 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
7984 goto done;
7987 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
7988 &base_commit_id, &fileindex, worktree, repo);
7989 if (error)
7990 goto done;
7992 if (edit_script_path) {
7993 error = histedit_load_list(&histedit_cmds,
7994 edit_script_path, repo);
7995 if (error) {
7996 got_worktree_histedit_abort(worktree, fileindex,
7997 repo, branch, base_commit_id,
7998 update_progress, &did_something);
7999 goto done;
8001 } else {
8002 const char *branch_name;
8003 branch_name = got_ref_get_symref_target(branch);
8004 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8005 branch_name += 11;
8006 error = histedit_edit_script(&histedit_cmds, &commits,
8007 branch_name, edit_logmsg_only, repo);
8008 if (error) {
8009 got_worktree_histedit_abort(worktree, fileindex,
8010 repo, branch, base_commit_id,
8011 update_progress, &did_something);
8012 goto done;
8017 error = histedit_save_list(&histedit_cmds, worktree,
8018 repo);
8019 if (error) {
8020 got_worktree_histedit_abort(worktree, fileindex,
8021 repo, branch, base_commit_id,
8022 update_progress, &did_something);
8023 goto done;
8028 error = histedit_check_script(&histedit_cmds, &commits, repo);
8029 if (error)
8030 goto done;
8032 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8033 if (resume_commit_id) {
8034 if (got_object_id_cmp(hle->commit_id,
8035 resume_commit_id) != 0)
8036 continue;
8038 resume_commit_id = NULL;
8039 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8040 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8041 error = histedit_skip_commit(hle, worktree,
8042 repo);
8043 if (error)
8044 goto done;
8045 } else {
8046 struct got_pathlist_head paths;
8047 int have_changes = 0;
8049 TAILQ_INIT(&paths);
8050 error = got_pathlist_append(&paths, "", NULL);
8051 if (error)
8052 goto done;
8053 error = got_worktree_status(worktree, &paths,
8054 repo, check_local_changes, &have_changes,
8055 check_cancelled, NULL);
8056 got_pathlist_free(&paths);
8057 if (error) {
8058 if (error->code != GOT_ERR_CANCELLED)
8059 goto done;
8060 if (sigint_received || sigpipe_received)
8061 goto done;
8063 if (have_changes) {
8064 error = histedit_commit(NULL, worktree,
8065 fileindex, tmp_branch, hle, repo);
8066 if (error)
8067 goto done;
8068 } else {
8069 error = got_object_open_as_commit(
8070 &commit, repo, hle->commit_id);
8071 if (error)
8072 goto done;
8073 error = show_histedit_progress(commit,
8074 hle, NULL);
8075 got_object_commit_close(commit);
8076 commit = NULL;
8077 if (error)
8078 goto done;
8081 continue;
8084 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8085 error = histedit_skip_commit(hle, worktree, repo);
8086 if (error)
8087 goto done;
8088 continue;
8091 error = got_object_open_as_commit(&commit, repo,
8092 hle->commit_id);
8093 if (error)
8094 goto done;
8095 parent_ids = got_object_commit_get_parent_ids(commit);
8096 pid = SIMPLEQ_FIRST(parent_ids);
8098 error = got_worktree_histedit_merge_files(&merged_paths,
8099 worktree, fileindex, pid->id, hle->commit_id, repo,
8100 rebase_progress, &rebase_status, check_cancelled, NULL);
8101 if (error)
8102 goto done;
8103 got_object_commit_close(commit);
8104 commit = NULL;
8106 if (rebase_status == GOT_STATUS_CONFLICT) {
8107 error = show_rebase_merge_conflict(hle->commit_id,
8108 repo);
8109 if (error)
8110 goto done;
8111 got_worktree_rebase_pathlist_free(&merged_paths);
8112 break;
8115 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8116 char *id_str;
8117 error = got_object_id_str(&id_str, hle->commit_id);
8118 if (error)
8119 goto done;
8120 printf("Stopping histedit for amending commit %s\n",
8121 id_str);
8122 free(id_str);
8123 got_worktree_rebase_pathlist_free(&merged_paths);
8124 error = got_worktree_histedit_postpone(worktree,
8125 fileindex);
8126 goto done;
8129 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8130 error = histedit_skip_commit(hle, worktree, repo);
8131 if (error)
8132 goto done;
8133 continue;
8136 error = histedit_commit(&merged_paths, worktree, fileindex,
8137 tmp_branch, hle, repo);
8138 got_worktree_rebase_pathlist_free(&merged_paths);
8139 if (error)
8140 goto done;
8143 if (rebase_status == GOT_STATUS_CONFLICT) {
8144 error = got_worktree_histedit_postpone(worktree, fileindex);
8145 if (error)
8146 goto done;
8147 error = got_error_msg(GOT_ERR_CONFLICTS,
8148 "conflicts must be resolved before histedit can continue");
8149 } else
8150 error = histedit_complete(worktree, fileindex, tmp_branch,
8151 branch, repo);
8152 done:
8153 got_object_id_queue_free(&commits);
8154 histedit_free_list(&histedit_cmds);
8155 free(head_commit_id);
8156 free(base_commit_id);
8157 free(resume_commit_id);
8158 if (commit)
8159 got_object_commit_close(commit);
8160 if (branch)
8161 got_ref_close(branch);
8162 if (tmp_branch)
8163 got_ref_close(tmp_branch);
8164 if (worktree)
8165 got_worktree_close(worktree);
8166 if (repo)
8167 got_repo_close(repo);
8168 return error;
8171 __dead static void
8172 usage_integrate(void)
8174 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
8175 exit(1);
8178 static const struct got_error *
8179 cmd_integrate(int argc, char *argv[])
8181 const struct got_error *error = NULL;
8182 struct got_repository *repo = NULL;
8183 struct got_worktree *worktree = NULL;
8184 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
8185 const char *branch_arg = NULL;
8186 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
8187 struct got_fileindex *fileindex = NULL;
8188 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
8189 int ch, did_something = 0;
8191 while ((ch = getopt(argc, argv, "")) != -1) {
8192 switch (ch) {
8193 default:
8194 usage_integrate();
8195 /* NOTREACHED */
8199 argc -= optind;
8200 argv += optind;
8202 if (argc != 1)
8203 usage_integrate();
8204 branch_arg = argv[0];
8206 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8207 "unveil", NULL) == -1)
8208 err(1, "pledge");
8210 cwd = getcwd(NULL, 0);
8211 if (cwd == NULL) {
8212 error = got_error_from_errno("getcwd");
8213 goto done;
8216 error = got_worktree_open(&worktree, cwd);
8217 if (error)
8218 goto done;
8220 error = check_rebase_or_histedit_in_progress(worktree);
8221 if (error)
8222 goto done;
8224 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8225 NULL);
8226 if (error != NULL)
8227 goto done;
8229 error = apply_unveil(got_repo_get_path(repo), 0,
8230 got_worktree_get_root_path(worktree));
8231 if (error)
8232 goto done;
8234 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
8235 error = got_error_from_errno("asprintf");
8236 goto done;
8239 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
8240 &base_branch_ref, worktree, refname, repo);
8241 if (error)
8242 goto done;
8244 refname = strdup(got_ref_get_name(branch_ref));
8245 if (refname == NULL) {
8246 error = got_error_from_errno("strdup");
8247 got_worktree_integrate_abort(worktree, fileindex, repo,
8248 branch_ref, base_branch_ref);
8249 goto done;
8251 base_refname = strdup(got_ref_get_name(base_branch_ref));
8252 if (base_refname == NULL) {
8253 error = got_error_from_errno("strdup");
8254 got_worktree_integrate_abort(worktree, fileindex, repo,
8255 branch_ref, base_branch_ref);
8256 goto done;
8259 error = got_ref_resolve(&commit_id, repo, branch_ref);
8260 if (error)
8261 goto done;
8263 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
8264 if (error)
8265 goto done;
8267 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
8268 error = got_error_msg(GOT_ERR_SAME_BRANCH,
8269 "specified branch has already been integrated");
8270 got_worktree_integrate_abort(worktree, fileindex, repo,
8271 branch_ref, base_branch_ref);
8272 goto done;
8275 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
8276 if (error) {
8277 if (error->code == GOT_ERR_ANCESTRY)
8278 error = got_error(GOT_ERR_REBASE_REQUIRED);
8279 got_worktree_integrate_abort(worktree, fileindex, repo,
8280 branch_ref, base_branch_ref);
8281 goto done;
8284 error = got_worktree_integrate_continue(worktree, fileindex, repo,
8285 branch_ref, base_branch_ref, update_progress, &did_something,
8286 check_cancelled, NULL);
8287 if (error)
8288 goto done;
8290 printf("Integrated %s into %s\n", refname, base_refname);
8291 done:
8292 if (repo)
8293 got_repo_close(repo);
8294 if (worktree)
8295 got_worktree_close(worktree);
8296 free(cwd);
8297 free(base_commit_id);
8298 free(commit_id);
8299 free(refname);
8300 free(base_refname);
8301 return error;
8304 __dead static void
8305 usage_stage(void)
8307 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
8308 "[file-path ...]\n",
8309 getprogname());
8310 exit(1);
8313 static const struct got_error *
8314 print_stage(void *arg, unsigned char status, unsigned char staged_status,
8315 const char *path, struct got_object_id *blob_id,
8316 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
8317 int dirfd, const char *de_name)
8319 const struct got_error *err = NULL;
8320 char *id_str = NULL;
8322 if (staged_status != GOT_STATUS_ADD &&
8323 staged_status != GOT_STATUS_MODIFY &&
8324 staged_status != GOT_STATUS_DELETE)
8325 return NULL;
8327 if (staged_status == GOT_STATUS_ADD ||
8328 staged_status == GOT_STATUS_MODIFY)
8329 err = got_object_id_str(&id_str, staged_blob_id);
8330 else
8331 err = got_object_id_str(&id_str, blob_id);
8332 if (err)
8333 return err;
8335 printf("%s %c %s\n", id_str, staged_status, path);
8336 free(id_str);
8337 return NULL;
8340 static const struct got_error *
8341 cmd_stage(int argc, char *argv[])
8343 const struct got_error *error = NULL;
8344 struct got_repository *repo = NULL;
8345 struct got_worktree *worktree = NULL;
8346 char *cwd = NULL;
8347 struct got_pathlist_head paths;
8348 struct got_pathlist_entry *pe;
8349 int ch, list_stage = 0, pflag = 0;
8350 FILE *patch_script_file = NULL;
8351 const char *patch_script_path = NULL;
8352 struct choose_patch_arg cpa;
8354 TAILQ_INIT(&paths);
8356 while ((ch = getopt(argc, argv, "lpF:")) != -1) {
8357 switch (ch) {
8358 case 'l':
8359 list_stage = 1;
8360 break;
8361 case 'p':
8362 pflag = 1;
8363 break;
8364 case 'F':
8365 patch_script_path = optarg;
8366 break;
8367 default:
8368 usage_stage();
8369 /* NOTREACHED */
8373 argc -= optind;
8374 argv += optind;
8376 #ifndef PROFILE
8377 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8378 "unveil", NULL) == -1)
8379 err(1, "pledge");
8380 #endif
8381 if (list_stage && (pflag || patch_script_path))
8382 errx(1, "-l option cannot be used with other options");
8383 if (patch_script_path && !pflag)
8384 errx(1, "-F option can only be used together with -p option");
8386 cwd = getcwd(NULL, 0);
8387 if (cwd == NULL) {
8388 error = got_error_from_errno("getcwd");
8389 goto done;
8392 error = got_worktree_open(&worktree, cwd);
8393 if (error)
8394 goto done;
8396 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8397 NULL);
8398 if (error != NULL)
8399 goto done;
8401 if (patch_script_path) {
8402 patch_script_file = fopen(patch_script_path, "r");
8403 if (patch_script_file == NULL) {
8404 error = got_error_from_errno2("fopen",
8405 patch_script_path);
8406 goto done;
8409 error = apply_unveil(got_repo_get_path(repo), 0,
8410 got_worktree_get_root_path(worktree));
8411 if (error)
8412 goto done;
8414 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8415 if (error)
8416 goto done;
8418 if (list_stage)
8419 error = got_worktree_status(worktree, &paths, repo,
8420 print_stage, NULL, check_cancelled, NULL);
8421 else {
8422 cpa.patch_script_file = patch_script_file;
8423 cpa.action = "stage";
8424 error = got_worktree_stage(worktree, &paths,
8425 pflag ? NULL : print_status, NULL,
8426 pflag ? choose_patch : NULL, &cpa, repo);
8428 done:
8429 if (patch_script_file && fclose(patch_script_file) == EOF &&
8430 error == NULL)
8431 error = got_error_from_errno2("fclose", patch_script_path);
8432 if (repo)
8433 got_repo_close(repo);
8434 if (worktree)
8435 got_worktree_close(worktree);
8436 TAILQ_FOREACH(pe, &paths, entry)
8437 free((char *)pe->path);
8438 got_pathlist_free(&paths);
8439 free(cwd);
8440 return error;
8443 __dead static void
8444 usage_unstage(void)
8446 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
8447 "[file-path ...]\n",
8448 getprogname());
8449 exit(1);
8453 static const struct got_error *
8454 cmd_unstage(int argc, char *argv[])
8456 const struct got_error *error = NULL;
8457 struct got_repository *repo = NULL;
8458 struct got_worktree *worktree = NULL;
8459 char *cwd = NULL;
8460 struct got_pathlist_head paths;
8461 struct got_pathlist_entry *pe;
8462 int ch, did_something = 0, pflag = 0;
8463 FILE *patch_script_file = NULL;
8464 const char *patch_script_path = NULL;
8465 struct choose_patch_arg cpa;
8467 TAILQ_INIT(&paths);
8469 while ((ch = getopt(argc, argv, "pF:")) != -1) {
8470 switch (ch) {
8471 case 'p':
8472 pflag = 1;
8473 break;
8474 case 'F':
8475 patch_script_path = optarg;
8476 break;
8477 default:
8478 usage_unstage();
8479 /* NOTREACHED */
8483 argc -= optind;
8484 argv += optind;
8486 #ifndef PROFILE
8487 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8488 "unveil", NULL) == -1)
8489 err(1, "pledge");
8490 #endif
8491 if (patch_script_path && !pflag)
8492 errx(1, "-F option can only be used together with -p option");
8494 cwd = getcwd(NULL, 0);
8495 if (cwd == NULL) {
8496 error = got_error_from_errno("getcwd");
8497 goto done;
8500 error = got_worktree_open(&worktree, cwd);
8501 if (error)
8502 goto done;
8504 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8505 NULL);
8506 if (error != NULL)
8507 goto done;
8509 if (patch_script_path) {
8510 patch_script_file = fopen(patch_script_path, "r");
8511 if (patch_script_file == NULL) {
8512 error = got_error_from_errno2("fopen",
8513 patch_script_path);
8514 goto done;
8518 error = apply_unveil(got_repo_get_path(repo), 0,
8519 got_worktree_get_root_path(worktree));
8520 if (error)
8521 goto done;
8523 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8524 if (error)
8525 goto done;
8527 cpa.patch_script_file = patch_script_file;
8528 cpa.action = "unstage";
8529 error = got_worktree_unstage(worktree, &paths, update_progress,
8530 &did_something, pflag ? choose_patch : NULL, &cpa, repo);
8531 done:
8532 if (patch_script_file && fclose(patch_script_file) == EOF &&
8533 error == NULL)
8534 error = got_error_from_errno2("fclose", patch_script_path);
8535 if (repo)
8536 got_repo_close(repo);
8537 if (worktree)
8538 got_worktree_close(worktree);
8539 TAILQ_FOREACH(pe, &paths, entry)
8540 free((char *)pe->path);
8541 got_pathlist_free(&paths);
8542 free(cwd);
8543 return error;
8546 __dead static void
8547 usage_cat(void)
8549 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
8550 "arg1 [arg2 ...]\n", getprogname());
8551 exit(1);
8554 static const struct got_error *
8555 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8557 const struct got_error *err;
8558 struct got_blob_object *blob;
8560 err = got_object_open_as_blob(&blob, repo, id, 8192);
8561 if (err)
8562 return err;
8564 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
8565 got_object_blob_close(blob);
8566 return err;
8569 static const struct got_error *
8570 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8572 const struct got_error *err;
8573 struct got_tree_object *tree;
8574 int nentries, i;
8576 err = got_object_open_as_tree(&tree, repo, id);
8577 if (err)
8578 return err;
8580 nentries = got_object_tree_get_nentries(tree);
8581 for (i = 0; i < nentries; i++) {
8582 struct got_tree_entry *te;
8583 char *id_str;
8584 if (sigint_received || sigpipe_received)
8585 break;
8586 te = got_object_tree_get_entry(tree, i);
8587 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
8588 if (err)
8589 break;
8590 fprintf(outfile, "%s %.7o %s\n", id_str,
8591 got_tree_entry_get_mode(te),
8592 got_tree_entry_get_name(te));
8593 free(id_str);
8596 got_object_tree_close(tree);
8597 return err;
8600 static const struct got_error *
8601 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8603 const struct got_error *err;
8604 struct got_commit_object *commit;
8605 const struct got_object_id_queue *parent_ids;
8606 struct got_object_qid *pid;
8607 char *id_str = NULL;
8608 const char *logmsg = NULL;
8610 err = got_object_open_as_commit(&commit, repo, id);
8611 if (err)
8612 return err;
8614 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
8615 if (err)
8616 goto done;
8618 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
8619 parent_ids = got_object_commit_get_parent_ids(commit);
8620 fprintf(outfile, "numparents %d\n",
8621 got_object_commit_get_nparents(commit));
8622 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
8623 char *pid_str;
8624 err = got_object_id_str(&pid_str, pid->id);
8625 if (err)
8626 goto done;
8627 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
8628 free(pid_str);
8630 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
8631 got_object_commit_get_author(commit),
8632 got_object_commit_get_author_time(commit));
8634 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
8635 got_object_commit_get_author(commit),
8636 got_object_commit_get_committer_time(commit));
8638 logmsg = got_object_commit_get_logmsg_raw(commit);
8639 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
8640 fprintf(outfile, "%s", logmsg);
8641 done:
8642 free(id_str);
8643 got_object_commit_close(commit);
8644 return err;
8647 static const struct got_error *
8648 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8650 const struct got_error *err;
8651 struct got_tag_object *tag;
8652 char *id_str = NULL;
8653 const char *tagmsg = NULL;
8655 err = got_object_open_as_tag(&tag, repo, id);
8656 if (err)
8657 return err;
8659 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
8660 if (err)
8661 goto done;
8663 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
8665 switch (got_object_tag_get_object_type(tag)) {
8666 case GOT_OBJ_TYPE_BLOB:
8667 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8668 GOT_OBJ_LABEL_BLOB);
8669 break;
8670 case GOT_OBJ_TYPE_TREE:
8671 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8672 GOT_OBJ_LABEL_TREE);
8673 break;
8674 case GOT_OBJ_TYPE_COMMIT:
8675 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8676 GOT_OBJ_LABEL_COMMIT);
8677 break;
8678 case GOT_OBJ_TYPE_TAG:
8679 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8680 GOT_OBJ_LABEL_TAG);
8681 break;
8682 default:
8683 break;
8686 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
8687 got_object_tag_get_name(tag));
8689 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
8690 got_object_tag_get_tagger(tag),
8691 got_object_tag_get_tagger_time(tag));
8693 tagmsg = got_object_tag_get_message(tag);
8694 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
8695 fprintf(outfile, "%s", tagmsg);
8696 done:
8697 free(id_str);
8698 got_object_tag_close(tag);
8699 return err;
8702 static const struct got_error *
8703 cmd_cat(int argc, char *argv[])
8705 const struct got_error *error;
8706 struct got_repository *repo = NULL;
8707 struct got_worktree *worktree = NULL;
8708 char *cwd = NULL, *repo_path = NULL, *label = NULL;
8709 const char *commit_id_str = NULL;
8710 struct got_object_id *id = NULL, *commit_id = NULL;
8711 int ch, obj_type, i, force_path = 0;
8713 #ifndef PROFILE
8714 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8715 NULL) == -1)
8716 err(1, "pledge");
8717 #endif
8719 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
8720 switch (ch) {
8721 case 'c':
8722 commit_id_str = optarg;
8723 break;
8724 case 'r':
8725 repo_path = realpath(optarg, NULL);
8726 if (repo_path == NULL)
8727 return got_error_from_errno2("realpath",
8728 optarg);
8729 got_path_strip_trailing_slashes(repo_path);
8730 break;
8731 case 'P':
8732 force_path = 1;
8733 break;
8734 default:
8735 usage_cat();
8736 /* NOTREACHED */
8740 argc -= optind;
8741 argv += optind;
8743 cwd = getcwd(NULL, 0);
8744 if (cwd == NULL) {
8745 error = got_error_from_errno("getcwd");
8746 goto done;
8748 error = got_worktree_open(&worktree, cwd);
8749 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8750 goto done;
8751 if (worktree) {
8752 if (repo_path == NULL) {
8753 repo_path = strdup(
8754 got_worktree_get_repo_path(worktree));
8755 if (repo_path == NULL) {
8756 error = got_error_from_errno("strdup");
8757 goto done;
8762 if (repo_path == NULL) {
8763 repo_path = getcwd(NULL, 0);
8764 if (repo_path == NULL)
8765 return got_error_from_errno("getcwd");
8768 error = got_repo_open(&repo, repo_path, NULL);
8769 free(repo_path);
8770 if (error != NULL)
8771 goto done;
8773 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
8774 if (error)
8775 goto done;
8777 if (commit_id_str == NULL)
8778 commit_id_str = GOT_REF_HEAD;
8779 error = got_repo_match_object_id(&commit_id, NULL,
8780 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
8781 if (error)
8782 goto done;
8784 for (i = 0; i < argc; i++) {
8785 if (force_path) {
8786 error = got_object_id_by_path(&id, repo, commit_id,
8787 argv[i]);
8788 if (error)
8789 break;
8790 } else {
8791 error = got_repo_match_object_id(&id, &label, argv[i],
8792 GOT_OBJ_TYPE_ANY, 0, repo);
8793 if (error) {
8794 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
8795 error->code != GOT_ERR_NOT_REF)
8796 break;
8797 error = got_object_id_by_path(&id, repo,
8798 commit_id, argv[i]);
8799 if (error)
8800 break;
8804 error = got_object_get_type(&obj_type, repo, id);
8805 if (error)
8806 break;
8808 switch (obj_type) {
8809 case GOT_OBJ_TYPE_BLOB:
8810 error = cat_blob(id, repo, stdout);
8811 break;
8812 case GOT_OBJ_TYPE_TREE:
8813 error = cat_tree(id, repo, stdout);
8814 break;
8815 case GOT_OBJ_TYPE_COMMIT:
8816 error = cat_commit(id, repo, stdout);
8817 break;
8818 case GOT_OBJ_TYPE_TAG:
8819 error = cat_tag(id, repo, stdout);
8820 break;
8821 default:
8822 error = got_error(GOT_ERR_OBJ_TYPE);
8823 break;
8825 if (error)
8826 break;
8827 free(label);
8828 label = NULL;
8829 free(id);
8830 id = NULL;
8832 done:
8833 free(label);
8834 free(id);
8835 free(commit_id);
8836 if (worktree)
8837 got_worktree_close(worktree);
8838 if (repo) {
8839 const struct got_error *repo_error;
8840 repo_error = got_repo_close(repo);
8841 if (error == NULL)
8842 error = repo_error;
8844 return error;