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(const char *refname, struct got_reference *target_ref,
927 int verbosity, struct got_repository *repo)
929 const struct got_error *err;
930 struct got_reference *head_symref;
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 got_ref_close(head_symref);
938 if (err == NULL && verbosity > 0) {
939 printf("Created reference %s: %s\n", GOT_REF_HEAD,
940 got_ref_get_name(target_ref));
942 return err;
945 static const struct got_error *
946 list_remote_refs(struct got_pathlist_head *symrefs,
947 struct got_pathlist_head *refs)
949 const struct got_error *err;
950 struct got_pathlist_entry *pe;
952 TAILQ_FOREACH(pe, symrefs, entry) {
953 const char *refname = pe->path;
954 const char *targetref = pe->data;
956 printf("%s: %s\n", refname, targetref);
959 TAILQ_FOREACH(pe, refs, entry) {
960 const char *refname = pe->path;
961 struct got_object_id *id = pe->data;
962 char *id_str;
964 err = got_object_id_str(&id_str, id);
965 if (err)
966 return err;
967 printf("%s: %s\n", refname, id_str);
968 free(id_str);
971 return NULL;
974 static const struct got_error *
975 create_ref(const char *refname, struct got_object_id *id,
976 int verbosity, struct got_repository *repo)
978 const struct got_error *err = NULL;
979 struct got_reference *ref;
980 char *id_str;
982 err = got_object_id_str(&id_str, id);
983 if (err)
984 return err;
986 err = got_ref_alloc(&ref, refname, id);
987 if (err)
988 goto done;
990 err = got_ref_write(ref, repo);
991 got_ref_close(ref);
993 if (err == NULL && verbosity >= 0)
994 printf("Created reference %s: %s\n", refname, id_str);
995 done:
996 free(id_str);
997 return err;
1000 static int
1001 match_wanted_ref(const char *refname, const char *wanted_ref)
1003 if (strncmp(refname, "refs/", 5) != 0)
1004 return 0;
1005 refname += 5;
1008 * Prevent fetching of references that won't make any
1009 * sense outside of the remote repository's context.
1011 if (strncmp(refname, "got/", 4) == 0)
1012 return 0;
1013 if (strncmp(refname, "remotes/", 8) == 0)
1014 return 0;
1016 if (strncmp(wanted_ref, "refs/", 5) == 0)
1017 wanted_ref += 5;
1019 /* Allow prefix match. */
1020 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1021 return 1;
1023 /* Allow exact match. */
1024 return (strcmp(refname, wanted_ref) == 0);
1027 static int
1028 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1030 struct got_pathlist_entry *pe;
1032 TAILQ_FOREACH(pe, wanted_refs, entry) {
1033 if (match_wanted_ref(refname, pe->path))
1034 return 1;
1037 return 0;
1040 static const struct got_error *
1041 create_wanted_ref(const char *refname, struct got_object_id *id,
1042 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1044 const struct got_error *err;
1045 char *remote_refname;
1047 if (strncmp("refs/", refname, 5) == 0)
1048 refname += 5;
1050 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1051 remote_repo_name, refname) == -1)
1052 return got_error_from_errno("asprintf");
1054 err = create_ref(remote_refname, id, verbosity, repo);
1055 free(remote_refname);
1056 return err;
1059 static const struct got_error *
1060 cmd_clone(int argc, char *argv[])
1062 const struct got_error *error = NULL;
1063 const char *uri, *dirname;
1064 char *proto, *host, *port, *repo_name, *server_path;
1065 char *default_destdir = NULL, *id_str = NULL;
1066 const char *repo_path, *remote_repo_path;
1067 struct got_repository *repo = NULL;
1068 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1069 struct got_pathlist_entry *pe;
1070 struct got_object_id *pack_hash = NULL;
1071 int ch, fetchfd = -1, fetchstatus;
1072 pid_t fetchpid = -1;
1073 struct got_fetch_progress_arg fpa;
1074 char *git_url = NULL;
1075 char *gitconfig_path = NULL, *gotconfig_path = NULL;
1076 char *gitconfig = NULL, *gotconfig = NULL;
1077 FILE *gitconfig_file = NULL, *gotconfig_file = NULL;
1078 ssize_t n;
1079 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1080 int list_refs_only = 0;
1081 struct got_reference *head_symref = NULL;
1083 TAILQ_INIT(&refs);
1084 TAILQ_INIT(&symrefs);
1085 TAILQ_INIT(&wanted_branches);
1086 TAILQ_INIT(&wanted_refs);
1088 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1089 switch (ch) {
1090 case 'a':
1091 fetch_all_branches = 1;
1092 break;
1093 case 'b':
1094 error = got_pathlist_append(&wanted_branches,
1095 optarg, NULL);
1096 if (error)
1097 return error;
1098 break;
1099 case 'l':
1100 list_refs_only = 1;
1101 break;
1102 case 'm':
1103 mirror_references = 1;
1104 break;
1105 case 'v':
1106 if (verbosity < 0)
1107 verbosity = 0;
1108 else if (verbosity < 3)
1109 verbosity++;
1110 break;
1111 case 'q':
1112 verbosity = -1;
1113 break;
1114 case 'R':
1115 error = got_pathlist_append(&wanted_refs,
1116 optarg, NULL);
1117 if (error)
1118 return error;
1119 break;
1120 default:
1121 usage_clone();
1122 break;
1125 argc -= optind;
1126 argv += optind;
1128 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1129 errx(1, "-a and -b options are mutually exclusive");
1130 if (list_refs_only) {
1131 if (!TAILQ_EMPTY(&wanted_branches))
1132 errx(1, "-l and -b options are mutually exclusive");
1133 if (fetch_all_branches)
1134 errx(1, "-l and -a options are mutually exclusive");
1135 if (mirror_references)
1136 errx(1, "-l and -m options are mutually exclusive");
1137 if (verbosity == -1)
1138 errx(1, "-l and -q options are mutually exclusive");
1139 if (!TAILQ_EMPTY(&wanted_refs))
1140 errx(1, "-l and -R options are mutually exclusive");
1143 uri = argv[0];
1145 if (argc == 1)
1146 dirname = NULL;
1147 else if (argc == 2)
1148 dirname = argv[1];
1149 else
1150 usage_clone();
1152 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1153 &repo_name, uri);
1154 if (error)
1155 goto done;
1157 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1158 host, port ? ":" : "", port ? port : "",
1159 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1160 error = got_error_from_errno("asprintf");
1161 goto done;
1164 if (strcmp(proto, "git") == 0) {
1165 #ifndef PROFILE
1166 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1167 "sendfd dns inet unveil", NULL) == -1)
1168 err(1, "pledge");
1169 #endif
1170 } else if (strcmp(proto, "git+ssh") == 0 ||
1171 strcmp(proto, "ssh") == 0) {
1172 #ifndef PROFILE
1173 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1174 "sendfd unveil", NULL) == -1)
1175 err(1, "pledge");
1176 #endif
1177 } else if (strcmp(proto, "http") == 0 ||
1178 strcmp(proto, "git+http") == 0) {
1179 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1180 goto done;
1181 } else {
1182 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1183 goto done;
1185 if (dirname == NULL) {
1186 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1187 error = got_error_from_errno("asprintf");
1188 goto done;
1190 repo_path = default_destdir;
1191 } else
1192 repo_path = dirname;
1194 if (!list_refs_only) {
1195 error = got_path_mkdir(repo_path);
1196 if (error)
1197 goto done;
1199 error = got_repo_init(repo_path);
1200 if (error)
1201 goto done;
1202 error = got_repo_open(&repo, repo_path, NULL);
1203 if (error)
1204 goto done;
1207 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1208 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1209 error = got_error_from_errno2("unveil",
1210 GOT_FETCH_PATH_SSH);
1211 goto done;
1214 error = apply_unveil(repo ? got_repo_get_path(repo) : NULL, 0, NULL);
1215 if (error)
1216 goto done;
1218 if (verbosity >= 0)
1219 printf("Connecting to %s%s%s\n", host,
1220 port ? ":" : "", port ? port : "");
1222 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1223 server_path, verbosity);
1224 if (error)
1225 goto done;
1227 fpa.last_scaled_size[0] = '\0';
1228 fpa.last_p_indexed = -1;
1229 fpa.last_p_resolved = -1;
1230 fpa.verbosity = verbosity;
1231 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1232 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1233 fetch_all_branches, &wanted_branches, &wanted_refs,
1234 list_refs_only, verbosity, fetchfd, repo,
1235 fetch_progress, &fpa);
1236 if (error)
1237 goto done;
1239 if (list_refs_only) {
1240 error = list_remote_refs(&symrefs, &refs);
1241 goto done;
1244 error = got_object_id_str(&id_str, pack_hash);
1245 if (error)
1246 goto done;
1247 if (verbosity >= 0)
1248 printf("\nFetched %s.pack\n", id_str);
1249 free(id_str);
1251 /* Set up references provided with the pack file. */
1252 TAILQ_FOREACH(pe, &refs, entry) {
1253 const char *refname = pe->path;
1254 struct got_object_id *id = pe->data;
1255 char *remote_refname;
1257 if (is_wanted_ref(&wanted_refs, refname) &&
1258 !mirror_references) {
1259 error = create_wanted_ref(refname, id,
1260 GOT_FETCH_DEFAULT_REMOTE_NAME,
1261 verbosity - 1, repo);
1262 if (error)
1263 goto done;
1264 continue;
1267 error = create_ref(refname, id, verbosity - 1, repo);
1268 if (error)
1269 goto done;
1271 if (mirror_references)
1272 continue;
1274 if (strncmp("refs/heads/", refname, 11) != 0)
1275 continue;
1277 if (asprintf(&remote_refname,
1278 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1279 refname + 11) == -1) {
1280 error = got_error_from_errno("asprintf");
1281 goto done;
1283 error = create_ref(remote_refname, id, verbosity - 1, repo);
1284 free(remote_refname);
1285 if (error)
1286 goto done;
1289 /* Set the HEAD reference if the server provided one. */
1290 TAILQ_FOREACH(pe, &symrefs, entry) {
1291 struct got_reference *target_ref;
1292 const char *refname = pe->path;
1293 const char *target = pe->data;
1294 char *remote_refname = NULL, *remote_target = NULL;
1296 if (strcmp(refname, GOT_REF_HEAD) != 0)
1297 continue;
1299 error = got_ref_open(&target_ref, repo, target, 0);
1300 if (error) {
1301 if (error->code == GOT_ERR_NOT_REF) {
1302 error = NULL;
1303 continue;
1305 goto done;
1308 error = create_symref(refname, target_ref, verbosity, repo);
1309 got_ref_close(target_ref);
1310 if (error)
1311 goto done;
1313 if (mirror_references)
1314 continue;
1316 if (strncmp("refs/heads/", target, 11) != 0)
1317 continue;
1319 if (asprintf(&remote_refname,
1320 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1321 refname) == -1) {
1322 error = got_error_from_errno("asprintf");
1323 goto done;
1325 if (asprintf(&remote_target,
1326 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1327 target + 11) == -1) {
1328 error = got_error_from_errno("asprintf");
1329 free(remote_refname);
1330 goto done;
1332 error = got_ref_open(&target_ref, repo, remote_target, 0);
1333 if (error) {
1334 free(remote_refname);
1335 free(remote_target);
1336 if (error->code == GOT_ERR_NOT_REF) {
1337 error = NULL;
1338 continue;
1340 goto done;
1342 error = create_symref(remote_refname, target_ref,
1343 verbosity - 1, repo);
1344 free(remote_refname);
1345 free(remote_target);
1346 got_ref_close(target_ref);
1347 if (error)
1348 goto done;
1350 if (pe == NULL) {
1352 * We failed to set the HEAD reference. If we asked for
1353 * a set of wanted branches use the first of one of those
1354 * which could be fetched instead.
1356 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1357 const char *target = pe->path;
1358 struct got_reference *target_ref;
1360 error = got_ref_open(&target_ref, repo, target, 0);
1361 if (error) {
1362 if (error->code == GOT_ERR_NOT_REF) {
1363 error = NULL;
1364 continue;
1366 goto done;
1369 error = create_symref(GOT_REF_HEAD, target_ref,
1370 verbosity, repo);
1371 got_ref_close(target_ref);
1372 if (error)
1373 goto done;
1374 break;
1378 /* Create got.conf(5). */
1379 gotconfig_path = got_repo_get_path_gotconfig(repo);
1380 if (gotconfig_path == NULL) {
1381 error = got_error_from_errno("got_repo_get_path_gotconfig");
1382 goto done;
1384 gotconfig_file = fopen(gotconfig_path, "a");
1385 if (gotconfig_file == NULL) {
1386 error = got_error_from_errno2("fopen", gotconfig_path);
1387 goto done;
1389 got_path_strip_trailing_slashes(server_path);
1390 remote_repo_path = server_path;
1391 while (remote_repo_path[0] == '/')
1392 remote_repo_path++;
1393 if (asprintf(&gotconfig,
1394 "remote \"%s\" {\n"
1395 "\tserver %s\n"
1396 "\tprotocol %s\n"
1397 "%s%s%s"
1398 "\trepository \"%s\"\n"
1399 "%s"
1400 "}\n",
1401 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1402 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1403 remote_repo_path,
1404 mirror_references ? "\tmirror-references yes\n" : "") == -1) {
1405 error = got_error_from_errno("asprintf");
1406 goto done;
1408 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1409 if (n != strlen(gotconfig)) {
1410 error = got_ferror(gotconfig_file, GOT_ERR_IO);
1411 goto done;
1414 /* Create a config file Git can understand. */
1415 gitconfig_path = got_repo_get_path_gitconfig(repo);
1416 if (gitconfig_path == NULL) {
1417 error = got_error_from_errno("got_repo_get_path_gitconfig");
1418 goto done;
1420 gitconfig_file = fopen(gitconfig_path, "a");
1421 if (gitconfig_file == NULL) {
1422 error = got_error_from_errno2("fopen", gitconfig_path);
1423 goto done;
1425 if (mirror_references) {
1426 if (asprintf(&gitconfig,
1427 "[remote \"%s\"]\n"
1428 "\turl = %s\n"
1429 "\tfetch = +refs/*:refs/*\n"
1430 "\tmirror = true\n",
1431 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1432 error = got_error_from_errno("asprintf");
1433 goto done;
1435 } else if (fetch_all_branches) {
1436 if (asprintf(&gitconfig,
1437 "[remote \"%s\"]\n"
1438 "\turl = %s\n"
1439 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1440 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1441 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1442 error = got_error_from_errno("asprintf");
1443 goto done;
1445 } else {
1446 const char *branchname;
1449 * If the server specified a default branch, use just that one.
1450 * Otherwise fall back to fetching all branches on next fetch.
1452 if (head_symref) {
1453 branchname = got_ref_get_symref_target(head_symref);
1454 if (strncmp(branchname, "refs/heads/", 11) == 0)
1455 branchname += 11;
1456 } else
1457 branchname = "*"; /* fall back to all branches */
1458 if (asprintf(&gitconfig,
1459 "[remote \"%s\"]\n"
1460 "\turl = %s\n"
1461 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1462 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1463 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1464 branchname) == -1) {
1465 error = got_error_from_errno("asprintf");
1466 goto done;
1469 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1470 if (n != strlen(gitconfig)) {
1471 error = got_ferror(gitconfig_file, GOT_ERR_IO);
1472 goto done;
1475 if (verbosity >= 0)
1476 printf("Created %s repository '%s'\n",
1477 mirror_references ? "mirrored" : "cloned", repo_path);
1478 done:
1479 if (fetchpid > 0) {
1480 if (kill(fetchpid, SIGTERM) == -1)
1481 error = got_error_from_errno("kill");
1482 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1483 error = got_error_from_errno("waitpid");
1485 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1486 error = got_error_from_errno("close");
1487 if (gotconfig_file && fclose(gotconfig_file) == EOF && error == NULL)
1488 error = got_error_from_errno("fclose");
1489 if (gitconfig_file && fclose(gitconfig_file) == EOF && error == NULL)
1490 error = got_error_from_errno("fclose");
1491 if (repo)
1492 got_repo_close(repo);
1493 if (head_symref)
1494 got_ref_close(head_symref);
1495 TAILQ_FOREACH(pe, &refs, entry) {
1496 free((void *)pe->path);
1497 free(pe->data);
1499 got_pathlist_free(&refs);
1500 TAILQ_FOREACH(pe, &symrefs, entry) {
1501 free((void *)pe->path);
1502 free(pe->data);
1504 got_pathlist_free(&symrefs);
1505 got_pathlist_free(&wanted_branches);
1506 got_pathlist_free(&wanted_refs);
1507 free(pack_hash);
1508 free(proto);
1509 free(host);
1510 free(port);
1511 free(server_path);
1512 free(repo_name);
1513 free(default_destdir);
1514 free(gotconfig);
1515 free(gitconfig);
1516 free(gotconfig_path);
1517 free(gitconfig_path);
1518 free(git_url);
1519 return error;
1522 static const struct got_error *
1523 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1524 int replace_tags, int verbosity, struct got_repository *repo)
1526 const struct got_error *err = NULL;
1527 char *new_id_str = NULL;
1528 struct got_object_id *old_id = NULL;
1530 err = got_object_id_str(&new_id_str, new_id);
1531 if (err)
1532 goto done;
1534 if (!replace_tags &&
1535 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1536 err = got_ref_resolve(&old_id, repo, ref);
1537 if (err)
1538 goto done;
1539 if (got_object_id_cmp(old_id, new_id) == 0)
1540 goto done;
1541 if (verbosity >= 0) {
1542 printf("Rejecting update of existing tag %s: %s\n",
1543 got_ref_get_name(ref), new_id_str);
1545 goto done;
1548 if (got_ref_is_symbolic(ref)) {
1549 if (verbosity >= 0) {
1550 printf("Replacing reference %s: %s\n",
1551 got_ref_get_name(ref),
1552 got_ref_get_symref_target(ref));
1554 err = got_ref_change_symref_to_ref(ref, new_id);
1555 if (err)
1556 goto done;
1557 err = got_ref_write(ref, repo);
1558 if (err)
1559 goto done;
1560 } else {
1561 err = got_ref_resolve(&old_id, repo, ref);
1562 if (err)
1563 goto done;
1564 if (got_object_id_cmp(old_id, new_id) == 0)
1565 goto done;
1567 err = got_ref_change_ref(ref, new_id);
1568 if (err)
1569 goto done;
1570 err = got_ref_write(ref, repo);
1571 if (err)
1572 goto done;
1575 if (verbosity >= 0)
1576 printf("Updated %s: %s\n", got_ref_get_name(ref),
1577 new_id_str);
1578 done:
1579 free(old_id);
1580 free(new_id_str);
1581 return err;
1584 static const struct got_error *
1585 update_symref(const char *refname, struct got_reference *target_ref,
1586 int verbosity, struct got_repository *repo)
1588 const struct got_error *err = NULL, *unlock_err;
1589 struct got_reference *symref;
1590 int symref_is_locked = 0;
1592 err = got_ref_open(&symref, repo, refname, 1);
1593 if (err) {
1594 if (err->code != GOT_ERR_NOT_REF)
1595 return err;
1596 err = got_ref_alloc_symref(&symref, refname, target_ref);
1597 if (err)
1598 goto done;
1600 err = got_ref_write(symref, repo);
1601 if (err)
1602 goto done;
1604 if (verbosity >= 0)
1605 printf("Created reference %s: %s\n",
1606 got_ref_get_name(symref),
1607 got_ref_get_symref_target(symref));
1608 } else {
1609 symref_is_locked = 1;
1611 if (strcmp(got_ref_get_symref_target(symref),
1612 got_ref_get_name(target_ref)) == 0)
1613 goto done;
1615 err = got_ref_change_symref(symref,
1616 got_ref_get_name(target_ref));
1617 if (err)
1618 goto done;
1620 err = got_ref_write(symref, repo);
1621 if (err)
1622 goto done;
1624 if (verbosity >= 0)
1625 printf("Updated %s: %s\n", got_ref_get_name(symref),
1626 got_ref_get_symref_target(symref));
1629 done:
1630 if (symref_is_locked) {
1631 unlock_err = got_ref_unlock(symref);
1632 if (unlock_err && err == NULL)
1633 err = unlock_err;
1635 got_ref_close(symref);
1636 return err;
1639 __dead static void
1640 usage_fetch(void)
1642 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1643 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1644 "[remote-repository-name]\n",
1645 getprogname());
1646 exit(1);
1649 static const struct got_error *
1650 delete_missing_ref(struct got_reference *ref,
1651 int verbosity, struct got_repository *repo)
1653 const struct got_error *err = NULL;
1654 struct got_object_id *id = NULL;
1655 char *id_str = NULL;
1657 if (got_ref_is_symbolic(ref)) {
1658 err = got_ref_delete(ref, repo);
1659 if (err)
1660 return err;
1661 if (verbosity >= 0) {
1662 printf("Deleted reference %s: %s\n",
1663 got_ref_get_name(ref),
1664 got_ref_get_symref_target(ref));
1666 } else {
1667 err = got_ref_resolve(&id, repo, ref);
1668 if (err)
1669 return err;
1670 err = got_object_id_str(&id_str, id);
1671 if (err)
1672 goto done;
1674 err = got_ref_delete(ref, repo);
1675 if (err)
1676 goto done;
1677 if (verbosity >= 0) {
1678 printf("Deleted reference %s: %s\n",
1679 got_ref_get_name(ref), id_str);
1682 done:
1683 free(id);
1684 free(id_str);
1685 return NULL;
1688 static const struct got_error *
1689 delete_missing_refs(struct got_pathlist_head *their_refs,
1690 struct got_pathlist_head *their_symrefs,
1691 const struct got_remote_repo *remote,
1692 int verbosity, struct got_repository *repo)
1694 const struct got_error *err = NULL, *unlock_err;
1695 struct got_reflist_head my_refs;
1696 struct got_reflist_entry *re;
1697 struct got_pathlist_entry *pe;
1698 char *remote_namespace = NULL;
1699 char *local_refname = NULL;
1701 SIMPLEQ_INIT(&my_refs);
1703 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
1704 == -1)
1705 return got_error_from_errno("asprintf");
1707 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1708 if (err)
1709 goto done;
1711 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1712 const char *refname = got_ref_get_name(re->ref);
1714 if (!remote->mirror_references) {
1715 if (strncmp(refname, remote_namespace,
1716 strlen(remote_namespace)) == 0) {
1717 if (strcmp(refname + strlen(remote_namespace),
1718 GOT_REF_HEAD) == 0)
1719 continue;
1720 if (asprintf(&local_refname, "refs/heads/%s",
1721 refname + strlen(remote_namespace)) == -1) {
1722 err = got_error_from_errno("asprintf");
1723 goto done;
1725 } else if (strncmp(refname, "refs/tags/", 10) != 0)
1726 continue;
1729 TAILQ_FOREACH(pe, their_refs, entry) {
1730 if (strcmp(local_refname, pe->path) == 0)
1731 break;
1733 if (pe != NULL)
1734 continue;
1736 TAILQ_FOREACH(pe, their_symrefs, entry) {
1737 if (strcmp(local_refname, pe->path) == 0)
1738 break;
1740 if (pe != NULL)
1741 continue;
1743 err = delete_missing_ref(re->ref, verbosity, repo);
1744 if (err)
1745 break;
1747 if (local_refname) {
1748 struct got_reference *ref;
1749 err = got_ref_open(&ref, repo, local_refname, 1);
1750 if (err) {
1751 if (err->code != GOT_ERR_NOT_REF)
1752 break;
1753 free(local_refname);
1754 local_refname = NULL;
1755 continue;
1757 err = delete_missing_ref(ref, verbosity, repo);
1758 if (err)
1759 break;
1760 unlock_err = got_ref_unlock(ref);
1761 got_ref_close(ref);
1762 if (unlock_err && err == NULL) {
1763 err = unlock_err;
1764 break;
1767 free(local_refname);
1768 local_refname = NULL;
1771 done:
1772 free(remote_namespace);
1773 free(local_refname);
1774 return err;
1777 static const struct got_error *
1778 update_wanted_ref(const char *refname, struct got_object_id *id,
1779 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1781 const struct got_error *err, *unlock_err;
1782 char *remote_refname;
1783 struct got_reference *ref;
1785 if (strncmp("refs/", refname, 5) == 0)
1786 refname += 5;
1788 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1789 remote_repo_name, refname) == -1)
1790 return got_error_from_errno("asprintf");
1792 err = got_ref_open(&ref, repo, remote_refname, 1);
1793 if (err) {
1794 if (err->code != GOT_ERR_NOT_REF)
1795 goto done;
1796 err = create_ref(remote_refname, id, verbosity, repo);
1797 } else {
1798 err = update_ref(ref, id, 0, verbosity, repo);
1799 unlock_err = got_ref_unlock(ref);
1800 if (unlock_err && err == NULL)
1801 err = unlock_err;
1802 got_ref_close(ref);
1804 done:
1805 free(remote_refname);
1806 return err;
1809 static const struct got_error *
1810 cmd_fetch(int argc, char *argv[])
1812 const struct got_error *error = NULL, *unlock_err;
1813 char *cwd = NULL, *repo_path = NULL;
1814 const char *remote_name;
1815 char *proto = NULL, *host = NULL, *port = NULL;
1816 char *repo_name = NULL, *server_path = NULL;
1817 const struct got_remote_repo *remotes, *remote = NULL;
1818 int nremotes;
1819 char *id_str = NULL;
1820 struct got_repository *repo = NULL;
1821 struct got_worktree *worktree = NULL;
1822 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
1823 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1824 struct got_pathlist_entry *pe;
1825 struct got_object_id *pack_hash = NULL;
1826 int i, ch, fetchfd = -1, fetchstatus;
1827 pid_t fetchpid = -1;
1828 struct got_fetch_progress_arg fpa;
1829 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
1830 int delete_refs = 0, replace_tags = 0;
1832 TAILQ_INIT(&refs);
1833 TAILQ_INIT(&symrefs);
1834 TAILQ_INIT(&wanted_branches);
1835 TAILQ_INIT(&wanted_refs);
1837 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
1838 switch (ch) {
1839 case 'a':
1840 fetch_all_branches = 1;
1841 break;
1842 case 'b':
1843 error = got_pathlist_append(&wanted_branches,
1844 optarg, NULL);
1845 if (error)
1846 return error;
1847 break;
1848 case 'd':
1849 delete_refs = 1;
1850 break;
1851 case 'l':
1852 list_refs_only = 1;
1853 break;
1854 case 'r':
1855 repo_path = realpath(optarg, NULL);
1856 if (repo_path == NULL)
1857 return got_error_from_errno2("realpath",
1858 optarg);
1859 got_path_strip_trailing_slashes(repo_path);
1860 break;
1861 case 't':
1862 replace_tags = 1;
1863 break;
1864 case 'v':
1865 if (verbosity < 0)
1866 verbosity = 0;
1867 else if (verbosity < 3)
1868 verbosity++;
1869 break;
1870 case 'q':
1871 verbosity = -1;
1872 break;
1873 case 'R':
1874 error = got_pathlist_append(&wanted_refs,
1875 optarg, NULL);
1876 if (error)
1877 return error;
1878 break;
1879 default:
1880 usage_fetch();
1881 break;
1884 argc -= optind;
1885 argv += optind;
1887 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1888 errx(1, "-a and -b options are mutually exclusive");
1889 if (list_refs_only) {
1890 if (!TAILQ_EMPTY(&wanted_branches))
1891 errx(1, "-l and -b options are mutually exclusive");
1892 if (fetch_all_branches)
1893 errx(1, "-l and -a options are mutually exclusive");
1894 if (delete_refs)
1895 errx(1, "-l and -d options are mutually exclusive");
1896 if (verbosity == -1)
1897 errx(1, "-l and -q options are mutually exclusive");
1900 if (argc == 0)
1901 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
1902 else if (argc == 1)
1903 remote_name = argv[0];
1904 else
1905 usage_fetch();
1907 cwd = getcwd(NULL, 0);
1908 if (cwd == NULL) {
1909 error = got_error_from_errno("getcwd");
1910 goto done;
1913 if (repo_path == NULL) {
1914 error = got_worktree_open(&worktree, cwd);
1915 if (error && error->code != GOT_ERR_NOT_WORKTREE)
1916 goto done;
1917 else
1918 error = NULL;
1919 if (worktree) {
1920 repo_path =
1921 strdup(got_worktree_get_repo_path(worktree));
1922 if (repo_path == NULL)
1923 error = got_error_from_errno("strdup");
1924 if (error)
1925 goto done;
1926 } else {
1927 repo_path = strdup(cwd);
1928 if (repo_path == NULL) {
1929 error = got_error_from_errno("strdup");
1930 goto done;
1935 error = got_repo_open(&repo, repo_path, NULL);
1936 if (error)
1937 goto done;
1939 if (worktree) {
1940 worktree_conf = got_worktree_get_gotconfig(worktree);
1941 if (worktree_conf) {
1942 got_gotconfig_get_remotes(&nremotes, &remotes,
1943 worktree_conf);
1944 for (i = 0; i < nremotes; i++) {
1945 remote = &remotes[i];
1946 if (strcmp(remote->name, remote_name) == 0)
1947 break;
1951 if (remote == NULL) {
1952 repo_conf = got_repo_get_gotconfig(repo);
1953 if (repo_conf) {
1954 got_gotconfig_get_remotes(&nremotes, &remotes,
1955 repo_conf);
1956 for (i = 0; i < nremotes; i++) {
1957 remote = &remotes[i];
1958 if (strcmp(remote->name, remote_name) == 0)
1959 break;
1963 if (remote == NULL) {
1964 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
1965 for (i = 0; i < nremotes; i++) {
1966 remote = &remotes[i];
1967 if (strcmp(remote->name, remote_name) == 0)
1968 break;
1971 if (remote == NULL) {
1972 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
1973 goto done;
1976 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1977 &repo_name, remote->url);
1978 if (error)
1979 goto done;
1981 if (strcmp(proto, "git") == 0) {
1982 #ifndef PROFILE
1983 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1984 "sendfd dns inet unveil", NULL) == -1)
1985 err(1, "pledge");
1986 #endif
1987 } else if (strcmp(proto, "git+ssh") == 0 ||
1988 strcmp(proto, "ssh") == 0) {
1989 #ifndef PROFILE
1990 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1991 "sendfd unveil", NULL) == -1)
1992 err(1, "pledge");
1993 #endif
1994 } else if (strcmp(proto, "http") == 0 ||
1995 strcmp(proto, "git+http") == 0) {
1996 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1997 goto done;
1998 } else {
1999 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2000 goto done;
2003 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
2004 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
2005 error = got_error_from_errno2("unveil",
2006 GOT_FETCH_PATH_SSH);
2007 goto done;
2010 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2011 if (error)
2012 goto done;
2014 if (verbosity >= 0)
2015 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2016 port ? ":" : "", port ? port : "");
2018 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2019 server_path, verbosity);
2020 if (error)
2021 goto done;
2023 fpa.last_scaled_size[0] = '\0';
2024 fpa.last_p_indexed = -1;
2025 fpa.last_p_resolved = -1;
2026 fpa.verbosity = verbosity;
2027 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2028 remote->mirror_references, fetch_all_branches, &wanted_branches,
2029 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2030 fetch_progress, &fpa);
2031 if (error)
2032 goto done;
2034 if (list_refs_only) {
2035 error = list_remote_refs(&symrefs, &refs);
2036 goto done;
2039 if (pack_hash == NULL) {
2040 if (verbosity >= 0)
2041 printf("Already up-to-date\n");
2042 } else if (verbosity >= 0) {
2043 error = got_object_id_str(&id_str, pack_hash);
2044 if (error)
2045 goto done;
2046 printf("\nFetched %s.pack\n", id_str);
2047 free(id_str);
2048 id_str = NULL;
2051 /* Update references provided with the pack file. */
2052 TAILQ_FOREACH(pe, &refs, entry) {
2053 const char *refname = pe->path;
2054 struct got_object_id *id = pe->data;
2055 struct got_reference *ref;
2056 char *remote_refname;
2058 if (is_wanted_ref(&wanted_refs, refname) &&
2059 !remote->mirror_references) {
2060 error = update_wanted_ref(refname, id,
2061 remote->name, verbosity, repo);
2062 if (error)
2063 goto done;
2064 continue;
2067 if (remote->mirror_references ||
2068 strncmp("refs/tags/", refname, 10) == 0) {
2069 error = got_ref_open(&ref, repo, refname, 1);
2070 if (error) {
2071 if (error->code != GOT_ERR_NOT_REF)
2072 goto done;
2073 error = create_ref(refname, id, verbosity,
2074 repo);
2075 if (error)
2076 goto done;
2077 } else {
2078 error = update_ref(ref, id, replace_tags,
2079 verbosity, repo);
2080 unlock_err = got_ref_unlock(ref);
2081 if (unlock_err && error == NULL)
2082 error = unlock_err;
2083 got_ref_close(ref);
2084 if (error)
2085 goto done;
2087 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2088 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2089 remote_name, refname + 11) == -1) {
2090 error = got_error_from_errno("asprintf");
2091 goto done;
2094 error = got_ref_open(&ref, repo, remote_refname, 1);
2095 if (error) {
2096 if (error->code != GOT_ERR_NOT_REF)
2097 goto done;
2098 error = create_ref(remote_refname, id,
2099 verbosity, repo);
2100 if (error)
2101 goto done;
2102 } else {
2103 error = update_ref(ref, id, replace_tags,
2104 verbosity, repo);
2105 unlock_err = got_ref_unlock(ref);
2106 if (unlock_err && error == NULL)
2107 error = unlock_err;
2108 got_ref_close(ref);
2109 if (error)
2110 goto done;
2113 /* Also create a local branch if none exists yet. */
2114 error = got_ref_open(&ref, repo, refname, 1);
2115 if (error) {
2116 if (error->code != GOT_ERR_NOT_REF)
2117 goto done;
2118 error = create_ref(refname, id, verbosity,
2119 repo);
2120 if (error)
2121 goto done;
2122 } else {
2123 unlock_err = got_ref_unlock(ref);
2124 if (unlock_err && error == NULL)
2125 error = unlock_err;
2126 got_ref_close(ref);
2130 if (delete_refs) {
2131 error = delete_missing_refs(&refs, &symrefs, remote,
2132 verbosity, repo);
2133 if (error)
2134 goto done;
2137 if (!remote->mirror_references) {
2138 /* Update remote HEAD reference if the server provided one. */
2139 TAILQ_FOREACH(pe, &symrefs, entry) {
2140 struct got_reference *target_ref;
2141 const char *refname = pe->path;
2142 const char *target = pe->data;
2143 char *remote_refname = NULL, *remote_target = NULL;
2145 if (strcmp(refname, GOT_REF_HEAD) != 0)
2146 continue;
2148 if (strncmp("refs/heads/", target, 11) != 0)
2149 continue;
2151 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2152 remote->name, refname) == -1) {
2153 error = got_error_from_errno("asprintf");
2154 goto done;
2156 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2157 remote->name, target + 11) == -1) {
2158 error = got_error_from_errno("asprintf");
2159 free(remote_refname);
2160 goto done;
2163 error = got_ref_open(&target_ref, repo, remote_target,
2164 0);
2165 if (error) {
2166 free(remote_refname);
2167 free(remote_target);
2168 if (error->code == GOT_ERR_NOT_REF) {
2169 error = NULL;
2170 continue;
2172 goto done;
2174 error = update_symref(remote_refname, target_ref,
2175 verbosity, repo);
2176 free(remote_refname);
2177 free(remote_target);
2178 got_ref_close(target_ref);
2179 if (error)
2180 goto done;
2183 done:
2184 if (fetchpid > 0) {
2185 if (kill(fetchpid, SIGTERM) == -1)
2186 error = got_error_from_errno("kill");
2187 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2188 error = got_error_from_errno("waitpid");
2190 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2191 error = got_error_from_errno("close");
2192 if (repo)
2193 got_repo_close(repo);
2194 if (worktree)
2195 got_worktree_close(worktree);
2196 TAILQ_FOREACH(pe, &refs, entry) {
2197 free((void *)pe->path);
2198 free(pe->data);
2200 got_pathlist_free(&refs);
2201 TAILQ_FOREACH(pe, &symrefs, entry) {
2202 free((void *)pe->path);
2203 free(pe->data);
2205 got_pathlist_free(&symrefs);
2206 got_pathlist_free(&wanted_branches);
2207 got_pathlist_free(&wanted_refs);
2208 free(id_str);
2209 free(cwd);
2210 free(repo_path);
2211 free(pack_hash);
2212 free(proto);
2213 free(host);
2214 free(port);
2215 free(server_path);
2216 free(repo_name);
2217 return error;
2221 __dead static void
2222 usage_checkout(void)
2224 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2225 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2226 exit(1);
2229 static void
2230 show_worktree_base_ref_warning(void)
2232 fprintf(stderr, "%s: warning: could not create a reference "
2233 "to the work tree's base commit; the commit could be "
2234 "garbage-collected by Git; making the repository "
2235 "writable and running 'got update' will prevent this\n",
2236 getprogname());
2239 struct got_checkout_progress_arg {
2240 const char *worktree_path;
2241 int had_base_commit_ref_error;
2244 static const struct got_error *
2245 checkout_progress(void *arg, unsigned char status, const char *path)
2247 struct got_checkout_progress_arg *a = arg;
2249 /* Base commit bump happens silently. */
2250 if (status == GOT_STATUS_BUMP_BASE)
2251 return NULL;
2253 if (status == GOT_STATUS_BASE_REF_ERR) {
2254 a->had_base_commit_ref_error = 1;
2255 return NULL;
2258 while (path[0] == '/')
2259 path++;
2261 printf("%c %s/%s\n", status, a->worktree_path, path);
2262 return NULL;
2265 static const struct got_error *
2266 check_cancelled(void *arg)
2268 if (sigint_received || sigpipe_received)
2269 return got_error(GOT_ERR_CANCELLED);
2270 return NULL;
2273 static const struct got_error *
2274 check_linear_ancestry(struct got_object_id *commit_id,
2275 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2276 struct got_repository *repo)
2278 const struct got_error *err = NULL;
2279 struct got_object_id *yca_id;
2281 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2282 commit_id, base_commit_id, repo, check_cancelled, NULL);
2283 if (err)
2284 return err;
2286 if (yca_id == NULL)
2287 return got_error(GOT_ERR_ANCESTRY);
2290 * Require a straight line of history between the target commit
2291 * and the work tree's base commit.
2293 * Non-linear situations such as this require a rebase:
2295 * (commit) D F (base_commit)
2296 * \ /
2297 * C E
2298 * \ /
2299 * B (yca)
2300 * |
2301 * A
2303 * 'got update' only handles linear cases:
2304 * Update forwards in time: A (base/yca) - B - C - D (commit)
2305 * Update backwards in time: D (base) - C - B - A (commit/yca)
2307 if (allow_forwards_in_time_only) {
2308 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2309 return got_error(GOT_ERR_ANCESTRY);
2310 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2311 got_object_id_cmp(base_commit_id, yca_id) != 0)
2312 return got_error(GOT_ERR_ANCESTRY);
2314 free(yca_id);
2315 return NULL;
2318 static const struct got_error *
2319 check_same_branch(struct got_object_id *commit_id,
2320 struct got_reference *head_ref, struct got_object_id *yca_id,
2321 struct got_repository *repo)
2323 const struct got_error *err = NULL;
2324 struct got_commit_graph *graph = NULL;
2325 struct got_object_id *head_commit_id = NULL;
2326 int is_same_branch = 0;
2328 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2329 if (err)
2330 goto done;
2332 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2333 is_same_branch = 1;
2334 goto done;
2336 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2337 is_same_branch = 1;
2338 goto done;
2341 err = got_commit_graph_open(&graph, "/", 1);
2342 if (err)
2343 goto done;
2345 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2346 check_cancelled, NULL);
2347 if (err)
2348 goto done;
2350 for (;;) {
2351 struct got_object_id *id;
2352 err = got_commit_graph_iter_next(&id, graph, repo,
2353 check_cancelled, NULL);
2354 if (err) {
2355 if (err->code == GOT_ERR_ITER_COMPLETED)
2356 err = NULL;
2357 break;
2360 if (id) {
2361 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2362 break;
2363 if (got_object_id_cmp(id, commit_id) == 0) {
2364 is_same_branch = 1;
2365 break;
2369 done:
2370 if (graph)
2371 got_commit_graph_close(graph);
2372 free(head_commit_id);
2373 if (!err && !is_same_branch)
2374 err = got_error(GOT_ERR_ANCESTRY);
2375 return err;
2378 static const struct got_error *
2379 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2381 static char msg[512];
2382 const char *branch_name;
2384 if (got_ref_is_symbolic(ref))
2385 branch_name = got_ref_get_symref_target(ref);
2386 else
2387 branch_name = got_ref_get_name(ref);
2389 if (strncmp("refs/heads/", branch_name, 11) == 0)
2390 branch_name += 11;
2392 snprintf(msg, sizeof(msg),
2393 "target commit is not contained in branch '%s'; "
2394 "the branch to use must be specified with -b; "
2395 "if necessary a new branch can be created for "
2396 "this commit with 'got branch -c %s BRANCH_NAME'",
2397 branch_name, commit_id_str);
2399 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2402 static const struct got_error *
2403 cmd_checkout(int argc, char *argv[])
2405 const struct got_error *error = NULL;
2406 struct got_repository *repo = NULL;
2407 struct got_reference *head_ref = NULL;
2408 struct got_worktree *worktree = NULL;
2409 char *repo_path = NULL;
2410 char *worktree_path = NULL;
2411 const char *path_prefix = "";
2412 const char *branch_name = GOT_REF_HEAD;
2413 char *commit_id_str = NULL;
2414 char *cwd = NULL, *path = NULL;
2415 int ch, same_path_prefix, allow_nonempty = 0;
2416 struct got_pathlist_head paths;
2417 struct got_checkout_progress_arg cpa;
2419 TAILQ_INIT(&paths);
2421 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2422 switch (ch) {
2423 case 'b':
2424 branch_name = optarg;
2425 break;
2426 case 'c':
2427 commit_id_str = strdup(optarg);
2428 if (commit_id_str == NULL)
2429 return got_error_from_errno("strdup");
2430 break;
2431 case 'E':
2432 allow_nonempty = 1;
2433 break;
2434 case 'p':
2435 path_prefix = optarg;
2436 break;
2437 default:
2438 usage_checkout();
2439 /* NOTREACHED */
2443 argc -= optind;
2444 argv += optind;
2446 #ifndef PROFILE
2447 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2448 "unveil", NULL) == -1)
2449 err(1, "pledge");
2450 #endif
2451 if (argc == 1) {
2452 char *base, *dotgit;
2453 repo_path = realpath(argv[0], NULL);
2454 if (repo_path == NULL)
2455 return got_error_from_errno2("realpath", argv[0]);
2456 cwd = getcwd(NULL, 0);
2457 if (cwd == NULL) {
2458 error = got_error_from_errno("getcwd");
2459 goto done;
2461 if (path_prefix[0])
2462 path = strdup(path_prefix);
2463 else
2464 path = strdup(repo_path);
2465 if (path == NULL) {
2466 error = got_error_from_errno("strdup");
2467 goto done;
2469 base = basename(path);
2470 if (base == NULL) {
2471 error = got_error_from_errno2("basename", path);
2472 goto done;
2474 dotgit = strstr(base, ".git");
2475 if (dotgit)
2476 *dotgit = '\0';
2477 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2478 error = got_error_from_errno("asprintf");
2479 goto done;
2481 } else if (argc == 2) {
2482 repo_path = realpath(argv[0], NULL);
2483 if (repo_path == NULL) {
2484 error = got_error_from_errno2("realpath", argv[0]);
2485 goto done;
2487 worktree_path = realpath(argv[1], NULL);
2488 if (worktree_path == NULL) {
2489 if (errno != ENOENT) {
2490 error = got_error_from_errno2("realpath",
2491 argv[1]);
2492 goto done;
2494 worktree_path = strdup(argv[1]);
2495 if (worktree_path == NULL) {
2496 error = got_error_from_errno("strdup");
2497 goto done;
2500 } else
2501 usage_checkout();
2503 got_path_strip_trailing_slashes(repo_path);
2504 got_path_strip_trailing_slashes(worktree_path);
2506 error = got_repo_open(&repo, repo_path, NULL);
2507 if (error != NULL)
2508 goto done;
2510 /* Pre-create work tree path for unveil(2) */
2511 error = got_path_mkdir(worktree_path);
2512 if (error) {
2513 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2514 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2515 goto done;
2516 if (!allow_nonempty &&
2517 !got_path_dir_is_empty(worktree_path)) {
2518 error = got_error_path(worktree_path,
2519 GOT_ERR_DIR_NOT_EMPTY);
2520 goto done;
2524 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2525 if (error)
2526 goto done;
2528 error = got_ref_open(&head_ref, repo, branch_name, 0);
2529 if (error != NULL)
2530 goto done;
2532 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2533 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2534 goto done;
2536 error = got_worktree_open(&worktree, worktree_path);
2537 if (error != NULL)
2538 goto done;
2540 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2541 path_prefix);
2542 if (error != NULL)
2543 goto done;
2544 if (!same_path_prefix) {
2545 error = got_error(GOT_ERR_PATH_PREFIX);
2546 goto done;
2549 if (commit_id_str) {
2550 struct got_object_id *commit_id;
2551 error = got_repo_match_object_id(&commit_id, NULL,
2552 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2553 if (error)
2554 goto done;
2555 error = check_linear_ancestry(commit_id,
2556 got_worktree_get_base_commit_id(worktree), 0, repo);
2557 if (error != NULL) {
2558 free(commit_id);
2559 if (error->code == GOT_ERR_ANCESTRY) {
2560 error = checkout_ancestry_error(
2561 head_ref, commit_id_str);
2563 goto done;
2565 error = check_same_branch(commit_id, head_ref, NULL, repo);
2566 if (error) {
2567 if (error->code == GOT_ERR_ANCESTRY) {
2568 error = checkout_ancestry_error(
2569 head_ref, commit_id_str);
2571 goto done;
2573 error = got_worktree_set_base_commit_id(worktree, repo,
2574 commit_id);
2575 free(commit_id);
2576 if (error)
2577 goto done;
2580 error = got_pathlist_append(&paths, "", NULL);
2581 if (error)
2582 goto done;
2583 cpa.worktree_path = worktree_path;
2584 cpa.had_base_commit_ref_error = 0;
2585 error = got_worktree_checkout_files(worktree, &paths, repo,
2586 checkout_progress, &cpa, check_cancelled, NULL);
2587 if (error != NULL)
2588 goto done;
2590 printf("Now shut up and hack\n");
2591 if (cpa.had_base_commit_ref_error)
2592 show_worktree_base_ref_warning();
2593 done:
2594 got_pathlist_free(&paths);
2595 free(commit_id_str);
2596 free(repo_path);
2597 free(worktree_path);
2598 free(cwd);
2599 free(path);
2600 return error;
2603 struct got_update_progress_arg {
2604 int did_something;
2605 int conflicts;
2606 int obstructed;
2607 int not_updated;
2610 void
2611 print_update_progress_stats(struct got_update_progress_arg *upa)
2613 if (!upa->did_something)
2614 return;
2616 if (upa->conflicts > 0)
2617 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2618 if (upa->obstructed > 0)
2619 printf("File paths obstructed by a non-regular file: %d\n",
2620 upa->obstructed);
2621 if (upa->not_updated > 0)
2622 printf("Files not updated because of existing merge "
2623 "conflicts: %d\n", upa->not_updated);
2626 __dead static void
2627 usage_update(void)
2629 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2630 getprogname());
2631 exit(1);
2634 static const struct got_error *
2635 update_progress(void *arg, unsigned char status, const char *path)
2637 struct got_update_progress_arg *upa = arg;
2639 if (status == GOT_STATUS_EXISTS ||
2640 status == GOT_STATUS_BASE_REF_ERR)
2641 return NULL;
2643 upa->did_something = 1;
2645 /* Base commit bump happens silently. */
2646 if (status == GOT_STATUS_BUMP_BASE)
2647 return NULL;
2649 if (status == GOT_STATUS_CONFLICT)
2650 upa->conflicts++;
2651 if (status == GOT_STATUS_OBSTRUCTED)
2652 upa->obstructed++;
2653 if (status == GOT_STATUS_CANNOT_UPDATE)
2654 upa->not_updated++;
2656 while (path[0] == '/')
2657 path++;
2658 printf("%c %s\n", status, path);
2659 return NULL;
2662 static const struct got_error *
2663 switch_head_ref(struct got_reference *head_ref,
2664 struct got_object_id *commit_id, struct got_worktree *worktree,
2665 struct got_repository *repo)
2667 const struct got_error *err = NULL;
2668 char *base_id_str;
2669 int ref_has_moved = 0;
2671 /* Trivial case: switching between two different references. */
2672 if (strcmp(got_ref_get_name(head_ref),
2673 got_worktree_get_head_ref_name(worktree)) != 0) {
2674 printf("Switching work tree from %s to %s\n",
2675 got_worktree_get_head_ref_name(worktree),
2676 got_ref_get_name(head_ref));
2677 return got_worktree_set_head_ref(worktree, head_ref);
2680 err = check_linear_ancestry(commit_id,
2681 got_worktree_get_base_commit_id(worktree), 0, repo);
2682 if (err) {
2683 if (err->code != GOT_ERR_ANCESTRY)
2684 return err;
2685 ref_has_moved = 1;
2687 if (!ref_has_moved)
2688 return NULL;
2690 /* Switching to a rebased branch with the same reference name. */
2691 err = got_object_id_str(&base_id_str,
2692 got_worktree_get_base_commit_id(worktree));
2693 if (err)
2694 return err;
2695 printf("Reference %s now points at a different branch\n",
2696 got_worktree_get_head_ref_name(worktree));
2697 printf("Switching work tree from %s to %s\n", base_id_str,
2698 got_worktree_get_head_ref_name(worktree));
2699 return NULL;
2702 static const struct got_error *
2703 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2705 const struct got_error *err;
2706 int in_progress;
2708 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2709 if (err)
2710 return err;
2711 if (in_progress)
2712 return got_error(GOT_ERR_REBASING);
2714 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2715 if (err)
2716 return err;
2717 if (in_progress)
2718 return got_error(GOT_ERR_HISTEDIT_BUSY);
2720 return NULL;
2723 static const struct got_error *
2724 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2725 char *argv[], struct got_worktree *worktree)
2727 const struct got_error *err = NULL;
2728 char *path;
2729 int i;
2731 if (argc == 0) {
2732 path = strdup("");
2733 if (path == NULL)
2734 return got_error_from_errno("strdup");
2735 return got_pathlist_append(paths, path, NULL);
2738 for (i = 0; i < argc; i++) {
2739 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2740 if (err)
2741 break;
2742 err = got_pathlist_append(paths, path, NULL);
2743 if (err) {
2744 free(path);
2745 break;
2749 return err;
2752 static const struct got_error *
2753 wrap_not_worktree_error(const struct got_error *orig_err,
2754 const char *cmdname, const char *path)
2756 const struct got_error *err;
2757 struct got_repository *repo;
2758 static char msg[512];
2760 err = got_repo_open(&repo, path, NULL);
2761 if (err)
2762 return orig_err;
2764 snprintf(msg, sizeof(msg),
2765 "'got %s' needs a work tree in addition to a git repository\n"
2766 "Work trees can be checked out from this Git repository with "
2767 "'got checkout'.\n"
2768 "The got(1) manual page contains more information.", cmdname);
2769 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2770 got_repo_close(repo);
2771 return err;
2774 static const struct got_error *
2775 cmd_update(int argc, char *argv[])
2777 const struct got_error *error = NULL;
2778 struct got_repository *repo = NULL;
2779 struct got_worktree *worktree = NULL;
2780 char *worktree_path = NULL;
2781 struct got_object_id *commit_id = NULL;
2782 char *commit_id_str = NULL;
2783 const char *branch_name = NULL;
2784 struct got_reference *head_ref = NULL;
2785 struct got_pathlist_head paths;
2786 struct got_pathlist_entry *pe;
2787 int ch;
2788 struct got_update_progress_arg upa;
2790 TAILQ_INIT(&paths);
2792 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2793 switch (ch) {
2794 case 'b':
2795 branch_name = optarg;
2796 break;
2797 case 'c':
2798 commit_id_str = strdup(optarg);
2799 if (commit_id_str == NULL)
2800 return got_error_from_errno("strdup");
2801 break;
2802 default:
2803 usage_update();
2804 /* NOTREACHED */
2808 argc -= optind;
2809 argv += optind;
2811 #ifndef PROFILE
2812 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2813 "unveil", NULL) == -1)
2814 err(1, "pledge");
2815 #endif
2816 worktree_path = getcwd(NULL, 0);
2817 if (worktree_path == NULL) {
2818 error = got_error_from_errno("getcwd");
2819 goto done;
2821 error = got_worktree_open(&worktree, worktree_path);
2822 if (error) {
2823 if (error->code == GOT_ERR_NOT_WORKTREE)
2824 error = wrap_not_worktree_error(error, "update",
2825 worktree_path);
2826 goto done;
2829 error = check_rebase_or_histedit_in_progress(worktree);
2830 if (error)
2831 goto done;
2833 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
2834 NULL);
2835 if (error != NULL)
2836 goto done;
2838 error = apply_unveil(got_repo_get_path(repo), 0,
2839 got_worktree_get_root_path(worktree));
2840 if (error)
2841 goto done;
2843 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2844 if (error)
2845 goto done;
2847 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
2848 got_worktree_get_head_ref_name(worktree), 0);
2849 if (error != NULL)
2850 goto done;
2851 if (commit_id_str == NULL) {
2852 error = got_ref_resolve(&commit_id, repo, head_ref);
2853 if (error != NULL)
2854 goto done;
2855 error = got_object_id_str(&commit_id_str, commit_id);
2856 if (error != NULL)
2857 goto done;
2858 } else {
2859 error = got_repo_match_object_id(&commit_id, NULL,
2860 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2861 free(commit_id_str);
2862 commit_id_str = NULL;
2863 if (error)
2864 goto done;
2865 error = got_object_id_str(&commit_id_str, commit_id);
2866 if (error)
2867 goto done;
2870 if (branch_name) {
2871 struct got_object_id *head_commit_id;
2872 TAILQ_FOREACH(pe, &paths, entry) {
2873 if (pe->path_len == 0)
2874 continue;
2875 error = got_error_msg(GOT_ERR_BAD_PATH,
2876 "switching between branches requires that "
2877 "the entire work tree gets updated");
2878 goto done;
2880 error = got_ref_resolve(&head_commit_id, repo, head_ref);
2881 if (error)
2882 goto done;
2883 error = check_linear_ancestry(commit_id, head_commit_id, 0,
2884 repo);
2885 free(head_commit_id);
2886 if (error != NULL)
2887 goto done;
2888 error = check_same_branch(commit_id, head_ref, NULL, repo);
2889 if (error)
2890 goto done;
2891 error = switch_head_ref(head_ref, commit_id, worktree, repo);
2892 if (error)
2893 goto done;
2894 } else {
2895 error = check_linear_ancestry(commit_id,
2896 got_worktree_get_base_commit_id(worktree), 0, repo);
2897 if (error != NULL) {
2898 if (error->code == GOT_ERR_ANCESTRY)
2899 error = got_error(GOT_ERR_BRANCH_MOVED);
2900 goto done;
2902 error = check_same_branch(commit_id, head_ref, NULL, repo);
2903 if (error)
2904 goto done;
2907 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
2908 commit_id) != 0) {
2909 error = got_worktree_set_base_commit_id(worktree, repo,
2910 commit_id);
2911 if (error)
2912 goto done;
2915 memset(&upa, 0, sizeof(upa));
2916 error = got_worktree_checkout_files(worktree, &paths, repo,
2917 update_progress, &upa, check_cancelled, NULL);
2918 if (error != NULL)
2919 goto done;
2921 if (upa.did_something)
2922 printf("Updated to commit %s\n", commit_id_str);
2923 else
2924 printf("Already up-to-date\n");
2925 print_update_progress_stats(&upa);
2926 done:
2927 free(worktree_path);
2928 TAILQ_FOREACH(pe, &paths, entry)
2929 free((char *)pe->path);
2930 got_pathlist_free(&paths);
2931 free(commit_id);
2932 free(commit_id_str);
2933 return error;
2936 static const struct got_error *
2937 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
2938 const char *path, int diff_context, int ignore_whitespace,
2939 struct got_repository *repo)
2941 const struct got_error *err = NULL;
2942 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
2944 if (blob_id1) {
2945 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
2946 if (err)
2947 goto done;
2950 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
2951 if (err)
2952 goto done;
2954 while (path[0] == '/')
2955 path++;
2956 err = got_diff_blob(blob1, blob2, path, path, diff_context,
2957 ignore_whitespace, stdout);
2958 done:
2959 if (blob1)
2960 got_object_blob_close(blob1);
2961 got_object_blob_close(blob2);
2962 return err;
2965 static const struct got_error *
2966 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
2967 const char *path, int diff_context, int ignore_whitespace,
2968 struct got_repository *repo)
2970 const struct got_error *err = NULL;
2971 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
2972 struct got_diff_blob_output_unidiff_arg arg;
2974 if (tree_id1) {
2975 err = got_object_open_as_tree(&tree1, repo, tree_id1);
2976 if (err)
2977 goto done;
2980 err = got_object_open_as_tree(&tree2, repo, tree_id2);
2981 if (err)
2982 goto done;
2984 arg.diff_context = diff_context;
2985 arg.ignore_whitespace = ignore_whitespace;
2986 arg.outfile = stdout;
2987 while (path[0] == '/')
2988 path++;
2989 err = got_diff_tree(tree1, tree2, path, path, repo,
2990 got_diff_blob_output_unidiff, &arg, 1);
2991 done:
2992 if (tree1)
2993 got_object_tree_close(tree1);
2994 if (tree2)
2995 got_object_tree_close(tree2);
2996 return err;
2999 static const struct got_error *
3000 get_changed_paths(struct got_pathlist_head *paths,
3001 struct got_commit_object *commit, struct got_repository *repo)
3003 const struct got_error *err = NULL;
3004 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3005 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3006 struct got_object_qid *qid;
3008 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3009 if (qid != NULL) {
3010 struct got_commit_object *pcommit;
3011 err = got_object_open_as_commit(&pcommit, repo,
3012 qid->id);
3013 if (err)
3014 return err;
3016 tree_id1 = got_object_commit_get_tree_id(pcommit);
3017 got_object_commit_close(pcommit);
3021 if (tree_id1) {
3022 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3023 if (err)
3024 goto done;
3027 tree_id2 = got_object_commit_get_tree_id(commit);
3028 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3029 if (err)
3030 goto done;
3032 err = got_diff_tree(tree1, tree2, "", "", repo,
3033 got_diff_tree_collect_changed_paths, paths, 0);
3034 done:
3035 if (tree1)
3036 got_object_tree_close(tree1);
3037 if (tree2)
3038 got_object_tree_close(tree2);
3039 return err;
3042 static const struct got_error *
3043 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3044 const char *path, int diff_context, struct got_repository *repo)
3046 const struct got_error *err = NULL;
3047 struct got_commit_object *pcommit = NULL;
3048 char *id_str1 = NULL, *id_str2 = NULL;
3049 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3050 struct got_object_qid *qid;
3052 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3053 if (qid != NULL) {
3054 err = got_object_open_as_commit(&pcommit, repo,
3055 qid->id);
3056 if (err)
3057 return err;
3060 if (path && path[0] != '\0') {
3061 int obj_type;
3062 err = got_object_id_by_path(&obj_id2, repo, id, path);
3063 if (err)
3064 goto done;
3065 err = got_object_id_str(&id_str2, obj_id2);
3066 if (err) {
3067 free(obj_id2);
3068 goto done;
3070 if (pcommit) {
3071 err = got_object_id_by_path(&obj_id1, repo,
3072 qid->id, path);
3073 if (err) {
3074 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3075 free(obj_id2);
3076 goto done;
3078 } else {
3079 err = got_object_id_str(&id_str1, obj_id1);
3080 if (err) {
3081 free(obj_id2);
3082 goto done;
3086 err = got_object_get_type(&obj_type, repo, obj_id2);
3087 if (err) {
3088 free(obj_id2);
3089 goto done;
3091 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3092 switch (obj_type) {
3093 case GOT_OBJ_TYPE_BLOB:
3094 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3095 0, repo);
3096 break;
3097 case GOT_OBJ_TYPE_TREE:
3098 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3099 0, repo);
3100 break;
3101 default:
3102 err = got_error(GOT_ERR_OBJ_TYPE);
3103 break;
3105 free(obj_id1);
3106 free(obj_id2);
3107 } else {
3108 obj_id2 = got_object_commit_get_tree_id(commit);
3109 err = got_object_id_str(&id_str2, obj_id2);
3110 if (err)
3111 goto done;
3112 obj_id1 = got_object_commit_get_tree_id(pcommit);
3113 err = got_object_id_str(&id_str1, obj_id1);
3114 if (err)
3115 goto done;
3116 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3117 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
3119 done:
3120 free(id_str1);
3121 free(id_str2);
3122 if (pcommit)
3123 got_object_commit_close(pcommit);
3124 return err;
3127 static char *
3128 get_datestr(time_t *time, char *datebuf)
3130 struct tm mytm, *tm;
3131 char *p, *s;
3133 tm = gmtime_r(time, &mytm);
3134 if (tm == NULL)
3135 return NULL;
3136 s = asctime_r(tm, datebuf);
3137 if (s == NULL)
3138 return NULL;
3139 p = strchr(s, '\n');
3140 if (p)
3141 *p = '\0';
3142 return s;
3145 static const struct got_error *
3146 match_logmsg(int *have_match, struct got_object_id *id,
3147 struct got_commit_object *commit, regex_t *regex)
3149 const struct got_error *err = NULL;
3150 regmatch_t regmatch;
3151 char *id_str = NULL, *logmsg = NULL;
3153 *have_match = 0;
3155 err = got_object_id_str(&id_str, id);
3156 if (err)
3157 return err;
3159 err = got_object_commit_get_logmsg(&logmsg, commit);
3160 if (err)
3161 goto done;
3163 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3164 *have_match = 1;
3165 done:
3166 free(id_str);
3167 free(logmsg);
3168 return err;
3171 static void
3172 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3173 regex_t *regex)
3175 regmatch_t regmatch;
3176 struct got_pathlist_entry *pe;
3178 *have_match = 0;
3180 TAILQ_FOREACH(pe, changed_paths, entry) {
3181 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3182 *have_match = 1;
3183 break;
3188 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3190 static const struct got_error *
3191 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3192 struct got_repository *repo, const char *path,
3193 struct got_pathlist_head *changed_paths, int show_patch,
3194 int diff_context, struct got_reflist_head *refs)
3196 const struct got_error *err = NULL;
3197 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3198 char datebuf[26];
3199 time_t committer_time;
3200 const char *author, *committer;
3201 char *refs_str = NULL;
3202 struct got_reflist_entry *re;
3204 SIMPLEQ_FOREACH(re, refs, entry) {
3205 char *s;
3206 const char *name;
3207 struct got_tag_object *tag = NULL;
3208 struct got_object_id *ref_id;
3209 int cmp;
3211 name = got_ref_get_name(re->ref);
3212 if (strcmp(name, GOT_REF_HEAD) == 0)
3213 continue;
3214 if (strncmp(name, "refs/", 5) == 0)
3215 name += 5;
3216 if (strncmp(name, "got/", 4) == 0)
3217 continue;
3218 if (strncmp(name, "heads/", 6) == 0)
3219 name += 6;
3220 if (strncmp(name, "remotes/", 8) == 0) {
3221 name += 8;
3222 s = strstr(name, "/" GOT_REF_HEAD);
3223 if (s != NULL && s[strlen(s)] == '\0')
3224 continue;
3226 err = got_ref_resolve(&ref_id, repo, re->ref);
3227 if (err)
3228 return err;
3229 if (strncmp(name, "tags/", 5) == 0) {
3230 err = got_object_open_as_tag(&tag, repo, ref_id);
3231 if (err) {
3232 if (err->code != GOT_ERR_OBJ_TYPE) {
3233 free(ref_id);
3234 return err;
3236 /* Ref points at something other than a tag. */
3237 err = NULL;
3238 tag = NULL;
3241 cmp = got_object_id_cmp(tag ?
3242 got_object_tag_get_object_id(tag) : ref_id, id);
3243 free(ref_id);
3244 if (tag)
3245 got_object_tag_close(tag);
3246 if (cmp != 0)
3247 continue;
3248 s = refs_str;
3249 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3250 name) == -1) {
3251 err = got_error_from_errno("asprintf");
3252 free(s);
3253 return err;
3255 free(s);
3257 err = got_object_id_str(&id_str, id);
3258 if (err)
3259 return err;
3261 printf(GOT_COMMIT_SEP_STR);
3262 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3263 refs_str ? refs_str : "", refs_str ? ")" : "");
3264 free(id_str);
3265 id_str = NULL;
3266 free(refs_str);
3267 refs_str = NULL;
3268 printf("from: %s\n", got_object_commit_get_author(commit));
3269 committer_time = got_object_commit_get_committer_time(commit);
3270 datestr = get_datestr(&committer_time, datebuf);
3271 if (datestr)
3272 printf("date: %s UTC\n", datestr);
3273 author = got_object_commit_get_author(commit);
3274 committer = got_object_commit_get_committer(commit);
3275 if (strcmp(author, committer) != 0)
3276 printf("via: %s\n", committer);
3277 if (got_object_commit_get_nparents(commit) > 1) {
3278 const struct got_object_id_queue *parent_ids;
3279 struct got_object_qid *qid;
3280 int n = 1;
3281 parent_ids = got_object_commit_get_parent_ids(commit);
3282 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3283 err = got_object_id_str(&id_str, qid->id);
3284 if (err)
3285 return err;
3286 printf("parent %d: %s\n", n++, id_str);
3287 free(id_str);
3291 err = got_object_commit_get_logmsg(&logmsg0, commit);
3292 if (err)
3293 return err;
3295 logmsg = logmsg0;
3296 do {
3297 line = strsep(&logmsg, "\n");
3298 if (line)
3299 printf(" %s\n", line);
3300 } while (line);
3301 free(logmsg0);
3303 if (changed_paths) {
3304 struct got_pathlist_entry *pe;
3305 TAILQ_FOREACH(pe, changed_paths, entry) {
3306 struct got_diff_changed_path *cp = pe->data;
3307 printf(" %c %s\n", cp->status, pe->path);
3309 printf("\n");
3311 if (show_patch) {
3312 err = print_patch(commit, id, path, diff_context, repo);
3313 if (err == 0)
3314 printf("\n");
3317 if (fflush(stdout) != 0 && err == NULL)
3318 err = got_error_from_errno("fflush");
3319 return err;
3322 static const struct got_error *
3323 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3324 struct got_repository *repo, const char *path, int show_changed_paths,
3325 int show_patch, const char *search_pattern, int diff_context, int limit,
3326 int log_branches, int reverse_display_order, struct got_reflist_head *refs)
3328 const struct got_error *err;
3329 struct got_commit_graph *graph;
3330 regex_t regex;
3331 int have_match;
3332 struct got_object_id_queue reversed_commits;
3333 struct got_object_qid *qid;
3334 struct got_commit_object *commit;
3335 struct got_pathlist_head changed_paths;
3336 struct got_pathlist_entry *pe;
3338 SIMPLEQ_INIT(&reversed_commits);
3339 TAILQ_INIT(&changed_paths);
3341 if (search_pattern && regcomp(&regex, search_pattern,
3342 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3343 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3345 err = got_commit_graph_open(&graph, path, !log_branches);
3346 if (err)
3347 return err;
3348 err = got_commit_graph_iter_start(graph, root_id, repo,
3349 check_cancelled, NULL);
3350 if (err)
3351 goto done;
3352 for (;;) {
3353 struct got_object_id *id;
3355 if (sigint_received || sigpipe_received)
3356 break;
3358 err = got_commit_graph_iter_next(&id, graph, repo,
3359 check_cancelled, NULL);
3360 if (err) {
3361 if (err->code == GOT_ERR_ITER_COMPLETED)
3362 err = NULL;
3363 break;
3365 if (id == NULL)
3366 break;
3368 err = got_object_open_as_commit(&commit, repo, id);
3369 if (err)
3370 break;
3372 if (show_changed_paths && !reverse_display_order) {
3373 err = get_changed_paths(&changed_paths, commit, repo);
3374 if (err)
3375 break;
3378 if (search_pattern) {
3379 err = match_logmsg(&have_match, id, commit, &regex);
3380 if (err) {
3381 got_object_commit_close(commit);
3382 break;
3384 if (have_match == 0 && show_changed_paths)
3385 match_changed_paths(&have_match,
3386 &changed_paths, &regex);
3387 if (have_match == 0) {
3388 got_object_commit_close(commit);
3389 TAILQ_FOREACH(pe, &changed_paths, entry) {
3390 free((char *)pe->path);
3391 free(pe->data);
3393 got_pathlist_free(&changed_paths);
3394 continue;
3398 if (reverse_display_order) {
3399 err = got_object_qid_alloc(&qid, id);
3400 if (err)
3401 break;
3402 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3403 got_object_commit_close(commit);
3404 } else {
3405 err = print_commit(commit, id, repo, path,
3406 show_changed_paths ? &changed_paths : NULL,
3407 show_patch, diff_context, refs);
3408 got_object_commit_close(commit);
3409 if (err)
3410 break;
3412 if ((limit && --limit == 0) ||
3413 (end_id && got_object_id_cmp(id, end_id) == 0))
3414 break;
3416 TAILQ_FOREACH(pe, &changed_paths, entry) {
3417 free((char *)pe->path);
3418 free(pe->data);
3420 got_pathlist_free(&changed_paths);
3422 if (reverse_display_order) {
3423 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3424 err = got_object_open_as_commit(&commit, repo, qid->id);
3425 if (err)
3426 break;
3427 if (show_changed_paths) {
3428 err = get_changed_paths(&changed_paths,
3429 commit, repo);
3430 if (err)
3431 break;
3433 err = print_commit(commit, qid->id, repo, path,
3434 show_changed_paths ? &changed_paths : NULL,
3435 show_patch, diff_context, refs);
3436 got_object_commit_close(commit);
3437 if (err)
3438 break;
3439 TAILQ_FOREACH(pe, &changed_paths, entry) {
3440 free((char *)pe->path);
3441 free(pe->data);
3443 got_pathlist_free(&changed_paths);
3446 done:
3447 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3448 qid = SIMPLEQ_FIRST(&reversed_commits);
3449 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3450 got_object_qid_free(qid);
3452 TAILQ_FOREACH(pe, &changed_paths, entry) {
3453 free((char *)pe->path);
3454 free(pe->data);
3456 got_pathlist_free(&changed_paths);
3457 if (search_pattern)
3458 regfree(&regex);
3459 got_commit_graph_close(graph);
3460 return err;
3463 __dead static void
3464 usage_log(void)
3466 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3467 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3468 "[-R] [path]\n", getprogname());
3469 exit(1);
3472 static int
3473 get_default_log_limit(void)
3475 const char *got_default_log_limit;
3476 long long n;
3477 const char *errstr;
3479 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3480 if (got_default_log_limit == NULL)
3481 return 0;
3482 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3483 if (errstr != NULL)
3484 return 0;
3485 return n;
3488 static const struct got_error *
3489 resolve_commit_arg(struct got_object_id **id, const char *commit_arg,
3490 struct got_repository *repo)
3492 const struct got_error *err = NULL;
3493 struct got_reference *ref;
3495 *id = NULL;
3497 err = got_ref_open(&ref, repo, commit_arg, 0);
3498 if (err == NULL) {
3499 int obj_type;
3500 err = got_ref_resolve(id, repo, ref);
3501 got_ref_close(ref);
3502 if (err)
3503 return err;
3504 err = got_object_get_type(&obj_type, repo, *id);
3505 if (err)
3506 return err;
3507 if (obj_type == GOT_OBJ_TYPE_TAG) {
3508 struct got_tag_object *tag;
3509 err = got_object_open_as_tag(&tag, repo, *id);
3510 if (err)
3511 return err;
3512 if (got_object_tag_get_object_type(tag) !=
3513 GOT_OBJ_TYPE_COMMIT) {
3514 got_object_tag_close(tag);
3515 return got_error(GOT_ERR_OBJ_TYPE);
3517 free(*id);
3518 *id = got_object_id_dup(
3519 got_object_tag_get_object_id(tag));
3520 if (*id == NULL)
3521 err = got_error_from_errno(
3522 "got_object_id_dup");
3523 got_object_tag_close(tag);
3524 if (err)
3525 return err;
3526 } else if (obj_type != GOT_OBJ_TYPE_COMMIT)
3527 return got_error(GOT_ERR_OBJ_TYPE);
3528 } else {
3529 err = got_repo_match_object_id_prefix(id, commit_arg,
3530 GOT_OBJ_TYPE_COMMIT, repo);
3533 return err;
3536 static const struct got_error *
3537 cmd_log(int argc, char *argv[])
3539 const struct got_error *error;
3540 struct got_repository *repo = NULL;
3541 struct got_worktree *worktree = NULL;
3542 struct got_object_id *start_id = NULL, *end_id = NULL;
3543 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3544 const char *start_commit = NULL, *end_commit = NULL;
3545 const char *search_pattern = NULL;
3546 int diff_context = -1, ch;
3547 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3548 int reverse_display_order = 0;
3549 const char *errstr;
3550 struct got_reflist_head refs;
3552 SIMPLEQ_INIT(&refs);
3554 #ifndef PROFILE
3555 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3556 NULL)
3557 == -1)
3558 err(1, "pledge");
3559 #endif
3561 limit = get_default_log_limit();
3563 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3564 switch (ch) {
3565 case 'p':
3566 show_patch = 1;
3567 break;
3568 case 'P':
3569 show_changed_paths = 1;
3570 break;
3571 case 'c':
3572 start_commit = optarg;
3573 break;
3574 case 'C':
3575 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3576 &errstr);
3577 if (errstr != NULL)
3578 err(1, "-C option %s", errstr);
3579 break;
3580 case 'l':
3581 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3582 if (errstr != NULL)
3583 err(1, "-l option %s", errstr);
3584 break;
3585 case 'b':
3586 log_branches = 1;
3587 break;
3588 case 'r':
3589 repo_path = realpath(optarg, NULL);
3590 if (repo_path == NULL)
3591 return got_error_from_errno2("realpath",
3592 optarg);
3593 got_path_strip_trailing_slashes(repo_path);
3594 break;
3595 case 'R':
3596 reverse_display_order = 1;
3597 break;
3598 case 's':
3599 search_pattern = optarg;
3600 break;
3601 case 'x':
3602 end_commit = optarg;
3603 break;
3604 default:
3605 usage_log();
3606 /* NOTREACHED */
3610 argc -= optind;
3611 argv += optind;
3613 if (diff_context == -1)
3614 diff_context = 3;
3615 else if (!show_patch)
3616 errx(1, "-C requires -p");
3618 cwd = getcwd(NULL, 0);
3619 if (cwd == NULL) {
3620 error = got_error_from_errno("getcwd");
3621 goto done;
3624 if (repo_path == NULL) {
3625 error = got_worktree_open(&worktree, cwd);
3626 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3627 goto done;
3628 error = NULL;
3631 if (argc == 0) {
3632 path = strdup("");
3633 if (path == NULL) {
3634 error = got_error_from_errno("strdup");
3635 goto done;
3637 } else if (argc == 1) {
3638 if (worktree) {
3639 error = got_worktree_resolve_path(&path, worktree,
3640 argv[0]);
3641 if (error)
3642 goto done;
3643 } else {
3644 path = strdup(argv[0]);
3645 if (path == NULL) {
3646 error = got_error_from_errno("strdup");
3647 goto done;
3650 } else
3651 usage_log();
3653 if (repo_path == NULL) {
3654 repo_path = worktree ?
3655 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3657 if (repo_path == NULL) {
3658 error = got_error_from_errno("strdup");
3659 goto done;
3662 error = got_repo_open(&repo, repo_path, NULL);
3663 if (error != NULL)
3664 goto done;
3666 error = apply_unveil(got_repo_get_path(repo), 1,
3667 worktree ? got_worktree_get_root_path(worktree) : NULL);
3668 if (error)
3669 goto done;
3671 if (start_commit == NULL) {
3672 struct got_reference *head_ref;
3673 struct got_commit_object *commit = NULL;
3674 error = got_ref_open(&head_ref, repo,
3675 worktree ? got_worktree_get_head_ref_name(worktree)
3676 : GOT_REF_HEAD, 0);
3677 if (error != NULL)
3678 goto done;
3679 error = got_ref_resolve(&start_id, repo, head_ref);
3680 got_ref_close(head_ref);
3681 if (error != NULL)
3682 goto done;
3683 error = got_object_open_as_commit(&commit, repo,
3684 start_id);
3685 if (error != NULL)
3686 goto done;
3687 got_object_commit_close(commit);
3688 } else {
3689 error = resolve_commit_arg(&start_id, start_commit, repo);
3690 if (error != NULL)
3691 goto done;
3693 if (end_commit != NULL) {
3694 error = resolve_commit_arg(&end_id, end_commit, repo);
3695 if (error != NULL)
3696 goto done;
3699 if (worktree) {
3700 const char *prefix = got_worktree_get_path_prefix(worktree);
3701 char *p;
3702 if (asprintf(&p, "%s%s%s", prefix,
3703 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3704 error = got_error_from_errno("asprintf");
3705 goto done;
3707 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3708 free(p);
3709 } else
3710 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3711 if (error != NULL)
3712 goto done;
3713 if (in_repo_path) {
3714 free(path);
3715 path = in_repo_path;
3718 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3719 if (error)
3720 goto done;
3722 error = print_commits(start_id, end_id, repo, path, show_changed_paths,
3723 show_patch, search_pattern, diff_context, limit, log_branches,
3724 reverse_display_order, &refs);
3725 done:
3726 free(path);
3727 free(repo_path);
3728 free(cwd);
3729 if (worktree)
3730 got_worktree_close(worktree);
3731 if (repo) {
3732 const struct got_error *repo_error;
3733 repo_error = got_repo_close(repo);
3734 if (error == NULL)
3735 error = repo_error;
3737 got_ref_list_free(&refs);
3738 return error;
3741 __dead static void
3742 usage_diff(void)
3744 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3745 "[-w] [object1 object2 | path]\n", getprogname());
3746 exit(1);
3749 struct print_diff_arg {
3750 struct got_repository *repo;
3751 struct got_worktree *worktree;
3752 int diff_context;
3753 const char *id_str;
3754 int header_shown;
3755 int diff_staged;
3756 int ignore_whitespace;
3760 * Create a file which contains the target path of a symlink so we can feed
3761 * it as content to the diff engine.
3763 static const struct got_error *
3764 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
3765 const char *abspath)
3767 const struct got_error *err = NULL;
3768 char target_path[PATH_MAX];
3769 ssize_t target_len, outlen;
3771 *fd = -1;
3773 if (dirfd != -1) {
3774 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
3775 if (target_len == -1)
3776 return got_error_from_errno2("readlinkat", abspath);
3777 } else {
3778 target_len = readlink(abspath, target_path, PATH_MAX);
3779 if (target_len == -1)
3780 return got_error_from_errno2("readlink", abspath);
3783 *fd = got_opentempfd();
3784 if (*fd == -1)
3785 return got_error_from_errno("got_opentempfd");
3787 outlen = write(*fd, target_path, target_len);
3788 if (outlen == -1) {
3789 err = got_error_from_errno("got_opentempfd");
3790 goto done;
3793 if (lseek(*fd, 0, SEEK_SET) == -1) {
3794 err = got_error_from_errno2("lseek", abspath);
3795 goto done;
3797 done:
3798 if (err) {
3799 close(*fd);
3800 *fd = -1;
3802 return err;
3805 static const struct got_error *
3806 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3807 const char *path, struct got_object_id *blob_id,
3808 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3809 int dirfd, const char *de_name)
3811 struct print_diff_arg *a = arg;
3812 const struct got_error *err = NULL;
3813 struct got_blob_object *blob1 = NULL;
3814 int fd = -1;
3815 FILE *f2 = NULL;
3816 char *abspath = NULL, *label1 = NULL;
3817 struct stat sb;
3819 if (a->diff_staged) {
3820 if (staged_status != GOT_STATUS_MODIFY &&
3821 staged_status != GOT_STATUS_ADD &&
3822 staged_status != GOT_STATUS_DELETE)
3823 return NULL;
3824 } else {
3825 if (staged_status == GOT_STATUS_DELETE)
3826 return NULL;
3827 if (status == GOT_STATUS_NONEXISTENT)
3828 return got_error_set_errno(ENOENT, path);
3829 if (status != GOT_STATUS_MODIFY &&
3830 status != GOT_STATUS_ADD &&
3831 status != GOT_STATUS_DELETE &&
3832 status != GOT_STATUS_CONFLICT)
3833 return NULL;
3836 if (!a->header_shown) {
3837 printf("diff %s %s%s\n", a->id_str,
3838 got_worktree_get_root_path(a->worktree),
3839 a->diff_staged ? " (staged changes)" : "");
3840 a->header_shown = 1;
3843 if (a->diff_staged) {
3844 const char *label1 = NULL, *label2 = NULL;
3845 switch (staged_status) {
3846 case GOT_STATUS_MODIFY:
3847 label1 = path;
3848 label2 = path;
3849 break;
3850 case GOT_STATUS_ADD:
3851 label2 = path;
3852 break;
3853 case GOT_STATUS_DELETE:
3854 label1 = path;
3855 break;
3856 default:
3857 return got_error(GOT_ERR_FILE_STATUS);
3859 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
3860 label1, label2, a->diff_context, a->ignore_whitespace,
3861 a->repo, stdout);
3864 if (staged_status == GOT_STATUS_ADD ||
3865 staged_status == GOT_STATUS_MODIFY) {
3866 char *id_str;
3867 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
3868 8192);
3869 if (err)
3870 goto done;
3871 err = got_object_id_str(&id_str, staged_blob_id);
3872 if (err)
3873 goto done;
3874 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
3875 err = got_error_from_errno("asprintf");
3876 free(id_str);
3877 goto done;
3879 free(id_str);
3880 } else if (status != GOT_STATUS_ADD) {
3881 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
3882 if (err)
3883 goto done;
3886 if (status != GOT_STATUS_DELETE) {
3887 if (asprintf(&abspath, "%s/%s",
3888 got_worktree_get_root_path(a->worktree), path) == -1) {
3889 err = got_error_from_errno("asprintf");
3890 goto done;
3893 if (dirfd != -1) {
3894 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
3895 if (fd == -1) {
3896 if (errno != ELOOP) {
3897 err = got_error_from_errno2("openat",
3898 abspath);
3899 goto done;
3901 err = get_symlink_target_file(&fd, dirfd,
3902 de_name, abspath);
3903 if (err)
3904 goto done;
3906 } else {
3907 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
3908 if (fd == -1) {
3909 if (errno != ELOOP) {
3910 err = got_error_from_errno2("open",
3911 abspath);
3912 goto done;
3914 err = get_symlink_target_file(&fd, dirfd,
3915 de_name, abspath);
3916 if (err)
3917 goto done;
3920 if (fstat(fd, &sb) == -1) {
3921 err = got_error_from_errno2("fstat", abspath);
3922 goto done;
3924 f2 = fdopen(fd, "r");
3925 if (f2 == NULL) {
3926 err = got_error_from_errno2("fdopen", abspath);
3927 goto done;
3929 fd = -1;
3930 } else
3931 sb.st_size = 0;
3933 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
3934 a->diff_context, a->ignore_whitespace, stdout);
3935 done:
3936 if (blob1)
3937 got_object_blob_close(blob1);
3938 if (f2 && fclose(f2) == EOF && err == NULL)
3939 err = got_error_from_errno("fclose");
3940 if (fd != -1 && close(fd) == -1 && err == NULL)
3941 err = got_error_from_errno("close");
3942 free(abspath);
3943 return err;
3946 static const struct got_error *
3947 cmd_diff(int argc, char *argv[])
3949 const struct got_error *error;
3950 struct got_repository *repo = NULL;
3951 struct got_worktree *worktree = NULL;
3952 char *cwd = NULL, *repo_path = NULL;
3953 struct got_object_id *id1 = NULL, *id2 = NULL;
3954 const char *id_str1 = NULL, *id_str2 = NULL;
3955 char *label1 = NULL, *label2 = NULL;
3956 int type1, type2;
3957 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
3958 const char *errstr;
3959 char *path = NULL;
3961 #ifndef PROFILE
3962 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3963 NULL) == -1)
3964 err(1, "pledge");
3965 #endif
3967 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
3968 switch (ch) {
3969 case 'C':
3970 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3971 &errstr);
3972 if (errstr != NULL)
3973 err(1, "-C option %s", errstr);
3974 break;
3975 case 'r':
3976 repo_path = realpath(optarg, NULL);
3977 if (repo_path == NULL)
3978 return got_error_from_errno2("realpath",
3979 optarg);
3980 got_path_strip_trailing_slashes(repo_path);
3981 break;
3982 case 's':
3983 diff_staged = 1;
3984 break;
3985 case 'w':
3986 ignore_whitespace = 1;
3987 break;
3988 default:
3989 usage_diff();
3990 /* NOTREACHED */
3994 argc -= optind;
3995 argv += optind;
3997 cwd = getcwd(NULL, 0);
3998 if (cwd == NULL) {
3999 error = got_error_from_errno("getcwd");
4000 goto done;
4002 if (argc <= 1) {
4003 if (repo_path)
4004 errx(1,
4005 "-r option can't be used when diffing a work tree");
4006 error = got_worktree_open(&worktree, cwd);
4007 if (error) {
4008 if (error->code == GOT_ERR_NOT_WORKTREE)
4009 error = wrap_not_worktree_error(error, "diff",
4010 cwd);
4011 goto done;
4013 repo_path = strdup(got_worktree_get_repo_path(worktree));
4014 if (repo_path == NULL) {
4015 error = got_error_from_errno("strdup");
4016 goto done;
4018 if (argc == 1) {
4019 error = got_worktree_resolve_path(&path, worktree,
4020 argv[0]);
4021 if (error)
4022 goto done;
4023 } else {
4024 path = strdup("");
4025 if (path == NULL) {
4026 error = got_error_from_errno("strdup");
4027 goto done;
4030 } else if (argc == 2) {
4031 if (diff_staged)
4032 errx(1, "-s option can't be used when diffing "
4033 "objects in repository");
4034 id_str1 = argv[0];
4035 id_str2 = argv[1];
4036 if (repo_path == NULL) {
4037 error = got_worktree_open(&worktree, cwd);
4038 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4039 goto done;
4040 if (worktree) {
4041 repo_path = strdup(
4042 got_worktree_get_repo_path(worktree));
4043 if (repo_path == NULL) {
4044 error = got_error_from_errno("strdup");
4045 goto done;
4047 } else {
4048 repo_path = strdup(cwd);
4049 if (repo_path == NULL) {
4050 error = got_error_from_errno("strdup");
4051 goto done;
4055 } else
4056 usage_diff();
4058 error = got_repo_open(&repo, repo_path, NULL);
4059 free(repo_path);
4060 if (error != NULL)
4061 goto done;
4063 error = apply_unveil(got_repo_get_path(repo), 1,
4064 worktree ? got_worktree_get_root_path(worktree) : NULL);
4065 if (error)
4066 goto done;
4068 if (argc <= 1) {
4069 struct print_diff_arg arg;
4070 struct got_pathlist_head paths;
4071 char *id_str;
4073 TAILQ_INIT(&paths);
4075 error = got_object_id_str(&id_str,
4076 got_worktree_get_base_commit_id(worktree));
4077 if (error)
4078 goto done;
4079 arg.repo = repo;
4080 arg.worktree = worktree;
4081 arg.diff_context = diff_context;
4082 arg.id_str = id_str;
4083 arg.header_shown = 0;
4084 arg.diff_staged = diff_staged;
4085 arg.ignore_whitespace = ignore_whitespace;
4087 error = got_pathlist_append(&paths, path, NULL);
4088 if (error)
4089 goto done;
4091 error = got_worktree_status(worktree, &paths, repo, print_diff,
4092 &arg, check_cancelled, NULL);
4093 free(id_str);
4094 got_pathlist_free(&paths);
4095 goto done;
4098 error = got_repo_match_object_id(&id1, &label1, id_str1,
4099 GOT_OBJ_TYPE_ANY, 1, repo);
4100 if (error)
4101 goto done;
4103 error = got_repo_match_object_id(&id2, &label2, id_str2,
4104 GOT_OBJ_TYPE_ANY, 1, repo);
4105 if (error)
4106 goto done;
4108 error = got_object_get_type(&type1, repo, id1);
4109 if (error)
4110 goto done;
4112 error = got_object_get_type(&type2, repo, id2);
4113 if (error)
4114 goto done;
4116 if (type1 != type2) {
4117 error = got_error(GOT_ERR_OBJ_TYPE);
4118 goto done;
4121 switch (type1) {
4122 case GOT_OBJ_TYPE_BLOB:
4123 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
4124 diff_context, ignore_whitespace, repo, stdout);
4125 break;
4126 case GOT_OBJ_TYPE_TREE:
4127 error = got_diff_objects_as_trees(id1, id2, "", "",
4128 diff_context, ignore_whitespace, repo, stdout);
4129 break;
4130 case GOT_OBJ_TYPE_COMMIT:
4131 printf("diff %s %s\n", label1, label2);
4132 error = got_diff_objects_as_commits(id1, id2, diff_context,
4133 ignore_whitespace, repo, stdout);
4134 break;
4135 default:
4136 error = got_error(GOT_ERR_OBJ_TYPE);
4138 done:
4139 free(label1);
4140 free(label2);
4141 free(id1);
4142 free(id2);
4143 free(path);
4144 if (worktree)
4145 got_worktree_close(worktree);
4146 if (repo) {
4147 const struct got_error *repo_error;
4148 repo_error = got_repo_close(repo);
4149 if (error == NULL)
4150 error = repo_error;
4152 return error;
4155 __dead static void
4156 usage_blame(void)
4158 fprintf(stderr,
4159 "usage: %s blame [-c commit] [-r repository-path] path\n",
4160 getprogname());
4161 exit(1);
4164 struct blame_line {
4165 int annotated;
4166 char *id_str;
4167 char *committer;
4168 char datebuf[11]; /* YYYY-MM-DD + NUL */
4171 struct blame_cb_args {
4172 struct blame_line *lines;
4173 int nlines;
4174 int nlines_prec;
4175 int lineno_cur;
4176 off_t *line_offsets;
4177 FILE *f;
4178 struct got_repository *repo;
4181 static const struct got_error *
4182 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4184 const struct got_error *err = NULL;
4185 struct blame_cb_args *a = arg;
4186 struct blame_line *bline;
4187 char *line = NULL;
4188 size_t linesize = 0;
4189 struct got_commit_object *commit = NULL;
4190 off_t offset;
4191 struct tm tm;
4192 time_t committer_time;
4194 if (nlines != a->nlines ||
4195 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4196 return got_error(GOT_ERR_RANGE);
4198 if (sigint_received)
4199 return got_error(GOT_ERR_ITER_COMPLETED);
4201 if (lineno == -1)
4202 return NULL; /* no change in this commit */
4204 /* Annotate this line. */
4205 bline = &a->lines[lineno - 1];
4206 if (bline->annotated)
4207 return NULL;
4208 err = got_object_id_str(&bline->id_str, id);
4209 if (err)
4210 return err;
4212 err = got_object_open_as_commit(&commit, a->repo, id);
4213 if (err)
4214 goto done;
4216 bline->committer = strdup(got_object_commit_get_committer(commit));
4217 if (bline->committer == NULL) {
4218 err = got_error_from_errno("strdup");
4219 goto done;
4222 committer_time = got_object_commit_get_committer_time(commit);
4223 if (localtime_r(&committer_time, &tm) == NULL)
4224 return got_error_from_errno("localtime_r");
4225 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4226 &tm) >= sizeof(bline->datebuf)) {
4227 err = got_error(GOT_ERR_NO_SPACE);
4228 goto done;
4230 bline->annotated = 1;
4232 /* Print lines annotated so far. */
4233 bline = &a->lines[a->lineno_cur - 1];
4234 if (!bline->annotated)
4235 goto done;
4237 offset = a->line_offsets[a->lineno_cur - 1];
4238 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4239 err = got_error_from_errno("fseeko");
4240 goto done;
4243 while (bline->annotated) {
4244 char *smallerthan, *at, *nl, *committer;
4245 size_t len;
4247 if (getline(&line, &linesize, a->f) == -1) {
4248 if (ferror(a->f))
4249 err = got_error_from_errno("getline");
4250 break;
4253 committer = bline->committer;
4254 smallerthan = strchr(committer, '<');
4255 if (smallerthan && smallerthan[1] != '\0')
4256 committer = smallerthan + 1;
4257 at = strchr(committer, '@');
4258 if (at)
4259 *at = '\0';
4260 len = strlen(committer);
4261 if (len >= 9)
4262 committer[8] = '\0';
4264 nl = strchr(line, '\n');
4265 if (nl)
4266 *nl = '\0';
4267 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4268 bline->id_str, bline->datebuf, committer, line);
4270 a->lineno_cur++;
4271 bline = &a->lines[a->lineno_cur - 1];
4273 done:
4274 if (commit)
4275 got_object_commit_close(commit);
4276 free(line);
4277 return err;
4280 static const struct got_error *
4281 cmd_blame(int argc, char *argv[])
4283 const struct got_error *error;
4284 struct got_repository *repo = NULL;
4285 struct got_worktree *worktree = NULL;
4286 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4287 char *link_target = NULL;
4288 struct got_object_id *obj_id = NULL;
4289 struct got_object_id *commit_id = NULL;
4290 struct got_blob_object *blob = NULL;
4291 char *commit_id_str = NULL;
4292 struct blame_cb_args bca;
4293 int ch, obj_type, i;
4294 size_t filesize;
4296 memset(&bca, 0, sizeof(bca));
4298 #ifndef PROFILE
4299 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4300 NULL) == -1)
4301 err(1, "pledge");
4302 #endif
4304 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4305 switch (ch) {
4306 case 'c':
4307 commit_id_str = optarg;
4308 break;
4309 case 'r':
4310 repo_path = realpath(optarg, NULL);
4311 if (repo_path == NULL)
4312 return got_error_from_errno2("realpath",
4313 optarg);
4314 got_path_strip_trailing_slashes(repo_path);
4315 break;
4316 default:
4317 usage_blame();
4318 /* NOTREACHED */
4322 argc -= optind;
4323 argv += optind;
4325 if (argc == 1)
4326 path = argv[0];
4327 else
4328 usage_blame();
4330 cwd = getcwd(NULL, 0);
4331 if (cwd == NULL) {
4332 error = got_error_from_errno("getcwd");
4333 goto done;
4335 if (repo_path == NULL) {
4336 error = got_worktree_open(&worktree, cwd);
4337 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4338 goto done;
4339 else
4340 error = NULL;
4341 if (worktree) {
4342 repo_path =
4343 strdup(got_worktree_get_repo_path(worktree));
4344 if (repo_path == NULL) {
4345 error = got_error_from_errno("strdup");
4346 if (error)
4347 goto done;
4349 } else {
4350 repo_path = strdup(cwd);
4351 if (repo_path == NULL) {
4352 error = got_error_from_errno("strdup");
4353 goto done;
4358 error = got_repo_open(&repo, repo_path, NULL);
4359 if (error != NULL)
4360 goto done;
4362 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4363 if (error)
4364 goto done;
4366 if (worktree) {
4367 const char *prefix = got_worktree_get_path_prefix(worktree);
4368 char *p, *worktree_subdir = cwd +
4369 strlen(got_worktree_get_root_path(worktree));
4370 if (asprintf(&p, "%s%s%s%s%s",
4371 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
4372 worktree_subdir, worktree_subdir[0] ? "/" : "",
4373 path) == -1) {
4374 error = got_error_from_errno("asprintf");
4375 goto done;
4377 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4378 free(p);
4379 } else {
4380 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4382 if (error)
4383 goto done;
4385 if (commit_id_str == NULL) {
4386 struct got_reference *head_ref;
4387 error = got_ref_open(&head_ref, repo, worktree ?
4388 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4389 if (error != NULL)
4390 goto done;
4391 error = got_ref_resolve(&commit_id, repo, head_ref);
4392 got_ref_close(head_ref);
4393 if (error != NULL)
4394 goto done;
4395 } else {
4396 error = got_repo_match_object_id(&commit_id, NULL,
4397 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4398 if (error)
4399 goto done;
4402 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4403 commit_id, repo);
4404 if (error)
4405 goto done;
4407 error = got_object_id_by_path(&obj_id, repo, commit_id,
4408 link_target ? link_target : in_repo_path);
4409 if (error)
4410 goto done;
4412 error = got_object_get_type(&obj_type, repo, obj_id);
4413 if (error)
4414 goto done;
4416 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4417 error = got_error_path(link_target ? link_target : in_repo_path,
4418 GOT_ERR_OBJ_TYPE);
4419 goto done;
4422 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4423 if (error)
4424 goto done;
4425 bca.f = got_opentemp();
4426 if (bca.f == NULL) {
4427 error = got_error_from_errno("got_opentemp");
4428 goto done;
4430 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4431 &bca.line_offsets, bca.f, blob);
4432 if (error || bca.nlines == 0)
4433 goto done;
4435 /* Don't include \n at EOF in the blame line count. */
4436 if (bca.line_offsets[bca.nlines - 1] == filesize)
4437 bca.nlines--;
4439 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4440 if (bca.lines == NULL) {
4441 error = got_error_from_errno("calloc");
4442 goto done;
4444 bca.lineno_cur = 1;
4445 bca.nlines_prec = 0;
4446 i = bca.nlines;
4447 while (i > 0) {
4448 i /= 10;
4449 bca.nlines_prec++;
4451 bca.repo = repo;
4453 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4454 repo, blame_cb, &bca, check_cancelled, NULL);
4455 done:
4456 free(in_repo_path);
4457 free(link_target);
4458 free(repo_path);
4459 free(cwd);
4460 free(commit_id);
4461 free(obj_id);
4462 if (blob)
4463 got_object_blob_close(blob);
4464 if (worktree)
4465 got_worktree_close(worktree);
4466 if (repo) {
4467 const struct got_error *repo_error;
4468 repo_error = got_repo_close(repo);
4469 if (error == NULL)
4470 error = repo_error;
4472 if (bca.lines) {
4473 for (i = 0; i < bca.nlines; i++) {
4474 struct blame_line *bline = &bca.lines[i];
4475 free(bline->id_str);
4476 free(bline->committer);
4478 free(bca.lines);
4480 free(bca.line_offsets);
4481 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4482 error = got_error_from_errno("fclose");
4483 return error;
4486 __dead static void
4487 usage_tree(void)
4489 fprintf(stderr,
4490 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4491 getprogname());
4492 exit(1);
4495 static const struct got_error *
4496 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4497 const char *root_path, struct got_repository *repo)
4499 const struct got_error *err = NULL;
4500 int is_root_path = (strcmp(path, root_path) == 0);
4501 const char *modestr = "";
4502 mode_t mode = got_tree_entry_get_mode(te);
4503 char *link_target = NULL;
4505 path += strlen(root_path);
4506 while (path[0] == '/')
4507 path++;
4509 if (got_object_tree_entry_is_submodule(te))
4510 modestr = "$";
4511 else if (S_ISLNK(mode)) {
4512 int i;
4514 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4515 if (err)
4516 return err;
4517 for (i = 0; i < strlen(link_target); i++) {
4518 if (!isprint((unsigned char)link_target[i]))
4519 link_target[i] = '?';
4522 modestr = "@";
4524 else if (S_ISDIR(mode))
4525 modestr = "/";
4526 else if (mode & S_IXUSR)
4527 modestr = "*";
4529 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4530 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4531 link_target ? " -> ": "", link_target ? link_target : "");
4533 free(link_target);
4534 return NULL;
4537 static const struct got_error *
4538 print_tree(const char *path, struct got_object_id *commit_id,
4539 int show_ids, int recurse, const char *root_path,
4540 struct got_repository *repo)
4542 const struct got_error *err = NULL;
4543 struct got_object_id *tree_id = NULL;
4544 struct got_tree_object *tree = NULL;
4545 int nentries, i;
4547 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4548 if (err)
4549 goto done;
4551 err = got_object_open_as_tree(&tree, repo, tree_id);
4552 if (err)
4553 goto done;
4554 nentries = got_object_tree_get_nentries(tree);
4555 for (i = 0; i < nentries; i++) {
4556 struct got_tree_entry *te;
4557 char *id = NULL;
4559 if (sigint_received || sigpipe_received)
4560 break;
4562 te = got_object_tree_get_entry(tree, i);
4563 if (show_ids) {
4564 char *id_str;
4565 err = got_object_id_str(&id_str,
4566 got_tree_entry_get_id(te));
4567 if (err)
4568 goto done;
4569 if (asprintf(&id, "%s ", id_str) == -1) {
4570 err = got_error_from_errno("asprintf");
4571 free(id_str);
4572 goto done;
4574 free(id_str);
4576 err = print_entry(te, id, path, root_path, repo);
4577 free(id);
4578 if (err)
4579 goto done;
4581 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4582 char *child_path;
4583 if (asprintf(&child_path, "%s%s%s", path,
4584 path[0] == '/' && path[1] == '\0' ? "" : "/",
4585 got_tree_entry_get_name(te)) == -1) {
4586 err = got_error_from_errno("asprintf");
4587 goto done;
4589 err = print_tree(child_path, commit_id, show_ids, 1,
4590 root_path, repo);
4591 free(child_path);
4592 if (err)
4593 goto done;
4596 done:
4597 if (tree)
4598 got_object_tree_close(tree);
4599 free(tree_id);
4600 return err;
4603 static const struct got_error *
4604 cmd_tree(int argc, char *argv[])
4606 const struct got_error *error;
4607 struct got_repository *repo = NULL;
4608 struct got_worktree *worktree = NULL;
4609 const char *path, *refname = NULL;
4610 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4611 struct got_object_id *commit_id = NULL;
4612 char *commit_id_str = NULL;
4613 int show_ids = 0, recurse = 0;
4614 int ch;
4616 #ifndef PROFILE
4617 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4618 NULL) == -1)
4619 err(1, "pledge");
4620 #endif
4622 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4623 switch (ch) {
4624 case 'c':
4625 commit_id_str = optarg;
4626 break;
4627 case 'r':
4628 repo_path = realpath(optarg, NULL);
4629 if (repo_path == NULL)
4630 return got_error_from_errno2("realpath",
4631 optarg);
4632 got_path_strip_trailing_slashes(repo_path);
4633 break;
4634 case 'i':
4635 show_ids = 1;
4636 break;
4637 case 'R':
4638 recurse = 1;
4639 break;
4640 default:
4641 usage_tree();
4642 /* NOTREACHED */
4646 argc -= optind;
4647 argv += optind;
4649 if (argc == 1)
4650 path = argv[0];
4651 else if (argc > 1)
4652 usage_tree();
4653 else
4654 path = NULL;
4656 cwd = getcwd(NULL, 0);
4657 if (cwd == NULL) {
4658 error = got_error_from_errno("getcwd");
4659 goto done;
4661 if (repo_path == NULL) {
4662 error = got_worktree_open(&worktree, cwd);
4663 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4664 goto done;
4665 else
4666 error = NULL;
4667 if (worktree) {
4668 repo_path =
4669 strdup(got_worktree_get_repo_path(worktree));
4670 if (repo_path == NULL)
4671 error = got_error_from_errno("strdup");
4672 if (error)
4673 goto done;
4674 } else {
4675 repo_path = strdup(cwd);
4676 if (repo_path == NULL) {
4677 error = got_error_from_errno("strdup");
4678 goto done;
4683 error = got_repo_open(&repo, repo_path, NULL);
4684 if (error != NULL)
4685 goto done;
4687 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4688 if (error)
4689 goto done;
4691 if (path == NULL) {
4692 if (worktree) {
4693 char *p, *worktree_subdir = cwd +
4694 strlen(got_worktree_get_root_path(worktree));
4695 if (asprintf(&p, "%s/%s",
4696 got_worktree_get_path_prefix(worktree),
4697 worktree_subdir) == -1) {
4698 error = got_error_from_errno("asprintf");
4699 goto done;
4701 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4702 free(p);
4703 if (error)
4704 goto done;
4705 } else
4706 path = "/";
4708 if (in_repo_path == NULL) {
4709 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4710 if (error != NULL)
4711 goto done;
4714 if (commit_id_str == NULL) {
4715 struct got_reference *head_ref;
4716 if (worktree)
4717 refname = got_worktree_get_head_ref_name(worktree);
4718 else
4719 refname = GOT_REF_HEAD;
4720 error = got_ref_open(&head_ref, repo, refname, 0);
4721 if (error != NULL)
4722 goto done;
4723 error = got_ref_resolve(&commit_id, repo, head_ref);
4724 got_ref_close(head_ref);
4725 if (error != NULL)
4726 goto done;
4727 } else {
4728 error = got_repo_match_object_id(&commit_id, NULL,
4729 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4730 if (error)
4731 goto done;
4734 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4735 in_repo_path, repo);
4736 done:
4737 free(in_repo_path);
4738 free(repo_path);
4739 free(cwd);
4740 free(commit_id);
4741 if (worktree)
4742 got_worktree_close(worktree);
4743 if (repo) {
4744 const struct got_error *repo_error;
4745 repo_error = got_repo_close(repo);
4746 if (error == NULL)
4747 error = repo_error;
4749 return error;
4752 __dead static void
4753 usage_status(void)
4755 fprintf(stderr, "usage: %s status [-s status-codes ] [path ...]\n",
4756 getprogname());
4757 exit(1);
4760 static const struct got_error *
4761 print_status(void *arg, unsigned char status, unsigned char staged_status,
4762 const char *path, struct got_object_id *blob_id,
4763 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4764 int dirfd, const char *de_name)
4766 if (status == staged_status && (status == GOT_STATUS_DELETE))
4767 status = GOT_STATUS_NO_CHANGE;
4768 if (arg) {
4769 char *status_codes = arg;
4770 size_t ncodes = strlen(status_codes);
4771 int i;
4772 for (i = 0; i < ncodes ; i++) {
4773 if (status == status_codes[i] ||
4774 staged_status == status_codes[i])
4775 break;
4777 if (i == ncodes)
4778 return NULL;
4780 printf("%c%c %s\n", status, staged_status, path);
4781 return NULL;
4784 static const struct got_error *
4785 cmd_status(int argc, char *argv[])
4787 const struct got_error *error = NULL;
4788 struct got_repository *repo = NULL;
4789 struct got_worktree *worktree = NULL;
4790 char *cwd = NULL, *status_codes = NULL;;
4791 struct got_pathlist_head paths;
4792 struct got_pathlist_entry *pe;
4793 int ch, i;
4795 TAILQ_INIT(&paths);
4797 while ((ch = getopt(argc, argv, "s:")) != -1) {
4798 switch (ch) {
4799 case 's':
4800 for (i = 0; i < strlen(optarg); i++) {
4801 switch (optarg[i]) {
4802 case GOT_STATUS_MODIFY:
4803 case GOT_STATUS_ADD:
4804 case GOT_STATUS_DELETE:
4805 case GOT_STATUS_CONFLICT:
4806 case GOT_STATUS_MISSING:
4807 case GOT_STATUS_OBSTRUCTED:
4808 case GOT_STATUS_UNVERSIONED:
4809 case GOT_STATUS_MODE_CHANGE:
4810 case GOT_STATUS_NONEXISTENT:
4811 break;
4812 default:
4813 errx(1, "invalid status code '%c'",
4814 optarg[i]);
4817 status_codes = optarg;
4818 break;
4819 default:
4820 usage_status();
4821 /* NOTREACHED */
4825 argc -= optind;
4826 argv += optind;
4828 #ifndef PROFILE
4829 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4830 NULL) == -1)
4831 err(1, "pledge");
4832 #endif
4833 cwd = getcwd(NULL, 0);
4834 if (cwd == NULL) {
4835 error = got_error_from_errno("getcwd");
4836 goto done;
4839 error = got_worktree_open(&worktree, cwd);
4840 if (error) {
4841 if (error->code == GOT_ERR_NOT_WORKTREE)
4842 error = wrap_not_worktree_error(error, "status", cwd);
4843 goto done;
4846 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4847 NULL);
4848 if (error != NULL)
4849 goto done;
4851 error = apply_unveil(got_repo_get_path(repo), 1,
4852 got_worktree_get_root_path(worktree));
4853 if (error)
4854 goto done;
4856 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
4857 if (error)
4858 goto done;
4860 error = got_worktree_status(worktree, &paths, repo, print_status,
4861 status_codes, check_cancelled, NULL);
4862 done:
4863 TAILQ_FOREACH(pe, &paths, entry)
4864 free((char *)pe->path);
4865 got_pathlist_free(&paths);
4866 free(cwd);
4867 return error;
4870 __dead static void
4871 usage_ref(void)
4873 fprintf(stderr,
4874 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
4875 "[-d] [name]\n",
4876 getprogname());
4877 exit(1);
4880 static const struct got_error *
4881 list_refs(struct got_repository *repo, const char *refname)
4883 static const struct got_error *err = NULL;
4884 struct got_reflist_head refs;
4885 struct got_reflist_entry *re;
4887 SIMPLEQ_INIT(&refs);
4888 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
4889 if (err)
4890 return err;
4892 SIMPLEQ_FOREACH(re, &refs, entry) {
4893 char *refstr;
4894 refstr = got_ref_to_str(re->ref);
4895 if (refstr == NULL)
4896 return got_error_from_errno("got_ref_to_str");
4897 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
4898 free(refstr);
4901 got_ref_list_free(&refs);
4902 return NULL;
4905 static const struct got_error *
4906 delete_ref(struct got_repository *repo, const char *refname)
4908 const struct got_error *err = NULL;
4909 struct got_reference *ref;
4911 err = got_ref_open(&ref, repo, refname, 0);
4912 if (err)
4913 return err;
4915 err = got_ref_delete(ref, repo);
4916 got_ref_close(ref);
4917 return err;
4920 static const struct got_error *
4921 add_ref(struct got_repository *repo, const char *refname, const char *target)
4923 const struct got_error *err = NULL;
4924 struct got_object_id *id;
4925 struct got_reference *ref = NULL;
4928 * Don't let the user create a reference name with a leading '-'.
4929 * While technically a valid reference name, this case is usually
4930 * an unintended typo.
4932 if (refname[0] == '-')
4933 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4935 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
4936 repo);
4937 if (err) {
4938 struct got_reference *target_ref;
4940 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
4941 return err;
4942 err = got_ref_open(&target_ref, repo, target, 0);
4943 if (err)
4944 return err;
4945 err = got_ref_resolve(&id, repo, target_ref);
4946 got_ref_close(target_ref);
4947 if (err)
4948 return err;
4951 err = got_ref_alloc(&ref, refname, id);
4952 if (err)
4953 goto done;
4955 err = got_ref_write(ref, repo);
4956 done:
4957 if (ref)
4958 got_ref_close(ref);
4959 free(id);
4960 return err;
4963 static const struct got_error *
4964 add_symref(struct got_repository *repo, const char *refname, const char *target)
4966 const struct got_error *err = NULL;
4967 struct got_reference *ref = NULL;
4968 struct got_reference *target_ref = NULL;
4971 * Don't let the user create a reference name with a leading '-'.
4972 * While technically a valid reference name, this case is usually
4973 * an unintended typo.
4975 if (refname[0] == '-')
4976 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4978 err = got_ref_open(&target_ref, repo, target, 0);
4979 if (err)
4980 return err;
4982 err = got_ref_alloc_symref(&ref, refname, target_ref);
4983 if (err)
4984 goto done;
4986 err = got_ref_write(ref, repo);
4987 done:
4988 if (target_ref)
4989 got_ref_close(target_ref);
4990 if (ref)
4991 got_ref_close(ref);
4992 return err;
4995 static const struct got_error *
4996 cmd_ref(int argc, char *argv[])
4998 const struct got_error *error = NULL;
4999 struct got_repository *repo = NULL;
5000 struct got_worktree *worktree = NULL;
5001 char *cwd = NULL, *repo_path = NULL;
5002 int ch, do_list = 0, do_delete = 0;
5003 const char *obj_arg = NULL, *symref_target= NULL;
5004 char *refname = NULL;
5006 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5007 switch (ch) {
5008 case 'c':
5009 obj_arg = optarg;
5010 break;
5011 case 'd':
5012 do_delete = 1;
5013 break;
5014 case 'r':
5015 repo_path = realpath(optarg, NULL);
5016 if (repo_path == NULL)
5017 return got_error_from_errno2("realpath",
5018 optarg);
5019 got_path_strip_trailing_slashes(repo_path);
5020 break;
5021 case 'l':
5022 do_list = 1;
5023 break;
5024 case 's':
5025 symref_target = optarg;
5026 break;
5027 default:
5028 usage_ref();
5029 /* NOTREACHED */
5033 if (obj_arg && do_list)
5034 errx(1, "-c and -l options are mutually exclusive");
5035 if (obj_arg && do_delete)
5036 errx(1, "-c and -d options are mutually exclusive");
5037 if (obj_arg && symref_target)
5038 errx(1, "-c and -s options are mutually exclusive");
5039 if (symref_target && do_delete)
5040 errx(1, "-s and -d options are mutually exclusive");
5041 if (symref_target && do_list)
5042 errx(1, "-s and -l options are mutually exclusive");
5043 if (do_delete && do_list)
5044 errx(1, "-d and -l options are mutually exclusive");
5046 argc -= optind;
5047 argv += optind;
5049 if (do_list) {
5050 if (argc != 0 && argc != 1)
5051 usage_ref();
5052 if (argc == 1) {
5053 refname = strdup(argv[0]);
5054 if (refname == NULL) {
5055 error = got_error_from_errno("strdup");
5056 goto done;
5059 } else {
5060 if (argc != 1)
5061 usage_ref();
5062 refname = strdup(argv[0]);
5063 if (refname == NULL) {
5064 error = got_error_from_errno("strdup");
5065 goto done;
5069 if (refname)
5070 got_path_strip_trailing_slashes(refname);
5072 #ifndef PROFILE
5073 if (do_list) {
5074 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5075 NULL) == -1)
5076 err(1, "pledge");
5077 } else {
5078 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5079 "sendfd unveil", NULL) == -1)
5080 err(1, "pledge");
5082 #endif
5083 cwd = getcwd(NULL, 0);
5084 if (cwd == NULL) {
5085 error = got_error_from_errno("getcwd");
5086 goto done;
5089 if (repo_path == NULL) {
5090 error = got_worktree_open(&worktree, cwd);
5091 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5092 goto done;
5093 else
5094 error = NULL;
5095 if (worktree) {
5096 repo_path =
5097 strdup(got_worktree_get_repo_path(worktree));
5098 if (repo_path == NULL)
5099 error = got_error_from_errno("strdup");
5100 if (error)
5101 goto done;
5102 } else {
5103 repo_path = strdup(cwd);
5104 if (repo_path == NULL) {
5105 error = got_error_from_errno("strdup");
5106 goto done;
5111 error = got_repo_open(&repo, repo_path, NULL);
5112 if (error != NULL)
5113 goto done;
5115 error = apply_unveil(got_repo_get_path(repo), do_list,
5116 worktree ? got_worktree_get_root_path(worktree) : NULL);
5117 if (error)
5118 goto done;
5120 if (do_list)
5121 error = list_refs(repo, refname);
5122 else if (do_delete)
5123 error = delete_ref(repo, refname);
5124 else if (symref_target)
5125 error = add_symref(repo, refname, symref_target);
5126 else {
5127 if (obj_arg == NULL)
5128 usage_ref();
5129 error = add_ref(repo, refname, obj_arg);
5131 done:
5132 free(refname);
5133 if (repo)
5134 got_repo_close(repo);
5135 if (worktree)
5136 got_worktree_close(worktree);
5137 free(cwd);
5138 free(repo_path);
5139 return error;
5142 __dead static void
5143 usage_branch(void)
5145 fprintf(stderr,
5146 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5147 "[name]\n", getprogname());
5148 exit(1);
5151 static const struct got_error *
5152 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5153 struct got_reference *ref)
5155 const struct got_error *err = NULL;
5156 const char *refname, *marker = " ";
5157 char *refstr;
5159 refname = got_ref_get_name(ref);
5160 if (worktree && strcmp(refname,
5161 got_worktree_get_head_ref_name(worktree)) == 0) {
5162 struct got_object_id *id = NULL;
5164 err = got_ref_resolve(&id, repo, ref);
5165 if (err)
5166 return err;
5167 if (got_object_id_cmp(id,
5168 got_worktree_get_base_commit_id(worktree)) == 0)
5169 marker = "* ";
5170 else
5171 marker = "~ ";
5172 free(id);
5175 if (strncmp(refname, "refs/heads/", 11) == 0)
5176 refname += 11;
5177 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5178 refname += 18;
5180 refstr = got_ref_to_str(ref);
5181 if (refstr == NULL)
5182 return got_error_from_errno("got_ref_to_str");
5184 printf("%s%s: %s\n", marker, refname, refstr);
5185 free(refstr);
5186 return NULL;
5189 static const struct got_error *
5190 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5192 const char *refname;
5194 if (worktree == NULL)
5195 return got_error(GOT_ERR_NOT_WORKTREE);
5197 refname = got_worktree_get_head_ref_name(worktree);
5199 if (strncmp(refname, "refs/heads/", 11) == 0)
5200 refname += 11;
5201 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5202 refname += 18;
5204 printf("%s\n", refname);
5206 return NULL;
5209 static const struct got_error *
5210 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5212 static const struct got_error *err = NULL;
5213 struct got_reflist_head refs;
5214 struct got_reflist_entry *re;
5215 struct got_reference *temp_ref = NULL;
5216 int rebase_in_progress, histedit_in_progress;
5218 SIMPLEQ_INIT(&refs);
5220 if (worktree) {
5221 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5222 worktree);
5223 if (err)
5224 return err;
5226 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5227 worktree);
5228 if (err)
5229 return err;
5231 if (rebase_in_progress || histedit_in_progress) {
5232 err = got_ref_open(&temp_ref, repo,
5233 got_worktree_get_head_ref_name(worktree), 0);
5234 if (err)
5235 return err;
5236 list_branch(repo, worktree, temp_ref);
5237 got_ref_close(temp_ref);
5241 err = got_ref_list(&refs, repo, "refs/heads",
5242 got_ref_cmp_by_name, NULL);
5243 if (err)
5244 return err;
5246 SIMPLEQ_FOREACH(re, &refs, entry)
5247 list_branch(repo, worktree, re->ref);
5249 got_ref_list_free(&refs);
5250 return NULL;
5253 static const struct got_error *
5254 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5255 const char *branch_name)
5257 const struct got_error *err = NULL;
5258 struct got_reference *ref = NULL;
5259 char *refname;
5261 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5262 return got_error_from_errno("asprintf");
5264 err = got_ref_open(&ref, repo, refname, 0);
5265 if (err)
5266 goto done;
5268 if (worktree &&
5269 strcmp(got_worktree_get_head_ref_name(worktree),
5270 got_ref_get_name(ref)) == 0) {
5271 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5272 "will not delete this work tree's current branch");
5273 goto done;
5276 err = got_ref_delete(ref, repo);
5277 done:
5278 if (ref)
5279 got_ref_close(ref);
5280 free(refname);
5281 return err;
5284 static const struct got_error *
5285 add_branch(struct got_repository *repo, const char *branch_name,
5286 struct got_object_id *base_commit_id)
5288 const struct got_error *err = NULL;
5289 struct got_reference *ref = NULL;
5290 char *base_refname = NULL, *refname = NULL;
5293 * Don't let the user create a branch name with a leading '-'.
5294 * While technically a valid reference name, this case is usually
5295 * an unintended typo.
5297 if (branch_name[0] == '-')
5298 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5300 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5301 err = got_error_from_errno("asprintf");
5302 goto done;
5305 err = got_ref_open(&ref, repo, refname, 0);
5306 if (err == NULL) {
5307 err = got_error(GOT_ERR_BRANCH_EXISTS);
5308 goto done;
5309 } else if (err->code != GOT_ERR_NOT_REF)
5310 goto done;
5312 err = got_ref_alloc(&ref, refname, base_commit_id);
5313 if (err)
5314 goto done;
5316 err = got_ref_write(ref, repo);
5317 done:
5318 if (ref)
5319 got_ref_close(ref);
5320 free(base_refname);
5321 free(refname);
5322 return err;
5325 static const struct got_error *
5326 cmd_branch(int argc, char *argv[])
5328 const struct got_error *error = NULL;
5329 struct got_repository *repo = NULL;
5330 struct got_worktree *worktree = NULL;
5331 char *cwd = NULL, *repo_path = NULL;
5332 int ch, do_list = 0, do_show = 0, do_update = 1;
5333 const char *delref = NULL, *commit_id_arg = NULL;
5334 struct got_reference *ref = NULL;
5335 struct got_pathlist_head paths;
5336 struct got_pathlist_entry *pe;
5337 struct got_object_id *commit_id = NULL;
5338 char *commit_id_str = NULL;
5340 TAILQ_INIT(&paths);
5342 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5343 switch (ch) {
5344 case 'c':
5345 commit_id_arg = optarg;
5346 break;
5347 case 'd':
5348 delref = optarg;
5349 break;
5350 case 'r':
5351 repo_path = realpath(optarg, NULL);
5352 if (repo_path == NULL)
5353 return got_error_from_errno2("realpath",
5354 optarg);
5355 got_path_strip_trailing_slashes(repo_path);
5356 break;
5357 case 'l':
5358 do_list = 1;
5359 break;
5360 case 'n':
5361 do_update = 0;
5362 break;
5363 default:
5364 usage_branch();
5365 /* NOTREACHED */
5369 if (do_list && delref)
5370 errx(1, "-l and -d options are mutually exclusive");
5372 argc -= optind;
5373 argv += optind;
5375 if (!do_list && !delref && argc == 0)
5376 do_show = 1;
5378 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5379 errx(1, "-c option can only be used when creating a branch");
5381 if (do_list || delref) {
5382 if (argc > 0)
5383 usage_branch();
5384 } else if (!do_show && argc != 1)
5385 usage_branch();
5387 #ifndef PROFILE
5388 if (do_list || do_show) {
5389 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5390 NULL) == -1)
5391 err(1, "pledge");
5392 } else {
5393 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5394 "sendfd unveil", NULL) == -1)
5395 err(1, "pledge");
5397 #endif
5398 cwd = getcwd(NULL, 0);
5399 if (cwd == NULL) {
5400 error = got_error_from_errno("getcwd");
5401 goto done;
5404 if (repo_path == NULL) {
5405 error = got_worktree_open(&worktree, cwd);
5406 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5407 goto done;
5408 else
5409 error = NULL;
5410 if (worktree) {
5411 repo_path =
5412 strdup(got_worktree_get_repo_path(worktree));
5413 if (repo_path == NULL)
5414 error = got_error_from_errno("strdup");
5415 if (error)
5416 goto done;
5417 } else {
5418 repo_path = strdup(cwd);
5419 if (repo_path == NULL) {
5420 error = got_error_from_errno("strdup");
5421 goto done;
5426 error = got_repo_open(&repo, repo_path, NULL);
5427 if (error != NULL)
5428 goto done;
5430 error = apply_unveil(got_repo_get_path(repo), do_list,
5431 worktree ? got_worktree_get_root_path(worktree) : NULL);
5432 if (error)
5433 goto done;
5435 if (do_show)
5436 error = show_current_branch(repo, worktree);
5437 else if (do_list)
5438 error = list_branches(repo, worktree);
5439 else if (delref)
5440 error = delete_branch(repo, worktree, delref);
5441 else {
5442 if (commit_id_arg == NULL)
5443 commit_id_arg = worktree ?
5444 got_worktree_get_head_ref_name(worktree) :
5445 GOT_REF_HEAD;
5446 error = got_repo_match_object_id(&commit_id, NULL,
5447 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5448 if (error)
5449 goto done;
5450 error = add_branch(repo, argv[0], commit_id);
5451 if (error)
5452 goto done;
5453 if (worktree && do_update) {
5454 struct got_update_progress_arg upa;
5455 char *branch_refname = NULL;
5457 error = got_object_id_str(&commit_id_str, commit_id);
5458 if (error)
5459 goto done;
5460 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5461 worktree);
5462 if (error)
5463 goto done;
5464 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5465 == -1) {
5466 error = got_error_from_errno("asprintf");
5467 goto done;
5469 error = got_ref_open(&ref, repo, branch_refname, 0);
5470 free(branch_refname);
5471 if (error)
5472 goto done;
5473 error = switch_head_ref(ref, commit_id, worktree,
5474 repo);
5475 if (error)
5476 goto done;
5477 error = got_worktree_set_base_commit_id(worktree, repo,
5478 commit_id);
5479 if (error)
5480 goto done;
5481 memset(&upa, 0, sizeof(upa));
5482 error = got_worktree_checkout_files(worktree, &paths,
5483 repo, update_progress, &upa, check_cancelled,
5484 NULL);
5485 if (error)
5486 goto done;
5487 if (upa.did_something)
5488 printf("Updated to commit %s\n", commit_id_str);
5489 print_update_progress_stats(&upa);
5492 done:
5493 if (ref)
5494 got_ref_close(ref);
5495 if (repo)
5496 got_repo_close(repo);
5497 if (worktree)
5498 got_worktree_close(worktree);
5499 free(cwd);
5500 free(repo_path);
5501 free(commit_id);
5502 free(commit_id_str);
5503 TAILQ_FOREACH(pe, &paths, entry)
5504 free((char *)pe->path);
5505 got_pathlist_free(&paths);
5506 return error;
5510 __dead static void
5511 usage_tag(void)
5513 fprintf(stderr,
5514 "usage: %s tag [-c commit] [-r repository] [-l] "
5515 "[-m message] name\n", getprogname());
5516 exit(1);
5519 #if 0
5520 static const struct got_error *
5521 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5523 const struct got_error *err = NULL;
5524 struct got_reflist_entry *re, *se, *new;
5525 struct got_object_id *re_id, *se_id;
5526 struct got_tag_object *re_tag, *se_tag;
5527 time_t re_time, se_time;
5529 SIMPLEQ_FOREACH(re, tags, entry) {
5530 se = SIMPLEQ_FIRST(sorted);
5531 if (se == NULL) {
5532 err = got_reflist_entry_dup(&new, re);
5533 if (err)
5534 return err;
5535 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5536 continue;
5537 } else {
5538 err = got_ref_resolve(&re_id, repo, re->ref);
5539 if (err)
5540 break;
5541 err = got_object_open_as_tag(&re_tag, repo, re_id);
5542 free(re_id);
5543 if (err)
5544 break;
5545 re_time = got_object_tag_get_tagger_time(re_tag);
5546 got_object_tag_close(re_tag);
5549 while (se) {
5550 err = got_ref_resolve(&se_id, repo, re->ref);
5551 if (err)
5552 break;
5553 err = got_object_open_as_tag(&se_tag, repo, se_id);
5554 free(se_id);
5555 if (err)
5556 break;
5557 se_time = got_object_tag_get_tagger_time(se_tag);
5558 got_object_tag_close(se_tag);
5560 if (se_time > re_time) {
5561 err = got_reflist_entry_dup(&new, re);
5562 if (err)
5563 return err;
5564 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5565 break;
5567 se = SIMPLEQ_NEXT(se, entry);
5568 continue;
5571 done:
5572 return err;
5574 #endif
5576 static const struct got_error *
5577 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5579 static const struct got_error *err = NULL;
5580 struct got_reflist_head refs;
5581 struct got_reflist_entry *re;
5583 SIMPLEQ_INIT(&refs);
5585 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5586 if (err)
5587 return err;
5589 SIMPLEQ_FOREACH(re, &refs, entry) {
5590 const char *refname;
5591 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5592 char datebuf[26];
5593 const char *tagger;
5594 time_t tagger_time;
5595 struct got_object_id *id;
5596 struct got_tag_object *tag;
5597 struct got_commit_object *commit = NULL;
5599 refname = got_ref_get_name(re->ref);
5600 if (strncmp(refname, "refs/tags/", 10) != 0)
5601 continue;
5602 refname += 10;
5603 refstr = got_ref_to_str(re->ref);
5604 if (refstr == NULL) {
5605 err = got_error_from_errno("got_ref_to_str");
5606 break;
5608 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5609 free(refstr);
5611 err = got_ref_resolve(&id, repo, re->ref);
5612 if (err)
5613 break;
5614 err = got_object_open_as_tag(&tag, repo, id);
5615 if (err) {
5616 if (err->code != GOT_ERR_OBJ_TYPE) {
5617 free(id);
5618 break;
5620 /* "lightweight" tag */
5621 err = got_object_open_as_commit(&commit, repo, id);
5622 if (err) {
5623 free(id);
5624 break;
5626 tagger = got_object_commit_get_committer(commit);
5627 tagger_time =
5628 got_object_commit_get_committer_time(commit);
5629 err = got_object_id_str(&id_str, id);
5630 free(id);
5631 if (err)
5632 break;
5633 } else {
5634 free(id);
5635 tagger = got_object_tag_get_tagger(tag);
5636 tagger_time = got_object_tag_get_tagger_time(tag);
5637 err = got_object_id_str(&id_str,
5638 got_object_tag_get_object_id(tag));
5639 if (err)
5640 break;
5642 printf("from: %s\n", tagger);
5643 datestr = get_datestr(&tagger_time, datebuf);
5644 if (datestr)
5645 printf("date: %s UTC\n", datestr);
5646 if (commit)
5647 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5648 else {
5649 switch (got_object_tag_get_object_type(tag)) {
5650 case GOT_OBJ_TYPE_BLOB:
5651 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5652 id_str);
5653 break;
5654 case GOT_OBJ_TYPE_TREE:
5655 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5656 id_str);
5657 break;
5658 case GOT_OBJ_TYPE_COMMIT:
5659 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5660 id_str);
5661 break;
5662 case GOT_OBJ_TYPE_TAG:
5663 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5664 id_str);
5665 break;
5666 default:
5667 break;
5670 free(id_str);
5671 if (commit) {
5672 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5673 if (err)
5674 break;
5675 got_object_commit_close(commit);
5676 } else {
5677 tagmsg0 = strdup(got_object_tag_get_message(tag));
5678 got_object_tag_close(tag);
5679 if (tagmsg0 == NULL) {
5680 err = got_error_from_errno("strdup");
5681 break;
5685 tagmsg = tagmsg0;
5686 do {
5687 line = strsep(&tagmsg, "\n");
5688 if (line)
5689 printf(" %s\n", line);
5690 } while (line);
5691 free(tagmsg0);
5694 got_ref_list_free(&refs);
5695 return NULL;
5698 static const struct got_error *
5699 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5700 const char *tag_name, const char *repo_path)
5702 const struct got_error *err = NULL;
5703 char *template = NULL, *initial_content = NULL;
5704 char *editor = NULL;
5705 int initial_content_len;
5706 int fd = -1;
5708 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5709 err = got_error_from_errno("asprintf");
5710 goto done;
5713 initial_content_len = asprintf(&initial_content,
5714 "\n# tagging commit %s as %s\n",
5715 commit_id_str, tag_name);
5716 if (initial_content_len == -1) {
5717 err = got_error_from_errno("asprintf");
5718 goto done;
5721 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5722 if (err)
5723 goto done;
5725 if (write(fd, initial_content, initial_content_len) == -1) {
5726 err = got_error_from_errno2("write", *tagmsg_path);
5727 goto done;
5730 err = get_editor(&editor);
5731 if (err)
5732 goto done;
5733 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
5734 done:
5735 free(initial_content);
5736 free(template);
5737 free(editor);
5739 if (fd != -1 && close(fd) == -1 && err == NULL)
5740 err = got_error_from_errno2("close", *tagmsg_path);
5742 /* Editor is done; we can now apply unveil(2) */
5743 if (err == NULL)
5744 err = apply_unveil(repo_path, 0, NULL);
5745 if (err) {
5746 free(*tagmsg);
5747 *tagmsg = NULL;
5749 return err;
5752 static const struct got_error *
5753 add_tag(struct got_repository *repo, struct got_worktree *worktree,
5754 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
5756 const struct got_error *err = NULL;
5757 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5758 char *label = NULL, *commit_id_str = NULL;
5759 struct got_reference *ref = NULL;
5760 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5761 char *tagmsg_path = NULL, *tag_id_str = NULL;
5762 int preserve_tagmsg = 0;
5765 * Don't let the user create a tag name with a leading '-'.
5766 * While technically a valid reference name, this case is usually
5767 * an unintended typo.
5769 if (tag_name[0] == '-')
5770 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5772 err = get_author(&tagger, repo, worktree);
5773 if (err)
5774 return err;
5776 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5777 GOT_OBJ_TYPE_COMMIT, 1, repo);
5778 if (err)
5779 goto done;
5781 err = got_object_id_str(&commit_id_str, commit_id);
5782 if (err)
5783 goto done;
5785 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5786 refname = strdup(tag_name);
5787 if (refname == NULL) {
5788 err = got_error_from_errno("strdup");
5789 goto done;
5791 tag_name += 10;
5792 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5793 err = got_error_from_errno("asprintf");
5794 goto done;
5797 err = got_ref_open(&ref, repo, refname, 0);
5798 if (err == NULL) {
5799 err = got_error(GOT_ERR_TAG_EXISTS);
5800 goto done;
5801 } else if (err->code != GOT_ERR_NOT_REF)
5802 goto done;
5804 if (tagmsg_arg == NULL) {
5805 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5806 tag_name, got_repo_get_path(repo));
5807 if (err) {
5808 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5809 tagmsg_path != NULL)
5810 preserve_tagmsg = 1;
5811 goto done;
5815 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5816 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5817 if (err) {
5818 if (tagmsg_path)
5819 preserve_tagmsg = 1;
5820 goto done;
5823 err = got_ref_alloc(&ref, refname, tag_id);
5824 if (err) {
5825 if (tagmsg_path)
5826 preserve_tagmsg = 1;
5827 goto done;
5830 err = got_ref_write(ref, repo);
5831 if (err) {
5832 if (tagmsg_path)
5833 preserve_tagmsg = 1;
5834 goto done;
5837 err = got_object_id_str(&tag_id_str, tag_id);
5838 if (err) {
5839 if (tagmsg_path)
5840 preserve_tagmsg = 1;
5841 goto done;
5843 printf("Created tag %s\n", tag_id_str);
5844 done:
5845 if (preserve_tagmsg) {
5846 fprintf(stderr, "%s: tag message preserved in %s\n",
5847 getprogname(), tagmsg_path);
5848 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
5849 err = got_error_from_errno2("unlink", tagmsg_path);
5850 free(tag_id_str);
5851 if (ref)
5852 got_ref_close(ref);
5853 free(commit_id);
5854 free(commit_id_str);
5855 free(refname);
5856 free(tagmsg);
5857 free(tagmsg_path);
5858 free(tagger);
5859 return err;
5862 static const struct got_error *
5863 cmd_tag(int argc, char *argv[])
5865 const struct got_error *error = NULL;
5866 struct got_repository *repo = NULL;
5867 struct got_worktree *worktree = NULL;
5868 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
5869 char *gitconfig_path = NULL;
5870 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
5871 int ch, do_list = 0;
5873 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
5874 switch (ch) {
5875 case 'c':
5876 commit_id_arg = optarg;
5877 break;
5878 case 'm':
5879 tagmsg = optarg;
5880 break;
5881 case 'r':
5882 repo_path = realpath(optarg, NULL);
5883 if (repo_path == NULL)
5884 return got_error_from_errno2("realpath",
5885 optarg);
5886 got_path_strip_trailing_slashes(repo_path);
5887 break;
5888 case 'l':
5889 do_list = 1;
5890 break;
5891 default:
5892 usage_tag();
5893 /* NOTREACHED */
5897 argc -= optind;
5898 argv += optind;
5900 if (do_list) {
5901 if (commit_id_arg != NULL)
5902 errx(1,
5903 "-c option can only be used when creating a tag");
5904 if (tagmsg)
5905 errx(1, "-l and -m options are mutually exclusive");
5906 if (argc > 0)
5907 usage_tag();
5908 } else if (argc != 1)
5909 usage_tag();
5911 tag_name = argv[0];
5913 #ifndef PROFILE
5914 if (do_list) {
5915 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5916 NULL) == -1)
5917 err(1, "pledge");
5918 } else {
5919 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5920 "sendfd unveil", NULL) == -1)
5921 err(1, "pledge");
5923 #endif
5924 cwd = getcwd(NULL, 0);
5925 if (cwd == NULL) {
5926 error = got_error_from_errno("getcwd");
5927 goto done;
5930 if (repo_path == NULL) {
5931 error = got_worktree_open(&worktree, cwd);
5932 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5933 goto done;
5934 else
5935 error = NULL;
5936 if (worktree) {
5937 repo_path =
5938 strdup(got_worktree_get_repo_path(worktree));
5939 if (repo_path == NULL)
5940 error = got_error_from_errno("strdup");
5941 if (error)
5942 goto done;
5943 } else {
5944 repo_path = strdup(cwd);
5945 if (repo_path == NULL) {
5946 error = got_error_from_errno("strdup");
5947 goto done;
5952 if (do_list) {
5953 error = got_repo_open(&repo, repo_path, NULL);
5954 if (error != NULL)
5955 goto done;
5956 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5957 if (error)
5958 goto done;
5959 error = list_tags(repo, worktree);
5960 } else {
5961 error = get_gitconfig_path(&gitconfig_path);
5962 if (error)
5963 goto done;
5964 error = got_repo_open(&repo, repo_path, gitconfig_path);
5965 if (error != NULL)
5966 goto done;
5968 if (tagmsg) {
5969 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5970 if (error)
5971 goto done;
5974 if (commit_id_arg == NULL) {
5975 struct got_reference *head_ref;
5976 struct got_object_id *commit_id;
5977 error = got_ref_open(&head_ref, repo,
5978 worktree ? got_worktree_get_head_ref_name(worktree)
5979 : GOT_REF_HEAD, 0);
5980 if (error)
5981 goto done;
5982 error = got_ref_resolve(&commit_id, repo, head_ref);
5983 got_ref_close(head_ref);
5984 if (error)
5985 goto done;
5986 error = got_object_id_str(&commit_id_str, commit_id);
5987 free(commit_id);
5988 if (error)
5989 goto done;
5992 error = add_tag(repo, worktree, tag_name,
5993 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
5995 done:
5996 if (repo)
5997 got_repo_close(repo);
5998 if (worktree)
5999 got_worktree_close(worktree);
6000 free(cwd);
6001 free(repo_path);
6002 free(gitconfig_path);
6003 free(commit_id_str);
6004 return error;
6007 __dead static void
6008 usage_add(void)
6010 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6011 getprogname());
6012 exit(1);
6015 static const struct got_error *
6016 add_progress(void *arg, unsigned char status, const char *path)
6018 while (path[0] == '/')
6019 path++;
6020 printf("%c %s\n", status, path);
6021 return NULL;
6024 static const struct got_error *
6025 cmd_add(int argc, char *argv[])
6027 const struct got_error *error = NULL;
6028 struct got_repository *repo = NULL;
6029 struct got_worktree *worktree = NULL;
6030 char *cwd = NULL;
6031 struct got_pathlist_head paths;
6032 struct got_pathlist_entry *pe;
6033 int ch, can_recurse = 0, no_ignores = 0;
6035 TAILQ_INIT(&paths);
6037 while ((ch = getopt(argc, argv, "IR")) != -1) {
6038 switch (ch) {
6039 case 'I':
6040 no_ignores = 1;
6041 break;
6042 case 'R':
6043 can_recurse = 1;
6044 break;
6045 default:
6046 usage_add();
6047 /* NOTREACHED */
6051 argc -= optind;
6052 argv += optind;
6054 #ifndef PROFILE
6055 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6056 NULL) == -1)
6057 err(1, "pledge");
6058 #endif
6059 if (argc < 1)
6060 usage_add();
6062 cwd = getcwd(NULL, 0);
6063 if (cwd == NULL) {
6064 error = got_error_from_errno("getcwd");
6065 goto done;
6068 error = got_worktree_open(&worktree, cwd);
6069 if (error) {
6070 if (error->code == GOT_ERR_NOT_WORKTREE)
6071 error = wrap_not_worktree_error(error, "add", cwd);
6072 goto done;
6075 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6076 NULL);
6077 if (error != NULL)
6078 goto done;
6080 error = apply_unveil(got_repo_get_path(repo), 1,
6081 got_worktree_get_root_path(worktree));
6082 if (error)
6083 goto done;
6085 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6086 if (error)
6087 goto done;
6089 if (!can_recurse && no_ignores) {
6090 error = got_error_msg(GOT_ERR_BAD_PATH,
6091 "disregarding ignores requires -R option");
6092 goto done;
6096 if (!can_recurse) {
6097 char *ondisk_path;
6098 struct stat sb;
6099 TAILQ_FOREACH(pe, &paths, entry) {
6100 if (asprintf(&ondisk_path, "%s/%s",
6101 got_worktree_get_root_path(worktree),
6102 pe->path) == -1) {
6103 error = got_error_from_errno("asprintf");
6104 goto done;
6106 if (lstat(ondisk_path, &sb) == -1) {
6107 if (errno == ENOENT) {
6108 free(ondisk_path);
6109 continue;
6111 error = got_error_from_errno2("lstat",
6112 ondisk_path);
6113 free(ondisk_path);
6114 goto done;
6116 free(ondisk_path);
6117 if (S_ISDIR(sb.st_mode)) {
6118 error = got_error_msg(GOT_ERR_BAD_PATH,
6119 "adding directories requires -R option");
6120 goto done;
6125 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6126 NULL, repo, no_ignores);
6127 done:
6128 if (repo)
6129 got_repo_close(repo);
6130 if (worktree)
6131 got_worktree_close(worktree);
6132 TAILQ_FOREACH(pe, &paths, entry)
6133 free((char *)pe->path);
6134 got_pathlist_free(&paths);
6135 free(cwd);
6136 return error;
6139 __dead static void
6140 usage_remove(void)
6142 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6143 "path ...\n", getprogname());
6144 exit(1);
6147 static const struct got_error *
6148 print_remove_status(void *arg, unsigned char status,
6149 unsigned char staged_status, const char *path)
6151 while (path[0] == '/')
6152 path++;
6153 if (status == GOT_STATUS_NONEXISTENT)
6154 return NULL;
6155 if (status == staged_status && (status == GOT_STATUS_DELETE))
6156 status = GOT_STATUS_NO_CHANGE;
6157 printf("%c%c %s\n", status, staged_status, path);
6158 return NULL;
6161 static const struct got_error *
6162 cmd_remove(int argc, char *argv[])
6164 const struct got_error *error = NULL;
6165 struct got_worktree *worktree = NULL;
6166 struct got_repository *repo = NULL;
6167 const char *status_codes = NULL;
6168 char *cwd = NULL;
6169 struct got_pathlist_head paths;
6170 struct got_pathlist_entry *pe;
6171 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6173 TAILQ_INIT(&paths);
6175 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6176 switch (ch) {
6177 case 'f':
6178 delete_local_mods = 1;
6179 break;
6180 case 'k':
6181 keep_on_disk = 1;
6182 break;
6183 case 'R':
6184 can_recurse = 1;
6185 break;
6186 case 's':
6187 for (i = 0; i < strlen(optarg); i++) {
6188 switch (optarg[i]) {
6189 case GOT_STATUS_MODIFY:
6190 delete_local_mods = 1;
6191 break;
6192 case GOT_STATUS_MISSING:
6193 break;
6194 default:
6195 errx(1, "invalid status code '%c'",
6196 optarg[i]);
6199 status_codes = optarg;
6200 break;
6201 default:
6202 usage_remove();
6203 /* NOTREACHED */
6207 argc -= optind;
6208 argv += optind;
6210 #ifndef PROFILE
6211 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6212 NULL) == -1)
6213 err(1, "pledge");
6214 #endif
6215 if (argc < 1)
6216 usage_remove();
6218 cwd = getcwd(NULL, 0);
6219 if (cwd == NULL) {
6220 error = got_error_from_errno("getcwd");
6221 goto done;
6223 error = got_worktree_open(&worktree, cwd);
6224 if (error) {
6225 if (error->code == GOT_ERR_NOT_WORKTREE)
6226 error = wrap_not_worktree_error(error, "remove", cwd);
6227 goto done;
6230 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6231 NULL);
6232 if (error)
6233 goto done;
6235 error = apply_unveil(got_repo_get_path(repo), 1,
6236 got_worktree_get_root_path(worktree));
6237 if (error)
6238 goto done;
6240 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6241 if (error)
6242 goto done;
6244 if (!can_recurse) {
6245 char *ondisk_path;
6246 struct stat sb;
6247 TAILQ_FOREACH(pe, &paths, entry) {
6248 if (asprintf(&ondisk_path, "%s/%s",
6249 got_worktree_get_root_path(worktree),
6250 pe->path) == -1) {
6251 error = got_error_from_errno("asprintf");
6252 goto done;
6254 if (lstat(ondisk_path, &sb) == -1) {
6255 if (errno == ENOENT) {
6256 free(ondisk_path);
6257 continue;
6259 error = got_error_from_errno2("lstat",
6260 ondisk_path);
6261 free(ondisk_path);
6262 goto done;
6264 free(ondisk_path);
6265 if (S_ISDIR(sb.st_mode)) {
6266 error = got_error_msg(GOT_ERR_BAD_PATH,
6267 "removing directories requires -R option");
6268 goto done;
6273 error = got_worktree_schedule_delete(worktree, &paths,
6274 delete_local_mods, status_codes, print_remove_status, NULL,
6275 repo, keep_on_disk);
6276 done:
6277 if (repo)
6278 got_repo_close(repo);
6279 if (worktree)
6280 got_worktree_close(worktree);
6281 TAILQ_FOREACH(pe, &paths, entry)
6282 free((char *)pe->path);
6283 got_pathlist_free(&paths);
6284 free(cwd);
6285 return error;
6288 __dead static void
6289 usage_revert(void)
6291 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6292 "path ...\n", getprogname());
6293 exit(1);
6296 static const struct got_error *
6297 revert_progress(void *arg, unsigned char status, const char *path)
6299 if (status == GOT_STATUS_UNVERSIONED)
6300 return NULL;
6302 while (path[0] == '/')
6303 path++;
6304 printf("%c %s\n", status, path);
6305 return NULL;
6308 struct choose_patch_arg {
6309 FILE *patch_script_file;
6310 const char *action;
6313 static const struct got_error *
6314 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6315 int nchanges, const char *action)
6317 char *line = NULL;
6318 size_t linesize = 0;
6319 ssize_t linelen;
6321 switch (status) {
6322 case GOT_STATUS_ADD:
6323 printf("A %s\n%s this addition? [y/n] ", path, action);
6324 break;
6325 case GOT_STATUS_DELETE:
6326 printf("D %s\n%s this deletion? [y/n] ", path, action);
6327 break;
6328 case GOT_STATUS_MODIFY:
6329 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6330 return got_error_from_errno("fseek");
6331 printf(GOT_COMMIT_SEP_STR);
6332 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6333 printf("%s", line);
6334 if (ferror(patch_file))
6335 return got_error_from_errno("getline");
6336 printf(GOT_COMMIT_SEP_STR);
6337 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6338 path, n, nchanges, action);
6339 break;
6340 default:
6341 return got_error_path(path, GOT_ERR_FILE_STATUS);
6344 return NULL;
6347 static const struct got_error *
6348 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6349 FILE *patch_file, int n, int nchanges)
6351 const struct got_error *err = NULL;
6352 char *line = NULL;
6353 size_t linesize = 0;
6354 ssize_t linelen;
6355 int resp = ' ';
6356 struct choose_patch_arg *a = arg;
6358 *choice = GOT_PATCH_CHOICE_NONE;
6360 if (a->patch_script_file) {
6361 char *nl;
6362 err = show_change(status, path, patch_file, n, nchanges,
6363 a->action);
6364 if (err)
6365 return err;
6366 linelen = getline(&line, &linesize, a->patch_script_file);
6367 if (linelen == -1) {
6368 if (ferror(a->patch_script_file))
6369 return got_error_from_errno("getline");
6370 return NULL;
6372 nl = strchr(line, '\n');
6373 if (nl)
6374 *nl = '\0';
6375 if (strcmp(line, "y") == 0) {
6376 *choice = GOT_PATCH_CHOICE_YES;
6377 printf("y\n");
6378 } else if (strcmp(line, "n") == 0) {
6379 *choice = GOT_PATCH_CHOICE_NO;
6380 printf("n\n");
6381 } else if (strcmp(line, "q") == 0 &&
6382 status == GOT_STATUS_MODIFY) {
6383 *choice = GOT_PATCH_CHOICE_QUIT;
6384 printf("q\n");
6385 } else
6386 printf("invalid response '%s'\n", line);
6387 free(line);
6388 return NULL;
6391 while (resp != 'y' && resp != 'n' && resp != 'q') {
6392 err = show_change(status, path, patch_file, n, nchanges,
6393 a->action);
6394 if (err)
6395 return err;
6396 resp = getchar();
6397 if (resp == '\n')
6398 resp = getchar();
6399 if (status == GOT_STATUS_MODIFY) {
6400 if (resp != 'y' && resp != 'n' && resp != 'q') {
6401 printf("invalid response '%c'\n", resp);
6402 resp = ' ';
6404 } else if (resp != 'y' && resp != 'n') {
6405 printf("invalid response '%c'\n", resp);
6406 resp = ' ';
6410 if (resp == 'y')
6411 *choice = GOT_PATCH_CHOICE_YES;
6412 else if (resp == 'n')
6413 *choice = GOT_PATCH_CHOICE_NO;
6414 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6415 *choice = GOT_PATCH_CHOICE_QUIT;
6417 return NULL;
6421 static const struct got_error *
6422 cmd_revert(int argc, char *argv[])
6424 const struct got_error *error = NULL;
6425 struct got_worktree *worktree = NULL;
6426 struct got_repository *repo = NULL;
6427 char *cwd = NULL, *path = NULL;
6428 struct got_pathlist_head paths;
6429 struct got_pathlist_entry *pe;
6430 int ch, can_recurse = 0, pflag = 0;
6431 FILE *patch_script_file = NULL;
6432 const char *patch_script_path = NULL;
6433 struct choose_patch_arg cpa;
6435 TAILQ_INIT(&paths);
6437 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6438 switch (ch) {
6439 case 'p':
6440 pflag = 1;
6441 break;
6442 case 'F':
6443 patch_script_path = optarg;
6444 break;
6445 case 'R':
6446 can_recurse = 1;
6447 break;
6448 default:
6449 usage_revert();
6450 /* NOTREACHED */
6454 argc -= optind;
6455 argv += optind;
6457 #ifndef PROFILE
6458 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6459 "unveil", NULL) == -1)
6460 err(1, "pledge");
6461 #endif
6462 if (argc < 1)
6463 usage_revert();
6464 if (patch_script_path && !pflag)
6465 errx(1, "-F option can only be used together with -p option");
6467 cwd = getcwd(NULL, 0);
6468 if (cwd == NULL) {
6469 error = got_error_from_errno("getcwd");
6470 goto done;
6472 error = got_worktree_open(&worktree, cwd);
6473 if (error) {
6474 if (error->code == GOT_ERR_NOT_WORKTREE)
6475 error = wrap_not_worktree_error(error, "revert", cwd);
6476 goto done;
6479 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6480 NULL);
6481 if (error != NULL)
6482 goto done;
6484 if (patch_script_path) {
6485 patch_script_file = fopen(patch_script_path, "r");
6486 if (patch_script_file == NULL) {
6487 error = got_error_from_errno2("fopen",
6488 patch_script_path);
6489 goto done;
6492 error = apply_unveil(got_repo_get_path(repo), 1,
6493 got_worktree_get_root_path(worktree));
6494 if (error)
6495 goto done;
6497 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6498 if (error)
6499 goto done;
6501 if (!can_recurse) {
6502 char *ondisk_path;
6503 struct stat sb;
6504 TAILQ_FOREACH(pe, &paths, entry) {
6505 if (asprintf(&ondisk_path, "%s/%s",
6506 got_worktree_get_root_path(worktree),
6507 pe->path) == -1) {
6508 error = got_error_from_errno("asprintf");
6509 goto done;
6511 if (lstat(ondisk_path, &sb) == -1) {
6512 if (errno == ENOENT) {
6513 free(ondisk_path);
6514 continue;
6516 error = got_error_from_errno2("lstat",
6517 ondisk_path);
6518 free(ondisk_path);
6519 goto done;
6521 free(ondisk_path);
6522 if (S_ISDIR(sb.st_mode)) {
6523 error = got_error_msg(GOT_ERR_BAD_PATH,
6524 "reverting directories requires -R option");
6525 goto done;
6530 cpa.patch_script_file = patch_script_file;
6531 cpa.action = "revert";
6532 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6533 pflag ? choose_patch : NULL, &cpa, repo);
6534 done:
6535 if (patch_script_file && fclose(patch_script_file) == EOF &&
6536 error == NULL)
6537 error = got_error_from_errno2("fclose", patch_script_path);
6538 if (repo)
6539 got_repo_close(repo);
6540 if (worktree)
6541 got_worktree_close(worktree);
6542 free(path);
6543 free(cwd);
6544 return error;
6547 __dead static void
6548 usage_commit(void)
6550 fprintf(stderr, "usage: %s commit [-m msg] [-S] [path ...]\n",
6551 getprogname());
6552 exit(1);
6555 struct collect_commit_logmsg_arg {
6556 const char *cmdline_log;
6557 const char *editor;
6558 const char *worktree_path;
6559 const char *branch_name;
6560 const char *repo_path;
6561 char *logmsg_path;
6565 static const struct got_error *
6566 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6567 void *arg)
6569 char *initial_content = NULL;
6570 struct got_pathlist_entry *pe;
6571 const struct got_error *err = NULL;
6572 char *template = NULL;
6573 struct collect_commit_logmsg_arg *a = arg;
6574 int initial_content_len;
6575 int fd = -1;
6576 size_t len;
6578 /* if a message was specified on the command line, just use it */
6579 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6580 len = strlen(a->cmdline_log) + 1;
6581 *logmsg = malloc(len + 1);
6582 if (*logmsg == NULL)
6583 return got_error_from_errno("malloc");
6584 strlcpy(*logmsg, a->cmdline_log, len);
6585 return NULL;
6588 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6589 return got_error_from_errno("asprintf");
6591 initial_content_len = asprintf(&initial_content,
6592 "\n# changes to be committed on branch %s:\n",
6593 a->branch_name);
6594 if (initial_content_len == -1)
6595 return got_error_from_errno("asprintf");
6597 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6598 if (err)
6599 goto done;
6601 if (write(fd, initial_content, initial_content_len) == -1) {
6602 err = got_error_from_errno2("write", a->logmsg_path);
6603 goto done;
6606 TAILQ_FOREACH(pe, commitable_paths, entry) {
6607 struct got_commitable *ct = pe->data;
6608 dprintf(fd, "# %c %s\n",
6609 got_commitable_get_status(ct),
6610 got_commitable_get_path(ct));
6613 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
6614 done:
6615 free(initial_content);
6616 free(template);
6618 if (fd != -1 && close(fd) == -1 && err == NULL)
6619 err = got_error_from_errno2("close", a->logmsg_path);
6621 /* Editor is done; we can now apply unveil(2) */
6622 if (err == NULL)
6623 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6624 if (err) {
6625 free(*logmsg);
6626 *logmsg = NULL;
6628 return err;
6631 static const struct got_error *
6632 cmd_commit(int argc, char *argv[])
6634 const struct got_error *error = NULL;
6635 struct got_worktree *worktree = NULL;
6636 struct got_repository *repo = NULL;
6637 char *cwd = NULL, *id_str = NULL;
6638 struct got_object_id *id = NULL;
6639 const char *logmsg = NULL;
6640 struct collect_commit_logmsg_arg cl_arg;
6641 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6642 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6643 int allow_bad_symlinks = 0;
6644 struct got_pathlist_head paths;
6646 TAILQ_INIT(&paths);
6647 cl_arg.logmsg_path = NULL;
6649 while ((ch = getopt(argc, argv, "m:S")) != -1) {
6650 switch (ch) {
6651 case 'm':
6652 logmsg = optarg;
6653 break;
6654 case 'S':
6655 allow_bad_symlinks = 1;
6656 break;
6657 default:
6658 usage_commit();
6659 /* NOTREACHED */
6663 argc -= optind;
6664 argv += optind;
6666 #ifndef PROFILE
6667 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6668 "unveil", NULL) == -1)
6669 err(1, "pledge");
6670 #endif
6671 cwd = getcwd(NULL, 0);
6672 if (cwd == NULL) {
6673 error = got_error_from_errno("getcwd");
6674 goto done;
6676 error = got_worktree_open(&worktree, cwd);
6677 if (error) {
6678 if (error->code == GOT_ERR_NOT_WORKTREE)
6679 error = wrap_not_worktree_error(error, "commit", cwd);
6680 goto done;
6683 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6684 if (error)
6685 goto done;
6686 if (rebase_in_progress) {
6687 error = got_error(GOT_ERR_REBASING);
6688 goto done;
6691 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6692 worktree);
6693 if (error)
6694 goto done;
6696 error = get_gitconfig_path(&gitconfig_path);
6697 if (error)
6698 goto done;
6699 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6700 gitconfig_path);
6701 if (error != NULL)
6702 goto done;
6704 error = get_author(&author, repo, worktree);
6705 if (error)
6706 return error;
6709 * unveil(2) traverses exec(2); if an editor is used we have
6710 * to apply unveil after the log message has been written.
6712 if (logmsg == NULL || strlen(logmsg) == 0)
6713 error = get_editor(&editor);
6714 else
6715 error = apply_unveil(got_repo_get_path(repo), 0,
6716 got_worktree_get_root_path(worktree));
6717 if (error)
6718 goto done;
6720 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6721 if (error)
6722 goto done;
6724 cl_arg.editor = editor;
6725 cl_arg.cmdline_log = logmsg;
6726 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6727 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6728 if (!histedit_in_progress) {
6729 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6730 error = got_error(GOT_ERR_COMMIT_BRANCH);
6731 goto done;
6733 cl_arg.branch_name += 11;
6735 cl_arg.repo_path = got_repo_get_path(repo);
6736 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6737 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
6738 print_status, NULL, repo);
6739 if (error) {
6740 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6741 cl_arg.logmsg_path != NULL)
6742 preserve_logmsg = 1;
6743 goto done;
6746 error = got_object_id_str(&id_str, id);
6747 if (error)
6748 goto done;
6749 printf("Created commit %s\n", id_str);
6750 done:
6751 if (preserve_logmsg) {
6752 fprintf(stderr, "%s: log message preserved in %s\n",
6753 getprogname(), cl_arg.logmsg_path);
6754 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6755 error == NULL)
6756 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6757 free(cl_arg.logmsg_path);
6758 if (repo)
6759 got_repo_close(repo);
6760 if (worktree)
6761 got_worktree_close(worktree);
6762 free(cwd);
6763 free(id_str);
6764 free(gitconfig_path);
6765 free(editor);
6766 free(author);
6767 return error;
6770 __dead static void
6771 usage_cherrypick(void)
6773 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6774 exit(1);
6777 static const struct got_error *
6778 cmd_cherrypick(int argc, char *argv[])
6780 const struct got_error *error = NULL;
6781 struct got_worktree *worktree = NULL;
6782 struct got_repository *repo = NULL;
6783 char *cwd = NULL, *commit_id_str = NULL;
6784 struct got_object_id *commit_id = NULL;
6785 struct got_commit_object *commit = NULL;
6786 struct got_object_qid *pid;
6787 struct got_reference *head_ref = NULL;
6788 int ch;
6789 struct got_update_progress_arg upa;
6791 while ((ch = getopt(argc, argv, "")) != -1) {
6792 switch (ch) {
6793 default:
6794 usage_cherrypick();
6795 /* NOTREACHED */
6799 argc -= optind;
6800 argv += optind;
6802 #ifndef PROFILE
6803 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6804 "unveil", NULL) == -1)
6805 err(1, "pledge");
6806 #endif
6807 if (argc != 1)
6808 usage_cherrypick();
6810 cwd = getcwd(NULL, 0);
6811 if (cwd == NULL) {
6812 error = got_error_from_errno("getcwd");
6813 goto done;
6815 error = got_worktree_open(&worktree, cwd);
6816 if (error) {
6817 if (error->code == GOT_ERR_NOT_WORKTREE)
6818 error = wrap_not_worktree_error(error, "cherrypick",
6819 cwd);
6820 goto done;
6823 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6824 NULL);
6825 if (error != NULL)
6826 goto done;
6828 error = apply_unveil(got_repo_get_path(repo), 0,
6829 got_worktree_get_root_path(worktree));
6830 if (error)
6831 goto done;
6833 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6834 GOT_OBJ_TYPE_COMMIT, repo);
6835 if (error != NULL) {
6836 struct got_reference *ref;
6837 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6838 goto done;
6839 error = got_ref_open(&ref, repo, argv[0], 0);
6840 if (error != NULL)
6841 goto done;
6842 error = got_ref_resolve(&commit_id, repo, ref);
6843 got_ref_close(ref);
6844 if (error != NULL)
6845 goto done;
6847 error = got_object_id_str(&commit_id_str, commit_id);
6848 if (error)
6849 goto done;
6851 error = got_ref_open(&head_ref, repo,
6852 got_worktree_get_head_ref_name(worktree), 0);
6853 if (error != NULL)
6854 goto done;
6856 error = check_same_branch(commit_id, head_ref, NULL, repo);
6857 if (error) {
6858 if (error->code != GOT_ERR_ANCESTRY)
6859 goto done;
6860 error = NULL;
6861 } else {
6862 error = got_error(GOT_ERR_SAME_BRANCH);
6863 goto done;
6866 error = got_object_open_as_commit(&commit, repo, commit_id);
6867 if (error)
6868 goto done;
6869 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6870 memset(&upa, 0, sizeof(upa));
6871 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
6872 commit_id, repo, update_progress, &upa, check_cancelled,
6873 NULL);
6874 if (error != NULL)
6875 goto done;
6877 if (upa.did_something)
6878 printf("Merged commit %s\n", commit_id_str);
6879 print_update_progress_stats(&upa);
6880 done:
6881 if (commit)
6882 got_object_commit_close(commit);
6883 free(commit_id_str);
6884 if (head_ref)
6885 got_ref_close(head_ref);
6886 if (worktree)
6887 got_worktree_close(worktree);
6888 if (repo)
6889 got_repo_close(repo);
6890 return error;
6893 __dead static void
6894 usage_backout(void)
6896 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
6897 exit(1);
6900 static const struct got_error *
6901 cmd_backout(int argc, char *argv[])
6903 const struct got_error *error = NULL;
6904 struct got_worktree *worktree = NULL;
6905 struct got_repository *repo = NULL;
6906 char *cwd = NULL, *commit_id_str = NULL;
6907 struct got_object_id *commit_id = NULL;
6908 struct got_commit_object *commit = NULL;
6909 struct got_object_qid *pid;
6910 struct got_reference *head_ref = NULL;
6911 int ch;
6912 struct got_update_progress_arg upa;
6914 while ((ch = getopt(argc, argv, "")) != -1) {
6915 switch (ch) {
6916 default:
6917 usage_backout();
6918 /* NOTREACHED */
6922 argc -= optind;
6923 argv += optind;
6925 #ifndef PROFILE
6926 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6927 "unveil", NULL) == -1)
6928 err(1, "pledge");
6929 #endif
6930 if (argc != 1)
6931 usage_backout();
6933 cwd = getcwd(NULL, 0);
6934 if (cwd == NULL) {
6935 error = got_error_from_errno("getcwd");
6936 goto done;
6938 error = got_worktree_open(&worktree, cwd);
6939 if (error) {
6940 if (error->code == GOT_ERR_NOT_WORKTREE)
6941 error = wrap_not_worktree_error(error, "backout", cwd);
6942 goto done;
6945 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6946 NULL);
6947 if (error != NULL)
6948 goto done;
6950 error = apply_unveil(got_repo_get_path(repo), 0,
6951 got_worktree_get_root_path(worktree));
6952 if (error)
6953 goto done;
6955 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6956 GOT_OBJ_TYPE_COMMIT, repo);
6957 if (error != NULL) {
6958 struct got_reference *ref;
6959 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6960 goto done;
6961 error = got_ref_open(&ref, repo, argv[0], 0);
6962 if (error != NULL)
6963 goto done;
6964 error = got_ref_resolve(&commit_id, repo, ref);
6965 got_ref_close(ref);
6966 if (error != NULL)
6967 goto done;
6969 error = got_object_id_str(&commit_id_str, commit_id);
6970 if (error)
6971 goto done;
6973 error = got_ref_open(&head_ref, repo,
6974 got_worktree_get_head_ref_name(worktree), 0);
6975 if (error != NULL)
6976 goto done;
6978 error = check_same_branch(commit_id, head_ref, NULL, repo);
6979 if (error)
6980 goto done;
6982 error = got_object_open_as_commit(&commit, repo, commit_id);
6983 if (error)
6984 goto done;
6985 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6986 if (pid == NULL) {
6987 error = got_error(GOT_ERR_ROOT_COMMIT);
6988 goto done;
6991 memset(&upa, 0, sizeof(upa));
6992 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
6993 update_progress, &upa, check_cancelled, NULL);
6994 if (error != NULL)
6995 goto done;
6997 if (upa.did_something)
6998 printf("Backed out commit %s\n", commit_id_str);
6999 print_update_progress_stats(&upa);
7000 done:
7001 if (commit)
7002 got_object_commit_close(commit);
7003 free(commit_id_str);
7004 if (head_ref)
7005 got_ref_close(head_ref);
7006 if (worktree)
7007 got_worktree_close(worktree);
7008 if (repo)
7009 got_repo_close(repo);
7010 return error;
7013 __dead static void
7014 usage_rebase(void)
7016 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
7017 getprogname());
7018 exit(1);
7021 void
7022 trim_logmsg(char *logmsg, int limit)
7024 char *nl;
7025 size_t len;
7027 len = strlen(logmsg);
7028 if (len > limit)
7029 len = limit;
7030 logmsg[len] = '\0';
7031 nl = strchr(logmsg, '\n');
7032 if (nl)
7033 *nl = '\0';
7036 static const struct got_error *
7037 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
7039 const struct got_error *err;
7040 char *logmsg0 = NULL;
7041 const char *s;
7043 err = got_object_commit_get_logmsg(&logmsg0, commit);
7044 if (err)
7045 return err;
7047 s = logmsg0;
7048 while (isspace((unsigned char)s[0]))
7049 s++;
7051 *logmsg = strdup(s);
7052 if (*logmsg == NULL) {
7053 err = got_error_from_errno("strdup");
7054 goto done;
7057 trim_logmsg(*logmsg, limit);
7058 done:
7059 free(logmsg0);
7060 return err;
7063 static const struct got_error *
7064 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
7066 const struct got_error *err;
7067 struct got_commit_object *commit = NULL;
7068 char *id_str = NULL, *logmsg = NULL;
7070 err = got_object_open_as_commit(&commit, repo, id);
7071 if (err)
7072 return err;
7074 err = got_object_id_str(&id_str, id);
7075 if (err)
7076 goto done;
7078 id_str[12] = '\0';
7080 err = get_short_logmsg(&logmsg, 42, commit);
7081 if (err)
7082 goto done;
7084 printf("%s -> merge conflict: %s\n", id_str, logmsg);
7085 done:
7086 free(id_str);
7087 got_object_commit_close(commit);
7088 free(logmsg);
7089 return err;
7092 static const struct got_error *
7093 show_rebase_progress(struct got_commit_object *commit,
7094 struct got_object_id *old_id, struct got_object_id *new_id)
7096 const struct got_error *err;
7097 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7099 err = got_object_id_str(&old_id_str, old_id);
7100 if (err)
7101 goto done;
7103 if (new_id) {
7104 err = got_object_id_str(&new_id_str, new_id);
7105 if (err)
7106 goto done;
7109 old_id_str[12] = '\0';
7110 if (new_id_str)
7111 new_id_str[12] = '\0';
7113 err = get_short_logmsg(&logmsg, 42, commit);
7114 if (err)
7115 goto done;
7117 printf("%s -> %s: %s\n", old_id_str,
7118 new_id_str ? new_id_str : "no-op change", logmsg);
7119 done:
7120 free(old_id_str);
7121 free(new_id_str);
7122 free(logmsg);
7123 return err;
7126 static const struct got_error *
7127 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
7128 struct got_reference *branch, struct got_reference *new_base_branch,
7129 struct got_reference *tmp_branch, struct got_repository *repo)
7131 printf("Switching work tree to %s\n", got_ref_get_name(branch));
7132 return got_worktree_rebase_complete(worktree, fileindex,
7133 new_base_branch, tmp_branch, branch, repo);
7136 static const struct got_error *
7137 rebase_commit(struct got_pathlist_head *merged_paths,
7138 struct got_worktree *worktree, struct got_fileindex *fileindex,
7139 struct got_reference *tmp_branch,
7140 struct got_object_id *commit_id, struct got_repository *repo)
7142 const struct got_error *error;
7143 struct got_commit_object *commit;
7144 struct got_object_id *new_commit_id;
7146 error = got_object_open_as_commit(&commit, repo, commit_id);
7147 if (error)
7148 return error;
7150 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
7151 worktree, fileindex, tmp_branch, commit, commit_id, repo);
7152 if (error) {
7153 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
7154 goto done;
7155 error = show_rebase_progress(commit, commit_id, NULL);
7156 } else {
7157 error = show_rebase_progress(commit, commit_id, new_commit_id);
7158 free(new_commit_id);
7160 done:
7161 got_object_commit_close(commit);
7162 return error;
7165 struct check_path_prefix_arg {
7166 const char *path_prefix;
7167 size_t len;
7168 int errcode;
7171 static const struct got_error *
7172 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
7173 struct got_blob_object *blob2, struct got_object_id *id1,
7174 struct got_object_id *id2, const char *path1, const char *path2,
7175 mode_t mode1, mode_t mode2, struct got_repository *repo)
7177 struct check_path_prefix_arg *a = arg;
7179 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
7180 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
7181 return got_error(a->errcode);
7183 return NULL;
7186 static const struct got_error *
7187 check_path_prefix(struct got_object_id *parent_id,
7188 struct got_object_id *commit_id, const char *path_prefix,
7189 int errcode, struct got_repository *repo)
7191 const struct got_error *err;
7192 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7193 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7194 struct check_path_prefix_arg cpp_arg;
7196 if (got_path_is_root_dir(path_prefix))
7197 return NULL;
7199 err = got_object_open_as_commit(&commit, repo, commit_id);
7200 if (err)
7201 goto done;
7203 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7204 if (err)
7205 goto done;
7207 err = got_object_open_as_tree(&tree1, repo,
7208 got_object_commit_get_tree_id(parent_commit));
7209 if (err)
7210 goto done;
7212 err = got_object_open_as_tree(&tree2, repo,
7213 got_object_commit_get_tree_id(commit));
7214 if (err)
7215 goto done;
7217 cpp_arg.path_prefix = path_prefix;
7218 while (cpp_arg.path_prefix[0] == '/')
7219 cpp_arg.path_prefix++;
7220 cpp_arg.len = strlen(cpp_arg.path_prefix);
7221 cpp_arg.errcode = errcode;
7222 err = got_diff_tree(tree1, tree2, "", "", repo,
7223 check_path_prefix_in_diff, &cpp_arg, 0);
7224 done:
7225 if (tree1)
7226 got_object_tree_close(tree1);
7227 if (tree2)
7228 got_object_tree_close(tree2);
7229 if (commit)
7230 got_object_commit_close(commit);
7231 if (parent_commit)
7232 got_object_commit_close(parent_commit);
7233 return err;
7236 static const struct got_error *
7237 collect_commits(struct got_object_id_queue *commits,
7238 struct got_object_id *initial_commit_id,
7239 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7240 const char *path_prefix, int path_prefix_errcode,
7241 struct got_repository *repo)
7243 const struct got_error *err = NULL;
7244 struct got_commit_graph *graph = NULL;
7245 struct got_object_id *parent_id = NULL;
7246 struct got_object_qid *qid;
7247 struct got_object_id *commit_id = initial_commit_id;
7249 err = got_commit_graph_open(&graph, "/", 1);
7250 if (err)
7251 return err;
7253 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7254 check_cancelled, NULL);
7255 if (err)
7256 goto done;
7257 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7258 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7259 check_cancelled, NULL);
7260 if (err) {
7261 if (err->code == GOT_ERR_ITER_COMPLETED) {
7262 err = got_error_msg(GOT_ERR_ANCESTRY,
7263 "ran out of commits to rebase before "
7264 "youngest common ancestor commit has "
7265 "been reached?!?");
7267 goto done;
7268 } else {
7269 err = check_path_prefix(parent_id, commit_id,
7270 path_prefix, path_prefix_errcode, repo);
7271 if (err)
7272 goto done;
7274 err = got_object_qid_alloc(&qid, commit_id);
7275 if (err)
7276 goto done;
7277 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
7278 commit_id = parent_id;
7281 done:
7282 got_commit_graph_close(graph);
7283 return err;
7286 static const struct got_error *
7287 cmd_rebase(int argc, char *argv[])
7289 const struct got_error *error = NULL;
7290 struct got_worktree *worktree = NULL;
7291 struct got_repository *repo = NULL;
7292 struct got_fileindex *fileindex = NULL;
7293 char *cwd = NULL;
7294 struct got_reference *branch = NULL;
7295 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
7296 struct got_object_id *commit_id = NULL, *parent_id = NULL;
7297 struct got_object_id *resume_commit_id = NULL;
7298 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
7299 struct got_commit_object *commit = NULL;
7300 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
7301 int histedit_in_progress = 0;
7302 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7303 struct got_object_id_queue commits;
7304 struct got_pathlist_head merged_paths;
7305 const struct got_object_id_queue *parent_ids;
7306 struct got_object_qid *qid, *pid;
7308 SIMPLEQ_INIT(&commits);
7309 TAILQ_INIT(&merged_paths);
7311 while ((ch = getopt(argc, argv, "ac")) != -1) {
7312 switch (ch) {
7313 case 'a':
7314 abort_rebase = 1;
7315 break;
7316 case 'c':
7317 continue_rebase = 1;
7318 break;
7319 default:
7320 usage_rebase();
7321 /* NOTREACHED */
7325 argc -= optind;
7326 argv += optind;
7328 #ifndef PROFILE
7329 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7330 "unveil", NULL) == -1)
7331 err(1, "pledge");
7332 #endif
7333 if (abort_rebase && continue_rebase)
7334 usage_rebase();
7335 else if (abort_rebase || continue_rebase) {
7336 if (argc != 0)
7337 usage_rebase();
7338 } else if (argc != 1)
7339 usage_rebase();
7341 cwd = getcwd(NULL, 0);
7342 if (cwd == NULL) {
7343 error = got_error_from_errno("getcwd");
7344 goto done;
7346 error = got_worktree_open(&worktree, cwd);
7347 if (error) {
7348 if (error->code == GOT_ERR_NOT_WORKTREE)
7349 error = wrap_not_worktree_error(error, "rebase", cwd);
7350 goto done;
7353 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7354 NULL);
7355 if (error != NULL)
7356 goto done;
7358 error = apply_unveil(got_repo_get_path(repo), 0,
7359 got_worktree_get_root_path(worktree));
7360 if (error)
7361 goto done;
7363 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7364 worktree);
7365 if (error)
7366 goto done;
7367 if (histedit_in_progress) {
7368 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7369 goto done;
7372 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7373 if (error)
7374 goto done;
7376 if (abort_rebase) {
7377 struct got_update_progress_arg upa;
7378 if (!rebase_in_progress) {
7379 error = got_error(GOT_ERR_NOT_REBASING);
7380 goto done;
7382 error = got_worktree_rebase_continue(&resume_commit_id,
7383 &new_base_branch, &tmp_branch, &branch, &fileindex,
7384 worktree, repo);
7385 if (error)
7386 goto done;
7387 printf("Switching work tree to %s\n",
7388 got_ref_get_symref_target(new_base_branch));
7389 memset(&upa, 0, sizeof(upa));
7390 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7391 new_base_branch, update_progress, &upa);
7392 if (error)
7393 goto done;
7394 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7395 print_update_progress_stats(&upa);
7396 goto done; /* nothing else to do */
7399 if (continue_rebase) {
7400 if (!rebase_in_progress) {
7401 error = got_error(GOT_ERR_NOT_REBASING);
7402 goto done;
7404 error = got_worktree_rebase_continue(&resume_commit_id,
7405 &new_base_branch, &tmp_branch, &branch, &fileindex,
7406 worktree, repo);
7407 if (error)
7408 goto done;
7410 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7411 resume_commit_id, repo);
7412 if (error)
7413 goto done;
7415 yca_id = got_object_id_dup(resume_commit_id);
7416 if (yca_id == NULL) {
7417 error = got_error_from_errno("got_object_id_dup");
7418 goto done;
7420 } else {
7421 error = got_ref_open(&branch, repo, argv[0], 0);
7422 if (error != NULL)
7423 goto done;
7426 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7427 if (error)
7428 goto done;
7430 if (!continue_rebase) {
7431 struct got_object_id *base_commit_id;
7433 base_commit_id = got_worktree_get_base_commit_id(worktree);
7434 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7435 base_commit_id, branch_head_commit_id, repo,
7436 check_cancelled, NULL);
7437 if (error)
7438 goto done;
7439 if (yca_id == NULL) {
7440 error = got_error_msg(GOT_ERR_ANCESTRY,
7441 "specified branch shares no common ancestry "
7442 "with work tree's branch");
7443 goto done;
7446 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7447 if (error) {
7448 if (error->code != GOT_ERR_ANCESTRY)
7449 goto done;
7450 error = NULL;
7451 } else {
7452 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7453 "specified branch resolves to a commit which "
7454 "is already contained in work tree's branch");
7455 goto done;
7457 error = got_worktree_rebase_prepare(&new_base_branch,
7458 &tmp_branch, &fileindex, worktree, branch, repo);
7459 if (error)
7460 goto done;
7463 commit_id = branch_head_commit_id;
7464 error = got_object_open_as_commit(&commit, repo, commit_id);
7465 if (error)
7466 goto done;
7468 parent_ids = got_object_commit_get_parent_ids(commit);
7469 pid = SIMPLEQ_FIRST(parent_ids);
7470 if (pid == NULL) {
7471 if (!continue_rebase) {
7472 struct got_update_progress_arg upa;
7473 memset(&upa, 0, sizeof(upa));
7474 error = got_worktree_rebase_abort(worktree, fileindex,
7475 repo, new_base_branch, update_progress, &upa);
7476 if (error)
7477 goto done;
7478 printf("Rebase of %s aborted\n",
7479 got_ref_get_name(branch));
7480 print_update_progress_stats(&upa);
7483 error = got_error(GOT_ERR_EMPTY_REBASE);
7484 goto done;
7486 error = collect_commits(&commits, commit_id, pid->id,
7487 yca_id, got_worktree_get_path_prefix(worktree),
7488 GOT_ERR_REBASE_PATH, repo);
7489 got_object_commit_close(commit);
7490 commit = NULL;
7491 if (error)
7492 goto done;
7494 if (SIMPLEQ_EMPTY(&commits)) {
7495 if (continue_rebase) {
7496 error = rebase_complete(worktree, fileindex,
7497 branch, new_base_branch, tmp_branch, repo);
7498 goto done;
7499 } else {
7500 /* Fast-forward the reference of the branch. */
7501 struct got_object_id *new_head_commit_id;
7502 char *id_str;
7503 error = got_ref_resolve(&new_head_commit_id, repo,
7504 new_base_branch);
7505 if (error)
7506 goto done;
7507 error = got_object_id_str(&id_str, new_head_commit_id);
7508 printf("Forwarding %s to commit %s\n",
7509 got_ref_get_name(branch), id_str);
7510 free(id_str);
7511 error = got_ref_change_ref(branch,
7512 new_head_commit_id);
7513 if (error)
7514 goto done;
7518 pid = NULL;
7519 SIMPLEQ_FOREACH(qid, &commits, entry) {
7520 struct got_update_progress_arg upa;
7522 commit_id = qid->id;
7523 parent_id = pid ? pid->id : yca_id;
7524 pid = qid;
7526 memset(&upa, 0, sizeof(upa));
7527 error = got_worktree_rebase_merge_files(&merged_paths,
7528 worktree, fileindex, parent_id, commit_id, repo,
7529 update_progress, &upa, check_cancelled, NULL);
7530 if (error)
7531 goto done;
7533 print_update_progress_stats(&upa);
7534 if (upa.conflicts > 0)
7535 rebase_status = GOT_STATUS_CONFLICT;
7537 if (rebase_status == GOT_STATUS_CONFLICT) {
7538 error = show_rebase_merge_conflict(qid->id, repo);
7539 if (error)
7540 goto done;
7541 got_worktree_rebase_pathlist_free(&merged_paths);
7542 break;
7545 error = rebase_commit(&merged_paths, worktree, fileindex,
7546 tmp_branch, commit_id, repo);
7547 got_worktree_rebase_pathlist_free(&merged_paths);
7548 if (error)
7549 goto done;
7552 if (rebase_status == GOT_STATUS_CONFLICT) {
7553 error = got_worktree_rebase_postpone(worktree, fileindex);
7554 if (error)
7555 goto done;
7556 error = got_error_msg(GOT_ERR_CONFLICTS,
7557 "conflicts must be resolved before rebasing can continue");
7558 } else
7559 error = rebase_complete(worktree, fileindex, branch,
7560 new_base_branch, tmp_branch, repo);
7561 done:
7562 got_object_id_queue_free(&commits);
7563 free(branch_head_commit_id);
7564 free(resume_commit_id);
7565 free(yca_id);
7566 if (commit)
7567 got_object_commit_close(commit);
7568 if (branch)
7569 got_ref_close(branch);
7570 if (new_base_branch)
7571 got_ref_close(new_base_branch);
7572 if (tmp_branch)
7573 got_ref_close(tmp_branch);
7574 if (worktree)
7575 got_worktree_close(worktree);
7576 if (repo)
7577 got_repo_close(repo);
7578 return error;
7581 __dead static void
7582 usage_histedit(void)
7584 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
7585 getprogname());
7586 exit(1);
7589 #define GOT_HISTEDIT_PICK 'p'
7590 #define GOT_HISTEDIT_EDIT 'e'
7591 #define GOT_HISTEDIT_FOLD 'f'
7592 #define GOT_HISTEDIT_DROP 'd'
7593 #define GOT_HISTEDIT_MESG 'm'
7595 static struct got_histedit_cmd {
7596 unsigned char code;
7597 const char *name;
7598 const char *desc;
7599 } got_histedit_cmds[] = {
7600 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7601 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7602 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7603 "be used" },
7604 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7605 { GOT_HISTEDIT_MESG, "mesg",
7606 "single-line log message for commit above (open editor if empty)" },
7609 struct got_histedit_list_entry {
7610 TAILQ_ENTRY(got_histedit_list_entry) entry;
7611 struct got_object_id *commit_id;
7612 const struct got_histedit_cmd *cmd;
7613 char *logmsg;
7615 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7617 static const struct got_error *
7618 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7619 FILE *f, struct got_repository *repo)
7621 const struct got_error *err = NULL;
7622 char *logmsg = NULL, *id_str = NULL;
7623 struct got_commit_object *commit = NULL;
7624 int n;
7626 err = got_object_open_as_commit(&commit, repo, commit_id);
7627 if (err)
7628 goto done;
7630 err = get_short_logmsg(&logmsg, 34, commit);
7631 if (err)
7632 goto done;
7634 err = got_object_id_str(&id_str, commit_id);
7635 if (err)
7636 goto done;
7638 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7639 if (n < 0)
7640 err = got_ferror(f, GOT_ERR_IO);
7641 done:
7642 if (commit)
7643 got_object_commit_close(commit);
7644 free(id_str);
7645 free(logmsg);
7646 return err;
7649 static const struct got_error *
7650 histedit_write_commit_list(struct got_object_id_queue *commits,
7651 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7653 const struct got_error *err = NULL;
7654 struct got_object_qid *qid;
7656 if (SIMPLEQ_EMPTY(commits))
7657 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7659 SIMPLEQ_FOREACH(qid, commits, entry) {
7660 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7661 f, repo);
7662 if (err)
7663 break;
7664 if (edit_logmsg_only) {
7665 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7666 if (n < 0) {
7667 err = got_ferror(f, GOT_ERR_IO);
7668 break;
7673 return err;
7676 static const struct got_error *
7677 write_cmd_list(FILE *f, const char *branch_name,
7678 struct got_object_id_queue *commits)
7680 const struct got_error *err = NULL;
7681 int n, i;
7682 char *id_str;
7683 struct got_object_qid *qid;
7685 qid = SIMPLEQ_FIRST(commits);
7686 err = got_object_id_str(&id_str, qid->id);
7687 if (err)
7688 return err;
7690 n = fprintf(f,
7691 "# Editing the history of branch '%s' starting at\n"
7692 "# commit %s\n"
7693 "# Commits will be processed in order from top to "
7694 "bottom of this file.\n", branch_name, id_str);
7695 if (n < 0) {
7696 err = got_ferror(f, GOT_ERR_IO);
7697 goto done;
7700 n = fprintf(f, "# Available histedit commands:\n");
7701 if (n < 0) {
7702 err = got_ferror(f, GOT_ERR_IO);
7703 goto done;
7706 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7707 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7708 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7709 cmd->desc);
7710 if (n < 0) {
7711 err = got_ferror(f, GOT_ERR_IO);
7712 break;
7715 done:
7716 free(id_str);
7717 return err;
7720 static const struct got_error *
7721 histedit_syntax_error(int lineno)
7723 static char msg[42];
7724 int ret;
7726 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7727 lineno);
7728 if (ret == -1 || ret >= sizeof(msg))
7729 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7731 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7734 static const struct got_error *
7735 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7736 char *logmsg, struct got_repository *repo)
7738 const struct got_error *err;
7739 struct got_commit_object *folded_commit = NULL;
7740 char *id_str, *folded_logmsg = NULL;
7742 err = got_object_id_str(&id_str, hle->commit_id);
7743 if (err)
7744 return err;
7746 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7747 if (err)
7748 goto done;
7750 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7751 if (err)
7752 goto done;
7753 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7754 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7755 folded_logmsg) == -1) {
7756 err = got_error_from_errno("asprintf");
7758 done:
7759 if (folded_commit)
7760 got_object_commit_close(folded_commit);
7761 free(id_str);
7762 free(folded_logmsg);
7763 return err;
7766 static struct got_histedit_list_entry *
7767 get_folded_commits(struct got_histedit_list_entry *hle)
7769 struct got_histedit_list_entry *prev, *folded = NULL;
7771 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7772 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7773 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7774 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7775 folded = prev;
7776 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7779 return folded;
7782 static const struct got_error *
7783 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7784 struct got_repository *repo)
7786 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7787 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7788 const struct got_error *err = NULL;
7789 struct got_commit_object *commit = NULL;
7790 int logmsg_len;
7791 int fd;
7792 struct got_histedit_list_entry *folded = NULL;
7794 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7795 if (err)
7796 return err;
7798 folded = get_folded_commits(hle);
7799 if (folded) {
7800 while (folded != hle) {
7801 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7802 folded = TAILQ_NEXT(folded, entry);
7803 continue;
7805 err = append_folded_commit_msg(&new_msg, folded,
7806 logmsg, repo);
7807 if (err)
7808 goto done;
7809 free(logmsg);
7810 logmsg = new_msg;
7811 folded = TAILQ_NEXT(folded, entry);
7815 err = got_object_id_str(&id_str, hle->commit_id);
7816 if (err)
7817 goto done;
7818 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7819 if (err)
7820 goto done;
7821 logmsg_len = asprintf(&new_msg,
7822 "%s\n# original log message of commit %s: %s",
7823 logmsg ? logmsg : "", id_str, orig_logmsg);
7824 if (logmsg_len == -1) {
7825 err = got_error_from_errno("asprintf");
7826 goto done;
7828 free(logmsg);
7829 logmsg = new_msg;
7831 err = got_object_id_str(&id_str, hle->commit_id);
7832 if (err)
7833 goto done;
7835 err = got_opentemp_named_fd(&logmsg_path, &fd,
7836 GOT_TMPDIR_STR "/got-logmsg");
7837 if (err)
7838 goto done;
7840 write(fd, logmsg, logmsg_len);
7841 close(fd);
7843 err = get_editor(&editor);
7844 if (err)
7845 goto done;
7847 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
7848 if (err) {
7849 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
7850 goto done;
7851 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
7853 done:
7854 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
7855 err = got_error_from_errno2("unlink", logmsg_path);
7856 free(logmsg_path);
7857 free(logmsg);
7858 free(orig_logmsg);
7859 free(editor);
7860 if (commit)
7861 got_object_commit_close(commit);
7862 return err;
7865 static const struct got_error *
7866 histedit_parse_list(struct got_histedit_list *histedit_cmds,
7867 FILE *f, struct got_repository *repo)
7869 const struct got_error *err = NULL;
7870 char *line = NULL, *p, *end;
7871 size_t size;
7872 ssize_t len;
7873 int lineno = 0, i;
7874 const struct got_histedit_cmd *cmd;
7875 struct got_object_id *commit_id = NULL;
7876 struct got_histedit_list_entry *hle = NULL;
7878 for (;;) {
7879 len = getline(&line, &size, f);
7880 if (len == -1) {
7881 const struct got_error *getline_err;
7882 if (feof(f))
7883 break;
7884 getline_err = got_error_from_errno("getline");
7885 err = got_ferror(f, getline_err->code);
7886 break;
7888 lineno++;
7889 p = line;
7890 while (isspace((unsigned char)p[0]))
7891 p++;
7892 if (p[0] == '#' || p[0] == '\0') {
7893 free(line);
7894 line = NULL;
7895 continue;
7897 cmd = NULL;
7898 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7899 cmd = &got_histedit_cmds[i];
7900 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
7901 isspace((unsigned char)p[strlen(cmd->name)])) {
7902 p += strlen(cmd->name);
7903 break;
7905 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
7906 p++;
7907 break;
7910 if (i == nitems(got_histedit_cmds)) {
7911 err = histedit_syntax_error(lineno);
7912 break;
7914 while (isspace((unsigned char)p[0]))
7915 p++;
7916 if (cmd->code == GOT_HISTEDIT_MESG) {
7917 if (hle == NULL || hle->logmsg != NULL) {
7918 err = got_error(GOT_ERR_HISTEDIT_CMD);
7919 break;
7921 if (p[0] == '\0') {
7922 err = histedit_edit_logmsg(hle, repo);
7923 if (err)
7924 break;
7925 } else {
7926 hle->logmsg = strdup(p);
7927 if (hle->logmsg == NULL) {
7928 err = got_error_from_errno("strdup");
7929 break;
7932 free(line);
7933 line = NULL;
7934 continue;
7935 } else {
7936 end = p;
7937 while (end[0] && !isspace((unsigned char)end[0]))
7938 end++;
7939 *end = '\0';
7941 err = got_object_resolve_id_str(&commit_id, repo, p);
7942 if (err) {
7943 /* override error code */
7944 err = histedit_syntax_error(lineno);
7945 break;
7948 hle = malloc(sizeof(*hle));
7949 if (hle == NULL) {
7950 err = got_error_from_errno("malloc");
7951 break;
7953 hle->cmd = cmd;
7954 hle->commit_id = commit_id;
7955 hle->logmsg = NULL;
7956 commit_id = NULL;
7957 free(line);
7958 line = NULL;
7959 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
7962 free(line);
7963 free(commit_id);
7964 return err;
7967 static const struct got_error *
7968 histedit_check_script(struct got_histedit_list *histedit_cmds,
7969 struct got_object_id_queue *commits, struct got_repository *repo)
7971 const struct got_error *err = NULL;
7972 struct got_object_qid *qid;
7973 struct got_histedit_list_entry *hle;
7974 static char msg[92];
7975 char *id_str;
7977 if (TAILQ_EMPTY(histedit_cmds))
7978 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
7979 "histedit script contains no commands");
7980 if (SIMPLEQ_EMPTY(commits))
7981 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7983 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7984 struct got_histedit_list_entry *hle2;
7985 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
7986 if (hle == hle2)
7987 continue;
7988 if (got_object_id_cmp(hle->commit_id,
7989 hle2->commit_id) != 0)
7990 continue;
7991 err = got_object_id_str(&id_str, hle->commit_id);
7992 if (err)
7993 return err;
7994 snprintf(msg, sizeof(msg), "commit %s is listed "
7995 "more than once in histedit script", id_str);
7996 free(id_str);
7997 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8001 SIMPLEQ_FOREACH(qid, commits, entry) {
8002 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8003 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
8004 break;
8006 if (hle == NULL) {
8007 err = got_object_id_str(&id_str, qid->id);
8008 if (err)
8009 return err;
8010 snprintf(msg, sizeof(msg),
8011 "commit %s missing from histedit script", id_str);
8012 free(id_str);
8013 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8017 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
8018 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
8019 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
8020 "last commit in histedit script cannot be folded");
8022 return NULL;
8025 static const struct got_error *
8026 histedit_run_editor(struct got_histedit_list *histedit_cmds,
8027 const char *path, struct got_object_id_queue *commits,
8028 struct got_repository *repo)
8030 const struct got_error *err = NULL;
8031 char *editor;
8032 FILE *f = NULL;
8034 err = get_editor(&editor);
8035 if (err)
8036 return err;
8038 if (spawn_editor(editor, path) == -1) {
8039 err = got_error_from_errno("failed spawning editor");
8040 goto done;
8043 f = fopen(path, "r");
8044 if (f == NULL) {
8045 err = got_error_from_errno("fopen");
8046 goto done;
8048 err = histedit_parse_list(histedit_cmds, f, repo);
8049 if (err)
8050 goto done;
8052 err = histedit_check_script(histedit_cmds, commits, repo);
8053 done:
8054 if (f && fclose(f) != 0 && err == NULL)
8055 err = got_error_from_errno("fclose");
8056 free(editor);
8057 return err;
8060 static const struct got_error *
8061 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
8062 struct got_object_id_queue *, const char *, const char *,
8063 struct got_repository *);
8065 static const struct got_error *
8066 histedit_edit_script(struct got_histedit_list *histedit_cmds,
8067 struct got_object_id_queue *commits, const char *branch_name,
8068 int edit_logmsg_only, struct got_repository *repo)
8070 const struct got_error *err;
8071 FILE *f = NULL;
8072 char *path = NULL;
8074 err = got_opentemp_named(&path, &f, "got-histedit");
8075 if (err)
8076 return err;
8078 err = write_cmd_list(f, branch_name, commits);
8079 if (err)
8080 goto done;
8082 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
8083 if (err)
8084 goto done;
8086 if (edit_logmsg_only) {
8087 rewind(f);
8088 err = histedit_parse_list(histedit_cmds, f, repo);
8089 } else {
8090 if (fclose(f) != 0) {
8091 err = got_error_from_errno("fclose");
8092 goto done;
8094 f = NULL;
8095 err = histedit_run_editor(histedit_cmds, path, commits, repo);
8096 if (err) {
8097 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8098 err->code != GOT_ERR_HISTEDIT_CMD)
8099 goto done;
8100 err = histedit_edit_list_retry(histedit_cmds, err,
8101 commits, path, branch_name, repo);
8104 done:
8105 if (f && fclose(f) != 0 && err == NULL)
8106 err = got_error_from_errno("fclose");
8107 if (path && unlink(path) != 0 && err == NULL)
8108 err = got_error_from_errno2("unlink", path);
8109 free(path);
8110 return err;
8113 static const struct got_error *
8114 histedit_save_list(struct got_histedit_list *histedit_cmds,
8115 struct got_worktree *worktree, struct got_repository *repo)
8117 const struct got_error *err = NULL;
8118 char *path = NULL;
8119 FILE *f = NULL;
8120 struct got_histedit_list_entry *hle;
8121 struct got_commit_object *commit = NULL;
8123 err = got_worktree_get_histedit_script_path(&path, worktree);
8124 if (err)
8125 return err;
8127 f = fopen(path, "w");
8128 if (f == NULL) {
8129 err = got_error_from_errno2("fopen", path);
8130 goto done;
8132 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8133 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
8134 repo);
8135 if (err)
8136 break;
8138 if (hle->logmsg) {
8139 int n = fprintf(f, "%c %s\n",
8140 GOT_HISTEDIT_MESG, hle->logmsg);
8141 if (n < 0) {
8142 err = got_ferror(f, GOT_ERR_IO);
8143 break;
8147 done:
8148 if (f && fclose(f) != 0 && err == NULL)
8149 err = got_error_from_errno("fclose");
8150 free(path);
8151 if (commit)
8152 got_object_commit_close(commit);
8153 return err;
8156 void
8157 histedit_free_list(struct got_histedit_list *histedit_cmds)
8159 struct got_histedit_list_entry *hle;
8161 while ((hle = TAILQ_FIRST(histedit_cmds))) {
8162 TAILQ_REMOVE(histedit_cmds, hle, entry);
8163 free(hle);
8167 static const struct got_error *
8168 histedit_load_list(struct got_histedit_list *histedit_cmds,
8169 const char *path, struct got_repository *repo)
8171 const struct got_error *err = NULL;
8172 FILE *f = NULL;
8174 f = fopen(path, "r");
8175 if (f == NULL) {
8176 err = got_error_from_errno2("fopen", path);
8177 goto done;
8180 err = histedit_parse_list(histedit_cmds, f, repo);
8181 done:
8182 if (f && fclose(f) != 0 && err == NULL)
8183 err = got_error_from_errno("fclose");
8184 return err;
8187 static const struct got_error *
8188 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
8189 const struct got_error *edit_err, struct got_object_id_queue *commits,
8190 const char *path, const char *branch_name, struct got_repository *repo)
8192 const struct got_error *err = NULL, *prev_err = edit_err;
8193 int resp = ' ';
8195 while (resp != 'c' && resp != 'r' && resp != 'a') {
8196 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
8197 "or (a)bort: ", getprogname(), prev_err->msg);
8198 resp = getchar();
8199 if (resp == '\n')
8200 resp = getchar();
8201 if (resp == 'c') {
8202 histedit_free_list(histedit_cmds);
8203 err = histedit_run_editor(histedit_cmds, path, commits,
8204 repo);
8205 if (err) {
8206 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8207 err->code != GOT_ERR_HISTEDIT_CMD)
8208 break;
8209 prev_err = err;
8210 resp = ' ';
8211 continue;
8213 break;
8214 } else if (resp == 'r') {
8215 histedit_free_list(histedit_cmds);
8216 err = histedit_edit_script(histedit_cmds,
8217 commits, branch_name, 0, repo);
8218 if (err) {
8219 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8220 err->code != GOT_ERR_HISTEDIT_CMD)
8221 break;
8222 prev_err = err;
8223 resp = ' ';
8224 continue;
8226 break;
8227 } else if (resp == 'a') {
8228 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
8229 break;
8230 } else
8231 printf("invalid response '%c'\n", resp);
8234 return err;
8237 static const struct got_error *
8238 histedit_complete(struct got_worktree *worktree,
8239 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
8240 struct got_reference *branch, struct got_repository *repo)
8242 printf("Switching work tree to %s\n",
8243 got_ref_get_symref_target(branch));
8244 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
8245 branch, repo);
8248 static const struct got_error *
8249 show_histedit_progress(struct got_commit_object *commit,
8250 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
8252 const struct got_error *err;
8253 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8255 err = got_object_id_str(&old_id_str, hle->commit_id);
8256 if (err)
8257 goto done;
8259 if (new_id) {
8260 err = got_object_id_str(&new_id_str, new_id);
8261 if (err)
8262 goto done;
8265 old_id_str[12] = '\0';
8266 if (new_id_str)
8267 new_id_str[12] = '\0';
8269 if (hle->logmsg) {
8270 logmsg = strdup(hle->logmsg);
8271 if (logmsg == NULL) {
8272 err = got_error_from_errno("strdup");
8273 goto done;
8275 trim_logmsg(logmsg, 42);
8276 } else {
8277 err = get_short_logmsg(&logmsg, 42, commit);
8278 if (err)
8279 goto done;
8282 switch (hle->cmd->code) {
8283 case GOT_HISTEDIT_PICK:
8284 case GOT_HISTEDIT_EDIT:
8285 printf("%s -> %s: %s\n", old_id_str,
8286 new_id_str ? new_id_str : "no-op change", logmsg);
8287 break;
8288 case GOT_HISTEDIT_DROP:
8289 case GOT_HISTEDIT_FOLD:
8290 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
8291 logmsg);
8292 break;
8293 default:
8294 break;
8296 done:
8297 free(old_id_str);
8298 free(new_id_str);
8299 return err;
8302 static const struct got_error *
8303 histedit_commit(struct got_pathlist_head *merged_paths,
8304 struct got_worktree *worktree, struct got_fileindex *fileindex,
8305 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
8306 struct got_repository *repo)
8308 const struct got_error *err;
8309 struct got_commit_object *commit;
8310 struct got_object_id *new_commit_id;
8312 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
8313 && hle->logmsg == NULL) {
8314 err = histedit_edit_logmsg(hle, repo);
8315 if (err)
8316 return err;
8319 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8320 if (err)
8321 return err;
8323 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
8324 worktree, fileindex, tmp_branch, commit, hle->commit_id,
8325 hle->logmsg, repo);
8326 if (err) {
8327 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
8328 goto done;
8329 err = show_histedit_progress(commit, hle, NULL);
8330 } else {
8331 err = show_histedit_progress(commit, hle, new_commit_id);
8332 free(new_commit_id);
8334 done:
8335 got_object_commit_close(commit);
8336 return err;
8339 static const struct got_error *
8340 histedit_skip_commit(struct got_histedit_list_entry *hle,
8341 struct got_worktree *worktree, struct got_repository *repo)
8343 const struct got_error *error;
8344 struct got_commit_object *commit;
8346 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
8347 repo);
8348 if (error)
8349 return error;
8351 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
8352 if (error)
8353 return error;
8355 error = show_histedit_progress(commit, hle, NULL);
8356 got_object_commit_close(commit);
8357 return error;
8360 static const struct got_error *
8361 check_local_changes(void *arg, unsigned char status,
8362 unsigned char staged_status, const char *path,
8363 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8364 struct got_object_id *commit_id, int dirfd, const char *de_name)
8366 int *have_local_changes = arg;
8368 switch (status) {
8369 case GOT_STATUS_ADD:
8370 case GOT_STATUS_DELETE:
8371 case GOT_STATUS_MODIFY:
8372 case GOT_STATUS_CONFLICT:
8373 *have_local_changes = 1;
8374 return got_error(GOT_ERR_CANCELLED);
8375 default:
8376 break;
8379 switch (staged_status) {
8380 case GOT_STATUS_ADD:
8381 case GOT_STATUS_DELETE:
8382 case GOT_STATUS_MODIFY:
8383 *have_local_changes = 1;
8384 return got_error(GOT_ERR_CANCELLED);
8385 default:
8386 break;
8389 return NULL;
8392 static const struct got_error *
8393 cmd_histedit(int argc, char *argv[])
8395 const struct got_error *error = NULL;
8396 struct got_worktree *worktree = NULL;
8397 struct got_fileindex *fileindex = NULL;
8398 struct got_repository *repo = NULL;
8399 char *cwd = NULL;
8400 struct got_reference *branch = NULL;
8401 struct got_reference *tmp_branch = NULL;
8402 struct got_object_id *resume_commit_id = NULL;
8403 struct got_object_id *base_commit_id = NULL;
8404 struct got_object_id *head_commit_id = NULL;
8405 struct got_commit_object *commit = NULL;
8406 int ch, rebase_in_progress = 0;
8407 struct got_update_progress_arg upa;
8408 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8409 int edit_logmsg_only = 0;
8410 const char *edit_script_path = NULL;
8411 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8412 struct got_object_id_queue commits;
8413 struct got_pathlist_head merged_paths;
8414 const struct got_object_id_queue *parent_ids;
8415 struct got_object_qid *pid;
8416 struct got_histedit_list histedit_cmds;
8417 struct got_histedit_list_entry *hle;
8419 SIMPLEQ_INIT(&commits);
8420 TAILQ_INIT(&histedit_cmds);
8421 TAILQ_INIT(&merged_paths);
8422 memset(&upa, 0, sizeof(upa));
8424 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
8425 switch (ch) {
8426 case 'a':
8427 abort_edit = 1;
8428 break;
8429 case 'c':
8430 continue_edit = 1;
8431 break;
8432 case 'F':
8433 edit_script_path = optarg;
8434 break;
8435 case 'm':
8436 edit_logmsg_only = 1;
8437 break;
8438 default:
8439 usage_histedit();
8440 /* NOTREACHED */
8444 argc -= optind;
8445 argv += optind;
8447 #ifndef PROFILE
8448 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8449 "unveil", NULL) == -1)
8450 err(1, "pledge");
8451 #endif
8452 if (abort_edit && continue_edit)
8453 errx(1, "histedit's -a and -c options are mutually exclusive");
8454 if (edit_script_path && edit_logmsg_only)
8455 errx(1, "histedit's -F and -m options are mutually exclusive");
8456 if (abort_edit && edit_logmsg_only)
8457 errx(1, "histedit's -a and -m options are mutually exclusive");
8458 if (continue_edit && edit_logmsg_only)
8459 errx(1, "histedit's -c and -m options are mutually exclusive");
8460 if (argc != 0)
8461 usage_histedit();
8464 * This command cannot apply unveil(2) in all cases because the
8465 * user may choose to run an editor to edit the histedit script
8466 * and to edit individual commit log messages.
8467 * unveil(2) traverses exec(2); if an editor is used we have to
8468 * apply unveil after edit script and log messages have been written.
8469 * XXX TODO: Make use of unveil(2) where possible.
8472 cwd = getcwd(NULL, 0);
8473 if (cwd == NULL) {
8474 error = got_error_from_errno("getcwd");
8475 goto done;
8477 error = got_worktree_open(&worktree, cwd);
8478 if (error) {
8479 if (error->code == GOT_ERR_NOT_WORKTREE)
8480 error = wrap_not_worktree_error(error, "histedit", cwd);
8481 goto done;
8484 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8485 NULL);
8486 if (error != NULL)
8487 goto done;
8489 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8490 if (error)
8491 goto done;
8492 if (rebase_in_progress) {
8493 error = got_error(GOT_ERR_REBASING);
8494 goto done;
8497 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8498 if (error)
8499 goto done;
8501 if (edit_in_progress && edit_logmsg_only) {
8502 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8503 "histedit operation is in progress in this "
8504 "work tree and must be continued or aborted "
8505 "before the -m option can be used");
8506 goto done;
8509 if (edit_in_progress && abort_edit) {
8510 error = got_worktree_histedit_continue(&resume_commit_id,
8511 &tmp_branch, &branch, &base_commit_id, &fileindex,
8512 worktree, repo);
8513 if (error)
8514 goto done;
8515 printf("Switching work tree to %s\n",
8516 got_ref_get_symref_target(branch));
8517 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8518 branch, base_commit_id, update_progress, &upa);
8519 if (error)
8520 goto done;
8521 printf("Histedit of %s aborted\n",
8522 got_ref_get_symref_target(branch));
8523 print_update_progress_stats(&upa);
8524 goto done; /* nothing else to do */
8525 } else if (abort_edit) {
8526 error = got_error(GOT_ERR_NOT_HISTEDIT);
8527 goto done;
8530 if (continue_edit) {
8531 char *path;
8533 if (!edit_in_progress) {
8534 error = got_error(GOT_ERR_NOT_HISTEDIT);
8535 goto done;
8538 error = got_worktree_get_histedit_script_path(&path, worktree);
8539 if (error)
8540 goto done;
8542 error = histedit_load_list(&histedit_cmds, path, repo);
8543 free(path);
8544 if (error)
8545 goto done;
8547 error = got_worktree_histedit_continue(&resume_commit_id,
8548 &tmp_branch, &branch, &base_commit_id, &fileindex,
8549 worktree, repo);
8550 if (error)
8551 goto done;
8553 error = got_ref_resolve(&head_commit_id, repo, branch);
8554 if (error)
8555 goto done;
8557 error = got_object_open_as_commit(&commit, repo,
8558 head_commit_id);
8559 if (error)
8560 goto done;
8561 parent_ids = got_object_commit_get_parent_ids(commit);
8562 pid = SIMPLEQ_FIRST(parent_ids);
8563 if (pid == NULL) {
8564 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8565 goto done;
8567 error = collect_commits(&commits, head_commit_id, pid->id,
8568 base_commit_id, got_worktree_get_path_prefix(worktree),
8569 GOT_ERR_HISTEDIT_PATH, repo);
8570 got_object_commit_close(commit);
8571 commit = NULL;
8572 if (error)
8573 goto done;
8574 } else {
8575 if (edit_in_progress) {
8576 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8577 goto done;
8580 error = got_ref_open(&branch, repo,
8581 got_worktree_get_head_ref_name(worktree), 0);
8582 if (error != NULL)
8583 goto done;
8585 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8586 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8587 "will not edit commit history of a branch outside "
8588 "the \"refs/heads/\" reference namespace");
8589 goto done;
8592 error = got_ref_resolve(&head_commit_id, repo, branch);
8593 got_ref_close(branch);
8594 branch = NULL;
8595 if (error)
8596 goto done;
8598 error = got_object_open_as_commit(&commit, repo,
8599 head_commit_id);
8600 if (error)
8601 goto done;
8602 parent_ids = got_object_commit_get_parent_ids(commit);
8603 pid = SIMPLEQ_FIRST(parent_ids);
8604 if (pid == NULL) {
8605 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8606 goto done;
8608 error = collect_commits(&commits, head_commit_id, pid->id,
8609 got_worktree_get_base_commit_id(worktree),
8610 got_worktree_get_path_prefix(worktree),
8611 GOT_ERR_HISTEDIT_PATH, repo);
8612 got_object_commit_close(commit);
8613 commit = NULL;
8614 if (error)
8615 goto done;
8617 if (SIMPLEQ_EMPTY(&commits)) {
8618 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8619 goto done;
8622 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8623 &base_commit_id, &fileindex, worktree, repo);
8624 if (error)
8625 goto done;
8627 if (edit_script_path) {
8628 error = histedit_load_list(&histedit_cmds,
8629 edit_script_path, repo);
8630 if (error) {
8631 got_worktree_histedit_abort(worktree, fileindex,
8632 repo, branch, base_commit_id,
8633 update_progress, &upa);
8634 print_update_progress_stats(&upa);
8635 goto done;
8637 } else {
8638 const char *branch_name;
8639 branch_name = got_ref_get_symref_target(branch);
8640 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8641 branch_name += 11;
8642 error = histedit_edit_script(&histedit_cmds, &commits,
8643 branch_name, edit_logmsg_only, repo);
8644 if (error) {
8645 got_worktree_histedit_abort(worktree, fileindex,
8646 repo, branch, base_commit_id,
8647 update_progress, &upa);
8648 print_update_progress_stats(&upa);
8649 goto done;
8654 error = histedit_save_list(&histedit_cmds, worktree,
8655 repo);
8656 if (error) {
8657 got_worktree_histedit_abort(worktree, fileindex,
8658 repo, branch, base_commit_id,
8659 update_progress, &upa);
8660 print_update_progress_stats(&upa);
8661 goto done;
8666 error = histedit_check_script(&histedit_cmds, &commits, repo);
8667 if (error)
8668 goto done;
8670 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8671 if (resume_commit_id) {
8672 if (got_object_id_cmp(hle->commit_id,
8673 resume_commit_id) != 0)
8674 continue;
8676 resume_commit_id = NULL;
8677 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8678 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8679 error = histedit_skip_commit(hle, worktree,
8680 repo);
8681 if (error)
8682 goto done;
8683 } else {
8684 struct got_pathlist_head paths;
8685 int have_changes = 0;
8687 TAILQ_INIT(&paths);
8688 error = got_pathlist_append(&paths, "", NULL);
8689 if (error)
8690 goto done;
8691 error = got_worktree_status(worktree, &paths,
8692 repo, check_local_changes, &have_changes,
8693 check_cancelled, NULL);
8694 got_pathlist_free(&paths);
8695 if (error) {
8696 if (error->code != GOT_ERR_CANCELLED)
8697 goto done;
8698 if (sigint_received || sigpipe_received)
8699 goto done;
8701 if (have_changes) {
8702 error = histedit_commit(NULL, worktree,
8703 fileindex, tmp_branch, hle, repo);
8704 if (error)
8705 goto done;
8706 } else {
8707 error = got_object_open_as_commit(
8708 &commit, repo, hle->commit_id);
8709 if (error)
8710 goto done;
8711 error = show_histedit_progress(commit,
8712 hle, NULL);
8713 got_object_commit_close(commit);
8714 commit = NULL;
8715 if (error)
8716 goto done;
8719 continue;
8722 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8723 error = histedit_skip_commit(hle, worktree, repo);
8724 if (error)
8725 goto done;
8726 continue;
8729 error = got_object_open_as_commit(&commit, repo,
8730 hle->commit_id);
8731 if (error)
8732 goto done;
8733 parent_ids = got_object_commit_get_parent_ids(commit);
8734 pid = SIMPLEQ_FIRST(parent_ids);
8736 error = got_worktree_histedit_merge_files(&merged_paths,
8737 worktree, fileindex, pid->id, hle->commit_id, repo,
8738 update_progress, &upa, check_cancelled, NULL);
8739 if (error)
8740 goto done;
8741 got_object_commit_close(commit);
8742 commit = NULL;
8744 print_update_progress_stats(&upa);
8745 if (upa.conflicts > 0)
8746 rebase_status = GOT_STATUS_CONFLICT;
8748 if (rebase_status == GOT_STATUS_CONFLICT) {
8749 error = show_rebase_merge_conflict(hle->commit_id,
8750 repo);
8751 if (error)
8752 goto done;
8753 got_worktree_rebase_pathlist_free(&merged_paths);
8754 break;
8757 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8758 char *id_str;
8759 error = got_object_id_str(&id_str, hle->commit_id);
8760 if (error)
8761 goto done;
8762 printf("Stopping histedit for amending commit %s\n",
8763 id_str);
8764 free(id_str);
8765 got_worktree_rebase_pathlist_free(&merged_paths);
8766 error = got_worktree_histedit_postpone(worktree,
8767 fileindex);
8768 goto done;
8771 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8772 error = histedit_skip_commit(hle, worktree, repo);
8773 if (error)
8774 goto done;
8775 continue;
8778 error = histedit_commit(&merged_paths, worktree, fileindex,
8779 tmp_branch, hle, repo);
8780 got_worktree_rebase_pathlist_free(&merged_paths);
8781 if (error)
8782 goto done;
8785 if (rebase_status == GOT_STATUS_CONFLICT) {
8786 error = got_worktree_histedit_postpone(worktree, fileindex);
8787 if (error)
8788 goto done;
8789 error = got_error_msg(GOT_ERR_CONFLICTS,
8790 "conflicts must be resolved before histedit can continue");
8791 } else
8792 error = histedit_complete(worktree, fileindex, tmp_branch,
8793 branch, repo);
8794 done:
8795 got_object_id_queue_free(&commits);
8796 histedit_free_list(&histedit_cmds);
8797 free(head_commit_id);
8798 free(base_commit_id);
8799 free(resume_commit_id);
8800 if (commit)
8801 got_object_commit_close(commit);
8802 if (branch)
8803 got_ref_close(branch);
8804 if (tmp_branch)
8805 got_ref_close(tmp_branch);
8806 if (worktree)
8807 got_worktree_close(worktree);
8808 if (repo)
8809 got_repo_close(repo);
8810 return error;
8813 __dead static void
8814 usage_integrate(void)
8816 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
8817 exit(1);
8820 static const struct got_error *
8821 cmd_integrate(int argc, char *argv[])
8823 const struct got_error *error = NULL;
8824 struct got_repository *repo = NULL;
8825 struct got_worktree *worktree = NULL;
8826 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
8827 const char *branch_arg = NULL;
8828 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
8829 struct got_fileindex *fileindex = NULL;
8830 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
8831 int ch;
8832 struct got_update_progress_arg upa;
8834 while ((ch = getopt(argc, argv, "")) != -1) {
8835 switch (ch) {
8836 default:
8837 usage_integrate();
8838 /* NOTREACHED */
8842 argc -= optind;
8843 argv += optind;
8845 if (argc != 1)
8846 usage_integrate();
8847 branch_arg = argv[0];
8849 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8850 "unveil", NULL) == -1)
8851 err(1, "pledge");
8853 cwd = getcwd(NULL, 0);
8854 if (cwd == NULL) {
8855 error = got_error_from_errno("getcwd");
8856 goto done;
8859 error = got_worktree_open(&worktree, cwd);
8860 if (error) {
8861 if (error->code == GOT_ERR_NOT_WORKTREE)
8862 error = wrap_not_worktree_error(error, "integrate",
8863 cwd);
8864 goto done;
8867 error = check_rebase_or_histedit_in_progress(worktree);
8868 if (error)
8869 goto done;
8871 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8872 NULL);
8873 if (error != NULL)
8874 goto done;
8876 error = apply_unveil(got_repo_get_path(repo), 0,
8877 got_worktree_get_root_path(worktree));
8878 if (error)
8879 goto done;
8881 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
8882 error = got_error_from_errno("asprintf");
8883 goto done;
8886 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
8887 &base_branch_ref, worktree, refname, repo);
8888 if (error)
8889 goto done;
8891 refname = strdup(got_ref_get_name(branch_ref));
8892 if (refname == NULL) {
8893 error = got_error_from_errno("strdup");
8894 got_worktree_integrate_abort(worktree, fileindex, repo,
8895 branch_ref, base_branch_ref);
8896 goto done;
8898 base_refname = strdup(got_ref_get_name(base_branch_ref));
8899 if (base_refname == NULL) {
8900 error = got_error_from_errno("strdup");
8901 got_worktree_integrate_abort(worktree, fileindex, repo,
8902 branch_ref, base_branch_ref);
8903 goto done;
8906 error = got_ref_resolve(&commit_id, repo, branch_ref);
8907 if (error)
8908 goto done;
8910 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
8911 if (error)
8912 goto done;
8914 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
8915 error = got_error_msg(GOT_ERR_SAME_BRANCH,
8916 "specified branch has already been integrated");
8917 got_worktree_integrate_abort(worktree, fileindex, repo,
8918 branch_ref, base_branch_ref);
8919 goto done;
8922 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
8923 if (error) {
8924 if (error->code == GOT_ERR_ANCESTRY)
8925 error = got_error(GOT_ERR_REBASE_REQUIRED);
8926 got_worktree_integrate_abort(worktree, fileindex, repo,
8927 branch_ref, base_branch_ref);
8928 goto done;
8931 memset(&upa, 0, sizeof(upa));
8932 error = got_worktree_integrate_continue(worktree, fileindex, repo,
8933 branch_ref, base_branch_ref, update_progress, &upa,
8934 check_cancelled, NULL);
8935 if (error)
8936 goto done;
8938 printf("Integrated %s into %s\n", refname, base_refname);
8939 print_update_progress_stats(&upa);
8940 done:
8941 if (repo)
8942 got_repo_close(repo);
8943 if (worktree)
8944 got_worktree_close(worktree);
8945 free(cwd);
8946 free(base_commit_id);
8947 free(commit_id);
8948 free(refname);
8949 free(base_refname);
8950 return error;
8953 __dead static void
8954 usage_stage(void)
8956 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
8957 "[-S] [file-path ...]\n",
8958 getprogname());
8959 exit(1);
8962 static const struct got_error *
8963 print_stage(void *arg, unsigned char status, unsigned char staged_status,
8964 const char *path, struct got_object_id *blob_id,
8965 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
8966 int dirfd, const char *de_name)
8968 const struct got_error *err = NULL;
8969 char *id_str = NULL;
8971 if (staged_status != GOT_STATUS_ADD &&
8972 staged_status != GOT_STATUS_MODIFY &&
8973 staged_status != GOT_STATUS_DELETE)
8974 return NULL;
8976 if (staged_status == GOT_STATUS_ADD ||
8977 staged_status == GOT_STATUS_MODIFY)
8978 err = got_object_id_str(&id_str, staged_blob_id);
8979 else
8980 err = got_object_id_str(&id_str, blob_id);
8981 if (err)
8982 return err;
8984 printf("%s %c %s\n", id_str, staged_status, path);
8985 free(id_str);
8986 return NULL;
8989 static const struct got_error *
8990 cmd_stage(int argc, char *argv[])
8992 const struct got_error *error = NULL;
8993 struct got_repository *repo = NULL;
8994 struct got_worktree *worktree = NULL;
8995 char *cwd = NULL;
8996 struct got_pathlist_head paths;
8997 struct got_pathlist_entry *pe;
8998 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
8999 FILE *patch_script_file = NULL;
9000 const char *patch_script_path = NULL;
9001 struct choose_patch_arg cpa;
9003 TAILQ_INIT(&paths);
9005 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
9006 switch (ch) {
9007 case 'l':
9008 list_stage = 1;
9009 break;
9010 case 'p':
9011 pflag = 1;
9012 break;
9013 case 'F':
9014 patch_script_path = optarg;
9015 break;
9016 case 'S':
9017 allow_bad_symlinks = 1;
9018 break;
9019 default:
9020 usage_stage();
9021 /* NOTREACHED */
9025 argc -= optind;
9026 argv += optind;
9028 #ifndef PROFILE
9029 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9030 "unveil", NULL) == -1)
9031 err(1, "pledge");
9032 #endif
9033 if (list_stage && (pflag || patch_script_path))
9034 errx(1, "-l option cannot be used with other options");
9035 if (patch_script_path && !pflag)
9036 errx(1, "-F option can only be used together with -p option");
9038 cwd = getcwd(NULL, 0);
9039 if (cwd == NULL) {
9040 error = got_error_from_errno("getcwd");
9041 goto done;
9044 error = got_worktree_open(&worktree, cwd);
9045 if (error) {
9046 if (error->code == GOT_ERR_NOT_WORKTREE)
9047 error = wrap_not_worktree_error(error, "stage", cwd);
9048 goto done;
9051 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9052 NULL);
9053 if (error != NULL)
9054 goto done;
9056 if (patch_script_path) {
9057 patch_script_file = fopen(patch_script_path, "r");
9058 if (patch_script_file == NULL) {
9059 error = got_error_from_errno2("fopen",
9060 patch_script_path);
9061 goto done;
9064 error = apply_unveil(got_repo_get_path(repo), 0,
9065 got_worktree_get_root_path(worktree));
9066 if (error)
9067 goto done;
9069 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9070 if (error)
9071 goto done;
9073 if (list_stage)
9074 error = got_worktree_status(worktree, &paths, repo,
9075 print_stage, NULL, check_cancelled, NULL);
9076 else {
9077 cpa.patch_script_file = patch_script_file;
9078 cpa.action = "stage";
9079 error = got_worktree_stage(worktree, &paths,
9080 pflag ? NULL : print_status, NULL,
9081 pflag ? choose_patch : NULL, &cpa,
9082 allow_bad_symlinks, repo);
9084 done:
9085 if (patch_script_file && fclose(patch_script_file) == EOF &&
9086 error == NULL)
9087 error = got_error_from_errno2("fclose", patch_script_path);
9088 if (repo)
9089 got_repo_close(repo);
9090 if (worktree)
9091 got_worktree_close(worktree);
9092 TAILQ_FOREACH(pe, &paths, entry)
9093 free((char *)pe->path);
9094 got_pathlist_free(&paths);
9095 free(cwd);
9096 return error;
9099 __dead static void
9100 usage_unstage(void)
9102 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
9103 "[file-path ...]\n",
9104 getprogname());
9105 exit(1);
9109 static const struct got_error *
9110 cmd_unstage(int argc, char *argv[])
9112 const struct got_error *error = NULL;
9113 struct got_repository *repo = NULL;
9114 struct got_worktree *worktree = NULL;
9115 char *cwd = NULL;
9116 struct got_pathlist_head paths;
9117 struct got_pathlist_entry *pe;
9118 int ch, pflag = 0;
9119 struct got_update_progress_arg upa;
9120 FILE *patch_script_file = NULL;
9121 const char *patch_script_path = NULL;
9122 struct choose_patch_arg cpa;
9124 TAILQ_INIT(&paths);
9126 while ((ch = getopt(argc, argv, "pF:")) != -1) {
9127 switch (ch) {
9128 case 'p':
9129 pflag = 1;
9130 break;
9131 case 'F':
9132 patch_script_path = optarg;
9133 break;
9134 default:
9135 usage_unstage();
9136 /* NOTREACHED */
9140 argc -= optind;
9141 argv += optind;
9143 #ifndef PROFILE
9144 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9145 "unveil", NULL) == -1)
9146 err(1, "pledge");
9147 #endif
9148 if (patch_script_path && !pflag)
9149 errx(1, "-F option can only be used together with -p option");
9151 cwd = getcwd(NULL, 0);
9152 if (cwd == NULL) {
9153 error = got_error_from_errno("getcwd");
9154 goto done;
9157 error = got_worktree_open(&worktree, cwd);
9158 if (error) {
9159 if (error->code == GOT_ERR_NOT_WORKTREE)
9160 error = wrap_not_worktree_error(error, "unstage", cwd);
9161 goto done;
9164 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9165 NULL);
9166 if (error != NULL)
9167 goto done;
9169 if (patch_script_path) {
9170 patch_script_file = fopen(patch_script_path, "r");
9171 if (patch_script_file == NULL) {
9172 error = got_error_from_errno2("fopen",
9173 patch_script_path);
9174 goto done;
9178 error = apply_unveil(got_repo_get_path(repo), 0,
9179 got_worktree_get_root_path(worktree));
9180 if (error)
9181 goto done;
9183 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9184 if (error)
9185 goto done;
9187 cpa.patch_script_file = patch_script_file;
9188 cpa.action = "unstage";
9189 memset(&upa, 0, sizeof(upa));
9190 error = got_worktree_unstage(worktree, &paths, update_progress,
9191 &upa, pflag ? choose_patch : NULL, &cpa, repo);
9192 if (!error)
9193 print_update_progress_stats(&upa);
9194 done:
9195 if (patch_script_file && fclose(patch_script_file) == EOF &&
9196 error == NULL)
9197 error = got_error_from_errno2("fclose", patch_script_path);
9198 if (repo)
9199 got_repo_close(repo);
9200 if (worktree)
9201 got_worktree_close(worktree);
9202 TAILQ_FOREACH(pe, &paths, entry)
9203 free((char *)pe->path);
9204 got_pathlist_free(&paths);
9205 free(cwd);
9206 return error;
9209 __dead static void
9210 usage_cat(void)
9212 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
9213 "arg1 [arg2 ...]\n", getprogname());
9214 exit(1);
9217 static const struct got_error *
9218 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9220 const struct got_error *err;
9221 struct got_blob_object *blob;
9223 err = got_object_open_as_blob(&blob, repo, id, 8192);
9224 if (err)
9225 return err;
9227 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
9228 got_object_blob_close(blob);
9229 return err;
9232 static const struct got_error *
9233 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9235 const struct got_error *err;
9236 struct got_tree_object *tree;
9237 int nentries, i;
9239 err = got_object_open_as_tree(&tree, repo, id);
9240 if (err)
9241 return err;
9243 nentries = got_object_tree_get_nentries(tree);
9244 for (i = 0; i < nentries; i++) {
9245 struct got_tree_entry *te;
9246 char *id_str;
9247 if (sigint_received || sigpipe_received)
9248 break;
9249 te = got_object_tree_get_entry(tree, i);
9250 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
9251 if (err)
9252 break;
9253 fprintf(outfile, "%s %.7o %s\n", id_str,
9254 got_tree_entry_get_mode(te),
9255 got_tree_entry_get_name(te));
9256 free(id_str);
9259 got_object_tree_close(tree);
9260 return err;
9263 static const struct got_error *
9264 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9266 const struct got_error *err;
9267 struct got_commit_object *commit;
9268 const struct got_object_id_queue *parent_ids;
9269 struct got_object_qid *pid;
9270 char *id_str = NULL;
9271 const char *logmsg = NULL;
9273 err = got_object_open_as_commit(&commit, repo, id);
9274 if (err)
9275 return err;
9277 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
9278 if (err)
9279 goto done;
9281 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
9282 parent_ids = got_object_commit_get_parent_ids(commit);
9283 fprintf(outfile, "numparents %d\n",
9284 got_object_commit_get_nparents(commit));
9285 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
9286 char *pid_str;
9287 err = got_object_id_str(&pid_str, pid->id);
9288 if (err)
9289 goto done;
9290 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
9291 free(pid_str);
9293 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
9294 got_object_commit_get_author(commit),
9295 got_object_commit_get_author_time(commit));
9297 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
9298 got_object_commit_get_author(commit),
9299 got_object_commit_get_committer_time(commit));
9301 logmsg = got_object_commit_get_logmsg_raw(commit);
9302 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
9303 fprintf(outfile, "%s", logmsg);
9304 done:
9305 free(id_str);
9306 got_object_commit_close(commit);
9307 return err;
9310 static const struct got_error *
9311 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9313 const struct got_error *err;
9314 struct got_tag_object *tag;
9315 char *id_str = NULL;
9316 const char *tagmsg = NULL;
9318 err = got_object_open_as_tag(&tag, repo, id);
9319 if (err)
9320 return err;
9322 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
9323 if (err)
9324 goto done;
9326 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
9328 switch (got_object_tag_get_object_type(tag)) {
9329 case GOT_OBJ_TYPE_BLOB:
9330 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9331 GOT_OBJ_LABEL_BLOB);
9332 break;
9333 case GOT_OBJ_TYPE_TREE:
9334 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9335 GOT_OBJ_LABEL_TREE);
9336 break;
9337 case GOT_OBJ_TYPE_COMMIT:
9338 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9339 GOT_OBJ_LABEL_COMMIT);
9340 break;
9341 case GOT_OBJ_TYPE_TAG:
9342 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9343 GOT_OBJ_LABEL_TAG);
9344 break;
9345 default:
9346 break;
9349 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
9350 got_object_tag_get_name(tag));
9352 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
9353 got_object_tag_get_tagger(tag),
9354 got_object_tag_get_tagger_time(tag));
9356 tagmsg = got_object_tag_get_message(tag);
9357 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
9358 fprintf(outfile, "%s", tagmsg);
9359 done:
9360 free(id_str);
9361 got_object_tag_close(tag);
9362 return err;
9365 static const struct got_error *
9366 cmd_cat(int argc, char *argv[])
9368 const struct got_error *error;
9369 struct got_repository *repo = NULL;
9370 struct got_worktree *worktree = NULL;
9371 char *cwd = NULL, *repo_path = NULL, *label = NULL;
9372 const char *commit_id_str = NULL;
9373 struct got_object_id *id = NULL, *commit_id = NULL;
9374 int ch, obj_type, i, force_path = 0;
9376 #ifndef PROFILE
9377 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9378 NULL) == -1)
9379 err(1, "pledge");
9380 #endif
9382 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
9383 switch (ch) {
9384 case 'c':
9385 commit_id_str = optarg;
9386 break;
9387 case 'r':
9388 repo_path = realpath(optarg, NULL);
9389 if (repo_path == NULL)
9390 return got_error_from_errno2("realpath",
9391 optarg);
9392 got_path_strip_trailing_slashes(repo_path);
9393 break;
9394 case 'P':
9395 force_path = 1;
9396 break;
9397 default:
9398 usage_cat();
9399 /* NOTREACHED */
9403 argc -= optind;
9404 argv += optind;
9406 cwd = getcwd(NULL, 0);
9407 if (cwd == NULL) {
9408 error = got_error_from_errno("getcwd");
9409 goto done;
9411 error = got_worktree_open(&worktree, cwd);
9412 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9413 goto done;
9414 if (worktree) {
9415 if (repo_path == NULL) {
9416 repo_path = strdup(
9417 got_worktree_get_repo_path(worktree));
9418 if (repo_path == NULL) {
9419 error = got_error_from_errno("strdup");
9420 goto done;
9425 if (repo_path == NULL) {
9426 repo_path = getcwd(NULL, 0);
9427 if (repo_path == NULL)
9428 return got_error_from_errno("getcwd");
9431 error = got_repo_open(&repo, repo_path, NULL);
9432 free(repo_path);
9433 if (error != NULL)
9434 goto done;
9436 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9437 if (error)
9438 goto done;
9440 if (commit_id_str == NULL)
9441 commit_id_str = GOT_REF_HEAD;
9442 error = got_repo_match_object_id(&commit_id, NULL,
9443 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
9444 if (error)
9445 goto done;
9447 for (i = 0; i < argc; i++) {
9448 if (force_path) {
9449 error = got_object_id_by_path(&id, repo, commit_id,
9450 argv[i]);
9451 if (error)
9452 break;
9453 } else {
9454 error = got_repo_match_object_id(&id, &label, argv[i],
9455 GOT_OBJ_TYPE_ANY, 0, repo);
9456 if (error) {
9457 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9458 error->code != GOT_ERR_NOT_REF)
9459 break;
9460 error = got_object_id_by_path(&id, repo,
9461 commit_id, argv[i]);
9462 if (error)
9463 break;
9467 error = got_object_get_type(&obj_type, repo, id);
9468 if (error)
9469 break;
9471 switch (obj_type) {
9472 case GOT_OBJ_TYPE_BLOB:
9473 error = cat_blob(id, repo, stdout);
9474 break;
9475 case GOT_OBJ_TYPE_TREE:
9476 error = cat_tree(id, repo, stdout);
9477 break;
9478 case GOT_OBJ_TYPE_COMMIT:
9479 error = cat_commit(id, repo, stdout);
9480 break;
9481 case GOT_OBJ_TYPE_TAG:
9482 error = cat_tag(id, repo, stdout);
9483 break;
9484 default:
9485 error = got_error(GOT_ERR_OBJ_TYPE);
9486 break;
9488 if (error)
9489 break;
9490 free(label);
9491 label = NULL;
9492 free(id);
9493 id = NULL;
9495 done:
9496 free(label);
9497 free(id);
9498 free(commit_id);
9499 if (worktree)
9500 got_worktree_close(worktree);
9501 if (repo) {
9502 const struct got_error *repo_error;
9503 repo_error = got_repo_close(repo);
9504 if (error == NULL)
9505 error = repo_error;
9507 return error;
9510 __dead static void
9511 usage_info(void)
9513 fprintf(stderr, "usage: %s info [path ...]\n",
9514 getprogname());
9515 exit(1);
9518 static const struct got_error *
9519 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
9520 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9521 struct got_object_id *commit_id)
9523 const struct got_error *err = NULL;
9524 char *id_str = NULL;
9525 char datebuf[128];
9526 struct tm mytm, *tm;
9527 struct got_pathlist_head *paths = arg;
9528 struct got_pathlist_entry *pe;
9531 * Clear error indication from any of the path arguments which
9532 * would cause this file index entry to be displayed.
9534 TAILQ_FOREACH(pe, paths, entry) {
9535 if (got_path_cmp(path, pe->path, strlen(path),
9536 pe->path_len) == 0 ||
9537 got_path_is_child(path, pe->path, pe->path_len))
9538 pe->data = NULL; /* no error */
9541 printf(GOT_COMMIT_SEP_STR);
9542 if (S_ISLNK(mode))
9543 printf("symlink: %s\n", path);
9544 else if (S_ISREG(mode)) {
9545 printf("file: %s\n", path);
9546 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
9547 } else if (S_ISDIR(mode))
9548 printf("directory: %s\n", path);
9549 else
9550 printf("something: %s\n", path);
9552 tm = localtime_r(&mtime, &mytm);
9553 if (tm == NULL)
9554 return NULL;
9555 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) >= sizeof(datebuf))
9556 return got_error(GOT_ERR_NO_SPACE);
9557 printf("timestamp: %s\n", datebuf);
9559 if (blob_id) {
9560 err = got_object_id_str(&id_str, blob_id);
9561 if (err)
9562 return err;
9563 printf("based on blob: %s\n", id_str);
9564 free(id_str);
9567 if (staged_blob_id) {
9568 err = got_object_id_str(&id_str, staged_blob_id);
9569 if (err)
9570 return err;
9571 printf("based on staged blob: %s\n", id_str);
9572 free(id_str);
9575 if (commit_id) {
9576 err = got_object_id_str(&id_str, commit_id);
9577 if (err)
9578 return err;
9579 printf("based on commit: %s\n", id_str);
9580 free(id_str);
9583 return NULL;
9586 static const struct got_error *
9587 cmd_info(int argc, char *argv[])
9589 const struct got_error *error = NULL;
9590 struct got_worktree *worktree = NULL;
9591 char *cwd = NULL, *id_str = NULL;
9592 struct got_pathlist_head paths;
9593 struct got_pathlist_entry *pe;
9594 char *uuidstr = NULL;
9595 int ch, show_files = 0;
9597 TAILQ_INIT(&paths);
9599 while ((ch = getopt(argc, argv, "")) != -1) {
9600 switch (ch) {
9601 default:
9602 usage_info();
9603 /* NOTREACHED */
9607 argc -= optind;
9608 argv += optind;
9610 #ifndef PROFILE
9611 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
9612 NULL) == -1)
9613 err(1, "pledge");
9614 #endif
9615 cwd = getcwd(NULL, 0);
9616 if (cwd == NULL) {
9617 error = got_error_from_errno("getcwd");
9618 goto done;
9621 error = got_worktree_open(&worktree, cwd);
9622 if (error) {
9623 if (error->code == GOT_ERR_NOT_WORKTREE)
9624 error = wrap_not_worktree_error(error, "status", cwd);
9625 goto done;
9628 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9629 if (error)
9630 goto done;
9632 if (argc >= 1) {
9633 error = get_worktree_paths_from_argv(&paths, argc, argv,
9634 worktree);
9635 if (error)
9636 goto done;
9637 show_files = 1;
9640 error = got_object_id_str(&id_str,
9641 got_worktree_get_base_commit_id(worktree));
9642 if (error)
9643 goto done;
9645 error = got_worktree_get_uuid(&uuidstr, worktree);
9646 if (error)
9647 goto done;
9649 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9650 printf("work tree base commit: %s\n", id_str);
9651 printf("work tree path prefix: %s\n",
9652 got_worktree_get_path_prefix(worktree));
9653 printf("work tree branch reference: %s\n",
9654 got_worktree_get_head_ref_name(worktree));
9655 printf("work tree UUID: %s\n", uuidstr);
9656 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
9658 if (show_files) {
9659 struct got_pathlist_entry *pe;
9660 TAILQ_FOREACH(pe, &paths, entry) {
9661 if (pe->path_len == 0)
9662 continue;
9664 * Assume this path will fail. This will be corrected
9665 * in print_path_info() in case the path does suceeed.
9667 pe->data = (void *)got_error_path(pe->path,
9668 GOT_ERR_BAD_PATH);
9670 error = got_worktree_path_info(worktree, &paths,
9671 print_path_info, &paths, check_cancelled, NULL);
9672 if (error)
9673 goto done;
9674 TAILQ_FOREACH(pe, &paths, entry) {
9675 if (pe->data != NULL) {
9676 error = pe->data; /* bad path */
9677 break;
9681 done:
9682 TAILQ_FOREACH(pe, &paths, entry)
9683 free((char *)pe->path);
9684 got_pathlist_free(&paths);
9685 free(cwd);
9686 free(id_str);
9687 free(uuidstr);
9688 return error;