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"
57 #include "got_gotconfig.h"
59 #ifndef nitems
60 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
61 #endif
63 static volatile sig_atomic_t sigint_received;
64 static volatile sig_atomic_t sigpipe_received;
66 static void
67 catch_sigint(int signo)
68 {
69 sigint_received = 1;
70 }
72 static void
73 catch_sigpipe(int signo)
74 {
75 sigpipe_received = 1;
76 }
79 struct got_cmd {
80 const char *cmd_name;
81 const struct got_error *(*cmd_main)(int, char *[]);
82 void (*cmd_usage)(void);
83 const char *cmd_alias;
84 };
86 __dead static void usage(int);
87 __dead static void usage_init(void);
88 __dead static void usage_import(void);
89 __dead static void usage_clone(void);
90 __dead static void usage_fetch(void);
91 __dead static void usage_checkout(void);
92 __dead static void usage_update(void);
93 __dead static void usage_log(void);
94 __dead static void usage_diff(void);
95 __dead static void usage_blame(void);
96 __dead static void usage_tree(void);
97 __dead static void usage_status(void);
98 __dead static void usage_ref(void);
99 __dead static void usage_branch(void);
100 __dead static void usage_tag(void);
101 __dead static void usage_add(void);
102 __dead static void usage_remove(void);
103 __dead static void usage_revert(void);
104 __dead static void usage_commit(void);
105 __dead static void usage_cherrypick(void);
106 __dead static void usage_backout(void);
107 __dead static void usage_rebase(void);
108 __dead static void usage_histedit(void);
109 __dead static void usage_integrate(void);
110 __dead static void usage_stage(void);
111 __dead static void usage_unstage(void);
112 __dead static void usage_cat(void);
113 __dead static void usage_info(void);
115 static const struct got_error* cmd_init(int, char *[]);
116 static const struct got_error* cmd_import(int, char *[]);
117 static const struct got_error* cmd_clone(int, char *[]);
118 static const struct got_error* cmd_fetch(int, char *[]);
119 static const struct got_error* cmd_checkout(int, char *[]);
120 static const struct got_error* cmd_update(int, char *[]);
121 static const struct got_error* cmd_log(int, char *[]);
122 static const struct got_error* cmd_diff(int, char *[]);
123 static const struct got_error* cmd_blame(int, char *[]);
124 static const struct got_error* cmd_tree(int, char *[]);
125 static const struct got_error* cmd_status(int, char *[]);
126 static const struct got_error* cmd_ref(int, char *[]);
127 static const struct got_error* cmd_branch(int, char *[]);
128 static const struct got_error* cmd_tag(int, char *[]);
129 static const struct got_error* cmd_add(int, char *[]);
130 static const struct got_error* cmd_remove(int, char *[]);
131 static const struct got_error* cmd_revert(int, char *[]);
132 static const struct got_error* cmd_commit(int, char *[]);
133 static const struct got_error* cmd_cherrypick(int, char *[]);
134 static const struct got_error* cmd_backout(int, char *[]);
135 static const struct got_error* cmd_rebase(int, char *[]);
136 static const struct got_error* cmd_histedit(int, char *[]);
137 static const struct got_error* cmd_integrate(int, char *[]);
138 static const struct got_error* cmd_stage(int, char *[]);
139 static const struct got_error* cmd_unstage(int, char *[]);
140 static const struct got_error* cmd_cat(int, char *[]);
141 static const struct got_error* cmd_info(int, char *[]);
143 static struct got_cmd got_commands[] = {
144 { "init", cmd_init, usage_init, "" },
145 { "import", cmd_import, usage_import, "im" },
146 { "clone", cmd_clone, usage_clone, "cl" },
147 { "fetch", cmd_fetch, usage_fetch, "fe" },
148 { "checkout", cmd_checkout, usage_checkout, "co" },
149 { "update", cmd_update, usage_update, "up" },
150 { "log", cmd_log, usage_log, "" },
151 { "diff", cmd_diff, usage_diff, "di" },
152 { "blame", cmd_blame, usage_blame, "bl" },
153 { "tree", cmd_tree, usage_tree, "tr" },
154 { "status", cmd_status, usage_status, "st" },
155 { "ref", cmd_ref, usage_ref, "" },
156 { "branch", cmd_branch, usage_branch, "br" },
157 { "tag", cmd_tag, usage_tag, "" },
158 { "add", cmd_add, usage_add, "" },
159 { "remove", cmd_remove, usage_remove, "rm" },
160 { "revert", cmd_revert, usage_revert, "rv" },
161 { "commit", cmd_commit, usage_commit, "ci" },
162 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
163 { "backout", cmd_backout, usage_backout, "bo" },
164 { "rebase", cmd_rebase, usage_rebase, "rb" },
165 { "histedit", cmd_histedit, usage_histedit, "he" },
166 { "integrate", cmd_integrate, usage_integrate,"ig" },
167 { "stage", cmd_stage, usage_stage, "sg" },
168 { "unstage", cmd_unstage, usage_unstage, "ug" },
169 { "cat", cmd_cat, usage_cat, "" },
170 { "info", cmd_info, usage_info, "" },
171 };
173 static void
174 list_commands(void)
176 int i;
178 fprintf(stderr, "commands:");
179 for (i = 0; i < nitems(got_commands); i++) {
180 struct got_cmd *cmd = &got_commands[i];
181 fprintf(stderr, " %s", cmd->cmd_name);
183 fputc('\n', stderr);
186 int
187 main(int argc, char *argv[])
189 struct got_cmd *cmd;
190 unsigned int i;
191 int ch;
192 int hflag = 0, Vflag = 0;
193 static struct option longopts[] = {
194 { "version", no_argument, NULL, 'V' },
195 { NULL, 0, NULL, 0}
196 };
198 setlocale(LC_CTYPE, "");
200 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
201 switch (ch) {
202 case 'h':
203 hflag = 1;
204 break;
205 case 'V':
206 Vflag = 1;
207 break;
208 default:
209 usage(hflag);
210 /* NOTREACHED */
214 argc -= optind;
215 argv += optind;
216 optind = 0;
218 if (Vflag) {
219 got_version_print_str();
220 return 1;
223 if (argc <= 0)
224 usage(hflag);
226 signal(SIGINT, catch_sigint);
227 signal(SIGPIPE, catch_sigpipe);
229 for (i = 0; i < nitems(got_commands); i++) {
230 const struct got_error *error;
232 cmd = &got_commands[i];
234 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
235 strcmp(cmd->cmd_alias, argv[0]) != 0)
236 continue;
238 if (hflag)
239 got_commands[i].cmd_usage();
241 error = got_commands[i].cmd_main(argc, argv);
242 if (error && error->code != GOT_ERR_CANCELLED &&
243 error->code != GOT_ERR_PRIVSEP_EXIT &&
244 !(sigpipe_received &&
245 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
246 !(sigint_received &&
247 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
248 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
249 return 1;
252 return 0;
255 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
256 list_commands();
257 return 1;
260 __dead static void
261 usage(int hflag)
263 fprintf(stderr, "usage: %s [-h] [-V | --version] command [arg ...]\n",
264 getprogname());
265 if (hflag)
266 list_commands();
267 exit(1);
270 static const struct got_error *
271 get_editor(char **abspath)
273 const struct got_error *err = NULL;
274 const char *editor;
276 *abspath = NULL;
278 editor = getenv("VISUAL");
279 if (editor == NULL)
280 editor = getenv("EDITOR");
282 if (editor) {
283 err = got_path_find_prog(abspath, editor);
284 if (err)
285 return err;
288 if (*abspath == NULL) {
289 *abspath = strdup("/bin/ed");
290 if (*abspath == NULL)
291 return got_error_from_errno("strdup");
294 return NULL;
297 static const struct got_error *
298 apply_unveil(const char *repo_path, int repo_read_only,
299 const char *worktree_path)
301 const struct got_error *err;
303 #ifdef PROFILE
304 if (unveil("gmon.out", "rwc") != 0)
305 return got_error_from_errno2("unveil", "gmon.out");
306 #endif
307 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
308 return got_error_from_errno2("unveil", repo_path);
310 if (worktree_path && unveil(worktree_path, "rwc") != 0)
311 return got_error_from_errno2("unveil", worktree_path);
313 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
314 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
316 err = got_privsep_unveil_exec_helpers();
317 if (err != NULL)
318 return err;
320 if (unveil(NULL, NULL) != 0)
321 return got_error_from_errno("unveil");
323 return NULL;
326 __dead static void
327 usage_init(void)
329 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
330 exit(1);
333 static const struct got_error *
334 cmd_init(int argc, char *argv[])
336 const struct got_error *error = NULL;
337 char *repo_path = NULL;
338 int ch;
340 while ((ch = getopt(argc, argv, "")) != -1) {
341 switch (ch) {
342 default:
343 usage_init();
344 /* NOTREACHED */
348 argc -= optind;
349 argv += optind;
351 #ifndef PROFILE
352 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
353 err(1, "pledge");
354 #endif
355 if (argc != 1)
356 usage_init();
358 repo_path = strdup(argv[0]);
359 if (repo_path == NULL)
360 return got_error_from_errno("strdup");
362 got_path_strip_trailing_slashes(repo_path);
364 error = got_path_mkdir(repo_path);
365 if (error &&
366 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
367 goto done;
369 error = apply_unveil(repo_path, 0, NULL);
370 if (error)
371 goto done;
373 error = got_repo_init(repo_path);
374 done:
375 free(repo_path);
376 return error;
379 __dead static void
380 usage_import(void)
382 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
383 "[-r repository-path] [-I pattern] path\n", getprogname());
384 exit(1);
387 int
388 spawn_editor(const char *editor, const char *file)
390 pid_t pid;
391 sig_t sighup, sigint, sigquit;
392 int st = -1;
394 sighup = signal(SIGHUP, SIG_IGN);
395 sigint = signal(SIGINT, SIG_IGN);
396 sigquit = signal(SIGQUIT, SIG_IGN);
398 switch (pid = fork()) {
399 case -1:
400 goto doneediting;
401 case 0:
402 execl(editor, editor, file, (char *)NULL);
403 _exit(127);
406 while (waitpid(pid, &st, 0) == -1)
407 if (errno != EINTR)
408 break;
410 doneediting:
411 (void)signal(SIGHUP, sighup);
412 (void)signal(SIGINT, sigint);
413 (void)signal(SIGQUIT, sigquit);
415 if (!WIFEXITED(st)) {
416 errno = EINTR;
417 return -1;
420 return WEXITSTATUS(st);
423 static const struct got_error *
424 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
425 const char *initial_content)
427 const struct got_error *err = NULL;
428 char buf[1024];
429 struct stat st, st2;
430 FILE *fp;
431 int content_changed = 0;
432 size_t len;
434 *logmsg = NULL;
436 if (stat(logmsg_path, &st) == -1)
437 return got_error_from_errno2("stat", logmsg_path);
439 if (spawn_editor(editor, logmsg_path) == -1)
440 return got_error_from_errno("failed spawning editor");
442 if (stat(logmsg_path, &st2) == -1)
443 return got_error_from_errno("stat");
445 if (st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
446 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
447 "no changes made to commit message, aborting");
449 *logmsg = malloc(st2.st_size + 1);
450 if (*logmsg == NULL)
451 return got_error_from_errno("malloc");
452 (*logmsg)[0] = '\0';
453 len = 0;
455 fp = fopen(logmsg_path, "r");
456 if (fp == NULL) {
457 err = got_error_from_errno("fopen");
458 goto done;
460 while (fgets(buf, sizeof(buf), fp) != NULL) {
461 if (!content_changed && strcmp(buf, initial_content) != 0)
462 content_changed = 1;
463 if (buf[0] == '#' || (len == 0 && buf[0] == '\n'))
464 continue; /* remove comments and leading empty lines */
465 len = strlcat(*logmsg, buf, st2.st_size);
467 fclose(fp);
469 while (len > 0 && (*logmsg)[len - 1] == '\n') {
470 (*logmsg)[len - 1] = '\0';
471 len--;
474 if (len == 0 || !content_changed)
475 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
476 "commit message cannot be empty, aborting");
477 done:
478 if (err) {
479 free(*logmsg);
480 *logmsg = NULL;
482 return err;
485 static const struct got_error *
486 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
487 const char *path_dir, const char *branch_name)
489 char *initial_content = NULL;
490 const struct got_error *err = NULL;
491 int initial_content_len;
492 int fd = -1;
494 initial_content_len = asprintf(&initial_content,
495 "\n# %s to be imported to branch %s\n", path_dir,
496 branch_name);
497 if (initial_content_len == -1)
498 return got_error_from_errno("asprintf");
500 err = got_opentemp_named_fd(logmsg_path, &fd,
501 GOT_TMPDIR_STR "/got-importmsg");
502 if (err)
503 goto done;
505 if (write(fd, initial_content, initial_content_len) == -1) {
506 err = got_error_from_errno2("write", *logmsg_path);
507 goto done;
510 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content);
511 done:
512 if (fd != -1 && close(fd) == -1 && err == NULL)
513 err = got_error_from_errno2("close", *logmsg_path);
514 free(initial_content);
515 if (err) {
516 free(*logmsg_path);
517 *logmsg_path = NULL;
519 return err;
522 static const struct got_error *
523 import_progress(void *arg, const char *path)
525 printf("A %s\n", path);
526 return NULL;
529 static const struct got_error *
530 get_author(char **author, struct got_repository *repo,
531 struct got_worktree *worktree)
533 const struct got_error *err = NULL;
534 const char *got_author = NULL, *name, *email;
535 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
537 *author = NULL;
539 if (worktree)
540 worktree_conf = got_worktree_get_gotconfig(worktree);
541 repo_conf = got_repo_get_gotconfig(repo);
543 /*
544 * Priority of potential author information sources, from most
545 * significant to least significant:
546 * 1) work tree's .got/got.conf file
547 * 2) repository's got.conf file
548 * 3) repository's git config file
549 * 4) environment variables
550 * 5) global git config files (in user's home directory or /etc)
551 */
553 if (worktree_conf)
554 got_author = got_gotconfig_get_author(worktree_conf);
555 if (got_author == NULL)
556 got_author = got_gotconfig_get_author(repo_conf);
557 if (got_author == NULL) {
558 name = got_repo_get_gitconfig_author_name(repo);
559 email = got_repo_get_gitconfig_author_email(repo);
560 if (name && email) {
561 if (asprintf(author, "%s <%s>", name, email) == -1)
562 return got_error_from_errno("asprintf");
563 return NULL;
566 got_author = getenv("GOT_AUTHOR");
567 if (got_author == NULL) {
568 name = got_repo_get_global_gitconfig_author_name(repo);
569 email = got_repo_get_global_gitconfig_author_email(
570 repo);
571 if (name && email) {
572 if (asprintf(author, "%s <%s>", name, email)
573 == -1)
574 return got_error_from_errno("asprintf");
575 return NULL;
577 /* TODO: Look up user in password database? */
578 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
582 *author = strdup(got_author);
583 if (*author == NULL)
584 return got_error_from_errno("strdup");
586 /*
587 * Really dumb email address check; we're only doing this to
588 * avoid git's object parser breaking on commits we create.
589 */
590 while (*got_author && *got_author != '<')
591 got_author++;
592 if (*got_author != '<') {
593 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
594 goto done;
596 while (*got_author && *got_author != '@')
597 got_author++;
598 if (*got_author != '@') {
599 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
600 goto done;
602 while (*got_author && *got_author != '>')
603 got_author++;
604 if (*got_author != '>')
605 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
606 done:
607 if (err) {
608 free(*author);
609 *author = NULL;
611 return err;
614 static const struct got_error *
615 get_gitconfig_path(char **gitconfig_path)
617 const char *homedir = getenv("HOME");
619 *gitconfig_path = NULL;
620 if (homedir) {
621 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
622 return got_error_from_errno("asprintf");
625 return NULL;
628 static const struct got_error *
629 cmd_import(int argc, char *argv[])
631 const struct got_error *error = NULL;
632 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
633 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
634 const char *branch_name = "main";
635 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
636 struct got_repository *repo = NULL;
637 struct got_reference *branch_ref = NULL, *head_ref = NULL;
638 struct got_object_id *new_commit_id = NULL;
639 int ch;
640 struct got_pathlist_head ignores;
641 struct got_pathlist_entry *pe;
642 int preserve_logmsg = 0;
644 TAILQ_INIT(&ignores);
646 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
647 switch (ch) {
648 case 'b':
649 branch_name = optarg;
650 break;
651 case 'm':
652 logmsg = strdup(optarg);
653 if (logmsg == NULL) {
654 error = got_error_from_errno("strdup");
655 goto done;
657 break;
658 case 'r':
659 repo_path = realpath(optarg, NULL);
660 if (repo_path == NULL) {
661 error = got_error_from_errno2("realpath",
662 optarg);
663 goto done;
665 break;
666 case 'I':
667 if (optarg[0] == '\0')
668 break;
669 error = got_pathlist_insert(&pe, &ignores, optarg,
670 NULL);
671 if (error)
672 goto done;
673 break;
674 default:
675 usage_import();
676 /* NOTREACHED */
680 argc -= optind;
681 argv += optind;
683 #ifndef PROFILE
684 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
685 "unveil",
686 NULL) == -1)
687 err(1, "pledge");
688 #endif
689 if (argc != 1)
690 usage_import();
692 if (repo_path == NULL) {
693 repo_path = getcwd(NULL, 0);
694 if (repo_path == NULL)
695 return got_error_from_errno("getcwd");
697 got_path_strip_trailing_slashes(repo_path);
698 error = get_gitconfig_path(&gitconfig_path);
699 if (error)
700 goto done;
701 error = got_repo_open(&repo, repo_path, gitconfig_path);
702 if (error)
703 goto done;
705 error = get_author(&author, repo, NULL);
706 if (error)
707 return error;
709 /*
710 * Don't let the user create a branch name with a leading '-'.
711 * While technically a valid reference name, this case is usually
712 * an unintended typo.
713 */
714 if (branch_name[0] == '-')
715 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
717 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
718 error = got_error_from_errno("asprintf");
719 goto done;
722 error = got_ref_open(&branch_ref, repo, refname, 0);
723 if (error) {
724 if (error->code != GOT_ERR_NOT_REF)
725 goto done;
726 } else {
727 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
728 "import target branch already exists");
729 goto done;
732 path_dir = realpath(argv[0], NULL);
733 if (path_dir == NULL) {
734 error = got_error_from_errno2("realpath", argv[0]);
735 goto done;
737 got_path_strip_trailing_slashes(path_dir);
739 /*
740 * unveil(2) traverses exec(2); if an editor is used we have
741 * to apply unveil after the log message has been written.
742 */
743 if (logmsg == NULL || strlen(logmsg) == 0) {
744 error = get_editor(&editor);
745 if (error)
746 goto done;
747 free(logmsg);
748 error = collect_import_msg(&logmsg, &logmsg_path, editor,
749 path_dir, refname);
750 if (error) {
751 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
752 logmsg_path != NULL)
753 preserve_logmsg = 1;
754 goto done;
758 if (unveil(path_dir, "r") != 0) {
759 error = got_error_from_errno2("unveil", path_dir);
760 if (logmsg_path)
761 preserve_logmsg = 1;
762 goto done;
765 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
766 if (error) {
767 if (logmsg_path)
768 preserve_logmsg = 1;
769 goto done;
772 error = got_repo_import(&new_commit_id, path_dir, logmsg,
773 author, &ignores, repo, import_progress, NULL);
774 if (error) {
775 if (logmsg_path)
776 preserve_logmsg = 1;
777 goto done;
780 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
781 if (error) {
782 if (logmsg_path)
783 preserve_logmsg = 1;
784 goto done;
787 error = got_ref_write(branch_ref, repo);
788 if (error) {
789 if (logmsg_path)
790 preserve_logmsg = 1;
791 goto done;
794 error = got_object_id_str(&id_str, new_commit_id);
795 if (error) {
796 if (logmsg_path)
797 preserve_logmsg = 1;
798 goto done;
801 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
802 if (error) {
803 if (error->code != GOT_ERR_NOT_REF) {
804 if (logmsg_path)
805 preserve_logmsg = 1;
806 goto done;
809 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
810 branch_ref);
811 if (error) {
812 if (logmsg_path)
813 preserve_logmsg = 1;
814 goto done;
817 error = got_ref_write(head_ref, repo);
818 if (error) {
819 if (logmsg_path)
820 preserve_logmsg = 1;
821 goto done;
825 printf("Created branch %s with commit %s\n",
826 got_ref_get_name(branch_ref), id_str);
827 done:
828 if (preserve_logmsg) {
829 fprintf(stderr, "%s: log message preserved in %s\n",
830 getprogname(), logmsg_path);
831 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
832 error = got_error_from_errno2("unlink", logmsg_path);
833 free(logmsg);
834 free(logmsg_path);
835 free(repo_path);
836 free(editor);
837 free(refname);
838 free(new_commit_id);
839 free(id_str);
840 free(author);
841 free(gitconfig_path);
842 if (branch_ref)
843 got_ref_close(branch_ref);
844 if (head_ref)
845 got_ref_close(head_ref);
846 return error;
849 __dead static void
850 usage_clone(void)
852 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
853 "[-R reference] repository-url [directory]\n", getprogname());
854 exit(1);
857 struct got_fetch_progress_arg {
858 char last_scaled_size[FMT_SCALED_STRSIZE];
859 int last_p_indexed;
860 int last_p_resolved;
861 int verbosity;
862 };
864 static const struct got_error *
865 fetch_progress(void *arg, const char *message, off_t packfile_size,
866 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
868 struct got_fetch_progress_arg *a = arg;
869 char scaled_size[FMT_SCALED_STRSIZE];
870 int p_indexed, p_resolved;
871 int print_size = 0, print_indexed = 0, print_resolved = 0;
873 if (a->verbosity < 0)
874 return NULL;
876 if (message && message[0] != '\0') {
877 printf("\rserver: %s", message);
878 fflush(stdout);
879 return NULL;
882 if (packfile_size > 0 || nobj_indexed > 0) {
883 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
884 (a->last_scaled_size[0] == '\0' ||
885 strcmp(scaled_size, a->last_scaled_size)) != 0) {
886 print_size = 1;
887 if (strlcpy(a->last_scaled_size, scaled_size,
888 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
889 return got_error(GOT_ERR_NO_SPACE);
891 if (nobj_indexed > 0) {
892 p_indexed = (nobj_indexed * 100) / nobj_total;
893 if (p_indexed != a->last_p_indexed) {
894 a->last_p_indexed = p_indexed;
895 print_indexed = 1;
896 print_size = 1;
899 if (nobj_resolved > 0) {
900 p_resolved = (nobj_resolved * 100) /
901 (nobj_total - nobj_loose);
902 if (p_resolved != a->last_p_resolved) {
903 a->last_p_resolved = p_resolved;
904 print_resolved = 1;
905 print_indexed = 1;
906 print_size = 1;
911 if (print_size || print_indexed || print_resolved)
912 printf("\r");
913 if (print_size)
914 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
915 if (print_indexed)
916 printf("; indexing %d%%", p_indexed);
917 if (print_resolved)
918 printf("; resolving deltas %d%%", p_resolved);
919 if (print_size || print_indexed || print_resolved)
920 fflush(stdout);
922 return NULL;
925 static const struct got_error *
926 create_symref(struct got_reference **head_symref, const char *refname,
927 struct got_reference *target_ref, int verbosity,
928 struct got_repository *repo)
930 const struct got_error *err;
932 err = got_ref_alloc_symref(head_symref, refname, target_ref);
933 if (err)
934 return err;
936 err = got_ref_write(*head_symref, repo);
937 if (err == NULL && verbosity > 0) {
938 printf("Created reference %s: %s\n", GOT_REF_HEAD,
939 got_ref_get_name(target_ref));
941 return err;
944 static const struct got_error *
945 list_remote_refs(struct got_pathlist_head *symrefs,
946 struct got_pathlist_head *refs)
948 const struct got_error *err;
949 struct got_pathlist_entry *pe;
951 TAILQ_FOREACH(pe, symrefs, entry) {
952 const char *refname = pe->path;
953 const char *targetref = pe->data;
955 printf("%s: %s\n", refname, targetref);
958 TAILQ_FOREACH(pe, refs, entry) {
959 const char *refname = pe->path;
960 struct got_object_id *id = pe->data;
961 char *id_str;
963 err = got_object_id_str(&id_str, id);
964 if (err)
965 return err;
966 printf("%s: %s\n", refname, id_str);
967 free(id_str);
970 return NULL;
973 static const struct got_error *
974 create_ref(const char *refname, struct got_object_id *id,
975 int verbosity, struct got_repository *repo)
977 const struct got_error *err = NULL;
978 struct got_reference *ref;
979 char *id_str;
981 err = got_object_id_str(&id_str, id);
982 if (err)
983 return err;
985 err = got_ref_alloc(&ref, refname, id);
986 if (err)
987 goto done;
989 err = got_ref_write(ref, repo);
990 got_ref_close(ref);
992 if (err == NULL && verbosity >= 0)
993 printf("Created reference %s: %s\n", refname, id_str);
994 done:
995 free(id_str);
996 return err;
999 static int
1000 match_wanted_ref(const char *refname, const char *wanted_ref)
1002 if (strncmp(refname, "refs/", 5) != 0)
1003 return 0;
1004 refname += 5;
1007 * Prevent fetching of references that won't make any
1008 * sense outside of the remote repository's context.
1010 if (strncmp(refname, "got/", 4) == 0)
1011 return 0;
1012 if (strncmp(refname, "remotes/", 8) == 0)
1013 return 0;
1015 if (strncmp(wanted_ref, "refs/", 5) == 0)
1016 wanted_ref += 5;
1018 /* Allow prefix match. */
1019 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1020 return 1;
1022 /* Allow exact match. */
1023 return (strcmp(refname, wanted_ref) == 0);
1026 static int
1027 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1029 struct got_pathlist_entry *pe;
1031 TAILQ_FOREACH(pe, wanted_refs, entry) {
1032 if (match_wanted_ref(refname, pe->path))
1033 return 1;
1036 return 0;
1039 static const struct got_error *
1040 create_wanted_ref(const char *refname, struct got_object_id *id,
1041 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1043 const struct got_error *err;
1044 char *remote_refname;
1046 if (strncmp("refs/", refname, 5) == 0)
1047 refname += 5;
1049 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1050 remote_repo_name, refname) == -1)
1051 return got_error_from_errno("asprintf");
1053 err = create_ref(remote_refname, id, verbosity, repo);
1054 free(remote_refname);
1055 return err;
1058 static const struct got_error *
1059 create_gotconfig(const char *proto, const char *host, const char *port,
1060 char *remote_repo_path, int fetch_all_branches, int mirror_references,
1061 struct got_repository *repo)
1063 const struct got_error *err = NULL;
1064 char *gotconfig_path = NULL;
1065 char *gotconfig = NULL;
1066 FILE *gotconfig_file = NULL;
1067 ssize_t n;
1069 /* Create got.conf(5). */
1070 gotconfig_path = got_repo_get_path_gotconfig(repo);
1071 if (gotconfig_path == NULL) {
1072 err = got_error_from_errno("got_repo_get_path_gotconfig");
1073 goto done;
1075 gotconfig_file = fopen(gotconfig_path, "a");
1076 if (gotconfig_file == NULL) {
1077 err = got_error_from_errno2("fopen", gotconfig_path);
1078 goto done;
1080 got_path_strip_trailing_slashes(remote_repo_path);
1081 if (asprintf(&gotconfig,
1082 "remote \"%s\" {\n"
1083 "\tserver %s\n"
1084 "\tprotocol %s\n"
1085 "%s%s%s"
1086 "\trepository \"%s\"\n"
1087 "%s"
1088 "}\n",
1089 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1090 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1091 remote_repo_path,
1092 mirror_references ? "\tmirror-references yes\n" : "") == -1) {
1093 err = got_error_from_errno("asprintf");
1094 goto done;
1096 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1097 if (n != strlen(gotconfig)) {
1098 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1099 goto done;
1102 done:
1103 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1104 err = got_error_from_errno2("fclose", gotconfig_path);
1105 free(gotconfig_path);
1106 return err;
1109 static const struct got_error *
1110 create_gitconfig(const char *git_url, struct got_reference *default_head,
1111 int fetch_all_branches, int mirror_references, struct got_repository *repo)
1113 const struct got_error *err = NULL;
1114 char *gitconfig_path = NULL;
1115 char *gitconfig = NULL;
1116 FILE *gitconfig_file = NULL;
1117 ssize_t n;
1119 /* Create a config file Git can understand. */
1120 gitconfig_path = got_repo_get_path_gitconfig(repo);
1121 if (gitconfig_path == NULL) {
1122 err = got_error_from_errno("got_repo_get_path_gitconfig");
1123 goto done;
1125 gitconfig_file = fopen(gitconfig_path, "a");
1126 if (gitconfig_file == NULL) {
1127 err = got_error_from_errno2("fopen", gitconfig_path);
1128 goto done;
1130 if (mirror_references) {
1131 if (asprintf(&gitconfig,
1132 "[remote \"%s\"]\n"
1133 "\turl = %s\n"
1134 "\tfetch = +refs/*:refs/*\n"
1135 "\tmirror = true\n",
1136 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1137 err = got_error_from_errno("asprintf");
1138 goto done;
1140 } else if (fetch_all_branches) {
1141 if (asprintf(&gitconfig,
1142 "[remote \"%s\"]\n"
1143 "\turl = %s\n"
1144 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1145 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1146 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1147 err = got_error_from_errno("asprintf");
1148 goto done;
1150 } else {
1151 const char *branchname;
1154 * If the server specified a default branch, use just that one.
1155 * Otherwise fall back to fetching all branches on next fetch.
1157 if (default_head) {
1158 branchname = got_ref_get_symref_target(default_head);
1159 if (strncmp(branchname, "refs/heads/", 11) == 0)
1160 branchname += 11;
1161 } else
1162 branchname = "*"; /* fall back to all branches */
1163 if (asprintf(&gitconfig,
1164 "[remote \"%s\"]\n"
1165 "\turl = %s\n"
1166 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1167 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1168 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1169 branchname) == -1) {
1170 err = got_error_from_errno("asprintf");
1171 goto done;
1174 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1175 if (n != strlen(gitconfig)) {
1176 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1177 goto done;
1179 done:
1180 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1181 err = got_error_from_errno2("fclose", gitconfig_path);
1182 free(gitconfig_path);
1183 return err;
1186 static const struct got_error *
1187 cmd_clone(int argc, char *argv[])
1189 const struct got_error *error = NULL;
1190 const char *uri, *dirname;
1191 char *proto, *host, *port, *repo_name, *server_path;
1192 char *default_destdir = NULL, *id_str = NULL;
1193 const char *repo_path;
1194 struct got_repository *repo = NULL;
1195 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1196 struct got_pathlist_entry *pe;
1197 struct got_object_id *pack_hash = NULL;
1198 int ch, fetchfd = -1, fetchstatus;
1199 pid_t fetchpid = -1;
1200 struct got_fetch_progress_arg fpa;
1201 char *git_url = NULL;
1202 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1203 int list_refs_only = 0;
1204 struct got_reference *default_head = NULL;
1206 TAILQ_INIT(&refs);
1207 TAILQ_INIT(&symrefs);
1208 TAILQ_INIT(&wanted_branches);
1209 TAILQ_INIT(&wanted_refs);
1211 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1212 switch (ch) {
1213 case 'a':
1214 fetch_all_branches = 1;
1215 break;
1216 case 'b':
1217 error = got_pathlist_append(&wanted_branches,
1218 optarg, NULL);
1219 if (error)
1220 return error;
1221 break;
1222 case 'l':
1223 list_refs_only = 1;
1224 break;
1225 case 'm':
1226 mirror_references = 1;
1227 break;
1228 case 'v':
1229 if (verbosity < 0)
1230 verbosity = 0;
1231 else if (verbosity < 3)
1232 verbosity++;
1233 break;
1234 case 'q':
1235 verbosity = -1;
1236 break;
1237 case 'R':
1238 error = got_pathlist_append(&wanted_refs,
1239 optarg, NULL);
1240 if (error)
1241 return error;
1242 break;
1243 default:
1244 usage_clone();
1245 break;
1248 argc -= optind;
1249 argv += optind;
1251 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1252 errx(1, "-a and -b options are mutually exclusive");
1253 if (list_refs_only) {
1254 if (!TAILQ_EMPTY(&wanted_branches))
1255 errx(1, "-l and -b options are mutually exclusive");
1256 if (fetch_all_branches)
1257 errx(1, "-l and -a options are mutually exclusive");
1258 if (mirror_references)
1259 errx(1, "-l and -m options are mutually exclusive");
1260 if (verbosity == -1)
1261 errx(1, "-l and -q options are mutually exclusive");
1262 if (!TAILQ_EMPTY(&wanted_refs))
1263 errx(1, "-l and -R options are mutually exclusive");
1266 uri = argv[0];
1268 if (argc == 1)
1269 dirname = NULL;
1270 else if (argc == 2)
1271 dirname = argv[1];
1272 else
1273 usage_clone();
1275 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1276 &repo_name, uri);
1277 if (error)
1278 goto done;
1280 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1281 host, port ? ":" : "", port ? port : "",
1282 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1283 error = got_error_from_errno("asprintf");
1284 goto done;
1287 if (strcmp(proto, "git") == 0) {
1288 #ifndef PROFILE
1289 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1290 "sendfd dns inet unveil", NULL) == -1)
1291 err(1, "pledge");
1292 #endif
1293 } else if (strcmp(proto, "git+ssh") == 0 ||
1294 strcmp(proto, "ssh") == 0) {
1295 #ifndef PROFILE
1296 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1297 "sendfd unveil", NULL) == -1)
1298 err(1, "pledge");
1299 #endif
1300 } else if (strcmp(proto, "http") == 0 ||
1301 strcmp(proto, "git+http") == 0) {
1302 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1303 goto done;
1304 } else {
1305 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1306 goto done;
1308 if (dirname == NULL) {
1309 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1310 error = got_error_from_errno("asprintf");
1311 goto done;
1313 repo_path = default_destdir;
1314 } else
1315 repo_path = dirname;
1317 if (!list_refs_only) {
1318 error = got_path_mkdir(repo_path);
1319 if (error &&
1320 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1321 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1322 goto done;
1323 if (!got_path_dir_is_empty(repo_path)) {
1324 error = got_error_path(repo_path,
1325 GOT_ERR_DIR_NOT_EMPTY);
1326 goto done;
1330 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1331 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1332 error = got_error_from_errno2("unveil",
1333 GOT_FETCH_PATH_SSH);
1334 goto done;
1337 error = apply_unveil(repo ? got_repo_get_path(repo) : NULL, 0, NULL);
1338 if (error)
1339 goto done;
1341 if (verbosity >= 0)
1342 printf("Connecting to %s%s%s\n", host,
1343 port ? ":" : "", port ? port : "");
1345 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1346 server_path, verbosity);
1347 if (error)
1348 goto done;
1350 if (!list_refs_only) {
1351 error = got_repo_init(repo_path);
1352 if (error)
1353 goto done;
1354 error = got_repo_open(&repo, repo_path, NULL);
1355 if (error)
1356 goto done;
1359 fpa.last_scaled_size[0] = '\0';
1360 fpa.last_p_indexed = -1;
1361 fpa.last_p_resolved = -1;
1362 fpa.verbosity = verbosity;
1363 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1364 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1365 fetch_all_branches, &wanted_branches, &wanted_refs,
1366 list_refs_only, verbosity, fetchfd, repo,
1367 fetch_progress, &fpa);
1368 if (error)
1369 goto done;
1371 if (list_refs_only) {
1372 error = list_remote_refs(&symrefs, &refs);
1373 goto done;
1376 error = got_object_id_str(&id_str, pack_hash);
1377 if (error)
1378 goto done;
1379 if (verbosity >= 0)
1380 printf("\nFetched %s.pack\n", id_str);
1381 free(id_str);
1383 /* Set up references provided with the pack file. */
1384 TAILQ_FOREACH(pe, &refs, entry) {
1385 const char *refname = pe->path;
1386 struct got_object_id *id = pe->data;
1387 char *remote_refname;
1389 if (is_wanted_ref(&wanted_refs, refname) &&
1390 !mirror_references) {
1391 error = create_wanted_ref(refname, id,
1392 GOT_FETCH_DEFAULT_REMOTE_NAME,
1393 verbosity - 1, repo);
1394 if (error)
1395 goto done;
1396 continue;
1399 error = create_ref(refname, id, verbosity - 1, repo);
1400 if (error)
1401 goto done;
1403 if (mirror_references)
1404 continue;
1406 if (strncmp("refs/heads/", refname, 11) != 0)
1407 continue;
1409 if (asprintf(&remote_refname,
1410 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1411 refname + 11) == -1) {
1412 error = got_error_from_errno("asprintf");
1413 goto done;
1415 error = create_ref(remote_refname, id, verbosity - 1, repo);
1416 free(remote_refname);
1417 if (error)
1418 goto done;
1421 /* Set the HEAD reference if the server provided one. */
1422 TAILQ_FOREACH(pe, &symrefs, entry) {
1423 struct got_reference *target_ref;
1424 const char *refname = pe->path;
1425 const char *target = pe->data;
1426 char *remote_refname = NULL, *remote_target = NULL;
1427 struct got_reference *head_symref;
1429 if (strcmp(refname, GOT_REF_HEAD) != 0)
1430 continue;
1432 error = got_ref_open(&target_ref, repo, target, 0);
1433 if (error) {
1434 if (error->code == GOT_ERR_NOT_REF) {
1435 error = NULL;
1436 continue;
1438 goto done;
1441 error = create_symref(&head_symref, refname, target_ref,
1442 verbosity, repo);
1443 got_ref_close(target_ref);
1444 if (error)
1445 goto done;
1447 /* First HEAD reference listed is the default branch. */
1448 if (default_head == NULL)
1449 default_head = head_symref;
1450 else
1451 got_ref_close(head_symref);
1453 if (mirror_references)
1454 continue;
1456 if (strncmp("refs/heads/", target, 11) != 0)
1457 continue;
1459 if (asprintf(&remote_refname,
1460 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1461 refname) == -1) {
1462 error = got_error_from_errno("asprintf");
1463 goto done;
1465 if (asprintf(&remote_target,
1466 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1467 target + 11) == -1) {
1468 error = got_error_from_errno("asprintf");
1469 free(remote_refname);
1470 goto done;
1472 error = got_ref_open(&target_ref, repo, remote_target, 0);
1473 if (error) {
1474 free(remote_refname);
1475 free(remote_target);
1476 if (error->code == GOT_ERR_NOT_REF) {
1477 error = NULL;
1478 continue;
1480 goto done;
1482 error = create_symref(&head_symref, remote_refname,
1483 target_ref, verbosity - 1, repo);
1484 free(remote_refname);
1485 free(remote_target);
1486 got_ref_close(target_ref);
1487 got_ref_close(head_symref);
1488 if (error)
1489 goto done;
1491 if (pe == NULL) {
1493 * We failed to set the HEAD reference. If we asked for
1494 * a set of wanted branches use the first of one of those
1495 * which could be fetched instead.
1497 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1498 const char *target = pe->path;
1499 struct got_reference *target_ref;
1501 error = got_ref_open(&target_ref, repo, target, 0);
1502 if (error) {
1503 if (error->code == GOT_ERR_NOT_REF) {
1504 error = NULL;
1505 continue;
1507 goto done;
1510 error = create_symref(&default_head, GOT_REF_HEAD,
1511 target_ref, verbosity, repo);
1512 got_ref_close(target_ref);
1513 if (error)
1514 goto done;
1515 break;
1519 /* Create got.conf(5). */
1520 error = create_gotconfig(proto, host, port, server_path,
1521 fetch_all_branches, mirror_references, repo);
1522 if (error)
1523 goto done;
1525 /* Create a config file Git can understand. */
1526 error = create_gitconfig(git_url, default_head, fetch_all_branches,
1527 mirror_references, repo);
1528 if (error)
1529 goto done;
1531 if (verbosity >= 0)
1532 printf("Created %s repository '%s'\n",
1533 mirror_references ? "mirrored" : "cloned", repo_path);
1534 done:
1535 if (fetchpid > 0) {
1536 if (kill(fetchpid, SIGTERM) == -1)
1537 error = got_error_from_errno("kill");
1538 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1539 error = got_error_from_errno("waitpid");
1541 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1542 error = got_error_from_errno("close");
1543 if (repo)
1544 got_repo_close(repo);
1545 if (default_head)
1546 got_ref_close(default_head);
1547 TAILQ_FOREACH(pe, &refs, entry) {
1548 free((void *)pe->path);
1549 free(pe->data);
1551 got_pathlist_free(&refs);
1552 TAILQ_FOREACH(pe, &symrefs, entry) {
1553 free((void *)pe->path);
1554 free(pe->data);
1556 got_pathlist_free(&symrefs);
1557 got_pathlist_free(&wanted_branches);
1558 got_pathlist_free(&wanted_refs);
1559 free(pack_hash);
1560 free(proto);
1561 free(host);
1562 free(port);
1563 free(server_path);
1564 free(repo_name);
1565 free(default_destdir);
1566 free(git_url);
1567 return error;
1570 static const struct got_error *
1571 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1572 int replace_tags, int verbosity, struct got_repository *repo)
1574 const struct got_error *err = NULL;
1575 char *new_id_str = NULL;
1576 struct got_object_id *old_id = NULL;
1578 err = got_object_id_str(&new_id_str, new_id);
1579 if (err)
1580 goto done;
1582 if (!replace_tags &&
1583 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1584 err = got_ref_resolve(&old_id, repo, ref);
1585 if (err)
1586 goto done;
1587 if (got_object_id_cmp(old_id, new_id) == 0)
1588 goto done;
1589 if (verbosity >= 0) {
1590 printf("Rejecting update of existing tag %s: %s\n",
1591 got_ref_get_name(ref), new_id_str);
1593 goto done;
1596 if (got_ref_is_symbolic(ref)) {
1597 if (verbosity >= 0) {
1598 printf("Replacing reference %s: %s\n",
1599 got_ref_get_name(ref),
1600 got_ref_get_symref_target(ref));
1602 err = got_ref_change_symref_to_ref(ref, new_id);
1603 if (err)
1604 goto done;
1605 err = got_ref_write(ref, repo);
1606 if (err)
1607 goto done;
1608 } else {
1609 err = got_ref_resolve(&old_id, repo, ref);
1610 if (err)
1611 goto done;
1612 if (got_object_id_cmp(old_id, new_id) == 0)
1613 goto done;
1615 err = got_ref_change_ref(ref, new_id);
1616 if (err)
1617 goto done;
1618 err = got_ref_write(ref, repo);
1619 if (err)
1620 goto done;
1623 if (verbosity >= 0)
1624 printf("Updated %s: %s\n", got_ref_get_name(ref),
1625 new_id_str);
1626 done:
1627 free(old_id);
1628 free(new_id_str);
1629 return err;
1632 static const struct got_error *
1633 update_symref(const char *refname, struct got_reference *target_ref,
1634 int verbosity, struct got_repository *repo)
1636 const struct got_error *err = NULL, *unlock_err;
1637 struct got_reference *symref;
1638 int symref_is_locked = 0;
1640 err = got_ref_open(&symref, repo, refname, 1);
1641 if (err) {
1642 if (err->code != GOT_ERR_NOT_REF)
1643 return err;
1644 err = got_ref_alloc_symref(&symref, refname, target_ref);
1645 if (err)
1646 goto done;
1648 err = got_ref_write(symref, repo);
1649 if (err)
1650 goto done;
1652 if (verbosity >= 0)
1653 printf("Created reference %s: %s\n",
1654 got_ref_get_name(symref),
1655 got_ref_get_symref_target(symref));
1656 } else {
1657 symref_is_locked = 1;
1659 if (strcmp(got_ref_get_symref_target(symref),
1660 got_ref_get_name(target_ref)) == 0)
1661 goto done;
1663 err = got_ref_change_symref(symref,
1664 got_ref_get_name(target_ref));
1665 if (err)
1666 goto done;
1668 err = got_ref_write(symref, repo);
1669 if (err)
1670 goto done;
1672 if (verbosity >= 0)
1673 printf("Updated %s: %s\n", got_ref_get_name(symref),
1674 got_ref_get_symref_target(symref));
1677 done:
1678 if (symref_is_locked) {
1679 unlock_err = got_ref_unlock(symref);
1680 if (unlock_err && err == NULL)
1681 err = unlock_err;
1683 got_ref_close(symref);
1684 return err;
1687 __dead static void
1688 usage_fetch(void)
1690 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1691 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1692 "[remote-repository-name]\n",
1693 getprogname());
1694 exit(1);
1697 static const struct got_error *
1698 delete_missing_ref(struct got_reference *ref,
1699 int verbosity, struct got_repository *repo)
1701 const struct got_error *err = NULL;
1702 struct got_object_id *id = NULL;
1703 char *id_str = NULL;
1705 if (got_ref_is_symbolic(ref)) {
1706 err = got_ref_delete(ref, repo);
1707 if (err)
1708 return err;
1709 if (verbosity >= 0) {
1710 printf("Deleted reference %s: %s\n",
1711 got_ref_get_name(ref),
1712 got_ref_get_symref_target(ref));
1714 } else {
1715 err = got_ref_resolve(&id, repo, ref);
1716 if (err)
1717 return err;
1718 err = got_object_id_str(&id_str, id);
1719 if (err)
1720 goto done;
1722 err = got_ref_delete(ref, repo);
1723 if (err)
1724 goto done;
1725 if (verbosity >= 0) {
1726 printf("Deleted reference %s: %s\n",
1727 got_ref_get_name(ref), id_str);
1730 done:
1731 free(id);
1732 free(id_str);
1733 return NULL;
1736 static const struct got_error *
1737 delete_missing_refs(struct got_pathlist_head *their_refs,
1738 struct got_pathlist_head *their_symrefs,
1739 const struct got_remote_repo *remote,
1740 int verbosity, struct got_repository *repo)
1742 const struct got_error *err = NULL, *unlock_err;
1743 struct got_reflist_head my_refs;
1744 struct got_reflist_entry *re;
1745 struct got_pathlist_entry *pe;
1746 char *remote_namespace = NULL;
1747 char *local_refname = NULL;
1749 SIMPLEQ_INIT(&my_refs);
1751 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
1752 == -1)
1753 return got_error_from_errno("asprintf");
1755 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1756 if (err)
1757 goto done;
1759 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1760 const char *refname = got_ref_get_name(re->ref);
1762 if (!remote->mirror_references) {
1763 if (strncmp(refname, remote_namespace,
1764 strlen(remote_namespace)) == 0) {
1765 if (strcmp(refname + strlen(remote_namespace),
1766 GOT_REF_HEAD) == 0)
1767 continue;
1768 if (asprintf(&local_refname, "refs/heads/%s",
1769 refname + strlen(remote_namespace)) == -1) {
1770 err = got_error_from_errno("asprintf");
1771 goto done;
1773 } else if (strncmp(refname, "refs/tags/", 10) != 0)
1774 continue;
1777 TAILQ_FOREACH(pe, their_refs, entry) {
1778 if (strcmp(local_refname, pe->path) == 0)
1779 break;
1781 if (pe != NULL)
1782 continue;
1784 TAILQ_FOREACH(pe, their_symrefs, entry) {
1785 if (strcmp(local_refname, pe->path) == 0)
1786 break;
1788 if (pe != NULL)
1789 continue;
1791 err = delete_missing_ref(re->ref, verbosity, repo);
1792 if (err)
1793 break;
1795 if (local_refname) {
1796 struct got_reference *ref;
1797 err = got_ref_open(&ref, repo, local_refname, 1);
1798 if (err) {
1799 if (err->code != GOT_ERR_NOT_REF)
1800 break;
1801 free(local_refname);
1802 local_refname = NULL;
1803 continue;
1805 err = delete_missing_ref(ref, verbosity, repo);
1806 if (err)
1807 break;
1808 unlock_err = got_ref_unlock(ref);
1809 got_ref_close(ref);
1810 if (unlock_err && err == NULL) {
1811 err = unlock_err;
1812 break;
1815 free(local_refname);
1816 local_refname = NULL;
1819 done:
1820 free(remote_namespace);
1821 free(local_refname);
1822 return err;
1825 static const struct got_error *
1826 update_wanted_ref(const char *refname, struct got_object_id *id,
1827 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1829 const struct got_error *err, *unlock_err;
1830 char *remote_refname;
1831 struct got_reference *ref;
1833 if (strncmp("refs/", refname, 5) == 0)
1834 refname += 5;
1836 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1837 remote_repo_name, refname) == -1)
1838 return got_error_from_errno("asprintf");
1840 err = got_ref_open(&ref, repo, remote_refname, 1);
1841 if (err) {
1842 if (err->code != GOT_ERR_NOT_REF)
1843 goto done;
1844 err = create_ref(remote_refname, id, verbosity, repo);
1845 } else {
1846 err = update_ref(ref, id, 0, verbosity, repo);
1847 unlock_err = got_ref_unlock(ref);
1848 if (unlock_err && err == NULL)
1849 err = unlock_err;
1850 got_ref_close(ref);
1852 done:
1853 free(remote_refname);
1854 return err;
1857 static const struct got_error *
1858 cmd_fetch(int argc, char *argv[])
1860 const struct got_error *error = NULL, *unlock_err;
1861 char *cwd = NULL, *repo_path = NULL;
1862 const char *remote_name;
1863 char *proto = NULL, *host = NULL, *port = NULL;
1864 char *repo_name = NULL, *server_path = NULL;
1865 const struct got_remote_repo *remotes, *remote = NULL;
1866 int nremotes;
1867 char *id_str = NULL;
1868 struct got_repository *repo = NULL;
1869 struct got_worktree *worktree = NULL;
1870 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
1871 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1872 struct got_pathlist_entry *pe;
1873 struct got_object_id *pack_hash = NULL;
1874 int i, ch, fetchfd = -1, fetchstatus;
1875 pid_t fetchpid = -1;
1876 struct got_fetch_progress_arg fpa;
1877 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
1878 int delete_refs = 0, replace_tags = 0;
1880 TAILQ_INIT(&refs);
1881 TAILQ_INIT(&symrefs);
1882 TAILQ_INIT(&wanted_branches);
1883 TAILQ_INIT(&wanted_refs);
1885 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
1886 switch (ch) {
1887 case 'a':
1888 fetch_all_branches = 1;
1889 break;
1890 case 'b':
1891 error = got_pathlist_append(&wanted_branches,
1892 optarg, NULL);
1893 if (error)
1894 return error;
1895 break;
1896 case 'd':
1897 delete_refs = 1;
1898 break;
1899 case 'l':
1900 list_refs_only = 1;
1901 break;
1902 case 'r':
1903 repo_path = realpath(optarg, NULL);
1904 if (repo_path == NULL)
1905 return got_error_from_errno2("realpath",
1906 optarg);
1907 got_path_strip_trailing_slashes(repo_path);
1908 break;
1909 case 't':
1910 replace_tags = 1;
1911 break;
1912 case 'v':
1913 if (verbosity < 0)
1914 verbosity = 0;
1915 else if (verbosity < 3)
1916 verbosity++;
1917 break;
1918 case 'q':
1919 verbosity = -1;
1920 break;
1921 case 'R':
1922 error = got_pathlist_append(&wanted_refs,
1923 optarg, NULL);
1924 if (error)
1925 return error;
1926 break;
1927 default:
1928 usage_fetch();
1929 break;
1932 argc -= optind;
1933 argv += optind;
1935 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1936 errx(1, "-a and -b options are mutually exclusive");
1937 if (list_refs_only) {
1938 if (!TAILQ_EMPTY(&wanted_branches))
1939 errx(1, "-l and -b options are mutually exclusive");
1940 if (fetch_all_branches)
1941 errx(1, "-l and -a options are mutually exclusive");
1942 if (delete_refs)
1943 errx(1, "-l and -d options are mutually exclusive");
1944 if (verbosity == -1)
1945 errx(1, "-l and -q options are mutually exclusive");
1948 if (argc == 0)
1949 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
1950 else if (argc == 1)
1951 remote_name = argv[0];
1952 else
1953 usage_fetch();
1955 cwd = getcwd(NULL, 0);
1956 if (cwd == NULL) {
1957 error = got_error_from_errno("getcwd");
1958 goto done;
1961 if (repo_path == NULL) {
1962 error = got_worktree_open(&worktree, cwd);
1963 if (error && error->code != GOT_ERR_NOT_WORKTREE)
1964 goto done;
1965 else
1966 error = NULL;
1967 if (worktree) {
1968 repo_path =
1969 strdup(got_worktree_get_repo_path(worktree));
1970 if (repo_path == NULL)
1971 error = got_error_from_errno("strdup");
1972 if (error)
1973 goto done;
1974 } else {
1975 repo_path = strdup(cwd);
1976 if (repo_path == NULL) {
1977 error = got_error_from_errno("strdup");
1978 goto done;
1983 error = got_repo_open(&repo, repo_path, NULL);
1984 if (error)
1985 goto done;
1987 if (worktree) {
1988 worktree_conf = got_worktree_get_gotconfig(worktree);
1989 if (worktree_conf) {
1990 got_gotconfig_get_remotes(&nremotes, &remotes,
1991 worktree_conf);
1992 for (i = 0; i < nremotes; i++) {
1993 remote = &remotes[i];
1994 if (strcmp(remote->name, remote_name) == 0)
1995 break;
1999 if (remote == NULL) {
2000 repo_conf = got_repo_get_gotconfig(repo);
2001 if (repo_conf) {
2002 got_gotconfig_get_remotes(&nremotes, &remotes,
2003 repo_conf);
2004 for (i = 0; i < nremotes; i++) {
2005 remote = &remotes[i];
2006 if (strcmp(remote->name, remote_name) == 0)
2007 break;
2011 if (remote == NULL) {
2012 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2013 for (i = 0; i < nremotes; i++) {
2014 remote = &remotes[i];
2015 if (strcmp(remote->name, remote_name) == 0)
2016 break;
2019 if (remote == NULL) {
2020 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2021 goto done;
2024 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
2025 &repo_name, remote->url);
2026 if (error)
2027 goto done;
2029 if (strcmp(proto, "git") == 0) {
2030 #ifndef PROFILE
2031 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2032 "sendfd dns inet unveil", NULL) == -1)
2033 err(1, "pledge");
2034 #endif
2035 } else if (strcmp(proto, "git+ssh") == 0 ||
2036 strcmp(proto, "ssh") == 0) {
2037 #ifndef PROFILE
2038 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2039 "sendfd unveil", NULL) == -1)
2040 err(1, "pledge");
2041 #endif
2042 } else if (strcmp(proto, "http") == 0 ||
2043 strcmp(proto, "git+http") == 0) {
2044 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2045 goto done;
2046 } else {
2047 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2048 goto done;
2051 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
2052 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
2053 error = got_error_from_errno2("unveil",
2054 GOT_FETCH_PATH_SSH);
2055 goto done;
2058 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2059 if (error)
2060 goto done;
2062 if (verbosity >= 0)
2063 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2064 port ? ":" : "", port ? port : "");
2066 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2067 server_path, verbosity);
2068 if (error)
2069 goto done;
2071 fpa.last_scaled_size[0] = '\0';
2072 fpa.last_p_indexed = -1;
2073 fpa.last_p_resolved = -1;
2074 fpa.verbosity = verbosity;
2075 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2076 remote->mirror_references, fetch_all_branches, &wanted_branches,
2077 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2078 fetch_progress, &fpa);
2079 if (error)
2080 goto done;
2082 if (list_refs_only) {
2083 error = list_remote_refs(&symrefs, &refs);
2084 goto done;
2087 if (pack_hash == NULL) {
2088 if (verbosity >= 0)
2089 printf("Already up-to-date\n");
2090 } else if (verbosity >= 0) {
2091 error = got_object_id_str(&id_str, pack_hash);
2092 if (error)
2093 goto done;
2094 printf("\nFetched %s.pack\n", id_str);
2095 free(id_str);
2096 id_str = NULL;
2099 /* Update references provided with the pack file. */
2100 TAILQ_FOREACH(pe, &refs, entry) {
2101 const char *refname = pe->path;
2102 struct got_object_id *id = pe->data;
2103 struct got_reference *ref;
2104 char *remote_refname;
2106 if (is_wanted_ref(&wanted_refs, refname) &&
2107 !remote->mirror_references) {
2108 error = update_wanted_ref(refname, id,
2109 remote->name, verbosity, repo);
2110 if (error)
2111 goto done;
2112 continue;
2115 if (remote->mirror_references ||
2116 strncmp("refs/tags/", refname, 10) == 0) {
2117 error = got_ref_open(&ref, repo, refname, 1);
2118 if (error) {
2119 if (error->code != GOT_ERR_NOT_REF)
2120 goto done;
2121 error = create_ref(refname, id, verbosity,
2122 repo);
2123 if (error)
2124 goto done;
2125 } else {
2126 error = update_ref(ref, id, replace_tags,
2127 verbosity, repo);
2128 unlock_err = got_ref_unlock(ref);
2129 if (unlock_err && error == NULL)
2130 error = unlock_err;
2131 got_ref_close(ref);
2132 if (error)
2133 goto done;
2135 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2136 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2137 remote_name, refname + 11) == -1) {
2138 error = got_error_from_errno("asprintf");
2139 goto done;
2142 error = got_ref_open(&ref, repo, remote_refname, 1);
2143 if (error) {
2144 if (error->code != GOT_ERR_NOT_REF)
2145 goto done;
2146 error = create_ref(remote_refname, id,
2147 verbosity, repo);
2148 if (error)
2149 goto done;
2150 } else {
2151 error = update_ref(ref, id, replace_tags,
2152 verbosity, repo);
2153 unlock_err = got_ref_unlock(ref);
2154 if (unlock_err && error == NULL)
2155 error = unlock_err;
2156 got_ref_close(ref);
2157 if (error)
2158 goto done;
2161 /* Also create a local branch if none exists yet. */
2162 error = got_ref_open(&ref, repo, refname, 1);
2163 if (error) {
2164 if (error->code != GOT_ERR_NOT_REF)
2165 goto done;
2166 error = create_ref(refname, id, verbosity,
2167 repo);
2168 if (error)
2169 goto done;
2170 } else {
2171 unlock_err = got_ref_unlock(ref);
2172 if (unlock_err && error == NULL)
2173 error = unlock_err;
2174 got_ref_close(ref);
2178 if (delete_refs) {
2179 error = delete_missing_refs(&refs, &symrefs, remote,
2180 verbosity, repo);
2181 if (error)
2182 goto done;
2185 if (!remote->mirror_references) {
2186 /* Update remote HEAD reference if the server provided one. */
2187 TAILQ_FOREACH(pe, &symrefs, entry) {
2188 struct got_reference *target_ref;
2189 const char *refname = pe->path;
2190 const char *target = pe->data;
2191 char *remote_refname = NULL, *remote_target = NULL;
2193 if (strcmp(refname, GOT_REF_HEAD) != 0)
2194 continue;
2196 if (strncmp("refs/heads/", target, 11) != 0)
2197 continue;
2199 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2200 remote->name, refname) == -1) {
2201 error = got_error_from_errno("asprintf");
2202 goto done;
2204 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2205 remote->name, target + 11) == -1) {
2206 error = got_error_from_errno("asprintf");
2207 free(remote_refname);
2208 goto done;
2211 error = got_ref_open(&target_ref, repo, remote_target,
2212 0);
2213 if (error) {
2214 free(remote_refname);
2215 free(remote_target);
2216 if (error->code == GOT_ERR_NOT_REF) {
2217 error = NULL;
2218 continue;
2220 goto done;
2222 error = update_symref(remote_refname, target_ref,
2223 verbosity, repo);
2224 free(remote_refname);
2225 free(remote_target);
2226 got_ref_close(target_ref);
2227 if (error)
2228 goto done;
2231 done:
2232 if (fetchpid > 0) {
2233 if (kill(fetchpid, SIGTERM) == -1)
2234 error = got_error_from_errno("kill");
2235 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2236 error = got_error_from_errno("waitpid");
2238 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2239 error = got_error_from_errno("close");
2240 if (repo)
2241 got_repo_close(repo);
2242 if (worktree)
2243 got_worktree_close(worktree);
2244 TAILQ_FOREACH(pe, &refs, entry) {
2245 free((void *)pe->path);
2246 free(pe->data);
2248 got_pathlist_free(&refs);
2249 TAILQ_FOREACH(pe, &symrefs, entry) {
2250 free((void *)pe->path);
2251 free(pe->data);
2253 got_pathlist_free(&symrefs);
2254 got_pathlist_free(&wanted_branches);
2255 got_pathlist_free(&wanted_refs);
2256 free(id_str);
2257 free(cwd);
2258 free(repo_path);
2259 free(pack_hash);
2260 free(proto);
2261 free(host);
2262 free(port);
2263 free(server_path);
2264 free(repo_name);
2265 return error;
2269 __dead static void
2270 usage_checkout(void)
2272 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2273 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2274 exit(1);
2277 static void
2278 show_worktree_base_ref_warning(void)
2280 fprintf(stderr, "%s: warning: could not create a reference "
2281 "to the work tree's base commit; the commit could be "
2282 "garbage-collected by Git; making the repository "
2283 "writable and running 'got update' will prevent this\n",
2284 getprogname());
2287 struct got_checkout_progress_arg {
2288 const char *worktree_path;
2289 int had_base_commit_ref_error;
2292 static const struct got_error *
2293 checkout_progress(void *arg, unsigned char status, const char *path)
2295 struct got_checkout_progress_arg *a = arg;
2297 /* Base commit bump happens silently. */
2298 if (status == GOT_STATUS_BUMP_BASE)
2299 return NULL;
2301 if (status == GOT_STATUS_BASE_REF_ERR) {
2302 a->had_base_commit_ref_error = 1;
2303 return NULL;
2306 while (path[0] == '/')
2307 path++;
2309 printf("%c %s/%s\n", status, a->worktree_path, path);
2310 return NULL;
2313 static const struct got_error *
2314 check_cancelled(void *arg)
2316 if (sigint_received || sigpipe_received)
2317 return got_error(GOT_ERR_CANCELLED);
2318 return NULL;
2321 static const struct got_error *
2322 check_linear_ancestry(struct got_object_id *commit_id,
2323 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2324 struct got_repository *repo)
2326 const struct got_error *err = NULL;
2327 struct got_object_id *yca_id;
2329 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2330 commit_id, base_commit_id, repo, check_cancelled, NULL);
2331 if (err)
2332 return err;
2334 if (yca_id == NULL)
2335 return got_error(GOT_ERR_ANCESTRY);
2338 * Require a straight line of history between the target commit
2339 * and the work tree's base commit.
2341 * Non-linear situations such as this require a rebase:
2343 * (commit) D F (base_commit)
2344 * \ /
2345 * C E
2346 * \ /
2347 * B (yca)
2348 * |
2349 * A
2351 * 'got update' only handles linear cases:
2352 * Update forwards in time: A (base/yca) - B - C - D (commit)
2353 * Update backwards in time: D (base) - C - B - A (commit/yca)
2355 if (allow_forwards_in_time_only) {
2356 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2357 return got_error(GOT_ERR_ANCESTRY);
2358 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2359 got_object_id_cmp(base_commit_id, yca_id) != 0)
2360 return got_error(GOT_ERR_ANCESTRY);
2362 free(yca_id);
2363 return NULL;
2366 static const struct got_error *
2367 check_same_branch(struct got_object_id *commit_id,
2368 struct got_reference *head_ref, struct got_object_id *yca_id,
2369 struct got_repository *repo)
2371 const struct got_error *err = NULL;
2372 struct got_commit_graph *graph = NULL;
2373 struct got_object_id *head_commit_id = NULL;
2374 int is_same_branch = 0;
2376 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2377 if (err)
2378 goto done;
2380 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2381 is_same_branch = 1;
2382 goto done;
2384 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2385 is_same_branch = 1;
2386 goto done;
2389 err = got_commit_graph_open(&graph, "/", 1);
2390 if (err)
2391 goto done;
2393 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2394 check_cancelled, NULL);
2395 if (err)
2396 goto done;
2398 for (;;) {
2399 struct got_object_id *id;
2400 err = got_commit_graph_iter_next(&id, graph, repo,
2401 check_cancelled, NULL);
2402 if (err) {
2403 if (err->code == GOT_ERR_ITER_COMPLETED)
2404 err = NULL;
2405 break;
2408 if (id) {
2409 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2410 break;
2411 if (got_object_id_cmp(id, commit_id) == 0) {
2412 is_same_branch = 1;
2413 break;
2417 done:
2418 if (graph)
2419 got_commit_graph_close(graph);
2420 free(head_commit_id);
2421 if (!err && !is_same_branch)
2422 err = got_error(GOT_ERR_ANCESTRY);
2423 return err;
2426 static const struct got_error *
2427 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2429 static char msg[512];
2430 const char *branch_name;
2432 if (got_ref_is_symbolic(ref))
2433 branch_name = got_ref_get_symref_target(ref);
2434 else
2435 branch_name = got_ref_get_name(ref);
2437 if (strncmp("refs/heads/", branch_name, 11) == 0)
2438 branch_name += 11;
2440 snprintf(msg, sizeof(msg),
2441 "target commit is not contained in branch '%s'; "
2442 "the branch to use must be specified with -b; "
2443 "if necessary a new branch can be created for "
2444 "this commit with 'got branch -c %s BRANCH_NAME'",
2445 branch_name, commit_id_str);
2447 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2450 static const struct got_error *
2451 cmd_checkout(int argc, char *argv[])
2453 const struct got_error *error = NULL;
2454 struct got_repository *repo = NULL;
2455 struct got_reference *head_ref = NULL;
2456 struct got_worktree *worktree = NULL;
2457 char *repo_path = NULL;
2458 char *worktree_path = NULL;
2459 const char *path_prefix = "";
2460 const char *branch_name = GOT_REF_HEAD;
2461 char *commit_id_str = NULL;
2462 char *cwd = NULL, *path = NULL;
2463 int ch, same_path_prefix, allow_nonempty = 0;
2464 struct got_pathlist_head paths;
2465 struct got_checkout_progress_arg cpa;
2467 TAILQ_INIT(&paths);
2469 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2470 switch (ch) {
2471 case 'b':
2472 branch_name = optarg;
2473 break;
2474 case 'c':
2475 commit_id_str = strdup(optarg);
2476 if (commit_id_str == NULL)
2477 return got_error_from_errno("strdup");
2478 break;
2479 case 'E':
2480 allow_nonempty = 1;
2481 break;
2482 case 'p':
2483 path_prefix = optarg;
2484 break;
2485 default:
2486 usage_checkout();
2487 /* NOTREACHED */
2491 argc -= optind;
2492 argv += optind;
2494 #ifndef PROFILE
2495 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2496 "unveil", NULL) == -1)
2497 err(1, "pledge");
2498 #endif
2499 if (argc == 1) {
2500 char *base, *dotgit;
2501 repo_path = realpath(argv[0], NULL);
2502 if (repo_path == NULL)
2503 return got_error_from_errno2("realpath", argv[0]);
2504 cwd = getcwd(NULL, 0);
2505 if (cwd == NULL) {
2506 error = got_error_from_errno("getcwd");
2507 goto done;
2509 if (path_prefix[0])
2510 path = strdup(path_prefix);
2511 else
2512 path = strdup(repo_path);
2513 if (path == NULL) {
2514 error = got_error_from_errno("strdup");
2515 goto done;
2517 base = basename(path);
2518 if (base == NULL) {
2519 error = got_error_from_errno2("basename", path);
2520 goto done;
2522 dotgit = strstr(base, ".git");
2523 if (dotgit)
2524 *dotgit = '\0';
2525 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2526 error = got_error_from_errno("asprintf");
2527 goto done;
2529 } else if (argc == 2) {
2530 repo_path = realpath(argv[0], NULL);
2531 if (repo_path == NULL) {
2532 error = got_error_from_errno2("realpath", argv[0]);
2533 goto done;
2535 worktree_path = realpath(argv[1], NULL);
2536 if (worktree_path == NULL) {
2537 if (errno != ENOENT) {
2538 error = got_error_from_errno2("realpath",
2539 argv[1]);
2540 goto done;
2542 worktree_path = strdup(argv[1]);
2543 if (worktree_path == NULL) {
2544 error = got_error_from_errno("strdup");
2545 goto done;
2548 } else
2549 usage_checkout();
2551 got_path_strip_trailing_slashes(repo_path);
2552 got_path_strip_trailing_slashes(worktree_path);
2554 error = got_repo_open(&repo, repo_path, NULL);
2555 if (error != NULL)
2556 goto done;
2558 /* Pre-create work tree path for unveil(2) */
2559 error = got_path_mkdir(worktree_path);
2560 if (error) {
2561 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2562 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2563 goto done;
2564 if (!allow_nonempty &&
2565 !got_path_dir_is_empty(worktree_path)) {
2566 error = got_error_path(worktree_path,
2567 GOT_ERR_DIR_NOT_EMPTY);
2568 goto done;
2572 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2573 if (error)
2574 goto done;
2576 error = got_ref_open(&head_ref, repo, branch_name, 0);
2577 if (error != NULL)
2578 goto done;
2580 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2581 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2582 goto done;
2584 error = got_worktree_open(&worktree, worktree_path);
2585 if (error != NULL)
2586 goto done;
2588 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2589 path_prefix);
2590 if (error != NULL)
2591 goto done;
2592 if (!same_path_prefix) {
2593 error = got_error(GOT_ERR_PATH_PREFIX);
2594 goto done;
2597 if (commit_id_str) {
2598 struct got_object_id *commit_id;
2599 error = got_repo_match_object_id(&commit_id, NULL,
2600 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2601 if (error)
2602 goto done;
2603 error = check_linear_ancestry(commit_id,
2604 got_worktree_get_base_commit_id(worktree), 0, repo);
2605 if (error != NULL) {
2606 free(commit_id);
2607 if (error->code == GOT_ERR_ANCESTRY) {
2608 error = checkout_ancestry_error(
2609 head_ref, commit_id_str);
2611 goto done;
2613 error = check_same_branch(commit_id, head_ref, NULL, repo);
2614 if (error) {
2615 if (error->code == GOT_ERR_ANCESTRY) {
2616 error = checkout_ancestry_error(
2617 head_ref, commit_id_str);
2619 goto done;
2621 error = got_worktree_set_base_commit_id(worktree, repo,
2622 commit_id);
2623 free(commit_id);
2624 if (error)
2625 goto done;
2628 error = got_pathlist_append(&paths, "", NULL);
2629 if (error)
2630 goto done;
2631 cpa.worktree_path = worktree_path;
2632 cpa.had_base_commit_ref_error = 0;
2633 error = got_worktree_checkout_files(worktree, &paths, repo,
2634 checkout_progress, &cpa, check_cancelled, NULL);
2635 if (error != NULL)
2636 goto done;
2638 printf("Now shut up and hack\n");
2639 if (cpa.had_base_commit_ref_error)
2640 show_worktree_base_ref_warning();
2641 done:
2642 got_pathlist_free(&paths);
2643 free(commit_id_str);
2644 free(repo_path);
2645 free(worktree_path);
2646 free(cwd);
2647 free(path);
2648 return error;
2651 struct got_update_progress_arg {
2652 int did_something;
2653 int conflicts;
2654 int obstructed;
2655 int not_updated;
2658 void
2659 print_update_progress_stats(struct got_update_progress_arg *upa)
2661 if (!upa->did_something)
2662 return;
2664 if (upa->conflicts > 0)
2665 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2666 if (upa->obstructed > 0)
2667 printf("File paths obstructed by a non-regular file: %d\n",
2668 upa->obstructed);
2669 if (upa->not_updated > 0)
2670 printf("Files not updated because of existing merge "
2671 "conflicts: %d\n", upa->not_updated);
2674 __dead static void
2675 usage_update(void)
2677 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2678 getprogname());
2679 exit(1);
2682 static const struct got_error *
2683 update_progress(void *arg, unsigned char status, const char *path)
2685 struct got_update_progress_arg *upa = arg;
2687 if (status == GOT_STATUS_EXISTS ||
2688 status == GOT_STATUS_BASE_REF_ERR)
2689 return NULL;
2691 upa->did_something = 1;
2693 /* Base commit bump happens silently. */
2694 if (status == GOT_STATUS_BUMP_BASE)
2695 return NULL;
2697 if (status == GOT_STATUS_CONFLICT)
2698 upa->conflicts++;
2699 if (status == GOT_STATUS_OBSTRUCTED)
2700 upa->obstructed++;
2701 if (status == GOT_STATUS_CANNOT_UPDATE)
2702 upa->not_updated++;
2704 while (path[0] == '/')
2705 path++;
2706 printf("%c %s\n", status, path);
2707 return NULL;
2710 static const struct got_error *
2711 switch_head_ref(struct got_reference *head_ref,
2712 struct got_object_id *commit_id, struct got_worktree *worktree,
2713 struct got_repository *repo)
2715 const struct got_error *err = NULL;
2716 char *base_id_str;
2717 int ref_has_moved = 0;
2719 /* Trivial case: switching between two different references. */
2720 if (strcmp(got_ref_get_name(head_ref),
2721 got_worktree_get_head_ref_name(worktree)) != 0) {
2722 printf("Switching work tree from %s to %s\n",
2723 got_worktree_get_head_ref_name(worktree),
2724 got_ref_get_name(head_ref));
2725 return got_worktree_set_head_ref(worktree, head_ref);
2728 err = check_linear_ancestry(commit_id,
2729 got_worktree_get_base_commit_id(worktree), 0, repo);
2730 if (err) {
2731 if (err->code != GOT_ERR_ANCESTRY)
2732 return err;
2733 ref_has_moved = 1;
2735 if (!ref_has_moved)
2736 return NULL;
2738 /* Switching to a rebased branch with the same reference name. */
2739 err = got_object_id_str(&base_id_str,
2740 got_worktree_get_base_commit_id(worktree));
2741 if (err)
2742 return err;
2743 printf("Reference %s now points at a different branch\n",
2744 got_worktree_get_head_ref_name(worktree));
2745 printf("Switching work tree from %s to %s\n", base_id_str,
2746 got_worktree_get_head_ref_name(worktree));
2747 return NULL;
2750 static const struct got_error *
2751 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2753 const struct got_error *err;
2754 int in_progress;
2756 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2757 if (err)
2758 return err;
2759 if (in_progress)
2760 return got_error(GOT_ERR_REBASING);
2762 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2763 if (err)
2764 return err;
2765 if (in_progress)
2766 return got_error(GOT_ERR_HISTEDIT_BUSY);
2768 return NULL;
2771 static const struct got_error *
2772 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2773 char *argv[], struct got_worktree *worktree)
2775 const struct got_error *err = NULL;
2776 char *path;
2777 int i;
2779 if (argc == 0) {
2780 path = strdup("");
2781 if (path == NULL)
2782 return got_error_from_errno("strdup");
2783 return got_pathlist_append(paths, path, NULL);
2786 for (i = 0; i < argc; i++) {
2787 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2788 if (err)
2789 break;
2790 err = got_pathlist_append(paths, path, NULL);
2791 if (err) {
2792 free(path);
2793 break;
2797 return err;
2800 static const struct got_error *
2801 wrap_not_worktree_error(const struct got_error *orig_err,
2802 const char *cmdname, const char *path)
2804 const struct got_error *err;
2805 struct got_repository *repo;
2806 static char msg[512];
2808 err = got_repo_open(&repo, path, NULL);
2809 if (err)
2810 return orig_err;
2812 snprintf(msg, sizeof(msg),
2813 "'got %s' needs a work tree in addition to a git repository\n"
2814 "Work trees can be checked out from this Git repository with "
2815 "'got checkout'.\n"
2816 "The got(1) manual page contains more information.", cmdname);
2817 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2818 got_repo_close(repo);
2819 return err;
2822 static const struct got_error *
2823 cmd_update(int argc, char *argv[])
2825 const struct got_error *error = NULL;
2826 struct got_repository *repo = NULL;
2827 struct got_worktree *worktree = NULL;
2828 char *worktree_path = NULL;
2829 struct got_object_id *commit_id = NULL;
2830 char *commit_id_str = NULL;
2831 const char *branch_name = NULL;
2832 struct got_reference *head_ref = NULL;
2833 struct got_pathlist_head paths;
2834 struct got_pathlist_entry *pe;
2835 int ch;
2836 struct got_update_progress_arg upa;
2838 TAILQ_INIT(&paths);
2840 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2841 switch (ch) {
2842 case 'b':
2843 branch_name = optarg;
2844 break;
2845 case 'c':
2846 commit_id_str = strdup(optarg);
2847 if (commit_id_str == NULL)
2848 return got_error_from_errno("strdup");
2849 break;
2850 default:
2851 usage_update();
2852 /* NOTREACHED */
2856 argc -= optind;
2857 argv += optind;
2859 #ifndef PROFILE
2860 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2861 "unveil", NULL) == -1)
2862 err(1, "pledge");
2863 #endif
2864 worktree_path = getcwd(NULL, 0);
2865 if (worktree_path == NULL) {
2866 error = got_error_from_errno("getcwd");
2867 goto done;
2869 error = got_worktree_open(&worktree, worktree_path);
2870 if (error) {
2871 if (error->code == GOT_ERR_NOT_WORKTREE)
2872 error = wrap_not_worktree_error(error, "update",
2873 worktree_path);
2874 goto done;
2877 error = check_rebase_or_histedit_in_progress(worktree);
2878 if (error)
2879 goto done;
2881 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
2882 NULL);
2883 if (error != NULL)
2884 goto done;
2886 error = apply_unveil(got_repo_get_path(repo), 0,
2887 got_worktree_get_root_path(worktree));
2888 if (error)
2889 goto done;
2891 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2892 if (error)
2893 goto done;
2895 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
2896 got_worktree_get_head_ref_name(worktree), 0);
2897 if (error != NULL)
2898 goto done;
2899 if (commit_id_str == NULL) {
2900 error = got_ref_resolve(&commit_id, repo, head_ref);
2901 if (error != NULL)
2902 goto done;
2903 error = got_object_id_str(&commit_id_str, commit_id);
2904 if (error != NULL)
2905 goto done;
2906 } else {
2907 error = got_repo_match_object_id(&commit_id, NULL,
2908 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2909 free(commit_id_str);
2910 commit_id_str = NULL;
2911 if (error)
2912 goto done;
2913 error = got_object_id_str(&commit_id_str, commit_id);
2914 if (error)
2915 goto done;
2918 if (branch_name) {
2919 struct got_object_id *head_commit_id;
2920 TAILQ_FOREACH(pe, &paths, entry) {
2921 if (pe->path_len == 0)
2922 continue;
2923 error = got_error_msg(GOT_ERR_BAD_PATH,
2924 "switching between branches requires that "
2925 "the entire work tree gets updated");
2926 goto done;
2928 error = got_ref_resolve(&head_commit_id, repo, head_ref);
2929 if (error)
2930 goto done;
2931 error = check_linear_ancestry(commit_id, head_commit_id, 0,
2932 repo);
2933 free(head_commit_id);
2934 if (error != NULL)
2935 goto done;
2936 error = check_same_branch(commit_id, head_ref, NULL, repo);
2937 if (error)
2938 goto done;
2939 error = switch_head_ref(head_ref, commit_id, worktree, repo);
2940 if (error)
2941 goto done;
2942 } else {
2943 error = check_linear_ancestry(commit_id,
2944 got_worktree_get_base_commit_id(worktree), 0, repo);
2945 if (error != NULL) {
2946 if (error->code == GOT_ERR_ANCESTRY)
2947 error = got_error(GOT_ERR_BRANCH_MOVED);
2948 goto done;
2950 error = check_same_branch(commit_id, head_ref, NULL, repo);
2951 if (error)
2952 goto done;
2955 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
2956 commit_id) != 0) {
2957 error = got_worktree_set_base_commit_id(worktree, repo,
2958 commit_id);
2959 if (error)
2960 goto done;
2963 memset(&upa, 0, sizeof(upa));
2964 error = got_worktree_checkout_files(worktree, &paths, repo,
2965 update_progress, &upa, check_cancelled, NULL);
2966 if (error != NULL)
2967 goto done;
2969 if (upa.did_something)
2970 printf("Updated to commit %s\n", commit_id_str);
2971 else
2972 printf("Already up-to-date\n");
2973 print_update_progress_stats(&upa);
2974 done:
2975 free(worktree_path);
2976 TAILQ_FOREACH(pe, &paths, entry)
2977 free((char *)pe->path);
2978 got_pathlist_free(&paths);
2979 free(commit_id);
2980 free(commit_id_str);
2981 return error;
2984 static const struct got_error *
2985 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
2986 const char *path, int diff_context, int ignore_whitespace,
2987 struct got_repository *repo)
2989 const struct got_error *err = NULL;
2990 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
2992 if (blob_id1) {
2993 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
2994 if (err)
2995 goto done;
2998 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
2999 if (err)
3000 goto done;
3002 while (path[0] == '/')
3003 path++;
3004 err = got_diff_blob(blob1, blob2, path, path, diff_context,
3005 ignore_whitespace, stdout);
3006 done:
3007 if (blob1)
3008 got_object_blob_close(blob1);
3009 got_object_blob_close(blob2);
3010 return err;
3013 static const struct got_error *
3014 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3015 const char *path, int diff_context, int ignore_whitespace,
3016 struct got_repository *repo)
3018 const struct got_error *err = NULL;
3019 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3020 struct got_diff_blob_output_unidiff_arg arg;
3022 if (tree_id1) {
3023 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3024 if (err)
3025 goto done;
3028 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3029 if (err)
3030 goto done;
3032 arg.diff_context = diff_context;
3033 arg.ignore_whitespace = ignore_whitespace;
3034 arg.outfile = stdout;
3035 while (path[0] == '/')
3036 path++;
3037 err = got_diff_tree(tree1, tree2, path, path, repo,
3038 got_diff_blob_output_unidiff, &arg, 1);
3039 done:
3040 if (tree1)
3041 got_object_tree_close(tree1);
3042 if (tree2)
3043 got_object_tree_close(tree2);
3044 return err;
3047 static const struct got_error *
3048 get_changed_paths(struct got_pathlist_head *paths,
3049 struct got_commit_object *commit, struct got_repository *repo)
3051 const struct got_error *err = NULL;
3052 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3053 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3054 struct got_object_qid *qid;
3056 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3057 if (qid != NULL) {
3058 struct got_commit_object *pcommit;
3059 err = got_object_open_as_commit(&pcommit, repo,
3060 qid->id);
3061 if (err)
3062 return err;
3064 tree_id1 = got_object_commit_get_tree_id(pcommit);
3065 got_object_commit_close(pcommit);
3069 if (tree_id1) {
3070 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3071 if (err)
3072 goto done;
3075 tree_id2 = got_object_commit_get_tree_id(commit);
3076 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3077 if (err)
3078 goto done;
3080 err = got_diff_tree(tree1, tree2, "", "", repo,
3081 got_diff_tree_collect_changed_paths, paths, 0);
3082 done:
3083 if (tree1)
3084 got_object_tree_close(tree1);
3085 if (tree2)
3086 got_object_tree_close(tree2);
3087 return err;
3090 static const struct got_error *
3091 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3092 const char *path, int diff_context, struct got_repository *repo)
3094 const struct got_error *err = NULL;
3095 struct got_commit_object *pcommit = NULL;
3096 char *id_str1 = NULL, *id_str2 = NULL;
3097 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3098 struct got_object_qid *qid;
3100 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3101 if (qid != NULL) {
3102 err = got_object_open_as_commit(&pcommit, repo,
3103 qid->id);
3104 if (err)
3105 return err;
3108 if (path && path[0] != '\0') {
3109 int obj_type;
3110 err = got_object_id_by_path(&obj_id2, repo, id, path);
3111 if (err)
3112 goto done;
3113 err = got_object_id_str(&id_str2, obj_id2);
3114 if (err) {
3115 free(obj_id2);
3116 goto done;
3118 if (pcommit) {
3119 err = got_object_id_by_path(&obj_id1, repo,
3120 qid->id, path);
3121 if (err) {
3122 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3123 free(obj_id2);
3124 goto done;
3126 } else {
3127 err = got_object_id_str(&id_str1, obj_id1);
3128 if (err) {
3129 free(obj_id2);
3130 goto done;
3134 err = got_object_get_type(&obj_type, repo, obj_id2);
3135 if (err) {
3136 free(obj_id2);
3137 goto done;
3139 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3140 switch (obj_type) {
3141 case GOT_OBJ_TYPE_BLOB:
3142 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3143 0, repo);
3144 break;
3145 case GOT_OBJ_TYPE_TREE:
3146 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3147 0, repo);
3148 break;
3149 default:
3150 err = got_error(GOT_ERR_OBJ_TYPE);
3151 break;
3153 free(obj_id1);
3154 free(obj_id2);
3155 } else {
3156 obj_id2 = got_object_commit_get_tree_id(commit);
3157 err = got_object_id_str(&id_str2, obj_id2);
3158 if (err)
3159 goto done;
3160 obj_id1 = got_object_commit_get_tree_id(pcommit);
3161 err = got_object_id_str(&id_str1, obj_id1);
3162 if (err)
3163 goto done;
3164 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3165 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
3167 done:
3168 free(id_str1);
3169 free(id_str2);
3170 if (pcommit)
3171 got_object_commit_close(pcommit);
3172 return err;
3175 static char *
3176 get_datestr(time_t *time, char *datebuf)
3178 struct tm mytm, *tm;
3179 char *p, *s;
3181 tm = gmtime_r(time, &mytm);
3182 if (tm == NULL)
3183 return NULL;
3184 s = asctime_r(tm, datebuf);
3185 if (s == NULL)
3186 return NULL;
3187 p = strchr(s, '\n');
3188 if (p)
3189 *p = '\0';
3190 return s;
3193 static const struct got_error *
3194 match_logmsg(int *have_match, struct got_object_id *id,
3195 struct got_commit_object *commit, regex_t *regex)
3197 const struct got_error *err = NULL;
3198 regmatch_t regmatch;
3199 char *id_str = NULL, *logmsg = NULL;
3201 *have_match = 0;
3203 err = got_object_id_str(&id_str, id);
3204 if (err)
3205 return err;
3207 err = got_object_commit_get_logmsg(&logmsg, commit);
3208 if (err)
3209 goto done;
3211 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3212 *have_match = 1;
3213 done:
3214 free(id_str);
3215 free(logmsg);
3216 return err;
3219 static void
3220 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3221 regex_t *regex)
3223 regmatch_t regmatch;
3224 struct got_pathlist_entry *pe;
3226 *have_match = 0;
3228 TAILQ_FOREACH(pe, changed_paths, entry) {
3229 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3230 *have_match = 1;
3231 break;
3236 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3238 static const struct got_error *
3239 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3240 struct got_repository *repo, const char *path,
3241 struct got_pathlist_head *changed_paths, int show_patch,
3242 int diff_context, struct got_reflist_head *refs)
3244 const struct got_error *err = NULL;
3245 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3246 char datebuf[26];
3247 time_t committer_time;
3248 const char *author, *committer;
3249 char *refs_str = NULL;
3250 struct got_reflist_entry *re;
3252 SIMPLEQ_FOREACH(re, refs, entry) {
3253 char *s;
3254 const char *name;
3255 struct got_tag_object *tag = NULL;
3256 struct got_object_id *ref_id;
3257 int cmp;
3259 name = got_ref_get_name(re->ref);
3260 if (strcmp(name, GOT_REF_HEAD) == 0)
3261 continue;
3262 if (strncmp(name, "refs/", 5) == 0)
3263 name += 5;
3264 if (strncmp(name, "got/", 4) == 0)
3265 continue;
3266 if (strncmp(name, "heads/", 6) == 0)
3267 name += 6;
3268 if (strncmp(name, "remotes/", 8) == 0) {
3269 name += 8;
3270 s = strstr(name, "/" GOT_REF_HEAD);
3271 if (s != NULL && s[strlen(s)] == '\0')
3272 continue;
3274 err = got_ref_resolve(&ref_id, repo, re->ref);
3275 if (err)
3276 return err;
3277 if (strncmp(name, "tags/", 5) == 0) {
3278 err = got_object_open_as_tag(&tag, repo, ref_id);
3279 if (err) {
3280 if (err->code != GOT_ERR_OBJ_TYPE) {
3281 free(ref_id);
3282 return err;
3284 /* Ref points at something other than a tag. */
3285 err = NULL;
3286 tag = NULL;
3289 cmp = got_object_id_cmp(tag ?
3290 got_object_tag_get_object_id(tag) : ref_id, id);
3291 free(ref_id);
3292 if (tag)
3293 got_object_tag_close(tag);
3294 if (cmp != 0)
3295 continue;
3296 s = refs_str;
3297 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3298 name) == -1) {
3299 err = got_error_from_errno("asprintf");
3300 free(s);
3301 return err;
3303 free(s);
3305 err = got_object_id_str(&id_str, id);
3306 if (err)
3307 return err;
3309 printf(GOT_COMMIT_SEP_STR);
3310 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3311 refs_str ? refs_str : "", refs_str ? ")" : "");
3312 free(id_str);
3313 id_str = NULL;
3314 free(refs_str);
3315 refs_str = NULL;
3316 printf("from: %s\n", got_object_commit_get_author(commit));
3317 committer_time = got_object_commit_get_committer_time(commit);
3318 datestr = get_datestr(&committer_time, datebuf);
3319 if (datestr)
3320 printf("date: %s UTC\n", datestr);
3321 author = got_object_commit_get_author(commit);
3322 committer = got_object_commit_get_committer(commit);
3323 if (strcmp(author, committer) != 0)
3324 printf("via: %s\n", committer);
3325 if (got_object_commit_get_nparents(commit) > 1) {
3326 const struct got_object_id_queue *parent_ids;
3327 struct got_object_qid *qid;
3328 int n = 1;
3329 parent_ids = got_object_commit_get_parent_ids(commit);
3330 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3331 err = got_object_id_str(&id_str, qid->id);
3332 if (err)
3333 return err;
3334 printf("parent %d: %s\n", n++, id_str);
3335 free(id_str);
3339 err = got_object_commit_get_logmsg(&logmsg0, commit);
3340 if (err)
3341 return err;
3343 logmsg = logmsg0;
3344 do {
3345 line = strsep(&logmsg, "\n");
3346 if (line)
3347 printf(" %s\n", line);
3348 } while (line);
3349 free(logmsg0);
3351 if (changed_paths) {
3352 struct got_pathlist_entry *pe;
3353 TAILQ_FOREACH(pe, changed_paths, entry) {
3354 struct got_diff_changed_path *cp = pe->data;
3355 printf(" %c %s\n", cp->status, pe->path);
3357 printf("\n");
3359 if (show_patch) {
3360 err = print_patch(commit, id, path, diff_context, repo);
3361 if (err == 0)
3362 printf("\n");
3365 if (fflush(stdout) != 0 && err == NULL)
3366 err = got_error_from_errno("fflush");
3367 return err;
3370 static const struct got_error *
3371 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3372 struct got_repository *repo, const char *path, int show_changed_paths,
3373 int show_patch, const char *search_pattern, int diff_context, int limit,
3374 int log_branches, int reverse_display_order, struct got_reflist_head *refs)
3376 const struct got_error *err;
3377 struct got_commit_graph *graph;
3378 regex_t regex;
3379 int have_match;
3380 struct got_object_id_queue reversed_commits;
3381 struct got_object_qid *qid;
3382 struct got_commit_object *commit;
3383 struct got_pathlist_head changed_paths;
3384 struct got_pathlist_entry *pe;
3386 SIMPLEQ_INIT(&reversed_commits);
3387 TAILQ_INIT(&changed_paths);
3389 if (search_pattern && regcomp(&regex, search_pattern,
3390 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3391 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3393 err = got_commit_graph_open(&graph, path, !log_branches);
3394 if (err)
3395 return err;
3396 err = got_commit_graph_iter_start(graph, root_id, repo,
3397 check_cancelled, NULL);
3398 if (err)
3399 goto done;
3400 for (;;) {
3401 struct got_object_id *id;
3403 if (sigint_received || sigpipe_received)
3404 break;
3406 err = got_commit_graph_iter_next(&id, graph, repo,
3407 check_cancelled, NULL);
3408 if (err) {
3409 if (err->code == GOT_ERR_ITER_COMPLETED)
3410 err = NULL;
3411 break;
3413 if (id == NULL)
3414 break;
3416 err = got_object_open_as_commit(&commit, repo, id);
3417 if (err)
3418 break;
3420 if (show_changed_paths && !reverse_display_order) {
3421 err = get_changed_paths(&changed_paths, commit, repo);
3422 if (err)
3423 break;
3426 if (search_pattern) {
3427 err = match_logmsg(&have_match, id, commit, &regex);
3428 if (err) {
3429 got_object_commit_close(commit);
3430 break;
3432 if (have_match == 0 && show_changed_paths)
3433 match_changed_paths(&have_match,
3434 &changed_paths, &regex);
3435 if (have_match == 0) {
3436 got_object_commit_close(commit);
3437 TAILQ_FOREACH(pe, &changed_paths, entry) {
3438 free((char *)pe->path);
3439 free(pe->data);
3441 got_pathlist_free(&changed_paths);
3442 continue;
3446 if (reverse_display_order) {
3447 err = got_object_qid_alloc(&qid, id);
3448 if (err)
3449 break;
3450 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3451 got_object_commit_close(commit);
3452 } else {
3453 err = print_commit(commit, id, repo, path,
3454 show_changed_paths ? &changed_paths : NULL,
3455 show_patch, diff_context, refs);
3456 got_object_commit_close(commit);
3457 if (err)
3458 break;
3460 if ((limit && --limit == 0) ||
3461 (end_id && got_object_id_cmp(id, end_id) == 0))
3462 break;
3464 TAILQ_FOREACH(pe, &changed_paths, entry) {
3465 free((char *)pe->path);
3466 free(pe->data);
3468 got_pathlist_free(&changed_paths);
3470 if (reverse_display_order) {
3471 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3472 err = got_object_open_as_commit(&commit, repo, qid->id);
3473 if (err)
3474 break;
3475 if (show_changed_paths) {
3476 err = get_changed_paths(&changed_paths,
3477 commit, repo);
3478 if (err)
3479 break;
3481 err = print_commit(commit, qid->id, repo, path,
3482 show_changed_paths ? &changed_paths : NULL,
3483 show_patch, diff_context, refs);
3484 got_object_commit_close(commit);
3485 if (err)
3486 break;
3487 TAILQ_FOREACH(pe, &changed_paths, entry) {
3488 free((char *)pe->path);
3489 free(pe->data);
3491 got_pathlist_free(&changed_paths);
3494 done:
3495 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3496 qid = SIMPLEQ_FIRST(&reversed_commits);
3497 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3498 got_object_qid_free(qid);
3500 TAILQ_FOREACH(pe, &changed_paths, entry) {
3501 free((char *)pe->path);
3502 free(pe->data);
3504 got_pathlist_free(&changed_paths);
3505 if (search_pattern)
3506 regfree(&regex);
3507 got_commit_graph_close(graph);
3508 return err;
3511 __dead static void
3512 usage_log(void)
3514 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3515 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3516 "[-R] [path]\n", getprogname());
3517 exit(1);
3520 static int
3521 get_default_log_limit(void)
3523 const char *got_default_log_limit;
3524 long long n;
3525 const char *errstr;
3527 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3528 if (got_default_log_limit == NULL)
3529 return 0;
3530 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3531 if (errstr != NULL)
3532 return 0;
3533 return n;
3536 static const struct got_error *
3537 resolve_commit_arg(struct got_object_id **id, const char *commit_arg,
3538 struct got_repository *repo)
3540 const struct got_error *err = NULL;
3541 struct got_reference *ref;
3543 *id = NULL;
3545 err = got_ref_open(&ref, repo, commit_arg, 0);
3546 if (err == NULL) {
3547 int obj_type;
3548 err = got_ref_resolve(id, repo, ref);
3549 got_ref_close(ref);
3550 if (err)
3551 return err;
3552 err = got_object_get_type(&obj_type, repo, *id);
3553 if (err)
3554 return err;
3555 if (obj_type == GOT_OBJ_TYPE_TAG) {
3556 struct got_tag_object *tag;
3557 err = got_object_open_as_tag(&tag, repo, *id);
3558 if (err)
3559 return err;
3560 if (got_object_tag_get_object_type(tag) !=
3561 GOT_OBJ_TYPE_COMMIT) {
3562 got_object_tag_close(tag);
3563 return got_error(GOT_ERR_OBJ_TYPE);
3565 free(*id);
3566 *id = got_object_id_dup(
3567 got_object_tag_get_object_id(tag));
3568 if (*id == NULL)
3569 err = got_error_from_errno(
3570 "got_object_id_dup");
3571 got_object_tag_close(tag);
3572 if (err)
3573 return err;
3574 } else if (obj_type != GOT_OBJ_TYPE_COMMIT)
3575 return got_error(GOT_ERR_OBJ_TYPE);
3576 } else {
3577 err = got_repo_match_object_id_prefix(id, commit_arg,
3578 GOT_OBJ_TYPE_COMMIT, repo);
3581 return err;
3584 static const struct got_error *
3585 cmd_log(int argc, char *argv[])
3587 const struct got_error *error;
3588 struct got_repository *repo = NULL;
3589 struct got_worktree *worktree = NULL;
3590 struct got_object_id *start_id = NULL, *end_id = NULL;
3591 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3592 const char *start_commit = NULL, *end_commit = NULL;
3593 const char *search_pattern = NULL;
3594 int diff_context = -1, ch;
3595 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3596 int reverse_display_order = 0;
3597 const char *errstr;
3598 struct got_reflist_head refs;
3600 SIMPLEQ_INIT(&refs);
3602 #ifndef PROFILE
3603 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3604 NULL)
3605 == -1)
3606 err(1, "pledge");
3607 #endif
3609 limit = get_default_log_limit();
3611 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3612 switch (ch) {
3613 case 'p':
3614 show_patch = 1;
3615 break;
3616 case 'P':
3617 show_changed_paths = 1;
3618 break;
3619 case 'c':
3620 start_commit = optarg;
3621 break;
3622 case 'C':
3623 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3624 &errstr);
3625 if (errstr != NULL)
3626 err(1, "-C option %s", errstr);
3627 break;
3628 case 'l':
3629 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3630 if (errstr != NULL)
3631 err(1, "-l option %s", errstr);
3632 break;
3633 case 'b':
3634 log_branches = 1;
3635 break;
3636 case 'r':
3637 repo_path = realpath(optarg, NULL);
3638 if (repo_path == NULL)
3639 return got_error_from_errno2("realpath",
3640 optarg);
3641 got_path_strip_trailing_slashes(repo_path);
3642 break;
3643 case 'R':
3644 reverse_display_order = 1;
3645 break;
3646 case 's':
3647 search_pattern = optarg;
3648 break;
3649 case 'x':
3650 end_commit = optarg;
3651 break;
3652 default:
3653 usage_log();
3654 /* NOTREACHED */
3658 argc -= optind;
3659 argv += optind;
3661 if (diff_context == -1)
3662 diff_context = 3;
3663 else if (!show_patch)
3664 errx(1, "-C requires -p");
3666 cwd = getcwd(NULL, 0);
3667 if (cwd == NULL) {
3668 error = got_error_from_errno("getcwd");
3669 goto done;
3672 if (repo_path == NULL) {
3673 error = got_worktree_open(&worktree, cwd);
3674 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3675 goto done;
3676 error = NULL;
3679 if (argc == 0) {
3680 path = strdup("");
3681 if (path == NULL) {
3682 error = got_error_from_errno("strdup");
3683 goto done;
3685 } else if (argc == 1) {
3686 if (worktree) {
3687 error = got_worktree_resolve_path(&path, worktree,
3688 argv[0]);
3689 if (error)
3690 goto done;
3691 } else {
3692 path = strdup(argv[0]);
3693 if (path == NULL) {
3694 error = got_error_from_errno("strdup");
3695 goto done;
3698 } else
3699 usage_log();
3701 if (repo_path == NULL) {
3702 repo_path = worktree ?
3703 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3705 if (repo_path == NULL) {
3706 error = got_error_from_errno("strdup");
3707 goto done;
3710 error = got_repo_open(&repo, repo_path, NULL);
3711 if (error != NULL)
3712 goto done;
3714 error = apply_unveil(got_repo_get_path(repo), 1,
3715 worktree ? got_worktree_get_root_path(worktree) : NULL);
3716 if (error)
3717 goto done;
3719 if (start_commit == NULL) {
3720 struct got_reference *head_ref;
3721 struct got_commit_object *commit = NULL;
3722 error = got_ref_open(&head_ref, repo,
3723 worktree ? got_worktree_get_head_ref_name(worktree)
3724 : GOT_REF_HEAD, 0);
3725 if (error != NULL)
3726 goto done;
3727 error = got_ref_resolve(&start_id, repo, head_ref);
3728 got_ref_close(head_ref);
3729 if (error != NULL)
3730 goto done;
3731 error = got_object_open_as_commit(&commit, repo,
3732 start_id);
3733 if (error != NULL)
3734 goto done;
3735 got_object_commit_close(commit);
3736 } else {
3737 error = resolve_commit_arg(&start_id, start_commit, repo);
3738 if (error != NULL)
3739 goto done;
3741 if (end_commit != NULL) {
3742 error = resolve_commit_arg(&end_id, end_commit, repo);
3743 if (error != NULL)
3744 goto done;
3747 if (worktree) {
3748 const char *prefix = got_worktree_get_path_prefix(worktree);
3749 char *p;
3750 if (asprintf(&p, "%s%s%s", prefix,
3751 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3752 error = got_error_from_errno("asprintf");
3753 goto done;
3755 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3756 free(p);
3757 } else
3758 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3759 if (error != NULL)
3760 goto done;
3761 if (in_repo_path) {
3762 free(path);
3763 path = in_repo_path;
3766 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3767 if (error)
3768 goto done;
3770 error = print_commits(start_id, end_id, repo, path, show_changed_paths,
3771 show_patch, search_pattern, diff_context, limit, log_branches,
3772 reverse_display_order, &refs);
3773 done:
3774 free(path);
3775 free(repo_path);
3776 free(cwd);
3777 if (worktree)
3778 got_worktree_close(worktree);
3779 if (repo) {
3780 const struct got_error *repo_error;
3781 repo_error = got_repo_close(repo);
3782 if (error == NULL)
3783 error = repo_error;
3785 got_ref_list_free(&refs);
3786 return error;
3789 __dead static void
3790 usage_diff(void)
3792 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3793 "[-w] [object1 object2 | path]\n", getprogname());
3794 exit(1);
3797 struct print_diff_arg {
3798 struct got_repository *repo;
3799 struct got_worktree *worktree;
3800 int diff_context;
3801 const char *id_str;
3802 int header_shown;
3803 int diff_staged;
3804 int ignore_whitespace;
3808 * Create a file which contains the target path of a symlink so we can feed
3809 * it as content to the diff engine.
3811 static const struct got_error *
3812 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
3813 const char *abspath)
3815 const struct got_error *err = NULL;
3816 char target_path[PATH_MAX];
3817 ssize_t target_len, outlen;
3819 *fd = -1;
3821 if (dirfd != -1) {
3822 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
3823 if (target_len == -1)
3824 return got_error_from_errno2("readlinkat", abspath);
3825 } else {
3826 target_len = readlink(abspath, target_path, PATH_MAX);
3827 if (target_len == -1)
3828 return got_error_from_errno2("readlink", abspath);
3831 *fd = got_opentempfd();
3832 if (*fd == -1)
3833 return got_error_from_errno("got_opentempfd");
3835 outlen = write(*fd, target_path, target_len);
3836 if (outlen == -1) {
3837 err = got_error_from_errno("got_opentempfd");
3838 goto done;
3841 if (lseek(*fd, 0, SEEK_SET) == -1) {
3842 err = got_error_from_errno2("lseek", abspath);
3843 goto done;
3845 done:
3846 if (err) {
3847 close(*fd);
3848 *fd = -1;
3850 return err;
3853 static const struct got_error *
3854 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3855 const char *path, struct got_object_id *blob_id,
3856 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3857 int dirfd, const char *de_name)
3859 struct print_diff_arg *a = arg;
3860 const struct got_error *err = NULL;
3861 struct got_blob_object *blob1 = NULL;
3862 int fd = -1;
3863 FILE *f2 = NULL;
3864 char *abspath = NULL, *label1 = NULL;
3865 struct stat sb;
3867 if (a->diff_staged) {
3868 if (staged_status != GOT_STATUS_MODIFY &&
3869 staged_status != GOT_STATUS_ADD &&
3870 staged_status != GOT_STATUS_DELETE)
3871 return NULL;
3872 } else {
3873 if (staged_status == GOT_STATUS_DELETE)
3874 return NULL;
3875 if (status == GOT_STATUS_NONEXISTENT)
3876 return got_error_set_errno(ENOENT, path);
3877 if (status != GOT_STATUS_MODIFY &&
3878 status != GOT_STATUS_ADD &&
3879 status != GOT_STATUS_DELETE &&
3880 status != GOT_STATUS_CONFLICT)
3881 return NULL;
3884 if (!a->header_shown) {
3885 printf("diff %s %s%s\n", a->id_str,
3886 got_worktree_get_root_path(a->worktree),
3887 a->diff_staged ? " (staged changes)" : "");
3888 a->header_shown = 1;
3891 if (a->diff_staged) {
3892 const char *label1 = NULL, *label2 = NULL;
3893 switch (staged_status) {
3894 case GOT_STATUS_MODIFY:
3895 label1 = path;
3896 label2 = path;
3897 break;
3898 case GOT_STATUS_ADD:
3899 label2 = path;
3900 break;
3901 case GOT_STATUS_DELETE:
3902 label1 = path;
3903 break;
3904 default:
3905 return got_error(GOT_ERR_FILE_STATUS);
3907 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
3908 label1, label2, a->diff_context, a->ignore_whitespace,
3909 a->repo, stdout);
3912 if (staged_status == GOT_STATUS_ADD ||
3913 staged_status == GOT_STATUS_MODIFY) {
3914 char *id_str;
3915 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
3916 8192);
3917 if (err)
3918 goto done;
3919 err = got_object_id_str(&id_str, staged_blob_id);
3920 if (err)
3921 goto done;
3922 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
3923 err = got_error_from_errno("asprintf");
3924 free(id_str);
3925 goto done;
3927 free(id_str);
3928 } else if (status != GOT_STATUS_ADD) {
3929 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
3930 if (err)
3931 goto done;
3934 if (status != GOT_STATUS_DELETE) {
3935 if (asprintf(&abspath, "%s/%s",
3936 got_worktree_get_root_path(a->worktree), path) == -1) {
3937 err = got_error_from_errno("asprintf");
3938 goto done;
3941 if (dirfd != -1) {
3942 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
3943 if (fd == -1) {
3944 if (errno != ELOOP) {
3945 err = got_error_from_errno2("openat",
3946 abspath);
3947 goto done;
3949 err = get_symlink_target_file(&fd, dirfd,
3950 de_name, abspath);
3951 if (err)
3952 goto done;
3954 } else {
3955 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
3956 if (fd == -1) {
3957 if (errno != ELOOP) {
3958 err = got_error_from_errno2("open",
3959 abspath);
3960 goto done;
3962 err = get_symlink_target_file(&fd, dirfd,
3963 de_name, abspath);
3964 if (err)
3965 goto done;
3968 if (fstat(fd, &sb) == -1) {
3969 err = got_error_from_errno2("fstat", abspath);
3970 goto done;
3972 f2 = fdopen(fd, "r");
3973 if (f2 == NULL) {
3974 err = got_error_from_errno2("fdopen", abspath);
3975 goto done;
3977 fd = -1;
3978 } else
3979 sb.st_size = 0;
3981 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
3982 a->diff_context, a->ignore_whitespace, stdout);
3983 done:
3984 if (blob1)
3985 got_object_blob_close(blob1);
3986 if (f2 && fclose(f2) == EOF && err == NULL)
3987 err = got_error_from_errno("fclose");
3988 if (fd != -1 && close(fd) == -1 && err == NULL)
3989 err = got_error_from_errno("close");
3990 free(abspath);
3991 return err;
3994 static const struct got_error *
3995 cmd_diff(int argc, char *argv[])
3997 const struct got_error *error;
3998 struct got_repository *repo = NULL;
3999 struct got_worktree *worktree = NULL;
4000 char *cwd = NULL, *repo_path = NULL;
4001 struct got_object_id *id1 = NULL, *id2 = NULL;
4002 const char *id_str1 = NULL, *id_str2 = NULL;
4003 char *label1 = NULL, *label2 = NULL;
4004 int type1, type2;
4005 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
4006 const char *errstr;
4007 char *path = NULL;
4009 #ifndef PROFILE
4010 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4011 NULL) == -1)
4012 err(1, "pledge");
4013 #endif
4015 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
4016 switch (ch) {
4017 case 'C':
4018 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4019 &errstr);
4020 if (errstr != NULL)
4021 err(1, "-C option %s", errstr);
4022 break;
4023 case 'r':
4024 repo_path = realpath(optarg, NULL);
4025 if (repo_path == NULL)
4026 return got_error_from_errno2("realpath",
4027 optarg);
4028 got_path_strip_trailing_slashes(repo_path);
4029 break;
4030 case 's':
4031 diff_staged = 1;
4032 break;
4033 case 'w':
4034 ignore_whitespace = 1;
4035 break;
4036 default:
4037 usage_diff();
4038 /* NOTREACHED */
4042 argc -= optind;
4043 argv += optind;
4045 cwd = getcwd(NULL, 0);
4046 if (cwd == NULL) {
4047 error = got_error_from_errno("getcwd");
4048 goto done;
4050 if (argc <= 1) {
4051 if (repo_path)
4052 errx(1,
4053 "-r option can't be used when diffing a work tree");
4054 error = got_worktree_open(&worktree, cwd);
4055 if (error) {
4056 if (error->code == GOT_ERR_NOT_WORKTREE)
4057 error = wrap_not_worktree_error(error, "diff",
4058 cwd);
4059 goto done;
4061 repo_path = strdup(got_worktree_get_repo_path(worktree));
4062 if (repo_path == NULL) {
4063 error = got_error_from_errno("strdup");
4064 goto done;
4066 if (argc == 1) {
4067 error = got_worktree_resolve_path(&path, worktree,
4068 argv[0]);
4069 if (error)
4070 goto done;
4071 } else {
4072 path = strdup("");
4073 if (path == NULL) {
4074 error = got_error_from_errno("strdup");
4075 goto done;
4078 } else if (argc == 2) {
4079 if (diff_staged)
4080 errx(1, "-s option can't be used when diffing "
4081 "objects in repository");
4082 id_str1 = argv[0];
4083 id_str2 = argv[1];
4084 if (repo_path == NULL) {
4085 error = got_worktree_open(&worktree, cwd);
4086 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4087 goto done;
4088 if (worktree) {
4089 repo_path = strdup(
4090 got_worktree_get_repo_path(worktree));
4091 if (repo_path == NULL) {
4092 error = got_error_from_errno("strdup");
4093 goto done;
4095 } else {
4096 repo_path = strdup(cwd);
4097 if (repo_path == NULL) {
4098 error = got_error_from_errno("strdup");
4099 goto done;
4103 } else
4104 usage_diff();
4106 error = got_repo_open(&repo, repo_path, NULL);
4107 free(repo_path);
4108 if (error != NULL)
4109 goto done;
4111 error = apply_unveil(got_repo_get_path(repo), 1,
4112 worktree ? got_worktree_get_root_path(worktree) : NULL);
4113 if (error)
4114 goto done;
4116 if (argc <= 1) {
4117 struct print_diff_arg arg;
4118 struct got_pathlist_head paths;
4119 char *id_str;
4121 TAILQ_INIT(&paths);
4123 error = got_object_id_str(&id_str,
4124 got_worktree_get_base_commit_id(worktree));
4125 if (error)
4126 goto done;
4127 arg.repo = repo;
4128 arg.worktree = worktree;
4129 arg.diff_context = diff_context;
4130 arg.id_str = id_str;
4131 arg.header_shown = 0;
4132 arg.diff_staged = diff_staged;
4133 arg.ignore_whitespace = ignore_whitespace;
4135 error = got_pathlist_append(&paths, path, NULL);
4136 if (error)
4137 goto done;
4139 error = got_worktree_status(worktree, &paths, repo, print_diff,
4140 &arg, check_cancelled, NULL);
4141 free(id_str);
4142 got_pathlist_free(&paths);
4143 goto done;
4146 error = got_repo_match_object_id(&id1, &label1, id_str1,
4147 GOT_OBJ_TYPE_ANY, 1, repo);
4148 if (error)
4149 goto done;
4151 error = got_repo_match_object_id(&id2, &label2, id_str2,
4152 GOT_OBJ_TYPE_ANY, 1, repo);
4153 if (error)
4154 goto done;
4156 error = got_object_get_type(&type1, repo, id1);
4157 if (error)
4158 goto done;
4160 error = got_object_get_type(&type2, repo, id2);
4161 if (error)
4162 goto done;
4164 if (type1 != type2) {
4165 error = got_error(GOT_ERR_OBJ_TYPE);
4166 goto done;
4169 switch (type1) {
4170 case GOT_OBJ_TYPE_BLOB:
4171 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
4172 diff_context, ignore_whitespace, repo, stdout);
4173 break;
4174 case GOT_OBJ_TYPE_TREE:
4175 error = got_diff_objects_as_trees(id1, id2, "", "",
4176 diff_context, ignore_whitespace, repo, stdout);
4177 break;
4178 case GOT_OBJ_TYPE_COMMIT:
4179 printf("diff %s %s\n", label1, label2);
4180 error = got_diff_objects_as_commits(id1, id2, diff_context,
4181 ignore_whitespace, repo, stdout);
4182 break;
4183 default:
4184 error = got_error(GOT_ERR_OBJ_TYPE);
4186 done:
4187 free(label1);
4188 free(label2);
4189 free(id1);
4190 free(id2);
4191 free(path);
4192 if (worktree)
4193 got_worktree_close(worktree);
4194 if (repo) {
4195 const struct got_error *repo_error;
4196 repo_error = got_repo_close(repo);
4197 if (error == NULL)
4198 error = repo_error;
4200 return error;
4203 __dead static void
4204 usage_blame(void)
4206 fprintf(stderr,
4207 "usage: %s blame [-c commit] [-r repository-path] path\n",
4208 getprogname());
4209 exit(1);
4212 struct blame_line {
4213 int annotated;
4214 char *id_str;
4215 char *committer;
4216 char datebuf[11]; /* YYYY-MM-DD + NUL */
4219 struct blame_cb_args {
4220 struct blame_line *lines;
4221 int nlines;
4222 int nlines_prec;
4223 int lineno_cur;
4224 off_t *line_offsets;
4225 FILE *f;
4226 struct got_repository *repo;
4229 static const struct got_error *
4230 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4232 const struct got_error *err = NULL;
4233 struct blame_cb_args *a = arg;
4234 struct blame_line *bline;
4235 char *line = NULL;
4236 size_t linesize = 0;
4237 struct got_commit_object *commit = NULL;
4238 off_t offset;
4239 struct tm tm;
4240 time_t committer_time;
4242 if (nlines != a->nlines ||
4243 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4244 return got_error(GOT_ERR_RANGE);
4246 if (sigint_received)
4247 return got_error(GOT_ERR_ITER_COMPLETED);
4249 if (lineno == -1)
4250 return NULL; /* no change in this commit */
4252 /* Annotate this line. */
4253 bline = &a->lines[lineno - 1];
4254 if (bline->annotated)
4255 return NULL;
4256 err = got_object_id_str(&bline->id_str, id);
4257 if (err)
4258 return err;
4260 err = got_object_open_as_commit(&commit, a->repo, id);
4261 if (err)
4262 goto done;
4264 bline->committer = strdup(got_object_commit_get_committer(commit));
4265 if (bline->committer == NULL) {
4266 err = got_error_from_errno("strdup");
4267 goto done;
4270 committer_time = got_object_commit_get_committer_time(commit);
4271 if (localtime_r(&committer_time, &tm) == NULL)
4272 return got_error_from_errno("localtime_r");
4273 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4274 &tm) >= sizeof(bline->datebuf)) {
4275 err = got_error(GOT_ERR_NO_SPACE);
4276 goto done;
4278 bline->annotated = 1;
4280 /* Print lines annotated so far. */
4281 bline = &a->lines[a->lineno_cur - 1];
4282 if (!bline->annotated)
4283 goto done;
4285 offset = a->line_offsets[a->lineno_cur - 1];
4286 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4287 err = got_error_from_errno("fseeko");
4288 goto done;
4291 while (bline->annotated) {
4292 char *smallerthan, *at, *nl, *committer;
4293 size_t len;
4295 if (getline(&line, &linesize, a->f) == -1) {
4296 if (ferror(a->f))
4297 err = got_error_from_errno("getline");
4298 break;
4301 committer = bline->committer;
4302 smallerthan = strchr(committer, '<');
4303 if (smallerthan && smallerthan[1] != '\0')
4304 committer = smallerthan + 1;
4305 at = strchr(committer, '@');
4306 if (at)
4307 *at = '\0';
4308 len = strlen(committer);
4309 if (len >= 9)
4310 committer[8] = '\0';
4312 nl = strchr(line, '\n');
4313 if (nl)
4314 *nl = '\0';
4315 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4316 bline->id_str, bline->datebuf, committer, line);
4318 a->lineno_cur++;
4319 bline = &a->lines[a->lineno_cur - 1];
4321 done:
4322 if (commit)
4323 got_object_commit_close(commit);
4324 free(line);
4325 return err;
4328 static const struct got_error *
4329 cmd_blame(int argc, char *argv[])
4331 const struct got_error *error;
4332 struct got_repository *repo = NULL;
4333 struct got_worktree *worktree = NULL;
4334 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4335 char *link_target = NULL;
4336 struct got_object_id *obj_id = NULL;
4337 struct got_object_id *commit_id = NULL;
4338 struct got_blob_object *blob = NULL;
4339 char *commit_id_str = NULL;
4340 struct blame_cb_args bca;
4341 int ch, obj_type, i;
4342 size_t filesize;
4344 memset(&bca, 0, sizeof(bca));
4346 #ifndef PROFILE
4347 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4348 NULL) == -1)
4349 err(1, "pledge");
4350 #endif
4352 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4353 switch (ch) {
4354 case 'c':
4355 commit_id_str = optarg;
4356 break;
4357 case 'r':
4358 repo_path = realpath(optarg, NULL);
4359 if (repo_path == NULL)
4360 return got_error_from_errno2("realpath",
4361 optarg);
4362 got_path_strip_trailing_slashes(repo_path);
4363 break;
4364 default:
4365 usage_blame();
4366 /* NOTREACHED */
4370 argc -= optind;
4371 argv += optind;
4373 if (argc == 1)
4374 path = argv[0];
4375 else
4376 usage_blame();
4378 cwd = getcwd(NULL, 0);
4379 if (cwd == NULL) {
4380 error = got_error_from_errno("getcwd");
4381 goto done;
4383 if (repo_path == NULL) {
4384 error = got_worktree_open(&worktree, cwd);
4385 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4386 goto done;
4387 else
4388 error = NULL;
4389 if (worktree) {
4390 repo_path =
4391 strdup(got_worktree_get_repo_path(worktree));
4392 if (repo_path == NULL) {
4393 error = got_error_from_errno("strdup");
4394 if (error)
4395 goto done;
4397 } else {
4398 repo_path = strdup(cwd);
4399 if (repo_path == NULL) {
4400 error = got_error_from_errno("strdup");
4401 goto done;
4406 error = got_repo_open(&repo, repo_path, NULL);
4407 if (error != NULL)
4408 goto done;
4410 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4411 if (error)
4412 goto done;
4414 if (worktree) {
4415 const char *prefix = got_worktree_get_path_prefix(worktree);
4416 char *p, *worktree_subdir = cwd +
4417 strlen(got_worktree_get_root_path(worktree));
4418 if (asprintf(&p, "%s%s%s%s%s",
4419 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
4420 worktree_subdir, worktree_subdir[0] ? "/" : "",
4421 path) == -1) {
4422 error = got_error_from_errno("asprintf");
4423 goto done;
4425 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4426 free(p);
4427 } else {
4428 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4430 if (error)
4431 goto done;
4433 if (commit_id_str == NULL) {
4434 struct got_reference *head_ref;
4435 error = got_ref_open(&head_ref, repo, worktree ?
4436 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4437 if (error != NULL)
4438 goto done;
4439 error = got_ref_resolve(&commit_id, repo, head_ref);
4440 got_ref_close(head_ref);
4441 if (error != NULL)
4442 goto done;
4443 } else {
4444 error = got_repo_match_object_id(&commit_id, NULL,
4445 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4446 if (error)
4447 goto done;
4450 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4451 commit_id, repo);
4452 if (error)
4453 goto done;
4455 error = got_object_id_by_path(&obj_id, repo, commit_id,
4456 link_target ? link_target : in_repo_path);
4457 if (error)
4458 goto done;
4460 error = got_object_get_type(&obj_type, repo, obj_id);
4461 if (error)
4462 goto done;
4464 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4465 error = got_error_path(link_target ? link_target : in_repo_path,
4466 GOT_ERR_OBJ_TYPE);
4467 goto done;
4470 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4471 if (error)
4472 goto done;
4473 bca.f = got_opentemp();
4474 if (bca.f == NULL) {
4475 error = got_error_from_errno("got_opentemp");
4476 goto done;
4478 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4479 &bca.line_offsets, bca.f, blob);
4480 if (error || bca.nlines == 0)
4481 goto done;
4483 /* Don't include \n at EOF in the blame line count. */
4484 if (bca.line_offsets[bca.nlines - 1] == filesize)
4485 bca.nlines--;
4487 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4488 if (bca.lines == NULL) {
4489 error = got_error_from_errno("calloc");
4490 goto done;
4492 bca.lineno_cur = 1;
4493 bca.nlines_prec = 0;
4494 i = bca.nlines;
4495 while (i > 0) {
4496 i /= 10;
4497 bca.nlines_prec++;
4499 bca.repo = repo;
4501 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4502 repo, blame_cb, &bca, check_cancelled, NULL);
4503 done:
4504 free(in_repo_path);
4505 free(link_target);
4506 free(repo_path);
4507 free(cwd);
4508 free(commit_id);
4509 free(obj_id);
4510 if (blob)
4511 got_object_blob_close(blob);
4512 if (worktree)
4513 got_worktree_close(worktree);
4514 if (repo) {
4515 const struct got_error *repo_error;
4516 repo_error = got_repo_close(repo);
4517 if (error == NULL)
4518 error = repo_error;
4520 if (bca.lines) {
4521 for (i = 0; i < bca.nlines; i++) {
4522 struct blame_line *bline = &bca.lines[i];
4523 free(bline->id_str);
4524 free(bline->committer);
4526 free(bca.lines);
4528 free(bca.line_offsets);
4529 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4530 error = got_error_from_errno("fclose");
4531 return error;
4534 __dead static void
4535 usage_tree(void)
4537 fprintf(stderr,
4538 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4539 getprogname());
4540 exit(1);
4543 static const struct got_error *
4544 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4545 const char *root_path, struct got_repository *repo)
4547 const struct got_error *err = NULL;
4548 int is_root_path = (strcmp(path, root_path) == 0);
4549 const char *modestr = "";
4550 mode_t mode = got_tree_entry_get_mode(te);
4551 char *link_target = NULL;
4553 path += strlen(root_path);
4554 while (path[0] == '/')
4555 path++;
4557 if (got_object_tree_entry_is_submodule(te))
4558 modestr = "$";
4559 else if (S_ISLNK(mode)) {
4560 int i;
4562 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4563 if (err)
4564 return err;
4565 for (i = 0; i < strlen(link_target); i++) {
4566 if (!isprint((unsigned char)link_target[i]))
4567 link_target[i] = '?';
4570 modestr = "@";
4572 else if (S_ISDIR(mode))
4573 modestr = "/";
4574 else if (mode & S_IXUSR)
4575 modestr = "*";
4577 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4578 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4579 link_target ? " -> ": "", link_target ? link_target : "");
4581 free(link_target);
4582 return NULL;
4585 static const struct got_error *
4586 print_tree(const char *path, struct got_object_id *commit_id,
4587 int show_ids, int recurse, const char *root_path,
4588 struct got_repository *repo)
4590 const struct got_error *err = NULL;
4591 struct got_object_id *tree_id = NULL;
4592 struct got_tree_object *tree = NULL;
4593 int nentries, i;
4595 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4596 if (err)
4597 goto done;
4599 err = got_object_open_as_tree(&tree, repo, tree_id);
4600 if (err)
4601 goto done;
4602 nentries = got_object_tree_get_nentries(tree);
4603 for (i = 0; i < nentries; i++) {
4604 struct got_tree_entry *te;
4605 char *id = NULL;
4607 if (sigint_received || sigpipe_received)
4608 break;
4610 te = got_object_tree_get_entry(tree, i);
4611 if (show_ids) {
4612 char *id_str;
4613 err = got_object_id_str(&id_str,
4614 got_tree_entry_get_id(te));
4615 if (err)
4616 goto done;
4617 if (asprintf(&id, "%s ", id_str) == -1) {
4618 err = got_error_from_errno("asprintf");
4619 free(id_str);
4620 goto done;
4622 free(id_str);
4624 err = print_entry(te, id, path, root_path, repo);
4625 free(id);
4626 if (err)
4627 goto done;
4629 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4630 char *child_path;
4631 if (asprintf(&child_path, "%s%s%s", path,
4632 path[0] == '/' && path[1] == '\0' ? "" : "/",
4633 got_tree_entry_get_name(te)) == -1) {
4634 err = got_error_from_errno("asprintf");
4635 goto done;
4637 err = print_tree(child_path, commit_id, show_ids, 1,
4638 root_path, repo);
4639 free(child_path);
4640 if (err)
4641 goto done;
4644 done:
4645 if (tree)
4646 got_object_tree_close(tree);
4647 free(tree_id);
4648 return err;
4651 static const struct got_error *
4652 cmd_tree(int argc, char *argv[])
4654 const struct got_error *error;
4655 struct got_repository *repo = NULL;
4656 struct got_worktree *worktree = NULL;
4657 const char *path, *refname = NULL;
4658 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4659 struct got_object_id *commit_id = NULL;
4660 char *commit_id_str = NULL;
4661 int show_ids = 0, recurse = 0;
4662 int ch;
4664 #ifndef PROFILE
4665 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4666 NULL) == -1)
4667 err(1, "pledge");
4668 #endif
4670 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4671 switch (ch) {
4672 case 'c':
4673 commit_id_str = optarg;
4674 break;
4675 case 'r':
4676 repo_path = realpath(optarg, NULL);
4677 if (repo_path == NULL)
4678 return got_error_from_errno2("realpath",
4679 optarg);
4680 got_path_strip_trailing_slashes(repo_path);
4681 break;
4682 case 'i':
4683 show_ids = 1;
4684 break;
4685 case 'R':
4686 recurse = 1;
4687 break;
4688 default:
4689 usage_tree();
4690 /* NOTREACHED */
4694 argc -= optind;
4695 argv += optind;
4697 if (argc == 1)
4698 path = argv[0];
4699 else if (argc > 1)
4700 usage_tree();
4701 else
4702 path = NULL;
4704 cwd = getcwd(NULL, 0);
4705 if (cwd == NULL) {
4706 error = got_error_from_errno("getcwd");
4707 goto done;
4709 if (repo_path == NULL) {
4710 error = got_worktree_open(&worktree, cwd);
4711 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4712 goto done;
4713 else
4714 error = NULL;
4715 if (worktree) {
4716 repo_path =
4717 strdup(got_worktree_get_repo_path(worktree));
4718 if (repo_path == NULL)
4719 error = got_error_from_errno("strdup");
4720 if (error)
4721 goto done;
4722 } else {
4723 repo_path = strdup(cwd);
4724 if (repo_path == NULL) {
4725 error = got_error_from_errno("strdup");
4726 goto done;
4731 error = got_repo_open(&repo, repo_path, NULL);
4732 if (error != NULL)
4733 goto done;
4735 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4736 if (error)
4737 goto done;
4739 if (path == NULL) {
4740 if (worktree) {
4741 char *p, *worktree_subdir = cwd +
4742 strlen(got_worktree_get_root_path(worktree));
4743 if (asprintf(&p, "%s/%s",
4744 got_worktree_get_path_prefix(worktree),
4745 worktree_subdir) == -1) {
4746 error = got_error_from_errno("asprintf");
4747 goto done;
4749 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4750 free(p);
4751 if (error)
4752 goto done;
4753 } else
4754 path = "/";
4756 if (in_repo_path == NULL) {
4757 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4758 if (error != NULL)
4759 goto done;
4762 if (commit_id_str == NULL) {
4763 struct got_reference *head_ref;
4764 if (worktree)
4765 refname = got_worktree_get_head_ref_name(worktree);
4766 else
4767 refname = GOT_REF_HEAD;
4768 error = got_ref_open(&head_ref, repo, refname, 0);
4769 if (error != NULL)
4770 goto done;
4771 error = got_ref_resolve(&commit_id, repo, head_ref);
4772 got_ref_close(head_ref);
4773 if (error != NULL)
4774 goto done;
4775 } else {
4776 error = got_repo_match_object_id(&commit_id, NULL,
4777 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4778 if (error)
4779 goto done;
4782 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4783 in_repo_path, repo);
4784 done:
4785 free(in_repo_path);
4786 free(repo_path);
4787 free(cwd);
4788 free(commit_id);
4789 if (worktree)
4790 got_worktree_close(worktree);
4791 if (repo) {
4792 const struct got_error *repo_error;
4793 repo_error = got_repo_close(repo);
4794 if (error == NULL)
4795 error = repo_error;
4797 return error;
4800 __dead static void
4801 usage_status(void)
4803 fprintf(stderr, "usage: %s status [-s status-codes ] [path ...]\n",
4804 getprogname());
4805 exit(1);
4808 static const struct got_error *
4809 print_status(void *arg, unsigned char status, unsigned char staged_status,
4810 const char *path, struct got_object_id *blob_id,
4811 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4812 int dirfd, const char *de_name)
4814 if (status == staged_status && (status == GOT_STATUS_DELETE))
4815 status = GOT_STATUS_NO_CHANGE;
4816 if (arg) {
4817 char *status_codes = arg;
4818 size_t ncodes = strlen(status_codes);
4819 int i;
4820 for (i = 0; i < ncodes ; i++) {
4821 if (status == status_codes[i] ||
4822 staged_status == status_codes[i])
4823 break;
4825 if (i == ncodes)
4826 return NULL;
4828 printf("%c%c %s\n", status, staged_status, path);
4829 return NULL;
4832 static const struct got_error *
4833 cmd_status(int argc, char *argv[])
4835 const struct got_error *error = NULL;
4836 struct got_repository *repo = NULL;
4837 struct got_worktree *worktree = NULL;
4838 char *cwd = NULL, *status_codes = NULL;;
4839 struct got_pathlist_head paths;
4840 struct got_pathlist_entry *pe;
4841 int ch, i;
4843 TAILQ_INIT(&paths);
4845 while ((ch = getopt(argc, argv, "s:")) != -1) {
4846 switch (ch) {
4847 case 's':
4848 for (i = 0; i < strlen(optarg); i++) {
4849 switch (optarg[i]) {
4850 case GOT_STATUS_MODIFY:
4851 case GOT_STATUS_ADD:
4852 case GOT_STATUS_DELETE:
4853 case GOT_STATUS_CONFLICT:
4854 case GOT_STATUS_MISSING:
4855 case GOT_STATUS_OBSTRUCTED:
4856 case GOT_STATUS_UNVERSIONED:
4857 case GOT_STATUS_MODE_CHANGE:
4858 case GOT_STATUS_NONEXISTENT:
4859 break;
4860 default:
4861 errx(1, "invalid status code '%c'",
4862 optarg[i]);
4865 status_codes = optarg;
4866 break;
4867 default:
4868 usage_status();
4869 /* NOTREACHED */
4873 argc -= optind;
4874 argv += optind;
4876 #ifndef PROFILE
4877 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4878 NULL) == -1)
4879 err(1, "pledge");
4880 #endif
4881 cwd = getcwd(NULL, 0);
4882 if (cwd == NULL) {
4883 error = got_error_from_errno("getcwd");
4884 goto done;
4887 error = got_worktree_open(&worktree, cwd);
4888 if (error) {
4889 if (error->code == GOT_ERR_NOT_WORKTREE)
4890 error = wrap_not_worktree_error(error, "status", cwd);
4891 goto done;
4894 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4895 NULL);
4896 if (error != NULL)
4897 goto done;
4899 error = apply_unveil(got_repo_get_path(repo), 1,
4900 got_worktree_get_root_path(worktree));
4901 if (error)
4902 goto done;
4904 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
4905 if (error)
4906 goto done;
4908 error = got_worktree_status(worktree, &paths, repo, print_status,
4909 status_codes, check_cancelled, NULL);
4910 done:
4911 TAILQ_FOREACH(pe, &paths, entry)
4912 free((char *)pe->path);
4913 got_pathlist_free(&paths);
4914 free(cwd);
4915 return error;
4918 __dead static void
4919 usage_ref(void)
4921 fprintf(stderr,
4922 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
4923 "[-d] [name]\n",
4924 getprogname());
4925 exit(1);
4928 static const struct got_error *
4929 list_refs(struct got_repository *repo, const char *refname)
4931 static const struct got_error *err = NULL;
4932 struct got_reflist_head refs;
4933 struct got_reflist_entry *re;
4935 SIMPLEQ_INIT(&refs);
4936 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
4937 if (err)
4938 return err;
4940 SIMPLEQ_FOREACH(re, &refs, entry) {
4941 char *refstr;
4942 refstr = got_ref_to_str(re->ref);
4943 if (refstr == NULL)
4944 return got_error_from_errno("got_ref_to_str");
4945 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
4946 free(refstr);
4949 got_ref_list_free(&refs);
4950 return NULL;
4953 static const struct got_error *
4954 delete_ref(struct got_repository *repo, const char *refname)
4956 const struct got_error *err = NULL;
4957 struct got_reference *ref;
4959 err = got_ref_open(&ref, repo, refname, 0);
4960 if (err)
4961 return err;
4963 err = got_ref_delete(ref, repo);
4964 got_ref_close(ref);
4965 return err;
4968 static const struct got_error *
4969 add_ref(struct got_repository *repo, const char *refname, const char *target)
4971 const struct got_error *err = NULL;
4972 struct got_object_id *id;
4973 struct got_reference *ref = NULL;
4976 * Don't let the user create a reference name with a leading '-'.
4977 * While technically a valid reference name, this case is usually
4978 * an unintended typo.
4980 if (refname[0] == '-')
4981 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4983 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
4984 repo);
4985 if (err) {
4986 struct got_reference *target_ref;
4988 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
4989 return err;
4990 err = got_ref_open(&target_ref, repo, target, 0);
4991 if (err)
4992 return err;
4993 err = got_ref_resolve(&id, repo, target_ref);
4994 got_ref_close(target_ref);
4995 if (err)
4996 return err;
4999 err = got_ref_alloc(&ref, refname, id);
5000 if (err)
5001 goto done;
5003 err = got_ref_write(ref, repo);
5004 done:
5005 if (ref)
5006 got_ref_close(ref);
5007 free(id);
5008 return err;
5011 static const struct got_error *
5012 add_symref(struct got_repository *repo, const char *refname, const char *target)
5014 const struct got_error *err = NULL;
5015 struct got_reference *ref = NULL;
5016 struct got_reference *target_ref = NULL;
5019 * Don't let the user create a reference name with a leading '-'.
5020 * While technically a valid reference name, this case is usually
5021 * an unintended typo.
5023 if (refname[0] == '-')
5024 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5026 err = got_ref_open(&target_ref, repo, target, 0);
5027 if (err)
5028 return err;
5030 err = got_ref_alloc_symref(&ref, refname, target_ref);
5031 if (err)
5032 goto done;
5034 err = got_ref_write(ref, repo);
5035 done:
5036 if (target_ref)
5037 got_ref_close(target_ref);
5038 if (ref)
5039 got_ref_close(ref);
5040 return err;
5043 static const struct got_error *
5044 cmd_ref(int argc, char *argv[])
5046 const struct got_error *error = NULL;
5047 struct got_repository *repo = NULL;
5048 struct got_worktree *worktree = NULL;
5049 char *cwd = NULL, *repo_path = NULL;
5050 int ch, do_list = 0, do_delete = 0;
5051 const char *obj_arg = NULL, *symref_target= NULL;
5052 char *refname = NULL;
5054 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5055 switch (ch) {
5056 case 'c':
5057 obj_arg = optarg;
5058 break;
5059 case 'd':
5060 do_delete = 1;
5061 break;
5062 case 'r':
5063 repo_path = realpath(optarg, NULL);
5064 if (repo_path == NULL)
5065 return got_error_from_errno2("realpath",
5066 optarg);
5067 got_path_strip_trailing_slashes(repo_path);
5068 break;
5069 case 'l':
5070 do_list = 1;
5071 break;
5072 case 's':
5073 symref_target = optarg;
5074 break;
5075 default:
5076 usage_ref();
5077 /* NOTREACHED */
5081 if (obj_arg && do_list)
5082 errx(1, "-c and -l options are mutually exclusive");
5083 if (obj_arg && do_delete)
5084 errx(1, "-c and -d options are mutually exclusive");
5085 if (obj_arg && symref_target)
5086 errx(1, "-c and -s options are mutually exclusive");
5087 if (symref_target && do_delete)
5088 errx(1, "-s and -d options are mutually exclusive");
5089 if (symref_target && do_list)
5090 errx(1, "-s and -l options are mutually exclusive");
5091 if (do_delete && do_list)
5092 errx(1, "-d and -l options are mutually exclusive");
5094 argc -= optind;
5095 argv += optind;
5097 if (do_list) {
5098 if (argc != 0 && argc != 1)
5099 usage_ref();
5100 if (argc == 1) {
5101 refname = strdup(argv[0]);
5102 if (refname == NULL) {
5103 error = got_error_from_errno("strdup");
5104 goto done;
5107 } else {
5108 if (argc != 1)
5109 usage_ref();
5110 refname = strdup(argv[0]);
5111 if (refname == NULL) {
5112 error = got_error_from_errno("strdup");
5113 goto done;
5117 if (refname)
5118 got_path_strip_trailing_slashes(refname);
5120 #ifndef PROFILE
5121 if (do_list) {
5122 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5123 NULL) == -1)
5124 err(1, "pledge");
5125 } else {
5126 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5127 "sendfd unveil", NULL) == -1)
5128 err(1, "pledge");
5130 #endif
5131 cwd = getcwd(NULL, 0);
5132 if (cwd == NULL) {
5133 error = got_error_from_errno("getcwd");
5134 goto done;
5137 if (repo_path == NULL) {
5138 error = got_worktree_open(&worktree, cwd);
5139 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5140 goto done;
5141 else
5142 error = NULL;
5143 if (worktree) {
5144 repo_path =
5145 strdup(got_worktree_get_repo_path(worktree));
5146 if (repo_path == NULL)
5147 error = got_error_from_errno("strdup");
5148 if (error)
5149 goto done;
5150 } else {
5151 repo_path = strdup(cwd);
5152 if (repo_path == NULL) {
5153 error = got_error_from_errno("strdup");
5154 goto done;
5159 error = got_repo_open(&repo, repo_path, NULL);
5160 if (error != NULL)
5161 goto done;
5163 error = apply_unveil(got_repo_get_path(repo), do_list,
5164 worktree ? got_worktree_get_root_path(worktree) : NULL);
5165 if (error)
5166 goto done;
5168 if (do_list)
5169 error = list_refs(repo, refname);
5170 else if (do_delete)
5171 error = delete_ref(repo, refname);
5172 else if (symref_target)
5173 error = add_symref(repo, refname, symref_target);
5174 else {
5175 if (obj_arg == NULL)
5176 usage_ref();
5177 error = add_ref(repo, refname, obj_arg);
5179 done:
5180 free(refname);
5181 if (repo)
5182 got_repo_close(repo);
5183 if (worktree)
5184 got_worktree_close(worktree);
5185 free(cwd);
5186 free(repo_path);
5187 return error;
5190 __dead static void
5191 usage_branch(void)
5193 fprintf(stderr,
5194 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5195 "[name]\n", getprogname());
5196 exit(1);
5199 static const struct got_error *
5200 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5201 struct got_reference *ref)
5203 const struct got_error *err = NULL;
5204 const char *refname, *marker = " ";
5205 char *refstr;
5207 refname = got_ref_get_name(ref);
5208 if (worktree && strcmp(refname,
5209 got_worktree_get_head_ref_name(worktree)) == 0) {
5210 struct got_object_id *id = NULL;
5212 err = got_ref_resolve(&id, repo, ref);
5213 if (err)
5214 return err;
5215 if (got_object_id_cmp(id,
5216 got_worktree_get_base_commit_id(worktree)) == 0)
5217 marker = "* ";
5218 else
5219 marker = "~ ";
5220 free(id);
5223 if (strncmp(refname, "refs/heads/", 11) == 0)
5224 refname += 11;
5225 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5226 refname += 18;
5228 refstr = got_ref_to_str(ref);
5229 if (refstr == NULL)
5230 return got_error_from_errno("got_ref_to_str");
5232 printf("%s%s: %s\n", marker, refname, refstr);
5233 free(refstr);
5234 return NULL;
5237 static const struct got_error *
5238 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5240 const char *refname;
5242 if (worktree == NULL)
5243 return got_error(GOT_ERR_NOT_WORKTREE);
5245 refname = got_worktree_get_head_ref_name(worktree);
5247 if (strncmp(refname, "refs/heads/", 11) == 0)
5248 refname += 11;
5249 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5250 refname += 18;
5252 printf("%s\n", refname);
5254 return NULL;
5257 static const struct got_error *
5258 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5260 static const struct got_error *err = NULL;
5261 struct got_reflist_head refs;
5262 struct got_reflist_entry *re;
5263 struct got_reference *temp_ref = NULL;
5264 int rebase_in_progress, histedit_in_progress;
5266 SIMPLEQ_INIT(&refs);
5268 if (worktree) {
5269 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5270 worktree);
5271 if (err)
5272 return err;
5274 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5275 worktree);
5276 if (err)
5277 return err;
5279 if (rebase_in_progress || histedit_in_progress) {
5280 err = got_ref_open(&temp_ref, repo,
5281 got_worktree_get_head_ref_name(worktree), 0);
5282 if (err)
5283 return err;
5284 list_branch(repo, worktree, temp_ref);
5285 got_ref_close(temp_ref);
5289 err = got_ref_list(&refs, repo, "refs/heads",
5290 got_ref_cmp_by_name, NULL);
5291 if (err)
5292 return err;
5294 SIMPLEQ_FOREACH(re, &refs, entry)
5295 list_branch(repo, worktree, re->ref);
5297 got_ref_list_free(&refs);
5298 return NULL;
5301 static const struct got_error *
5302 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5303 const char *branch_name)
5305 const struct got_error *err = NULL;
5306 struct got_reference *ref = NULL;
5307 char *refname;
5309 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5310 return got_error_from_errno("asprintf");
5312 err = got_ref_open(&ref, repo, refname, 0);
5313 if (err)
5314 goto done;
5316 if (worktree &&
5317 strcmp(got_worktree_get_head_ref_name(worktree),
5318 got_ref_get_name(ref)) == 0) {
5319 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5320 "will not delete this work tree's current branch");
5321 goto done;
5324 err = got_ref_delete(ref, repo);
5325 done:
5326 if (ref)
5327 got_ref_close(ref);
5328 free(refname);
5329 return err;
5332 static const struct got_error *
5333 add_branch(struct got_repository *repo, const char *branch_name,
5334 struct got_object_id *base_commit_id)
5336 const struct got_error *err = NULL;
5337 struct got_reference *ref = NULL;
5338 char *base_refname = NULL, *refname = NULL;
5341 * Don't let the user create a branch name with a leading '-'.
5342 * While technically a valid reference name, this case is usually
5343 * an unintended typo.
5345 if (branch_name[0] == '-')
5346 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5348 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5349 err = got_error_from_errno("asprintf");
5350 goto done;
5353 err = got_ref_open(&ref, repo, refname, 0);
5354 if (err == NULL) {
5355 err = got_error(GOT_ERR_BRANCH_EXISTS);
5356 goto done;
5357 } else if (err->code != GOT_ERR_NOT_REF)
5358 goto done;
5360 err = got_ref_alloc(&ref, refname, base_commit_id);
5361 if (err)
5362 goto done;
5364 err = got_ref_write(ref, repo);
5365 done:
5366 if (ref)
5367 got_ref_close(ref);
5368 free(base_refname);
5369 free(refname);
5370 return err;
5373 static const struct got_error *
5374 cmd_branch(int argc, char *argv[])
5376 const struct got_error *error = NULL;
5377 struct got_repository *repo = NULL;
5378 struct got_worktree *worktree = NULL;
5379 char *cwd = NULL, *repo_path = NULL;
5380 int ch, do_list = 0, do_show = 0, do_update = 1;
5381 const char *delref = NULL, *commit_id_arg = NULL;
5382 struct got_reference *ref = NULL;
5383 struct got_pathlist_head paths;
5384 struct got_pathlist_entry *pe;
5385 struct got_object_id *commit_id = NULL;
5386 char *commit_id_str = NULL;
5388 TAILQ_INIT(&paths);
5390 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5391 switch (ch) {
5392 case 'c':
5393 commit_id_arg = optarg;
5394 break;
5395 case 'd':
5396 delref = optarg;
5397 break;
5398 case 'r':
5399 repo_path = realpath(optarg, NULL);
5400 if (repo_path == NULL)
5401 return got_error_from_errno2("realpath",
5402 optarg);
5403 got_path_strip_trailing_slashes(repo_path);
5404 break;
5405 case 'l':
5406 do_list = 1;
5407 break;
5408 case 'n':
5409 do_update = 0;
5410 break;
5411 default:
5412 usage_branch();
5413 /* NOTREACHED */
5417 if (do_list && delref)
5418 errx(1, "-l and -d options are mutually exclusive");
5420 argc -= optind;
5421 argv += optind;
5423 if (!do_list && !delref && argc == 0)
5424 do_show = 1;
5426 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5427 errx(1, "-c option can only be used when creating a branch");
5429 if (do_list || delref) {
5430 if (argc > 0)
5431 usage_branch();
5432 } else if (!do_show && argc != 1)
5433 usage_branch();
5435 #ifndef PROFILE
5436 if (do_list || do_show) {
5437 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5438 NULL) == -1)
5439 err(1, "pledge");
5440 } else {
5441 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5442 "sendfd unveil", NULL) == -1)
5443 err(1, "pledge");
5445 #endif
5446 cwd = getcwd(NULL, 0);
5447 if (cwd == NULL) {
5448 error = got_error_from_errno("getcwd");
5449 goto done;
5452 if (repo_path == NULL) {
5453 error = got_worktree_open(&worktree, cwd);
5454 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5455 goto done;
5456 else
5457 error = NULL;
5458 if (worktree) {
5459 repo_path =
5460 strdup(got_worktree_get_repo_path(worktree));
5461 if (repo_path == NULL)
5462 error = got_error_from_errno("strdup");
5463 if (error)
5464 goto done;
5465 } else {
5466 repo_path = strdup(cwd);
5467 if (repo_path == NULL) {
5468 error = got_error_from_errno("strdup");
5469 goto done;
5474 error = got_repo_open(&repo, repo_path, NULL);
5475 if (error != NULL)
5476 goto done;
5478 error = apply_unveil(got_repo_get_path(repo), do_list,
5479 worktree ? got_worktree_get_root_path(worktree) : NULL);
5480 if (error)
5481 goto done;
5483 if (do_show)
5484 error = show_current_branch(repo, worktree);
5485 else if (do_list)
5486 error = list_branches(repo, worktree);
5487 else if (delref)
5488 error = delete_branch(repo, worktree, delref);
5489 else {
5490 if (commit_id_arg == NULL)
5491 commit_id_arg = worktree ?
5492 got_worktree_get_head_ref_name(worktree) :
5493 GOT_REF_HEAD;
5494 error = got_repo_match_object_id(&commit_id, NULL,
5495 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5496 if (error)
5497 goto done;
5498 error = add_branch(repo, argv[0], commit_id);
5499 if (error)
5500 goto done;
5501 if (worktree && do_update) {
5502 struct got_update_progress_arg upa;
5503 char *branch_refname = NULL;
5505 error = got_object_id_str(&commit_id_str, commit_id);
5506 if (error)
5507 goto done;
5508 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5509 worktree);
5510 if (error)
5511 goto done;
5512 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5513 == -1) {
5514 error = got_error_from_errno("asprintf");
5515 goto done;
5517 error = got_ref_open(&ref, repo, branch_refname, 0);
5518 free(branch_refname);
5519 if (error)
5520 goto done;
5521 error = switch_head_ref(ref, commit_id, worktree,
5522 repo);
5523 if (error)
5524 goto done;
5525 error = got_worktree_set_base_commit_id(worktree, repo,
5526 commit_id);
5527 if (error)
5528 goto done;
5529 memset(&upa, 0, sizeof(upa));
5530 error = got_worktree_checkout_files(worktree, &paths,
5531 repo, update_progress, &upa, check_cancelled,
5532 NULL);
5533 if (error)
5534 goto done;
5535 if (upa.did_something)
5536 printf("Updated to commit %s\n", commit_id_str);
5537 print_update_progress_stats(&upa);
5540 done:
5541 if (ref)
5542 got_ref_close(ref);
5543 if (repo)
5544 got_repo_close(repo);
5545 if (worktree)
5546 got_worktree_close(worktree);
5547 free(cwd);
5548 free(repo_path);
5549 free(commit_id);
5550 free(commit_id_str);
5551 TAILQ_FOREACH(pe, &paths, entry)
5552 free((char *)pe->path);
5553 got_pathlist_free(&paths);
5554 return error;
5558 __dead static void
5559 usage_tag(void)
5561 fprintf(stderr,
5562 "usage: %s tag [-c commit] [-r repository] [-l] "
5563 "[-m message] name\n", getprogname());
5564 exit(1);
5567 #if 0
5568 static const struct got_error *
5569 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5571 const struct got_error *err = NULL;
5572 struct got_reflist_entry *re, *se, *new;
5573 struct got_object_id *re_id, *se_id;
5574 struct got_tag_object *re_tag, *se_tag;
5575 time_t re_time, se_time;
5577 SIMPLEQ_FOREACH(re, tags, entry) {
5578 se = SIMPLEQ_FIRST(sorted);
5579 if (se == NULL) {
5580 err = got_reflist_entry_dup(&new, re);
5581 if (err)
5582 return err;
5583 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5584 continue;
5585 } else {
5586 err = got_ref_resolve(&re_id, repo, re->ref);
5587 if (err)
5588 break;
5589 err = got_object_open_as_tag(&re_tag, repo, re_id);
5590 free(re_id);
5591 if (err)
5592 break;
5593 re_time = got_object_tag_get_tagger_time(re_tag);
5594 got_object_tag_close(re_tag);
5597 while (se) {
5598 err = got_ref_resolve(&se_id, repo, re->ref);
5599 if (err)
5600 break;
5601 err = got_object_open_as_tag(&se_tag, repo, se_id);
5602 free(se_id);
5603 if (err)
5604 break;
5605 se_time = got_object_tag_get_tagger_time(se_tag);
5606 got_object_tag_close(se_tag);
5608 if (se_time > re_time) {
5609 err = got_reflist_entry_dup(&new, re);
5610 if (err)
5611 return err;
5612 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5613 break;
5615 se = SIMPLEQ_NEXT(se, entry);
5616 continue;
5619 done:
5620 return err;
5622 #endif
5624 static const struct got_error *
5625 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5627 static const struct got_error *err = NULL;
5628 struct got_reflist_head refs;
5629 struct got_reflist_entry *re;
5631 SIMPLEQ_INIT(&refs);
5633 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5634 if (err)
5635 return err;
5637 SIMPLEQ_FOREACH(re, &refs, entry) {
5638 const char *refname;
5639 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5640 char datebuf[26];
5641 const char *tagger;
5642 time_t tagger_time;
5643 struct got_object_id *id;
5644 struct got_tag_object *tag;
5645 struct got_commit_object *commit = NULL;
5647 refname = got_ref_get_name(re->ref);
5648 if (strncmp(refname, "refs/tags/", 10) != 0)
5649 continue;
5650 refname += 10;
5651 refstr = got_ref_to_str(re->ref);
5652 if (refstr == NULL) {
5653 err = got_error_from_errno("got_ref_to_str");
5654 break;
5656 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5657 free(refstr);
5659 err = got_ref_resolve(&id, repo, re->ref);
5660 if (err)
5661 break;
5662 err = got_object_open_as_tag(&tag, repo, id);
5663 if (err) {
5664 if (err->code != GOT_ERR_OBJ_TYPE) {
5665 free(id);
5666 break;
5668 /* "lightweight" tag */
5669 err = got_object_open_as_commit(&commit, repo, id);
5670 if (err) {
5671 free(id);
5672 break;
5674 tagger = got_object_commit_get_committer(commit);
5675 tagger_time =
5676 got_object_commit_get_committer_time(commit);
5677 err = got_object_id_str(&id_str, id);
5678 free(id);
5679 if (err)
5680 break;
5681 } else {
5682 free(id);
5683 tagger = got_object_tag_get_tagger(tag);
5684 tagger_time = got_object_tag_get_tagger_time(tag);
5685 err = got_object_id_str(&id_str,
5686 got_object_tag_get_object_id(tag));
5687 if (err)
5688 break;
5690 printf("from: %s\n", tagger);
5691 datestr = get_datestr(&tagger_time, datebuf);
5692 if (datestr)
5693 printf("date: %s UTC\n", datestr);
5694 if (commit)
5695 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5696 else {
5697 switch (got_object_tag_get_object_type(tag)) {
5698 case GOT_OBJ_TYPE_BLOB:
5699 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5700 id_str);
5701 break;
5702 case GOT_OBJ_TYPE_TREE:
5703 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5704 id_str);
5705 break;
5706 case GOT_OBJ_TYPE_COMMIT:
5707 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5708 id_str);
5709 break;
5710 case GOT_OBJ_TYPE_TAG:
5711 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5712 id_str);
5713 break;
5714 default:
5715 break;
5718 free(id_str);
5719 if (commit) {
5720 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5721 if (err)
5722 break;
5723 got_object_commit_close(commit);
5724 } else {
5725 tagmsg0 = strdup(got_object_tag_get_message(tag));
5726 got_object_tag_close(tag);
5727 if (tagmsg0 == NULL) {
5728 err = got_error_from_errno("strdup");
5729 break;
5733 tagmsg = tagmsg0;
5734 do {
5735 line = strsep(&tagmsg, "\n");
5736 if (line)
5737 printf(" %s\n", line);
5738 } while (line);
5739 free(tagmsg0);
5742 got_ref_list_free(&refs);
5743 return NULL;
5746 static const struct got_error *
5747 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5748 const char *tag_name, const char *repo_path)
5750 const struct got_error *err = NULL;
5751 char *template = NULL, *initial_content = NULL;
5752 char *editor = NULL;
5753 int initial_content_len;
5754 int fd = -1;
5756 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5757 err = got_error_from_errno("asprintf");
5758 goto done;
5761 initial_content_len = asprintf(&initial_content,
5762 "\n# tagging commit %s as %s\n",
5763 commit_id_str, tag_name);
5764 if (initial_content_len == -1) {
5765 err = got_error_from_errno("asprintf");
5766 goto done;
5769 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5770 if (err)
5771 goto done;
5773 if (write(fd, initial_content, initial_content_len) == -1) {
5774 err = got_error_from_errno2("write", *tagmsg_path);
5775 goto done;
5778 err = get_editor(&editor);
5779 if (err)
5780 goto done;
5781 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
5782 done:
5783 free(initial_content);
5784 free(template);
5785 free(editor);
5787 if (fd != -1 && close(fd) == -1 && err == NULL)
5788 err = got_error_from_errno2("close", *tagmsg_path);
5790 /* Editor is done; we can now apply unveil(2) */
5791 if (err == NULL)
5792 err = apply_unveil(repo_path, 0, NULL);
5793 if (err) {
5794 free(*tagmsg);
5795 *tagmsg = NULL;
5797 return err;
5800 static const struct got_error *
5801 add_tag(struct got_repository *repo, struct got_worktree *worktree,
5802 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
5804 const struct got_error *err = NULL;
5805 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5806 char *label = NULL, *commit_id_str = NULL;
5807 struct got_reference *ref = NULL;
5808 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5809 char *tagmsg_path = NULL, *tag_id_str = NULL;
5810 int preserve_tagmsg = 0;
5813 * Don't let the user create a tag name with a leading '-'.
5814 * While technically a valid reference name, this case is usually
5815 * an unintended typo.
5817 if (tag_name[0] == '-')
5818 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5820 err = get_author(&tagger, repo, worktree);
5821 if (err)
5822 return err;
5824 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5825 GOT_OBJ_TYPE_COMMIT, 1, repo);
5826 if (err)
5827 goto done;
5829 err = got_object_id_str(&commit_id_str, commit_id);
5830 if (err)
5831 goto done;
5833 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5834 refname = strdup(tag_name);
5835 if (refname == NULL) {
5836 err = got_error_from_errno("strdup");
5837 goto done;
5839 tag_name += 10;
5840 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5841 err = got_error_from_errno("asprintf");
5842 goto done;
5845 err = got_ref_open(&ref, repo, refname, 0);
5846 if (err == NULL) {
5847 err = got_error(GOT_ERR_TAG_EXISTS);
5848 goto done;
5849 } else if (err->code != GOT_ERR_NOT_REF)
5850 goto done;
5852 if (tagmsg_arg == NULL) {
5853 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5854 tag_name, got_repo_get_path(repo));
5855 if (err) {
5856 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5857 tagmsg_path != NULL)
5858 preserve_tagmsg = 1;
5859 goto done;
5863 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5864 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5865 if (err) {
5866 if (tagmsg_path)
5867 preserve_tagmsg = 1;
5868 goto done;
5871 err = got_ref_alloc(&ref, refname, tag_id);
5872 if (err) {
5873 if (tagmsg_path)
5874 preserve_tagmsg = 1;
5875 goto done;
5878 err = got_ref_write(ref, repo);
5879 if (err) {
5880 if (tagmsg_path)
5881 preserve_tagmsg = 1;
5882 goto done;
5885 err = got_object_id_str(&tag_id_str, tag_id);
5886 if (err) {
5887 if (tagmsg_path)
5888 preserve_tagmsg = 1;
5889 goto done;
5891 printf("Created tag %s\n", tag_id_str);
5892 done:
5893 if (preserve_tagmsg) {
5894 fprintf(stderr, "%s: tag message preserved in %s\n",
5895 getprogname(), tagmsg_path);
5896 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
5897 err = got_error_from_errno2("unlink", tagmsg_path);
5898 free(tag_id_str);
5899 if (ref)
5900 got_ref_close(ref);
5901 free(commit_id);
5902 free(commit_id_str);
5903 free(refname);
5904 free(tagmsg);
5905 free(tagmsg_path);
5906 free(tagger);
5907 return err;
5910 static const struct got_error *
5911 cmd_tag(int argc, char *argv[])
5913 const struct got_error *error = NULL;
5914 struct got_repository *repo = NULL;
5915 struct got_worktree *worktree = NULL;
5916 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
5917 char *gitconfig_path = NULL;
5918 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
5919 int ch, do_list = 0;
5921 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
5922 switch (ch) {
5923 case 'c':
5924 commit_id_arg = optarg;
5925 break;
5926 case 'm':
5927 tagmsg = optarg;
5928 break;
5929 case 'r':
5930 repo_path = realpath(optarg, NULL);
5931 if (repo_path == NULL)
5932 return got_error_from_errno2("realpath",
5933 optarg);
5934 got_path_strip_trailing_slashes(repo_path);
5935 break;
5936 case 'l':
5937 do_list = 1;
5938 break;
5939 default:
5940 usage_tag();
5941 /* NOTREACHED */
5945 argc -= optind;
5946 argv += optind;
5948 if (do_list) {
5949 if (commit_id_arg != NULL)
5950 errx(1,
5951 "-c option can only be used when creating a tag");
5952 if (tagmsg)
5953 errx(1, "-l and -m options are mutually exclusive");
5954 if (argc > 0)
5955 usage_tag();
5956 } else if (argc != 1)
5957 usage_tag();
5959 tag_name = argv[0];
5961 #ifndef PROFILE
5962 if (do_list) {
5963 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5964 NULL) == -1)
5965 err(1, "pledge");
5966 } else {
5967 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5968 "sendfd unveil", NULL) == -1)
5969 err(1, "pledge");
5971 #endif
5972 cwd = getcwd(NULL, 0);
5973 if (cwd == NULL) {
5974 error = got_error_from_errno("getcwd");
5975 goto done;
5978 if (repo_path == NULL) {
5979 error = got_worktree_open(&worktree, cwd);
5980 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5981 goto done;
5982 else
5983 error = NULL;
5984 if (worktree) {
5985 repo_path =
5986 strdup(got_worktree_get_repo_path(worktree));
5987 if (repo_path == NULL)
5988 error = got_error_from_errno("strdup");
5989 if (error)
5990 goto done;
5991 } else {
5992 repo_path = strdup(cwd);
5993 if (repo_path == NULL) {
5994 error = got_error_from_errno("strdup");
5995 goto done;
6000 if (do_list) {
6001 error = got_repo_open(&repo, repo_path, NULL);
6002 if (error != NULL)
6003 goto done;
6004 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6005 if (error)
6006 goto done;
6007 error = list_tags(repo, worktree);
6008 } else {
6009 error = get_gitconfig_path(&gitconfig_path);
6010 if (error)
6011 goto done;
6012 error = got_repo_open(&repo, repo_path, gitconfig_path);
6013 if (error != NULL)
6014 goto done;
6016 if (tagmsg) {
6017 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6018 if (error)
6019 goto done;
6022 if (commit_id_arg == NULL) {
6023 struct got_reference *head_ref;
6024 struct got_object_id *commit_id;
6025 error = got_ref_open(&head_ref, repo,
6026 worktree ? got_worktree_get_head_ref_name(worktree)
6027 : GOT_REF_HEAD, 0);
6028 if (error)
6029 goto done;
6030 error = got_ref_resolve(&commit_id, repo, head_ref);
6031 got_ref_close(head_ref);
6032 if (error)
6033 goto done;
6034 error = got_object_id_str(&commit_id_str, commit_id);
6035 free(commit_id);
6036 if (error)
6037 goto done;
6040 error = add_tag(repo, worktree, tag_name,
6041 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6043 done:
6044 if (repo)
6045 got_repo_close(repo);
6046 if (worktree)
6047 got_worktree_close(worktree);
6048 free(cwd);
6049 free(repo_path);
6050 free(gitconfig_path);
6051 free(commit_id_str);
6052 return error;
6055 __dead static void
6056 usage_add(void)
6058 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6059 getprogname());
6060 exit(1);
6063 static const struct got_error *
6064 add_progress(void *arg, unsigned char status, const char *path)
6066 while (path[0] == '/')
6067 path++;
6068 printf("%c %s\n", status, path);
6069 return NULL;
6072 static const struct got_error *
6073 cmd_add(int argc, char *argv[])
6075 const struct got_error *error = NULL;
6076 struct got_repository *repo = NULL;
6077 struct got_worktree *worktree = NULL;
6078 char *cwd = NULL;
6079 struct got_pathlist_head paths;
6080 struct got_pathlist_entry *pe;
6081 int ch, can_recurse = 0, no_ignores = 0;
6083 TAILQ_INIT(&paths);
6085 while ((ch = getopt(argc, argv, "IR")) != -1) {
6086 switch (ch) {
6087 case 'I':
6088 no_ignores = 1;
6089 break;
6090 case 'R':
6091 can_recurse = 1;
6092 break;
6093 default:
6094 usage_add();
6095 /* NOTREACHED */
6099 argc -= optind;
6100 argv += optind;
6102 #ifndef PROFILE
6103 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6104 NULL) == -1)
6105 err(1, "pledge");
6106 #endif
6107 if (argc < 1)
6108 usage_add();
6110 cwd = getcwd(NULL, 0);
6111 if (cwd == NULL) {
6112 error = got_error_from_errno("getcwd");
6113 goto done;
6116 error = got_worktree_open(&worktree, cwd);
6117 if (error) {
6118 if (error->code == GOT_ERR_NOT_WORKTREE)
6119 error = wrap_not_worktree_error(error, "add", cwd);
6120 goto done;
6123 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6124 NULL);
6125 if (error != NULL)
6126 goto done;
6128 error = apply_unveil(got_repo_get_path(repo), 1,
6129 got_worktree_get_root_path(worktree));
6130 if (error)
6131 goto done;
6133 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6134 if (error)
6135 goto done;
6137 if (!can_recurse && no_ignores) {
6138 error = got_error_msg(GOT_ERR_BAD_PATH,
6139 "disregarding ignores requires -R option");
6140 goto done;
6144 if (!can_recurse) {
6145 char *ondisk_path;
6146 struct stat sb;
6147 TAILQ_FOREACH(pe, &paths, entry) {
6148 if (asprintf(&ondisk_path, "%s/%s",
6149 got_worktree_get_root_path(worktree),
6150 pe->path) == -1) {
6151 error = got_error_from_errno("asprintf");
6152 goto done;
6154 if (lstat(ondisk_path, &sb) == -1) {
6155 if (errno == ENOENT) {
6156 free(ondisk_path);
6157 continue;
6159 error = got_error_from_errno2("lstat",
6160 ondisk_path);
6161 free(ondisk_path);
6162 goto done;
6164 free(ondisk_path);
6165 if (S_ISDIR(sb.st_mode)) {
6166 error = got_error_msg(GOT_ERR_BAD_PATH,
6167 "adding directories requires -R option");
6168 goto done;
6173 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6174 NULL, repo, no_ignores);
6175 done:
6176 if (repo)
6177 got_repo_close(repo);
6178 if (worktree)
6179 got_worktree_close(worktree);
6180 TAILQ_FOREACH(pe, &paths, entry)
6181 free((char *)pe->path);
6182 got_pathlist_free(&paths);
6183 free(cwd);
6184 return error;
6187 __dead static void
6188 usage_remove(void)
6190 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6191 "path ...\n", getprogname());
6192 exit(1);
6195 static const struct got_error *
6196 print_remove_status(void *arg, unsigned char status,
6197 unsigned char staged_status, const char *path)
6199 while (path[0] == '/')
6200 path++;
6201 if (status == GOT_STATUS_NONEXISTENT)
6202 return NULL;
6203 if (status == staged_status && (status == GOT_STATUS_DELETE))
6204 status = GOT_STATUS_NO_CHANGE;
6205 printf("%c%c %s\n", status, staged_status, path);
6206 return NULL;
6209 static const struct got_error *
6210 cmd_remove(int argc, char *argv[])
6212 const struct got_error *error = NULL;
6213 struct got_worktree *worktree = NULL;
6214 struct got_repository *repo = NULL;
6215 const char *status_codes = NULL;
6216 char *cwd = NULL;
6217 struct got_pathlist_head paths;
6218 struct got_pathlist_entry *pe;
6219 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6221 TAILQ_INIT(&paths);
6223 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6224 switch (ch) {
6225 case 'f':
6226 delete_local_mods = 1;
6227 break;
6228 case 'k':
6229 keep_on_disk = 1;
6230 break;
6231 case 'R':
6232 can_recurse = 1;
6233 break;
6234 case 's':
6235 for (i = 0; i < strlen(optarg); i++) {
6236 switch (optarg[i]) {
6237 case GOT_STATUS_MODIFY:
6238 delete_local_mods = 1;
6239 break;
6240 case GOT_STATUS_MISSING:
6241 break;
6242 default:
6243 errx(1, "invalid status code '%c'",
6244 optarg[i]);
6247 status_codes = optarg;
6248 break;
6249 default:
6250 usage_remove();
6251 /* NOTREACHED */
6255 argc -= optind;
6256 argv += optind;
6258 #ifndef PROFILE
6259 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6260 NULL) == -1)
6261 err(1, "pledge");
6262 #endif
6263 if (argc < 1)
6264 usage_remove();
6266 cwd = getcwd(NULL, 0);
6267 if (cwd == NULL) {
6268 error = got_error_from_errno("getcwd");
6269 goto done;
6271 error = got_worktree_open(&worktree, cwd);
6272 if (error) {
6273 if (error->code == GOT_ERR_NOT_WORKTREE)
6274 error = wrap_not_worktree_error(error, "remove", cwd);
6275 goto done;
6278 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6279 NULL);
6280 if (error)
6281 goto done;
6283 error = apply_unveil(got_repo_get_path(repo), 1,
6284 got_worktree_get_root_path(worktree));
6285 if (error)
6286 goto done;
6288 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6289 if (error)
6290 goto done;
6292 if (!can_recurse) {
6293 char *ondisk_path;
6294 struct stat sb;
6295 TAILQ_FOREACH(pe, &paths, entry) {
6296 if (asprintf(&ondisk_path, "%s/%s",
6297 got_worktree_get_root_path(worktree),
6298 pe->path) == -1) {
6299 error = got_error_from_errno("asprintf");
6300 goto done;
6302 if (lstat(ondisk_path, &sb) == -1) {
6303 if (errno == ENOENT) {
6304 free(ondisk_path);
6305 continue;
6307 error = got_error_from_errno2("lstat",
6308 ondisk_path);
6309 free(ondisk_path);
6310 goto done;
6312 free(ondisk_path);
6313 if (S_ISDIR(sb.st_mode)) {
6314 error = got_error_msg(GOT_ERR_BAD_PATH,
6315 "removing directories requires -R option");
6316 goto done;
6321 error = got_worktree_schedule_delete(worktree, &paths,
6322 delete_local_mods, status_codes, print_remove_status, NULL,
6323 repo, keep_on_disk);
6324 done:
6325 if (repo)
6326 got_repo_close(repo);
6327 if (worktree)
6328 got_worktree_close(worktree);
6329 TAILQ_FOREACH(pe, &paths, entry)
6330 free((char *)pe->path);
6331 got_pathlist_free(&paths);
6332 free(cwd);
6333 return error;
6336 __dead static void
6337 usage_revert(void)
6339 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6340 "path ...\n", getprogname());
6341 exit(1);
6344 static const struct got_error *
6345 revert_progress(void *arg, unsigned char status, const char *path)
6347 if (status == GOT_STATUS_UNVERSIONED)
6348 return NULL;
6350 while (path[0] == '/')
6351 path++;
6352 printf("%c %s\n", status, path);
6353 return NULL;
6356 struct choose_patch_arg {
6357 FILE *patch_script_file;
6358 const char *action;
6361 static const struct got_error *
6362 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6363 int nchanges, const char *action)
6365 char *line = NULL;
6366 size_t linesize = 0;
6367 ssize_t linelen;
6369 switch (status) {
6370 case GOT_STATUS_ADD:
6371 printf("A %s\n%s this addition? [y/n] ", path, action);
6372 break;
6373 case GOT_STATUS_DELETE:
6374 printf("D %s\n%s this deletion? [y/n] ", path, action);
6375 break;
6376 case GOT_STATUS_MODIFY:
6377 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6378 return got_error_from_errno("fseek");
6379 printf(GOT_COMMIT_SEP_STR);
6380 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6381 printf("%s", line);
6382 if (ferror(patch_file))
6383 return got_error_from_errno("getline");
6384 printf(GOT_COMMIT_SEP_STR);
6385 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6386 path, n, nchanges, action);
6387 break;
6388 default:
6389 return got_error_path(path, GOT_ERR_FILE_STATUS);
6392 return NULL;
6395 static const struct got_error *
6396 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6397 FILE *patch_file, int n, int nchanges)
6399 const struct got_error *err = NULL;
6400 char *line = NULL;
6401 size_t linesize = 0;
6402 ssize_t linelen;
6403 int resp = ' ';
6404 struct choose_patch_arg *a = arg;
6406 *choice = GOT_PATCH_CHOICE_NONE;
6408 if (a->patch_script_file) {
6409 char *nl;
6410 err = show_change(status, path, patch_file, n, nchanges,
6411 a->action);
6412 if (err)
6413 return err;
6414 linelen = getline(&line, &linesize, a->patch_script_file);
6415 if (linelen == -1) {
6416 if (ferror(a->patch_script_file))
6417 return got_error_from_errno("getline");
6418 return NULL;
6420 nl = strchr(line, '\n');
6421 if (nl)
6422 *nl = '\0';
6423 if (strcmp(line, "y") == 0) {
6424 *choice = GOT_PATCH_CHOICE_YES;
6425 printf("y\n");
6426 } else if (strcmp(line, "n") == 0) {
6427 *choice = GOT_PATCH_CHOICE_NO;
6428 printf("n\n");
6429 } else if (strcmp(line, "q") == 0 &&
6430 status == GOT_STATUS_MODIFY) {
6431 *choice = GOT_PATCH_CHOICE_QUIT;
6432 printf("q\n");
6433 } else
6434 printf("invalid response '%s'\n", line);
6435 free(line);
6436 return NULL;
6439 while (resp != 'y' && resp != 'n' && resp != 'q') {
6440 err = show_change(status, path, patch_file, n, nchanges,
6441 a->action);
6442 if (err)
6443 return err;
6444 resp = getchar();
6445 if (resp == '\n')
6446 resp = getchar();
6447 if (status == GOT_STATUS_MODIFY) {
6448 if (resp != 'y' && resp != 'n' && resp != 'q') {
6449 printf("invalid response '%c'\n", resp);
6450 resp = ' ';
6452 } else if (resp != 'y' && resp != 'n') {
6453 printf("invalid response '%c'\n", resp);
6454 resp = ' ';
6458 if (resp == 'y')
6459 *choice = GOT_PATCH_CHOICE_YES;
6460 else if (resp == 'n')
6461 *choice = GOT_PATCH_CHOICE_NO;
6462 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6463 *choice = GOT_PATCH_CHOICE_QUIT;
6465 return NULL;
6469 static const struct got_error *
6470 cmd_revert(int argc, char *argv[])
6472 const struct got_error *error = NULL;
6473 struct got_worktree *worktree = NULL;
6474 struct got_repository *repo = NULL;
6475 char *cwd = NULL, *path = NULL;
6476 struct got_pathlist_head paths;
6477 struct got_pathlist_entry *pe;
6478 int ch, can_recurse = 0, pflag = 0;
6479 FILE *patch_script_file = NULL;
6480 const char *patch_script_path = NULL;
6481 struct choose_patch_arg cpa;
6483 TAILQ_INIT(&paths);
6485 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6486 switch (ch) {
6487 case 'p':
6488 pflag = 1;
6489 break;
6490 case 'F':
6491 patch_script_path = optarg;
6492 break;
6493 case 'R':
6494 can_recurse = 1;
6495 break;
6496 default:
6497 usage_revert();
6498 /* NOTREACHED */
6502 argc -= optind;
6503 argv += optind;
6505 #ifndef PROFILE
6506 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6507 "unveil", NULL) == -1)
6508 err(1, "pledge");
6509 #endif
6510 if (argc < 1)
6511 usage_revert();
6512 if (patch_script_path && !pflag)
6513 errx(1, "-F option can only be used together with -p option");
6515 cwd = getcwd(NULL, 0);
6516 if (cwd == NULL) {
6517 error = got_error_from_errno("getcwd");
6518 goto done;
6520 error = got_worktree_open(&worktree, cwd);
6521 if (error) {
6522 if (error->code == GOT_ERR_NOT_WORKTREE)
6523 error = wrap_not_worktree_error(error, "revert", cwd);
6524 goto done;
6527 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6528 NULL);
6529 if (error != NULL)
6530 goto done;
6532 if (patch_script_path) {
6533 patch_script_file = fopen(patch_script_path, "r");
6534 if (patch_script_file == NULL) {
6535 error = got_error_from_errno2("fopen",
6536 patch_script_path);
6537 goto done;
6540 error = apply_unveil(got_repo_get_path(repo), 1,
6541 got_worktree_get_root_path(worktree));
6542 if (error)
6543 goto done;
6545 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6546 if (error)
6547 goto done;
6549 if (!can_recurse) {
6550 char *ondisk_path;
6551 struct stat sb;
6552 TAILQ_FOREACH(pe, &paths, entry) {
6553 if (asprintf(&ondisk_path, "%s/%s",
6554 got_worktree_get_root_path(worktree),
6555 pe->path) == -1) {
6556 error = got_error_from_errno("asprintf");
6557 goto done;
6559 if (lstat(ondisk_path, &sb) == -1) {
6560 if (errno == ENOENT) {
6561 free(ondisk_path);
6562 continue;
6564 error = got_error_from_errno2("lstat",
6565 ondisk_path);
6566 free(ondisk_path);
6567 goto done;
6569 free(ondisk_path);
6570 if (S_ISDIR(sb.st_mode)) {
6571 error = got_error_msg(GOT_ERR_BAD_PATH,
6572 "reverting directories requires -R option");
6573 goto done;
6578 cpa.patch_script_file = patch_script_file;
6579 cpa.action = "revert";
6580 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6581 pflag ? choose_patch : NULL, &cpa, repo);
6582 done:
6583 if (patch_script_file && fclose(patch_script_file) == EOF &&
6584 error == NULL)
6585 error = got_error_from_errno2("fclose", patch_script_path);
6586 if (repo)
6587 got_repo_close(repo);
6588 if (worktree)
6589 got_worktree_close(worktree);
6590 free(path);
6591 free(cwd);
6592 return error;
6595 __dead static void
6596 usage_commit(void)
6598 fprintf(stderr, "usage: %s commit [-m msg] [-S] [path ...]\n",
6599 getprogname());
6600 exit(1);
6603 struct collect_commit_logmsg_arg {
6604 const char *cmdline_log;
6605 const char *editor;
6606 const char *worktree_path;
6607 const char *branch_name;
6608 const char *repo_path;
6609 char *logmsg_path;
6613 static const struct got_error *
6614 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6615 void *arg)
6617 char *initial_content = NULL;
6618 struct got_pathlist_entry *pe;
6619 const struct got_error *err = NULL;
6620 char *template = NULL;
6621 struct collect_commit_logmsg_arg *a = arg;
6622 int initial_content_len;
6623 int fd = -1;
6624 size_t len;
6626 /* if a message was specified on the command line, just use it */
6627 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6628 len = strlen(a->cmdline_log) + 1;
6629 *logmsg = malloc(len + 1);
6630 if (*logmsg == NULL)
6631 return got_error_from_errno("malloc");
6632 strlcpy(*logmsg, a->cmdline_log, len);
6633 return NULL;
6636 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6637 return got_error_from_errno("asprintf");
6639 initial_content_len = asprintf(&initial_content,
6640 "\n# changes to be committed on branch %s:\n",
6641 a->branch_name);
6642 if (initial_content_len == -1)
6643 return got_error_from_errno("asprintf");
6645 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6646 if (err)
6647 goto done;
6649 if (write(fd, initial_content, initial_content_len) == -1) {
6650 err = got_error_from_errno2("write", a->logmsg_path);
6651 goto done;
6654 TAILQ_FOREACH(pe, commitable_paths, entry) {
6655 struct got_commitable *ct = pe->data;
6656 dprintf(fd, "# %c %s\n",
6657 got_commitable_get_status(ct),
6658 got_commitable_get_path(ct));
6661 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
6662 done:
6663 free(initial_content);
6664 free(template);
6666 if (fd != -1 && close(fd) == -1 && err == NULL)
6667 err = got_error_from_errno2("close", a->logmsg_path);
6669 /* Editor is done; we can now apply unveil(2) */
6670 if (err == NULL)
6671 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6672 if (err) {
6673 free(*logmsg);
6674 *logmsg = NULL;
6676 return err;
6679 static const struct got_error *
6680 cmd_commit(int argc, char *argv[])
6682 const struct got_error *error = NULL;
6683 struct got_worktree *worktree = NULL;
6684 struct got_repository *repo = NULL;
6685 char *cwd = NULL, *id_str = NULL;
6686 struct got_object_id *id = NULL;
6687 const char *logmsg = NULL;
6688 struct collect_commit_logmsg_arg cl_arg;
6689 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6690 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6691 int allow_bad_symlinks = 0;
6692 struct got_pathlist_head paths;
6694 TAILQ_INIT(&paths);
6695 cl_arg.logmsg_path = NULL;
6697 while ((ch = getopt(argc, argv, "m:S")) != -1) {
6698 switch (ch) {
6699 case 'm':
6700 logmsg = optarg;
6701 break;
6702 case 'S':
6703 allow_bad_symlinks = 1;
6704 break;
6705 default:
6706 usage_commit();
6707 /* NOTREACHED */
6711 argc -= optind;
6712 argv += optind;
6714 #ifndef PROFILE
6715 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6716 "unveil", NULL) == -1)
6717 err(1, "pledge");
6718 #endif
6719 cwd = getcwd(NULL, 0);
6720 if (cwd == NULL) {
6721 error = got_error_from_errno("getcwd");
6722 goto done;
6724 error = got_worktree_open(&worktree, cwd);
6725 if (error) {
6726 if (error->code == GOT_ERR_NOT_WORKTREE)
6727 error = wrap_not_worktree_error(error, "commit", cwd);
6728 goto done;
6731 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6732 if (error)
6733 goto done;
6734 if (rebase_in_progress) {
6735 error = got_error(GOT_ERR_REBASING);
6736 goto done;
6739 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6740 worktree);
6741 if (error)
6742 goto done;
6744 error = get_gitconfig_path(&gitconfig_path);
6745 if (error)
6746 goto done;
6747 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6748 gitconfig_path);
6749 if (error != NULL)
6750 goto done;
6752 error = get_author(&author, repo, worktree);
6753 if (error)
6754 return error;
6757 * unveil(2) traverses exec(2); if an editor is used we have
6758 * to apply unveil after the log message has been written.
6760 if (logmsg == NULL || strlen(logmsg) == 0)
6761 error = get_editor(&editor);
6762 else
6763 error = apply_unveil(got_repo_get_path(repo), 0,
6764 got_worktree_get_root_path(worktree));
6765 if (error)
6766 goto done;
6768 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6769 if (error)
6770 goto done;
6772 cl_arg.editor = editor;
6773 cl_arg.cmdline_log = logmsg;
6774 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6775 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6776 if (!histedit_in_progress) {
6777 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6778 error = got_error(GOT_ERR_COMMIT_BRANCH);
6779 goto done;
6781 cl_arg.branch_name += 11;
6783 cl_arg.repo_path = got_repo_get_path(repo);
6784 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6785 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
6786 print_status, NULL, repo);
6787 if (error) {
6788 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6789 cl_arg.logmsg_path != NULL)
6790 preserve_logmsg = 1;
6791 goto done;
6794 error = got_object_id_str(&id_str, id);
6795 if (error)
6796 goto done;
6797 printf("Created commit %s\n", id_str);
6798 done:
6799 if (preserve_logmsg) {
6800 fprintf(stderr, "%s: log message preserved in %s\n",
6801 getprogname(), cl_arg.logmsg_path);
6802 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6803 error == NULL)
6804 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6805 free(cl_arg.logmsg_path);
6806 if (repo)
6807 got_repo_close(repo);
6808 if (worktree)
6809 got_worktree_close(worktree);
6810 free(cwd);
6811 free(id_str);
6812 free(gitconfig_path);
6813 free(editor);
6814 free(author);
6815 return error;
6818 __dead static void
6819 usage_cherrypick(void)
6821 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6822 exit(1);
6825 static const struct got_error *
6826 cmd_cherrypick(int argc, char *argv[])
6828 const struct got_error *error = NULL;
6829 struct got_worktree *worktree = NULL;
6830 struct got_repository *repo = NULL;
6831 char *cwd = NULL, *commit_id_str = NULL;
6832 struct got_object_id *commit_id = NULL;
6833 struct got_commit_object *commit = NULL;
6834 struct got_object_qid *pid;
6835 struct got_reference *head_ref = NULL;
6836 int ch;
6837 struct got_update_progress_arg upa;
6839 while ((ch = getopt(argc, argv, "")) != -1) {
6840 switch (ch) {
6841 default:
6842 usage_cherrypick();
6843 /* NOTREACHED */
6847 argc -= optind;
6848 argv += optind;
6850 #ifndef PROFILE
6851 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6852 "unveil", NULL) == -1)
6853 err(1, "pledge");
6854 #endif
6855 if (argc != 1)
6856 usage_cherrypick();
6858 cwd = getcwd(NULL, 0);
6859 if (cwd == NULL) {
6860 error = got_error_from_errno("getcwd");
6861 goto done;
6863 error = got_worktree_open(&worktree, cwd);
6864 if (error) {
6865 if (error->code == GOT_ERR_NOT_WORKTREE)
6866 error = wrap_not_worktree_error(error, "cherrypick",
6867 cwd);
6868 goto done;
6871 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6872 NULL);
6873 if (error != NULL)
6874 goto done;
6876 error = apply_unveil(got_repo_get_path(repo), 0,
6877 got_worktree_get_root_path(worktree));
6878 if (error)
6879 goto done;
6881 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6882 GOT_OBJ_TYPE_COMMIT, repo);
6883 if (error != NULL) {
6884 struct got_reference *ref;
6885 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6886 goto done;
6887 error = got_ref_open(&ref, repo, argv[0], 0);
6888 if (error != NULL)
6889 goto done;
6890 error = got_ref_resolve(&commit_id, repo, ref);
6891 got_ref_close(ref);
6892 if (error != NULL)
6893 goto done;
6895 error = got_object_id_str(&commit_id_str, commit_id);
6896 if (error)
6897 goto done;
6899 error = got_ref_open(&head_ref, repo,
6900 got_worktree_get_head_ref_name(worktree), 0);
6901 if (error != NULL)
6902 goto done;
6904 error = check_same_branch(commit_id, head_ref, NULL, repo);
6905 if (error) {
6906 if (error->code != GOT_ERR_ANCESTRY)
6907 goto done;
6908 error = NULL;
6909 } else {
6910 error = got_error(GOT_ERR_SAME_BRANCH);
6911 goto done;
6914 error = got_object_open_as_commit(&commit, repo, commit_id);
6915 if (error)
6916 goto done;
6917 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6918 memset(&upa, 0, sizeof(upa));
6919 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
6920 commit_id, repo, update_progress, &upa, check_cancelled,
6921 NULL);
6922 if (error != NULL)
6923 goto done;
6925 if (upa.did_something)
6926 printf("Merged commit %s\n", commit_id_str);
6927 print_update_progress_stats(&upa);
6928 done:
6929 if (commit)
6930 got_object_commit_close(commit);
6931 free(commit_id_str);
6932 if (head_ref)
6933 got_ref_close(head_ref);
6934 if (worktree)
6935 got_worktree_close(worktree);
6936 if (repo)
6937 got_repo_close(repo);
6938 return error;
6941 __dead static void
6942 usage_backout(void)
6944 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
6945 exit(1);
6948 static const struct got_error *
6949 cmd_backout(int argc, char *argv[])
6951 const struct got_error *error = NULL;
6952 struct got_worktree *worktree = NULL;
6953 struct got_repository *repo = NULL;
6954 char *cwd = NULL, *commit_id_str = NULL;
6955 struct got_object_id *commit_id = NULL;
6956 struct got_commit_object *commit = NULL;
6957 struct got_object_qid *pid;
6958 struct got_reference *head_ref = NULL;
6959 int ch;
6960 struct got_update_progress_arg upa;
6962 while ((ch = getopt(argc, argv, "")) != -1) {
6963 switch (ch) {
6964 default:
6965 usage_backout();
6966 /* NOTREACHED */
6970 argc -= optind;
6971 argv += optind;
6973 #ifndef PROFILE
6974 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6975 "unveil", NULL) == -1)
6976 err(1, "pledge");
6977 #endif
6978 if (argc != 1)
6979 usage_backout();
6981 cwd = getcwd(NULL, 0);
6982 if (cwd == NULL) {
6983 error = got_error_from_errno("getcwd");
6984 goto done;
6986 error = got_worktree_open(&worktree, cwd);
6987 if (error) {
6988 if (error->code == GOT_ERR_NOT_WORKTREE)
6989 error = wrap_not_worktree_error(error, "backout", cwd);
6990 goto done;
6993 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6994 NULL);
6995 if (error != NULL)
6996 goto done;
6998 error = apply_unveil(got_repo_get_path(repo), 0,
6999 got_worktree_get_root_path(worktree));
7000 if (error)
7001 goto done;
7003 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7004 GOT_OBJ_TYPE_COMMIT, repo);
7005 if (error != NULL) {
7006 struct got_reference *ref;
7007 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7008 goto done;
7009 error = got_ref_open(&ref, repo, argv[0], 0);
7010 if (error != NULL)
7011 goto done;
7012 error = got_ref_resolve(&commit_id, repo, ref);
7013 got_ref_close(ref);
7014 if (error != NULL)
7015 goto done;
7017 error = got_object_id_str(&commit_id_str, commit_id);
7018 if (error)
7019 goto done;
7021 error = got_ref_open(&head_ref, repo,
7022 got_worktree_get_head_ref_name(worktree), 0);
7023 if (error != NULL)
7024 goto done;
7026 error = check_same_branch(commit_id, head_ref, NULL, repo);
7027 if (error)
7028 goto done;
7030 error = got_object_open_as_commit(&commit, repo, commit_id);
7031 if (error)
7032 goto done;
7033 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7034 if (pid == NULL) {
7035 error = got_error(GOT_ERR_ROOT_COMMIT);
7036 goto done;
7039 memset(&upa, 0, sizeof(upa));
7040 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
7041 update_progress, &upa, check_cancelled, NULL);
7042 if (error != NULL)
7043 goto done;
7045 if (upa.did_something)
7046 printf("Backed out commit %s\n", commit_id_str);
7047 print_update_progress_stats(&upa);
7048 done:
7049 if (commit)
7050 got_object_commit_close(commit);
7051 free(commit_id_str);
7052 if (head_ref)
7053 got_ref_close(head_ref);
7054 if (worktree)
7055 got_worktree_close(worktree);
7056 if (repo)
7057 got_repo_close(repo);
7058 return error;
7061 __dead static void
7062 usage_rebase(void)
7064 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
7065 getprogname());
7066 exit(1);
7069 void
7070 trim_logmsg(char *logmsg, int limit)
7072 char *nl;
7073 size_t len;
7075 len = strlen(logmsg);
7076 if (len > limit)
7077 len = limit;
7078 logmsg[len] = '\0';
7079 nl = strchr(logmsg, '\n');
7080 if (nl)
7081 *nl = '\0';
7084 static const struct got_error *
7085 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
7087 const struct got_error *err;
7088 char *logmsg0 = NULL;
7089 const char *s;
7091 err = got_object_commit_get_logmsg(&logmsg0, commit);
7092 if (err)
7093 return err;
7095 s = logmsg0;
7096 while (isspace((unsigned char)s[0]))
7097 s++;
7099 *logmsg = strdup(s);
7100 if (*logmsg == NULL) {
7101 err = got_error_from_errno("strdup");
7102 goto done;
7105 trim_logmsg(*logmsg, limit);
7106 done:
7107 free(logmsg0);
7108 return err;
7111 static const struct got_error *
7112 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
7114 const struct got_error *err;
7115 struct got_commit_object *commit = NULL;
7116 char *id_str = NULL, *logmsg = NULL;
7118 err = got_object_open_as_commit(&commit, repo, id);
7119 if (err)
7120 return err;
7122 err = got_object_id_str(&id_str, id);
7123 if (err)
7124 goto done;
7126 id_str[12] = '\0';
7128 err = get_short_logmsg(&logmsg, 42, commit);
7129 if (err)
7130 goto done;
7132 printf("%s -> merge conflict: %s\n", id_str, logmsg);
7133 done:
7134 free(id_str);
7135 got_object_commit_close(commit);
7136 free(logmsg);
7137 return err;
7140 static const struct got_error *
7141 show_rebase_progress(struct got_commit_object *commit,
7142 struct got_object_id *old_id, struct got_object_id *new_id)
7144 const struct got_error *err;
7145 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7147 err = got_object_id_str(&old_id_str, old_id);
7148 if (err)
7149 goto done;
7151 if (new_id) {
7152 err = got_object_id_str(&new_id_str, new_id);
7153 if (err)
7154 goto done;
7157 old_id_str[12] = '\0';
7158 if (new_id_str)
7159 new_id_str[12] = '\0';
7161 err = get_short_logmsg(&logmsg, 42, commit);
7162 if (err)
7163 goto done;
7165 printf("%s -> %s: %s\n", old_id_str,
7166 new_id_str ? new_id_str : "no-op change", logmsg);
7167 done:
7168 free(old_id_str);
7169 free(new_id_str);
7170 free(logmsg);
7171 return err;
7174 static const struct got_error *
7175 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
7176 struct got_reference *branch, struct got_reference *new_base_branch,
7177 struct got_reference *tmp_branch, struct got_repository *repo)
7179 printf("Switching work tree to %s\n", got_ref_get_name(branch));
7180 return got_worktree_rebase_complete(worktree, fileindex,
7181 new_base_branch, tmp_branch, branch, repo);
7184 static const struct got_error *
7185 rebase_commit(struct got_pathlist_head *merged_paths,
7186 struct got_worktree *worktree, struct got_fileindex *fileindex,
7187 struct got_reference *tmp_branch,
7188 struct got_object_id *commit_id, struct got_repository *repo)
7190 const struct got_error *error;
7191 struct got_commit_object *commit;
7192 struct got_object_id *new_commit_id;
7194 error = got_object_open_as_commit(&commit, repo, commit_id);
7195 if (error)
7196 return error;
7198 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
7199 worktree, fileindex, tmp_branch, commit, commit_id, repo);
7200 if (error) {
7201 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
7202 goto done;
7203 error = show_rebase_progress(commit, commit_id, NULL);
7204 } else {
7205 error = show_rebase_progress(commit, commit_id, new_commit_id);
7206 free(new_commit_id);
7208 done:
7209 got_object_commit_close(commit);
7210 return error;
7213 struct check_path_prefix_arg {
7214 const char *path_prefix;
7215 size_t len;
7216 int errcode;
7219 static const struct got_error *
7220 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
7221 struct got_blob_object *blob2, struct got_object_id *id1,
7222 struct got_object_id *id2, const char *path1, const char *path2,
7223 mode_t mode1, mode_t mode2, struct got_repository *repo)
7225 struct check_path_prefix_arg *a = arg;
7227 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
7228 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
7229 return got_error(a->errcode);
7231 return NULL;
7234 static const struct got_error *
7235 check_path_prefix(struct got_object_id *parent_id,
7236 struct got_object_id *commit_id, const char *path_prefix,
7237 int errcode, struct got_repository *repo)
7239 const struct got_error *err;
7240 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7241 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7242 struct check_path_prefix_arg cpp_arg;
7244 if (got_path_is_root_dir(path_prefix))
7245 return NULL;
7247 err = got_object_open_as_commit(&commit, repo, commit_id);
7248 if (err)
7249 goto done;
7251 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7252 if (err)
7253 goto done;
7255 err = got_object_open_as_tree(&tree1, repo,
7256 got_object_commit_get_tree_id(parent_commit));
7257 if (err)
7258 goto done;
7260 err = got_object_open_as_tree(&tree2, repo,
7261 got_object_commit_get_tree_id(commit));
7262 if (err)
7263 goto done;
7265 cpp_arg.path_prefix = path_prefix;
7266 while (cpp_arg.path_prefix[0] == '/')
7267 cpp_arg.path_prefix++;
7268 cpp_arg.len = strlen(cpp_arg.path_prefix);
7269 cpp_arg.errcode = errcode;
7270 err = got_diff_tree(tree1, tree2, "", "", repo,
7271 check_path_prefix_in_diff, &cpp_arg, 0);
7272 done:
7273 if (tree1)
7274 got_object_tree_close(tree1);
7275 if (tree2)
7276 got_object_tree_close(tree2);
7277 if (commit)
7278 got_object_commit_close(commit);
7279 if (parent_commit)
7280 got_object_commit_close(parent_commit);
7281 return err;
7284 static const struct got_error *
7285 collect_commits(struct got_object_id_queue *commits,
7286 struct got_object_id *initial_commit_id,
7287 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7288 const char *path_prefix, int path_prefix_errcode,
7289 struct got_repository *repo)
7291 const struct got_error *err = NULL;
7292 struct got_commit_graph *graph = NULL;
7293 struct got_object_id *parent_id = NULL;
7294 struct got_object_qid *qid;
7295 struct got_object_id *commit_id = initial_commit_id;
7297 err = got_commit_graph_open(&graph, "/", 1);
7298 if (err)
7299 return err;
7301 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7302 check_cancelled, NULL);
7303 if (err)
7304 goto done;
7305 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7306 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7307 check_cancelled, NULL);
7308 if (err) {
7309 if (err->code == GOT_ERR_ITER_COMPLETED) {
7310 err = got_error_msg(GOT_ERR_ANCESTRY,
7311 "ran out of commits to rebase before "
7312 "youngest common ancestor commit has "
7313 "been reached?!?");
7315 goto done;
7316 } else {
7317 err = check_path_prefix(parent_id, commit_id,
7318 path_prefix, path_prefix_errcode, repo);
7319 if (err)
7320 goto done;
7322 err = got_object_qid_alloc(&qid, commit_id);
7323 if (err)
7324 goto done;
7325 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
7326 commit_id = parent_id;
7329 done:
7330 got_commit_graph_close(graph);
7331 return err;
7334 static const struct got_error *
7335 cmd_rebase(int argc, char *argv[])
7337 const struct got_error *error = NULL;
7338 struct got_worktree *worktree = NULL;
7339 struct got_repository *repo = NULL;
7340 struct got_fileindex *fileindex = NULL;
7341 char *cwd = NULL;
7342 struct got_reference *branch = NULL;
7343 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
7344 struct got_object_id *commit_id = NULL, *parent_id = NULL;
7345 struct got_object_id *resume_commit_id = NULL;
7346 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
7347 struct got_commit_object *commit = NULL;
7348 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
7349 int histedit_in_progress = 0;
7350 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7351 struct got_object_id_queue commits;
7352 struct got_pathlist_head merged_paths;
7353 const struct got_object_id_queue *parent_ids;
7354 struct got_object_qid *qid, *pid;
7356 SIMPLEQ_INIT(&commits);
7357 TAILQ_INIT(&merged_paths);
7359 while ((ch = getopt(argc, argv, "ac")) != -1) {
7360 switch (ch) {
7361 case 'a':
7362 abort_rebase = 1;
7363 break;
7364 case 'c':
7365 continue_rebase = 1;
7366 break;
7367 default:
7368 usage_rebase();
7369 /* NOTREACHED */
7373 argc -= optind;
7374 argv += optind;
7376 #ifndef PROFILE
7377 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7378 "unveil", NULL) == -1)
7379 err(1, "pledge");
7380 #endif
7381 if (abort_rebase && continue_rebase)
7382 usage_rebase();
7383 else if (abort_rebase || continue_rebase) {
7384 if (argc != 0)
7385 usage_rebase();
7386 } else if (argc != 1)
7387 usage_rebase();
7389 cwd = getcwd(NULL, 0);
7390 if (cwd == NULL) {
7391 error = got_error_from_errno("getcwd");
7392 goto done;
7394 error = got_worktree_open(&worktree, cwd);
7395 if (error) {
7396 if (error->code == GOT_ERR_NOT_WORKTREE)
7397 error = wrap_not_worktree_error(error, "rebase", cwd);
7398 goto done;
7401 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7402 NULL);
7403 if (error != NULL)
7404 goto done;
7406 error = apply_unveil(got_repo_get_path(repo), 0,
7407 got_worktree_get_root_path(worktree));
7408 if (error)
7409 goto done;
7411 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7412 worktree);
7413 if (error)
7414 goto done;
7415 if (histedit_in_progress) {
7416 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7417 goto done;
7420 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7421 if (error)
7422 goto done;
7424 if (abort_rebase) {
7425 struct got_update_progress_arg upa;
7426 if (!rebase_in_progress) {
7427 error = got_error(GOT_ERR_NOT_REBASING);
7428 goto done;
7430 error = got_worktree_rebase_continue(&resume_commit_id,
7431 &new_base_branch, &tmp_branch, &branch, &fileindex,
7432 worktree, repo);
7433 if (error)
7434 goto done;
7435 printf("Switching work tree to %s\n",
7436 got_ref_get_symref_target(new_base_branch));
7437 memset(&upa, 0, sizeof(upa));
7438 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7439 new_base_branch, update_progress, &upa);
7440 if (error)
7441 goto done;
7442 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7443 print_update_progress_stats(&upa);
7444 goto done; /* nothing else to do */
7447 if (continue_rebase) {
7448 if (!rebase_in_progress) {
7449 error = got_error(GOT_ERR_NOT_REBASING);
7450 goto done;
7452 error = got_worktree_rebase_continue(&resume_commit_id,
7453 &new_base_branch, &tmp_branch, &branch, &fileindex,
7454 worktree, repo);
7455 if (error)
7456 goto done;
7458 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7459 resume_commit_id, repo);
7460 if (error)
7461 goto done;
7463 yca_id = got_object_id_dup(resume_commit_id);
7464 if (yca_id == NULL) {
7465 error = got_error_from_errno("got_object_id_dup");
7466 goto done;
7468 } else {
7469 error = got_ref_open(&branch, repo, argv[0], 0);
7470 if (error != NULL)
7471 goto done;
7474 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7475 if (error)
7476 goto done;
7478 if (!continue_rebase) {
7479 struct got_object_id *base_commit_id;
7481 base_commit_id = got_worktree_get_base_commit_id(worktree);
7482 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7483 base_commit_id, branch_head_commit_id, repo,
7484 check_cancelled, NULL);
7485 if (error)
7486 goto done;
7487 if (yca_id == NULL) {
7488 error = got_error_msg(GOT_ERR_ANCESTRY,
7489 "specified branch shares no common ancestry "
7490 "with work tree's branch");
7491 goto done;
7494 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7495 if (error) {
7496 if (error->code != GOT_ERR_ANCESTRY)
7497 goto done;
7498 error = NULL;
7499 } else {
7500 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7501 "specified branch resolves to a commit which "
7502 "is already contained in work tree's branch");
7503 goto done;
7505 error = got_worktree_rebase_prepare(&new_base_branch,
7506 &tmp_branch, &fileindex, worktree, branch, repo);
7507 if (error)
7508 goto done;
7511 commit_id = branch_head_commit_id;
7512 error = got_object_open_as_commit(&commit, repo, commit_id);
7513 if (error)
7514 goto done;
7516 parent_ids = got_object_commit_get_parent_ids(commit);
7517 pid = SIMPLEQ_FIRST(parent_ids);
7518 if (pid == NULL) {
7519 if (!continue_rebase) {
7520 struct got_update_progress_arg upa;
7521 memset(&upa, 0, sizeof(upa));
7522 error = got_worktree_rebase_abort(worktree, fileindex,
7523 repo, new_base_branch, update_progress, &upa);
7524 if (error)
7525 goto done;
7526 printf("Rebase of %s aborted\n",
7527 got_ref_get_name(branch));
7528 print_update_progress_stats(&upa);
7531 error = got_error(GOT_ERR_EMPTY_REBASE);
7532 goto done;
7534 error = collect_commits(&commits, commit_id, pid->id,
7535 yca_id, got_worktree_get_path_prefix(worktree),
7536 GOT_ERR_REBASE_PATH, repo);
7537 got_object_commit_close(commit);
7538 commit = NULL;
7539 if (error)
7540 goto done;
7542 if (SIMPLEQ_EMPTY(&commits)) {
7543 if (continue_rebase) {
7544 error = rebase_complete(worktree, fileindex,
7545 branch, new_base_branch, tmp_branch, repo);
7546 goto done;
7547 } else {
7548 /* Fast-forward the reference of the branch. */
7549 struct got_object_id *new_head_commit_id;
7550 char *id_str;
7551 error = got_ref_resolve(&new_head_commit_id, repo,
7552 new_base_branch);
7553 if (error)
7554 goto done;
7555 error = got_object_id_str(&id_str, new_head_commit_id);
7556 printf("Forwarding %s to commit %s\n",
7557 got_ref_get_name(branch), id_str);
7558 free(id_str);
7559 error = got_ref_change_ref(branch,
7560 new_head_commit_id);
7561 if (error)
7562 goto done;
7566 pid = NULL;
7567 SIMPLEQ_FOREACH(qid, &commits, entry) {
7568 struct got_update_progress_arg upa;
7570 commit_id = qid->id;
7571 parent_id = pid ? pid->id : yca_id;
7572 pid = qid;
7574 memset(&upa, 0, sizeof(upa));
7575 error = got_worktree_rebase_merge_files(&merged_paths,
7576 worktree, fileindex, parent_id, commit_id, repo,
7577 update_progress, &upa, check_cancelled, NULL);
7578 if (error)
7579 goto done;
7581 print_update_progress_stats(&upa);
7582 if (upa.conflicts > 0)
7583 rebase_status = GOT_STATUS_CONFLICT;
7585 if (rebase_status == GOT_STATUS_CONFLICT) {
7586 error = show_rebase_merge_conflict(qid->id, repo);
7587 if (error)
7588 goto done;
7589 got_worktree_rebase_pathlist_free(&merged_paths);
7590 break;
7593 error = rebase_commit(&merged_paths, worktree, fileindex,
7594 tmp_branch, commit_id, repo);
7595 got_worktree_rebase_pathlist_free(&merged_paths);
7596 if (error)
7597 goto done;
7600 if (rebase_status == GOT_STATUS_CONFLICT) {
7601 error = got_worktree_rebase_postpone(worktree, fileindex);
7602 if (error)
7603 goto done;
7604 error = got_error_msg(GOT_ERR_CONFLICTS,
7605 "conflicts must be resolved before rebasing can continue");
7606 } else
7607 error = rebase_complete(worktree, fileindex, branch,
7608 new_base_branch, tmp_branch, repo);
7609 done:
7610 got_object_id_queue_free(&commits);
7611 free(branch_head_commit_id);
7612 free(resume_commit_id);
7613 free(yca_id);
7614 if (commit)
7615 got_object_commit_close(commit);
7616 if (branch)
7617 got_ref_close(branch);
7618 if (new_base_branch)
7619 got_ref_close(new_base_branch);
7620 if (tmp_branch)
7621 got_ref_close(tmp_branch);
7622 if (worktree)
7623 got_worktree_close(worktree);
7624 if (repo)
7625 got_repo_close(repo);
7626 return error;
7629 __dead static void
7630 usage_histedit(void)
7632 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
7633 getprogname());
7634 exit(1);
7637 #define GOT_HISTEDIT_PICK 'p'
7638 #define GOT_HISTEDIT_EDIT 'e'
7639 #define GOT_HISTEDIT_FOLD 'f'
7640 #define GOT_HISTEDIT_DROP 'd'
7641 #define GOT_HISTEDIT_MESG 'm'
7643 static struct got_histedit_cmd {
7644 unsigned char code;
7645 const char *name;
7646 const char *desc;
7647 } got_histedit_cmds[] = {
7648 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7649 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7650 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7651 "be used" },
7652 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7653 { GOT_HISTEDIT_MESG, "mesg",
7654 "single-line log message for commit above (open editor if empty)" },
7657 struct got_histedit_list_entry {
7658 TAILQ_ENTRY(got_histedit_list_entry) entry;
7659 struct got_object_id *commit_id;
7660 const struct got_histedit_cmd *cmd;
7661 char *logmsg;
7663 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7665 static const struct got_error *
7666 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7667 FILE *f, struct got_repository *repo)
7669 const struct got_error *err = NULL;
7670 char *logmsg = NULL, *id_str = NULL;
7671 struct got_commit_object *commit = NULL;
7672 int n;
7674 err = got_object_open_as_commit(&commit, repo, commit_id);
7675 if (err)
7676 goto done;
7678 err = get_short_logmsg(&logmsg, 34, commit);
7679 if (err)
7680 goto done;
7682 err = got_object_id_str(&id_str, commit_id);
7683 if (err)
7684 goto done;
7686 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7687 if (n < 0)
7688 err = got_ferror(f, GOT_ERR_IO);
7689 done:
7690 if (commit)
7691 got_object_commit_close(commit);
7692 free(id_str);
7693 free(logmsg);
7694 return err;
7697 static const struct got_error *
7698 histedit_write_commit_list(struct got_object_id_queue *commits,
7699 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7701 const struct got_error *err = NULL;
7702 struct got_object_qid *qid;
7704 if (SIMPLEQ_EMPTY(commits))
7705 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7707 SIMPLEQ_FOREACH(qid, commits, entry) {
7708 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7709 f, repo);
7710 if (err)
7711 break;
7712 if (edit_logmsg_only) {
7713 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7714 if (n < 0) {
7715 err = got_ferror(f, GOT_ERR_IO);
7716 break;
7721 return err;
7724 static const struct got_error *
7725 write_cmd_list(FILE *f, const char *branch_name,
7726 struct got_object_id_queue *commits)
7728 const struct got_error *err = NULL;
7729 int n, i;
7730 char *id_str;
7731 struct got_object_qid *qid;
7733 qid = SIMPLEQ_FIRST(commits);
7734 err = got_object_id_str(&id_str, qid->id);
7735 if (err)
7736 return err;
7738 n = fprintf(f,
7739 "# Editing the history of branch '%s' starting at\n"
7740 "# commit %s\n"
7741 "# Commits will be processed in order from top to "
7742 "bottom of this file.\n", branch_name, id_str);
7743 if (n < 0) {
7744 err = got_ferror(f, GOT_ERR_IO);
7745 goto done;
7748 n = fprintf(f, "# Available histedit commands:\n");
7749 if (n < 0) {
7750 err = got_ferror(f, GOT_ERR_IO);
7751 goto done;
7754 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7755 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7756 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7757 cmd->desc);
7758 if (n < 0) {
7759 err = got_ferror(f, GOT_ERR_IO);
7760 break;
7763 done:
7764 free(id_str);
7765 return err;
7768 static const struct got_error *
7769 histedit_syntax_error(int lineno)
7771 static char msg[42];
7772 int ret;
7774 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7775 lineno);
7776 if (ret == -1 || ret >= sizeof(msg))
7777 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7779 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7782 static const struct got_error *
7783 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7784 char *logmsg, struct got_repository *repo)
7786 const struct got_error *err;
7787 struct got_commit_object *folded_commit = NULL;
7788 char *id_str, *folded_logmsg = NULL;
7790 err = got_object_id_str(&id_str, hle->commit_id);
7791 if (err)
7792 return err;
7794 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7795 if (err)
7796 goto done;
7798 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7799 if (err)
7800 goto done;
7801 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7802 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7803 folded_logmsg) == -1) {
7804 err = got_error_from_errno("asprintf");
7806 done:
7807 if (folded_commit)
7808 got_object_commit_close(folded_commit);
7809 free(id_str);
7810 free(folded_logmsg);
7811 return err;
7814 static struct got_histedit_list_entry *
7815 get_folded_commits(struct got_histedit_list_entry *hle)
7817 struct got_histedit_list_entry *prev, *folded = NULL;
7819 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7820 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7821 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7822 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7823 folded = prev;
7824 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7827 return folded;
7830 static const struct got_error *
7831 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7832 struct got_repository *repo)
7834 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7835 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7836 const struct got_error *err = NULL;
7837 struct got_commit_object *commit = NULL;
7838 int logmsg_len;
7839 int fd;
7840 struct got_histedit_list_entry *folded = NULL;
7842 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7843 if (err)
7844 return err;
7846 folded = get_folded_commits(hle);
7847 if (folded) {
7848 while (folded != hle) {
7849 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7850 folded = TAILQ_NEXT(folded, entry);
7851 continue;
7853 err = append_folded_commit_msg(&new_msg, folded,
7854 logmsg, repo);
7855 if (err)
7856 goto done;
7857 free(logmsg);
7858 logmsg = new_msg;
7859 folded = TAILQ_NEXT(folded, entry);
7863 err = got_object_id_str(&id_str, hle->commit_id);
7864 if (err)
7865 goto done;
7866 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7867 if (err)
7868 goto done;
7869 logmsg_len = asprintf(&new_msg,
7870 "%s\n# original log message of commit %s: %s",
7871 logmsg ? logmsg : "", id_str, orig_logmsg);
7872 if (logmsg_len == -1) {
7873 err = got_error_from_errno("asprintf");
7874 goto done;
7876 free(logmsg);
7877 logmsg = new_msg;
7879 err = got_object_id_str(&id_str, hle->commit_id);
7880 if (err)
7881 goto done;
7883 err = got_opentemp_named_fd(&logmsg_path, &fd,
7884 GOT_TMPDIR_STR "/got-logmsg");
7885 if (err)
7886 goto done;
7888 write(fd, logmsg, logmsg_len);
7889 close(fd);
7891 err = get_editor(&editor);
7892 if (err)
7893 goto done;
7895 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
7896 if (err) {
7897 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
7898 goto done;
7899 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
7901 done:
7902 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
7903 err = got_error_from_errno2("unlink", logmsg_path);
7904 free(logmsg_path);
7905 free(logmsg);
7906 free(orig_logmsg);
7907 free(editor);
7908 if (commit)
7909 got_object_commit_close(commit);
7910 return err;
7913 static const struct got_error *
7914 histedit_parse_list(struct got_histedit_list *histedit_cmds,
7915 FILE *f, struct got_repository *repo)
7917 const struct got_error *err = NULL;
7918 char *line = NULL, *p, *end;
7919 size_t size;
7920 ssize_t len;
7921 int lineno = 0, i;
7922 const struct got_histedit_cmd *cmd;
7923 struct got_object_id *commit_id = NULL;
7924 struct got_histedit_list_entry *hle = NULL;
7926 for (;;) {
7927 len = getline(&line, &size, f);
7928 if (len == -1) {
7929 const struct got_error *getline_err;
7930 if (feof(f))
7931 break;
7932 getline_err = got_error_from_errno("getline");
7933 err = got_ferror(f, getline_err->code);
7934 break;
7936 lineno++;
7937 p = line;
7938 while (isspace((unsigned char)p[0]))
7939 p++;
7940 if (p[0] == '#' || p[0] == '\0') {
7941 free(line);
7942 line = NULL;
7943 continue;
7945 cmd = NULL;
7946 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7947 cmd = &got_histedit_cmds[i];
7948 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
7949 isspace((unsigned char)p[strlen(cmd->name)])) {
7950 p += strlen(cmd->name);
7951 break;
7953 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
7954 p++;
7955 break;
7958 if (i == nitems(got_histedit_cmds)) {
7959 err = histedit_syntax_error(lineno);
7960 break;
7962 while (isspace((unsigned char)p[0]))
7963 p++;
7964 if (cmd->code == GOT_HISTEDIT_MESG) {
7965 if (hle == NULL || hle->logmsg != NULL) {
7966 err = got_error(GOT_ERR_HISTEDIT_CMD);
7967 break;
7969 if (p[0] == '\0') {
7970 err = histedit_edit_logmsg(hle, repo);
7971 if (err)
7972 break;
7973 } else {
7974 hle->logmsg = strdup(p);
7975 if (hle->logmsg == NULL) {
7976 err = got_error_from_errno("strdup");
7977 break;
7980 free(line);
7981 line = NULL;
7982 continue;
7983 } else {
7984 end = p;
7985 while (end[0] && !isspace((unsigned char)end[0]))
7986 end++;
7987 *end = '\0';
7989 err = got_object_resolve_id_str(&commit_id, repo, p);
7990 if (err) {
7991 /* override error code */
7992 err = histedit_syntax_error(lineno);
7993 break;
7996 hle = malloc(sizeof(*hle));
7997 if (hle == NULL) {
7998 err = got_error_from_errno("malloc");
7999 break;
8001 hle->cmd = cmd;
8002 hle->commit_id = commit_id;
8003 hle->logmsg = NULL;
8004 commit_id = NULL;
8005 free(line);
8006 line = NULL;
8007 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
8010 free(line);
8011 free(commit_id);
8012 return err;
8015 static const struct got_error *
8016 histedit_check_script(struct got_histedit_list *histedit_cmds,
8017 struct got_object_id_queue *commits, struct got_repository *repo)
8019 const struct got_error *err = NULL;
8020 struct got_object_qid *qid;
8021 struct got_histedit_list_entry *hle;
8022 static char msg[92];
8023 char *id_str;
8025 if (TAILQ_EMPTY(histedit_cmds))
8026 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
8027 "histedit script contains no commands");
8028 if (SIMPLEQ_EMPTY(commits))
8029 return got_error(GOT_ERR_EMPTY_HISTEDIT);
8031 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8032 struct got_histedit_list_entry *hle2;
8033 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
8034 if (hle == hle2)
8035 continue;
8036 if (got_object_id_cmp(hle->commit_id,
8037 hle2->commit_id) != 0)
8038 continue;
8039 err = got_object_id_str(&id_str, hle->commit_id);
8040 if (err)
8041 return err;
8042 snprintf(msg, sizeof(msg), "commit %s is listed "
8043 "more than once in histedit script", id_str);
8044 free(id_str);
8045 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8049 SIMPLEQ_FOREACH(qid, commits, entry) {
8050 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8051 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
8052 break;
8054 if (hle == NULL) {
8055 err = got_object_id_str(&id_str, qid->id);
8056 if (err)
8057 return err;
8058 snprintf(msg, sizeof(msg),
8059 "commit %s missing from histedit script", id_str);
8060 free(id_str);
8061 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8065 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
8066 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
8067 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
8068 "last commit in histedit script cannot be folded");
8070 return NULL;
8073 static const struct got_error *
8074 histedit_run_editor(struct got_histedit_list *histedit_cmds,
8075 const char *path, struct got_object_id_queue *commits,
8076 struct got_repository *repo)
8078 const struct got_error *err = NULL;
8079 char *editor;
8080 FILE *f = NULL;
8082 err = get_editor(&editor);
8083 if (err)
8084 return err;
8086 if (spawn_editor(editor, path) == -1) {
8087 err = got_error_from_errno("failed spawning editor");
8088 goto done;
8091 f = fopen(path, "r");
8092 if (f == NULL) {
8093 err = got_error_from_errno("fopen");
8094 goto done;
8096 err = histedit_parse_list(histedit_cmds, f, repo);
8097 if (err)
8098 goto done;
8100 err = histedit_check_script(histedit_cmds, commits, repo);
8101 done:
8102 if (f && fclose(f) != 0 && err == NULL)
8103 err = got_error_from_errno("fclose");
8104 free(editor);
8105 return err;
8108 static const struct got_error *
8109 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
8110 struct got_object_id_queue *, const char *, const char *,
8111 struct got_repository *);
8113 static const struct got_error *
8114 histedit_edit_script(struct got_histedit_list *histedit_cmds,
8115 struct got_object_id_queue *commits, const char *branch_name,
8116 int edit_logmsg_only, struct got_repository *repo)
8118 const struct got_error *err;
8119 FILE *f = NULL;
8120 char *path = NULL;
8122 err = got_opentemp_named(&path, &f, "got-histedit");
8123 if (err)
8124 return err;
8126 err = write_cmd_list(f, branch_name, commits);
8127 if (err)
8128 goto done;
8130 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
8131 if (err)
8132 goto done;
8134 if (edit_logmsg_only) {
8135 rewind(f);
8136 err = histedit_parse_list(histedit_cmds, f, repo);
8137 } else {
8138 if (fclose(f) != 0) {
8139 err = got_error_from_errno("fclose");
8140 goto done;
8142 f = NULL;
8143 err = histedit_run_editor(histedit_cmds, path, commits, repo);
8144 if (err) {
8145 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8146 err->code != GOT_ERR_HISTEDIT_CMD)
8147 goto done;
8148 err = histedit_edit_list_retry(histedit_cmds, err,
8149 commits, path, branch_name, repo);
8152 done:
8153 if (f && fclose(f) != 0 && err == NULL)
8154 err = got_error_from_errno("fclose");
8155 if (path && unlink(path) != 0 && err == NULL)
8156 err = got_error_from_errno2("unlink", path);
8157 free(path);
8158 return err;
8161 static const struct got_error *
8162 histedit_save_list(struct got_histedit_list *histedit_cmds,
8163 struct got_worktree *worktree, struct got_repository *repo)
8165 const struct got_error *err = NULL;
8166 char *path = NULL;
8167 FILE *f = NULL;
8168 struct got_histedit_list_entry *hle;
8169 struct got_commit_object *commit = NULL;
8171 err = got_worktree_get_histedit_script_path(&path, worktree);
8172 if (err)
8173 return err;
8175 f = fopen(path, "w");
8176 if (f == NULL) {
8177 err = got_error_from_errno2("fopen", path);
8178 goto done;
8180 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8181 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
8182 repo);
8183 if (err)
8184 break;
8186 if (hle->logmsg) {
8187 int n = fprintf(f, "%c %s\n",
8188 GOT_HISTEDIT_MESG, hle->logmsg);
8189 if (n < 0) {
8190 err = got_ferror(f, GOT_ERR_IO);
8191 break;
8195 done:
8196 if (f && fclose(f) != 0 && err == NULL)
8197 err = got_error_from_errno("fclose");
8198 free(path);
8199 if (commit)
8200 got_object_commit_close(commit);
8201 return err;
8204 void
8205 histedit_free_list(struct got_histedit_list *histedit_cmds)
8207 struct got_histedit_list_entry *hle;
8209 while ((hle = TAILQ_FIRST(histedit_cmds))) {
8210 TAILQ_REMOVE(histedit_cmds, hle, entry);
8211 free(hle);
8215 static const struct got_error *
8216 histedit_load_list(struct got_histedit_list *histedit_cmds,
8217 const char *path, struct got_repository *repo)
8219 const struct got_error *err = NULL;
8220 FILE *f = NULL;
8222 f = fopen(path, "r");
8223 if (f == NULL) {
8224 err = got_error_from_errno2("fopen", path);
8225 goto done;
8228 err = histedit_parse_list(histedit_cmds, f, repo);
8229 done:
8230 if (f && fclose(f) != 0 && err == NULL)
8231 err = got_error_from_errno("fclose");
8232 return err;
8235 static const struct got_error *
8236 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
8237 const struct got_error *edit_err, struct got_object_id_queue *commits,
8238 const char *path, const char *branch_name, struct got_repository *repo)
8240 const struct got_error *err = NULL, *prev_err = edit_err;
8241 int resp = ' ';
8243 while (resp != 'c' && resp != 'r' && resp != 'a') {
8244 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
8245 "or (a)bort: ", getprogname(), prev_err->msg);
8246 resp = getchar();
8247 if (resp == '\n')
8248 resp = getchar();
8249 if (resp == 'c') {
8250 histedit_free_list(histedit_cmds);
8251 err = histedit_run_editor(histedit_cmds, path, commits,
8252 repo);
8253 if (err) {
8254 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8255 err->code != GOT_ERR_HISTEDIT_CMD)
8256 break;
8257 prev_err = err;
8258 resp = ' ';
8259 continue;
8261 break;
8262 } else if (resp == 'r') {
8263 histedit_free_list(histedit_cmds);
8264 err = histedit_edit_script(histedit_cmds,
8265 commits, branch_name, 0, repo);
8266 if (err) {
8267 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8268 err->code != GOT_ERR_HISTEDIT_CMD)
8269 break;
8270 prev_err = err;
8271 resp = ' ';
8272 continue;
8274 break;
8275 } else if (resp == 'a') {
8276 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
8277 break;
8278 } else
8279 printf("invalid response '%c'\n", resp);
8282 return err;
8285 static const struct got_error *
8286 histedit_complete(struct got_worktree *worktree,
8287 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
8288 struct got_reference *branch, struct got_repository *repo)
8290 printf("Switching work tree to %s\n",
8291 got_ref_get_symref_target(branch));
8292 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
8293 branch, repo);
8296 static const struct got_error *
8297 show_histedit_progress(struct got_commit_object *commit,
8298 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
8300 const struct got_error *err;
8301 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8303 err = got_object_id_str(&old_id_str, hle->commit_id);
8304 if (err)
8305 goto done;
8307 if (new_id) {
8308 err = got_object_id_str(&new_id_str, new_id);
8309 if (err)
8310 goto done;
8313 old_id_str[12] = '\0';
8314 if (new_id_str)
8315 new_id_str[12] = '\0';
8317 if (hle->logmsg) {
8318 logmsg = strdup(hle->logmsg);
8319 if (logmsg == NULL) {
8320 err = got_error_from_errno("strdup");
8321 goto done;
8323 trim_logmsg(logmsg, 42);
8324 } else {
8325 err = get_short_logmsg(&logmsg, 42, commit);
8326 if (err)
8327 goto done;
8330 switch (hle->cmd->code) {
8331 case GOT_HISTEDIT_PICK:
8332 case GOT_HISTEDIT_EDIT:
8333 printf("%s -> %s: %s\n", old_id_str,
8334 new_id_str ? new_id_str : "no-op change", logmsg);
8335 break;
8336 case GOT_HISTEDIT_DROP:
8337 case GOT_HISTEDIT_FOLD:
8338 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
8339 logmsg);
8340 break;
8341 default:
8342 break;
8344 done:
8345 free(old_id_str);
8346 free(new_id_str);
8347 return err;
8350 static const struct got_error *
8351 histedit_commit(struct got_pathlist_head *merged_paths,
8352 struct got_worktree *worktree, struct got_fileindex *fileindex,
8353 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
8354 struct got_repository *repo)
8356 const struct got_error *err;
8357 struct got_commit_object *commit;
8358 struct got_object_id *new_commit_id;
8360 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
8361 && hle->logmsg == NULL) {
8362 err = histedit_edit_logmsg(hle, repo);
8363 if (err)
8364 return err;
8367 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8368 if (err)
8369 return err;
8371 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
8372 worktree, fileindex, tmp_branch, commit, hle->commit_id,
8373 hle->logmsg, repo);
8374 if (err) {
8375 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
8376 goto done;
8377 err = show_histedit_progress(commit, hle, NULL);
8378 } else {
8379 err = show_histedit_progress(commit, hle, new_commit_id);
8380 free(new_commit_id);
8382 done:
8383 got_object_commit_close(commit);
8384 return err;
8387 static const struct got_error *
8388 histedit_skip_commit(struct got_histedit_list_entry *hle,
8389 struct got_worktree *worktree, struct got_repository *repo)
8391 const struct got_error *error;
8392 struct got_commit_object *commit;
8394 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
8395 repo);
8396 if (error)
8397 return error;
8399 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
8400 if (error)
8401 return error;
8403 error = show_histedit_progress(commit, hle, NULL);
8404 got_object_commit_close(commit);
8405 return error;
8408 static const struct got_error *
8409 check_local_changes(void *arg, unsigned char status,
8410 unsigned char staged_status, const char *path,
8411 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8412 struct got_object_id *commit_id, int dirfd, const char *de_name)
8414 int *have_local_changes = arg;
8416 switch (status) {
8417 case GOT_STATUS_ADD:
8418 case GOT_STATUS_DELETE:
8419 case GOT_STATUS_MODIFY:
8420 case GOT_STATUS_CONFLICT:
8421 *have_local_changes = 1;
8422 return got_error(GOT_ERR_CANCELLED);
8423 default:
8424 break;
8427 switch (staged_status) {
8428 case GOT_STATUS_ADD:
8429 case GOT_STATUS_DELETE:
8430 case GOT_STATUS_MODIFY:
8431 *have_local_changes = 1;
8432 return got_error(GOT_ERR_CANCELLED);
8433 default:
8434 break;
8437 return NULL;
8440 static const struct got_error *
8441 cmd_histedit(int argc, char *argv[])
8443 const struct got_error *error = NULL;
8444 struct got_worktree *worktree = NULL;
8445 struct got_fileindex *fileindex = NULL;
8446 struct got_repository *repo = NULL;
8447 char *cwd = NULL;
8448 struct got_reference *branch = NULL;
8449 struct got_reference *tmp_branch = NULL;
8450 struct got_object_id *resume_commit_id = NULL;
8451 struct got_object_id *base_commit_id = NULL;
8452 struct got_object_id *head_commit_id = NULL;
8453 struct got_commit_object *commit = NULL;
8454 int ch, rebase_in_progress = 0;
8455 struct got_update_progress_arg upa;
8456 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8457 int edit_logmsg_only = 0;
8458 const char *edit_script_path = NULL;
8459 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8460 struct got_object_id_queue commits;
8461 struct got_pathlist_head merged_paths;
8462 const struct got_object_id_queue *parent_ids;
8463 struct got_object_qid *pid;
8464 struct got_histedit_list histedit_cmds;
8465 struct got_histedit_list_entry *hle;
8467 SIMPLEQ_INIT(&commits);
8468 TAILQ_INIT(&histedit_cmds);
8469 TAILQ_INIT(&merged_paths);
8470 memset(&upa, 0, sizeof(upa));
8472 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
8473 switch (ch) {
8474 case 'a':
8475 abort_edit = 1;
8476 break;
8477 case 'c':
8478 continue_edit = 1;
8479 break;
8480 case 'F':
8481 edit_script_path = optarg;
8482 break;
8483 case 'm':
8484 edit_logmsg_only = 1;
8485 break;
8486 default:
8487 usage_histedit();
8488 /* NOTREACHED */
8492 argc -= optind;
8493 argv += optind;
8495 #ifndef PROFILE
8496 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8497 "unveil", NULL) == -1)
8498 err(1, "pledge");
8499 #endif
8500 if (abort_edit && continue_edit)
8501 errx(1, "histedit's -a and -c options are mutually exclusive");
8502 if (edit_script_path && edit_logmsg_only)
8503 errx(1, "histedit's -F and -m options are mutually exclusive");
8504 if (abort_edit && edit_logmsg_only)
8505 errx(1, "histedit's -a and -m options are mutually exclusive");
8506 if (continue_edit && edit_logmsg_only)
8507 errx(1, "histedit's -c and -m options are mutually exclusive");
8508 if (argc != 0)
8509 usage_histedit();
8512 * This command cannot apply unveil(2) in all cases because the
8513 * user may choose to run an editor to edit the histedit script
8514 * and to edit individual commit log messages.
8515 * unveil(2) traverses exec(2); if an editor is used we have to
8516 * apply unveil after edit script and log messages have been written.
8517 * XXX TODO: Make use of unveil(2) where possible.
8520 cwd = getcwd(NULL, 0);
8521 if (cwd == NULL) {
8522 error = got_error_from_errno("getcwd");
8523 goto done;
8525 error = got_worktree_open(&worktree, cwd);
8526 if (error) {
8527 if (error->code == GOT_ERR_NOT_WORKTREE)
8528 error = wrap_not_worktree_error(error, "histedit", cwd);
8529 goto done;
8532 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8533 NULL);
8534 if (error != NULL)
8535 goto done;
8537 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8538 if (error)
8539 goto done;
8540 if (rebase_in_progress) {
8541 error = got_error(GOT_ERR_REBASING);
8542 goto done;
8545 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8546 if (error)
8547 goto done;
8549 if (edit_in_progress && edit_logmsg_only) {
8550 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8551 "histedit operation is in progress in this "
8552 "work tree and must be continued or aborted "
8553 "before the -m option can be used");
8554 goto done;
8557 if (edit_in_progress && abort_edit) {
8558 error = got_worktree_histedit_continue(&resume_commit_id,
8559 &tmp_branch, &branch, &base_commit_id, &fileindex,
8560 worktree, repo);
8561 if (error)
8562 goto done;
8563 printf("Switching work tree to %s\n",
8564 got_ref_get_symref_target(branch));
8565 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8566 branch, base_commit_id, update_progress, &upa);
8567 if (error)
8568 goto done;
8569 printf("Histedit of %s aborted\n",
8570 got_ref_get_symref_target(branch));
8571 print_update_progress_stats(&upa);
8572 goto done; /* nothing else to do */
8573 } else if (abort_edit) {
8574 error = got_error(GOT_ERR_NOT_HISTEDIT);
8575 goto done;
8578 if (continue_edit) {
8579 char *path;
8581 if (!edit_in_progress) {
8582 error = got_error(GOT_ERR_NOT_HISTEDIT);
8583 goto done;
8586 error = got_worktree_get_histedit_script_path(&path, worktree);
8587 if (error)
8588 goto done;
8590 error = histedit_load_list(&histedit_cmds, path, repo);
8591 free(path);
8592 if (error)
8593 goto done;
8595 error = got_worktree_histedit_continue(&resume_commit_id,
8596 &tmp_branch, &branch, &base_commit_id, &fileindex,
8597 worktree, repo);
8598 if (error)
8599 goto done;
8601 error = got_ref_resolve(&head_commit_id, repo, branch);
8602 if (error)
8603 goto done;
8605 error = got_object_open_as_commit(&commit, repo,
8606 head_commit_id);
8607 if (error)
8608 goto done;
8609 parent_ids = got_object_commit_get_parent_ids(commit);
8610 pid = SIMPLEQ_FIRST(parent_ids);
8611 if (pid == NULL) {
8612 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8613 goto done;
8615 error = collect_commits(&commits, head_commit_id, pid->id,
8616 base_commit_id, got_worktree_get_path_prefix(worktree),
8617 GOT_ERR_HISTEDIT_PATH, repo);
8618 got_object_commit_close(commit);
8619 commit = NULL;
8620 if (error)
8621 goto done;
8622 } else {
8623 if (edit_in_progress) {
8624 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8625 goto done;
8628 error = got_ref_open(&branch, repo,
8629 got_worktree_get_head_ref_name(worktree), 0);
8630 if (error != NULL)
8631 goto done;
8633 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8634 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8635 "will not edit commit history of a branch outside "
8636 "the \"refs/heads/\" reference namespace");
8637 goto done;
8640 error = got_ref_resolve(&head_commit_id, repo, branch);
8641 got_ref_close(branch);
8642 branch = NULL;
8643 if (error)
8644 goto done;
8646 error = got_object_open_as_commit(&commit, repo,
8647 head_commit_id);
8648 if (error)
8649 goto done;
8650 parent_ids = got_object_commit_get_parent_ids(commit);
8651 pid = SIMPLEQ_FIRST(parent_ids);
8652 if (pid == NULL) {
8653 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8654 goto done;
8656 error = collect_commits(&commits, head_commit_id, pid->id,
8657 got_worktree_get_base_commit_id(worktree),
8658 got_worktree_get_path_prefix(worktree),
8659 GOT_ERR_HISTEDIT_PATH, repo);
8660 got_object_commit_close(commit);
8661 commit = NULL;
8662 if (error)
8663 goto done;
8665 if (SIMPLEQ_EMPTY(&commits)) {
8666 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8667 goto done;
8670 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8671 &base_commit_id, &fileindex, worktree, repo);
8672 if (error)
8673 goto done;
8675 if (edit_script_path) {
8676 error = histedit_load_list(&histedit_cmds,
8677 edit_script_path, repo);
8678 if (error) {
8679 got_worktree_histedit_abort(worktree, fileindex,
8680 repo, branch, base_commit_id,
8681 update_progress, &upa);
8682 print_update_progress_stats(&upa);
8683 goto done;
8685 } else {
8686 const char *branch_name;
8687 branch_name = got_ref_get_symref_target(branch);
8688 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8689 branch_name += 11;
8690 error = histedit_edit_script(&histedit_cmds, &commits,
8691 branch_name, edit_logmsg_only, repo);
8692 if (error) {
8693 got_worktree_histedit_abort(worktree, fileindex,
8694 repo, branch, base_commit_id,
8695 update_progress, &upa);
8696 print_update_progress_stats(&upa);
8697 goto done;
8702 error = histedit_save_list(&histedit_cmds, worktree,
8703 repo);
8704 if (error) {
8705 got_worktree_histedit_abort(worktree, fileindex,
8706 repo, branch, base_commit_id,
8707 update_progress, &upa);
8708 print_update_progress_stats(&upa);
8709 goto done;
8714 error = histedit_check_script(&histedit_cmds, &commits, repo);
8715 if (error)
8716 goto done;
8718 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8719 if (resume_commit_id) {
8720 if (got_object_id_cmp(hle->commit_id,
8721 resume_commit_id) != 0)
8722 continue;
8724 resume_commit_id = NULL;
8725 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8726 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8727 error = histedit_skip_commit(hle, worktree,
8728 repo);
8729 if (error)
8730 goto done;
8731 } else {
8732 struct got_pathlist_head paths;
8733 int have_changes = 0;
8735 TAILQ_INIT(&paths);
8736 error = got_pathlist_append(&paths, "", NULL);
8737 if (error)
8738 goto done;
8739 error = got_worktree_status(worktree, &paths,
8740 repo, check_local_changes, &have_changes,
8741 check_cancelled, NULL);
8742 got_pathlist_free(&paths);
8743 if (error) {
8744 if (error->code != GOT_ERR_CANCELLED)
8745 goto done;
8746 if (sigint_received || sigpipe_received)
8747 goto done;
8749 if (have_changes) {
8750 error = histedit_commit(NULL, worktree,
8751 fileindex, tmp_branch, hle, repo);
8752 if (error)
8753 goto done;
8754 } else {
8755 error = got_object_open_as_commit(
8756 &commit, repo, hle->commit_id);
8757 if (error)
8758 goto done;
8759 error = show_histedit_progress(commit,
8760 hle, NULL);
8761 got_object_commit_close(commit);
8762 commit = NULL;
8763 if (error)
8764 goto done;
8767 continue;
8770 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8771 error = histedit_skip_commit(hle, worktree, repo);
8772 if (error)
8773 goto done;
8774 continue;
8777 error = got_object_open_as_commit(&commit, repo,
8778 hle->commit_id);
8779 if (error)
8780 goto done;
8781 parent_ids = got_object_commit_get_parent_ids(commit);
8782 pid = SIMPLEQ_FIRST(parent_ids);
8784 error = got_worktree_histedit_merge_files(&merged_paths,
8785 worktree, fileindex, pid->id, hle->commit_id, repo,
8786 update_progress, &upa, check_cancelled, NULL);
8787 if (error)
8788 goto done;
8789 got_object_commit_close(commit);
8790 commit = NULL;
8792 print_update_progress_stats(&upa);
8793 if (upa.conflicts > 0)
8794 rebase_status = GOT_STATUS_CONFLICT;
8796 if (rebase_status == GOT_STATUS_CONFLICT) {
8797 error = show_rebase_merge_conflict(hle->commit_id,
8798 repo);
8799 if (error)
8800 goto done;
8801 got_worktree_rebase_pathlist_free(&merged_paths);
8802 break;
8805 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8806 char *id_str;
8807 error = got_object_id_str(&id_str, hle->commit_id);
8808 if (error)
8809 goto done;
8810 printf("Stopping histedit for amending commit %s\n",
8811 id_str);
8812 free(id_str);
8813 got_worktree_rebase_pathlist_free(&merged_paths);
8814 error = got_worktree_histedit_postpone(worktree,
8815 fileindex);
8816 goto done;
8819 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8820 error = histedit_skip_commit(hle, worktree, repo);
8821 if (error)
8822 goto done;
8823 continue;
8826 error = histedit_commit(&merged_paths, worktree, fileindex,
8827 tmp_branch, hle, repo);
8828 got_worktree_rebase_pathlist_free(&merged_paths);
8829 if (error)
8830 goto done;
8833 if (rebase_status == GOT_STATUS_CONFLICT) {
8834 error = got_worktree_histedit_postpone(worktree, fileindex);
8835 if (error)
8836 goto done;
8837 error = got_error_msg(GOT_ERR_CONFLICTS,
8838 "conflicts must be resolved before histedit can continue");
8839 } else
8840 error = histedit_complete(worktree, fileindex, tmp_branch,
8841 branch, repo);
8842 done:
8843 got_object_id_queue_free(&commits);
8844 histedit_free_list(&histedit_cmds);
8845 free(head_commit_id);
8846 free(base_commit_id);
8847 free(resume_commit_id);
8848 if (commit)
8849 got_object_commit_close(commit);
8850 if (branch)
8851 got_ref_close(branch);
8852 if (tmp_branch)
8853 got_ref_close(tmp_branch);
8854 if (worktree)
8855 got_worktree_close(worktree);
8856 if (repo)
8857 got_repo_close(repo);
8858 return error;
8861 __dead static void
8862 usage_integrate(void)
8864 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
8865 exit(1);
8868 static const struct got_error *
8869 cmd_integrate(int argc, char *argv[])
8871 const struct got_error *error = NULL;
8872 struct got_repository *repo = NULL;
8873 struct got_worktree *worktree = NULL;
8874 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
8875 const char *branch_arg = NULL;
8876 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
8877 struct got_fileindex *fileindex = NULL;
8878 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
8879 int ch;
8880 struct got_update_progress_arg upa;
8882 while ((ch = getopt(argc, argv, "")) != -1) {
8883 switch (ch) {
8884 default:
8885 usage_integrate();
8886 /* NOTREACHED */
8890 argc -= optind;
8891 argv += optind;
8893 if (argc != 1)
8894 usage_integrate();
8895 branch_arg = argv[0];
8897 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8898 "unveil", NULL) == -1)
8899 err(1, "pledge");
8901 cwd = getcwd(NULL, 0);
8902 if (cwd == NULL) {
8903 error = got_error_from_errno("getcwd");
8904 goto done;
8907 error = got_worktree_open(&worktree, cwd);
8908 if (error) {
8909 if (error->code == GOT_ERR_NOT_WORKTREE)
8910 error = wrap_not_worktree_error(error, "integrate",
8911 cwd);
8912 goto done;
8915 error = check_rebase_or_histedit_in_progress(worktree);
8916 if (error)
8917 goto done;
8919 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8920 NULL);
8921 if (error != NULL)
8922 goto done;
8924 error = apply_unveil(got_repo_get_path(repo), 0,
8925 got_worktree_get_root_path(worktree));
8926 if (error)
8927 goto done;
8929 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
8930 error = got_error_from_errno("asprintf");
8931 goto done;
8934 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
8935 &base_branch_ref, worktree, refname, repo);
8936 if (error)
8937 goto done;
8939 refname = strdup(got_ref_get_name(branch_ref));
8940 if (refname == NULL) {
8941 error = got_error_from_errno("strdup");
8942 got_worktree_integrate_abort(worktree, fileindex, repo,
8943 branch_ref, base_branch_ref);
8944 goto done;
8946 base_refname = strdup(got_ref_get_name(base_branch_ref));
8947 if (base_refname == NULL) {
8948 error = got_error_from_errno("strdup");
8949 got_worktree_integrate_abort(worktree, fileindex, repo,
8950 branch_ref, base_branch_ref);
8951 goto done;
8954 error = got_ref_resolve(&commit_id, repo, branch_ref);
8955 if (error)
8956 goto done;
8958 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
8959 if (error)
8960 goto done;
8962 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
8963 error = got_error_msg(GOT_ERR_SAME_BRANCH,
8964 "specified branch has already been integrated");
8965 got_worktree_integrate_abort(worktree, fileindex, repo,
8966 branch_ref, base_branch_ref);
8967 goto done;
8970 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
8971 if (error) {
8972 if (error->code == GOT_ERR_ANCESTRY)
8973 error = got_error(GOT_ERR_REBASE_REQUIRED);
8974 got_worktree_integrate_abort(worktree, fileindex, repo,
8975 branch_ref, base_branch_ref);
8976 goto done;
8979 memset(&upa, 0, sizeof(upa));
8980 error = got_worktree_integrate_continue(worktree, fileindex, repo,
8981 branch_ref, base_branch_ref, update_progress, &upa,
8982 check_cancelled, NULL);
8983 if (error)
8984 goto done;
8986 printf("Integrated %s into %s\n", refname, base_refname);
8987 print_update_progress_stats(&upa);
8988 done:
8989 if (repo)
8990 got_repo_close(repo);
8991 if (worktree)
8992 got_worktree_close(worktree);
8993 free(cwd);
8994 free(base_commit_id);
8995 free(commit_id);
8996 free(refname);
8997 free(base_refname);
8998 return error;
9001 __dead static void
9002 usage_stage(void)
9004 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
9005 "[-S] [file-path ...]\n",
9006 getprogname());
9007 exit(1);
9010 static const struct got_error *
9011 print_stage(void *arg, unsigned char status, unsigned char staged_status,
9012 const char *path, struct got_object_id *blob_id,
9013 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
9014 int dirfd, const char *de_name)
9016 const struct got_error *err = NULL;
9017 char *id_str = NULL;
9019 if (staged_status != GOT_STATUS_ADD &&
9020 staged_status != GOT_STATUS_MODIFY &&
9021 staged_status != GOT_STATUS_DELETE)
9022 return NULL;
9024 if (staged_status == GOT_STATUS_ADD ||
9025 staged_status == GOT_STATUS_MODIFY)
9026 err = got_object_id_str(&id_str, staged_blob_id);
9027 else
9028 err = got_object_id_str(&id_str, blob_id);
9029 if (err)
9030 return err;
9032 printf("%s %c %s\n", id_str, staged_status, path);
9033 free(id_str);
9034 return NULL;
9037 static const struct got_error *
9038 cmd_stage(int argc, char *argv[])
9040 const struct got_error *error = NULL;
9041 struct got_repository *repo = NULL;
9042 struct got_worktree *worktree = NULL;
9043 char *cwd = NULL;
9044 struct got_pathlist_head paths;
9045 struct got_pathlist_entry *pe;
9046 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
9047 FILE *patch_script_file = NULL;
9048 const char *patch_script_path = NULL;
9049 struct choose_patch_arg cpa;
9051 TAILQ_INIT(&paths);
9053 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
9054 switch (ch) {
9055 case 'l':
9056 list_stage = 1;
9057 break;
9058 case 'p':
9059 pflag = 1;
9060 break;
9061 case 'F':
9062 patch_script_path = optarg;
9063 break;
9064 case 'S':
9065 allow_bad_symlinks = 1;
9066 break;
9067 default:
9068 usage_stage();
9069 /* NOTREACHED */
9073 argc -= optind;
9074 argv += optind;
9076 #ifndef PROFILE
9077 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9078 "unveil", NULL) == -1)
9079 err(1, "pledge");
9080 #endif
9081 if (list_stage && (pflag || patch_script_path))
9082 errx(1, "-l option cannot be used with other options");
9083 if (patch_script_path && !pflag)
9084 errx(1, "-F option can only be used together with -p option");
9086 cwd = getcwd(NULL, 0);
9087 if (cwd == NULL) {
9088 error = got_error_from_errno("getcwd");
9089 goto done;
9092 error = got_worktree_open(&worktree, cwd);
9093 if (error) {
9094 if (error->code == GOT_ERR_NOT_WORKTREE)
9095 error = wrap_not_worktree_error(error, "stage", cwd);
9096 goto done;
9099 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9100 NULL);
9101 if (error != NULL)
9102 goto done;
9104 if (patch_script_path) {
9105 patch_script_file = fopen(patch_script_path, "r");
9106 if (patch_script_file == NULL) {
9107 error = got_error_from_errno2("fopen",
9108 patch_script_path);
9109 goto done;
9112 error = apply_unveil(got_repo_get_path(repo), 0,
9113 got_worktree_get_root_path(worktree));
9114 if (error)
9115 goto done;
9117 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9118 if (error)
9119 goto done;
9121 if (list_stage)
9122 error = got_worktree_status(worktree, &paths, repo,
9123 print_stage, NULL, check_cancelled, NULL);
9124 else {
9125 cpa.patch_script_file = patch_script_file;
9126 cpa.action = "stage";
9127 error = got_worktree_stage(worktree, &paths,
9128 pflag ? NULL : print_status, NULL,
9129 pflag ? choose_patch : NULL, &cpa,
9130 allow_bad_symlinks, repo);
9132 done:
9133 if (patch_script_file && fclose(patch_script_file) == EOF &&
9134 error == NULL)
9135 error = got_error_from_errno2("fclose", patch_script_path);
9136 if (repo)
9137 got_repo_close(repo);
9138 if (worktree)
9139 got_worktree_close(worktree);
9140 TAILQ_FOREACH(pe, &paths, entry)
9141 free((char *)pe->path);
9142 got_pathlist_free(&paths);
9143 free(cwd);
9144 return error;
9147 __dead static void
9148 usage_unstage(void)
9150 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
9151 "[file-path ...]\n",
9152 getprogname());
9153 exit(1);
9157 static const struct got_error *
9158 cmd_unstage(int argc, char *argv[])
9160 const struct got_error *error = NULL;
9161 struct got_repository *repo = NULL;
9162 struct got_worktree *worktree = NULL;
9163 char *cwd = NULL;
9164 struct got_pathlist_head paths;
9165 struct got_pathlist_entry *pe;
9166 int ch, pflag = 0;
9167 struct got_update_progress_arg upa;
9168 FILE *patch_script_file = NULL;
9169 const char *patch_script_path = NULL;
9170 struct choose_patch_arg cpa;
9172 TAILQ_INIT(&paths);
9174 while ((ch = getopt(argc, argv, "pF:")) != -1) {
9175 switch (ch) {
9176 case 'p':
9177 pflag = 1;
9178 break;
9179 case 'F':
9180 patch_script_path = optarg;
9181 break;
9182 default:
9183 usage_unstage();
9184 /* NOTREACHED */
9188 argc -= optind;
9189 argv += optind;
9191 #ifndef PROFILE
9192 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9193 "unveil", NULL) == -1)
9194 err(1, "pledge");
9195 #endif
9196 if (patch_script_path && !pflag)
9197 errx(1, "-F option can only be used together with -p option");
9199 cwd = getcwd(NULL, 0);
9200 if (cwd == NULL) {
9201 error = got_error_from_errno("getcwd");
9202 goto done;
9205 error = got_worktree_open(&worktree, cwd);
9206 if (error) {
9207 if (error->code == GOT_ERR_NOT_WORKTREE)
9208 error = wrap_not_worktree_error(error, "unstage", cwd);
9209 goto done;
9212 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9213 NULL);
9214 if (error != NULL)
9215 goto done;
9217 if (patch_script_path) {
9218 patch_script_file = fopen(patch_script_path, "r");
9219 if (patch_script_file == NULL) {
9220 error = got_error_from_errno2("fopen",
9221 patch_script_path);
9222 goto done;
9226 error = apply_unveil(got_repo_get_path(repo), 0,
9227 got_worktree_get_root_path(worktree));
9228 if (error)
9229 goto done;
9231 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9232 if (error)
9233 goto done;
9235 cpa.patch_script_file = patch_script_file;
9236 cpa.action = "unstage";
9237 memset(&upa, 0, sizeof(upa));
9238 error = got_worktree_unstage(worktree, &paths, update_progress,
9239 &upa, pflag ? choose_patch : NULL, &cpa, repo);
9240 if (!error)
9241 print_update_progress_stats(&upa);
9242 done:
9243 if (patch_script_file && fclose(patch_script_file) == EOF &&
9244 error == NULL)
9245 error = got_error_from_errno2("fclose", patch_script_path);
9246 if (repo)
9247 got_repo_close(repo);
9248 if (worktree)
9249 got_worktree_close(worktree);
9250 TAILQ_FOREACH(pe, &paths, entry)
9251 free((char *)pe->path);
9252 got_pathlist_free(&paths);
9253 free(cwd);
9254 return error;
9257 __dead static void
9258 usage_cat(void)
9260 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
9261 "arg1 [arg2 ...]\n", getprogname());
9262 exit(1);
9265 static const struct got_error *
9266 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9268 const struct got_error *err;
9269 struct got_blob_object *blob;
9271 err = got_object_open_as_blob(&blob, repo, id, 8192);
9272 if (err)
9273 return err;
9275 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
9276 got_object_blob_close(blob);
9277 return err;
9280 static const struct got_error *
9281 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9283 const struct got_error *err;
9284 struct got_tree_object *tree;
9285 int nentries, i;
9287 err = got_object_open_as_tree(&tree, repo, id);
9288 if (err)
9289 return err;
9291 nentries = got_object_tree_get_nentries(tree);
9292 for (i = 0; i < nentries; i++) {
9293 struct got_tree_entry *te;
9294 char *id_str;
9295 if (sigint_received || sigpipe_received)
9296 break;
9297 te = got_object_tree_get_entry(tree, i);
9298 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
9299 if (err)
9300 break;
9301 fprintf(outfile, "%s %.7o %s\n", id_str,
9302 got_tree_entry_get_mode(te),
9303 got_tree_entry_get_name(te));
9304 free(id_str);
9307 got_object_tree_close(tree);
9308 return err;
9311 static const struct got_error *
9312 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9314 const struct got_error *err;
9315 struct got_commit_object *commit;
9316 const struct got_object_id_queue *parent_ids;
9317 struct got_object_qid *pid;
9318 char *id_str = NULL;
9319 const char *logmsg = NULL;
9321 err = got_object_open_as_commit(&commit, repo, id);
9322 if (err)
9323 return err;
9325 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
9326 if (err)
9327 goto done;
9329 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
9330 parent_ids = got_object_commit_get_parent_ids(commit);
9331 fprintf(outfile, "numparents %d\n",
9332 got_object_commit_get_nparents(commit));
9333 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
9334 char *pid_str;
9335 err = got_object_id_str(&pid_str, pid->id);
9336 if (err)
9337 goto done;
9338 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
9339 free(pid_str);
9341 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
9342 got_object_commit_get_author(commit),
9343 got_object_commit_get_author_time(commit));
9345 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
9346 got_object_commit_get_author(commit),
9347 got_object_commit_get_committer_time(commit));
9349 logmsg = got_object_commit_get_logmsg_raw(commit);
9350 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
9351 fprintf(outfile, "%s", logmsg);
9352 done:
9353 free(id_str);
9354 got_object_commit_close(commit);
9355 return err;
9358 static const struct got_error *
9359 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9361 const struct got_error *err;
9362 struct got_tag_object *tag;
9363 char *id_str = NULL;
9364 const char *tagmsg = NULL;
9366 err = got_object_open_as_tag(&tag, repo, id);
9367 if (err)
9368 return err;
9370 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
9371 if (err)
9372 goto done;
9374 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
9376 switch (got_object_tag_get_object_type(tag)) {
9377 case GOT_OBJ_TYPE_BLOB:
9378 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9379 GOT_OBJ_LABEL_BLOB);
9380 break;
9381 case GOT_OBJ_TYPE_TREE:
9382 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9383 GOT_OBJ_LABEL_TREE);
9384 break;
9385 case GOT_OBJ_TYPE_COMMIT:
9386 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9387 GOT_OBJ_LABEL_COMMIT);
9388 break;
9389 case GOT_OBJ_TYPE_TAG:
9390 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9391 GOT_OBJ_LABEL_TAG);
9392 break;
9393 default:
9394 break;
9397 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
9398 got_object_tag_get_name(tag));
9400 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
9401 got_object_tag_get_tagger(tag),
9402 got_object_tag_get_tagger_time(tag));
9404 tagmsg = got_object_tag_get_message(tag);
9405 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
9406 fprintf(outfile, "%s", tagmsg);
9407 done:
9408 free(id_str);
9409 got_object_tag_close(tag);
9410 return err;
9413 static const struct got_error *
9414 cmd_cat(int argc, char *argv[])
9416 const struct got_error *error;
9417 struct got_repository *repo = NULL;
9418 struct got_worktree *worktree = NULL;
9419 char *cwd = NULL, *repo_path = NULL, *label = NULL;
9420 const char *commit_id_str = NULL;
9421 struct got_object_id *id = NULL, *commit_id = NULL;
9422 int ch, obj_type, i, force_path = 0;
9424 #ifndef PROFILE
9425 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9426 NULL) == -1)
9427 err(1, "pledge");
9428 #endif
9430 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
9431 switch (ch) {
9432 case 'c':
9433 commit_id_str = optarg;
9434 break;
9435 case 'r':
9436 repo_path = realpath(optarg, NULL);
9437 if (repo_path == NULL)
9438 return got_error_from_errno2("realpath",
9439 optarg);
9440 got_path_strip_trailing_slashes(repo_path);
9441 break;
9442 case 'P':
9443 force_path = 1;
9444 break;
9445 default:
9446 usage_cat();
9447 /* NOTREACHED */
9451 argc -= optind;
9452 argv += optind;
9454 cwd = getcwd(NULL, 0);
9455 if (cwd == NULL) {
9456 error = got_error_from_errno("getcwd");
9457 goto done;
9459 error = got_worktree_open(&worktree, cwd);
9460 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9461 goto done;
9462 if (worktree) {
9463 if (repo_path == NULL) {
9464 repo_path = strdup(
9465 got_worktree_get_repo_path(worktree));
9466 if (repo_path == NULL) {
9467 error = got_error_from_errno("strdup");
9468 goto done;
9473 if (repo_path == NULL) {
9474 repo_path = getcwd(NULL, 0);
9475 if (repo_path == NULL)
9476 return got_error_from_errno("getcwd");
9479 error = got_repo_open(&repo, repo_path, NULL);
9480 free(repo_path);
9481 if (error != NULL)
9482 goto done;
9484 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9485 if (error)
9486 goto done;
9488 if (commit_id_str == NULL)
9489 commit_id_str = GOT_REF_HEAD;
9490 error = got_repo_match_object_id(&commit_id, NULL,
9491 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
9492 if (error)
9493 goto done;
9495 for (i = 0; i < argc; i++) {
9496 if (force_path) {
9497 error = got_object_id_by_path(&id, repo, commit_id,
9498 argv[i]);
9499 if (error)
9500 break;
9501 } else {
9502 error = got_repo_match_object_id(&id, &label, argv[i],
9503 GOT_OBJ_TYPE_ANY, 0, repo);
9504 if (error) {
9505 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9506 error->code != GOT_ERR_NOT_REF)
9507 break;
9508 error = got_object_id_by_path(&id, repo,
9509 commit_id, argv[i]);
9510 if (error)
9511 break;
9515 error = got_object_get_type(&obj_type, repo, id);
9516 if (error)
9517 break;
9519 switch (obj_type) {
9520 case GOT_OBJ_TYPE_BLOB:
9521 error = cat_blob(id, repo, stdout);
9522 break;
9523 case GOT_OBJ_TYPE_TREE:
9524 error = cat_tree(id, repo, stdout);
9525 break;
9526 case GOT_OBJ_TYPE_COMMIT:
9527 error = cat_commit(id, repo, stdout);
9528 break;
9529 case GOT_OBJ_TYPE_TAG:
9530 error = cat_tag(id, repo, stdout);
9531 break;
9532 default:
9533 error = got_error(GOT_ERR_OBJ_TYPE);
9534 break;
9536 if (error)
9537 break;
9538 free(label);
9539 label = NULL;
9540 free(id);
9541 id = NULL;
9543 done:
9544 free(label);
9545 free(id);
9546 free(commit_id);
9547 if (worktree)
9548 got_worktree_close(worktree);
9549 if (repo) {
9550 const struct got_error *repo_error;
9551 repo_error = got_repo_close(repo);
9552 if (error == NULL)
9553 error = repo_error;
9555 return error;
9558 __dead static void
9559 usage_info(void)
9561 fprintf(stderr, "usage: %s info [path ...]\n",
9562 getprogname());
9563 exit(1);
9566 static const struct got_error *
9567 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
9568 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9569 struct got_object_id *commit_id)
9571 const struct got_error *err = NULL;
9572 char *id_str = NULL;
9573 char datebuf[128];
9574 struct tm mytm, *tm;
9575 struct got_pathlist_head *paths = arg;
9576 struct got_pathlist_entry *pe;
9579 * Clear error indication from any of the path arguments which
9580 * would cause this file index entry to be displayed.
9582 TAILQ_FOREACH(pe, paths, entry) {
9583 if (got_path_cmp(path, pe->path, strlen(path),
9584 pe->path_len) == 0 ||
9585 got_path_is_child(path, pe->path, pe->path_len))
9586 pe->data = NULL; /* no error */
9589 printf(GOT_COMMIT_SEP_STR);
9590 if (S_ISLNK(mode))
9591 printf("symlink: %s\n", path);
9592 else if (S_ISREG(mode)) {
9593 printf("file: %s\n", path);
9594 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
9595 } else if (S_ISDIR(mode))
9596 printf("directory: %s\n", path);
9597 else
9598 printf("something: %s\n", path);
9600 tm = localtime_r(&mtime, &mytm);
9601 if (tm == NULL)
9602 return NULL;
9603 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) >= sizeof(datebuf))
9604 return got_error(GOT_ERR_NO_SPACE);
9605 printf("timestamp: %s\n", datebuf);
9607 if (blob_id) {
9608 err = got_object_id_str(&id_str, blob_id);
9609 if (err)
9610 return err;
9611 printf("based on blob: %s\n", id_str);
9612 free(id_str);
9615 if (staged_blob_id) {
9616 err = got_object_id_str(&id_str, staged_blob_id);
9617 if (err)
9618 return err;
9619 printf("based on staged blob: %s\n", id_str);
9620 free(id_str);
9623 if (commit_id) {
9624 err = got_object_id_str(&id_str, commit_id);
9625 if (err)
9626 return err;
9627 printf("based on commit: %s\n", id_str);
9628 free(id_str);
9631 return NULL;
9634 static const struct got_error *
9635 cmd_info(int argc, char *argv[])
9637 const struct got_error *error = NULL;
9638 struct got_worktree *worktree = NULL;
9639 char *cwd = NULL, *id_str = NULL;
9640 struct got_pathlist_head paths;
9641 struct got_pathlist_entry *pe;
9642 char *uuidstr = NULL;
9643 int ch, show_files = 0;
9645 TAILQ_INIT(&paths);
9647 while ((ch = getopt(argc, argv, "")) != -1) {
9648 switch (ch) {
9649 default:
9650 usage_info();
9651 /* NOTREACHED */
9655 argc -= optind;
9656 argv += optind;
9658 #ifndef PROFILE
9659 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
9660 NULL) == -1)
9661 err(1, "pledge");
9662 #endif
9663 cwd = getcwd(NULL, 0);
9664 if (cwd == NULL) {
9665 error = got_error_from_errno("getcwd");
9666 goto done;
9669 error = got_worktree_open(&worktree, cwd);
9670 if (error) {
9671 if (error->code == GOT_ERR_NOT_WORKTREE)
9672 error = wrap_not_worktree_error(error, "status", cwd);
9673 goto done;
9676 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9677 if (error)
9678 goto done;
9680 if (argc >= 1) {
9681 error = get_worktree_paths_from_argv(&paths, argc, argv,
9682 worktree);
9683 if (error)
9684 goto done;
9685 show_files = 1;
9688 error = got_object_id_str(&id_str,
9689 got_worktree_get_base_commit_id(worktree));
9690 if (error)
9691 goto done;
9693 error = got_worktree_get_uuid(&uuidstr, worktree);
9694 if (error)
9695 goto done;
9697 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9698 printf("work tree base commit: %s\n", id_str);
9699 printf("work tree path prefix: %s\n",
9700 got_worktree_get_path_prefix(worktree));
9701 printf("work tree branch reference: %s\n",
9702 got_worktree_get_head_ref_name(worktree));
9703 printf("work tree UUID: %s\n", uuidstr);
9704 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
9706 if (show_files) {
9707 struct got_pathlist_entry *pe;
9708 TAILQ_FOREACH(pe, &paths, entry) {
9709 if (pe->path_len == 0)
9710 continue;
9712 * Assume this path will fail. This will be corrected
9713 * in print_path_info() in case the path does suceeed.
9715 pe->data = (void *)got_error_path(pe->path,
9716 GOT_ERR_BAD_PATH);
9718 error = got_worktree_path_info(worktree, &paths,
9719 print_path_info, &paths, check_cancelled, NULL);
9720 if (error)
9721 goto done;
9722 TAILQ_FOREACH(pe, &paths, entry) {
9723 if (pe->data != NULL) {
9724 error = pe->data; /* bad path */
9725 break;
9729 done:
9730 TAILQ_FOREACH(pe, &paths, entry)
9731 free((char *)pe->path);
9732 got_pathlist_free(&paths);
9733 free(cwd);
9734 free(id_str);
9735 free(uuidstr);
9736 return error;