Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/param.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
41 #include <util.h>
43 #include "got_version.h"
44 #include "got_error.h"
45 #include "got_object.h"
46 #include "got_reference.h"
47 #include "got_repository.h"
48 #include "got_path.h"
49 #include "got_cancel.h"
50 #include "got_worktree.h"
51 #include "got_diff.h"
52 #include "got_commit_graph.h"
53 #include "got_fetch.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_opentemp.h"
57 #include "got_gotconfig.h"
59 #ifndef nitems
60 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
61 #endif
63 static volatile sig_atomic_t sigint_received;
64 static volatile sig_atomic_t sigpipe_received;
66 static void
67 catch_sigint(int signo)
68 {
69 sigint_received = 1;
70 }
72 static void
73 catch_sigpipe(int signo)
74 {
75 sigpipe_received = 1;
76 }
79 struct got_cmd {
80 const char *cmd_name;
81 const struct got_error *(*cmd_main)(int, char *[]);
82 void (*cmd_usage)(void);
83 const char *cmd_alias;
84 };
86 __dead static void usage(int);
87 __dead static void usage_init(void);
88 __dead static void usage_import(void);
89 __dead static void usage_clone(void);
90 __dead static void usage_fetch(void);
91 __dead static void usage_checkout(void);
92 __dead static void usage_update(void);
93 __dead static void usage_log(void);
94 __dead static void usage_diff(void);
95 __dead static void usage_blame(void);
96 __dead static void usage_tree(void);
97 __dead static void usage_status(void);
98 __dead static void usage_ref(void);
99 __dead static void usage_branch(void);
100 __dead static void usage_tag(void);
101 __dead static void usage_add(void);
102 __dead static void usage_remove(void);
103 __dead static void usage_revert(void);
104 __dead static void usage_commit(void);
105 __dead static void usage_cherrypick(void);
106 __dead static void usage_backout(void);
107 __dead static void usage_rebase(void);
108 __dead static void usage_histedit(void);
109 __dead static void usage_integrate(void);
110 __dead static void usage_stage(void);
111 __dead static void usage_unstage(void);
112 __dead static void usage_cat(void);
113 __dead static void usage_info(void);
115 static const struct got_error* cmd_init(int, char *[]);
116 static const struct got_error* cmd_import(int, char *[]);
117 static const struct got_error* cmd_clone(int, char *[]);
118 static const struct got_error* cmd_fetch(int, char *[]);
119 static const struct got_error* cmd_checkout(int, char *[]);
120 static const struct got_error* cmd_update(int, char *[]);
121 static const struct got_error* cmd_log(int, char *[]);
122 static const struct got_error* cmd_diff(int, char *[]);
123 static const struct got_error* cmd_blame(int, char *[]);
124 static const struct got_error* cmd_tree(int, char *[]);
125 static const struct got_error* cmd_status(int, char *[]);
126 static const struct got_error* cmd_ref(int, char *[]);
127 static const struct got_error* cmd_branch(int, char *[]);
128 static const struct got_error* cmd_tag(int, char *[]);
129 static const struct got_error* cmd_add(int, char *[]);
130 static const struct got_error* cmd_remove(int, char *[]);
131 static const struct got_error* cmd_revert(int, char *[]);
132 static const struct got_error* cmd_commit(int, char *[]);
133 static const struct got_error* cmd_cherrypick(int, char *[]);
134 static const struct got_error* cmd_backout(int, char *[]);
135 static const struct got_error* cmd_rebase(int, char *[]);
136 static const struct got_error* cmd_histedit(int, char *[]);
137 static const struct got_error* cmd_integrate(int, char *[]);
138 static const struct got_error* cmd_stage(int, char *[]);
139 static const struct got_error* cmd_unstage(int, char *[]);
140 static const struct got_error* cmd_cat(int, char *[]);
141 static const struct got_error* cmd_info(int, char *[]);
143 static struct got_cmd got_commands[] = {
144 { "init", cmd_init, usage_init, "" },
145 { "import", cmd_import, usage_import, "im" },
146 { "clone", cmd_clone, usage_clone, "cl" },
147 { "fetch", cmd_fetch, usage_fetch, "fe" },
148 { "checkout", cmd_checkout, usage_checkout, "co" },
149 { "update", cmd_update, usage_update, "up" },
150 { "log", cmd_log, usage_log, "" },
151 { "diff", cmd_diff, usage_diff, "di" },
152 { "blame", cmd_blame, usage_blame, "bl" },
153 { "tree", cmd_tree, usage_tree, "tr" },
154 { "status", cmd_status, usage_status, "st" },
155 { "ref", cmd_ref, usage_ref, "" },
156 { "branch", cmd_branch, usage_branch, "br" },
157 { "tag", cmd_tag, usage_tag, "" },
158 { "add", cmd_add, usage_add, "" },
159 { "remove", cmd_remove, usage_remove, "rm" },
160 { "revert", cmd_revert, usage_revert, "rv" },
161 { "commit", cmd_commit, usage_commit, "ci" },
162 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
163 { "backout", cmd_backout, usage_backout, "bo" },
164 { "rebase", cmd_rebase, usage_rebase, "rb" },
165 { "histedit", cmd_histedit, usage_histedit, "he" },
166 { "integrate", cmd_integrate, usage_integrate,"ig" },
167 { "stage", cmd_stage, usage_stage, "sg" },
168 { "unstage", cmd_unstage, usage_unstage, "ug" },
169 { "cat", cmd_cat, usage_cat, "" },
170 { "info", cmd_info, usage_info, "" },
171 };
173 static void
174 list_commands(void)
176 int i;
178 fprintf(stderr, "commands:");
179 for (i = 0; i < nitems(got_commands); i++) {
180 struct got_cmd *cmd = &got_commands[i];
181 fprintf(stderr, " %s", cmd->cmd_name);
183 fputc('\n', stderr);
186 int
187 main(int argc, char *argv[])
189 struct got_cmd *cmd;
190 unsigned int i;
191 int ch;
192 int hflag = 0, Vflag = 0;
193 static struct option longopts[] = {
194 { "version", no_argument, NULL, 'V' },
195 { NULL, 0, NULL, 0}
196 };
198 setlocale(LC_CTYPE, "");
200 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
201 switch (ch) {
202 case 'h':
203 hflag = 1;
204 break;
205 case 'V':
206 Vflag = 1;
207 break;
208 default:
209 usage(hflag);
210 /* NOTREACHED */
214 argc -= optind;
215 argv += optind;
216 optind = 0;
218 if (Vflag) {
219 got_version_print_str();
220 return 1;
223 if (argc <= 0)
224 usage(hflag);
226 signal(SIGINT, catch_sigint);
227 signal(SIGPIPE, catch_sigpipe);
229 for (i = 0; i < nitems(got_commands); i++) {
230 const struct got_error *error;
232 cmd = &got_commands[i];
234 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
235 strcmp(cmd->cmd_alias, argv[0]) != 0)
236 continue;
238 if (hflag)
239 got_commands[i].cmd_usage();
241 error = got_commands[i].cmd_main(argc, argv);
242 if (error && error->code != GOT_ERR_CANCELLED &&
243 error->code != GOT_ERR_PRIVSEP_EXIT &&
244 !(sigpipe_received &&
245 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
246 !(sigint_received &&
247 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
248 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
249 return 1;
252 return 0;
255 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
256 list_commands();
257 return 1;
260 __dead static void
261 usage(int hflag)
263 fprintf(stderr, "usage: %s [-h] [-V | --version] command [arg ...]\n",
264 getprogname());
265 if (hflag)
266 list_commands();
267 exit(1);
270 static const struct got_error *
271 get_editor(char **abspath)
273 const struct got_error *err = NULL;
274 const char *editor;
276 *abspath = NULL;
278 editor = getenv("VISUAL");
279 if (editor == NULL)
280 editor = getenv("EDITOR");
282 if (editor) {
283 err = got_path_find_prog(abspath, editor);
284 if (err)
285 return err;
288 if (*abspath == NULL) {
289 *abspath = strdup("/bin/ed");
290 if (*abspath == NULL)
291 return got_error_from_errno("strdup");
294 return NULL;
297 static const struct got_error *
298 apply_unveil(const char *repo_path, int repo_read_only,
299 const char *worktree_path)
301 const struct got_error *err;
303 #ifdef PROFILE
304 if (unveil("gmon.out", "rwc") != 0)
305 return got_error_from_errno2("unveil", "gmon.out");
306 #endif
307 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
308 return got_error_from_errno2("unveil", repo_path);
310 if (worktree_path && unveil(worktree_path, "rwc") != 0)
311 return got_error_from_errno2("unveil", worktree_path);
313 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
314 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
316 err = got_privsep_unveil_exec_helpers();
317 if (err != NULL)
318 return err;
320 if (unveil(NULL, NULL) != 0)
321 return got_error_from_errno("unveil");
323 return NULL;
326 __dead static void
327 usage_init(void)
329 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
330 exit(1);
333 static const struct got_error *
334 cmd_init(int argc, char *argv[])
336 const struct got_error *error = NULL;
337 char *repo_path = NULL;
338 int ch;
340 while ((ch = getopt(argc, argv, "")) != -1) {
341 switch (ch) {
342 default:
343 usage_init();
344 /* NOTREACHED */
348 argc -= optind;
349 argv += optind;
351 #ifndef PROFILE
352 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
353 err(1, "pledge");
354 #endif
355 if (argc != 1)
356 usage_init();
358 repo_path = strdup(argv[0]);
359 if (repo_path == NULL)
360 return got_error_from_errno("strdup");
362 got_path_strip_trailing_slashes(repo_path);
364 error = got_path_mkdir(repo_path);
365 if (error &&
366 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
367 goto done;
369 error = apply_unveil(repo_path, 0, NULL);
370 if (error)
371 goto done;
373 error = got_repo_init(repo_path);
374 done:
375 free(repo_path);
376 return error;
379 __dead static void
380 usage_import(void)
382 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
383 "[-r repository-path] [-I pattern] path\n", getprogname());
384 exit(1);
387 int
388 spawn_editor(const char *editor, const char *file)
390 pid_t pid;
391 sig_t sighup, sigint, sigquit;
392 int st = -1;
394 sighup = signal(SIGHUP, SIG_IGN);
395 sigint = signal(SIGINT, SIG_IGN);
396 sigquit = signal(SIGQUIT, SIG_IGN);
398 switch (pid = fork()) {
399 case -1:
400 goto doneediting;
401 case 0:
402 execl(editor, editor, file, (char *)NULL);
403 _exit(127);
406 while (waitpid(pid, &st, 0) == -1)
407 if (errno != EINTR)
408 break;
410 doneediting:
411 (void)signal(SIGHUP, sighup);
412 (void)signal(SIGINT, sigint);
413 (void)signal(SIGQUIT, sigquit);
415 if (!WIFEXITED(st)) {
416 errno = EINTR;
417 return -1;
420 return WEXITSTATUS(st);
423 static const struct got_error *
424 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
425 const char *initial_content)
427 const struct got_error *err = NULL;
428 char buf[1024];
429 struct stat st, st2;
430 FILE *fp;
431 int content_changed = 0;
432 size_t len;
434 *logmsg = NULL;
436 if (stat(logmsg_path, &st) == -1)
437 return got_error_from_errno2("stat", logmsg_path);
439 if (spawn_editor(editor, logmsg_path) == -1)
440 return got_error_from_errno("failed spawning editor");
442 if (stat(logmsg_path, &st2) == -1)
443 return got_error_from_errno("stat");
445 if (st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
446 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
447 "no changes made to commit message, aborting");
449 *logmsg = malloc(st2.st_size + 1);
450 if (*logmsg == NULL)
451 return got_error_from_errno("malloc");
452 (*logmsg)[0] = '\0';
453 len = 0;
455 fp = fopen(logmsg_path, "r");
456 if (fp == NULL) {
457 err = got_error_from_errno("fopen");
458 goto done;
460 while (fgets(buf, sizeof(buf), fp) != NULL) {
461 if (!content_changed && strcmp(buf, initial_content) != 0)
462 content_changed = 1;
463 if (buf[0] == '#' || (len == 0 && buf[0] == '\n'))
464 continue; /* remove comments and leading empty lines */
465 len = strlcat(*logmsg, buf, st2.st_size);
467 fclose(fp);
469 while (len > 0 && (*logmsg)[len - 1] == '\n') {
470 (*logmsg)[len - 1] = '\0';
471 len--;
474 if (len == 0 || !content_changed)
475 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
476 "commit message cannot be empty, aborting");
477 done:
478 if (err) {
479 free(*logmsg);
480 *logmsg = NULL;
482 return err;
485 static const struct got_error *
486 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
487 const char *path_dir, const char *branch_name)
489 char *initial_content = NULL;
490 const struct got_error *err = NULL;
491 int initial_content_len;
492 int fd = -1;
494 initial_content_len = asprintf(&initial_content,
495 "\n# %s to be imported to branch %s\n", path_dir,
496 branch_name);
497 if (initial_content_len == -1)
498 return got_error_from_errno("asprintf");
500 err = got_opentemp_named_fd(logmsg_path, &fd,
501 GOT_TMPDIR_STR "/got-importmsg");
502 if (err)
503 goto done;
505 if (write(fd, initial_content, initial_content_len) == -1) {
506 err = got_error_from_errno2("write", *logmsg_path);
507 goto done;
510 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content);
511 done:
512 if (fd != -1 && close(fd) == -1 && err == NULL)
513 err = got_error_from_errno2("close", *logmsg_path);
514 free(initial_content);
515 if (err) {
516 free(*logmsg_path);
517 *logmsg_path = NULL;
519 return err;
522 static const struct got_error *
523 import_progress(void *arg, const char *path)
525 printf("A %s\n", path);
526 return NULL;
529 static const struct got_error *
530 get_author(char **author, struct got_repository *repo,
531 struct got_worktree *worktree)
533 const struct got_error *err = NULL;
534 const char *got_author = NULL, *name, *email;
535 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
537 *author = NULL;
539 if (worktree)
540 worktree_conf = got_worktree_get_gotconfig(worktree);
541 repo_conf = got_repo_get_gotconfig(repo);
543 /*
544 * Priority of potential author information sources, from most
545 * significant to least significant:
546 * 1) work tree's .got/got.conf file
547 * 2) repository's got.conf file
548 * 3) repository's git config file
549 * 4) environment variables
550 * 5) global git config files (in user's home directory or /etc)
551 */
553 if (worktree_conf)
554 got_author = got_gotconfig_get_author(worktree_conf);
555 if (got_author == NULL)
556 got_author = got_gotconfig_get_author(repo_conf);
557 if (got_author == NULL) {
558 name = got_repo_get_gitconfig_author_name(repo);
559 email = got_repo_get_gitconfig_author_email(repo);
560 if (name && email) {
561 if (asprintf(author, "%s <%s>", name, email) == -1)
562 return got_error_from_errno("asprintf");
563 return NULL;
566 got_author = getenv("GOT_AUTHOR");
567 if (got_author == NULL) {
568 name = got_repo_get_global_gitconfig_author_name(repo);
569 email = got_repo_get_global_gitconfig_author_email(
570 repo);
571 if (name && email) {
572 if (asprintf(author, "%s <%s>", name, email)
573 == -1)
574 return got_error_from_errno("asprintf");
575 return NULL;
577 /* TODO: Look up user in password database? */
578 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
582 *author = strdup(got_author);
583 if (*author == NULL)
584 return got_error_from_errno("strdup");
586 /*
587 * Really dumb email address check; we're only doing this to
588 * avoid git's object parser breaking on commits we create.
589 */
590 while (*got_author && *got_author != '<')
591 got_author++;
592 if (*got_author != '<') {
593 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
594 goto done;
596 while (*got_author && *got_author != '@')
597 got_author++;
598 if (*got_author != '@') {
599 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
600 goto done;
602 while (*got_author && *got_author != '>')
603 got_author++;
604 if (*got_author != '>')
605 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
606 done:
607 if (err) {
608 free(*author);
609 *author = NULL;
611 return err;
614 static const struct got_error *
615 get_gitconfig_path(char **gitconfig_path)
617 const char *homedir = getenv("HOME");
619 *gitconfig_path = NULL;
620 if (homedir) {
621 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
622 return got_error_from_errno("asprintf");
625 return NULL;
628 static const struct got_error *
629 cmd_import(int argc, char *argv[])
631 const struct got_error *error = NULL;
632 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
633 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
634 const char *branch_name = "main";
635 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
636 struct got_repository *repo = NULL;
637 struct got_reference *branch_ref = NULL, *head_ref = NULL;
638 struct got_object_id *new_commit_id = NULL;
639 int ch;
640 struct got_pathlist_head ignores;
641 struct got_pathlist_entry *pe;
642 int preserve_logmsg = 0;
644 TAILQ_INIT(&ignores);
646 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
647 switch (ch) {
648 case 'b':
649 branch_name = optarg;
650 break;
651 case 'm':
652 logmsg = strdup(optarg);
653 if (logmsg == NULL) {
654 error = got_error_from_errno("strdup");
655 goto done;
657 break;
658 case 'r':
659 repo_path = realpath(optarg, NULL);
660 if (repo_path == NULL) {
661 error = got_error_from_errno2("realpath",
662 optarg);
663 goto done;
665 break;
666 case 'I':
667 if (optarg[0] == '\0')
668 break;
669 error = got_pathlist_insert(&pe, &ignores, optarg,
670 NULL);
671 if (error)
672 goto done;
673 break;
674 default:
675 usage_import();
676 /* NOTREACHED */
680 argc -= optind;
681 argv += optind;
683 #ifndef PROFILE
684 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
685 "unveil",
686 NULL) == -1)
687 err(1, "pledge");
688 #endif
689 if (argc != 1)
690 usage_import();
692 if (repo_path == NULL) {
693 repo_path = getcwd(NULL, 0);
694 if (repo_path == NULL)
695 return got_error_from_errno("getcwd");
697 got_path_strip_trailing_slashes(repo_path);
698 error = get_gitconfig_path(&gitconfig_path);
699 if (error)
700 goto done;
701 error = got_repo_open(&repo, repo_path, gitconfig_path);
702 if (error)
703 goto done;
705 error = get_author(&author, repo, NULL);
706 if (error)
707 return error;
709 /*
710 * Don't let the user create a branch name with a leading '-'.
711 * While technically a valid reference name, this case is usually
712 * an unintended typo.
713 */
714 if (branch_name[0] == '-')
715 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
717 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
718 error = got_error_from_errno("asprintf");
719 goto done;
722 error = got_ref_open(&branch_ref, repo, refname, 0);
723 if (error) {
724 if (error->code != GOT_ERR_NOT_REF)
725 goto done;
726 } else {
727 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
728 "import target branch already exists");
729 goto done;
732 path_dir = realpath(argv[0], NULL);
733 if (path_dir == NULL) {
734 error = got_error_from_errno2("realpath", argv[0]);
735 goto done;
737 got_path_strip_trailing_slashes(path_dir);
739 /*
740 * unveil(2) traverses exec(2); if an editor is used we have
741 * to apply unveil after the log message has been written.
742 */
743 if (logmsg == NULL || strlen(logmsg) == 0) {
744 error = get_editor(&editor);
745 if (error)
746 goto done;
747 free(logmsg);
748 error = collect_import_msg(&logmsg, &logmsg_path, editor,
749 path_dir, refname);
750 if (error) {
751 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
752 logmsg_path != NULL)
753 preserve_logmsg = 1;
754 goto done;
758 if (unveil(path_dir, "r") != 0) {
759 error = got_error_from_errno2("unveil", path_dir);
760 if (logmsg_path)
761 preserve_logmsg = 1;
762 goto done;
765 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
766 if (error) {
767 if (logmsg_path)
768 preserve_logmsg = 1;
769 goto done;
772 error = got_repo_import(&new_commit_id, path_dir, logmsg,
773 author, &ignores, repo, import_progress, NULL);
774 if (error) {
775 if (logmsg_path)
776 preserve_logmsg = 1;
777 goto done;
780 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
781 if (error) {
782 if (logmsg_path)
783 preserve_logmsg = 1;
784 goto done;
787 error = got_ref_write(branch_ref, repo);
788 if (error) {
789 if (logmsg_path)
790 preserve_logmsg = 1;
791 goto done;
794 error = got_object_id_str(&id_str, new_commit_id);
795 if (error) {
796 if (logmsg_path)
797 preserve_logmsg = 1;
798 goto done;
801 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
802 if (error) {
803 if (error->code != GOT_ERR_NOT_REF) {
804 if (logmsg_path)
805 preserve_logmsg = 1;
806 goto done;
809 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
810 branch_ref);
811 if (error) {
812 if (logmsg_path)
813 preserve_logmsg = 1;
814 goto done;
817 error = got_ref_write(head_ref, repo);
818 if (error) {
819 if (logmsg_path)
820 preserve_logmsg = 1;
821 goto done;
825 printf("Created branch %s with commit %s\n",
826 got_ref_get_name(branch_ref), id_str);
827 done:
828 if (preserve_logmsg) {
829 fprintf(stderr, "%s: log message preserved in %s\n",
830 getprogname(), logmsg_path);
831 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
832 error = got_error_from_errno2("unlink", logmsg_path);
833 free(logmsg);
834 free(logmsg_path);
835 free(repo_path);
836 free(editor);
837 free(refname);
838 free(new_commit_id);
839 free(id_str);
840 free(author);
841 free(gitconfig_path);
842 if (branch_ref)
843 got_ref_close(branch_ref);
844 if (head_ref)
845 got_ref_close(head_ref);
846 return error;
849 __dead static void
850 usage_clone(void)
852 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
853 "[-R reference] repository-url [directory]\n", getprogname());
854 exit(1);
857 struct got_fetch_progress_arg {
858 char last_scaled_size[FMT_SCALED_STRSIZE];
859 int last_p_indexed;
860 int last_p_resolved;
861 int verbosity;
862 };
864 static const struct got_error *
865 fetch_progress(void *arg, const char *message, off_t packfile_size,
866 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
868 struct got_fetch_progress_arg *a = arg;
869 char scaled_size[FMT_SCALED_STRSIZE];
870 int p_indexed, p_resolved;
871 int print_size = 0, print_indexed = 0, print_resolved = 0;
873 if (a->verbosity < 0)
874 return NULL;
876 if (message && message[0] != '\0') {
877 printf("\rserver: %s", message);
878 fflush(stdout);
879 return NULL;
882 if (packfile_size > 0 || nobj_indexed > 0) {
883 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
884 (a->last_scaled_size[0] == '\0' ||
885 strcmp(scaled_size, a->last_scaled_size)) != 0) {
886 print_size = 1;
887 if (strlcpy(a->last_scaled_size, scaled_size,
888 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
889 return got_error(GOT_ERR_NO_SPACE);
891 if (nobj_indexed > 0) {
892 p_indexed = (nobj_indexed * 100) / nobj_total;
893 if (p_indexed != a->last_p_indexed) {
894 a->last_p_indexed = p_indexed;
895 print_indexed = 1;
896 print_size = 1;
899 if (nobj_resolved > 0) {
900 p_resolved = (nobj_resolved * 100) /
901 (nobj_total - nobj_loose);
902 if (p_resolved != a->last_p_resolved) {
903 a->last_p_resolved = p_resolved;
904 print_resolved = 1;
905 print_indexed = 1;
906 print_size = 1;
911 if (print_size || print_indexed || print_resolved)
912 printf("\r");
913 if (print_size)
914 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
915 if (print_indexed)
916 printf("; indexing %d%%", p_indexed);
917 if (print_resolved)
918 printf("; resolving deltas %d%%", p_resolved);
919 if (print_size || print_indexed || print_resolved)
920 fflush(stdout);
922 return NULL;
925 static const struct got_error *
926 create_symref(struct got_reference **head_symref, const char *refname,
927 struct got_reference *target_ref, int verbosity,
928 struct got_repository *repo)
930 const struct got_error *err;
932 err = got_ref_alloc_symref(head_symref, refname, target_ref);
933 if (err)
934 return err;
936 err = got_ref_write(*head_symref, repo);
937 if (err == NULL && verbosity > 0) {
938 printf("Created reference %s: %s\n", GOT_REF_HEAD,
939 got_ref_get_name(target_ref));
941 return err;
944 static const struct got_error *
945 list_remote_refs(struct got_pathlist_head *symrefs,
946 struct got_pathlist_head *refs)
948 const struct got_error *err;
949 struct got_pathlist_entry *pe;
951 TAILQ_FOREACH(pe, symrefs, entry) {
952 const char *refname = pe->path;
953 const char *targetref = pe->data;
955 printf("%s: %s\n", refname, targetref);
958 TAILQ_FOREACH(pe, refs, entry) {
959 const char *refname = pe->path;
960 struct got_object_id *id = pe->data;
961 char *id_str;
963 err = got_object_id_str(&id_str, id);
964 if (err)
965 return err;
966 printf("%s: %s\n", refname, id_str);
967 free(id_str);
970 return NULL;
973 static const struct got_error *
974 create_ref(const char *refname, struct got_object_id *id,
975 int verbosity, struct got_repository *repo)
977 const struct got_error *err = NULL;
978 struct got_reference *ref;
979 char *id_str;
981 err = got_object_id_str(&id_str, id);
982 if (err)
983 return err;
985 err = got_ref_alloc(&ref, refname, id);
986 if (err)
987 goto done;
989 err = got_ref_write(ref, repo);
990 got_ref_close(ref);
992 if (err == NULL && verbosity >= 0)
993 printf("Created reference %s: %s\n", refname, id_str);
994 done:
995 free(id_str);
996 return err;
999 static int
1000 match_wanted_ref(const char *refname, const char *wanted_ref)
1002 if (strncmp(refname, "refs/", 5) != 0)
1003 return 0;
1004 refname += 5;
1007 * Prevent fetching of references that won't make any
1008 * sense outside of the remote repository's context.
1010 if (strncmp(refname, "got/", 4) == 0)
1011 return 0;
1012 if (strncmp(refname, "remotes/", 8) == 0)
1013 return 0;
1015 if (strncmp(wanted_ref, "refs/", 5) == 0)
1016 wanted_ref += 5;
1018 /* Allow prefix match. */
1019 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1020 return 1;
1022 /* Allow exact match. */
1023 return (strcmp(refname, wanted_ref) == 0);
1026 static int
1027 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1029 struct got_pathlist_entry *pe;
1031 TAILQ_FOREACH(pe, wanted_refs, entry) {
1032 if (match_wanted_ref(refname, pe->path))
1033 return 1;
1036 return 0;
1039 static const struct got_error *
1040 create_wanted_ref(const char *refname, struct got_object_id *id,
1041 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1043 const struct got_error *err;
1044 char *remote_refname;
1046 if (strncmp("refs/", refname, 5) == 0)
1047 refname += 5;
1049 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1050 remote_repo_name, refname) == -1)
1051 return got_error_from_errno("asprintf");
1053 err = create_ref(remote_refname, id, verbosity, repo);
1054 free(remote_refname);
1055 return err;
1058 static const struct got_error *
1059 cmd_clone(int argc, char *argv[])
1061 const struct got_error *error = NULL;
1062 const char *uri, *dirname;
1063 char *proto, *host, *port, *repo_name, *server_path;
1064 char *default_destdir = NULL, *id_str = NULL;
1065 const char *repo_path;
1066 struct got_repository *repo = NULL;
1067 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1068 struct got_pathlist_entry *pe;
1069 struct got_object_id *pack_hash = NULL;
1070 int ch, fetchfd = -1, fetchstatus;
1071 pid_t fetchpid = -1;
1072 struct got_fetch_progress_arg fpa;
1073 char *git_url = NULL;
1074 char *gitconfig_path = NULL, *gotconfig_path = NULL;
1075 char *gitconfig = NULL, *gotconfig = NULL;
1076 FILE *gitconfig_file = NULL, *gotconfig_file = NULL;
1077 ssize_t n;
1078 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1079 int list_refs_only = 0;
1080 struct got_reference *default_head = NULL;
1082 TAILQ_INIT(&refs);
1083 TAILQ_INIT(&symrefs);
1084 TAILQ_INIT(&wanted_branches);
1085 TAILQ_INIT(&wanted_refs);
1087 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1088 switch (ch) {
1089 case 'a':
1090 fetch_all_branches = 1;
1091 break;
1092 case 'b':
1093 error = got_pathlist_append(&wanted_branches,
1094 optarg, NULL);
1095 if (error)
1096 return error;
1097 break;
1098 case 'l':
1099 list_refs_only = 1;
1100 break;
1101 case 'm':
1102 mirror_references = 1;
1103 break;
1104 case 'v':
1105 if (verbosity < 0)
1106 verbosity = 0;
1107 else if (verbosity < 3)
1108 verbosity++;
1109 break;
1110 case 'q':
1111 verbosity = -1;
1112 break;
1113 case 'R':
1114 error = got_pathlist_append(&wanted_refs,
1115 optarg, NULL);
1116 if (error)
1117 return error;
1118 break;
1119 default:
1120 usage_clone();
1121 break;
1124 argc -= optind;
1125 argv += optind;
1127 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1128 errx(1, "-a and -b options are mutually exclusive");
1129 if (list_refs_only) {
1130 if (!TAILQ_EMPTY(&wanted_branches))
1131 errx(1, "-l and -b options are mutually exclusive");
1132 if (fetch_all_branches)
1133 errx(1, "-l and -a options are mutually exclusive");
1134 if (mirror_references)
1135 errx(1, "-l and -m options are mutually exclusive");
1136 if (verbosity == -1)
1137 errx(1, "-l and -q options are mutually exclusive");
1138 if (!TAILQ_EMPTY(&wanted_refs))
1139 errx(1, "-l and -R options are mutually exclusive");
1142 uri = argv[0];
1144 if (argc == 1)
1145 dirname = NULL;
1146 else if (argc == 2)
1147 dirname = argv[1];
1148 else
1149 usage_clone();
1151 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1152 &repo_name, uri);
1153 if (error)
1154 goto done;
1156 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1157 host, port ? ":" : "", port ? port : "",
1158 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1159 error = got_error_from_errno("asprintf");
1160 goto done;
1163 if (strcmp(proto, "git") == 0) {
1164 #ifndef PROFILE
1165 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1166 "sendfd dns inet unveil", NULL) == -1)
1167 err(1, "pledge");
1168 #endif
1169 } else if (strcmp(proto, "git+ssh") == 0 ||
1170 strcmp(proto, "ssh") == 0) {
1171 #ifndef PROFILE
1172 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1173 "sendfd unveil", NULL) == -1)
1174 err(1, "pledge");
1175 #endif
1176 } else if (strcmp(proto, "http") == 0 ||
1177 strcmp(proto, "git+http") == 0) {
1178 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1179 goto done;
1180 } else {
1181 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1182 goto done;
1184 if (dirname == NULL) {
1185 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1186 error = got_error_from_errno("asprintf");
1187 goto done;
1189 repo_path = default_destdir;
1190 } else
1191 repo_path = dirname;
1193 if (!list_refs_only) {
1194 error = got_path_mkdir(repo_path);
1195 if (error &&
1196 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1197 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1198 goto done;
1199 if (!got_path_dir_is_empty(repo_path)) {
1200 error = got_error_path(repo_path,
1201 GOT_ERR_DIR_NOT_EMPTY);
1202 goto done;
1206 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1207 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1208 error = got_error_from_errno2("unveil",
1209 GOT_FETCH_PATH_SSH);
1210 goto done;
1213 error = apply_unveil(repo ? got_repo_get_path(repo) : NULL, 0, NULL);
1214 if (error)
1215 goto done;
1217 if (verbosity >= 0)
1218 printf("Connecting to %s%s%s\n", host,
1219 port ? ":" : "", port ? port : "");
1221 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1222 server_path, verbosity);
1223 if (error)
1224 goto done;
1226 if (!list_refs_only) {
1227 error = got_repo_init(repo_path);
1228 if (error)
1229 goto done;
1230 error = got_repo_open(&repo, repo_path, NULL);
1231 if (error)
1232 goto done;
1235 fpa.last_scaled_size[0] = '\0';
1236 fpa.last_p_indexed = -1;
1237 fpa.last_p_resolved = -1;
1238 fpa.verbosity = verbosity;
1239 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1240 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1241 fetch_all_branches, &wanted_branches, &wanted_refs,
1242 list_refs_only, verbosity, fetchfd, repo,
1243 fetch_progress, &fpa);
1244 if (error)
1245 goto done;
1247 if (list_refs_only) {
1248 error = list_remote_refs(&symrefs, &refs);
1249 goto done;
1252 error = got_object_id_str(&id_str, pack_hash);
1253 if (error)
1254 goto done;
1255 if (verbosity >= 0)
1256 printf("\nFetched %s.pack\n", id_str);
1257 free(id_str);
1259 /* Set up references provided with the pack file. */
1260 TAILQ_FOREACH(pe, &refs, entry) {
1261 const char *refname = pe->path;
1262 struct got_object_id *id = pe->data;
1263 char *remote_refname;
1265 if (is_wanted_ref(&wanted_refs, refname) &&
1266 !mirror_references) {
1267 error = create_wanted_ref(refname, id,
1268 GOT_FETCH_DEFAULT_REMOTE_NAME,
1269 verbosity - 1, repo);
1270 if (error)
1271 goto done;
1272 continue;
1275 error = create_ref(refname, id, verbosity - 1, repo);
1276 if (error)
1277 goto done;
1279 if (mirror_references)
1280 continue;
1282 if (strncmp("refs/heads/", refname, 11) != 0)
1283 continue;
1285 if (asprintf(&remote_refname,
1286 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1287 refname + 11) == -1) {
1288 error = got_error_from_errno("asprintf");
1289 goto done;
1291 error = create_ref(remote_refname, id, verbosity - 1, repo);
1292 free(remote_refname);
1293 if (error)
1294 goto done;
1297 /* Set the HEAD reference if the server provided one. */
1298 TAILQ_FOREACH(pe, &symrefs, entry) {
1299 struct got_reference *target_ref;
1300 const char *refname = pe->path;
1301 const char *target = pe->data;
1302 char *remote_refname = NULL, *remote_target = NULL;
1303 struct got_reference *head_symref;
1305 if (strcmp(refname, GOT_REF_HEAD) != 0)
1306 continue;
1308 error = got_ref_open(&target_ref, repo, target, 0);
1309 if (error) {
1310 if (error->code == GOT_ERR_NOT_REF) {
1311 error = NULL;
1312 continue;
1314 goto done;
1317 error = create_symref(&head_symref, refname, target_ref,
1318 verbosity, repo);
1319 got_ref_close(target_ref);
1320 if (error)
1321 goto done;
1323 /* First HEAD reference listed is the default branch. */
1324 if (default_head == NULL)
1325 default_head = head_symref;
1326 else
1327 got_ref_close(head_symref);
1329 if (mirror_references)
1330 continue;
1332 if (strncmp("refs/heads/", target, 11) != 0)
1333 continue;
1335 if (asprintf(&remote_refname,
1336 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1337 refname) == -1) {
1338 error = got_error_from_errno("asprintf");
1339 goto done;
1341 if (asprintf(&remote_target,
1342 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1343 target + 11) == -1) {
1344 error = got_error_from_errno("asprintf");
1345 free(remote_refname);
1346 goto done;
1348 error = got_ref_open(&target_ref, repo, remote_target, 0);
1349 if (error) {
1350 free(remote_refname);
1351 free(remote_target);
1352 if (error->code == GOT_ERR_NOT_REF) {
1353 error = NULL;
1354 continue;
1356 goto done;
1358 error = create_symref(&head_symref, remote_refname,
1359 target_ref, verbosity - 1, repo);
1360 free(remote_refname);
1361 free(remote_target);
1362 got_ref_close(target_ref);
1363 got_ref_close(head_symref);
1364 if (error)
1365 goto done;
1367 if (pe == NULL) {
1369 * We failed to set the HEAD reference. If we asked for
1370 * a set of wanted branches use the first of one of those
1371 * which could be fetched instead.
1373 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1374 const char *target = pe->path;
1375 struct got_reference *target_ref;
1377 error = got_ref_open(&target_ref, repo, target, 0);
1378 if (error) {
1379 if (error->code == GOT_ERR_NOT_REF) {
1380 error = NULL;
1381 continue;
1383 goto done;
1386 error = create_symref(&default_head, GOT_REF_HEAD,
1387 target_ref, verbosity, repo);
1388 got_ref_close(target_ref);
1389 if (error)
1390 goto done;
1391 break;
1395 /* Create got.conf(5). */
1396 gotconfig_path = got_repo_get_path_gotconfig(repo);
1397 if (gotconfig_path == NULL) {
1398 error = got_error_from_errno("got_repo_get_path_gotconfig");
1399 goto done;
1401 gotconfig_file = fopen(gotconfig_path, "a");
1402 if (gotconfig_file == NULL) {
1403 error = got_error_from_errno2("fopen", gotconfig_path);
1404 goto done;
1406 got_path_strip_trailing_slashes(server_path);
1407 if (asprintf(&gotconfig,
1408 "remote \"%s\" {\n"
1409 "\tserver %s\n"
1410 "\tprotocol %s\n"
1411 "%s%s%s"
1412 "\trepository \"%s\"\n"
1413 "%s"
1414 "}\n",
1415 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1416 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1417 server_path,
1418 mirror_references ? "\tmirror-references yes\n" : "") == -1) {
1419 error = got_error_from_errno("asprintf");
1420 goto done;
1422 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1423 if (n != strlen(gotconfig)) {
1424 error = got_ferror(gotconfig_file, GOT_ERR_IO);
1425 goto done;
1428 /* Create a config file Git can understand. */
1429 gitconfig_path = got_repo_get_path_gitconfig(repo);
1430 if (gitconfig_path == NULL) {
1431 error = got_error_from_errno("got_repo_get_path_gitconfig");
1432 goto done;
1434 gitconfig_file = fopen(gitconfig_path, "a");
1435 if (gitconfig_file == NULL) {
1436 error = got_error_from_errno2("fopen", gitconfig_path);
1437 goto done;
1439 if (mirror_references) {
1440 if (asprintf(&gitconfig,
1441 "[remote \"%s\"]\n"
1442 "\turl = %s\n"
1443 "\tfetch = +refs/*:refs/*\n"
1444 "\tmirror = true\n",
1445 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1446 error = got_error_from_errno("asprintf");
1447 goto done;
1449 } else if (fetch_all_branches) {
1450 if (asprintf(&gitconfig,
1451 "[remote \"%s\"]\n"
1452 "\turl = %s\n"
1453 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1454 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1455 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1456 error = got_error_from_errno("asprintf");
1457 goto done;
1459 } else {
1460 const char *branchname;
1463 * If the server specified a default branch, use just that one.
1464 * Otherwise fall back to fetching all branches on next fetch.
1466 if (default_head) {
1467 branchname = got_ref_get_symref_target(default_head);
1468 if (strncmp(branchname, "refs/heads/", 11) == 0)
1469 branchname += 11;
1470 } else
1471 branchname = "*"; /* fall back to all branches */
1472 if (asprintf(&gitconfig,
1473 "[remote \"%s\"]\n"
1474 "\turl = %s\n"
1475 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1476 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1477 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1478 branchname) == -1) {
1479 error = got_error_from_errno("asprintf");
1480 goto done;
1483 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1484 if (n != strlen(gitconfig)) {
1485 error = got_ferror(gitconfig_file, GOT_ERR_IO);
1486 goto done;
1489 if (verbosity >= 0)
1490 printf("Created %s repository '%s'\n",
1491 mirror_references ? "mirrored" : "cloned", repo_path);
1492 done:
1493 if (fetchpid > 0) {
1494 if (kill(fetchpid, SIGTERM) == -1)
1495 error = got_error_from_errno("kill");
1496 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1497 error = got_error_from_errno("waitpid");
1499 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1500 error = got_error_from_errno("close");
1501 if (gotconfig_file && fclose(gotconfig_file) == EOF && error == NULL)
1502 error = got_error_from_errno("fclose");
1503 if (gitconfig_file && fclose(gitconfig_file) == EOF && error == NULL)
1504 error = got_error_from_errno("fclose");
1505 if (repo)
1506 got_repo_close(repo);
1507 if (default_head)
1508 got_ref_close(default_head);
1509 TAILQ_FOREACH(pe, &refs, entry) {
1510 free((void *)pe->path);
1511 free(pe->data);
1513 got_pathlist_free(&refs);
1514 TAILQ_FOREACH(pe, &symrefs, entry) {
1515 free((void *)pe->path);
1516 free(pe->data);
1518 got_pathlist_free(&symrefs);
1519 got_pathlist_free(&wanted_branches);
1520 got_pathlist_free(&wanted_refs);
1521 free(pack_hash);
1522 free(proto);
1523 free(host);
1524 free(port);
1525 free(server_path);
1526 free(repo_name);
1527 free(default_destdir);
1528 free(gotconfig);
1529 free(gitconfig);
1530 free(gotconfig_path);
1531 free(gitconfig_path);
1532 free(git_url);
1533 return error;
1536 static const struct got_error *
1537 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1538 int replace_tags, int verbosity, struct got_repository *repo)
1540 const struct got_error *err = NULL;
1541 char *new_id_str = NULL;
1542 struct got_object_id *old_id = NULL;
1544 err = got_object_id_str(&new_id_str, new_id);
1545 if (err)
1546 goto done;
1548 if (!replace_tags &&
1549 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1550 err = got_ref_resolve(&old_id, repo, ref);
1551 if (err)
1552 goto done;
1553 if (got_object_id_cmp(old_id, new_id) == 0)
1554 goto done;
1555 if (verbosity >= 0) {
1556 printf("Rejecting update of existing tag %s: %s\n",
1557 got_ref_get_name(ref), new_id_str);
1559 goto done;
1562 if (got_ref_is_symbolic(ref)) {
1563 if (verbosity >= 0) {
1564 printf("Replacing reference %s: %s\n",
1565 got_ref_get_name(ref),
1566 got_ref_get_symref_target(ref));
1568 err = got_ref_change_symref_to_ref(ref, new_id);
1569 if (err)
1570 goto done;
1571 err = got_ref_write(ref, repo);
1572 if (err)
1573 goto done;
1574 } else {
1575 err = got_ref_resolve(&old_id, repo, ref);
1576 if (err)
1577 goto done;
1578 if (got_object_id_cmp(old_id, new_id) == 0)
1579 goto done;
1581 err = got_ref_change_ref(ref, new_id);
1582 if (err)
1583 goto done;
1584 err = got_ref_write(ref, repo);
1585 if (err)
1586 goto done;
1589 if (verbosity >= 0)
1590 printf("Updated %s: %s\n", got_ref_get_name(ref),
1591 new_id_str);
1592 done:
1593 free(old_id);
1594 free(new_id_str);
1595 return err;
1598 static const struct got_error *
1599 update_symref(const char *refname, struct got_reference *target_ref,
1600 int verbosity, struct got_repository *repo)
1602 const struct got_error *err = NULL, *unlock_err;
1603 struct got_reference *symref;
1604 int symref_is_locked = 0;
1606 err = got_ref_open(&symref, repo, refname, 1);
1607 if (err) {
1608 if (err->code != GOT_ERR_NOT_REF)
1609 return err;
1610 err = got_ref_alloc_symref(&symref, refname, target_ref);
1611 if (err)
1612 goto done;
1614 err = got_ref_write(symref, repo);
1615 if (err)
1616 goto done;
1618 if (verbosity >= 0)
1619 printf("Created reference %s: %s\n",
1620 got_ref_get_name(symref),
1621 got_ref_get_symref_target(symref));
1622 } else {
1623 symref_is_locked = 1;
1625 if (strcmp(got_ref_get_symref_target(symref),
1626 got_ref_get_name(target_ref)) == 0)
1627 goto done;
1629 err = got_ref_change_symref(symref,
1630 got_ref_get_name(target_ref));
1631 if (err)
1632 goto done;
1634 err = got_ref_write(symref, repo);
1635 if (err)
1636 goto done;
1638 if (verbosity >= 0)
1639 printf("Updated %s: %s\n", got_ref_get_name(symref),
1640 got_ref_get_symref_target(symref));
1643 done:
1644 if (symref_is_locked) {
1645 unlock_err = got_ref_unlock(symref);
1646 if (unlock_err && err == NULL)
1647 err = unlock_err;
1649 got_ref_close(symref);
1650 return err;
1653 __dead static void
1654 usage_fetch(void)
1656 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1657 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1658 "[remote-repository-name]\n",
1659 getprogname());
1660 exit(1);
1663 static const struct got_error *
1664 delete_missing_ref(struct got_reference *ref,
1665 int verbosity, struct got_repository *repo)
1667 const struct got_error *err = NULL;
1668 struct got_object_id *id = NULL;
1669 char *id_str = NULL;
1671 if (got_ref_is_symbolic(ref)) {
1672 err = got_ref_delete(ref, repo);
1673 if (err)
1674 return err;
1675 if (verbosity >= 0) {
1676 printf("Deleted reference %s: %s\n",
1677 got_ref_get_name(ref),
1678 got_ref_get_symref_target(ref));
1680 } else {
1681 err = got_ref_resolve(&id, repo, ref);
1682 if (err)
1683 return err;
1684 err = got_object_id_str(&id_str, id);
1685 if (err)
1686 goto done;
1688 err = got_ref_delete(ref, repo);
1689 if (err)
1690 goto done;
1691 if (verbosity >= 0) {
1692 printf("Deleted reference %s: %s\n",
1693 got_ref_get_name(ref), id_str);
1696 done:
1697 free(id);
1698 free(id_str);
1699 return NULL;
1702 static const struct got_error *
1703 delete_missing_refs(struct got_pathlist_head *their_refs,
1704 struct got_pathlist_head *their_symrefs,
1705 const struct got_remote_repo *remote,
1706 int verbosity, struct got_repository *repo)
1708 const struct got_error *err = NULL, *unlock_err;
1709 struct got_reflist_head my_refs;
1710 struct got_reflist_entry *re;
1711 struct got_pathlist_entry *pe;
1712 char *remote_namespace = NULL;
1713 char *local_refname = NULL;
1715 SIMPLEQ_INIT(&my_refs);
1717 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
1718 == -1)
1719 return got_error_from_errno("asprintf");
1721 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1722 if (err)
1723 goto done;
1725 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1726 const char *refname = got_ref_get_name(re->ref);
1728 if (!remote->mirror_references) {
1729 if (strncmp(refname, remote_namespace,
1730 strlen(remote_namespace)) == 0) {
1731 if (strcmp(refname + strlen(remote_namespace),
1732 GOT_REF_HEAD) == 0)
1733 continue;
1734 if (asprintf(&local_refname, "refs/heads/%s",
1735 refname + strlen(remote_namespace)) == -1) {
1736 err = got_error_from_errno("asprintf");
1737 goto done;
1739 } else if (strncmp(refname, "refs/tags/", 10) != 0)
1740 continue;
1743 TAILQ_FOREACH(pe, their_refs, entry) {
1744 if (strcmp(local_refname, pe->path) == 0)
1745 break;
1747 if (pe != NULL)
1748 continue;
1750 TAILQ_FOREACH(pe, their_symrefs, entry) {
1751 if (strcmp(local_refname, pe->path) == 0)
1752 break;
1754 if (pe != NULL)
1755 continue;
1757 err = delete_missing_ref(re->ref, verbosity, repo);
1758 if (err)
1759 break;
1761 if (local_refname) {
1762 struct got_reference *ref;
1763 err = got_ref_open(&ref, repo, local_refname, 1);
1764 if (err) {
1765 if (err->code != GOT_ERR_NOT_REF)
1766 break;
1767 free(local_refname);
1768 local_refname = NULL;
1769 continue;
1771 err = delete_missing_ref(ref, verbosity, repo);
1772 if (err)
1773 break;
1774 unlock_err = got_ref_unlock(ref);
1775 got_ref_close(ref);
1776 if (unlock_err && err == NULL) {
1777 err = unlock_err;
1778 break;
1781 free(local_refname);
1782 local_refname = NULL;
1785 done:
1786 free(remote_namespace);
1787 free(local_refname);
1788 return err;
1791 static const struct got_error *
1792 update_wanted_ref(const char *refname, struct got_object_id *id,
1793 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1795 const struct got_error *err, *unlock_err;
1796 char *remote_refname;
1797 struct got_reference *ref;
1799 if (strncmp("refs/", refname, 5) == 0)
1800 refname += 5;
1802 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1803 remote_repo_name, refname) == -1)
1804 return got_error_from_errno("asprintf");
1806 err = got_ref_open(&ref, repo, remote_refname, 1);
1807 if (err) {
1808 if (err->code != GOT_ERR_NOT_REF)
1809 goto done;
1810 err = create_ref(remote_refname, id, verbosity, repo);
1811 } else {
1812 err = update_ref(ref, id, 0, verbosity, repo);
1813 unlock_err = got_ref_unlock(ref);
1814 if (unlock_err && err == NULL)
1815 err = unlock_err;
1816 got_ref_close(ref);
1818 done:
1819 free(remote_refname);
1820 return err;
1823 static const struct got_error *
1824 cmd_fetch(int argc, char *argv[])
1826 const struct got_error *error = NULL, *unlock_err;
1827 char *cwd = NULL, *repo_path = NULL;
1828 const char *remote_name;
1829 char *proto = NULL, *host = NULL, *port = NULL;
1830 char *repo_name = NULL, *server_path = NULL;
1831 const struct got_remote_repo *remotes, *remote = NULL;
1832 int nremotes;
1833 char *id_str = NULL;
1834 struct got_repository *repo = NULL;
1835 struct got_worktree *worktree = NULL;
1836 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
1837 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1838 struct got_pathlist_entry *pe;
1839 struct got_object_id *pack_hash = NULL;
1840 int i, ch, fetchfd = -1, fetchstatus;
1841 pid_t fetchpid = -1;
1842 struct got_fetch_progress_arg fpa;
1843 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
1844 int delete_refs = 0, replace_tags = 0;
1846 TAILQ_INIT(&refs);
1847 TAILQ_INIT(&symrefs);
1848 TAILQ_INIT(&wanted_branches);
1849 TAILQ_INIT(&wanted_refs);
1851 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
1852 switch (ch) {
1853 case 'a':
1854 fetch_all_branches = 1;
1855 break;
1856 case 'b':
1857 error = got_pathlist_append(&wanted_branches,
1858 optarg, NULL);
1859 if (error)
1860 return error;
1861 break;
1862 case 'd':
1863 delete_refs = 1;
1864 break;
1865 case 'l':
1866 list_refs_only = 1;
1867 break;
1868 case 'r':
1869 repo_path = realpath(optarg, NULL);
1870 if (repo_path == NULL)
1871 return got_error_from_errno2("realpath",
1872 optarg);
1873 got_path_strip_trailing_slashes(repo_path);
1874 break;
1875 case 't':
1876 replace_tags = 1;
1877 break;
1878 case 'v':
1879 if (verbosity < 0)
1880 verbosity = 0;
1881 else if (verbosity < 3)
1882 verbosity++;
1883 break;
1884 case 'q':
1885 verbosity = -1;
1886 break;
1887 case 'R':
1888 error = got_pathlist_append(&wanted_refs,
1889 optarg, NULL);
1890 if (error)
1891 return error;
1892 break;
1893 default:
1894 usage_fetch();
1895 break;
1898 argc -= optind;
1899 argv += optind;
1901 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1902 errx(1, "-a and -b options are mutually exclusive");
1903 if (list_refs_only) {
1904 if (!TAILQ_EMPTY(&wanted_branches))
1905 errx(1, "-l and -b options are mutually exclusive");
1906 if (fetch_all_branches)
1907 errx(1, "-l and -a options are mutually exclusive");
1908 if (delete_refs)
1909 errx(1, "-l and -d options are mutually exclusive");
1910 if (verbosity == -1)
1911 errx(1, "-l and -q options are mutually exclusive");
1914 if (argc == 0)
1915 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
1916 else if (argc == 1)
1917 remote_name = argv[0];
1918 else
1919 usage_fetch();
1921 cwd = getcwd(NULL, 0);
1922 if (cwd == NULL) {
1923 error = got_error_from_errno("getcwd");
1924 goto done;
1927 if (repo_path == NULL) {
1928 error = got_worktree_open(&worktree, cwd);
1929 if (error && error->code != GOT_ERR_NOT_WORKTREE)
1930 goto done;
1931 else
1932 error = NULL;
1933 if (worktree) {
1934 repo_path =
1935 strdup(got_worktree_get_repo_path(worktree));
1936 if (repo_path == NULL)
1937 error = got_error_from_errno("strdup");
1938 if (error)
1939 goto done;
1940 } else {
1941 repo_path = strdup(cwd);
1942 if (repo_path == NULL) {
1943 error = got_error_from_errno("strdup");
1944 goto done;
1949 error = got_repo_open(&repo, repo_path, NULL);
1950 if (error)
1951 goto done;
1953 if (worktree) {
1954 worktree_conf = got_worktree_get_gotconfig(worktree);
1955 if (worktree_conf) {
1956 got_gotconfig_get_remotes(&nremotes, &remotes,
1957 worktree_conf);
1958 for (i = 0; i < nremotes; i++) {
1959 remote = &remotes[i];
1960 if (strcmp(remote->name, remote_name) == 0)
1961 break;
1965 if (remote == NULL) {
1966 repo_conf = got_repo_get_gotconfig(repo);
1967 if (repo_conf) {
1968 got_gotconfig_get_remotes(&nremotes, &remotes,
1969 repo_conf);
1970 for (i = 0; i < nremotes; i++) {
1971 remote = &remotes[i];
1972 if (strcmp(remote->name, remote_name) == 0)
1973 break;
1977 if (remote == NULL) {
1978 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
1979 for (i = 0; i < nremotes; i++) {
1980 remote = &remotes[i];
1981 if (strcmp(remote->name, remote_name) == 0)
1982 break;
1985 if (remote == NULL) {
1986 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
1987 goto done;
1990 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1991 &repo_name, remote->url);
1992 if (error)
1993 goto done;
1995 if (strcmp(proto, "git") == 0) {
1996 #ifndef PROFILE
1997 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1998 "sendfd dns inet unveil", NULL) == -1)
1999 err(1, "pledge");
2000 #endif
2001 } else if (strcmp(proto, "git+ssh") == 0 ||
2002 strcmp(proto, "ssh") == 0) {
2003 #ifndef PROFILE
2004 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2005 "sendfd unveil", NULL) == -1)
2006 err(1, "pledge");
2007 #endif
2008 } else if (strcmp(proto, "http") == 0 ||
2009 strcmp(proto, "git+http") == 0) {
2010 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2011 goto done;
2012 } else {
2013 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2014 goto done;
2017 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
2018 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
2019 error = got_error_from_errno2("unveil",
2020 GOT_FETCH_PATH_SSH);
2021 goto done;
2024 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2025 if (error)
2026 goto done;
2028 if (verbosity >= 0)
2029 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2030 port ? ":" : "", port ? port : "");
2032 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2033 server_path, verbosity);
2034 if (error)
2035 goto done;
2037 fpa.last_scaled_size[0] = '\0';
2038 fpa.last_p_indexed = -1;
2039 fpa.last_p_resolved = -1;
2040 fpa.verbosity = verbosity;
2041 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2042 remote->mirror_references, fetch_all_branches, &wanted_branches,
2043 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2044 fetch_progress, &fpa);
2045 if (error)
2046 goto done;
2048 if (list_refs_only) {
2049 error = list_remote_refs(&symrefs, &refs);
2050 goto done;
2053 if (pack_hash == NULL) {
2054 if (verbosity >= 0)
2055 printf("Already up-to-date\n");
2056 } else if (verbosity >= 0) {
2057 error = got_object_id_str(&id_str, pack_hash);
2058 if (error)
2059 goto done;
2060 printf("\nFetched %s.pack\n", id_str);
2061 free(id_str);
2062 id_str = NULL;
2065 /* Update references provided with the pack file. */
2066 TAILQ_FOREACH(pe, &refs, entry) {
2067 const char *refname = pe->path;
2068 struct got_object_id *id = pe->data;
2069 struct got_reference *ref;
2070 char *remote_refname;
2072 if (is_wanted_ref(&wanted_refs, refname) &&
2073 !remote->mirror_references) {
2074 error = update_wanted_ref(refname, id,
2075 remote->name, verbosity, repo);
2076 if (error)
2077 goto done;
2078 continue;
2081 if (remote->mirror_references ||
2082 strncmp("refs/tags/", refname, 10) == 0) {
2083 error = got_ref_open(&ref, repo, refname, 1);
2084 if (error) {
2085 if (error->code != GOT_ERR_NOT_REF)
2086 goto done;
2087 error = create_ref(refname, id, verbosity,
2088 repo);
2089 if (error)
2090 goto done;
2091 } else {
2092 error = update_ref(ref, id, replace_tags,
2093 verbosity, repo);
2094 unlock_err = got_ref_unlock(ref);
2095 if (unlock_err && error == NULL)
2096 error = unlock_err;
2097 got_ref_close(ref);
2098 if (error)
2099 goto done;
2101 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2102 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2103 remote_name, refname + 11) == -1) {
2104 error = got_error_from_errno("asprintf");
2105 goto done;
2108 error = got_ref_open(&ref, repo, remote_refname, 1);
2109 if (error) {
2110 if (error->code != GOT_ERR_NOT_REF)
2111 goto done;
2112 error = create_ref(remote_refname, id,
2113 verbosity, repo);
2114 if (error)
2115 goto done;
2116 } else {
2117 error = update_ref(ref, id, replace_tags,
2118 verbosity, repo);
2119 unlock_err = got_ref_unlock(ref);
2120 if (unlock_err && error == NULL)
2121 error = unlock_err;
2122 got_ref_close(ref);
2123 if (error)
2124 goto done;
2127 /* Also create a local branch if none exists yet. */
2128 error = got_ref_open(&ref, repo, refname, 1);
2129 if (error) {
2130 if (error->code != GOT_ERR_NOT_REF)
2131 goto done;
2132 error = create_ref(refname, id, verbosity,
2133 repo);
2134 if (error)
2135 goto done;
2136 } else {
2137 unlock_err = got_ref_unlock(ref);
2138 if (unlock_err && error == NULL)
2139 error = unlock_err;
2140 got_ref_close(ref);
2144 if (delete_refs) {
2145 error = delete_missing_refs(&refs, &symrefs, remote,
2146 verbosity, repo);
2147 if (error)
2148 goto done;
2151 if (!remote->mirror_references) {
2152 /* Update remote HEAD reference if the server provided one. */
2153 TAILQ_FOREACH(pe, &symrefs, entry) {
2154 struct got_reference *target_ref;
2155 const char *refname = pe->path;
2156 const char *target = pe->data;
2157 char *remote_refname = NULL, *remote_target = NULL;
2159 if (strcmp(refname, GOT_REF_HEAD) != 0)
2160 continue;
2162 if (strncmp("refs/heads/", target, 11) != 0)
2163 continue;
2165 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2166 remote->name, refname) == -1) {
2167 error = got_error_from_errno("asprintf");
2168 goto done;
2170 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2171 remote->name, target + 11) == -1) {
2172 error = got_error_from_errno("asprintf");
2173 free(remote_refname);
2174 goto done;
2177 error = got_ref_open(&target_ref, repo, remote_target,
2178 0);
2179 if (error) {
2180 free(remote_refname);
2181 free(remote_target);
2182 if (error->code == GOT_ERR_NOT_REF) {
2183 error = NULL;
2184 continue;
2186 goto done;
2188 error = update_symref(remote_refname, target_ref,
2189 verbosity, repo);
2190 free(remote_refname);
2191 free(remote_target);
2192 got_ref_close(target_ref);
2193 if (error)
2194 goto done;
2197 done:
2198 if (fetchpid > 0) {
2199 if (kill(fetchpid, SIGTERM) == -1)
2200 error = got_error_from_errno("kill");
2201 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2202 error = got_error_from_errno("waitpid");
2204 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2205 error = got_error_from_errno("close");
2206 if (repo)
2207 got_repo_close(repo);
2208 if (worktree)
2209 got_worktree_close(worktree);
2210 TAILQ_FOREACH(pe, &refs, entry) {
2211 free((void *)pe->path);
2212 free(pe->data);
2214 got_pathlist_free(&refs);
2215 TAILQ_FOREACH(pe, &symrefs, entry) {
2216 free((void *)pe->path);
2217 free(pe->data);
2219 got_pathlist_free(&symrefs);
2220 got_pathlist_free(&wanted_branches);
2221 got_pathlist_free(&wanted_refs);
2222 free(id_str);
2223 free(cwd);
2224 free(repo_path);
2225 free(pack_hash);
2226 free(proto);
2227 free(host);
2228 free(port);
2229 free(server_path);
2230 free(repo_name);
2231 return error;
2235 __dead static void
2236 usage_checkout(void)
2238 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2239 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2240 exit(1);
2243 static void
2244 show_worktree_base_ref_warning(void)
2246 fprintf(stderr, "%s: warning: could not create a reference "
2247 "to the work tree's base commit; the commit could be "
2248 "garbage-collected by Git; making the repository "
2249 "writable and running 'got update' will prevent this\n",
2250 getprogname());
2253 struct got_checkout_progress_arg {
2254 const char *worktree_path;
2255 int had_base_commit_ref_error;
2258 static const struct got_error *
2259 checkout_progress(void *arg, unsigned char status, const char *path)
2261 struct got_checkout_progress_arg *a = arg;
2263 /* Base commit bump happens silently. */
2264 if (status == GOT_STATUS_BUMP_BASE)
2265 return NULL;
2267 if (status == GOT_STATUS_BASE_REF_ERR) {
2268 a->had_base_commit_ref_error = 1;
2269 return NULL;
2272 while (path[0] == '/')
2273 path++;
2275 printf("%c %s/%s\n", status, a->worktree_path, path);
2276 return NULL;
2279 static const struct got_error *
2280 check_cancelled(void *arg)
2282 if (sigint_received || sigpipe_received)
2283 return got_error(GOT_ERR_CANCELLED);
2284 return NULL;
2287 static const struct got_error *
2288 check_linear_ancestry(struct got_object_id *commit_id,
2289 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2290 struct got_repository *repo)
2292 const struct got_error *err = NULL;
2293 struct got_object_id *yca_id;
2295 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2296 commit_id, base_commit_id, repo, check_cancelled, NULL);
2297 if (err)
2298 return err;
2300 if (yca_id == NULL)
2301 return got_error(GOT_ERR_ANCESTRY);
2304 * Require a straight line of history between the target commit
2305 * and the work tree's base commit.
2307 * Non-linear situations such as this require a rebase:
2309 * (commit) D F (base_commit)
2310 * \ /
2311 * C E
2312 * \ /
2313 * B (yca)
2314 * |
2315 * A
2317 * 'got update' only handles linear cases:
2318 * Update forwards in time: A (base/yca) - B - C - D (commit)
2319 * Update backwards in time: D (base) - C - B - A (commit/yca)
2321 if (allow_forwards_in_time_only) {
2322 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2323 return got_error(GOT_ERR_ANCESTRY);
2324 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2325 got_object_id_cmp(base_commit_id, yca_id) != 0)
2326 return got_error(GOT_ERR_ANCESTRY);
2328 free(yca_id);
2329 return NULL;
2332 static const struct got_error *
2333 check_same_branch(struct got_object_id *commit_id,
2334 struct got_reference *head_ref, struct got_object_id *yca_id,
2335 struct got_repository *repo)
2337 const struct got_error *err = NULL;
2338 struct got_commit_graph *graph = NULL;
2339 struct got_object_id *head_commit_id = NULL;
2340 int is_same_branch = 0;
2342 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2343 if (err)
2344 goto done;
2346 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2347 is_same_branch = 1;
2348 goto done;
2350 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2351 is_same_branch = 1;
2352 goto done;
2355 err = got_commit_graph_open(&graph, "/", 1);
2356 if (err)
2357 goto done;
2359 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2360 check_cancelled, NULL);
2361 if (err)
2362 goto done;
2364 for (;;) {
2365 struct got_object_id *id;
2366 err = got_commit_graph_iter_next(&id, graph, repo,
2367 check_cancelled, NULL);
2368 if (err) {
2369 if (err->code == GOT_ERR_ITER_COMPLETED)
2370 err = NULL;
2371 break;
2374 if (id) {
2375 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2376 break;
2377 if (got_object_id_cmp(id, commit_id) == 0) {
2378 is_same_branch = 1;
2379 break;
2383 done:
2384 if (graph)
2385 got_commit_graph_close(graph);
2386 free(head_commit_id);
2387 if (!err && !is_same_branch)
2388 err = got_error(GOT_ERR_ANCESTRY);
2389 return err;
2392 static const struct got_error *
2393 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2395 static char msg[512];
2396 const char *branch_name;
2398 if (got_ref_is_symbolic(ref))
2399 branch_name = got_ref_get_symref_target(ref);
2400 else
2401 branch_name = got_ref_get_name(ref);
2403 if (strncmp("refs/heads/", branch_name, 11) == 0)
2404 branch_name += 11;
2406 snprintf(msg, sizeof(msg),
2407 "target commit is not contained in branch '%s'; "
2408 "the branch to use must be specified with -b; "
2409 "if necessary a new branch can be created for "
2410 "this commit with 'got branch -c %s BRANCH_NAME'",
2411 branch_name, commit_id_str);
2413 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2416 static const struct got_error *
2417 cmd_checkout(int argc, char *argv[])
2419 const struct got_error *error = NULL;
2420 struct got_repository *repo = NULL;
2421 struct got_reference *head_ref = NULL;
2422 struct got_worktree *worktree = NULL;
2423 char *repo_path = NULL;
2424 char *worktree_path = NULL;
2425 const char *path_prefix = "";
2426 const char *branch_name = GOT_REF_HEAD;
2427 char *commit_id_str = NULL;
2428 char *cwd = NULL, *path = NULL;
2429 int ch, same_path_prefix, allow_nonempty = 0;
2430 struct got_pathlist_head paths;
2431 struct got_checkout_progress_arg cpa;
2433 TAILQ_INIT(&paths);
2435 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2436 switch (ch) {
2437 case 'b':
2438 branch_name = optarg;
2439 break;
2440 case 'c':
2441 commit_id_str = strdup(optarg);
2442 if (commit_id_str == NULL)
2443 return got_error_from_errno("strdup");
2444 break;
2445 case 'E':
2446 allow_nonempty = 1;
2447 break;
2448 case 'p':
2449 path_prefix = optarg;
2450 break;
2451 default:
2452 usage_checkout();
2453 /* NOTREACHED */
2457 argc -= optind;
2458 argv += optind;
2460 #ifndef PROFILE
2461 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2462 "unveil", NULL) == -1)
2463 err(1, "pledge");
2464 #endif
2465 if (argc == 1) {
2466 char *base, *dotgit;
2467 repo_path = realpath(argv[0], NULL);
2468 if (repo_path == NULL)
2469 return got_error_from_errno2("realpath", argv[0]);
2470 cwd = getcwd(NULL, 0);
2471 if (cwd == NULL) {
2472 error = got_error_from_errno("getcwd");
2473 goto done;
2475 if (path_prefix[0])
2476 path = strdup(path_prefix);
2477 else
2478 path = strdup(repo_path);
2479 if (path == NULL) {
2480 error = got_error_from_errno("strdup");
2481 goto done;
2483 base = basename(path);
2484 if (base == NULL) {
2485 error = got_error_from_errno2("basename", path);
2486 goto done;
2488 dotgit = strstr(base, ".git");
2489 if (dotgit)
2490 *dotgit = '\0';
2491 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2492 error = got_error_from_errno("asprintf");
2493 goto done;
2495 } else if (argc == 2) {
2496 repo_path = realpath(argv[0], NULL);
2497 if (repo_path == NULL) {
2498 error = got_error_from_errno2("realpath", argv[0]);
2499 goto done;
2501 worktree_path = realpath(argv[1], NULL);
2502 if (worktree_path == NULL) {
2503 if (errno != ENOENT) {
2504 error = got_error_from_errno2("realpath",
2505 argv[1]);
2506 goto done;
2508 worktree_path = strdup(argv[1]);
2509 if (worktree_path == NULL) {
2510 error = got_error_from_errno("strdup");
2511 goto done;
2514 } else
2515 usage_checkout();
2517 got_path_strip_trailing_slashes(repo_path);
2518 got_path_strip_trailing_slashes(worktree_path);
2520 error = got_repo_open(&repo, repo_path, NULL);
2521 if (error != NULL)
2522 goto done;
2524 /* Pre-create work tree path for unveil(2) */
2525 error = got_path_mkdir(worktree_path);
2526 if (error) {
2527 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2528 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2529 goto done;
2530 if (!allow_nonempty &&
2531 !got_path_dir_is_empty(worktree_path)) {
2532 error = got_error_path(worktree_path,
2533 GOT_ERR_DIR_NOT_EMPTY);
2534 goto done;
2538 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2539 if (error)
2540 goto done;
2542 error = got_ref_open(&head_ref, repo, branch_name, 0);
2543 if (error != NULL)
2544 goto done;
2546 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2547 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2548 goto done;
2550 error = got_worktree_open(&worktree, worktree_path);
2551 if (error != NULL)
2552 goto done;
2554 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2555 path_prefix);
2556 if (error != NULL)
2557 goto done;
2558 if (!same_path_prefix) {
2559 error = got_error(GOT_ERR_PATH_PREFIX);
2560 goto done;
2563 if (commit_id_str) {
2564 struct got_object_id *commit_id;
2565 error = got_repo_match_object_id(&commit_id, NULL,
2566 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2567 if (error)
2568 goto done;
2569 error = check_linear_ancestry(commit_id,
2570 got_worktree_get_base_commit_id(worktree), 0, repo);
2571 if (error != NULL) {
2572 free(commit_id);
2573 if (error->code == GOT_ERR_ANCESTRY) {
2574 error = checkout_ancestry_error(
2575 head_ref, commit_id_str);
2577 goto done;
2579 error = check_same_branch(commit_id, head_ref, NULL, repo);
2580 if (error) {
2581 if (error->code == GOT_ERR_ANCESTRY) {
2582 error = checkout_ancestry_error(
2583 head_ref, commit_id_str);
2585 goto done;
2587 error = got_worktree_set_base_commit_id(worktree, repo,
2588 commit_id);
2589 free(commit_id);
2590 if (error)
2591 goto done;
2594 error = got_pathlist_append(&paths, "", NULL);
2595 if (error)
2596 goto done;
2597 cpa.worktree_path = worktree_path;
2598 cpa.had_base_commit_ref_error = 0;
2599 error = got_worktree_checkout_files(worktree, &paths, repo,
2600 checkout_progress, &cpa, check_cancelled, NULL);
2601 if (error != NULL)
2602 goto done;
2604 printf("Now shut up and hack\n");
2605 if (cpa.had_base_commit_ref_error)
2606 show_worktree_base_ref_warning();
2607 done:
2608 got_pathlist_free(&paths);
2609 free(commit_id_str);
2610 free(repo_path);
2611 free(worktree_path);
2612 free(cwd);
2613 free(path);
2614 return error;
2617 struct got_update_progress_arg {
2618 int did_something;
2619 int conflicts;
2620 int obstructed;
2621 int not_updated;
2624 void
2625 print_update_progress_stats(struct got_update_progress_arg *upa)
2627 if (!upa->did_something)
2628 return;
2630 if (upa->conflicts > 0)
2631 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2632 if (upa->obstructed > 0)
2633 printf("File paths obstructed by a non-regular file: %d\n",
2634 upa->obstructed);
2635 if (upa->not_updated > 0)
2636 printf("Files not updated because of existing merge "
2637 "conflicts: %d\n", upa->not_updated);
2640 __dead static void
2641 usage_update(void)
2643 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2644 getprogname());
2645 exit(1);
2648 static const struct got_error *
2649 update_progress(void *arg, unsigned char status, const char *path)
2651 struct got_update_progress_arg *upa = arg;
2653 if (status == GOT_STATUS_EXISTS ||
2654 status == GOT_STATUS_BASE_REF_ERR)
2655 return NULL;
2657 upa->did_something = 1;
2659 /* Base commit bump happens silently. */
2660 if (status == GOT_STATUS_BUMP_BASE)
2661 return NULL;
2663 if (status == GOT_STATUS_CONFLICT)
2664 upa->conflicts++;
2665 if (status == GOT_STATUS_OBSTRUCTED)
2666 upa->obstructed++;
2667 if (status == GOT_STATUS_CANNOT_UPDATE)
2668 upa->not_updated++;
2670 while (path[0] == '/')
2671 path++;
2672 printf("%c %s\n", status, path);
2673 return NULL;
2676 static const struct got_error *
2677 switch_head_ref(struct got_reference *head_ref,
2678 struct got_object_id *commit_id, struct got_worktree *worktree,
2679 struct got_repository *repo)
2681 const struct got_error *err = NULL;
2682 char *base_id_str;
2683 int ref_has_moved = 0;
2685 /* Trivial case: switching between two different references. */
2686 if (strcmp(got_ref_get_name(head_ref),
2687 got_worktree_get_head_ref_name(worktree)) != 0) {
2688 printf("Switching work tree from %s to %s\n",
2689 got_worktree_get_head_ref_name(worktree),
2690 got_ref_get_name(head_ref));
2691 return got_worktree_set_head_ref(worktree, head_ref);
2694 err = check_linear_ancestry(commit_id,
2695 got_worktree_get_base_commit_id(worktree), 0, repo);
2696 if (err) {
2697 if (err->code != GOT_ERR_ANCESTRY)
2698 return err;
2699 ref_has_moved = 1;
2701 if (!ref_has_moved)
2702 return NULL;
2704 /* Switching to a rebased branch with the same reference name. */
2705 err = got_object_id_str(&base_id_str,
2706 got_worktree_get_base_commit_id(worktree));
2707 if (err)
2708 return err;
2709 printf("Reference %s now points at a different branch\n",
2710 got_worktree_get_head_ref_name(worktree));
2711 printf("Switching work tree from %s to %s\n", base_id_str,
2712 got_worktree_get_head_ref_name(worktree));
2713 return NULL;
2716 static const struct got_error *
2717 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2719 const struct got_error *err;
2720 int in_progress;
2722 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2723 if (err)
2724 return err;
2725 if (in_progress)
2726 return got_error(GOT_ERR_REBASING);
2728 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2729 if (err)
2730 return err;
2731 if (in_progress)
2732 return got_error(GOT_ERR_HISTEDIT_BUSY);
2734 return NULL;
2737 static const struct got_error *
2738 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2739 char *argv[], struct got_worktree *worktree)
2741 const struct got_error *err = NULL;
2742 char *path;
2743 int i;
2745 if (argc == 0) {
2746 path = strdup("");
2747 if (path == NULL)
2748 return got_error_from_errno("strdup");
2749 return got_pathlist_append(paths, path, NULL);
2752 for (i = 0; i < argc; i++) {
2753 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2754 if (err)
2755 break;
2756 err = got_pathlist_append(paths, path, NULL);
2757 if (err) {
2758 free(path);
2759 break;
2763 return err;
2766 static const struct got_error *
2767 wrap_not_worktree_error(const struct got_error *orig_err,
2768 const char *cmdname, const char *path)
2770 const struct got_error *err;
2771 struct got_repository *repo;
2772 static char msg[512];
2774 err = got_repo_open(&repo, path, NULL);
2775 if (err)
2776 return orig_err;
2778 snprintf(msg, sizeof(msg),
2779 "'got %s' needs a work tree in addition to a git repository\n"
2780 "Work trees can be checked out from this Git repository with "
2781 "'got checkout'.\n"
2782 "The got(1) manual page contains more information.", cmdname);
2783 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2784 got_repo_close(repo);
2785 return err;
2788 static const struct got_error *
2789 cmd_update(int argc, char *argv[])
2791 const struct got_error *error = NULL;
2792 struct got_repository *repo = NULL;
2793 struct got_worktree *worktree = NULL;
2794 char *worktree_path = NULL;
2795 struct got_object_id *commit_id = NULL;
2796 char *commit_id_str = NULL;
2797 const char *branch_name = NULL;
2798 struct got_reference *head_ref = NULL;
2799 struct got_pathlist_head paths;
2800 struct got_pathlist_entry *pe;
2801 int ch;
2802 struct got_update_progress_arg upa;
2804 TAILQ_INIT(&paths);
2806 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2807 switch (ch) {
2808 case 'b':
2809 branch_name = optarg;
2810 break;
2811 case 'c':
2812 commit_id_str = strdup(optarg);
2813 if (commit_id_str == NULL)
2814 return got_error_from_errno("strdup");
2815 break;
2816 default:
2817 usage_update();
2818 /* NOTREACHED */
2822 argc -= optind;
2823 argv += optind;
2825 #ifndef PROFILE
2826 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2827 "unveil", NULL) == -1)
2828 err(1, "pledge");
2829 #endif
2830 worktree_path = getcwd(NULL, 0);
2831 if (worktree_path == NULL) {
2832 error = got_error_from_errno("getcwd");
2833 goto done;
2835 error = got_worktree_open(&worktree, worktree_path);
2836 if (error) {
2837 if (error->code == GOT_ERR_NOT_WORKTREE)
2838 error = wrap_not_worktree_error(error, "update",
2839 worktree_path);
2840 goto done;
2843 error = check_rebase_or_histedit_in_progress(worktree);
2844 if (error)
2845 goto done;
2847 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
2848 NULL);
2849 if (error != NULL)
2850 goto done;
2852 error = apply_unveil(got_repo_get_path(repo), 0,
2853 got_worktree_get_root_path(worktree));
2854 if (error)
2855 goto done;
2857 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2858 if (error)
2859 goto done;
2861 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
2862 got_worktree_get_head_ref_name(worktree), 0);
2863 if (error != NULL)
2864 goto done;
2865 if (commit_id_str == NULL) {
2866 error = got_ref_resolve(&commit_id, repo, head_ref);
2867 if (error != NULL)
2868 goto done;
2869 error = got_object_id_str(&commit_id_str, commit_id);
2870 if (error != NULL)
2871 goto done;
2872 } else {
2873 error = got_repo_match_object_id(&commit_id, NULL,
2874 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2875 free(commit_id_str);
2876 commit_id_str = NULL;
2877 if (error)
2878 goto done;
2879 error = got_object_id_str(&commit_id_str, commit_id);
2880 if (error)
2881 goto done;
2884 if (branch_name) {
2885 struct got_object_id *head_commit_id;
2886 TAILQ_FOREACH(pe, &paths, entry) {
2887 if (pe->path_len == 0)
2888 continue;
2889 error = got_error_msg(GOT_ERR_BAD_PATH,
2890 "switching between branches requires that "
2891 "the entire work tree gets updated");
2892 goto done;
2894 error = got_ref_resolve(&head_commit_id, repo, head_ref);
2895 if (error)
2896 goto done;
2897 error = check_linear_ancestry(commit_id, head_commit_id, 0,
2898 repo);
2899 free(head_commit_id);
2900 if (error != NULL)
2901 goto done;
2902 error = check_same_branch(commit_id, head_ref, NULL, repo);
2903 if (error)
2904 goto done;
2905 error = switch_head_ref(head_ref, commit_id, worktree, repo);
2906 if (error)
2907 goto done;
2908 } else {
2909 error = check_linear_ancestry(commit_id,
2910 got_worktree_get_base_commit_id(worktree), 0, repo);
2911 if (error != NULL) {
2912 if (error->code == GOT_ERR_ANCESTRY)
2913 error = got_error(GOT_ERR_BRANCH_MOVED);
2914 goto done;
2916 error = check_same_branch(commit_id, head_ref, NULL, repo);
2917 if (error)
2918 goto done;
2921 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
2922 commit_id) != 0) {
2923 error = got_worktree_set_base_commit_id(worktree, repo,
2924 commit_id);
2925 if (error)
2926 goto done;
2929 memset(&upa, 0, sizeof(upa));
2930 error = got_worktree_checkout_files(worktree, &paths, repo,
2931 update_progress, &upa, check_cancelled, NULL);
2932 if (error != NULL)
2933 goto done;
2935 if (upa.did_something)
2936 printf("Updated to commit %s\n", commit_id_str);
2937 else
2938 printf("Already up-to-date\n");
2939 print_update_progress_stats(&upa);
2940 done:
2941 free(worktree_path);
2942 TAILQ_FOREACH(pe, &paths, entry)
2943 free((char *)pe->path);
2944 got_pathlist_free(&paths);
2945 free(commit_id);
2946 free(commit_id_str);
2947 return error;
2950 static const struct got_error *
2951 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
2952 const char *path, int diff_context, int ignore_whitespace,
2953 struct got_repository *repo)
2955 const struct got_error *err = NULL;
2956 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
2958 if (blob_id1) {
2959 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
2960 if (err)
2961 goto done;
2964 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
2965 if (err)
2966 goto done;
2968 while (path[0] == '/')
2969 path++;
2970 err = got_diff_blob(blob1, blob2, path, path, diff_context,
2971 ignore_whitespace, stdout);
2972 done:
2973 if (blob1)
2974 got_object_blob_close(blob1);
2975 got_object_blob_close(blob2);
2976 return err;
2979 static const struct got_error *
2980 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
2981 const char *path, int diff_context, int ignore_whitespace,
2982 struct got_repository *repo)
2984 const struct got_error *err = NULL;
2985 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
2986 struct got_diff_blob_output_unidiff_arg arg;
2988 if (tree_id1) {
2989 err = got_object_open_as_tree(&tree1, repo, tree_id1);
2990 if (err)
2991 goto done;
2994 err = got_object_open_as_tree(&tree2, repo, tree_id2);
2995 if (err)
2996 goto done;
2998 arg.diff_context = diff_context;
2999 arg.ignore_whitespace = ignore_whitespace;
3000 arg.outfile = stdout;
3001 while (path[0] == '/')
3002 path++;
3003 err = got_diff_tree(tree1, tree2, path, path, repo,
3004 got_diff_blob_output_unidiff, &arg, 1);
3005 done:
3006 if (tree1)
3007 got_object_tree_close(tree1);
3008 if (tree2)
3009 got_object_tree_close(tree2);
3010 return err;
3013 static const struct got_error *
3014 get_changed_paths(struct got_pathlist_head *paths,
3015 struct got_commit_object *commit, struct got_repository *repo)
3017 const struct got_error *err = NULL;
3018 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3019 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3020 struct got_object_qid *qid;
3022 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3023 if (qid != NULL) {
3024 struct got_commit_object *pcommit;
3025 err = got_object_open_as_commit(&pcommit, repo,
3026 qid->id);
3027 if (err)
3028 return err;
3030 tree_id1 = got_object_commit_get_tree_id(pcommit);
3031 got_object_commit_close(pcommit);
3035 if (tree_id1) {
3036 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3037 if (err)
3038 goto done;
3041 tree_id2 = got_object_commit_get_tree_id(commit);
3042 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3043 if (err)
3044 goto done;
3046 err = got_diff_tree(tree1, tree2, "", "", repo,
3047 got_diff_tree_collect_changed_paths, paths, 0);
3048 done:
3049 if (tree1)
3050 got_object_tree_close(tree1);
3051 if (tree2)
3052 got_object_tree_close(tree2);
3053 return err;
3056 static const struct got_error *
3057 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3058 const char *path, int diff_context, struct got_repository *repo)
3060 const struct got_error *err = NULL;
3061 struct got_commit_object *pcommit = NULL;
3062 char *id_str1 = NULL, *id_str2 = NULL;
3063 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3064 struct got_object_qid *qid;
3066 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3067 if (qid != NULL) {
3068 err = got_object_open_as_commit(&pcommit, repo,
3069 qid->id);
3070 if (err)
3071 return err;
3074 if (path && path[0] != '\0') {
3075 int obj_type;
3076 err = got_object_id_by_path(&obj_id2, repo, id, path);
3077 if (err)
3078 goto done;
3079 err = got_object_id_str(&id_str2, obj_id2);
3080 if (err) {
3081 free(obj_id2);
3082 goto done;
3084 if (pcommit) {
3085 err = got_object_id_by_path(&obj_id1, repo,
3086 qid->id, path);
3087 if (err) {
3088 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3089 free(obj_id2);
3090 goto done;
3092 } else {
3093 err = got_object_id_str(&id_str1, obj_id1);
3094 if (err) {
3095 free(obj_id2);
3096 goto done;
3100 err = got_object_get_type(&obj_type, repo, obj_id2);
3101 if (err) {
3102 free(obj_id2);
3103 goto done;
3105 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3106 switch (obj_type) {
3107 case GOT_OBJ_TYPE_BLOB:
3108 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3109 0, repo);
3110 break;
3111 case GOT_OBJ_TYPE_TREE:
3112 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3113 0, repo);
3114 break;
3115 default:
3116 err = got_error(GOT_ERR_OBJ_TYPE);
3117 break;
3119 free(obj_id1);
3120 free(obj_id2);
3121 } else {
3122 obj_id2 = got_object_commit_get_tree_id(commit);
3123 err = got_object_id_str(&id_str2, obj_id2);
3124 if (err)
3125 goto done;
3126 obj_id1 = got_object_commit_get_tree_id(pcommit);
3127 err = got_object_id_str(&id_str1, obj_id1);
3128 if (err)
3129 goto done;
3130 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3131 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
3133 done:
3134 free(id_str1);
3135 free(id_str2);
3136 if (pcommit)
3137 got_object_commit_close(pcommit);
3138 return err;
3141 static char *
3142 get_datestr(time_t *time, char *datebuf)
3144 struct tm mytm, *tm;
3145 char *p, *s;
3147 tm = gmtime_r(time, &mytm);
3148 if (tm == NULL)
3149 return NULL;
3150 s = asctime_r(tm, datebuf);
3151 if (s == NULL)
3152 return NULL;
3153 p = strchr(s, '\n');
3154 if (p)
3155 *p = '\0';
3156 return s;
3159 static const struct got_error *
3160 match_logmsg(int *have_match, struct got_object_id *id,
3161 struct got_commit_object *commit, regex_t *regex)
3163 const struct got_error *err = NULL;
3164 regmatch_t regmatch;
3165 char *id_str = NULL, *logmsg = NULL;
3167 *have_match = 0;
3169 err = got_object_id_str(&id_str, id);
3170 if (err)
3171 return err;
3173 err = got_object_commit_get_logmsg(&logmsg, commit);
3174 if (err)
3175 goto done;
3177 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3178 *have_match = 1;
3179 done:
3180 free(id_str);
3181 free(logmsg);
3182 return err;
3185 static void
3186 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3187 regex_t *regex)
3189 regmatch_t regmatch;
3190 struct got_pathlist_entry *pe;
3192 *have_match = 0;
3194 TAILQ_FOREACH(pe, changed_paths, entry) {
3195 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3196 *have_match = 1;
3197 break;
3202 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3204 static const struct got_error *
3205 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3206 struct got_repository *repo, const char *path,
3207 struct got_pathlist_head *changed_paths, int show_patch,
3208 int diff_context, struct got_reflist_head *refs)
3210 const struct got_error *err = NULL;
3211 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3212 char datebuf[26];
3213 time_t committer_time;
3214 const char *author, *committer;
3215 char *refs_str = NULL;
3216 struct got_reflist_entry *re;
3218 SIMPLEQ_FOREACH(re, refs, entry) {
3219 char *s;
3220 const char *name;
3221 struct got_tag_object *tag = NULL;
3222 struct got_object_id *ref_id;
3223 int cmp;
3225 name = got_ref_get_name(re->ref);
3226 if (strcmp(name, GOT_REF_HEAD) == 0)
3227 continue;
3228 if (strncmp(name, "refs/", 5) == 0)
3229 name += 5;
3230 if (strncmp(name, "got/", 4) == 0)
3231 continue;
3232 if (strncmp(name, "heads/", 6) == 0)
3233 name += 6;
3234 if (strncmp(name, "remotes/", 8) == 0) {
3235 name += 8;
3236 s = strstr(name, "/" GOT_REF_HEAD);
3237 if (s != NULL && s[strlen(s)] == '\0')
3238 continue;
3240 err = got_ref_resolve(&ref_id, repo, re->ref);
3241 if (err)
3242 return err;
3243 if (strncmp(name, "tags/", 5) == 0) {
3244 err = got_object_open_as_tag(&tag, repo, ref_id);
3245 if (err) {
3246 if (err->code != GOT_ERR_OBJ_TYPE) {
3247 free(ref_id);
3248 return err;
3250 /* Ref points at something other than a tag. */
3251 err = NULL;
3252 tag = NULL;
3255 cmp = got_object_id_cmp(tag ?
3256 got_object_tag_get_object_id(tag) : ref_id, id);
3257 free(ref_id);
3258 if (tag)
3259 got_object_tag_close(tag);
3260 if (cmp != 0)
3261 continue;
3262 s = refs_str;
3263 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3264 name) == -1) {
3265 err = got_error_from_errno("asprintf");
3266 free(s);
3267 return err;
3269 free(s);
3271 err = got_object_id_str(&id_str, id);
3272 if (err)
3273 return err;
3275 printf(GOT_COMMIT_SEP_STR);
3276 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3277 refs_str ? refs_str : "", refs_str ? ")" : "");
3278 free(id_str);
3279 id_str = NULL;
3280 free(refs_str);
3281 refs_str = NULL;
3282 printf("from: %s\n", got_object_commit_get_author(commit));
3283 committer_time = got_object_commit_get_committer_time(commit);
3284 datestr = get_datestr(&committer_time, datebuf);
3285 if (datestr)
3286 printf("date: %s UTC\n", datestr);
3287 author = got_object_commit_get_author(commit);
3288 committer = got_object_commit_get_committer(commit);
3289 if (strcmp(author, committer) != 0)
3290 printf("via: %s\n", committer);
3291 if (got_object_commit_get_nparents(commit) > 1) {
3292 const struct got_object_id_queue *parent_ids;
3293 struct got_object_qid *qid;
3294 int n = 1;
3295 parent_ids = got_object_commit_get_parent_ids(commit);
3296 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3297 err = got_object_id_str(&id_str, qid->id);
3298 if (err)
3299 return err;
3300 printf("parent %d: %s\n", n++, id_str);
3301 free(id_str);
3305 err = got_object_commit_get_logmsg(&logmsg0, commit);
3306 if (err)
3307 return err;
3309 logmsg = logmsg0;
3310 do {
3311 line = strsep(&logmsg, "\n");
3312 if (line)
3313 printf(" %s\n", line);
3314 } while (line);
3315 free(logmsg0);
3317 if (changed_paths) {
3318 struct got_pathlist_entry *pe;
3319 TAILQ_FOREACH(pe, changed_paths, entry) {
3320 struct got_diff_changed_path *cp = pe->data;
3321 printf(" %c %s\n", cp->status, pe->path);
3323 printf("\n");
3325 if (show_patch) {
3326 err = print_patch(commit, id, path, diff_context, repo);
3327 if (err == 0)
3328 printf("\n");
3331 if (fflush(stdout) != 0 && err == NULL)
3332 err = got_error_from_errno("fflush");
3333 return err;
3336 static const struct got_error *
3337 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3338 struct got_repository *repo, const char *path, int show_changed_paths,
3339 int show_patch, const char *search_pattern, int diff_context, int limit,
3340 int log_branches, int reverse_display_order, struct got_reflist_head *refs)
3342 const struct got_error *err;
3343 struct got_commit_graph *graph;
3344 regex_t regex;
3345 int have_match;
3346 struct got_object_id_queue reversed_commits;
3347 struct got_object_qid *qid;
3348 struct got_commit_object *commit;
3349 struct got_pathlist_head changed_paths;
3350 struct got_pathlist_entry *pe;
3352 SIMPLEQ_INIT(&reversed_commits);
3353 TAILQ_INIT(&changed_paths);
3355 if (search_pattern && regcomp(&regex, search_pattern,
3356 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3357 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3359 err = got_commit_graph_open(&graph, path, !log_branches);
3360 if (err)
3361 return err;
3362 err = got_commit_graph_iter_start(graph, root_id, repo,
3363 check_cancelled, NULL);
3364 if (err)
3365 goto done;
3366 for (;;) {
3367 struct got_object_id *id;
3369 if (sigint_received || sigpipe_received)
3370 break;
3372 err = got_commit_graph_iter_next(&id, graph, repo,
3373 check_cancelled, NULL);
3374 if (err) {
3375 if (err->code == GOT_ERR_ITER_COMPLETED)
3376 err = NULL;
3377 break;
3379 if (id == NULL)
3380 break;
3382 err = got_object_open_as_commit(&commit, repo, id);
3383 if (err)
3384 break;
3386 if (show_changed_paths && !reverse_display_order) {
3387 err = get_changed_paths(&changed_paths, commit, repo);
3388 if (err)
3389 break;
3392 if (search_pattern) {
3393 err = match_logmsg(&have_match, id, commit, &regex);
3394 if (err) {
3395 got_object_commit_close(commit);
3396 break;
3398 if (have_match == 0 && show_changed_paths)
3399 match_changed_paths(&have_match,
3400 &changed_paths, &regex);
3401 if (have_match == 0) {
3402 got_object_commit_close(commit);
3403 TAILQ_FOREACH(pe, &changed_paths, entry) {
3404 free((char *)pe->path);
3405 free(pe->data);
3407 got_pathlist_free(&changed_paths);
3408 continue;
3412 if (reverse_display_order) {
3413 err = got_object_qid_alloc(&qid, id);
3414 if (err)
3415 break;
3416 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3417 got_object_commit_close(commit);
3418 } else {
3419 err = print_commit(commit, id, repo, path,
3420 show_changed_paths ? &changed_paths : NULL,
3421 show_patch, diff_context, refs);
3422 got_object_commit_close(commit);
3423 if (err)
3424 break;
3426 if ((limit && --limit == 0) ||
3427 (end_id && got_object_id_cmp(id, end_id) == 0))
3428 break;
3430 TAILQ_FOREACH(pe, &changed_paths, entry) {
3431 free((char *)pe->path);
3432 free(pe->data);
3434 got_pathlist_free(&changed_paths);
3436 if (reverse_display_order) {
3437 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3438 err = got_object_open_as_commit(&commit, repo, qid->id);
3439 if (err)
3440 break;
3441 if (show_changed_paths) {
3442 err = get_changed_paths(&changed_paths,
3443 commit, repo);
3444 if (err)
3445 break;
3447 err = print_commit(commit, qid->id, repo, path,
3448 show_changed_paths ? &changed_paths : NULL,
3449 show_patch, diff_context, refs);
3450 got_object_commit_close(commit);
3451 if (err)
3452 break;
3453 TAILQ_FOREACH(pe, &changed_paths, entry) {
3454 free((char *)pe->path);
3455 free(pe->data);
3457 got_pathlist_free(&changed_paths);
3460 done:
3461 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3462 qid = SIMPLEQ_FIRST(&reversed_commits);
3463 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3464 got_object_qid_free(qid);
3466 TAILQ_FOREACH(pe, &changed_paths, entry) {
3467 free((char *)pe->path);
3468 free(pe->data);
3470 got_pathlist_free(&changed_paths);
3471 if (search_pattern)
3472 regfree(&regex);
3473 got_commit_graph_close(graph);
3474 return err;
3477 __dead static void
3478 usage_log(void)
3480 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3481 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3482 "[-R] [path]\n", getprogname());
3483 exit(1);
3486 static int
3487 get_default_log_limit(void)
3489 const char *got_default_log_limit;
3490 long long n;
3491 const char *errstr;
3493 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3494 if (got_default_log_limit == NULL)
3495 return 0;
3496 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3497 if (errstr != NULL)
3498 return 0;
3499 return n;
3502 static const struct got_error *
3503 resolve_commit_arg(struct got_object_id **id, const char *commit_arg,
3504 struct got_repository *repo)
3506 const struct got_error *err = NULL;
3507 struct got_reference *ref;
3509 *id = NULL;
3511 err = got_ref_open(&ref, repo, commit_arg, 0);
3512 if (err == NULL) {
3513 int obj_type;
3514 err = got_ref_resolve(id, repo, ref);
3515 got_ref_close(ref);
3516 if (err)
3517 return err;
3518 err = got_object_get_type(&obj_type, repo, *id);
3519 if (err)
3520 return err;
3521 if (obj_type == GOT_OBJ_TYPE_TAG) {
3522 struct got_tag_object *tag;
3523 err = got_object_open_as_tag(&tag, repo, *id);
3524 if (err)
3525 return err;
3526 if (got_object_tag_get_object_type(tag) !=
3527 GOT_OBJ_TYPE_COMMIT) {
3528 got_object_tag_close(tag);
3529 return got_error(GOT_ERR_OBJ_TYPE);
3531 free(*id);
3532 *id = got_object_id_dup(
3533 got_object_tag_get_object_id(tag));
3534 if (*id == NULL)
3535 err = got_error_from_errno(
3536 "got_object_id_dup");
3537 got_object_tag_close(tag);
3538 if (err)
3539 return err;
3540 } else if (obj_type != GOT_OBJ_TYPE_COMMIT)
3541 return got_error(GOT_ERR_OBJ_TYPE);
3542 } else {
3543 err = got_repo_match_object_id_prefix(id, commit_arg,
3544 GOT_OBJ_TYPE_COMMIT, repo);
3547 return err;
3550 static const struct got_error *
3551 cmd_log(int argc, char *argv[])
3553 const struct got_error *error;
3554 struct got_repository *repo = NULL;
3555 struct got_worktree *worktree = NULL;
3556 struct got_object_id *start_id = NULL, *end_id = NULL;
3557 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3558 const char *start_commit = NULL, *end_commit = NULL;
3559 const char *search_pattern = NULL;
3560 int diff_context = -1, ch;
3561 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3562 int reverse_display_order = 0;
3563 const char *errstr;
3564 struct got_reflist_head refs;
3566 SIMPLEQ_INIT(&refs);
3568 #ifndef PROFILE
3569 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3570 NULL)
3571 == -1)
3572 err(1, "pledge");
3573 #endif
3575 limit = get_default_log_limit();
3577 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3578 switch (ch) {
3579 case 'p':
3580 show_patch = 1;
3581 break;
3582 case 'P':
3583 show_changed_paths = 1;
3584 break;
3585 case 'c':
3586 start_commit = optarg;
3587 break;
3588 case 'C':
3589 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3590 &errstr);
3591 if (errstr != NULL)
3592 err(1, "-C option %s", errstr);
3593 break;
3594 case 'l':
3595 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3596 if (errstr != NULL)
3597 err(1, "-l option %s", errstr);
3598 break;
3599 case 'b':
3600 log_branches = 1;
3601 break;
3602 case 'r':
3603 repo_path = realpath(optarg, NULL);
3604 if (repo_path == NULL)
3605 return got_error_from_errno2("realpath",
3606 optarg);
3607 got_path_strip_trailing_slashes(repo_path);
3608 break;
3609 case 'R':
3610 reverse_display_order = 1;
3611 break;
3612 case 's':
3613 search_pattern = optarg;
3614 break;
3615 case 'x':
3616 end_commit = optarg;
3617 break;
3618 default:
3619 usage_log();
3620 /* NOTREACHED */
3624 argc -= optind;
3625 argv += optind;
3627 if (diff_context == -1)
3628 diff_context = 3;
3629 else if (!show_patch)
3630 errx(1, "-C requires -p");
3632 cwd = getcwd(NULL, 0);
3633 if (cwd == NULL) {
3634 error = got_error_from_errno("getcwd");
3635 goto done;
3638 if (repo_path == NULL) {
3639 error = got_worktree_open(&worktree, cwd);
3640 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3641 goto done;
3642 error = NULL;
3645 if (argc == 0) {
3646 path = strdup("");
3647 if (path == NULL) {
3648 error = got_error_from_errno("strdup");
3649 goto done;
3651 } else if (argc == 1) {
3652 if (worktree) {
3653 error = got_worktree_resolve_path(&path, worktree,
3654 argv[0]);
3655 if (error)
3656 goto done;
3657 } else {
3658 path = strdup(argv[0]);
3659 if (path == NULL) {
3660 error = got_error_from_errno("strdup");
3661 goto done;
3664 } else
3665 usage_log();
3667 if (repo_path == NULL) {
3668 repo_path = worktree ?
3669 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3671 if (repo_path == NULL) {
3672 error = got_error_from_errno("strdup");
3673 goto done;
3676 error = got_repo_open(&repo, repo_path, NULL);
3677 if (error != NULL)
3678 goto done;
3680 error = apply_unveil(got_repo_get_path(repo), 1,
3681 worktree ? got_worktree_get_root_path(worktree) : NULL);
3682 if (error)
3683 goto done;
3685 if (start_commit == NULL) {
3686 struct got_reference *head_ref;
3687 struct got_commit_object *commit = NULL;
3688 error = got_ref_open(&head_ref, repo,
3689 worktree ? got_worktree_get_head_ref_name(worktree)
3690 : GOT_REF_HEAD, 0);
3691 if (error != NULL)
3692 goto done;
3693 error = got_ref_resolve(&start_id, repo, head_ref);
3694 got_ref_close(head_ref);
3695 if (error != NULL)
3696 goto done;
3697 error = got_object_open_as_commit(&commit, repo,
3698 start_id);
3699 if (error != NULL)
3700 goto done;
3701 got_object_commit_close(commit);
3702 } else {
3703 error = resolve_commit_arg(&start_id, start_commit, repo);
3704 if (error != NULL)
3705 goto done;
3707 if (end_commit != NULL) {
3708 error = resolve_commit_arg(&end_id, end_commit, repo);
3709 if (error != NULL)
3710 goto done;
3713 if (worktree) {
3714 const char *prefix = got_worktree_get_path_prefix(worktree);
3715 char *p;
3716 if (asprintf(&p, "%s%s%s", prefix,
3717 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3718 error = got_error_from_errno("asprintf");
3719 goto done;
3721 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3722 free(p);
3723 } else
3724 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3725 if (error != NULL)
3726 goto done;
3727 if (in_repo_path) {
3728 free(path);
3729 path = in_repo_path;
3732 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3733 if (error)
3734 goto done;
3736 error = print_commits(start_id, end_id, repo, path, show_changed_paths,
3737 show_patch, search_pattern, diff_context, limit, log_branches,
3738 reverse_display_order, &refs);
3739 done:
3740 free(path);
3741 free(repo_path);
3742 free(cwd);
3743 if (worktree)
3744 got_worktree_close(worktree);
3745 if (repo) {
3746 const struct got_error *repo_error;
3747 repo_error = got_repo_close(repo);
3748 if (error == NULL)
3749 error = repo_error;
3751 got_ref_list_free(&refs);
3752 return error;
3755 __dead static void
3756 usage_diff(void)
3758 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3759 "[-w] [object1 object2 | path]\n", getprogname());
3760 exit(1);
3763 struct print_diff_arg {
3764 struct got_repository *repo;
3765 struct got_worktree *worktree;
3766 int diff_context;
3767 const char *id_str;
3768 int header_shown;
3769 int diff_staged;
3770 int ignore_whitespace;
3774 * Create a file which contains the target path of a symlink so we can feed
3775 * it as content to the diff engine.
3777 static const struct got_error *
3778 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
3779 const char *abspath)
3781 const struct got_error *err = NULL;
3782 char target_path[PATH_MAX];
3783 ssize_t target_len, outlen;
3785 *fd = -1;
3787 if (dirfd != -1) {
3788 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
3789 if (target_len == -1)
3790 return got_error_from_errno2("readlinkat", abspath);
3791 } else {
3792 target_len = readlink(abspath, target_path, PATH_MAX);
3793 if (target_len == -1)
3794 return got_error_from_errno2("readlink", abspath);
3797 *fd = got_opentempfd();
3798 if (*fd == -1)
3799 return got_error_from_errno("got_opentempfd");
3801 outlen = write(*fd, target_path, target_len);
3802 if (outlen == -1) {
3803 err = got_error_from_errno("got_opentempfd");
3804 goto done;
3807 if (lseek(*fd, 0, SEEK_SET) == -1) {
3808 err = got_error_from_errno2("lseek", abspath);
3809 goto done;
3811 done:
3812 if (err) {
3813 close(*fd);
3814 *fd = -1;
3816 return err;
3819 static const struct got_error *
3820 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3821 const char *path, struct got_object_id *blob_id,
3822 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3823 int dirfd, const char *de_name)
3825 struct print_diff_arg *a = arg;
3826 const struct got_error *err = NULL;
3827 struct got_blob_object *blob1 = NULL;
3828 int fd = -1;
3829 FILE *f2 = NULL;
3830 char *abspath = NULL, *label1 = NULL;
3831 struct stat sb;
3833 if (a->diff_staged) {
3834 if (staged_status != GOT_STATUS_MODIFY &&
3835 staged_status != GOT_STATUS_ADD &&
3836 staged_status != GOT_STATUS_DELETE)
3837 return NULL;
3838 } else {
3839 if (staged_status == GOT_STATUS_DELETE)
3840 return NULL;
3841 if (status == GOT_STATUS_NONEXISTENT)
3842 return got_error_set_errno(ENOENT, path);
3843 if (status != GOT_STATUS_MODIFY &&
3844 status != GOT_STATUS_ADD &&
3845 status != GOT_STATUS_DELETE &&
3846 status != GOT_STATUS_CONFLICT)
3847 return NULL;
3850 if (!a->header_shown) {
3851 printf("diff %s %s%s\n", a->id_str,
3852 got_worktree_get_root_path(a->worktree),
3853 a->diff_staged ? " (staged changes)" : "");
3854 a->header_shown = 1;
3857 if (a->diff_staged) {
3858 const char *label1 = NULL, *label2 = NULL;
3859 switch (staged_status) {
3860 case GOT_STATUS_MODIFY:
3861 label1 = path;
3862 label2 = path;
3863 break;
3864 case GOT_STATUS_ADD:
3865 label2 = path;
3866 break;
3867 case GOT_STATUS_DELETE:
3868 label1 = path;
3869 break;
3870 default:
3871 return got_error(GOT_ERR_FILE_STATUS);
3873 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
3874 label1, label2, a->diff_context, a->ignore_whitespace,
3875 a->repo, stdout);
3878 if (staged_status == GOT_STATUS_ADD ||
3879 staged_status == GOT_STATUS_MODIFY) {
3880 char *id_str;
3881 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
3882 8192);
3883 if (err)
3884 goto done;
3885 err = got_object_id_str(&id_str, staged_blob_id);
3886 if (err)
3887 goto done;
3888 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
3889 err = got_error_from_errno("asprintf");
3890 free(id_str);
3891 goto done;
3893 free(id_str);
3894 } else if (status != GOT_STATUS_ADD) {
3895 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
3896 if (err)
3897 goto done;
3900 if (status != GOT_STATUS_DELETE) {
3901 if (asprintf(&abspath, "%s/%s",
3902 got_worktree_get_root_path(a->worktree), path) == -1) {
3903 err = got_error_from_errno("asprintf");
3904 goto done;
3907 if (dirfd != -1) {
3908 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
3909 if (fd == -1) {
3910 if (errno != ELOOP) {
3911 err = got_error_from_errno2("openat",
3912 abspath);
3913 goto done;
3915 err = get_symlink_target_file(&fd, dirfd,
3916 de_name, abspath);
3917 if (err)
3918 goto done;
3920 } else {
3921 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
3922 if (fd == -1) {
3923 if (errno != ELOOP) {
3924 err = got_error_from_errno2("open",
3925 abspath);
3926 goto done;
3928 err = get_symlink_target_file(&fd, dirfd,
3929 de_name, abspath);
3930 if (err)
3931 goto done;
3934 if (fstat(fd, &sb) == -1) {
3935 err = got_error_from_errno2("fstat", abspath);
3936 goto done;
3938 f2 = fdopen(fd, "r");
3939 if (f2 == NULL) {
3940 err = got_error_from_errno2("fdopen", abspath);
3941 goto done;
3943 fd = -1;
3944 } else
3945 sb.st_size = 0;
3947 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
3948 a->diff_context, a->ignore_whitespace, stdout);
3949 done:
3950 if (blob1)
3951 got_object_blob_close(blob1);
3952 if (f2 && fclose(f2) == EOF && err == NULL)
3953 err = got_error_from_errno("fclose");
3954 if (fd != -1 && close(fd) == -1 && err == NULL)
3955 err = got_error_from_errno("close");
3956 free(abspath);
3957 return err;
3960 static const struct got_error *
3961 cmd_diff(int argc, char *argv[])
3963 const struct got_error *error;
3964 struct got_repository *repo = NULL;
3965 struct got_worktree *worktree = NULL;
3966 char *cwd = NULL, *repo_path = NULL;
3967 struct got_object_id *id1 = NULL, *id2 = NULL;
3968 const char *id_str1 = NULL, *id_str2 = NULL;
3969 char *label1 = NULL, *label2 = NULL;
3970 int type1, type2;
3971 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
3972 const char *errstr;
3973 char *path = NULL;
3975 #ifndef PROFILE
3976 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3977 NULL) == -1)
3978 err(1, "pledge");
3979 #endif
3981 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
3982 switch (ch) {
3983 case 'C':
3984 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3985 &errstr);
3986 if (errstr != NULL)
3987 err(1, "-C option %s", errstr);
3988 break;
3989 case 'r':
3990 repo_path = realpath(optarg, NULL);
3991 if (repo_path == NULL)
3992 return got_error_from_errno2("realpath",
3993 optarg);
3994 got_path_strip_trailing_slashes(repo_path);
3995 break;
3996 case 's':
3997 diff_staged = 1;
3998 break;
3999 case 'w':
4000 ignore_whitespace = 1;
4001 break;
4002 default:
4003 usage_diff();
4004 /* NOTREACHED */
4008 argc -= optind;
4009 argv += optind;
4011 cwd = getcwd(NULL, 0);
4012 if (cwd == NULL) {
4013 error = got_error_from_errno("getcwd");
4014 goto done;
4016 if (argc <= 1) {
4017 if (repo_path)
4018 errx(1,
4019 "-r option can't be used when diffing a work tree");
4020 error = got_worktree_open(&worktree, cwd);
4021 if (error) {
4022 if (error->code == GOT_ERR_NOT_WORKTREE)
4023 error = wrap_not_worktree_error(error, "diff",
4024 cwd);
4025 goto done;
4027 repo_path = strdup(got_worktree_get_repo_path(worktree));
4028 if (repo_path == NULL) {
4029 error = got_error_from_errno("strdup");
4030 goto done;
4032 if (argc == 1) {
4033 error = got_worktree_resolve_path(&path, worktree,
4034 argv[0]);
4035 if (error)
4036 goto done;
4037 } else {
4038 path = strdup("");
4039 if (path == NULL) {
4040 error = got_error_from_errno("strdup");
4041 goto done;
4044 } else if (argc == 2) {
4045 if (diff_staged)
4046 errx(1, "-s option can't be used when diffing "
4047 "objects in repository");
4048 id_str1 = argv[0];
4049 id_str2 = argv[1];
4050 if (repo_path == NULL) {
4051 error = got_worktree_open(&worktree, cwd);
4052 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4053 goto done;
4054 if (worktree) {
4055 repo_path = strdup(
4056 got_worktree_get_repo_path(worktree));
4057 if (repo_path == NULL) {
4058 error = got_error_from_errno("strdup");
4059 goto done;
4061 } else {
4062 repo_path = strdup(cwd);
4063 if (repo_path == NULL) {
4064 error = got_error_from_errno("strdup");
4065 goto done;
4069 } else
4070 usage_diff();
4072 error = got_repo_open(&repo, repo_path, NULL);
4073 free(repo_path);
4074 if (error != NULL)
4075 goto done;
4077 error = apply_unveil(got_repo_get_path(repo), 1,
4078 worktree ? got_worktree_get_root_path(worktree) : NULL);
4079 if (error)
4080 goto done;
4082 if (argc <= 1) {
4083 struct print_diff_arg arg;
4084 struct got_pathlist_head paths;
4085 char *id_str;
4087 TAILQ_INIT(&paths);
4089 error = got_object_id_str(&id_str,
4090 got_worktree_get_base_commit_id(worktree));
4091 if (error)
4092 goto done;
4093 arg.repo = repo;
4094 arg.worktree = worktree;
4095 arg.diff_context = diff_context;
4096 arg.id_str = id_str;
4097 arg.header_shown = 0;
4098 arg.diff_staged = diff_staged;
4099 arg.ignore_whitespace = ignore_whitespace;
4101 error = got_pathlist_append(&paths, path, NULL);
4102 if (error)
4103 goto done;
4105 error = got_worktree_status(worktree, &paths, repo, print_diff,
4106 &arg, check_cancelled, NULL);
4107 free(id_str);
4108 got_pathlist_free(&paths);
4109 goto done;
4112 error = got_repo_match_object_id(&id1, &label1, id_str1,
4113 GOT_OBJ_TYPE_ANY, 1, repo);
4114 if (error)
4115 goto done;
4117 error = got_repo_match_object_id(&id2, &label2, id_str2,
4118 GOT_OBJ_TYPE_ANY, 1, repo);
4119 if (error)
4120 goto done;
4122 error = got_object_get_type(&type1, repo, id1);
4123 if (error)
4124 goto done;
4126 error = got_object_get_type(&type2, repo, id2);
4127 if (error)
4128 goto done;
4130 if (type1 != type2) {
4131 error = got_error(GOT_ERR_OBJ_TYPE);
4132 goto done;
4135 switch (type1) {
4136 case GOT_OBJ_TYPE_BLOB:
4137 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
4138 diff_context, ignore_whitespace, repo, stdout);
4139 break;
4140 case GOT_OBJ_TYPE_TREE:
4141 error = got_diff_objects_as_trees(id1, id2, "", "",
4142 diff_context, ignore_whitespace, repo, stdout);
4143 break;
4144 case GOT_OBJ_TYPE_COMMIT:
4145 printf("diff %s %s\n", label1, label2);
4146 error = got_diff_objects_as_commits(id1, id2, diff_context,
4147 ignore_whitespace, repo, stdout);
4148 break;
4149 default:
4150 error = got_error(GOT_ERR_OBJ_TYPE);
4152 done:
4153 free(label1);
4154 free(label2);
4155 free(id1);
4156 free(id2);
4157 free(path);
4158 if (worktree)
4159 got_worktree_close(worktree);
4160 if (repo) {
4161 const struct got_error *repo_error;
4162 repo_error = got_repo_close(repo);
4163 if (error == NULL)
4164 error = repo_error;
4166 return error;
4169 __dead static void
4170 usage_blame(void)
4172 fprintf(stderr,
4173 "usage: %s blame [-c commit] [-r repository-path] path\n",
4174 getprogname());
4175 exit(1);
4178 struct blame_line {
4179 int annotated;
4180 char *id_str;
4181 char *committer;
4182 char datebuf[11]; /* YYYY-MM-DD + NUL */
4185 struct blame_cb_args {
4186 struct blame_line *lines;
4187 int nlines;
4188 int nlines_prec;
4189 int lineno_cur;
4190 off_t *line_offsets;
4191 FILE *f;
4192 struct got_repository *repo;
4195 static const struct got_error *
4196 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4198 const struct got_error *err = NULL;
4199 struct blame_cb_args *a = arg;
4200 struct blame_line *bline;
4201 char *line = NULL;
4202 size_t linesize = 0;
4203 struct got_commit_object *commit = NULL;
4204 off_t offset;
4205 struct tm tm;
4206 time_t committer_time;
4208 if (nlines != a->nlines ||
4209 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4210 return got_error(GOT_ERR_RANGE);
4212 if (sigint_received)
4213 return got_error(GOT_ERR_ITER_COMPLETED);
4215 if (lineno == -1)
4216 return NULL; /* no change in this commit */
4218 /* Annotate this line. */
4219 bline = &a->lines[lineno - 1];
4220 if (bline->annotated)
4221 return NULL;
4222 err = got_object_id_str(&bline->id_str, id);
4223 if (err)
4224 return err;
4226 err = got_object_open_as_commit(&commit, a->repo, id);
4227 if (err)
4228 goto done;
4230 bline->committer = strdup(got_object_commit_get_committer(commit));
4231 if (bline->committer == NULL) {
4232 err = got_error_from_errno("strdup");
4233 goto done;
4236 committer_time = got_object_commit_get_committer_time(commit);
4237 if (localtime_r(&committer_time, &tm) == NULL)
4238 return got_error_from_errno("localtime_r");
4239 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4240 &tm) >= sizeof(bline->datebuf)) {
4241 err = got_error(GOT_ERR_NO_SPACE);
4242 goto done;
4244 bline->annotated = 1;
4246 /* Print lines annotated so far. */
4247 bline = &a->lines[a->lineno_cur - 1];
4248 if (!bline->annotated)
4249 goto done;
4251 offset = a->line_offsets[a->lineno_cur - 1];
4252 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4253 err = got_error_from_errno("fseeko");
4254 goto done;
4257 while (bline->annotated) {
4258 char *smallerthan, *at, *nl, *committer;
4259 size_t len;
4261 if (getline(&line, &linesize, a->f) == -1) {
4262 if (ferror(a->f))
4263 err = got_error_from_errno("getline");
4264 break;
4267 committer = bline->committer;
4268 smallerthan = strchr(committer, '<');
4269 if (smallerthan && smallerthan[1] != '\0')
4270 committer = smallerthan + 1;
4271 at = strchr(committer, '@');
4272 if (at)
4273 *at = '\0';
4274 len = strlen(committer);
4275 if (len >= 9)
4276 committer[8] = '\0';
4278 nl = strchr(line, '\n');
4279 if (nl)
4280 *nl = '\0';
4281 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4282 bline->id_str, bline->datebuf, committer, line);
4284 a->lineno_cur++;
4285 bline = &a->lines[a->lineno_cur - 1];
4287 done:
4288 if (commit)
4289 got_object_commit_close(commit);
4290 free(line);
4291 return err;
4294 static const struct got_error *
4295 cmd_blame(int argc, char *argv[])
4297 const struct got_error *error;
4298 struct got_repository *repo = NULL;
4299 struct got_worktree *worktree = NULL;
4300 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4301 char *link_target = NULL;
4302 struct got_object_id *obj_id = NULL;
4303 struct got_object_id *commit_id = NULL;
4304 struct got_blob_object *blob = NULL;
4305 char *commit_id_str = NULL;
4306 struct blame_cb_args bca;
4307 int ch, obj_type, i;
4308 size_t filesize;
4310 memset(&bca, 0, sizeof(bca));
4312 #ifndef PROFILE
4313 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4314 NULL) == -1)
4315 err(1, "pledge");
4316 #endif
4318 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4319 switch (ch) {
4320 case 'c':
4321 commit_id_str = optarg;
4322 break;
4323 case 'r':
4324 repo_path = realpath(optarg, NULL);
4325 if (repo_path == NULL)
4326 return got_error_from_errno2("realpath",
4327 optarg);
4328 got_path_strip_trailing_slashes(repo_path);
4329 break;
4330 default:
4331 usage_blame();
4332 /* NOTREACHED */
4336 argc -= optind;
4337 argv += optind;
4339 if (argc == 1)
4340 path = argv[0];
4341 else
4342 usage_blame();
4344 cwd = getcwd(NULL, 0);
4345 if (cwd == NULL) {
4346 error = got_error_from_errno("getcwd");
4347 goto done;
4349 if (repo_path == NULL) {
4350 error = got_worktree_open(&worktree, cwd);
4351 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4352 goto done;
4353 else
4354 error = NULL;
4355 if (worktree) {
4356 repo_path =
4357 strdup(got_worktree_get_repo_path(worktree));
4358 if (repo_path == NULL) {
4359 error = got_error_from_errno("strdup");
4360 if (error)
4361 goto done;
4363 } else {
4364 repo_path = strdup(cwd);
4365 if (repo_path == NULL) {
4366 error = got_error_from_errno("strdup");
4367 goto done;
4372 error = got_repo_open(&repo, repo_path, NULL);
4373 if (error != NULL)
4374 goto done;
4376 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4377 if (error)
4378 goto done;
4380 if (worktree) {
4381 const char *prefix = got_worktree_get_path_prefix(worktree);
4382 char *p, *worktree_subdir = cwd +
4383 strlen(got_worktree_get_root_path(worktree));
4384 if (asprintf(&p, "%s%s%s%s%s",
4385 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
4386 worktree_subdir, worktree_subdir[0] ? "/" : "",
4387 path) == -1) {
4388 error = got_error_from_errno("asprintf");
4389 goto done;
4391 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4392 free(p);
4393 } else {
4394 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4396 if (error)
4397 goto done;
4399 if (commit_id_str == NULL) {
4400 struct got_reference *head_ref;
4401 error = got_ref_open(&head_ref, repo, worktree ?
4402 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4403 if (error != NULL)
4404 goto done;
4405 error = got_ref_resolve(&commit_id, repo, head_ref);
4406 got_ref_close(head_ref);
4407 if (error != NULL)
4408 goto done;
4409 } else {
4410 error = got_repo_match_object_id(&commit_id, NULL,
4411 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4412 if (error)
4413 goto done;
4416 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4417 commit_id, repo);
4418 if (error)
4419 goto done;
4421 error = got_object_id_by_path(&obj_id, repo, commit_id,
4422 link_target ? link_target : in_repo_path);
4423 if (error)
4424 goto done;
4426 error = got_object_get_type(&obj_type, repo, obj_id);
4427 if (error)
4428 goto done;
4430 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4431 error = got_error_path(link_target ? link_target : in_repo_path,
4432 GOT_ERR_OBJ_TYPE);
4433 goto done;
4436 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4437 if (error)
4438 goto done;
4439 bca.f = got_opentemp();
4440 if (bca.f == NULL) {
4441 error = got_error_from_errno("got_opentemp");
4442 goto done;
4444 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4445 &bca.line_offsets, bca.f, blob);
4446 if (error || bca.nlines == 0)
4447 goto done;
4449 /* Don't include \n at EOF in the blame line count. */
4450 if (bca.line_offsets[bca.nlines - 1] == filesize)
4451 bca.nlines--;
4453 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4454 if (bca.lines == NULL) {
4455 error = got_error_from_errno("calloc");
4456 goto done;
4458 bca.lineno_cur = 1;
4459 bca.nlines_prec = 0;
4460 i = bca.nlines;
4461 while (i > 0) {
4462 i /= 10;
4463 bca.nlines_prec++;
4465 bca.repo = repo;
4467 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4468 repo, blame_cb, &bca, check_cancelled, NULL);
4469 done:
4470 free(in_repo_path);
4471 free(link_target);
4472 free(repo_path);
4473 free(cwd);
4474 free(commit_id);
4475 free(obj_id);
4476 if (blob)
4477 got_object_blob_close(blob);
4478 if (worktree)
4479 got_worktree_close(worktree);
4480 if (repo) {
4481 const struct got_error *repo_error;
4482 repo_error = got_repo_close(repo);
4483 if (error == NULL)
4484 error = repo_error;
4486 if (bca.lines) {
4487 for (i = 0; i < bca.nlines; i++) {
4488 struct blame_line *bline = &bca.lines[i];
4489 free(bline->id_str);
4490 free(bline->committer);
4492 free(bca.lines);
4494 free(bca.line_offsets);
4495 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4496 error = got_error_from_errno("fclose");
4497 return error;
4500 __dead static void
4501 usage_tree(void)
4503 fprintf(stderr,
4504 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4505 getprogname());
4506 exit(1);
4509 static const struct got_error *
4510 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4511 const char *root_path, struct got_repository *repo)
4513 const struct got_error *err = NULL;
4514 int is_root_path = (strcmp(path, root_path) == 0);
4515 const char *modestr = "";
4516 mode_t mode = got_tree_entry_get_mode(te);
4517 char *link_target = NULL;
4519 path += strlen(root_path);
4520 while (path[0] == '/')
4521 path++;
4523 if (got_object_tree_entry_is_submodule(te))
4524 modestr = "$";
4525 else if (S_ISLNK(mode)) {
4526 int i;
4528 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4529 if (err)
4530 return err;
4531 for (i = 0; i < strlen(link_target); i++) {
4532 if (!isprint((unsigned char)link_target[i]))
4533 link_target[i] = '?';
4536 modestr = "@";
4538 else if (S_ISDIR(mode))
4539 modestr = "/";
4540 else if (mode & S_IXUSR)
4541 modestr = "*";
4543 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4544 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4545 link_target ? " -> ": "", link_target ? link_target : "");
4547 free(link_target);
4548 return NULL;
4551 static const struct got_error *
4552 print_tree(const char *path, struct got_object_id *commit_id,
4553 int show_ids, int recurse, const char *root_path,
4554 struct got_repository *repo)
4556 const struct got_error *err = NULL;
4557 struct got_object_id *tree_id = NULL;
4558 struct got_tree_object *tree = NULL;
4559 int nentries, i;
4561 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4562 if (err)
4563 goto done;
4565 err = got_object_open_as_tree(&tree, repo, tree_id);
4566 if (err)
4567 goto done;
4568 nentries = got_object_tree_get_nentries(tree);
4569 for (i = 0; i < nentries; i++) {
4570 struct got_tree_entry *te;
4571 char *id = NULL;
4573 if (sigint_received || sigpipe_received)
4574 break;
4576 te = got_object_tree_get_entry(tree, i);
4577 if (show_ids) {
4578 char *id_str;
4579 err = got_object_id_str(&id_str,
4580 got_tree_entry_get_id(te));
4581 if (err)
4582 goto done;
4583 if (asprintf(&id, "%s ", id_str) == -1) {
4584 err = got_error_from_errno("asprintf");
4585 free(id_str);
4586 goto done;
4588 free(id_str);
4590 err = print_entry(te, id, path, root_path, repo);
4591 free(id);
4592 if (err)
4593 goto done;
4595 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4596 char *child_path;
4597 if (asprintf(&child_path, "%s%s%s", path,
4598 path[0] == '/' && path[1] == '\0' ? "" : "/",
4599 got_tree_entry_get_name(te)) == -1) {
4600 err = got_error_from_errno("asprintf");
4601 goto done;
4603 err = print_tree(child_path, commit_id, show_ids, 1,
4604 root_path, repo);
4605 free(child_path);
4606 if (err)
4607 goto done;
4610 done:
4611 if (tree)
4612 got_object_tree_close(tree);
4613 free(tree_id);
4614 return err;
4617 static const struct got_error *
4618 cmd_tree(int argc, char *argv[])
4620 const struct got_error *error;
4621 struct got_repository *repo = NULL;
4622 struct got_worktree *worktree = NULL;
4623 const char *path, *refname = NULL;
4624 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4625 struct got_object_id *commit_id = NULL;
4626 char *commit_id_str = NULL;
4627 int show_ids = 0, recurse = 0;
4628 int ch;
4630 #ifndef PROFILE
4631 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4632 NULL) == -1)
4633 err(1, "pledge");
4634 #endif
4636 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4637 switch (ch) {
4638 case 'c':
4639 commit_id_str = optarg;
4640 break;
4641 case 'r':
4642 repo_path = realpath(optarg, NULL);
4643 if (repo_path == NULL)
4644 return got_error_from_errno2("realpath",
4645 optarg);
4646 got_path_strip_trailing_slashes(repo_path);
4647 break;
4648 case 'i':
4649 show_ids = 1;
4650 break;
4651 case 'R':
4652 recurse = 1;
4653 break;
4654 default:
4655 usage_tree();
4656 /* NOTREACHED */
4660 argc -= optind;
4661 argv += optind;
4663 if (argc == 1)
4664 path = argv[0];
4665 else if (argc > 1)
4666 usage_tree();
4667 else
4668 path = NULL;
4670 cwd = getcwd(NULL, 0);
4671 if (cwd == NULL) {
4672 error = got_error_from_errno("getcwd");
4673 goto done;
4675 if (repo_path == NULL) {
4676 error = got_worktree_open(&worktree, cwd);
4677 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4678 goto done;
4679 else
4680 error = NULL;
4681 if (worktree) {
4682 repo_path =
4683 strdup(got_worktree_get_repo_path(worktree));
4684 if (repo_path == NULL)
4685 error = got_error_from_errno("strdup");
4686 if (error)
4687 goto done;
4688 } else {
4689 repo_path = strdup(cwd);
4690 if (repo_path == NULL) {
4691 error = got_error_from_errno("strdup");
4692 goto done;
4697 error = got_repo_open(&repo, repo_path, NULL);
4698 if (error != NULL)
4699 goto done;
4701 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4702 if (error)
4703 goto done;
4705 if (path == NULL) {
4706 if (worktree) {
4707 char *p, *worktree_subdir = cwd +
4708 strlen(got_worktree_get_root_path(worktree));
4709 if (asprintf(&p, "%s/%s",
4710 got_worktree_get_path_prefix(worktree),
4711 worktree_subdir) == -1) {
4712 error = got_error_from_errno("asprintf");
4713 goto done;
4715 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4716 free(p);
4717 if (error)
4718 goto done;
4719 } else
4720 path = "/";
4722 if (in_repo_path == NULL) {
4723 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4724 if (error != NULL)
4725 goto done;
4728 if (commit_id_str == NULL) {
4729 struct got_reference *head_ref;
4730 if (worktree)
4731 refname = got_worktree_get_head_ref_name(worktree);
4732 else
4733 refname = GOT_REF_HEAD;
4734 error = got_ref_open(&head_ref, repo, refname, 0);
4735 if (error != NULL)
4736 goto done;
4737 error = got_ref_resolve(&commit_id, repo, head_ref);
4738 got_ref_close(head_ref);
4739 if (error != NULL)
4740 goto done;
4741 } else {
4742 error = got_repo_match_object_id(&commit_id, NULL,
4743 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4744 if (error)
4745 goto done;
4748 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4749 in_repo_path, repo);
4750 done:
4751 free(in_repo_path);
4752 free(repo_path);
4753 free(cwd);
4754 free(commit_id);
4755 if (worktree)
4756 got_worktree_close(worktree);
4757 if (repo) {
4758 const struct got_error *repo_error;
4759 repo_error = got_repo_close(repo);
4760 if (error == NULL)
4761 error = repo_error;
4763 return error;
4766 __dead static void
4767 usage_status(void)
4769 fprintf(stderr, "usage: %s status [-s status-codes ] [path ...]\n",
4770 getprogname());
4771 exit(1);
4774 static const struct got_error *
4775 print_status(void *arg, unsigned char status, unsigned char staged_status,
4776 const char *path, struct got_object_id *blob_id,
4777 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4778 int dirfd, const char *de_name)
4780 if (status == staged_status && (status == GOT_STATUS_DELETE))
4781 status = GOT_STATUS_NO_CHANGE;
4782 if (arg) {
4783 char *status_codes = arg;
4784 size_t ncodes = strlen(status_codes);
4785 int i;
4786 for (i = 0; i < ncodes ; i++) {
4787 if (status == status_codes[i] ||
4788 staged_status == status_codes[i])
4789 break;
4791 if (i == ncodes)
4792 return NULL;
4794 printf("%c%c %s\n", status, staged_status, path);
4795 return NULL;
4798 static const struct got_error *
4799 cmd_status(int argc, char *argv[])
4801 const struct got_error *error = NULL;
4802 struct got_repository *repo = NULL;
4803 struct got_worktree *worktree = NULL;
4804 char *cwd = NULL, *status_codes = NULL;;
4805 struct got_pathlist_head paths;
4806 struct got_pathlist_entry *pe;
4807 int ch, i;
4809 TAILQ_INIT(&paths);
4811 while ((ch = getopt(argc, argv, "s:")) != -1) {
4812 switch (ch) {
4813 case 's':
4814 for (i = 0; i < strlen(optarg); i++) {
4815 switch (optarg[i]) {
4816 case GOT_STATUS_MODIFY:
4817 case GOT_STATUS_ADD:
4818 case GOT_STATUS_DELETE:
4819 case GOT_STATUS_CONFLICT:
4820 case GOT_STATUS_MISSING:
4821 case GOT_STATUS_OBSTRUCTED:
4822 case GOT_STATUS_UNVERSIONED:
4823 case GOT_STATUS_MODE_CHANGE:
4824 case GOT_STATUS_NONEXISTENT:
4825 break;
4826 default:
4827 errx(1, "invalid status code '%c'",
4828 optarg[i]);
4831 status_codes = optarg;
4832 break;
4833 default:
4834 usage_status();
4835 /* NOTREACHED */
4839 argc -= optind;
4840 argv += optind;
4842 #ifndef PROFILE
4843 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4844 NULL) == -1)
4845 err(1, "pledge");
4846 #endif
4847 cwd = getcwd(NULL, 0);
4848 if (cwd == NULL) {
4849 error = got_error_from_errno("getcwd");
4850 goto done;
4853 error = got_worktree_open(&worktree, cwd);
4854 if (error) {
4855 if (error->code == GOT_ERR_NOT_WORKTREE)
4856 error = wrap_not_worktree_error(error, "status", cwd);
4857 goto done;
4860 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4861 NULL);
4862 if (error != NULL)
4863 goto done;
4865 error = apply_unveil(got_repo_get_path(repo), 1,
4866 got_worktree_get_root_path(worktree));
4867 if (error)
4868 goto done;
4870 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
4871 if (error)
4872 goto done;
4874 error = got_worktree_status(worktree, &paths, repo, print_status,
4875 status_codes, check_cancelled, NULL);
4876 done:
4877 TAILQ_FOREACH(pe, &paths, entry)
4878 free((char *)pe->path);
4879 got_pathlist_free(&paths);
4880 free(cwd);
4881 return error;
4884 __dead static void
4885 usage_ref(void)
4887 fprintf(stderr,
4888 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
4889 "[-d] [name]\n",
4890 getprogname());
4891 exit(1);
4894 static const struct got_error *
4895 list_refs(struct got_repository *repo, const char *refname)
4897 static const struct got_error *err = NULL;
4898 struct got_reflist_head refs;
4899 struct got_reflist_entry *re;
4901 SIMPLEQ_INIT(&refs);
4902 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
4903 if (err)
4904 return err;
4906 SIMPLEQ_FOREACH(re, &refs, entry) {
4907 char *refstr;
4908 refstr = got_ref_to_str(re->ref);
4909 if (refstr == NULL)
4910 return got_error_from_errno("got_ref_to_str");
4911 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
4912 free(refstr);
4915 got_ref_list_free(&refs);
4916 return NULL;
4919 static const struct got_error *
4920 delete_ref(struct got_repository *repo, const char *refname)
4922 const struct got_error *err = NULL;
4923 struct got_reference *ref;
4925 err = got_ref_open(&ref, repo, refname, 0);
4926 if (err)
4927 return err;
4929 err = got_ref_delete(ref, repo);
4930 got_ref_close(ref);
4931 return err;
4934 static const struct got_error *
4935 add_ref(struct got_repository *repo, const char *refname, const char *target)
4937 const struct got_error *err = NULL;
4938 struct got_object_id *id;
4939 struct got_reference *ref = NULL;
4942 * Don't let the user create a reference name with a leading '-'.
4943 * While technically a valid reference name, this case is usually
4944 * an unintended typo.
4946 if (refname[0] == '-')
4947 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4949 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
4950 repo);
4951 if (err) {
4952 struct got_reference *target_ref;
4954 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
4955 return err;
4956 err = got_ref_open(&target_ref, repo, target, 0);
4957 if (err)
4958 return err;
4959 err = got_ref_resolve(&id, repo, target_ref);
4960 got_ref_close(target_ref);
4961 if (err)
4962 return err;
4965 err = got_ref_alloc(&ref, refname, id);
4966 if (err)
4967 goto done;
4969 err = got_ref_write(ref, repo);
4970 done:
4971 if (ref)
4972 got_ref_close(ref);
4973 free(id);
4974 return err;
4977 static const struct got_error *
4978 add_symref(struct got_repository *repo, const char *refname, const char *target)
4980 const struct got_error *err = NULL;
4981 struct got_reference *ref = NULL;
4982 struct got_reference *target_ref = NULL;
4985 * Don't let the user create a reference name with a leading '-'.
4986 * While technically a valid reference name, this case is usually
4987 * an unintended typo.
4989 if (refname[0] == '-')
4990 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4992 err = got_ref_open(&target_ref, repo, target, 0);
4993 if (err)
4994 return err;
4996 err = got_ref_alloc_symref(&ref, refname, target_ref);
4997 if (err)
4998 goto done;
5000 err = got_ref_write(ref, repo);
5001 done:
5002 if (target_ref)
5003 got_ref_close(target_ref);
5004 if (ref)
5005 got_ref_close(ref);
5006 return err;
5009 static const struct got_error *
5010 cmd_ref(int argc, char *argv[])
5012 const struct got_error *error = NULL;
5013 struct got_repository *repo = NULL;
5014 struct got_worktree *worktree = NULL;
5015 char *cwd = NULL, *repo_path = NULL;
5016 int ch, do_list = 0, do_delete = 0;
5017 const char *obj_arg = NULL, *symref_target= NULL;
5018 char *refname = NULL;
5020 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5021 switch (ch) {
5022 case 'c':
5023 obj_arg = optarg;
5024 break;
5025 case 'd':
5026 do_delete = 1;
5027 break;
5028 case 'r':
5029 repo_path = realpath(optarg, NULL);
5030 if (repo_path == NULL)
5031 return got_error_from_errno2("realpath",
5032 optarg);
5033 got_path_strip_trailing_slashes(repo_path);
5034 break;
5035 case 'l':
5036 do_list = 1;
5037 break;
5038 case 's':
5039 symref_target = optarg;
5040 break;
5041 default:
5042 usage_ref();
5043 /* NOTREACHED */
5047 if (obj_arg && do_list)
5048 errx(1, "-c and -l options are mutually exclusive");
5049 if (obj_arg && do_delete)
5050 errx(1, "-c and -d options are mutually exclusive");
5051 if (obj_arg && symref_target)
5052 errx(1, "-c and -s options are mutually exclusive");
5053 if (symref_target && do_delete)
5054 errx(1, "-s and -d options are mutually exclusive");
5055 if (symref_target && do_list)
5056 errx(1, "-s and -l options are mutually exclusive");
5057 if (do_delete && do_list)
5058 errx(1, "-d and -l options are mutually exclusive");
5060 argc -= optind;
5061 argv += optind;
5063 if (do_list) {
5064 if (argc != 0 && argc != 1)
5065 usage_ref();
5066 if (argc == 1) {
5067 refname = strdup(argv[0]);
5068 if (refname == NULL) {
5069 error = got_error_from_errno("strdup");
5070 goto done;
5073 } else {
5074 if (argc != 1)
5075 usage_ref();
5076 refname = strdup(argv[0]);
5077 if (refname == NULL) {
5078 error = got_error_from_errno("strdup");
5079 goto done;
5083 if (refname)
5084 got_path_strip_trailing_slashes(refname);
5086 #ifndef PROFILE
5087 if (do_list) {
5088 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5089 NULL) == -1)
5090 err(1, "pledge");
5091 } else {
5092 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5093 "sendfd unveil", NULL) == -1)
5094 err(1, "pledge");
5096 #endif
5097 cwd = getcwd(NULL, 0);
5098 if (cwd == NULL) {
5099 error = got_error_from_errno("getcwd");
5100 goto done;
5103 if (repo_path == NULL) {
5104 error = got_worktree_open(&worktree, cwd);
5105 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5106 goto done;
5107 else
5108 error = NULL;
5109 if (worktree) {
5110 repo_path =
5111 strdup(got_worktree_get_repo_path(worktree));
5112 if (repo_path == NULL)
5113 error = got_error_from_errno("strdup");
5114 if (error)
5115 goto done;
5116 } else {
5117 repo_path = strdup(cwd);
5118 if (repo_path == NULL) {
5119 error = got_error_from_errno("strdup");
5120 goto done;
5125 error = got_repo_open(&repo, repo_path, NULL);
5126 if (error != NULL)
5127 goto done;
5129 error = apply_unveil(got_repo_get_path(repo), do_list,
5130 worktree ? got_worktree_get_root_path(worktree) : NULL);
5131 if (error)
5132 goto done;
5134 if (do_list)
5135 error = list_refs(repo, refname);
5136 else if (do_delete)
5137 error = delete_ref(repo, refname);
5138 else if (symref_target)
5139 error = add_symref(repo, refname, symref_target);
5140 else {
5141 if (obj_arg == NULL)
5142 usage_ref();
5143 error = add_ref(repo, refname, obj_arg);
5145 done:
5146 free(refname);
5147 if (repo)
5148 got_repo_close(repo);
5149 if (worktree)
5150 got_worktree_close(worktree);
5151 free(cwd);
5152 free(repo_path);
5153 return error;
5156 __dead static void
5157 usage_branch(void)
5159 fprintf(stderr,
5160 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5161 "[name]\n", getprogname());
5162 exit(1);
5165 static const struct got_error *
5166 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5167 struct got_reference *ref)
5169 const struct got_error *err = NULL;
5170 const char *refname, *marker = " ";
5171 char *refstr;
5173 refname = got_ref_get_name(ref);
5174 if (worktree && strcmp(refname,
5175 got_worktree_get_head_ref_name(worktree)) == 0) {
5176 struct got_object_id *id = NULL;
5178 err = got_ref_resolve(&id, repo, ref);
5179 if (err)
5180 return err;
5181 if (got_object_id_cmp(id,
5182 got_worktree_get_base_commit_id(worktree)) == 0)
5183 marker = "* ";
5184 else
5185 marker = "~ ";
5186 free(id);
5189 if (strncmp(refname, "refs/heads/", 11) == 0)
5190 refname += 11;
5191 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5192 refname += 18;
5194 refstr = got_ref_to_str(ref);
5195 if (refstr == NULL)
5196 return got_error_from_errno("got_ref_to_str");
5198 printf("%s%s: %s\n", marker, refname, refstr);
5199 free(refstr);
5200 return NULL;
5203 static const struct got_error *
5204 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5206 const char *refname;
5208 if (worktree == NULL)
5209 return got_error(GOT_ERR_NOT_WORKTREE);
5211 refname = got_worktree_get_head_ref_name(worktree);
5213 if (strncmp(refname, "refs/heads/", 11) == 0)
5214 refname += 11;
5215 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5216 refname += 18;
5218 printf("%s\n", refname);
5220 return NULL;
5223 static const struct got_error *
5224 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5226 static const struct got_error *err = NULL;
5227 struct got_reflist_head refs;
5228 struct got_reflist_entry *re;
5229 struct got_reference *temp_ref = NULL;
5230 int rebase_in_progress, histedit_in_progress;
5232 SIMPLEQ_INIT(&refs);
5234 if (worktree) {
5235 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5236 worktree);
5237 if (err)
5238 return err;
5240 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5241 worktree);
5242 if (err)
5243 return err;
5245 if (rebase_in_progress || histedit_in_progress) {
5246 err = got_ref_open(&temp_ref, repo,
5247 got_worktree_get_head_ref_name(worktree), 0);
5248 if (err)
5249 return err;
5250 list_branch(repo, worktree, temp_ref);
5251 got_ref_close(temp_ref);
5255 err = got_ref_list(&refs, repo, "refs/heads",
5256 got_ref_cmp_by_name, NULL);
5257 if (err)
5258 return err;
5260 SIMPLEQ_FOREACH(re, &refs, entry)
5261 list_branch(repo, worktree, re->ref);
5263 got_ref_list_free(&refs);
5264 return NULL;
5267 static const struct got_error *
5268 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5269 const char *branch_name)
5271 const struct got_error *err = NULL;
5272 struct got_reference *ref = NULL;
5273 char *refname;
5275 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5276 return got_error_from_errno("asprintf");
5278 err = got_ref_open(&ref, repo, refname, 0);
5279 if (err)
5280 goto done;
5282 if (worktree &&
5283 strcmp(got_worktree_get_head_ref_name(worktree),
5284 got_ref_get_name(ref)) == 0) {
5285 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5286 "will not delete this work tree's current branch");
5287 goto done;
5290 err = got_ref_delete(ref, repo);
5291 done:
5292 if (ref)
5293 got_ref_close(ref);
5294 free(refname);
5295 return err;
5298 static const struct got_error *
5299 add_branch(struct got_repository *repo, const char *branch_name,
5300 struct got_object_id *base_commit_id)
5302 const struct got_error *err = NULL;
5303 struct got_reference *ref = NULL;
5304 char *base_refname = NULL, *refname = NULL;
5307 * Don't let the user create a branch name with a leading '-'.
5308 * While technically a valid reference name, this case is usually
5309 * an unintended typo.
5311 if (branch_name[0] == '-')
5312 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5314 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5315 err = got_error_from_errno("asprintf");
5316 goto done;
5319 err = got_ref_open(&ref, repo, refname, 0);
5320 if (err == NULL) {
5321 err = got_error(GOT_ERR_BRANCH_EXISTS);
5322 goto done;
5323 } else if (err->code != GOT_ERR_NOT_REF)
5324 goto done;
5326 err = got_ref_alloc(&ref, refname, base_commit_id);
5327 if (err)
5328 goto done;
5330 err = got_ref_write(ref, repo);
5331 done:
5332 if (ref)
5333 got_ref_close(ref);
5334 free(base_refname);
5335 free(refname);
5336 return err;
5339 static const struct got_error *
5340 cmd_branch(int argc, char *argv[])
5342 const struct got_error *error = NULL;
5343 struct got_repository *repo = NULL;
5344 struct got_worktree *worktree = NULL;
5345 char *cwd = NULL, *repo_path = NULL;
5346 int ch, do_list = 0, do_show = 0, do_update = 1;
5347 const char *delref = NULL, *commit_id_arg = NULL;
5348 struct got_reference *ref = NULL;
5349 struct got_pathlist_head paths;
5350 struct got_pathlist_entry *pe;
5351 struct got_object_id *commit_id = NULL;
5352 char *commit_id_str = NULL;
5354 TAILQ_INIT(&paths);
5356 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5357 switch (ch) {
5358 case 'c':
5359 commit_id_arg = optarg;
5360 break;
5361 case 'd':
5362 delref = optarg;
5363 break;
5364 case 'r':
5365 repo_path = realpath(optarg, NULL);
5366 if (repo_path == NULL)
5367 return got_error_from_errno2("realpath",
5368 optarg);
5369 got_path_strip_trailing_slashes(repo_path);
5370 break;
5371 case 'l':
5372 do_list = 1;
5373 break;
5374 case 'n':
5375 do_update = 0;
5376 break;
5377 default:
5378 usage_branch();
5379 /* NOTREACHED */
5383 if (do_list && delref)
5384 errx(1, "-l and -d options are mutually exclusive");
5386 argc -= optind;
5387 argv += optind;
5389 if (!do_list && !delref && argc == 0)
5390 do_show = 1;
5392 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5393 errx(1, "-c option can only be used when creating a branch");
5395 if (do_list || delref) {
5396 if (argc > 0)
5397 usage_branch();
5398 } else if (!do_show && argc != 1)
5399 usage_branch();
5401 #ifndef PROFILE
5402 if (do_list || do_show) {
5403 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5404 NULL) == -1)
5405 err(1, "pledge");
5406 } else {
5407 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5408 "sendfd unveil", NULL) == -1)
5409 err(1, "pledge");
5411 #endif
5412 cwd = getcwd(NULL, 0);
5413 if (cwd == NULL) {
5414 error = got_error_from_errno("getcwd");
5415 goto done;
5418 if (repo_path == NULL) {
5419 error = got_worktree_open(&worktree, cwd);
5420 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5421 goto done;
5422 else
5423 error = NULL;
5424 if (worktree) {
5425 repo_path =
5426 strdup(got_worktree_get_repo_path(worktree));
5427 if (repo_path == NULL)
5428 error = got_error_from_errno("strdup");
5429 if (error)
5430 goto done;
5431 } else {
5432 repo_path = strdup(cwd);
5433 if (repo_path == NULL) {
5434 error = got_error_from_errno("strdup");
5435 goto done;
5440 error = got_repo_open(&repo, repo_path, NULL);
5441 if (error != NULL)
5442 goto done;
5444 error = apply_unveil(got_repo_get_path(repo), do_list,
5445 worktree ? got_worktree_get_root_path(worktree) : NULL);
5446 if (error)
5447 goto done;
5449 if (do_show)
5450 error = show_current_branch(repo, worktree);
5451 else if (do_list)
5452 error = list_branches(repo, worktree);
5453 else if (delref)
5454 error = delete_branch(repo, worktree, delref);
5455 else {
5456 if (commit_id_arg == NULL)
5457 commit_id_arg = worktree ?
5458 got_worktree_get_head_ref_name(worktree) :
5459 GOT_REF_HEAD;
5460 error = got_repo_match_object_id(&commit_id, NULL,
5461 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5462 if (error)
5463 goto done;
5464 error = add_branch(repo, argv[0], commit_id);
5465 if (error)
5466 goto done;
5467 if (worktree && do_update) {
5468 struct got_update_progress_arg upa;
5469 char *branch_refname = NULL;
5471 error = got_object_id_str(&commit_id_str, commit_id);
5472 if (error)
5473 goto done;
5474 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5475 worktree);
5476 if (error)
5477 goto done;
5478 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5479 == -1) {
5480 error = got_error_from_errno("asprintf");
5481 goto done;
5483 error = got_ref_open(&ref, repo, branch_refname, 0);
5484 free(branch_refname);
5485 if (error)
5486 goto done;
5487 error = switch_head_ref(ref, commit_id, worktree,
5488 repo);
5489 if (error)
5490 goto done;
5491 error = got_worktree_set_base_commit_id(worktree, repo,
5492 commit_id);
5493 if (error)
5494 goto done;
5495 memset(&upa, 0, sizeof(upa));
5496 error = got_worktree_checkout_files(worktree, &paths,
5497 repo, update_progress, &upa, check_cancelled,
5498 NULL);
5499 if (error)
5500 goto done;
5501 if (upa.did_something)
5502 printf("Updated to commit %s\n", commit_id_str);
5503 print_update_progress_stats(&upa);
5506 done:
5507 if (ref)
5508 got_ref_close(ref);
5509 if (repo)
5510 got_repo_close(repo);
5511 if (worktree)
5512 got_worktree_close(worktree);
5513 free(cwd);
5514 free(repo_path);
5515 free(commit_id);
5516 free(commit_id_str);
5517 TAILQ_FOREACH(pe, &paths, entry)
5518 free((char *)pe->path);
5519 got_pathlist_free(&paths);
5520 return error;
5524 __dead static void
5525 usage_tag(void)
5527 fprintf(stderr,
5528 "usage: %s tag [-c commit] [-r repository] [-l] "
5529 "[-m message] name\n", getprogname());
5530 exit(1);
5533 #if 0
5534 static const struct got_error *
5535 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5537 const struct got_error *err = NULL;
5538 struct got_reflist_entry *re, *se, *new;
5539 struct got_object_id *re_id, *se_id;
5540 struct got_tag_object *re_tag, *se_tag;
5541 time_t re_time, se_time;
5543 SIMPLEQ_FOREACH(re, tags, entry) {
5544 se = SIMPLEQ_FIRST(sorted);
5545 if (se == NULL) {
5546 err = got_reflist_entry_dup(&new, re);
5547 if (err)
5548 return err;
5549 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5550 continue;
5551 } else {
5552 err = got_ref_resolve(&re_id, repo, re->ref);
5553 if (err)
5554 break;
5555 err = got_object_open_as_tag(&re_tag, repo, re_id);
5556 free(re_id);
5557 if (err)
5558 break;
5559 re_time = got_object_tag_get_tagger_time(re_tag);
5560 got_object_tag_close(re_tag);
5563 while (se) {
5564 err = got_ref_resolve(&se_id, repo, re->ref);
5565 if (err)
5566 break;
5567 err = got_object_open_as_tag(&se_tag, repo, se_id);
5568 free(se_id);
5569 if (err)
5570 break;
5571 se_time = got_object_tag_get_tagger_time(se_tag);
5572 got_object_tag_close(se_tag);
5574 if (se_time > re_time) {
5575 err = got_reflist_entry_dup(&new, re);
5576 if (err)
5577 return err;
5578 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5579 break;
5581 se = SIMPLEQ_NEXT(se, entry);
5582 continue;
5585 done:
5586 return err;
5588 #endif
5590 static const struct got_error *
5591 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5593 static const struct got_error *err = NULL;
5594 struct got_reflist_head refs;
5595 struct got_reflist_entry *re;
5597 SIMPLEQ_INIT(&refs);
5599 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5600 if (err)
5601 return err;
5603 SIMPLEQ_FOREACH(re, &refs, entry) {
5604 const char *refname;
5605 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5606 char datebuf[26];
5607 const char *tagger;
5608 time_t tagger_time;
5609 struct got_object_id *id;
5610 struct got_tag_object *tag;
5611 struct got_commit_object *commit = NULL;
5613 refname = got_ref_get_name(re->ref);
5614 if (strncmp(refname, "refs/tags/", 10) != 0)
5615 continue;
5616 refname += 10;
5617 refstr = got_ref_to_str(re->ref);
5618 if (refstr == NULL) {
5619 err = got_error_from_errno("got_ref_to_str");
5620 break;
5622 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5623 free(refstr);
5625 err = got_ref_resolve(&id, repo, re->ref);
5626 if (err)
5627 break;
5628 err = got_object_open_as_tag(&tag, repo, id);
5629 if (err) {
5630 if (err->code != GOT_ERR_OBJ_TYPE) {
5631 free(id);
5632 break;
5634 /* "lightweight" tag */
5635 err = got_object_open_as_commit(&commit, repo, id);
5636 if (err) {
5637 free(id);
5638 break;
5640 tagger = got_object_commit_get_committer(commit);
5641 tagger_time =
5642 got_object_commit_get_committer_time(commit);
5643 err = got_object_id_str(&id_str, id);
5644 free(id);
5645 if (err)
5646 break;
5647 } else {
5648 free(id);
5649 tagger = got_object_tag_get_tagger(tag);
5650 tagger_time = got_object_tag_get_tagger_time(tag);
5651 err = got_object_id_str(&id_str,
5652 got_object_tag_get_object_id(tag));
5653 if (err)
5654 break;
5656 printf("from: %s\n", tagger);
5657 datestr = get_datestr(&tagger_time, datebuf);
5658 if (datestr)
5659 printf("date: %s UTC\n", datestr);
5660 if (commit)
5661 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5662 else {
5663 switch (got_object_tag_get_object_type(tag)) {
5664 case GOT_OBJ_TYPE_BLOB:
5665 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5666 id_str);
5667 break;
5668 case GOT_OBJ_TYPE_TREE:
5669 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5670 id_str);
5671 break;
5672 case GOT_OBJ_TYPE_COMMIT:
5673 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5674 id_str);
5675 break;
5676 case GOT_OBJ_TYPE_TAG:
5677 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5678 id_str);
5679 break;
5680 default:
5681 break;
5684 free(id_str);
5685 if (commit) {
5686 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5687 if (err)
5688 break;
5689 got_object_commit_close(commit);
5690 } else {
5691 tagmsg0 = strdup(got_object_tag_get_message(tag));
5692 got_object_tag_close(tag);
5693 if (tagmsg0 == NULL) {
5694 err = got_error_from_errno("strdup");
5695 break;
5699 tagmsg = tagmsg0;
5700 do {
5701 line = strsep(&tagmsg, "\n");
5702 if (line)
5703 printf(" %s\n", line);
5704 } while (line);
5705 free(tagmsg0);
5708 got_ref_list_free(&refs);
5709 return NULL;
5712 static const struct got_error *
5713 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5714 const char *tag_name, const char *repo_path)
5716 const struct got_error *err = NULL;
5717 char *template = NULL, *initial_content = NULL;
5718 char *editor = NULL;
5719 int initial_content_len;
5720 int fd = -1;
5722 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5723 err = got_error_from_errno("asprintf");
5724 goto done;
5727 initial_content_len = asprintf(&initial_content,
5728 "\n# tagging commit %s as %s\n",
5729 commit_id_str, tag_name);
5730 if (initial_content_len == -1) {
5731 err = got_error_from_errno("asprintf");
5732 goto done;
5735 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5736 if (err)
5737 goto done;
5739 if (write(fd, initial_content, initial_content_len) == -1) {
5740 err = got_error_from_errno2("write", *tagmsg_path);
5741 goto done;
5744 err = get_editor(&editor);
5745 if (err)
5746 goto done;
5747 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
5748 done:
5749 free(initial_content);
5750 free(template);
5751 free(editor);
5753 if (fd != -1 && close(fd) == -1 && err == NULL)
5754 err = got_error_from_errno2("close", *tagmsg_path);
5756 /* Editor is done; we can now apply unveil(2) */
5757 if (err == NULL)
5758 err = apply_unveil(repo_path, 0, NULL);
5759 if (err) {
5760 free(*tagmsg);
5761 *tagmsg = NULL;
5763 return err;
5766 static const struct got_error *
5767 add_tag(struct got_repository *repo, struct got_worktree *worktree,
5768 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
5770 const struct got_error *err = NULL;
5771 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5772 char *label = NULL, *commit_id_str = NULL;
5773 struct got_reference *ref = NULL;
5774 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5775 char *tagmsg_path = NULL, *tag_id_str = NULL;
5776 int preserve_tagmsg = 0;
5779 * Don't let the user create a tag name with a leading '-'.
5780 * While technically a valid reference name, this case is usually
5781 * an unintended typo.
5783 if (tag_name[0] == '-')
5784 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5786 err = get_author(&tagger, repo, worktree);
5787 if (err)
5788 return err;
5790 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5791 GOT_OBJ_TYPE_COMMIT, 1, repo);
5792 if (err)
5793 goto done;
5795 err = got_object_id_str(&commit_id_str, commit_id);
5796 if (err)
5797 goto done;
5799 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5800 refname = strdup(tag_name);
5801 if (refname == NULL) {
5802 err = got_error_from_errno("strdup");
5803 goto done;
5805 tag_name += 10;
5806 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5807 err = got_error_from_errno("asprintf");
5808 goto done;
5811 err = got_ref_open(&ref, repo, refname, 0);
5812 if (err == NULL) {
5813 err = got_error(GOT_ERR_TAG_EXISTS);
5814 goto done;
5815 } else if (err->code != GOT_ERR_NOT_REF)
5816 goto done;
5818 if (tagmsg_arg == NULL) {
5819 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5820 tag_name, got_repo_get_path(repo));
5821 if (err) {
5822 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5823 tagmsg_path != NULL)
5824 preserve_tagmsg = 1;
5825 goto done;
5829 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5830 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5831 if (err) {
5832 if (tagmsg_path)
5833 preserve_tagmsg = 1;
5834 goto done;
5837 err = got_ref_alloc(&ref, refname, tag_id);
5838 if (err) {
5839 if (tagmsg_path)
5840 preserve_tagmsg = 1;
5841 goto done;
5844 err = got_ref_write(ref, repo);
5845 if (err) {
5846 if (tagmsg_path)
5847 preserve_tagmsg = 1;
5848 goto done;
5851 err = got_object_id_str(&tag_id_str, tag_id);
5852 if (err) {
5853 if (tagmsg_path)
5854 preserve_tagmsg = 1;
5855 goto done;
5857 printf("Created tag %s\n", tag_id_str);
5858 done:
5859 if (preserve_tagmsg) {
5860 fprintf(stderr, "%s: tag message preserved in %s\n",
5861 getprogname(), tagmsg_path);
5862 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
5863 err = got_error_from_errno2("unlink", tagmsg_path);
5864 free(tag_id_str);
5865 if (ref)
5866 got_ref_close(ref);
5867 free(commit_id);
5868 free(commit_id_str);
5869 free(refname);
5870 free(tagmsg);
5871 free(tagmsg_path);
5872 free(tagger);
5873 return err;
5876 static const struct got_error *
5877 cmd_tag(int argc, char *argv[])
5879 const struct got_error *error = NULL;
5880 struct got_repository *repo = NULL;
5881 struct got_worktree *worktree = NULL;
5882 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
5883 char *gitconfig_path = NULL;
5884 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
5885 int ch, do_list = 0;
5887 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
5888 switch (ch) {
5889 case 'c':
5890 commit_id_arg = optarg;
5891 break;
5892 case 'm':
5893 tagmsg = optarg;
5894 break;
5895 case 'r':
5896 repo_path = realpath(optarg, NULL);
5897 if (repo_path == NULL)
5898 return got_error_from_errno2("realpath",
5899 optarg);
5900 got_path_strip_trailing_slashes(repo_path);
5901 break;
5902 case 'l':
5903 do_list = 1;
5904 break;
5905 default:
5906 usage_tag();
5907 /* NOTREACHED */
5911 argc -= optind;
5912 argv += optind;
5914 if (do_list) {
5915 if (commit_id_arg != NULL)
5916 errx(1,
5917 "-c option can only be used when creating a tag");
5918 if (tagmsg)
5919 errx(1, "-l and -m options are mutually exclusive");
5920 if (argc > 0)
5921 usage_tag();
5922 } else if (argc != 1)
5923 usage_tag();
5925 tag_name = argv[0];
5927 #ifndef PROFILE
5928 if (do_list) {
5929 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5930 NULL) == -1)
5931 err(1, "pledge");
5932 } else {
5933 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5934 "sendfd unveil", NULL) == -1)
5935 err(1, "pledge");
5937 #endif
5938 cwd = getcwd(NULL, 0);
5939 if (cwd == NULL) {
5940 error = got_error_from_errno("getcwd");
5941 goto done;
5944 if (repo_path == NULL) {
5945 error = got_worktree_open(&worktree, cwd);
5946 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5947 goto done;
5948 else
5949 error = NULL;
5950 if (worktree) {
5951 repo_path =
5952 strdup(got_worktree_get_repo_path(worktree));
5953 if (repo_path == NULL)
5954 error = got_error_from_errno("strdup");
5955 if (error)
5956 goto done;
5957 } else {
5958 repo_path = strdup(cwd);
5959 if (repo_path == NULL) {
5960 error = got_error_from_errno("strdup");
5961 goto done;
5966 if (do_list) {
5967 error = got_repo_open(&repo, repo_path, NULL);
5968 if (error != NULL)
5969 goto done;
5970 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5971 if (error)
5972 goto done;
5973 error = list_tags(repo, worktree);
5974 } else {
5975 error = get_gitconfig_path(&gitconfig_path);
5976 if (error)
5977 goto done;
5978 error = got_repo_open(&repo, repo_path, gitconfig_path);
5979 if (error != NULL)
5980 goto done;
5982 if (tagmsg) {
5983 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5984 if (error)
5985 goto done;
5988 if (commit_id_arg == NULL) {
5989 struct got_reference *head_ref;
5990 struct got_object_id *commit_id;
5991 error = got_ref_open(&head_ref, repo,
5992 worktree ? got_worktree_get_head_ref_name(worktree)
5993 : GOT_REF_HEAD, 0);
5994 if (error)
5995 goto done;
5996 error = got_ref_resolve(&commit_id, repo, head_ref);
5997 got_ref_close(head_ref);
5998 if (error)
5999 goto done;
6000 error = got_object_id_str(&commit_id_str, commit_id);
6001 free(commit_id);
6002 if (error)
6003 goto done;
6006 error = add_tag(repo, worktree, tag_name,
6007 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6009 done:
6010 if (repo)
6011 got_repo_close(repo);
6012 if (worktree)
6013 got_worktree_close(worktree);
6014 free(cwd);
6015 free(repo_path);
6016 free(gitconfig_path);
6017 free(commit_id_str);
6018 return error;
6021 __dead static void
6022 usage_add(void)
6024 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6025 getprogname());
6026 exit(1);
6029 static const struct got_error *
6030 add_progress(void *arg, unsigned char status, const char *path)
6032 while (path[0] == '/')
6033 path++;
6034 printf("%c %s\n", status, path);
6035 return NULL;
6038 static const struct got_error *
6039 cmd_add(int argc, char *argv[])
6041 const struct got_error *error = NULL;
6042 struct got_repository *repo = NULL;
6043 struct got_worktree *worktree = NULL;
6044 char *cwd = NULL;
6045 struct got_pathlist_head paths;
6046 struct got_pathlist_entry *pe;
6047 int ch, can_recurse = 0, no_ignores = 0;
6049 TAILQ_INIT(&paths);
6051 while ((ch = getopt(argc, argv, "IR")) != -1) {
6052 switch (ch) {
6053 case 'I':
6054 no_ignores = 1;
6055 break;
6056 case 'R':
6057 can_recurse = 1;
6058 break;
6059 default:
6060 usage_add();
6061 /* NOTREACHED */
6065 argc -= optind;
6066 argv += optind;
6068 #ifndef PROFILE
6069 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6070 NULL) == -1)
6071 err(1, "pledge");
6072 #endif
6073 if (argc < 1)
6074 usage_add();
6076 cwd = getcwd(NULL, 0);
6077 if (cwd == NULL) {
6078 error = got_error_from_errno("getcwd");
6079 goto done;
6082 error = got_worktree_open(&worktree, cwd);
6083 if (error) {
6084 if (error->code == GOT_ERR_NOT_WORKTREE)
6085 error = wrap_not_worktree_error(error, "add", cwd);
6086 goto done;
6089 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6090 NULL);
6091 if (error != NULL)
6092 goto done;
6094 error = apply_unveil(got_repo_get_path(repo), 1,
6095 got_worktree_get_root_path(worktree));
6096 if (error)
6097 goto done;
6099 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6100 if (error)
6101 goto done;
6103 if (!can_recurse && no_ignores) {
6104 error = got_error_msg(GOT_ERR_BAD_PATH,
6105 "disregarding ignores requires -R option");
6106 goto done;
6110 if (!can_recurse) {
6111 char *ondisk_path;
6112 struct stat sb;
6113 TAILQ_FOREACH(pe, &paths, entry) {
6114 if (asprintf(&ondisk_path, "%s/%s",
6115 got_worktree_get_root_path(worktree),
6116 pe->path) == -1) {
6117 error = got_error_from_errno("asprintf");
6118 goto done;
6120 if (lstat(ondisk_path, &sb) == -1) {
6121 if (errno == ENOENT) {
6122 free(ondisk_path);
6123 continue;
6125 error = got_error_from_errno2("lstat",
6126 ondisk_path);
6127 free(ondisk_path);
6128 goto done;
6130 free(ondisk_path);
6131 if (S_ISDIR(sb.st_mode)) {
6132 error = got_error_msg(GOT_ERR_BAD_PATH,
6133 "adding directories requires -R option");
6134 goto done;
6139 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6140 NULL, repo, no_ignores);
6141 done:
6142 if (repo)
6143 got_repo_close(repo);
6144 if (worktree)
6145 got_worktree_close(worktree);
6146 TAILQ_FOREACH(pe, &paths, entry)
6147 free((char *)pe->path);
6148 got_pathlist_free(&paths);
6149 free(cwd);
6150 return error;
6153 __dead static void
6154 usage_remove(void)
6156 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6157 "path ...\n", getprogname());
6158 exit(1);
6161 static const struct got_error *
6162 print_remove_status(void *arg, unsigned char status,
6163 unsigned char staged_status, const char *path)
6165 while (path[0] == '/')
6166 path++;
6167 if (status == GOT_STATUS_NONEXISTENT)
6168 return NULL;
6169 if (status == staged_status && (status == GOT_STATUS_DELETE))
6170 status = GOT_STATUS_NO_CHANGE;
6171 printf("%c%c %s\n", status, staged_status, path);
6172 return NULL;
6175 static const struct got_error *
6176 cmd_remove(int argc, char *argv[])
6178 const struct got_error *error = NULL;
6179 struct got_worktree *worktree = NULL;
6180 struct got_repository *repo = NULL;
6181 const char *status_codes = NULL;
6182 char *cwd = NULL;
6183 struct got_pathlist_head paths;
6184 struct got_pathlist_entry *pe;
6185 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6187 TAILQ_INIT(&paths);
6189 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6190 switch (ch) {
6191 case 'f':
6192 delete_local_mods = 1;
6193 break;
6194 case 'k':
6195 keep_on_disk = 1;
6196 break;
6197 case 'R':
6198 can_recurse = 1;
6199 break;
6200 case 's':
6201 for (i = 0; i < strlen(optarg); i++) {
6202 switch (optarg[i]) {
6203 case GOT_STATUS_MODIFY:
6204 delete_local_mods = 1;
6205 break;
6206 case GOT_STATUS_MISSING:
6207 break;
6208 default:
6209 errx(1, "invalid status code '%c'",
6210 optarg[i]);
6213 status_codes = optarg;
6214 break;
6215 default:
6216 usage_remove();
6217 /* NOTREACHED */
6221 argc -= optind;
6222 argv += optind;
6224 #ifndef PROFILE
6225 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6226 NULL) == -1)
6227 err(1, "pledge");
6228 #endif
6229 if (argc < 1)
6230 usage_remove();
6232 cwd = getcwd(NULL, 0);
6233 if (cwd == NULL) {
6234 error = got_error_from_errno("getcwd");
6235 goto done;
6237 error = got_worktree_open(&worktree, cwd);
6238 if (error) {
6239 if (error->code == GOT_ERR_NOT_WORKTREE)
6240 error = wrap_not_worktree_error(error, "remove", cwd);
6241 goto done;
6244 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6245 NULL);
6246 if (error)
6247 goto done;
6249 error = apply_unveil(got_repo_get_path(repo), 1,
6250 got_worktree_get_root_path(worktree));
6251 if (error)
6252 goto done;
6254 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6255 if (error)
6256 goto done;
6258 if (!can_recurse) {
6259 char *ondisk_path;
6260 struct stat sb;
6261 TAILQ_FOREACH(pe, &paths, entry) {
6262 if (asprintf(&ondisk_path, "%s/%s",
6263 got_worktree_get_root_path(worktree),
6264 pe->path) == -1) {
6265 error = got_error_from_errno("asprintf");
6266 goto done;
6268 if (lstat(ondisk_path, &sb) == -1) {
6269 if (errno == ENOENT) {
6270 free(ondisk_path);
6271 continue;
6273 error = got_error_from_errno2("lstat",
6274 ondisk_path);
6275 free(ondisk_path);
6276 goto done;
6278 free(ondisk_path);
6279 if (S_ISDIR(sb.st_mode)) {
6280 error = got_error_msg(GOT_ERR_BAD_PATH,
6281 "removing directories requires -R option");
6282 goto done;
6287 error = got_worktree_schedule_delete(worktree, &paths,
6288 delete_local_mods, status_codes, print_remove_status, NULL,
6289 repo, keep_on_disk);
6290 done:
6291 if (repo)
6292 got_repo_close(repo);
6293 if (worktree)
6294 got_worktree_close(worktree);
6295 TAILQ_FOREACH(pe, &paths, entry)
6296 free((char *)pe->path);
6297 got_pathlist_free(&paths);
6298 free(cwd);
6299 return error;
6302 __dead static void
6303 usage_revert(void)
6305 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6306 "path ...\n", getprogname());
6307 exit(1);
6310 static const struct got_error *
6311 revert_progress(void *arg, unsigned char status, const char *path)
6313 if (status == GOT_STATUS_UNVERSIONED)
6314 return NULL;
6316 while (path[0] == '/')
6317 path++;
6318 printf("%c %s\n", status, path);
6319 return NULL;
6322 struct choose_patch_arg {
6323 FILE *patch_script_file;
6324 const char *action;
6327 static const struct got_error *
6328 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6329 int nchanges, const char *action)
6331 char *line = NULL;
6332 size_t linesize = 0;
6333 ssize_t linelen;
6335 switch (status) {
6336 case GOT_STATUS_ADD:
6337 printf("A %s\n%s this addition? [y/n] ", path, action);
6338 break;
6339 case GOT_STATUS_DELETE:
6340 printf("D %s\n%s this deletion? [y/n] ", path, action);
6341 break;
6342 case GOT_STATUS_MODIFY:
6343 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6344 return got_error_from_errno("fseek");
6345 printf(GOT_COMMIT_SEP_STR);
6346 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6347 printf("%s", line);
6348 if (ferror(patch_file))
6349 return got_error_from_errno("getline");
6350 printf(GOT_COMMIT_SEP_STR);
6351 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6352 path, n, nchanges, action);
6353 break;
6354 default:
6355 return got_error_path(path, GOT_ERR_FILE_STATUS);
6358 return NULL;
6361 static const struct got_error *
6362 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6363 FILE *patch_file, int n, int nchanges)
6365 const struct got_error *err = NULL;
6366 char *line = NULL;
6367 size_t linesize = 0;
6368 ssize_t linelen;
6369 int resp = ' ';
6370 struct choose_patch_arg *a = arg;
6372 *choice = GOT_PATCH_CHOICE_NONE;
6374 if (a->patch_script_file) {
6375 char *nl;
6376 err = show_change(status, path, patch_file, n, nchanges,
6377 a->action);
6378 if (err)
6379 return err;
6380 linelen = getline(&line, &linesize, a->patch_script_file);
6381 if (linelen == -1) {
6382 if (ferror(a->patch_script_file))
6383 return got_error_from_errno("getline");
6384 return NULL;
6386 nl = strchr(line, '\n');
6387 if (nl)
6388 *nl = '\0';
6389 if (strcmp(line, "y") == 0) {
6390 *choice = GOT_PATCH_CHOICE_YES;
6391 printf("y\n");
6392 } else if (strcmp(line, "n") == 0) {
6393 *choice = GOT_PATCH_CHOICE_NO;
6394 printf("n\n");
6395 } else if (strcmp(line, "q") == 0 &&
6396 status == GOT_STATUS_MODIFY) {
6397 *choice = GOT_PATCH_CHOICE_QUIT;
6398 printf("q\n");
6399 } else
6400 printf("invalid response '%s'\n", line);
6401 free(line);
6402 return NULL;
6405 while (resp != 'y' && resp != 'n' && resp != 'q') {
6406 err = show_change(status, path, patch_file, n, nchanges,
6407 a->action);
6408 if (err)
6409 return err;
6410 resp = getchar();
6411 if (resp == '\n')
6412 resp = getchar();
6413 if (status == GOT_STATUS_MODIFY) {
6414 if (resp != 'y' && resp != 'n' && resp != 'q') {
6415 printf("invalid response '%c'\n", resp);
6416 resp = ' ';
6418 } else if (resp != 'y' && resp != 'n') {
6419 printf("invalid response '%c'\n", resp);
6420 resp = ' ';
6424 if (resp == 'y')
6425 *choice = GOT_PATCH_CHOICE_YES;
6426 else if (resp == 'n')
6427 *choice = GOT_PATCH_CHOICE_NO;
6428 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6429 *choice = GOT_PATCH_CHOICE_QUIT;
6431 return NULL;
6435 static const struct got_error *
6436 cmd_revert(int argc, char *argv[])
6438 const struct got_error *error = NULL;
6439 struct got_worktree *worktree = NULL;
6440 struct got_repository *repo = NULL;
6441 char *cwd = NULL, *path = NULL;
6442 struct got_pathlist_head paths;
6443 struct got_pathlist_entry *pe;
6444 int ch, can_recurse = 0, pflag = 0;
6445 FILE *patch_script_file = NULL;
6446 const char *patch_script_path = NULL;
6447 struct choose_patch_arg cpa;
6449 TAILQ_INIT(&paths);
6451 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6452 switch (ch) {
6453 case 'p':
6454 pflag = 1;
6455 break;
6456 case 'F':
6457 patch_script_path = optarg;
6458 break;
6459 case 'R':
6460 can_recurse = 1;
6461 break;
6462 default:
6463 usage_revert();
6464 /* NOTREACHED */
6468 argc -= optind;
6469 argv += optind;
6471 #ifndef PROFILE
6472 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6473 "unveil", NULL) == -1)
6474 err(1, "pledge");
6475 #endif
6476 if (argc < 1)
6477 usage_revert();
6478 if (patch_script_path && !pflag)
6479 errx(1, "-F option can only be used together with -p option");
6481 cwd = getcwd(NULL, 0);
6482 if (cwd == NULL) {
6483 error = got_error_from_errno("getcwd");
6484 goto done;
6486 error = got_worktree_open(&worktree, cwd);
6487 if (error) {
6488 if (error->code == GOT_ERR_NOT_WORKTREE)
6489 error = wrap_not_worktree_error(error, "revert", cwd);
6490 goto done;
6493 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6494 NULL);
6495 if (error != NULL)
6496 goto done;
6498 if (patch_script_path) {
6499 patch_script_file = fopen(patch_script_path, "r");
6500 if (patch_script_file == NULL) {
6501 error = got_error_from_errno2("fopen",
6502 patch_script_path);
6503 goto done;
6506 error = apply_unveil(got_repo_get_path(repo), 1,
6507 got_worktree_get_root_path(worktree));
6508 if (error)
6509 goto done;
6511 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6512 if (error)
6513 goto done;
6515 if (!can_recurse) {
6516 char *ondisk_path;
6517 struct stat sb;
6518 TAILQ_FOREACH(pe, &paths, entry) {
6519 if (asprintf(&ondisk_path, "%s/%s",
6520 got_worktree_get_root_path(worktree),
6521 pe->path) == -1) {
6522 error = got_error_from_errno("asprintf");
6523 goto done;
6525 if (lstat(ondisk_path, &sb) == -1) {
6526 if (errno == ENOENT) {
6527 free(ondisk_path);
6528 continue;
6530 error = got_error_from_errno2("lstat",
6531 ondisk_path);
6532 free(ondisk_path);
6533 goto done;
6535 free(ondisk_path);
6536 if (S_ISDIR(sb.st_mode)) {
6537 error = got_error_msg(GOT_ERR_BAD_PATH,
6538 "reverting directories requires -R option");
6539 goto done;
6544 cpa.patch_script_file = patch_script_file;
6545 cpa.action = "revert";
6546 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6547 pflag ? choose_patch : NULL, &cpa, repo);
6548 done:
6549 if (patch_script_file && fclose(patch_script_file) == EOF &&
6550 error == NULL)
6551 error = got_error_from_errno2("fclose", patch_script_path);
6552 if (repo)
6553 got_repo_close(repo);
6554 if (worktree)
6555 got_worktree_close(worktree);
6556 free(path);
6557 free(cwd);
6558 return error;
6561 __dead static void
6562 usage_commit(void)
6564 fprintf(stderr, "usage: %s commit [-m msg] [-S] [path ...]\n",
6565 getprogname());
6566 exit(1);
6569 struct collect_commit_logmsg_arg {
6570 const char *cmdline_log;
6571 const char *editor;
6572 const char *worktree_path;
6573 const char *branch_name;
6574 const char *repo_path;
6575 char *logmsg_path;
6579 static const struct got_error *
6580 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6581 void *arg)
6583 char *initial_content = NULL;
6584 struct got_pathlist_entry *pe;
6585 const struct got_error *err = NULL;
6586 char *template = NULL;
6587 struct collect_commit_logmsg_arg *a = arg;
6588 int initial_content_len;
6589 int fd = -1;
6590 size_t len;
6592 /* if a message was specified on the command line, just use it */
6593 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6594 len = strlen(a->cmdline_log) + 1;
6595 *logmsg = malloc(len + 1);
6596 if (*logmsg == NULL)
6597 return got_error_from_errno("malloc");
6598 strlcpy(*logmsg, a->cmdline_log, len);
6599 return NULL;
6602 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6603 return got_error_from_errno("asprintf");
6605 initial_content_len = asprintf(&initial_content,
6606 "\n# changes to be committed on branch %s:\n",
6607 a->branch_name);
6608 if (initial_content_len == -1)
6609 return got_error_from_errno("asprintf");
6611 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6612 if (err)
6613 goto done;
6615 if (write(fd, initial_content, initial_content_len) == -1) {
6616 err = got_error_from_errno2("write", a->logmsg_path);
6617 goto done;
6620 TAILQ_FOREACH(pe, commitable_paths, entry) {
6621 struct got_commitable *ct = pe->data;
6622 dprintf(fd, "# %c %s\n",
6623 got_commitable_get_status(ct),
6624 got_commitable_get_path(ct));
6627 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
6628 done:
6629 free(initial_content);
6630 free(template);
6632 if (fd != -1 && close(fd) == -1 && err == NULL)
6633 err = got_error_from_errno2("close", a->logmsg_path);
6635 /* Editor is done; we can now apply unveil(2) */
6636 if (err == NULL)
6637 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6638 if (err) {
6639 free(*logmsg);
6640 *logmsg = NULL;
6642 return err;
6645 static const struct got_error *
6646 cmd_commit(int argc, char *argv[])
6648 const struct got_error *error = NULL;
6649 struct got_worktree *worktree = NULL;
6650 struct got_repository *repo = NULL;
6651 char *cwd = NULL, *id_str = NULL;
6652 struct got_object_id *id = NULL;
6653 const char *logmsg = NULL;
6654 struct collect_commit_logmsg_arg cl_arg;
6655 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6656 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6657 int allow_bad_symlinks = 0;
6658 struct got_pathlist_head paths;
6660 TAILQ_INIT(&paths);
6661 cl_arg.logmsg_path = NULL;
6663 while ((ch = getopt(argc, argv, "m:S")) != -1) {
6664 switch (ch) {
6665 case 'm':
6666 logmsg = optarg;
6667 break;
6668 case 'S':
6669 allow_bad_symlinks = 1;
6670 break;
6671 default:
6672 usage_commit();
6673 /* NOTREACHED */
6677 argc -= optind;
6678 argv += optind;
6680 #ifndef PROFILE
6681 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6682 "unveil", NULL) == -1)
6683 err(1, "pledge");
6684 #endif
6685 cwd = getcwd(NULL, 0);
6686 if (cwd == NULL) {
6687 error = got_error_from_errno("getcwd");
6688 goto done;
6690 error = got_worktree_open(&worktree, cwd);
6691 if (error) {
6692 if (error->code == GOT_ERR_NOT_WORKTREE)
6693 error = wrap_not_worktree_error(error, "commit", cwd);
6694 goto done;
6697 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6698 if (error)
6699 goto done;
6700 if (rebase_in_progress) {
6701 error = got_error(GOT_ERR_REBASING);
6702 goto done;
6705 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6706 worktree);
6707 if (error)
6708 goto done;
6710 error = get_gitconfig_path(&gitconfig_path);
6711 if (error)
6712 goto done;
6713 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6714 gitconfig_path);
6715 if (error != NULL)
6716 goto done;
6718 error = get_author(&author, repo, worktree);
6719 if (error)
6720 return error;
6723 * unveil(2) traverses exec(2); if an editor is used we have
6724 * to apply unveil after the log message has been written.
6726 if (logmsg == NULL || strlen(logmsg) == 0)
6727 error = get_editor(&editor);
6728 else
6729 error = apply_unveil(got_repo_get_path(repo), 0,
6730 got_worktree_get_root_path(worktree));
6731 if (error)
6732 goto done;
6734 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6735 if (error)
6736 goto done;
6738 cl_arg.editor = editor;
6739 cl_arg.cmdline_log = logmsg;
6740 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6741 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6742 if (!histedit_in_progress) {
6743 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6744 error = got_error(GOT_ERR_COMMIT_BRANCH);
6745 goto done;
6747 cl_arg.branch_name += 11;
6749 cl_arg.repo_path = got_repo_get_path(repo);
6750 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6751 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
6752 print_status, NULL, repo);
6753 if (error) {
6754 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6755 cl_arg.logmsg_path != NULL)
6756 preserve_logmsg = 1;
6757 goto done;
6760 error = got_object_id_str(&id_str, id);
6761 if (error)
6762 goto done;
6763 printf("Created commit %s\n", id_str);
6764 done:
6765 if (preserve_logmsg) {
6766 fprintf(stderr, "%s: log message preserved in %s\n",
6767 getprogname(), cl_arg.logmsg_path);
6768 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6769 error == NULL)
6770 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6771 free(cl_arg.logmsg_path);
6772 if (repo)
6773 got_repo_close(repo);
6774 if (worktree)
6775 got_worktree_close(worktree);
6776 free(cwd);
6777 free(id_str);
6778 free(gitconfig_path);
6779 free(editor);
6780 free(author);
6781 return error;
6784 __dead static void
6785 usage_cherrypick(void)
6787 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6788 exit(1);
6791 static const struct got_error *
6792 cmd_cherrypick(int argc, char *argv[])
6794 const struct got_error *error = NULL;
6795 struct got_worktree *worktree = NULL;
6796 struct got_repository *repo = NULL;
6797 char *cwd = NULL, *commit_id_str = NULL;
6798 struct got_object_id *commit_id = NULL;
6799 struct got_commit_object *commit = NULL;
6800 struct got_object_qid *pid;
6801 struct got_reference *head_ref = NULL;
6802 int ch;
6803 struct got_update_progress_arg upa;
6805 while ((ch = getopt(argc, argv, "")) != -1) {
6806 switch (ch) {
6807 default:
6808 usage_cherrypick();
6809 /* NOTREACHED */
6813 argc -= optind;
6814 argv += optind;
6816 #ifndef PROFILE
6817 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6818 "unveil", NULL) == -1)
6819 err(1, "pledge");
6820 #endif
6821 if (argc != 1)
6822 usage_cherrypick();
6824 cwd = getcwd(NULL, 0);
6825 if (cwd == NULL) {
6826 error = got_error_from_errno("getcwd");
6827 goto done;
6829 error = got_worktree_open(&worktree, cwd);
6830 if (error) {
6831 if (error->code == GOT_ERR_NOT_WORKTREE)
6832 error = wrap_not_worktree_error(error, "cherrypick",
6833 cwd);
6834 goto done;
6837 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6838 NULL);
6839 if (error != NULL)
6840 goto done;
6842 error = apply_unveil(got_repo_get_path(repo), 0,
6843 got_worktree_get_root_path(worktree));
6844 if (error)
6845 goto done;
6847 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6848 GOT_OBJ_TYPE_COMMIT, repo);
6849 if (error != NULL) {
6850 struct got_reference *ref;
6851 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6852 goto done;
6853 error = got_ref_open(&ref, repo, argv[0], 0);
6854 if (error != NULL)
6855 goto done;
6856 error = got_ref_resolve(&commit_id, repo, ref);
6857 got_ref_close(ref);
6858 if (error != NULL)
6859 goto done;
6861 error = got_object_id_str(&commit_id_str, commit_id);
6862 if (error)
6863 goto done;
6865 error = got_ref_open(&head_ref, repo,
6866 got_worktree_get_head_ref_name(worktree), 0);
6867 if (error != NULL)
6868 goto done;
6870 error = check_same_branch(commit_id, head_ref, NULL, repo);
6871 if (error) {
6872 if (error->code != GOT_ERR_ANCESTRY)
6873 goto done;
6874 error = NULL;
6875 } else {
6876 error = got_error(GOT_ERR_SAME_BRANCH);
6877 goto done;
6880 error = got_object_open_as_commit(&commit, repo, commit_id);
6881 if (error)
6882 goto done;
6883 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6884 memset(&upa, 0, sizeof(upa));
6885 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
6886 commit_id, repo, update_progress, &upa, check_cancelled,
6887 NULL);
6888 if (error != NULL)
6889 goto done;
6891 if (upa.did_something)
6892 printf("Merged commit %s\n", commit_id_str);
6893 print_update_progress_stats(&upa);
6894 done:
6895 if (commit)
6896 got_object_commit_close(commit);
6897 free(commit_id_str);
6898 if (head_ref)
6899 got_ref_close(head_ref);
6900 if (worktree)
6901 got_worktree_close(worktree);
6902 if (repo)
6903 got_repo_close(repo);
6904 return error;
6907 __dead static void
6908 usage_backout(void)
6910 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
6911 exit(1);
6914 static const struct got_error *
6915 cmd_backout(int argc, char *argv[])
6917 const struct got_error *error = NULL;
6918 struct got_worktree *worktree = NULL;
6919 struct got_repository *repo = NULL;
6920 char *cwd = NULL, *commit_id_str = NULL;
6921 struct got_object_id *commit_id = NULL;
6922 struct got_commit_object *commit = NULL;
6923 struct got_object_qid *pid;
6924 struct got_reference *head_ref = NULL;
6925 int ch;
6926 struct got_update_progress_arg upa;
6928 while ((ch = getopt(argc, argv, "")) != -1) {
6929 switch (ch) {
6930 default:
6931 usage_backout();
6932 /* NOTREACHED */
6936 argc -= optind;
6937 argv += optind;
6939 #ifndef PROFILE
6940 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6941 "unveil", NULL) == -1)
6942 err(1, "pledge");
6943 #endif
6944 if (argc != 1)
6945 usage_backout();
6947 cwd = getcwd(NULL, 0);
6948 if (cwd == NULL) {
6949 error = got_error_from_errno("getcwd");
6950 goto done;
6952 error = got_worktree_open(&worktree, cwd);
6953 if (error) {
6954 if (error->code == GOT_ERR_NOT_WORKTREE)
6955 error = wrap_not_worktree_error(error, "backout", cwd);
6956 goto done;
6959 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6960 NULL);
6961 if (error != NULL)
6962 goto done;
6964 error = apply_unveil(got_repo_get_path(repo), 0,
6965 got_worktree_get_root_path(worktree));
6966 if (error)
6967 goto done;
6969 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6970 GOT_OBJ_TYPE_COMMIT, repo);
6971 if (error != NULL) {
6972 struct got_reference *ref;
6973 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6974 goto done;
6975 error = got_ref_open(&ref, repo, argv[0], 0);
6976 if (error != NULL)
6977 goto done;
6978 error = got_ref_resolve(&commit_id, repo, ref);
6979 got_ref_close(ref);
6980 if (error != NULL)
6981 goto done;
6983 error = got_object_id_str(&commit_id_str, commit_id);
6984 if (error)
6985 goto done;
6987 error = got_ref_open(&head_ref, repo,
6988 got_worktree_get_head_ref_name(worktree), 0);
6989 if (error != NULL)
6990 goto done;
6992 error = check_same_branch(commit_id, head_ref, NULL, repo);
6993 if (error)
6994 goto done;
6996 error = got_object_open_as_commit(&commit, repo, commit_id);
6997 if (error)
6998 goto done;
6999 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7000 if (pid == NULL) {
7001 error = got_error(GOT_ERR_ROOT_COMMIT);
7002 goto done;
7005 memset(&upa, 0, sizeof(upa));
7006 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
7007 update_progress, &upa, check_cancelled, NULL);
7008 if (error != NULL)
7009 goto done;
7011 if (upa.did_something)
7012 printf("Backed out commit %s\n", commit_id_str);
7013 print_update_progress_stats(&upa);
7014 done:
7015 if (commit)
7016 got_object_commit_close(commit);
7017 free(commit_id_str);
7018 if (head_ref)
7019 got_ref_close(head_ref);
7020 if (worktree)
7021 got_worktree_close(worktree);
7022 if (repo)
7023 got_repo_close(repo);
7024 return error;
7027 __dead static void
7028 usage_rebase(void)
7030 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
7031 getprogname());
7032 exit(1);
7035 void
7036 trim_logmsg(char *logmsg, int limit)
7038 char *nl;
7039 size_t len;
7041 len = strlen(logmsg);
7042 if (len > limit)
7043 len = limit;
7044 logmsg[len] = '\0';
7045 nl = strchr(logmsg, '\n');
7046 if (nl)
7047 *nl = '\0';
7050 static const struct got_error *
7051 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
7053 const struct got_error *err;
7054 char *logmsg0 = NULL;
7055 const char *s;
7057 err = got_object_commit_get_logmsg(&logmsg0, commit);
7058 if (err)
7059 return err;
7061 s = logmsg0;
7062 while (isspace((unsigned char)s[0]))
7063 s++;
7065 *logmsg = strdup(s);
7066 if (*logmsg == NULL) {
7067 err = got_error_from_errno("strdup");
7068 goto done;
7071 trim_logmsg(*logmsg, limit);
7072 done:
7073 free(logmsg0);
7074 return err;
7077 static const struct got_error *
7078 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
7080 const struct got_error *err;
7081 struct got_commit_object *commit = NULL;
7082 char *id_str = NULL, *logmsg = NULL;
7084 err = got_object_open_as_commit(&commit, repo, id);
7085 if (err)
7086 return err;
7088 err = got_object_id_str(&id_str, id);
7089 if (err)
7090 goto done;
7092 id_str[12] = '\0';
7094 err = get_short_logmsg(&logmsg, 42, commit);
7095 if (err)
7096 goto done;
7098 printf("%s -> merge conflict: %s\n", id_str, logmsg);
7099 done:
7100 free(id_str);
7101 got_object_commit_close(commit);
7102 free(logmsg);
7103 return err;
7106 static const struct got_error *
7107 show_rebase_progress(struct got_commit_object *commit,
7108 struct got_object_id *old_id, struct got_object_id *new_id)
7110 const struct got_error *err;
7111 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7113 err = got_object_id_str(&old_id_str, old_id);
7114 if (err)
7115 goto done;
7117 if (new_id) {
7118 err = got_object_id_str(&new_id_str, new_id);
7119 if (err)
7120 goto done;
7123 old_id_str[12] = '\0';
7124 if (new_id_str)
7125 new_id_str[12] = '\0';
7127 err = get_short_logmsg(&logmsg, 42, commit);
7128 if (err)
7129 goto done;
7131 printf("%s -> %s: %s\n", old_id_str,
7132 new_id_str ? new_id_str : "no-op change", logmsg);
7133 done:
7134 free(old_id_str);
7135 free(new_id_str);
7136 free(logmsg);
7137 return err;
7140 static const struct got_error *
7141 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
7142 struct got_reference *branch, struct got_reference *new_base_branch,
7143 struct got_reference *tmp_branch, struct got_repository *repo)
7145 printf("Switching work tree to %s\n", got_ref_get_name(branch));
7146 return got_worktree_rebase_complete(worktree, fileindex,
7147 new_base_branch, tmp_branch, branch, repo);
7150 static const struct got_error *
7151 rebase_commit(struct got_pathlist_head *merged_paths,
7152 struct got_worktree *worktree, struct got_fileindex *fileindex,
7153 struct got_reference *tmp_branch,
7154 struct got_object_id *commit_id, struct got_repository *repo)
7156 const struct got_error *error;
7157 struct got_commit_object *commit;
7158 struct got_object_id *new_commit_id;
7160 error = got_object_open_as_commit(&commit, repo, commit_id);
7161 if (error)
7162 return error;
7164 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
7165 worktree, fileindex, tmp_branch, commit, commit_id, repo);
7166 if (error) {
7167 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
7168 goto done;
7169 error = show_rebase_progress(commit, commit_id, NULL);
7170 } else {
7171 error = show_rebase_progress(commit, commit_id, new_commit_id);
7172 free(new_commit_id);
7174 done:
7175 got_object_commit_close(commit);
7176 return error;
7179 struct check_path_prefix_arg {
7180 const char *path_prefix;
7181 size_t len;
7182 int errcode;
7185 static const struct got_error *
7186 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
7187 struct got_blob_object *blob2, struct got_object_id *id1,
7188 struct got_object_id *id2, const char *path1, const char *path2,
7189 mode_t mode1, mode_t mode2, struct got_repository *repo)
7191 struct check_path_prefix_arg *a = arg;
7193 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
7194 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
7195 return got_error(a->errcode);
7197 return NULL;
7200 static const struct got_error *
7201 check_path_prefix(struct got_object_id *parent_id,
7202 struct got_object_id *commit_id, const char *path_prefix,
7203 int errcode, struct got_repository *repo)
7205 const struct got_error *err;
7206 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7207 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7208 struct check_path_prefix_arg cpp_arg;
7210 if (got_path_is_root_dir(path_prefix))
7211 return NULL;
7213 err = got_object_open_as_commit(&commit, repo, commit_id);
7214 if (err)
7215 goto done;
7217 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7218 if (err)
7219 goto done;
7221 err = got_object_open_as_tree(&tree1, repo,
7222 got_object_commit_get_tree_id(parent_commit));
7223 if (err)
7224 goto done;
7226 err = got_object_open_as_tree(&tree2, repo,
7227 got_object_commit_get_tree_id(commit));
7228 if (err)
7229 goto done;
7231 cpp_arg.path_prefix = path_prefix;
7232 while (cpp_arg.path_prefix[0] == '/')
7233 cpp_arg.path_prefix++;
7234 cpp_arg.len = strlen(cpp_arg.path_prefix);
7235 cpp_arg.errcode = errcode;
7236 err = got_diff_tree(tree1, tree2, "", "", repo,
7237 check_path_prefix_in_diff, &cpp_arg, 0);
7238 done:
7239 if (tree1)
7240 got_object_tree_close(tree1);
7241 if (tree2)
7242 got_object_tree_close(tree2);
7243 if (commit)
7244 got_object_commit_close(commit);
7245 if (parent_commit)
7246 got_object_commit_close(parent_commit);
7247 return err;
7250 static const struct got_error *
7251 collect_commits(struct got_object_id_queue *commits,
7252 struct got_object_id *initial_commit_id,
7253 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7254 const char *path_prefix, int path_prefix_errcode,
7255 struct got_repository *repo)
7257 const struct got_error *err = NULL;
7258 struct got_commit_graph *graph = NULL;
7259 struct got_object_id *parent_id = NULL;
7260 struct got_object_qid *qid;
7261 struct got_object_id *commit_id = initial_commit_id;
7263 err = got_commit_graph_open(&graph, "/", 1);
7264 if (err)
7265 return err;
7267 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7268 check_cancelled, NULL);
7269 if (err)
7270 goto done;
7271 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7272 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7273 check_cancelled, NULL);
7274 if (err) {
7275 if (err->code == GOT_ERR_ITER_COMPLETED) {
7276 err = got_error_msg(GOT_ERR_ANCESTRY,
7277 "ran out of commits to rebase before "
7278 "youngest common ancestor commit has "
7279 "been reached?!?");
7281 goto done;
7282 } else {
7283 err = check_path_prefix(parent_id, commit_id,
7284 path_prefix, path_prefix_errcode, repo);
7285 if (err)
7286 goto done;
7288 err = got_object_qid_alloc(&qid, commit_id);
7289 if (err)
7290 goto done;
7291 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
7292 commit_id = parent_id;
7295 done:
7296 got_commit_graph_close(graph);
7297 return err;
7300 static const struct got_error *
7301 cmd_rebase(int argc, char *argv[])
7303 const struct got_error *error = NULL;
7304 struct got_worktree *worktree = NULL;
7305 struct got_repository *repo = NULL;
7306 struct got_fileindex *fileindex = NULL;
7307 char *cwd = NULL;
7308 struct got_reference *branch = NULL;
7309 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
7310 struct got_object_id *commit_id = NULL, *parent_id = NULL;
7311 struct got_object_id *resume_commit_id = NULL;
7312 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
7313 struct got_commit_object *commit = NULL;
7314 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
7315 int histedit_in_progress = 0;
7316 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7317 struct got_object_id_queue commits;
7318 struct got_pathlist_head merged_paths;
7319 const struct got_object_id_queue *parent_ids;
7320 struct got_object_qid *qid, *pid;
7322 SIMPLEQ_INIT(&commits);
7323 TAILQ_INIT(&merged_paths);
7325 while ((ch = getopt(argc, argv, "ac")) != -1) {
7326 switch (ch) {
7327 case 'a':
7328 abort_rebase = 1;
7329 break;
7330 case 'c':
7331 continue_rebase = 1;
7332 break;
7333 default:
7334 usage_rebase();
7335 /* NOTREACHED */
7339 argc -= optind;
7340 argv += optind;
7342 #ifndef PROFILE
7343 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7344 "unveil", NULL) == -1)
7345 err(1, "pledge");
7346 #endif
7347 if (abort_rebase && continue_rebase)
7348 usage_rebase();
7349 else if (abort_rebase || continue_rebase) {
7350 if (argc != 0)
7351 usage_rebase();
7352 } else if (argc != 1)
7353 usage_rebase();
7355 cwd = getcwd(NULL, 0);
7356 if (cwd == NULL) {
7357 error = got_error_from_errno("getcwd");
7358 goto done;
7360 error = got_worktree_open(&worktree, cwd);
7361 if (error) {
7362 if (error->code == GOT_ERR_NOT_WORKTREE)
7363 error = wrap_not_worktree_error(error, "rebase", cwd);
7364 goto done;
7367 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7368 NULL);
7369 if (error != NULL)
7370 goto done;
7372 error = apply_unveil(got_repo_get_path(repo), 0,
7373 got_worktree_get_root_path(worktree));
7374 if (error)
7375 goto done;
7377 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7378 worktree);
7379 if (error)
7380 goto done;
7381 if (histedit_in_progress) {
7382 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7383 goto done;
7386 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7387 if (error)
7388 goto done;
7390 if (abort_rebase) {
7391 struct got_update_progress_arg upa;
7392 if (!rebase_in_progress) {
7393 error = got_error(GOT_ERR_NOT_REBASING);
7394 goto done;
7396 error = got_worktree_rebase_continue(&resume_commit_id,
7397 &new_base_branch, &tmp_branch, &branch, &fileindex,
7398 worktree, repo);
7399 if (error)
7400 goto done;
7401 printf("Switching work tree to %s\n",
7402 got_ref_get_symref_target(new_base_branch));
7403 memset(&upa, 0, sizeof(upa));
7404 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7405 new_base_branch, update_progress, &upa);
7406 if (error)
7407 goto done;
7408 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7409 print_update_progress_stats(&upa);
7410 goto done; /* nothing else to do */
7413 if (continue_rebase) {
7414 if (!rebase_in_progress) {
7415 error = got_error(GOT_ERR_NOT_REBASING);
7416 goto done;
7418 error = got_worktree_rebase_continue(&resume_commit_id,
7419 &new_base_branch, &tmp_branch, &branch, &fileindex,
7420 worktree, repo);
7421 if (error)
7422 goto done;
7424 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7425 resume_commit_id, repo);
7426 if (error)
7427 goto done;
7429 yca_id = got_object_id_dup(resume_commit_id);
7430 if (yca_id == NULL) {
7431 error = got_error_from_errno("got_object_id_dup");
7432 goto done;
7434 } else {
7435 error = got_ref_open(&branch, repo, argv[0], 0);
7436 if (error != NULL)
7437 goto done;
7440 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7441 if (error)
7442 goto done;
7444 if (!continue_rebase) {
7445 struct got_object_id *base_commit_id;
7447 base_commit_id = got_worktree_get_base_commit_id(worktree);
7448 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7449 base_commit_id, branch_head_commit_id, repo,
7450 check_cancelled, NULL);
7451 if (error)
7452 goto done;
7453 if (yca_id == NULL) {
7454 error = got_error_msg(GOT_ERR_ANCESTRY,
7455 "specified branch shares no common ancestry "
7456 "with work tree's branch");
7457 goto done;
7460 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7461 if (error) {
7462 if (error->code != GOT_ERR_ANCESTRY)
7463 goto done;
7464 error = NULL;
7465 } else {
7466 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7467 "specified branch resolves to a commit which "
7468 "is already contained in work tree's branch");
7469 goto done;
7471 error = got_worktree_rebase_prepare(&new_base_branch,
7472 &tmp_branch, &fileindex, worktree, branch, repo);
7473 if (error)
7474 goto done;
7477 commit_id = branch_head_commit_id;
7478 error = got_object_open_as_commit(&commit, repo, commit_id);
7479 if (error)
7480 goto done;
7482 parent_ids = got_object_commit_get_parent_ids(commit);
7483 pid = SIMPLEQ_FIRST(parent_ids);
7484 if (pid == NULL) {
7485 if (!continue_rebase) {
7486 struct got_update_progress_arg upa;
7487 memset(&upa, 0, sizeof(upa));
7488 error = got_worktree_rebase_abort(worktree, fileindex,
7489 repo, new_base_branch, update_progress, &upa);
7490 if (error)
7491 goto done;
7492 printf("Rebase of %s aborted\n",
7493 got_ref_get_name(branch));
7494 print_update_progress_stats(&upa);
7497 error = got_error(GOT_ERR_EMPTY_REBASE);
7498 goto done;
7500 error = collect_commits(&commits, commit_id, pid->id,
7501 yca_id, got_worktree_get_path_prefix(worktree),
7502 GOT_ERR_REBASE_PATH, repo);
7503 got_object_commit_close(commit);
7504 commit = NULL;
7505 if (error)
7506 goto done;
7508 if (SIMPLEQ_EMPTY(&commits)) {
7509 if (continue_rebase) {
7510 error = rebase_complete(worktree, fileindex,
7511 branch, new_base_branch, tmp_branch, repo);
7512 goto done;
7513 } else {
7514 /* Fast-forward the reference of the branch. */
7515 struct got_object_id *new_head_commit_id;
7516 char *id_str;
7517 error = got_ref_resolve(&new_head_commit_id, repo,
7518 new_base_branch);
7519 if (error)
7520 goto done;
7521 error = got_object_id_str(&id_str, new_head_commit_id);
7522 printf("Forwarding %s to commit %s\n",
7523 got_ref_get_name(branch), id_str);
7524 free(id_str);
7525 error = got_ref_change_ref(branch,
7526 new_head_commit_id);
7527 if (error)
7528 goto done;
7532 pid = NULL;
7533 SIMPLEQ_FOREACH(qid, &commits, entry) {
7534 struct got_update_progress_arg upa;
7536 commit_id = qid->id;
7537 parent_id = pid ? pid->id : yca_id;
7538 pid = qid;
7540 memset(&upa, 0, sizeof(upa));
7541 error = got_worktree_rebase_merge_files(&merged_paths,
7542 worktree, fileindex, parent_id, commit_id, repo,
7543 update_progress, &upa, check_cancelled, NULL);
7544 if (error)
7545 goto done;
7547 print_update_progress_stats(&upa);
7548 if (upa.conflicts > 0)
7549 rebase_status = GOT_STATUS_CONFLICT;
7551 if (rebase_status == GOT_STATUS_CONFLICT) {
7552 error = show_rebase_merge_conflict(qid->id, repo);
7553 if (error)
7554 goto done;
7555 got_worktree_rebase_pathlist_free(&merged_paths);
7556 break;
7559 error = rebase_commit(&merged_paths, worktree, fileindex,
7560 tmp_branch, commit_id, repo);
7561 got_worktree_rebase_pathlist_free(&merged_paths);
7562 if (error)
7563 goto done;
7566 if (rebase_status == GOT_STATUS_CONFLICT) {
7567 error = got_worktree_rebase_postpone(worktree, fileindex);
7568 if (error)
7569 goto done;
7570 error = got_error_msg(GOT_ERR_CONFLICTS,
7571 "conflicts must be resolved before rebasing can continue");
7572 } else
7573 error = rebase_complete(worktree, fileindex, branch,
7574 new_base_branch, tmp_branch, repo);
7575 done:
7576 got_object_id_queue_free(&commits);
7577 free(branch_head_commit_id);
7578 free(resume_commit_id);
7579 free(yca_id);
7580 if (commit)
7581 got_object_commit_close(commit);
7582 if (branch)
7583 got_ref_close(branch);
7584 if (new_base_branch)
7585 got_ref_close(new_base_branch);
7586 if (tmp_branch)
7587 got_ref_close(tmp_branch);
7588 if (worktree)
7589 got_worktree_close(worktree);
7590 if (repo)
7591 got_repo_close(repo);
7592 return error;
7595 __dead static void
7596 usage_histedit(void)
7598 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
7599 getprogname());
7600 exit(1);
7603 #define GOT_HISTEDIT_PICK 'p'
7604 #define GOT_HISTEDIT_EDIT 'e'
7605 #define GOT_HISTEDIT_FOLD 'f'
7606 #define GOT_HISTEDIT_DROP 'd'
7607 #define GOT_HISTEDIT_MESG 'm'
7609 static struct got_histedit_cmd {
7610 unsigned char code;
7611 const char *name;
7612 const char *desc;
7613 } got_histedit_cmds[] = {
7614 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7615 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7616 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7617 "be used" },
7618 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7619 { GOT_HISTEDIT_MESG, "mesg",
7620 "single-line log message for commit above (open editor if empty)" },
7623 struct got_histedit_list_entry {
7624 TAILQ_ENTRY(got_histedit_list_entry) entry;
7625 struct got_object_id *commit_id;
7626 const struct got_histedit_cmd *cmd;
7627 char *logmsg;
7629 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7631 static const struct got_error *
7632 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7633 FILE *f, struct got_repository *repo)
7635 const struct got_error *err = NULL;
7636 char *logmsg = NULL, *id_str = NULL;
7637 struct got_commit_object *commit = NULL;
7638 int n;
7640 err = got_object_open_as_commit(&commit, repo, commit_id);
7641 if (err)
7642 goto done;
7644 err = get_short_logmsg(&logmsg, 34, commit);
7645 if (err)
7646 goto done;
7648 err = got_object_id_str(&id_str, commit_id);
7649 if (err)
7650 goto done;
7652 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7653 if (n < 0)
7654 err = got_ferror(f, GOT_ERR_IO);
7655 done:
7656 if (commit)
7657 got_object_commit_close(commit);
7658 free(id_str);
7659 free(logmsg);
7660 return err;
7663 static const struct got_error *
7664 histedit_write_commit_list(struct got_object_id_queue *commits,
7665 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7667 const struct got_error *err = NULL;
7668 struct got_object_qid *qid;
7670 if (SIMPLEQ_EMPTY(commits))
7671 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7673 SIMPLEQ_FOREACH(qid, commits, entry) {
7674 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7675 f, repo);
7676 if (err)
7677 break;
7678 if (edit_logmsg_only) {
7679 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7680 if (n < 0) {
7681 err = got_ferror(f, GOT_ERR_IO);
7682 break;
7687 return err;
7690 static const struct got_error *
7691 write_cmd_list(FILE *f, const char *branch_name,
7692 struct got_object_id_queue *commits)
7694 const struct got_error *err = NULL;
7695 int n, i;
7696 char *id_str;
7697 struct got_object_qid *qid;
7699 qid = SIMPLEQ_FIRST(commits);
7700 err = got_object_id_str(&id_str, qid->id);
7701 if (err)
7702 return err;
7704 n = fprintf(f,
7705 "# Editing the history of branch '%s' starting at\n"
7706 "# commit %s\n"
7707 "# Commits will be processed in order from top to "
7708 "bottom of this file.\n", branch_name, id_str);
7709 if (n < 0) {
7710 err = got_ferror(f, GOT_ERR_IO);
7711 goto done;
7714 n = fprintf(f, "# Available histedit commands:\n");
7715 if (n < 0) {
7716 err = got_ferror(f, GOT_ERR_IO);
7717 goto done;
7720 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7721 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7722 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7723 cmd->desc);
7724 if (n < 0) {
7725 err = got_ferror(f, GOT_ERR_IO);
7726 break;
7729 done:
7730 free(id_str);
7731 return err;
7734 static const struct got_error *
7735 histedit_syntax_error(int lineno)
7737 static char msg[42];
7738 int ret;
7740 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7741 lineno);
7742 if (ret == -1 || ret >= sizeof(msg))
7743 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7745 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7748 static const struct got_error *
7749 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7750 char *logmsg, struct got_repository *repo)
7752 const struct got_error *err;
7753 struct got_commit_object *folded_commit = NULL;
7754 char *id_str, *folded_logmsg = NULL;
7756 err = got_object_id_str(&id_str, hle->commit_id);
7757 if (err)
7758 return err;
7760 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7761 if (err)
7762 goto done;
7764 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7765 if (err)
7766 goto done;
7767 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7768 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7769 folded_logmsg) == -1) {
7770 err = got_error_from_errno("asprintf");
7772 done:
7773 if (folded_commit)
7774 got_object_commit_close(folded_commit);
7775 free(id_str);
7776 free(folded_logmsg);
7777 return err;
7780 static struct got_histedit_list_entry *
7781 get_folded_commits(struct got_histedit_list_entry *hle)
7783 struct got_histedit_list_entry *prev, *folded = NULL;
7785 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7786 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7787 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7788 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7789 folded = prev;
7790 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7793 return folded;
7796 static const struct got_error *
7797 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7798 struct got_repository *repo)
7800 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7801 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7802 const struct got_error *err = NULL;
7803 struct got_commit_object *commit = NULL;
7804 int logmsg_len;
7805 int fd;
7806 struct got_histedit_list_entry *folded = NULL;
7808 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7809 if (err)
7810 return err;
7812 folded = get_folded_commits(hle);
7813 if (folded) {
7814 while (folded != hle) {
7815 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7816 folded = TAILQ_NEXT(folded, entry);
7817 continue;
7819 err = append_folded_commit_msg(&new_msg, folded,
7820 logmsg, repo);
7821 if (err)
7822 goto done;
7823 free(logmsg);
7824 logmsg = new_msg;
7825 folded = TAILQ_NEXT(folded, entry);
7829 err = got_object_id_str(&id_str, hle->commit_id);
7830 if (err)
7831 goto done;
7832 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7833 if (err)
7834 goto done;
7835 logmsg_len = asprintf(&new_msg,
7836 "%s\n# original log message of commit %s: %s",
7837 logmsg ? logmsg : "", id_str, orig_logmsg);
7838 if (logmsg_len == -1) {
7839 err = got_error_from_errno("asprintf");
7840 goto done;
7842 free(logmsg);
7843 logmsg = new_msg;
7845 err = got_object_id_str(&id_str, hle->commit_id);
7846 if (err)
7847 goto done;
7849 err = got_opentemp_named_fd(&logmsg_path, &fd,
7850 GOT_TMPDIR_STR "/got-logmsg");
7851 if (err)
7852 goto done;
7854 write(fd, logmsg, logmsg_len);
7855 close(fd);
7857 err = get_editor(&editor);
7858 if (err)
7859 goto done;
7861 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
7862 if (err) {
7863 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
7864 goto done;
7865 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
7867 done:
7868 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
7869 err = got_error_from_errno2("unlink", logmsg_path);
7870 free(logmsg_path);
7871 free(logmsg);
7872 free(orig_logmsg);
7873 free(editor);
7874 if (commit)
7875 got_object_commit_close(commit);
7876 return err;
7879 static const struct got_error *
7880 histedit_parse_list(struct got_histedit_list *histedit_cmds,
7881 FILE *f, struct got_repository *repo)
7883 const struct got_error *err = NULL;
7884 char *line = NULL, *p, *end;
7885 size_t size;
7886 ssize_t len;
7887 int lineno = 0, i;
7888 const struct got_histedit_cmd *cmd;
7889 struct got_object_id *commit_id = NULL;
7890 struct got_histedit_list_entry *hle = NULL;
7892 for (;;) {
7893 len = getline(&line, &size, f);
7894 if (len == -1) {
7895 const struct got_error *getline_err;
7896 if (feof(f))
7897 break;
7898 getline_err = got_error_from_errno("getline");
7899 err = got_ferror(f, getline_err->code);
7900 break;
7902 lineno++;
7903 p = line;
7904 while (isspace((unsigned char)p[0]))
7905 p++;
7906 if (p[0] == '#' || p[0] == '\0') {
7907 free(line);
7908 line = NULL;
7909 continue;
7911 cmd = NULL;
7912 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7913 cmd = &got_histedit_cmds[i];
7914 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
7915 isspace((unsigned char)p[strlen(cmd->name)])) {
7916 p += strlen(cmd->name);
7917 break;
7919 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
7920 p++;
7921 break;
7924 if (i == nitems(got_histedit_cmds)) {
7925 err = histedit_syntax_error(lineno);
7926 break;
7928 while (isspace((unsigned char)p[0]))
7929 p++;
7930 if (cmd->code == GOT_HISTEDIT_MESG) {
7931 if (hle == NULL || hle->logmsg != NULL) {
7932 err = got_error(GOT_ERR_HISTEDIT_CMD);
7933 break;
7935 if (p[0] == '\0') {
7936 err = histedit_edit_logmsg(hle, repo);
7937 if (err)
7938 break;
7939 } else {
7940 hle->logmsg = strdup(p);
7941 if (hle->logmsg == NULL) {
7942 err = got_error_from_errno("strdup");
7943 break;
7946 free(line);
7947 line = NULL;
7948 continue;
7949 } else {
7950 end = p;
7951 while (end[0] && !isspace((unsigned char)end[0]))
7952 end++;
7953 *end = '\0';
7955 err = got_object_resolve_id_str(&commit_id, repo, p);
7956 if (err) {
7957 /* override error code */
7958 err = histedit_syntax_error(lineno);
7959 break;
7962 hle = malloc(sizeof(*hle));
7963 if (hle == NULL) {
7964 err = got_error_from_errno("malloc");
7965 break;
7967 hle->cmd = cmd;
7968 hle->commit_id = commit_id;
7969 hle->logmsg = NULL;
7970 commit_id = NULL;
7971 free(line);
7972 line = NULL;
7973 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
7976 free(line);
7977 free(commit_id);
7978 return err;
7981 static const struct got_error *
7982 histedit_check_script(struct got_histedit_list *histedit_cmds,
7983 struct got_object_id_queue *commits, struct got_repository *repo)
7985 const struct got_error *err = NULL;
7986 struct got_object_qid *qid;
7987 struct got_histedit_list_entry *hle;
7988 static char msg[92];
7989 char *id_str;
7991 if (TAILQ_EMPTY(histedit_cmds))
7992 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
7993 "histedit script contains no commands");
7994 if (SIMPLEQ_EMPTY(commits))
7995 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7997 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7998 struct got_histedit_list_entry *hle2;
7999 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
8000 if (hle == hle2)
8001 continue;
8002 if (got_object_id_cmp(hle->commit_id,
8003 hle2->commit_id) != 0)
8004 continue;
8005 err = got_object_id_str(&id_str, hle->commit_id);
8006 if (err)
8007 return err;
8008 snprintf(msg, sizeof(msg), "commit %s is listed "
8009 "more than once in histedit script", id_str);
8010 free(id_str);
8011 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8015 SIMPLEQ_FOREACH(qid, commits, entry) {
8016 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8017 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
8018 break;
8020 if (hle == NULL) {
8021 err = got_object_id_str(&id_str, qid->id);
8022 if (err)
8023 return err;
8024 snprintf(msg, sizeof(msg),
8025 "commit %s missing from histedit script", id_str);
8026 free(id_str);
8027 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8031 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
8032 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
8033 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
8034 "last commit in histedit script cannot be folded");
8036 return NULL;
8039 static const struct got_error *
8040 histedit_run_editor(struct got_histedit_list *histedit_cmds,
8041 const char *path, struct got_object_id_queue *commits,
8042 struct got_repository *repo)
8044 const struct got_error *err = NULL;
8045 char *editor;
8046 FILE *f = NULL;
8048 err = get_editor(&editor);
8049 if (err)
8050 return err;
8052 if (spawn_editor(editor, path) == -1) {
8053 err = got_error_from_errno("failed spawning editor");
8054 goto done;
8057 f = fopen(path, "r");
8058 if (f == NULL) {
8059 err = got_error_from_errno("fopen");
8060 goto done;
8062 err = histedit_parse_list(histedit_cmds, f, repo);
8063 if (err)
8064 goto done;
8066 err = histedit_check_script(histedit_cmds, commits, repo);
8067 done:
8068 if (f && fclose(f) != 0 && err == NULL)
8069 err = got_error_from_errno("fclose");
8070 free(editor);
8071 return err;
8074 static const struct got_error *
8075 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
8076 struct got_object_id_queue *, const char *, const char *,
8077 struct got_repository *);
8079 static const struct got_error *
8080 histedit_edit_script(struct got_histedit_list *histedit_cmds,
8081 struct got_object_id_queue *commits, const char *branch_name,
8082 int edit_logmsg_only, struct got_repository *repo)
8084 const struct got_error *err;
8085 FILE *f = NULL;
8086 char *path = NULL;
8088 err = got_opentemp_named(&path, &f, "got-histedit");
8089 if (err)
8090 return err;
8092 err = write_cmd_list(f, branch_name, commits);
8093 if (err)
8094 goto done;
8096 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
8097 if (err)
8098 goto done;
8100 if (edit_logmsg_only) {
8101 rewind(f);
8102 err = histedit_parse_list(histedit_cmds, f, repo);
8103 } else {
8104 if (fclose(f) != 0) {
8105 err = got_error_from_errno("fclose");
8106 goto done;
8108 f = NULL;
8109 err = histedit_run_editor(histedit_cmds, path, commits, repo);
8110 if (err) {
8111 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8112 err->code != GOT_ERR_HISTEDIT_CMD)
8113 goto done;
8114 err = histedit_edit_list_retry(histedit_cmds, err,
8115 commits, path, branch_name, repo);
8118 done:
8119 if (f && fclose(f) != 0 && err == NULL)
8120 err = got_error_from_errno("fclose");
8121 if (path && unlink(path) != 0 && err == NULL)
8122 err = got_error_from_errno2("unlink", path);
8123 free(path);
8124 return err;
8127 static const struct got_error *
8128 histedit_save_list(struct got_histedit_list *histedit_cmds,
8129 struct got_worktree *worktree, struct got_repository *repo)
8131 const struct got_error *err = NULL;
8132 char *path = NULL;
8133 FILE *f = NULL;
8134 struct got_histedit_list_entry *hle;
8135 struct got_commit_object *commit = NULL;
8137 err = got_worktree_get_histedit_script_path(&path, worktree);
8138 if (err)
8139 return err;
8141 f = fopen(path, "w");
8142 if (f == NULL) {
8143 err = got_error_from_errno2("fopen", path);
8144 goto done;
8146 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8147 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
8148 repo);
8149 if (err)
8150 break;
8152 if (hle->logmsg) {
8153 int n = fprintf(f, "%c %s\n",
8154 GOT_HISTEDIT_MESG, hle->logmsg);
8155 if (n < 0) {
8156 err = got_ferror(f, GOT_ERR_IO);
8157 break;
8161 done:
8162 if (f && fclose(f) != 0 && err == NULL)
8163 err = got_error_from_errno("fclose");
8164 free(path);
8165 if (commit)
8166 got_object_commit_close(commit);
8167 return err;
8170 void
8171 histedit_free_list(struct got_histedit_list *histedit_cmds)
8173 struct got_histedit_list_entry *hle;
8175 while ((hle = TAILQ_FIRST(histedit_cmds))) {
8176 TAILQ_REMOVE(histedit_cmds, hle, entry);
8177 free(hle);
8181 static const struct got_error *
8182 histedit_load_list(struct got_histedit_list *histedit_cmds,
8183 const char *path, struct got_repository *repo)
8185 const struct got_error *err = NULL;
8186 FILE *f = NULL;
8188 f = fopen(path, "r");
8189 if (f == NULL) {
8190 err = got_error_from_errno2("fopen", path);
8191 goto done;
8194 err = histedit_parse_list(histedit_cmds, f, repo);
8195 done:
8196 if (f && fclose(f) != 0 && err == NULL)
8197 err = got_error_from_errno("fclose");
8198 return err;
8201 static const struct got_error *
8202 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
8203 const struct got_error *edit_err, struct got_object_id_queue *commits,
8204 const char *path, const char *branch_name, struct got_repository *repo)
8206 const struct got_error *err = NULL, *prev_err = edit_err;
8207 int resp = ' ';
8209 while (resp != 'c' && resp != 'r' && resp != 'a') {
8210 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
8211 "or (a)bort: ", getprogname(), prev_err->msg);
8212 resp = getchar();
8213 if (resp == '\n')
8214 resp = getchar();
8215 if (resp == 'c') {
8216 histedit_free_list(histedit_cmds);
8217 err = histedit_run_editor(histedit_cmds, path, commits,
8218 repo);
8219 if (err) {
8220 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8221 err->code != GOT_ERR_HISTEDIT_CMD)
8222 break;
8223 prev_err = err;
8224 resp = ' ';
8225 continue;
8227 break;
8228 } else if (resp == 'r') {
8229 histedit_free_list(histedit_cmds);
8230 err = histedit_edit_script(histedit_cmds,
8231 commits, branch_name, 0, repo);
8232 if (err) {
8233 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8234 err->code != GOT_ERR_HISTEDIT_CMD)
8235 break;
8236 prev_err = err;
8237 resp = ' ';
8238 continue;
8240 break;
8241 } else if (resp == 'a') {
8242 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
8243 break;
8244 } else
8245 printf("invalid response '%c'\n", resp);
8248 return err;
8251 static const struct got_error *
8252 histedit_complete(struct got_worktree *worktree,
8253 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
8254 struct got_reference *branch, struct got_repository *repo)
8256 printf("Switching work tree to %s\n",
8257 got_ref_get_symref_target(branch));
8258 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
8259 branch, repo);
8262 static const struct got_error *
8263 show_histedit_progress(struct got_commit_object *commit,
8264 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
8266 const struct got_error *err;
8267 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8269 err = got_object_id_str(&old_id_str, hle->commit_id);
8270 if (err)
8271 goto done;
8273 if (new_id) {
8274 err = got_object_id_str(&new_id_str, new_id);
8275 if (err)
8276 goto done;
8279 old_id_str[12] = '\0';
8280 if (new_id_str)
8281 new_id_str[12] = '\0';
8283 if (hle->logmsg) {
8284 logmsg = strdup(hle->logmsg);
8285 if (logmsg == NULL) {
8286 err = got_error_from_errno("strdup");
8287 goto done;
8289 trim_logmsg(logmsg, 42);
8290 } else {
8291 err = get_short_logmsg(&logmsg, 42, commit);
8292 if (err)
8293 goto done;
8296 switch (hle->cmd->code) {
8297 case GOT_HISTEDIT_PICK:
8298 case GOT_HISTEDIT_EDIT:
8299 printf("%s -> %s: %s\n", old_id_str,
8300 new_id_str ? new_id_str : "no-op change", logmsg);
8301 break;
8302 case GOT_HISTEDIT_DROP:
8303 case GOT_HISTEDIT_FOLD:
8304 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
8305 logmsg);
8306 break;
8307 default:
8308 break;
8310 done:
8311 free(old_id_str);
8312 free(new_id_str);
8313 return err;
8316 static const struct got_error *
8317 histedit_commit(struct got_pathlist_head *merged_paths,
8318 struct got_worktree *worktree, struct got_fileindex *fileindex,
8319 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
8320 struct got_repository *repo)
8322 const struct got_error *err;
8323 struct got_commit_object *commit;
8324 struct got_object_id *new_commit_id;
8326 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
8327 && hle->logmsg == NULL) {
8328 err = histedit_edit_logmsg(hle, repo);
8329 if (err)
8330 return err;
8333 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8334 if (err)
8335 return err;
8337 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
8338 worktree, fileindex, tmp_branch, commit, hle->commit_id,
8339 hle->logmsg, repo);
8340 if (err) {
8341 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
8342 goto done;
8343 err = show_histedit_progress(commit, hle, NULL);
8344 } else {
8345 err = show_histedit_progress(commit, hle, new_commit_id);
8346 free(new_commit_id);
8348 done:
8349 got_object_commit_close(commit);
8350 return err;
8353 static const struct got_error *
8354 histedit_skip_commit(struct got_histedit_list_entry *hle,
8355 struct got_worktree *worktree, struct got_repository *repo)
8357 const struct got_error *error;
8358 struct got_commit_object *commit;
8360 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
8361 repo);
8362 if (error)
8363 return error;
8365 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
8366 if (error)
8367 return error;
8369 error = show_histedit_progress(commit, hle, NULL);
8370 got_object_commit_close(commit);
8371 return error;
8374 static const struct got_error *
8375 check_local_changes(void *arg, unsigned char status,
8376 unsigned char staged_status, const char *path,
8377 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8378 struct got_object_id *commit_id, int dirfd, const char *de_name)
8380 int *have_local_changes = arg;
8382 switch (status) {
8383 case GOT_STATUS_ADD:
8384 case GOT_STATUS_DELETE:
8385 case GOT_STATUS_MODIFY:
8386 case GOT_STATUS_CONFLICT:
8387 *have_local_changes = 1;
8388 return got_error(GOT_ERR_CANCELLED);
8389 default:
8390 break;
8393 switch (staged_status) {
8394 case GOT_STATUS_ADD:
8395 case GOT_STATUS_DELETE:
8396 case GOT_STATUS_MODIFY:
8397 *have_local_changes = 1;
8398 return got_error(GOT_ERR_CANCELLED);
8399 default:
8400 break;
8403 return NULL;
8406 static const struct got_error *
8407 cmd_histedit(int argc, char *argv[])
8409 const struct got_error *error = NULL;
8410 struct got_worktree *worktree = NULL;
8411 struct got_fileindex *fileindex = NULL;
8412 struct got_repository *repo = NULL;
8413 char *cwd = NULL;
8414 struct got_reference *branch = NULL;
8415 struct got_reference *tmp_branch = NULL;
8416 struct got_object_id *resume_commit_id = NULL;
8417 struct got_object_id *base_commit_id = NULL;
8418 struct got_object_id *head_commit_id = NULL;
8419 struct got_commit_object *commit = NULL;
8420 int ch, rebase_in_progress = 0;
8421 struct got_update_progress_arg upa;
8422 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8423 int edit_logmsg_only = 0;
8424 const char *edit_script_path = NULL;
8425 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8426 struct got_object_id_queue commits;
8427 struct got_pathlist_head merged_paths;
8428 const struct got_object_id_queue *parent_ids;
8429 struct got_object_qid *pid;
8430 struct got_histedit_list histedit_cmds;
8431 struct got_histedit_list_entry *hle;
8433 SIMPLEQ_INIT(&commits);
8434 TAILQ_INIT(&histedit_cmds);
8435 TAILQ_INIT(&merged_paths);
8436 memset(&upa, 0, sizeof(upa));
8438 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
8439 switch (ch) {
8440 case 'a':
8441 abort_edit = 1;
8442 break;
8443 case 'c':
8444 continue_edit = 1;
8445 break;
8446 case 'F':
8447 edit_script_path = optarg;
8448 break;
8449 case 'm':
8450 edit_logmsg_only = 1;
8451 break;
8452 default:
8453 usage_histedit();
8454 /* NOTREACHED */
8458 argc -= optind;
8459 argv += optind;
8461 #ifndef PROFILE
8462 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8463 "unveil", NULL) == -1)
8464 err(1, "pledge");
8465 #endif
8466 if (abort_edit && continue_edit)
8467 errx(1, "histedit's -a and -c options are mutually exclusive");
8468 if (edit_script_path && edit_logmsg_only)
8469 errx(1, "histedit's -F and -m options are mutually exclusive");
8470 if (abort_edit && edit_logmsg_only)
8471 errx(1, "histedit's -a and -m options are mutually exclusive");
8472 if (continue_edit && edit_logmsg_only)
8473 errx(1, "histedit's -c and -m options are mutually exclusive");
8474 if (argc != 0)
8475 usage_histedit();
8478 * This command cannot apply unveil(2) in all cases because the
8479 * user may choose to run an editor to edit the histedit script
8480 * and to edit individual commit log messages.
8481 * unveil(2) traverses exec(2); if an editor is used we have to
8482 * apply unveil after edit script and log messages have been written.
8483 * XXX TODO: Make use of unveil(2) where possible.
8486 cwd = getcwd(NULL, 0);
8487 if (cwd == NULL) {
8488 error = got_error_from_errno("getcwd");
8489 goto done;
8491 error = got_worktree_open(&worktree, cwd);
8492 if (error) {
8493 if (error->code == GOT_ERR_NOT_WORKTREE)
8494 error = wrap_not_worktree_error(error, "histedit", cwd);
8495 goto done;
8498 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8499 NULL);
8500 if (error != NULL)
8501 goto done;
8503 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8504 if (error)
8505 goto done;
8506 if (rebase_in_progress) {
8507 error = got_error(GOT_ERR_REBASING);
8508 goto done;
8511 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8512 if (error)
8513 goto done;
8515 if (edit_in_progress && edit_logmsg_only) {
8516 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8517 "histedit operation is in progress in this "
8518 "work tree and must be continued or aborted "
8519 "before the -m option can be used");
8520 goto done;
8523 if (edit_in_progress && abort_edit) {
8524 error = got_worktree_histedit_continue(&resume_commit_id,
8525 &tmp_branch, &branch, &base_commit_id, &fileindex,
8526 worktree, repo);
8527 if (error)
8528 goto done;
8529 printf("Switching work tree to %s\n",
8530 got_ref_get_symref_target(branch));
8531 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8532 branch, base_commit_id, update_progress, &upa);
8533 if (error)
8534 goto done;
8535 printf("Histedit of %s aborted\n",
8536 got_ref_get_symref_target(branch));
8537 print_update_progress_stats(&upa);
8538 goto done; /* nothing else to do */
8539 } else if (abort_edit) {
8540 error = got_error(GOT_ERR_NOT_HISTEDIT);
8541 goto done;
8544 if (continue_edit) {
8545 char *path;
8547 if (!edit_in_progress) {
8548 error = got_error(GOT_ERR_NOT_HISTEDIT);
8549 goto done;
8552 error = got_worktree_get_histedit_script_path(&path, worktree);
8553 if (error)
8554 goto done;
8556 error = histedit_load_list(&histedit_cmds, path, repo);
8557 free(path);
8558 if (error)
8559 goto done;
8561 error = got_worktree_histedit_continue(&resume_commit_id,
8562 &tmp_branch, &branch, &base_commit_id, &fileindex,
8563 worktree, repo);
8564 if (error)
8565 goto done;
8567 error = got_ref_resolve(&head_commit_id, repo, branch);
8568 if (error)
8569 goto done;
8571 error = got_object_open_as_commit(&commit, repo,
8572 head_commit_id);
8573 if (error)
8574 goto done;
8575 parent_ids = got_object_commit_get_parent_ids(commit);
8576 pid = SIMPLEQ_FIRST(parent_ids);
8577 if (pid == NULL) {
8578 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8579 goto done;
8581 error = collect_commits(&commits, head_commit_id, pid->id,
8582 base_commit_id, got_worktree_get_path_prefix(worktree),
8583 GOT_ERR_HISTEDIT_PATH, repo);
8584 got_object_commit_close(commit);
8585 commit = NULL;
8586 if (error)
8587 goto done;
8588 } else {
8589 if (edit_in_progress) {
8590 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8591 goto done;
8594 error = got_ref_open(&branch, repo,
8595 got_worktree_get_head_ref_name(worktree), 0);
8596 if (error != NULL)
8597 goto done;
8599 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8600 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8601 "will not edit commit history of a branch outside "
8602 "the \"refs/heads/\" reference namespace");
8603 goto done;
8606 error = got_ref_resolve(&head_commit_id, repo, branch);
8607 got_ref_close(branch);
8608 branch = NULL;
8609 if (error)
8610 goto done;
8612 error = got_object_open_as_commit(&commit, repo,
8613 head_commit_id);
8614 if (error)
8615 goto done;
8616 parent_ids = got_object_commit_get_parent_ids(commit);
8617 pid = SIMPLEQ_FIRST(parent_ids);
8618 if (pid == NULL) {
8619 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8620 goto done;
8622 error = collect_commits(&commits, head_commit_id, pid->id,
8623 got_worktree_get_base_commit_id(worktree),
8624 got_worktree_get_path_prefix(worktree),
8625 GOT_ERR_HISTEDIT_PATH, repo);
8626 got_object_commit_close(commit);
8627 commit = NULL;
8628 if (error)
8629 goto done;
8631 if (SIMPLEQ_EMPTY(&commits)) {
8632 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8633 goto done;
8636 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8637 &base_commit_id, &fileindex, worktree, repo);
8638 if (error)
8639 goto done;
8641 if (edit_script_path) {
8642 error = histedit_load_list(&histedit_cmds,
8643 edit_script_path, 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;
8651 } else {
8652 const char *branch_name;
8653 branch_name = got_ref_get_symref_target(branch);
8654 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8655 branch_name += 11;
8656 error = histedit_edit_script(&histedit_cmds, &commits,
8657 branch_name, edit_logmsg_only, repo);
8658 if (error) {
8659 got_worktree_histedit_abort(worktree, fileindex,
8660 repo, branch, base_commit_id,
8661 update_progress, &upa);
8662 print_update_progress_stats(&upa);
8663 goto done;
8668 error = histedit_save_list(&histedit_cmds, worktree,
8669 repo);
8670 if (error) {
8671 got_worktree_histedit_abort(worktree, fileindex,
8672 repo, branch, base_commit_id,
8673 update_progress, &upa);
8674 print_update_progress_stats(&upa);
8675 goto done;
8680 error = histedit_check_script(&histedit_cmds, &commits, repo);
8681 if (error)
8682 goto done;
8684 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8685 if (resume_commit_id) {
8686 if (got_object_id_cmp(hle->commit_id,
8687 resume_commit_id) != 0)
8688 continue;
8690 resume_commit_id = NULL;
8691 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8692 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8693 error = histedit_skip_commit(hle, worktree,
8694 repo);
8695 if (error)
8696 goto done;
8697 } else {
8698 struct got_pathlist_head paths;
8699 int have_changes = 0;
8701 TAILQ_INIT(&paths);
8702 error = got_pathlist_append(&paths, "", NULL);
8703 if (error)
8704 goto done;
8705 error = got_worktree_status(worktree, &paths,
8706 repo, check_local_changes, &have_changes,
8707 check_cancelled, NULL);
8708 got_pathlist_free(&paths);
8709 if (error) {
8710 if (error->code != GOT_ERR_CANCELLED)
8711 goto done;
8712 if (sigint_received || sigpipe_received)
8713 goto done;
8715 if (have_changes) {
8716 error = histedit_commit(NULL, worktree,
8717 fileindex, tmp_branch, hle, repo);
8718 if (error)
8719 goto done;
8720 } else {
8721 error = got_object_open_as_commit(
8722 &commit, repo, hle->commit_id);
8723 if (error)
8724 goto done;
8725 error = show_histedit_progress(commit,
8726 hle, NULL);
8727 got_object_commit_close(commit);
8728 commit = NULL;
8729 if (error)
8730 goto done;
8733 continue;
8736 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8737 error = histedit_skip_commit(hle, worktree, repo);
8738 if (error)
8739 goto done;
8740 continue;
8743 error = got_object_open_as_commit(&commit, repo,
8744 hle->commit_id);
8745 if (error)
8746 goto done;
8747 parent_ids = got_object_commit_get_parent_ids(commit);
8748 pid = SIMPLEQ_FIRST(parent_ids);
8750 error = got_worktree_histedit_merge_files(&merged_paths,
8751 worktree, fileindex, pid->id, hle->commit_id, repo,
8752 update_progress, &upa, check_cancelled, NULL);
8753 if (error)
8754 goto done;
8755 got_object_commit_close(commit);
8756 commit = NULL;
8758 print_update_progress_stats(&upa);
8759 if (upa.conflicts > 0)
8760 rebase_status = GOT_STATUS_CONFLICT;
8762 if (rebase_status == GOT_STATUS_CONFLICT) {
8763 error = show_rebase_merge_conflict(hle->commit_id,
8764 repo);
8765 if (error)
8766 goto done;
8767 got_worktree_rebase_pathlist_free(&merged_paths);
8768 break;
8771 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8772 char *id_str;
8773 error = got_object_id_str(&id_str, hle->commit_id);
8774 if (error)
8775 goto done;
8776 printf("Stopping histedit for amending commit %s\n",
8777 id_str);
8778 free(id_str);
8779 got_worktree_rebase_pathlist_free(&merged_paths);
8780 error = got_worktree_histedit_postpone(worktree,
8781 fileindex);
8782 goto done;
8785 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8786 error = histedit_skip_commit(hle, worktree, repo);
8787 if (error)
8788 goto done;
8789 continue;
8792 error = histedit_commit(&merged_paths, worktree, fileindex,
8793 tmp_branch, hle, repo);
8794 got_worktree_rebase_pathlist_free(&merged_paths);
8795 if (error)
8796 goto done;
8799 if (rebase_status == GOT_STATUS_CONFLICT) {
8800 error = got_worktree_histedit_postpone(worktree, fileindex);
8801 if (error)
8802 goto done;
8803 error = got_error_msg(GOT_ERR_CONFLICTS,
8804 "conflicts must be resolved before histedit can continue");
8805 } else
8806 error = histedit_complete(worktree, fileindex, tmp_branch,
8807 branch, repo);
8808 done:
8809 got_object_id_queue_free(&commits);
8810 histedit_free_list(&histedit_cmds);
8811 free(head_commit_id);
8812 free(base_commit_id);
8813 free(resume_commit_id);
8814 if (commit)
8815 got_object_commit_close(commit);
8816 if (branch)
8817 got_ref_close(branch);
8818 if (tmp_branch)
8819 got_ref_close(tmp_branch);
8820 if (worktree)
8821 got_worktree_close(worktree);
8822 if (repo)
8823 got_repo_close(repo);
8824 return error;
8827 __dead static void
8828 usage_integrate(void)
8830 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
8831 exit(1);
8834 static const struct got_error *
8835 cmd_integrate(int argc, char *argv[])
8837 const struct got_error *error = NULL;
8838 struct got_repository *repo = NULL;
8839 struct got_worktree *worktree = NULL;
8840 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
8841 const char *branch_arg = NULL;
8842 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
8843 struct got_fileindex *fileindex = NULL;
8844 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
8845 int ch;
8846 struct got_update_progress_arg upa;
8848 while ((ch = getopt(argc, argv, "")) != -1) {
8849 switch (ch) {
8850 default:
8851 usage_integrate();
8852 /* NOTREACHED */
8856 argc -= optind;
8857 argv += optind;
8859 if (argc != 1)
8860 usage_integrate();
8861 branch_arg = argv[0];
8863 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8864 "unveil", NULL) == -1)
8865 err(1, "pledge");
8867 cwd = getcwd(NULL, 0);
8868 if (cwd == NULL) {
8869 error = got_error_from_errno("getcwd");
8870 goto done;
8873 error = got_worktree_open(&worktree, cwd);
8874 if (error) {
8875 if (error->code == GOT_ERR_NOT_WORKTREE)
8876 error = wrap_not_worktree_error(error, "integrate",
8877 cwd);
8878 goto done;
8881 error = check_rebase_or_histedit_in_progress(worktree);
8882 if (error)
8883 goto done;
8885 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8886 NULL);
8887 if (error != NULL)
8888 goto done;
8890 error = apply_unveil(got_repo_get_path(repo), 0,
8891 got_worktree_get_root_path(worktree));
8892 if (error)
8893 goto done;
8895 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
8896 error = got_error_from_errno("asprintf");
8897 goto done;
8900 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
8901 &base_branch_ref, worktree, refname, repo);
8902 if (error)
8903 goto done;
8905 refname = strdup(got_ref_get_name(branch_ref));
8906 if (refname == NULL) {
8907 error = got_error_from_errno("strdup");
8908 got_worktree_integrate_abort(worktree, fileindex, repo,
8909 branch_ref, base_branch_ref);
8910 goto done;
8912 base_refname = strdup(got_ref_get_name(base_branch_ref));
8913 if (base_refname == NULL) {
8914 error = got_error_from_errno("strdup");
8915 got_worktree_integrate_abort(worktree, fileindex, repo,
8916 branch_ref, base_branch_ref);
8917 goto done;
8920 error = got_ref_resolve(&commit_id, repo, branch_ref);
8921 if (error)
8922 goto done;
8924 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
8925 if (error)
8926 goto done;
8928 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
8929 error = got_error_msg(GOT_ERR_SAME_BRANCH,
8930 "specified branch has already been integrated");
8931 got_worktree_integrate_abort(worktree, fileindex, repo,
8932 branch_ref, base_branch_ref);
8933 goto done;
8936 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
8937 if (error) {
8938 if (error->code == GOT_ERR_ANCESTRY)
8939 error = got_error(GOT_ERR_REBASE_REQUIRED);
8940 got_worktree_integrate_abort(worktree, fileindex, repo,
8941 branch_ref, base_branch_ref);
8942 goto done;
8945 memset(&upa, 0, sizeof(upa));
8946 error = got_worktree_integrate_continue(worktree, fileindex, repo,
8947 branch_ref, base_branch_ref, update_progress, &upa,
8948 check_cancelled, NULL);
8949 if (error)
8950 goto done;
8952 printf("Integrated %s into %s\n", refname, base_refname);
8953 print_update_progress_stats(&upa);
8954 done:
8955 if (repo)
8956 got_repo_close(repo);
8957 if (worktree)
8958 got_worktree_close(worktree);
8959 free(cwd);
8960 free(base_commit_id);
8961 free(commit_id);
8962 free(refname);
8963 free(base_refname);
8964 return error;
8967 __dead static void
8968 usage_stage(void)
8970 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
8971 "[-S] [file-path ...]\n",
8972 getprogname());
8973 exit(1);
8976 static const struct got_error *
8977 print_stage(void *arg, unsigned char status, unsigned char staged_status,
8978 const char *path, struct got_object_id *blob_id,
8979 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
8980 int dirfd, const char *de_name)
8982 const struct got_error *err = NULL;
8983 char *id_str = NULL;
8985 if (staged_status != GOT_STATUS_ADD &&
8986 staged_status != GOT_STATUS_MODIFY &&
8987 staged_status != GOT_STATUS_DELETE)
8988 return NULL;
8990 if (staged_status == GOT_STATUS_ADD ||
8991 staged_status == GOT_STATUS_MODIFY)
8992 err = got_object_id_str(&id_str, staged_blob_id);
8993 else
8994 err = got_object_id_str(&id_str, blob_id);
8995 if (err)
8996 return err;
8998 printf("%s %c %s\n", id_str, staged_status, path);
8999 free(id_str);
9000 return NULL;
9003 static const struct got_error *
9004 cmd_stage(int argc, char *argv[])
9006 const struct got_error *error = NULL;
9007 struct got_repository *repo = NULL;
9008 struct got_worktree *worktree = NULL;
9009 char *cwd = NULL;
9010 struct got_pathlist_head paths;
9011 struct got_pathlist_entry *pe;
9012 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
9013 FILE *patch_script_file = NULL;
9014 const char *patch_script_path = NULL;
9015 struct choose_patch_arg cpa;
9017 TAILQ_INIT(&paths);
9019 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
9020 switch (ch) {
9021 case 'l':
9022 list_stage = 1;
9023 break;
9024 case 'p':
9025 pflag = 1;
9026 break;
9027 case 'F':
9028 patch_script_path = optarg;
9029 break;
9030 case 'S':
9031 allow_bad_symlinks = 1;
9032 break;
9033 default:
9034 usage_stage();
9035 /* NOTREACHED */
9039 argc -= optind;
9040 argv += optind;
9042 #ifndef PROFILE
9043 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9044 "unveil", NULL) == -1)
9045 err(1, "pledge");
9046 #endif
9047 if (list_stage && (pflag || patch_script_path))
9048 errx(1, "-l option cannot be used with other options");
9049 if (patch_script_path && !pflag)
9050 errx(1, "-F option can only be used together with -p option");
9052 cwd = getcwd(NULL, 0);
9053 if (cwd == NULL) {
9054 error = got_error_from_errno("getcwd");
9055 goto done;
9058 error = got_worktree_open(&worktree, cwd);
9059 if (error) {
9060 if (error->code == GOT_ERR_NOT_WORKTREE)
9061 error = wrap_not_worktree_error(error, "stage", cwd);
9062 goto done;
9065 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9066 NULL);
9067 if (error != NULL)
9068 goto done;
9070 if (patch_script_path) {
9071 patch_script_file = fopen(patch_script_path, "r");
9072 if (patch_script_file == NULL) {
9073 error = got_error_from_errno2("fopen",
9074 patch_script_path);
9075 goto done;
9078 error = apply_unveil(got_repo_get_path(repo), 0,
9079 got_worktree_get_root_path(worktree));
9080 if (error)
9081 goto done;
9083 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9084 if (error)
9085 goto done;
9087 if (list_stage)
9088 error = got_worktree_status(worktree, &paths, repo,
9089 print_stage, NULL, check_cancelled, NULL);
9090 else {
9091 cpa.patch_script_file = patch_script_file;
9092 cpa.action = "stage";
9093 error = got_worktree_stage(worktree, &paths,
9094 pflag ? NULL : print_status, NULL,
9095 pflag ? choose_patch : NULL, &cpa,
9096 allow_bad_symlinks, repo);
9098 done:
9099 if (patch_script_file && fclose(patch_script_file) == EOF &&
9100 error == NULL)
9101 error = got_error_from_errno2("fclose", patch_script_path);
9102 if (repo)
9103 got_repo_close(repo);
9104 if (worktree)
9105 got_worktree_close(worktree);
9106 TAILQ_FOREACH(pe, &paths, entry)
9107 free((char *)pe->path);
9108 got_pathlist_free(&paths);
9109 free(cwd);
9110 return error;
9113 __dead static void
9114 usage_unstage(void)
9116 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
9117 "[file-path ...]\n",
9118 getprogname());
9119 exit(1);
9123 static const struct got_error *
9124 cmd_unstage(int argc, char *argv[])
9126 const struct got_error *error = NULL;
9127 struct got_repository *repo = NULL;
9128 struct got_worktree *worktree = NULL;
9129 char *cwd = NULL;
9130 struct got_pathlist_head paths;
9131 struct got_pathlist_entry *pe;
9132 int ch, pflag = 0;
9133 struct got_update_progress_arg upa;
9134 FILE *patch_script_file = NULL;
9135 const char *patch_script_path = NULL;
9136 struct choose_patch_arg cpa;
9138 TAILQ_INIT(&paths);
9140 while ((ch = getopt(argc, argv, "pF:")) != -1) {
9141 switch (ch) {
9142 case 'p':
9143 pflag = 1;
9144 break;
9145 case 'F':
9146 patch_script_path = optarg;
9147 break;
9148 default:
9149 usage_unstage();
9150 /* NOTREACHED */
9154 argc -= optind;
9155 argv += optind;
9157 #ifndef PROFILE
9158 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9159 "unveil", NULL) == -1)
9160 err(1, "pledge");
9161 #endif
9162 if (patch_script_path && !pflag)
9163 errx(1, "-F option can only be used together with -p option");
9165 cwd = getcwd(NULL, 0);
9166 if (cwd == NULL) {
9167 error = got_error_from_errno("getcwd");
9168 goto done;
9171 error = got_worktree_open(&worktree, cwd);
9172 if (error) {
9173 if (error->code == GOT_ERR_NOT_WORKTREE)
9174 error = wrap_not_worktree_error(error, "unstage", cwd);
9175 goto done;
9178 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9179 NULL);
9180 if (error != NULL)
9181 goto done;
9183 if (patch_script_path) {
9184 patch_script_file = fopen(patch_script_path, "r");
9185 if (patch_script_file == NULL) {
9186 error = got_error_from_errno2("fopen",
9187 patch_script_path);
9188 goto done;
9192 error = apply_unveil(got_repo_get_path(repo), 0,
9193 got_worktree_get_root_path(worktree));
9194 if (error)
9195 goto done;
9197 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9198 if (error)
9199 goto done;
9201 cpa.patch_script_file = patch_script_file;
9202 cpa.action = "unstage";
9203 memset(&upa, 0, sizeof(upa));
9204 error = got_worktree_unstage(worktree, &paths, update_progress,
9205 &upa, pflag ? choose_patch : NULL, &cpa, repo);
9206 if (!error)
9207 print_update_progress_stats(&upa);
9208 done:
9209 if (patch_script_file && fclose(patch_script_file) == EOF &&
9210 error == NULL)
9211 error = got_error_from_errno2("fclose", patch_script_path);
9212 if (repo)
9213 got_repo_close(repo);
9214 if (worktree)
9215 got_worktree_close(worktree);
9216 TAILQ_FOREACH(pe, &paths, entry)
9217 free((char *)pe->path);
9218 got_pathlist_free(&paths);
9219 free(cwd);
9220 return error;
9223 __dead static void
9224 usage_cat(void)
9226 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
9227 "arg1 [arg2 ...]\n", getprogname());
9228 exit(1);
9231 static const struct got_error *
9232 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9234 const struct got_error *err;
9235 struct got_blob_object *blob;
9237 err = got_object_open_as_blob(&blob, repo, id, 8192);
9238 if (err)
9239 return err;
9241 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
9242 got_object_blob_close(blob);
9243 return err;
9246 static const struct got_error *
9247 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9249 const struct got_error *err;
9250 struct got_tree_object *tree;
9251 int nentries, i;
9253 err = got_object_open_as_tree(&tree, repo, id);
9254 if (err)
9255 return err;
9257 nentries = got_object_tree_get_nentries(tree);
9258 for (i = 0; i < nentries; i++) {
9259 struct got_tree_entry *te;
9260 char *id_str;
9261 if (sigint_received || sigpipe_received)
9262 break;
9263 te = got_object_tree_get_entry(tree, i);
9264 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
9265 if (err)
9266 break;
9267 fprintf(outfile, "%s %.7o %s\n", id_str,
9268 got_tree_entry_get_mode(te),
9269 got_tree_entry_get_name(te));
9270 free(id_str);
9273 got_object_tree_close(tree);
9274 return err;
9277 static const struct got_error *
9278 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9280 const struct got_error *err;
9281 struct got_commit_object *commit;
9282 const struct got_object_id_queue *parent_ids;
9283 struct got_object_qid *pid;
9284 char *id_str = NULL;
9285 const char *logmsg = NULL;
9287 err = got_object_open_as_commit(&commit, repo, id);
9288 if (err)
9289 return err;
9291 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
9292 if (err)
9293 goto done;
9295 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
9296 parent_ids = got_object_commit_get_parent_ids(commit);
9297 fprintf(outfile, "numparents %d\n",
9298 got_object_commit_get_nparents(commit));
9299 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
9300 char *pid_str;
9301 err = got_object_id_str(&pid_str, pid->id);
9302 if (err)
9303 goto done;
9304 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
9305 free(pid_str);
9307 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
9308 got_object_commit_get_author(commit),
9309 got_object_commit_get_author_time(commit));
9311 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
9312 got_object_commit_get_author(commit),
9313 got_object_commit_get_committer_time(commit));
9315 logmsg = got_object_commit_get_logmsg_raw(commit);
9316 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
9317 fprintf(outfile, "%s", logmsg);
9318 done:
9319 free(id_str);
9320 got_object_commit_close(commit);
9321 return err;
9324 static const struct got_error *
9325 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9327 const struct got_error *err;
9328 struct got_tag_object *tag;
9329 char *id_str = NULL;
9330 const char *tagmsg = NULL;
9332 err = got_object_open_as_tag(&tag, repo, id);
9333 if (err)
9334 return err;
9336 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
9337 if (err)
9338 goto done;
9340 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
9342 switch (got_object_tag_get_object_type(tag)) {
9343 case GOT_OBJ_TYPE_BLOB:
9344 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9345 GOT_OBJ_LABEL_BLOB);
9346 break;
9347 case GOT_OBJ_TYPE_TREE:
9348 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9349 GOT_OBJ_LABEL_TREE);
9350 break;
9351 case GOT_OBJ_TYPE_COMMIT:
9352 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9353 GOT_OBJ_LABEL_COMMIT);
9354 break;
9355 case GOT_OBJ_TYPE_TAG:
9356 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9357 GOT_OBJ_LABEL_TAG);
9358 break;
9359 default:
9360 break;
9363 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
9364 got_object_tag_get_name(tag));
9366 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
9367 got_object_tag_get_tagger(tag),
9368 got_object_tag_get_tagger_time(tag));
9370 tagmsg = got_object_tag_get_message(tag);
9371 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
9372 fprintf(outfile, "%s", tagmsg);
9373 done:
9374 free(id_str);
9375 got_object_tag_close(tag);
9376 return err;
9379 static const struct got_error *
9380 cmd_cat(int argc, char *argv[])
9382 const struct got_error *error;
9383 struct got_repository *repo = NULL;
9384 struct got_worktree *worktree = NULL;
9385 char *cwd = NULL, *repo_path = NULL, *label = NULL;
9386 const char *commit_id_str = NULL;
9387 struct got_object_id *id = NULL, *commit_id = NULL;
9388 int ch, obj_type, i, force_path = 0;
9390 #ifndef PROFILE
9391 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9392 NULL) == -1)
9393 err(1, "pledge");
9394 #endif
9396 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
9397 switch (ch) {
9398 case 'c':
9399 commit_id_str = optarg;
9400 break;
9401 case 'r':
9402 repo_path = realpath(optarg, NULL);
9403 if (repo_path == NULL)
9404 return got_error_from_errno2("realpath",
9405 optarg);
9406 got_path_strip_trailing_slashes(repo_path);
9407 break;
9408 case 'P':
9409 force_path = 1;
9410 break;
9411 default:
9412 usage_cat();
9413 /* NOTREACHED */
9417 argc -= optind;
9418 argv += optind;
9420 cwd = getcwd(NULL, 0);
9421 if (cwd == NULL) {
9422 error = got_error_from_errno("getcwd");
9423 goto done;
9425 error = got_worktree_open(&worktree, cwd);
9426 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9427 goto done;
9428 if (worktree) {
9429 if (repo_path == NULL) {
9430 repo_path = strdup(
9431 got_worktree_get_repo_path(worktree));
9432 if (repo_path == NULL) {
9433 error = got_error_from_errno("strdup");
9434 goto done;
9439 if (repo_path == NULL) {
9440 repo_path = getcwd(NULL, 0);
9441 if (repo_path == NULL)
9442 return got_error_from_errno("getcwd");
9445 error = got_repo_open(&repo, repo_path, NULL);
9446 free(repo_path);
9447 if (error != NULL)
9448 goto done;
9450 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9451 if (error)
9452 goto done;
9454 if (commit_id_str == NULL)
9455 commit_id_str = GOT_REF_HEAD;
9456 error = got_repo_match_object_id(&commit_id, NULL,
9457 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
9458 if (error)
9459 goto done;
9461 for (i = 0; i < argc; i++) {
9462 if (force_path) {
9463 error = got_object_id_by_path(&id, repo, commit_id,
9464 argv[i]);
9465 if (error)
9466 break;
9467 } else {
9468 error = got_repo_match_object_id(&id, &label, argv[i],
9469 GOT_OBJ_TYPE_ANY, 0, repo);
9470 if (error) {
9471 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9472 error->code != GOT_ERR_NOT_REF)
9473 break;
9474 error = got_object_id_by_path(&id, repo,
9475 commit_id, argv[i]);
9476 if (error)
9477 break;
9481 error = got_object_get_type(&obj_type, repo, id);
9482 if (error)
9483 break;
9485 switch (obj_type) {
9486 case GOT_OBJ_TYPE_BLOB:
9487 error = cat_blob(id, repo, stdout);
9488 break;
9489 case GOT_OBJ_TYPE_TREE:
9490 error = cat_tree(id, repo, stdout);
9491 break;
9492 case GOT_OBJ_TYPE_COMMIT:
9493 error = cat_commit(id, repo, stdout);
9494 break;
9495 case GOT_OBJ_TYPE_TAG:
9496 error = cat_tag(id, repo, stdout);
9497 break;
9498 default:
9499 error = got_error(GOT_ERR_OBJ_TYPE);
9500 break;
9502 if (error)
9503 break;
9504 free(label);
9505 label = NULL;
9506 free(id);
9507 id = NULL;
9509 done:
9510 free(label);
9511 free(id);
9512 free(commit_id);
9513 if (worktree)
9514 got_worktree_close(worktree);
9515 if (repo) {
9516 const struct got_error *repo_error;
9517 repo_error = got_repo_close(repo);
9518 if (error == NULL)
9519 error = repo_error;
9521 return error;
9524 __dead static void
9525 usage_info(void)
9527 fprintf(stderr, "usage: %s info [path ...]\n",
9528 getprogname());
9529 exit(1);
9532 static const struct got_error *
9533 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
9534 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9535 struct got_object_id *commit_id)
9537 const struct got_error *err = NULL;
9538 char *id_str = NULL;
9539 char datebuf[128];
9540 struct tm mytm, *tm;
9541 struct got_pathlist_head *paths = arg;
9542 struct got_pathlist_entry *pe;
9545 * Clear error indication from any of the path arguments which
9546 * would cause this file index entry to be displayed.
9548 TAILQ_FOREACH(pe, paths, entry) {
9549 if (got_path_cmp(path, pe->path, strlen(path),
9550 pe->path_len) == 0 ||
9551 got_path_is_child(path, pe->path, pe->path_len))
9552 pe->data = NULL; /* no error */
9555 printf(GOT_COMMIT_SEP_STR);
9556 if (S_ISLNK(mode))
9557 printf("symlink: %s\n", path);
9558 else if (S_ISREG(mode)) {
9559 printf("file: %s\n", path);
9560 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
9561 } else if (S_ISDIR(mode))
9562 printf("directory: %s\n", path);
9563 else
9564 printf("something: %s\n", path);
9566 tm = localtime_r(&mtime, &mytm);
9567 if (tm == NULL)
9568 return NULL;
9569 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) >= sizeof(datebuf))
9570 return got_error(GOT_ERR_NO_SPACE);
9571 printf("timestamp: %s\n", datebuf);
9573 if (blob_id) {
9574 err = got_object_id_str(&id_str, blob_id);
9575 if (err)
9576 return err;
9577 printf("based on blob: %s\n", id_str);
9578 free(id_str);
9581 if (staged_blob_id) {
9582 err = got_object_id_str(&id_str, staged_blob_id);
9583 if (err)
9584 return err;
9585 printf("based on staged blob: %s\n", id_str);
9586 free(id_str);
9589 if (commit_id) {
9590 err = got_object_id_str(&id_str, commit_id);
9591 if (err)
9592 return err;
9593 printf("based on commit: %s\n", id_str);
9594 free(id_str);
9597 return NULL;
9600 static const struct got_error *
9601 cmd_info(int argc, char *argv[])
9603 const struct got_error *error = NULL;
9604 struct got_worktree *worktree = NULL;
9605 char *cwd = NULL, *id_str = NULL;
9606 struct got_pathlist_head paths;
9607 struct got_pathlist_entry *pe;
9608 char *uuidstr = NULL;
9609 int ch, show_files = 0;
9611 TAILQ_INIT(&paths);
9613 while ((ch = getopt(argc, argv, "")) != -1) {
9614 switch (ch) {
9615 default:
9616 usage_info();
9617 /* NOTREACHED */
9621 argc -= optind;
9622 argv += optind;
9624 #ifndef PROFILE
9625 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
9626 NULL) == -1)
9627 err(1, "pledge");
9628 #endif
9629 cwd = getcwd(NULL, 0);
9630 if (cwd == NULL) {
9631 error = got_error_from_errno("getcwd");
9632 goto done;
9635 error = got_worktree_open(&worktree, cwd);
9636 if (error) {
9637 if (error->code == GOT_ERR_NOT_WORKTREE)
9638 error = wrap_not_worktree_error(error, "status", cwd);
9639 goto done;
9642 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9643 if (error)
9644 goto done;
9646 if (argc >= 1) {
9647 error = get_worktree_paths_from_argv(&paths, argc, argv,
9648 worktree);
9649 if (error)
9650 goto done;
9651 show_files = 1;
9654 error = got_object_id_str(&id_str,
9655 got_worktree_get_base_commit_id(worktree));
9656 if (error)
9657 goto done;
9659 error = got_worktree_get_uuid(&uuidstr, worktree);
9660 if (error)
9661 goto done;
9663 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9664 printf("work tree base commit: %s\n", id_str);
9665 printf("work tree path prefix: %s\n",
9666 got_worktree_get_path_prefix(worktree));
9667 printf("work tree branch reference: %s\n",
9668 got_worktree_get_head_ref_name(worktree));
9669 printf("work tree UUID: %s\n", uuidstr);
9670 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
9672 if (show_files) {
9673 struct got_pathlist_entry *pe;
9674 TAILQ_FOREACH(pe, &paths, entry) {
9675 if (pe->path_len == 0)
9676 continue;
9678 * Assume this path will fail. This will be corrected
9679 * in print_path_info() in case the path does suceeed.
9681 pe->data = (void *)got_error_path(pe->path,
9682 GOT_ERR_BAD_PATH);
9684 error = got_worktree_path_info(worktree, &paths,
9685 print_path_info, &paths, check_cancelled, NULL);
9686 if (error)
9687 goto done;
9688 TAILQ_FOREACH(pe, &paths, entry) {
9689 if (pe->data != NULL) {
9690 error = pe->data; /* bad path */
9691 break;
9695 done:
9696 TAILQ_FOREACH(pe, &paths, entry)
9697 free((char *)pe->path);
9698 got_pathlist_free(&paths);
9699 free(cwd);
9700 free(id_str);
9701 free(uuidstr);
9702 return error;