Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/param.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
41 #include <util.h>
43 #include "got_version.h"
44 #include "got_error.h"
45 #include "got_object.h"
46 #include "got_reference.h"
47 #include "got_repository.h"
48 #include "got_path.h"
49 #include "got_cancel.h"
50 #include "got_worktree.h"
51 #include "got_diff.h"
52 #include "got_commit_graph.h"
53 #include "got_fetch.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_opentemp.h"
57 #include "got_gotconfig.h"
59 #ifndef nitems
60 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
61 #endif
63 static volatile sig_atomic_t sigint_received;
64 static volatile sig_atomic_t sigpipe_received;
66 static void
67 catch_sigint(int signo)
68 {
69 sigint_received = 1;
70 }
72 static void
73 catch_sigpipe(int signo)
74 {
75 sigpipe_received = 1;
76 }
79 struct got_cmd {
80 const char *cmd_name;
81 const struct got_error *(*cmd_main)(int, char *[]);
82 void (*cmd_usage)(void);
83 const char *cmd_alias;
84 };
86 __dead static void usage(int);
87 __dead static void usage_init(void);
88 __dead static void usage_import(void);
89 __dead static void usage_clone(void);
90 __dead static void usage_fetch(void);
91 __dead static void usage_checkout(void);
92 __dead static void usage_update(void);
93 __dead static void usage_log(void);
94 __dead static void usage_diff(void);
95 __dead static void usage_blame(void);
96 __dead static void usage_tree(void);
97 __dead static void usage_status(void);
98 __dead static void usage_ref(void);
99 __dead static void usage_branch(void);
100 __dead static void usage_tag(void);
101 __dead static void usage_add(void);
102 __dead static void usage_remove(void);
103 __dead static void usage_revert(void);
104 __dead static void usage_commit(void);
105 __dead static void usage_cherrypick(void);
106 __dead static void usage_backout(void);
107 __dead static void usage_rebase(void);
108 __dead static void usage_histedit(void);
109 __dead static void usage_integrate(void);
110 __dead static void usage_stage(void);
111 __dead static void usage_unstage(void);
112 __dead static void usage_cat(void);
113 __dead static void usage_info(void);
115 static const struct got_error* cmd_init(int, char *[]);
116 static const struct got_error* cmd_import(int, char *[]);
117 static const struct got_error* cmd_clone(int, char *[]);
118 static const struct got_error* cmd_fetch(int, char *[]);
119 static const struct got_error* cmd_checkout(int, char *[]);
120 static const struct got_error* cmd_update(int, char *[]);
121 static const struct got_error* cmd_log(int, char *[]);
122 static const struct got_error* cmd_diff(int, char *[]);
123 static const struct got_error* cmd_blame(int, char *[]);
124 static const struct got_error* cmd_tree(int, char *[]);
125 static const struct got_error* cmd_status(int, char *[]);
126 static const struct got_error* cmd_ref(int, char *[]);
127 static const struct got_error* cmd_branch(int, char *[]);
128 static const struct got_error* cmd_tag(int, char *[]);
129 static const struct got_error* cmd_add(int, char *[]);
130 static const struct got_error* cmd_remove(int, char *[]);
131 static const struct got_error* cmd_revert(int, char *[]);
132 static const struct got_error* cmd_commit(int, char *[]);
133 static const struct got_error* cmd_cherrypick(int, char *[]);
134 static const struct got_error* cmd_backout(int, char *[]);
135 static const struct got_error* cmd_rebase(int, char *[]);
136 static const struct got_error* cmd_histedit(int, char *[]);
137 static const struct got_error* cmd_integrate(int, char *[]);
138 static const struct got_error* cmd_stage(int, char *[]);
139 static const struct got_error* cmd_unstage(int, char *[]);
140 static const struct got_error* cmd_cat(int, char *[]);
141 static const struct got_error* cmd_info(int, char *[]);
143 static struct got_cmd got_commands[] = {
144 { "init", cmd_init, usage_init, "" },
145 { "import", cmd_import, usage_import, "im" },
146 { "clone", cmd_clone, usage_clone, "cl" },
147 { "fetch", cmd_fetch, usage_fetch, "fe" },
148 { "checkout", cmd_checkout, usage_checkout, "co" },
149 { "update", cmd_update, usage_update, "up" },
150 { "log", cmd_log, usage_log, "" },
151 { "diff", cmd_diff, usage_diff, "di" },
152 { "blame", cmd_blame, usage_blame, "bl" },
153 { "tree", cmd_tree, usage_tree, "tr" },
154 { "status", cmd_status, usage_status, "st" },
155 { "ref", cmd_ref, usage_ref, "" },
156 { "branch", cmd_branch, usage_branch, "br" },
157 { "tag", cmd_tag, usage_tag, "" },
158 { "add", cmd_add, usage_add, "" },
159 { "remove", cmd_remove, usage_remove, "rm" },
160 { "revert", cmd_revert, usage_revert, "rv" },
161 { "commit", cmd_commit, usage_commit, "ci" },
162 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
163 { "backout", cmd_backout, usage_backout, "bo" },
164 { "rebase", cmd_rebase, usage_rebase, "rb" },
165 { "histedit", cmd_histedit, usage_histedit, "he" },
166 { "integrate", cmd_integrate, usage_integrate,"ig" },
167 { "stage", cmd_stage, usage_stage, "sg" },
168 { "unstage", cmd_unstage, usage_unstage, "ug" },
169 { "cat", cmd_cat, usage_cat, "" },
170 { "info", cmd_info, usage_info, "" },
171 };
173 static void
174 list_commands(void)
176 int i;
178 fprintf(stderr, "commands:");
179 for (i = 0; i < nitems(got_commands); i++) {
180 struct got_cmd *cmd = &got_commands[i];
181 fprintf(stderr, " %s", cmd->cmd_name);
183 fputc('\n', stderr);
186 int
187 main(int argc, char *argv[])
189 struct got_cmd *cmd;
190 unsigned int i;
191 int ch;
192 int hflag = 0, Vflag = 0;
193 static struct option longopts[] = {
194 { "version", no_argument, NULL, 'V' },
195 { NULL, 0, NULL, 0}
196 };
198 setlocale(LC_CTYPE, "");
200 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
201 switch (ch) {
202 case 'h':
203 hflag = 1;
204 break;
205 case 'V':
206 Vflag = 1;
207 break;
208 default:
209 usage(hflag);
210 /* NOTREACHED */
214 argc -= optind;
215 argv += optind;
216 optind = 0;
218 if (Vflag) {
219 got_version_print_str();
220 return 1;
223 if (argc <= 0)
224 usage(hflag);
226 signal(SIGINT, catch_sigint);
227 signal(SIGPIPE, catch_sigpipe);
229 for (i = 0; i < nitems(got_commands); i++) {
230 const struct got_error *error;
232 cmd = &got_commands[i];
234 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
235 strcmp(cmd->cmd_alias, argv[0]) != 0)
236 continue;
238 if (hflag)
239 got_commands[i].cmd_usage();
241 error = got_commands[i].cmd_main(argc, argv);
242 if (error && error->code != GOT_ERR_CANCELLED &&
243 error->code != GOT_ERR_PRIVSEP_EXIT &&
244 !(sigpipe_received &&
245 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
246 !(sigint_received &&
247 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
248 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
249 return 1;
252 return 0;
255 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
256 list_commands();
257 return 1;
260 __dead static void
261 usage(int hflag)
263 fprintf(stderr, "usage: %s [-h] [-V | --version] command [arg ...]\n",
264 getprogname());
265 if (hflag)
266 list_commands();
267 exit(1);
270 static const struct got_error *
271 get_editor(char **abspath)
273 const struct got_error *err = NULL;
274 const char *editor;
276 *abspath = NULL;
278 editor = getenv("VISUAL");
279 if (editor == NULL)
280 editor = getenv("EDITOR");
282 if (editor) {
283 err = got_path_find_prog(abspath, editor);
284 if (err)
285 return err;
288 if (*abspath == NULL) {
289 *abspath = strdup("/bin/ed");
290 if (*abspath == NULL)
291 return got_error_from_errno("strdup");
294 return NULL;
297 static const struct got_error *
298 apply_unveil(const char *repo_path, int repo_read_only,
299 const char *worktree_path)
301 const struct got_error *err;
303 #ifdef PROFILE
304 if (unveil("gmon.out", "rwc") != 0)
305 return got_error_from_errno2("unveil", "gmon.out");
306 #endif
307 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
308 return got_error_from_errno2("unveil", repo_path);
310 if (worktree_path && unveil(worktree_path, "rwc") != 0)
311 return got_error_from_errno2("unveil", worktree_path);
313 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
314 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
316 err = got_privsep_unveil_exec_helpers();
317 if (err != NULL)
318 return err;
320 if (unveil(NULL, NULL) != 0)
321 return got_error_from_errno("unveil");
323 return NULL;
326 __dead static void
327 usage_init(void)
329 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
330 exit(1);
333 static const struct got_error *
334 cmd_init(int argc, char *argv[])
336 const struct got_error *error = NULL;
337 char *repo_path = NULL;
338 int ch;
340 while ((ch = getopt(argc, argv, "")) != -1) {
341 switch (ch) {
342 default:
343 usage_init();
344 /* NOTREACHED */
348 argc -= optind;
349 argv += optind;
351 #ifndef PROFILE
352 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
353 err(1, "pledge");
354 #endif
355 if (argc != 1)
356 usage_init();
358 repo_path = strdup(argv[0]);
359 if (repo_path == NULL)
360 return got_error_from_errno("strdup");
362 got_path_strip_trailing_slashes(repo_path);
364 error = got_path_mkdir(repo_path);
365 if (error &&
366 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
367 goto done;
369 error = apply_unveil(repo_path, 0, NULL);
370 if (error)
371 goto done;
373 error = got_repo_init(repo_path);
374 done:
375 free(repo_path);
376 return error;
379 __dead static void
380 usage_import(void)
382 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
383 "[-r repository-path] [-I pattern] path\n", getprogname());
384 exit(1);
387 int
388 spawn_editor(const char *editor, const char *file)
390 pid_t pid;
391 sig_t sighup, sigint, sigquit;
392 int st = -1;
394 sighup = signal(SIGHUP, SIG_IGN);
395 sigint = signal(SIGINT, SIG_IGN);
396 sigquit = signal(SIGQUIT, SIG_IGN);
398 switch (pid = fork()) {
399 case -1:
400 goto doneediting;
401 case 0:
402 execl(editor, editor, file, (char *)NULL);
403 _exit(127);
406 while (waitpid(pid, &st, 0) == -1)
407 if (errno != EINTR)
408 break;
410 doneediting:
411 (void)signal(SIGHUP, sighup);
412 (void)signal(SIGINT, sigint);
413 (void)signal(SIGQUIT, sigquit);
415 if (!WIFEXITED(st)) {
416 errno = EINTR;
417 return -1;
420 return WEXITSTATUS(st);
423 static const struct got_error *
424 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
425 const char *initial_content)
427 const struct got_error *err = NULL;
428 char buf[1024];
429 struct stat st, st2;
430 FILE *fp;
431 int content_changed = 0;
432 size_t len;
434 *logmsg = NULL;
436 if (stat(logmsg_path, &st) == -1)
437 return got_error_from_errno2("stat", logmsg_path);
439 if (spawn_editor(editor, logmsg_path) == -1)
440 return got_error_from_errno("failed spawning editor");
442 if (stat(logmsg_path, &st2) == -1)
443 return got_error_from_errno("stat");
445 if (st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
446 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
447 "no changes made to commit message, aborting");
449 *logmsg = malloc(st2.st_size + 1);
450 if (*logmsg == NULL)
451 return got_error_from_errno("malloc");
452 (*logmsg)[0] = '\0';
453 len = 0;
455 fp = fopen(logmsg_path, "r");
456 if (fp == NULL) {
457 err = got_error_from_errno("fopen");
458 goto done;
460 while (fgets(buf, sizeof(buf), fp) != NULL) {
461 if (!content_changed && strcmp(buf, initial_content) != 0)
462 content_changed = 1;
463 if (buf[0] == '#' || (len == 0 && buf[0] == '\n'))
464 continue; /* remove comments and leading empty lines */
465 len = strlcat(*logmsg, buf, st2.st_size);
467 fclose(fp);
469 while (len > 0 && (*logmsg)[len - 1] == '\n') {
470 (*logmsg)[len - 1] = '\0';
471 len--;
474 if (len == 0 || !content_changed)
475 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
476 "commit message cannot be empty, aborting");
477 done:
478 if (err) {
479 free(*logmsg);
480 *logmsg = NULL;
482 return err;
485 static const struct got_error *
486 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
487 const char *path_dir, const char *branch_name)
489 char *initial_content = NULL;
490 const struct got_error *err = NULL;
491 int initial_content_len;
492 int fd = -1;
494 initial_content_len = asprintf(&initial_content,
495 "\n# %s to be imported to branch %s\n", path_dir,
496 branch_name);
497 if (initial_content_len == -1)
498 return got_error_from_errno("asprintf");
500 err = got_opentemp_named_fd(logmsg_path, &fd,
501 GOT_TMPDIR_STR "/got-importmsg");
502 if (err)
503 goto done;
505 if (write(fd, initial_content, initial_content_len) == -1) {
506 err = got_error_from_errno2("write", *logmsg_path);
507 goto done;
510 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content);
511 done:
512 if (fd != -1 && close(fd) == -1 && err == NULL)
513 err = got_error_from_errno2("close", *logmsg_path);
514 free(initial_content);
515 if (err) {
516 free(*logmsg_path);
517 *logmsg_path = NULL;
519 return err;
522 static const struct got_error *
523 import_progress(void *arg, const char *path)
525 printf("A %s\n", path);
526 return NULL;
529 static const struct got_error *
530 get_author(char **author, struct got_repository *repo,
531 struct got_worktree *worktree)
533 const struct got_error *err = NULL;
534 const char *got_author = NULL, *name, *email;
535 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
537 *author = NULL;
539 if (worktree)
540 worktree_conf = got_worktree_get_gotconfig(worktree);
541 repo_conf = got_repo_get_gotconfig(repo);
543 /*
544 * Priority of potential author information sources, from most
545 * significant to least significant:
546 * 1) work tree's .got/got.conf file
547 * 2) repository's got.conf file
548 * 3) repository's git config file
549 * 4) environment variables
550 * 5) global git config files (in user's home directory or /etc)
551 */
553 if (worktree_conf)
554 got_author = got_gotconfig_get_author(worktree_conf);
555 if (got_author == NULL)
556 got_author = got_gotconfig_get_author(repo_conf);
557 if (got_author == NULL) {
558 name = got_repo_get_gitconfig_author_name(repo);
559 email = got_repo_get_gitconfig_author_email(repo);
560 if (name && email) {
561 if (asprintf(author, "%s <%s>", name, email) == -1)
562 return got_error_from_errno("asprintf");
563 return NULL;
566 got_author = getenv("GOT_AUTHOR");
567 if (got_author == NULL) {
568 name = got_repo_get_global_gitconfig_author_name(repo);
569 email = got_repo_get_global_gitconfig_author_email(
570 repo);
571 if (name && email) {
572 if (asprintf(author, "%s <%s>", name, email)
573 == -1)
574 return got_error_from_errno("asprintf");
575 return NULL;
577 /* TODO: Look up user in password database? */
578 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
582 *author = strdup(got_author);
583 if (*author == NULL)
584 return got_error_from_errno("strdup");
586 /*
587 * Really dumb email address check; we're only doing this to
588 * avoid git's object parser breaking on commits we create.
589 */
590 while (*got_author && *got_author != '<')
591 got_author++;
592 if (*got_author != '<') {
593 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
594 goto done;
596 while (*got_author && *got_author != '@')
597 got_author++;
598 if (*got_author != '@') {
599 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
600 goto done;
602 while (*got_author && *got_author != '>')
603 got_author++;
604 if (*got_author != '>')
605 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
606 done:
607 if (err) {
608 free(*author);
609 *author = NULL;
611 return err;
614 static const struct got_error *
615 get_gitconfig_path(char **gitconfig_path)
617 const char *homedir = getenv("HOME");
619 *gitconfig_path = NULL;
620 if (homedir) {
621 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
622 return got_error_from_errno("asprintf");
625 return NULL;
628 static const struct got_error *
629 cmd_import(int argc, char *argv[])
631 const struct got_error *error = NULL;
632 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
633 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
634 const char *branch_name = "main";
635 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
636 struct got_repository *repo = NULL;
637 struct got_reference *branch_ref = NULL, *head_ref = NULL;
638 struct got_object_id *new_commit_id = NULL;
639 int ch;
640 struct got_pathlist_head ignores;
641 struct got_pathlist_entry *pe;
642 int preserve_logmsg = 0;
644 TAILQ_INIT(&ignores);
646 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
647 switch (ch) {
648 case 'b':
649 branch_name = optarg;
650 break;
651 case 'm':
652 logmsg = strdup(optarg);
653 if (logmsg == NULL) {
654 error = got_error_from_errno("strdup");
655 goto done;
657 break;
658 case 'r':
659 repo_path = realpath(optarg, NULL);
660 if (repo_path == NULL) {
661 error = got_error_from_errno2("realpath",
662 optarg);
663 goto done;
665 break;
666 case 'I':
667 if (optarg[0] == '\0')
668 break;
669 error = got_pathlist_insert(&pe, &ignores, optarg,
670 NULL);
671 if (error)
672 goto done;
673 break;
674 default:
675 usage_import();
676 /* NOTREACHED */
680 argc -= optind;
681 argv += optind;
683 #ifndef PROFILE
684 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
685 "unveil",
686 NULL) == -1)
687 err(1, "pledge");
688 #endif
689 if (argc != 1)
690 usage_import();
692 if (repo_path == NULL) {
693 repo_path = getcwd(NULL, 0);
694 if (repo_path == NULL)
695 return got_error_from_errno("getcwd");
697 got_path_strip_trailing_slashes(repo_path);
698 error = get_gitconfig_path(&gitconfig_path);
699 if (error)
700 goto done;
701 error = got_repo_open(&repo, repo_path, gitconfig_path);
702 if (error)
703 goto done;
705 error = get_author(&author, repo, NULL);
706 if (error)
707 return error;
709 /*
710 * Don't let the user create a branch name with a leading '-'.
711 * While technically a valid reference name, this case is usually
712 * an unintended typo.
713 */
714 if (branch_name[0] == '-')
715 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
717 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
718 error = got_error_from_errno("asprintf");
719 goto done;
722 error = got_ref_open(&branch_ref, repo, refname, 0);
723 if (error) {
724 if (error->code != GOT_ERR_NOT_REF)
725 goto done;
726 } else {
727 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
728 "import target branch already exists");
729 goto done;
732 path_dir = realpath(argv[0], NULL);
733 if (path_dir == NULL) {
734 error = got_error_from_errno2("realpath", argv[0]);
735 goto done;
737 got_path_strip_trailing_slashes(path_dir);
739 /*
740 * unveil(2) traverses exec(2); if an editor is used we have
741 * to apply unveil after the log message has been written.
742 */
743 if (logmsg == NULL || strlen(logmsg) == 0) {
744 error = get_editor(&editor);
745 if (error)
746 goto done;
747 free(logmsg);
748 error = collect_import_msg(&logmsg, &logmsg_path, editor,
749 path_dir, refname);
750 if (error) {
751 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
752 logmsg_path != NULL)
753 preserve_logmsg = 1;
754 goto done;
758 if (unveil(path_dir, "r") != 0) {
759 error = got_error_from_errno2("unveil", path_dir);
760 if (logmsg_path)
761 preserve_logmsg = 1;
762 goto done;
765 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
766 if (error) {
767 if (logmsg_path)
768 preserve_logmsg = 1;
769 goto done;
772 error = got_repo_import(&new_commit_id, path_dir, logmsg,
773 author, &ignores, repo, import_progress, NULL);
774 if (error) {
775 if (logmsg_path)
776 preserve_logmsg = 1;
777 goto done;
780 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
781 if (error) {
782 if (logmsg_path)
783 preserve_logmsg = 1;
784 goto done;
787 error = got_ref_write(branch_ref, repo);
788 if (error) {
789 if (logmsg_path)
790 preserve_logmsg = 1;
791 goto done;
794 error = got_object_id_str(&id_str, new_commit_id);
795 if (error) {
796 if (logmsg_path)
797 preserve_logmsg = 1;
798 goto done;
801 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
802 if (error) {
803 if (error->code != GOT_ERR_NOT_REF) {
804 if (logmsg_path)
805 preserve_logmsg = 1;
806 goto done;
809 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
810 branch_ref);
811 if (error) {
812 if (logmsg_path)
813 preserve_logmsg = 1;
814 goto done;
817 error = got_ref_write(head_ref, repo);
818 if (error) {
819 if (logmsg_path)
820 preserve_logmsg = 1;
821 goto done;
825 printf("Created branch %s with commit %s\n",
826 got_ref_get_name(branch_ref), id_str);
827 done:
828 if (preserve_logmsg) {
829 fprintf(stderr, "%s: log message preserved in %s\n",
830 getprogname(), logmsg_path);
831 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
832 error = got_error_from_errno2("unlink", logmsg_path);
833 free(logmsg);
834 free(logmsg_path);
835 free(repo_path);
836 free(editor);
837 free(refname);
838 free(new_commit_id);
839 free(id_str);
840 free(author);
841 free(gitconfig_path);
842 if (branch_ref)
843 got_ref_close(branch_ref);
844 if (head_ref)
845 got_ref_close(head_ref);
846 return error;
849 __dead static void
850 usage_clone(void)
852 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
853 "[-R reference] repository-url [directory]\n", getprogname());
854 exit(1);
857 struct got_fetch_progress_arg {
858 char last_scaled_size[FMT_SCALED_STRSIZE];
859 int last_p_indexed;
860 int last_p_resolved;
861 int verbosity;
862 };
864 static const struct got_error *
865 fetch_progress(void *arg, const char *message, off_t packfile_size,
866 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
868 struct got_fetch_progress_arg *a = arg;
869 char scaled_size[FMT_SCALED_STRSIZE];
870 int p_indexed, p_resolved;
871 int print_size = 0, print_indexed = 0, print_resolved = 0;
873 if (a->verbosity < 0)
874 return NULL;
876 if (message && message[0] != '\0') {
877 printf("\rserver: %s", message);
878 fflush(stdout);
879 return NULL;
882 if (packfile_size > 0 || nobj_indexed > 0) {
883 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
884 (a->last_scaled_size[0] == '\0' ||
885 strcmp(scaled_size, a->last_scaled_size)) != 0) {
886 print_size = 1;
887 if (strlcpy(a->last_scaled_size, scaled_size,
888 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
889 return got_error(GOT_ERR_NO_SPACE);
891 if (nobj_indexed > 0) {
892 p_indexed = (nobj_indexed * 100) / nobj_total;
893 if (p_indexed != a->last_p_indexed) {
894 a->last_p_indexed = p_indexed;
895 print_indexed = 1;
896 print_size = 1;
899 if (nobj_resolved > 0) {
900 p_resolved = (nobj_resolved * 100) /
901 (nobj_total - nobj_loose);
902 if (p_resolved != a->last_p_resolved) {
903 a->last_p_resolved = p_resolved;
904 print_resolved = 1;
905 print_indexed = 1;
906 print_size = 1;
911 if (print_size || print_indexed || print_resolved)
912 printf("\r");
913 if (print_size)
914 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
915 if (print_indexed)
916 printf("; indexing %d%%", p_indexed);
917 if (print_resolved)
918 printf("; resolving deltas %d%%", p_resolved);
919 if (print_size || print_indexed || print_resolved)
920 fflush(stdout);
922 return NULL;
925 static const struct got_error *
926 create_symref(const char *refname, struct got_reference *target_ref,
927 int verbosity, struct got_repository *repo)
929 const struct got_error *err;
930 struct got_reference *head_symref;
932 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
933 if (err)
934 return err;
936 err = got_ref_write(head_symref, repo);
937 got_ref_close(head_symref);
938 if (err == NULL && verbosity > 0) {
939 printf("Created reference %s: %s\n", GOT_REF_HEAD,
940 got_ref_get_name(target_ref));
942 return err;
945 static const struct got_error *
946 list_remote_refs(struct got_pathlist_head *symrefs,
947 struct got_pathlist_head *refs)
949 const struct got_error *err;
950 struct got_pathlist_entry *pe;
952 TAILQ_FOREACH(pe, symrefs, entry) {
953 const char *refname = pe->path;
954 const char *targetref = pe->data;
956 printf("%s: %s\n", refname, targetref);
959 TAILQ_FOREACH(pe, refs, entry) {
960 const char *refname = pe->path;
961 struct got_object_id *id = pe->data;
962 char *id_str;
964 err = got_object_id_str(&id_str, id);
965 if (err)
966 return err;
967 printf("%s: %s\n", refname, id_str);
968 free(id_str);
971 return NULL;
974 static const struct got_error *
975 create_ref(const char *refname, struct got_object_id *id,
976 int verbosity, struct got_repository *repo)
978 const struct got_error *err = NULL;
979 struct got_reference *ref;
980 char *id_str;
982 err = got_object_id_str(&id_str, id);
983 if (err)
984 return err;
986 err = got_ref_alloc(&ref, refname, id);
987 if (err)
988 goto done;
990 err = got_ref_write(ref, repo);
991 got_ref_close(ref);
993 if (err == NULL && verbosity >= 0)
994 printf("Created reference %s: %s\n", refname, id_str);
995 done:
996 free(id_str);
997 return err;
1000 static int
1001 match_wanted_ref(const char *refname, const char *wanted_ref)
1003 if (strncmp(refname, "refs/", 5) != 0)
1004 return 0;
1005 refname += 5;
1008 * Prevent fetching of references that won't make any
1009 * sense outside of the remote repository's context.
1011 if (strncmp(refname, "got/", 4) == 0)
1012 return 0;
1013 if (strncmp(refname, "remotes/", 8) == 0)
1014 return 0;
1016 if (strncmp(wanted_ref, "refs/", 5) == 0)
1017 wanted_ref += 5;
1019 /* Allow prefix match. */
1020 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1021 return 1;
1023 /* Allow exact match. */
1024 return (strcmp(refname, wanted_ref) == 0);
1027 static int
1028 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1030 struct got_pathlist_entry *pe;
1032 TAILQ_FOREACH(pe, wanted_refs, entry) {
1033 if (match_wanted_ref(refname, pe->path))
1034 return 1;
1037 return 0;
1040 static const struct got_error *
1041 create_wanted_ref(const char *refname, struct got_object_id *id,
1042 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1044 const struct got_error *err;
1045 char *remote_refname;
1047 if (strncmp("refs/", refname, 5) == 0)
1048 refname += 5;
1050 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1051 remote_repo_name, refname) == -1)
1052 return got_error_from_errno("asprintf");
1054 err = create_ref(remote_refname, id, verbosity, repo);
1055 free(remote_refname);
1056 return err;
1059 static const struct got_error *
1060 cmd_clone(int argc, char *argv[])
1062 const struct got_error *error = NULL;
1063 const char *uri, *dirname;
1064 char *proto, *host, *port, *repo_name, *server_path;
1065 char *default_destdir = NULL, *id_str = NULL;
1066 const char *repo_path;
1067 struct got_repository *repo = NULL;
1068 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1069 struct got_pathlist_entry *pe;
1070 struct got_object_id *pack_hash = NULL;
1071 int ch, fetchfd = -1, fetchstatus;
1072 pid_t fetchpid = -1;
1073 struct got_fetch_progress_arg fpa;
1074 char *git_url = NULL;
1075 char *gitconfig_path = NULL, *gotconfig_path = NULL;
1076 char *gitconfig = NULL, *gotconfig = NULL;
1077 FILE *gitconfig_file = NULL, *gotconfig_file = NULL;
1078 ssize_t n;
1079 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1080 int list_refs_only = 0;
1081 struct got_reference *head_symref = NULL;
1083 TAILQ_INIT(&refs);
1084 TAILQ_INIT(&symrefs);
1085 TAILQ_INIT(&wanted_branches);
1086 TAILQ_INIT(&wanted_refs);
1088 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1089 switch (ch) {
1090 case 'a':
1091 fetch_all_branches = 1;
1092 break;
1093 case 'b':
1094 error = got_pathlist_append(&wanted_branches,
1095 optarg, NULL);
1096 if (error)
1097 return error;
1098 break;
1099 case 'l':
1100 list_refs_only = 1;
1101 break;
1102 case 'm':
1103 mirror_references = 1;
1104 break;
1105 case 'v':
1106 if (verbosity < 0)
1107 verbosity = 0;
1108 else if (verbosity < 3)
1109 verbosity++;
1110 break;
1111 case 'q':
1112 verbosity = -1;
1113 break;
1114 case 'R':
1115 error = got_pathlist_append(&wanted_refs,
1116 optarg, NULL);
1117 if (error)
1118 return error;
1119 break;
1120 default:
1121 usage_clone();
1122 break;
1125 argc -= optind;
1126 argv += optind;
1128 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1129 errx(1, "-a and -b options are mutually exclusive");
1130 if (list_refs_only) {
1131 if (!TAILQ_EMPTY(&wanted_branches))
1132 errx(1, "-l and -b options are mutually exclusive");
1133 if (fetch_all_branches)
1134 errx(1, "-l and -a options are mutually exclusive");
1135 if (mirror_references)
1136 errx(1, "-l and -m options are mutually exclusive");
1137 if (verbosity == -1)
1138 errx(1, "-l and -q options are mutually exclusive");
1139 if (!TAILQ_EMPTY(&wanted_refs))
1140 errx(1, "-l and -R options are mutually exclusive");
1143 uri = argv[0];
1145 if (argc == 1)
1146 dirname = NULL;
1147 else if (argc == 2)
1148 dirname = argv[1];
1149 else
1150 usage_clone();
1152 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1153 &repo_name, uri);
1154 if (error)
1155 goto done;
1157 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1158 host, port ? ":" : "", port ? port : "",
1159 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1160 error = got_error_from_errno("asprintf");
1161 goto done;
1164 if (strcmp(proto, "git") == 0) {
1165 #ifndef PROFILE
1166 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1167 "sendfd dns inet unveil", NULL) == -1)
1168 err(1, "pledge");
1169 #endif
1170 } else if (strcmp(proto, "git+ssh") == 0 ||
1171 strcmp(proto, "ssh") == 0) {
1172 #ifndef PROFILE
1173 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1174 "sendfd unveil", NULL) == -1)
1175 err(1, "pledge");
1176 #endif
1177 } else if (strcmp(proto, "http") == 0 ||
1178 strcmp(proto, "git+http") == 0) {
1179 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1180 goto done;
1181 } else {
1182 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1183 goto done;
1185 if (dirname == NULL) {
1186 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1187 error = got_error_from_errno("asprintf");
1188 goto done;
1190 repo_path = default_destdir;
1191 } else
1192 repo_path = dirname;
1194 if (!list_refs_only) {
1195 error = got_path_mkdir(repo_path);
1196 if (error)
1197 goto done;
1199 error = got_repo_init(repo_path);
1200 if (error)
1201 goto done;
1202 error = got_repo_open(&repo, repo_path, NULL);
1203 if (error)
1204 goto done;
1207 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1208 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1209 error = got_error_from_errno2("unveil",
1210 GOT_FETCH_PATH_SSH);
1211 goto done;
1214 error = apply_unveil(repo ? got_repo_get_path(repo) : NULL, 0, NULL);
1215 if (error)
1216 goto done;
1218 if (verbosity >= 0)
1219 printf("Connecting to %s%s%s\n", host,
1220 port ? ":" : "", port ? port : "");
1222 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1223 server_path, verbosity);
1224 if (error)
1225 goto done;
1227 fpa.last_scaled_size[0] = '\0';
1228 fpa.last_p_indexed = -1;
1229 fpa.last_p_resolved = -1;
1230 fpa.verbosity = verbosity;
1231 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1232 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1233 fetch_all_branches, &wanted_branches, &wanted_refs,
1234 list_refs_only, verbosity, fetchfd, repo,
1235 fetch_progress, &fpa);
1236 if (error)
1237 goto done;
1239 if (list_refs_only) {
1240 error = list_remote_refs(&symrefs, &refs);
1241 goto done;
1244 error = got_object_id_str(&id_str, pack_hash);
1245 if (error)
1246 goto done;
1247 if (verbosity >= 0)
1248 printf("\nFetched %s.pack\n", id_str);
1249 free(id_str);
1251 /* Set up references provided with the pack file. */
1252 TAILQ_FOREACH(pe, &refs, entry) {
1253 const char *refname = pe->path;
1254 struct got_object_id *id = pe->data;
1255 char *remote_refname;
1257 if (is_wanted_ref(&wanted_refs, refname) &&
1258 !mirror_references) {
1259 error = create_wanted_ref(refname, id,
1260 GOT_FETCH_DEFAULT_REMOTE_NAME,
1261 verbosity - 1, repo);
1262 if (error)
1263 goto done;
1264 continue;
1267 error = create_ref(refname, id, verbosity - 1, repo);
1268 if (error)
1269 goto done;
1271 if (mirror_references)
1272 continue;
1274 if (strncmp("refs/heads/", refname, 11) != 0)
1275 continue;
1277 if (asprintf(&remote_refname,
1278 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1279 refname + 11) == -1) {
1280 error = got_error_from_errno("asprintf");
1281 goto done;
1283 error = create_ref(remote_refname, id, verbosity - 1, repo);
1284 free(remote_refname);
1285 if (error)
1286 goto done;
1289 /* Set the HEAD reference if the server provided one. */
1290 TAILQ_FOREACH(pe, &symrefs, entry) {
1291 struct got_reference *target_ref;
1292 const char *refname = pe->path;
1293 const char *target = pe->data;
1294 char *remote_refname = NULL, *remote_target = NULL;
1296 if (strcmp(refname, GOT_REF_HEAD) != 0)
1297 continue;
1299 error = got_ref_open(&target_ref, repo, target, 0);
1300 if (error) {
1301 if (error->code == GOT_ERR_NOT_REF) {
1302 error = NULL;
1303 continue;
1305 goto done;
1308 error = create_symref(refname, target_ref, verbosity, repo);
1309 got_ref_close(target_ref);
1310 if (error)
1311 goto done;
1313 if (mirror_references)
1314 continue;
1316 if (strncmp("refs/heads/", target, 11) != 0)
1317 continue;
1319 if (asprintf(&remote_refname,
1320 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1321 refname) == -1) {
1322 error = got_error_from_errno("asprintf");
1323 goto done;
1325 if (asprintf(&remote_target,
1326 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1327 target + 11) == -1) {
1328 error = got_error_from_errno("asprintf");
1329 free(remote_refname);
1330 goto done;
1332 error = got_ref_open(&target_ref, repo, remote_target, 0);
1333 if (error) {
1334 free(remote_refname);
1335 free(remote_target);
1336 if (error->code == GOT_ERR_NOT_REF) {
1337 error = NULL;
1338 continue;
1340 goto done;
1342 error = create_symref(remote_refname, target_ref,
1343 verbosity - 1, repo);
1344 free(remote_refname);
1345 free(remote_target);
1346 got_ref_close(target_ref);
1347 if (error)
1348 goto done;
1350 if (pe == NULL) {
1352 * We failed to set the HEAD reference. If we asked for
1353 * a set of wanted branches use the first of one of those
1354 * which could be fetched instead.
1356 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1357 const char *target = pe->path;
1358 struct got_reference *target_ref;
1360 error = got_ref_open(&target_ref, repo, target, 0);
1361 if (error) {
1362 if (error->code == GOT_ERR_NOT_REF) {
1363 error = NULL;
1364 continue;
1366 goto done;
1369 error = create_symref(GOT_REF_HEAD, target_ref,
1370 verbosity, repo);
1371 got_ref_close(target_ref);
1372 if (error)
1373 goto done;
1374 break;
1378 /* Create got.conf(5). */
1379 gotconfig_path = got_repo_get_path_gotconfig(repo);
1380 if (gotconfig_path == NULL) {
1381 error = got_error_from_errno("got_repo_get_path_gotconfig");
1382 goto done;
1384 gotconfig_file = fopen(gotconfig_path, "a");
1385 if (gotconfig_file == NULL) {
1386 error = got_error_from_errno2("fopen", gotconfig_path);
1387 goto done;
1389 got_path_strip_trailing_slashes(server_path);
1390 if (asprintf(&gotconfig,
1391 "remote \"%s\" {\n"
1392 "\tserver %s\n"
1393 "\tprotocol %s\n"
1394 "%s%s%s"
1395 "\trepository \"%s\"\n"
1396 "%s"
1397 "}\n",
1398 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1399 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1400 server_path,
1401 mirror_references ? "\tmirror-references yes\n" : "") == -1) {
1402 error = got_error_from_errno("asprintf");
1403 goto done;
1405 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1406 if (n != strlen(gotconfig)) {
1407 error = got_ferror(gotconfig_file, GOT_ERR_IO);
1408 goto done;
1411 /* Create a config file Git can understand. */
1412 gitconfig_path = got_repo_get_path_gitconfig(repo);
1413 if (gitconfig_path == NULL) {
1414 error = got_error_from_errno("got_repo_get_path_gitconfig");
1415 goto done;
1417 gitconfig_file = fopen(gitconfig_path, "a");
1418 if (gitconfig_file == NULL) {
1419 error = got_error_from_errno2("fopen", gitconfig_path);
1420 goto done;
1422 if (mirror_references) {
1423 if (asprintf(&gitconfig,
1424 "[remote \"%s\"]\n"
1425 "\turl = %s\n"
1426 "\tfetch = +refs/*:refs/*\n"
1427 "\tmirror = true\n",
1428 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1429 error = got_error_from_errno("asprintf");
1430 goto done;
1432 } else if (fetch_all_branches) {
1433 if (asprintf(&gitconfig,
1434 "[remote \"%s\"]\n"
1435 "\turl = %s\n"
1436 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1437 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1438 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1439 error = got_error_from_errno("asprintf");
1440 goto done;
1442 } else {
1443 const char *branchname;
1446 * If the server specified a default branch, use just that one.
1447 * Otherwise fall back to fetching all branches on next fetch.
1449 if (head_symref) {
1450 branchname = got_ref_get_symref_target(head_symref);
1451 if (strncmp(branchname, "refs/heads/", 11) == 0)
1452 branchname += 11;
1453 } else
1454 branchname = "*"; /* fall back to all branches */
1455 if (asprintf(&gitconfig,
1456 "[remote \"%s\"]\n"
1457 "\turl = %s\n"
1458 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1459 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1460 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1461 branchname) == -1) {
1462 error = got_error_from_errno("asprintf");
1463 goto done;
1466 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1467 if (n != strlen(gitconfig)) {
1468 error = got_ferror(gitconfig_file, GOT_ERR_IO);
1469 goto done;
1472 if (verbosity >= 0)
1473 printf("Created %s repository '%s'\n",
1474 mirror_references ? "mirrored" : "cloned", repo_path);
1475 done:
1476 if (fetchpid > 0) {
1477 if (kill(fetchpid, SIGTERM) == -1)
1478 error = got_error_from_errno("kill");
1479 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1480 error = got_error_from_errno("waitpid");
1482 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1483 error = got_error_from_errno("close");
1484 if (gotconfig_file && fclose(gotconfig_file) == EOF && error == NULL)
1485 error = got_error_from_errno("fclose");
1486 if (gitconfig_file && fclose(gitconfig_file) == EOF && error == NULL)
1487 error = got_error_from_errno("fclose");
1488 if (repo)
1489 got_repo_close(repo);
1490 if (head_symref)
1491 got_ref_close(head_symref);
1492 TAILQ_FOREACH(pe, &refs, entry) {
1493 free((void *)pe->path);
1494 free(pe->data);
1496 got_pathlist_free(&refs);
1497 TAILQ_FOREACH(pe, &symrefs, entry) {
1498 free((void *)pe->path);
1499 free(pe->data);
1501 got_pathlist_free(&symrefs);
1502 got_pathlist_free(&wanted_branches);
1503 got_pathlist_free(&wanted_refs);
1504 free(pack_hash);
1505 free(proto);
1506 free(host);
1507 free(port);
1508 free(server_path);
1509 free(repo_name);
1510 free(default_destdir);
1511 free(gotconfig);
1512 free(gitconfig);
1513 free(gotconfig_path);
1514 free(gitconfig_path);
1515 free(git_url);
1516 return error;
1519 static const struct got_error *
1520 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1521 int replace_tags, int verbosity, struct got_repository *repo)
1523 const struct got_error *err = NULL;
1524 char *new_id_str = NULL;
1525 struct got_object_id *old_id = NULL;
1527 err = got_object_id_str(&new_id_str, new_id);
1528 if (err)
1529 goto done;
1531 if (!replace_tags &&
1532 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1533 err = got_ref_resolve(&old_id, repo, ref);
1534 if (err)
1535 goto done;
1536 if (got_object_id_cmp(old_id, new_id) == 0)
1537 goto done;
1538 if (verbosity >= 0) {
1539 printf("Rejecting update of existing tag %s: %s\n",
1540 got_ref_get_name(ref), new_id_str);
1542 goto done;
1545 if (got_ref_is_symbolic(ref)) {
1546 if (verbosity >= 0) {
1547 printf("Replacing reference %s: %s\n",
1548 got_ref_get_name(ref),
1549 got_ref_get_symref_target(ref));
1551 err = got_ref_change_symref_to_ref(ref, new_id);
1552 if (err)
1553 goto done;
1554 err = got_ref_write(ref, repo);
1555 if (err)
1556 goto done;
1557 } else {
1558 err = got_ref_resolve(&old_id, repo, ref);
1559 if (err)
1560 goto done;
1561 if (got_object_id_cmp(old_id, new_id) == 0)
1562 goto done;
1564 err = got_ref_change_ref(ref, new_id);
1565 if (err)
1566 goto done;
1567 err = got_ref_write(ref, repo);
1568 if (err)
1569 goto done;
1572 if (verbosity >= 0)
1573 printf("Updated %s: %s\n", got_ref_get_name(ref),
1574 new_id_str);
1575 done:
1576 free(old_id);
1577 free(new_id_str);
1578 return err;
1581 static const struct got_error *
1582 update_symref(const char *refname, struct got_reference *target_ref,
1583 int verbosity, struct got_repository *repo)
1585 const struct got_error *err = NULL, *unlock_err;
1586 struct got_reference *symref;
1587 int symref_is_locked = 0;
1589 err = got_ref_open(&symref, repo, refname, 1);
1590 if (err) {
1591 if (err->code != GOT_ERR_NOT_REF)
1592 return err;
1593 err = got_ref_alloc_symref(&symref, refname, target_ref);
1594 if (err)
1595 goto done;
1597 err = got_ref_write(symref, repo);
1598 if (err)
1599 goto done;
1601 if (verbosity >= 0)
1602 printf("Created reference %s: %s\n",
1603 got_ref_get_name(symref),
1604 got_ref_get_symref_target(symref));
1605 } else {
1606 symref_is_locked = 1;
1608 if (strcmp(got_ref_get_symref_target(symref),
1609 got_ref_get_name(target_ref)) == 0)
1610 goto done;
1612 err = got_ref_change_symref(symref,
1613 got_ref_get_name(target_ref));
1614 if (err)
1615 goto done;
1617 err = got_ref_write(symref, repo);
1618 if (err)
1619 goto done;
1621 if (verbosity >= 0)
1622 printf("Updated %s: %s\n", got_ref_get_name(symref),
1623 got_ref_get_symref_target(symref));
1626 done:
1627 if (symref_is_locked) {
1628 unlock_err = got_ref_unlock(symref);
1629 if (unlock_err && err == NULL)
1630 err = unlock_err;
1632 got_ref_close(symref);
1633 return err;
1636 __dead static void
1637 usage_fetch(void)
1639 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1640 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1641 "[remote-repository-name]\n",
1642 getprogname());
1643 exit(1);
1646 static const struct got_error *
1647 delete_missing_ref(struct got_reference *ref,
1648 int verbosity, struct got_repository *repo)
1650 const struct got_error *err = NULL;
1651 struct got_object_id *id = NULL;
1652 char *id_str = NULL;
1654 if (got_ref_is_symbolic(ref)) {
1655 err = got_ref_delete(ref, repo);
1656 if (err)
1657 return err;
1658 if (verbosity >= 0) {
1659 printf("Deleted reference %s: %s\n",
1660 got_ref_get_name(ref),
1661 got_ref_get_symref_target(ref));
1663 } else {
1664 err = got_ref_resolve(&id, repo, ref);
1665 if (err)
1666 return err;
1667 err = got_object_id_str(&id_str, id);
1668 if (err)
1669 goto done;
1671 err = got_ref_delete(ref, repo);
1672 if (err)
1673 goto done;
1674 if (verbosity >= 0) {
1675 printf("Deleted reference %s: %s\n",
1676 got_ref_get_name(ref), id_str);
1679 done:
1680 free(id);
1681 free(id_str);
1682 return NULL;
1685 static const struct got_error *
1686 delete_missing_refs(struct got_pathlist_head *their_refs,
1687 struct got_pathlist_head *their_symrefs,
1688 const struct got_remote_repo *remote,
1689 int verbosity, struct got_repository *repo)
1691 const struct got_error *err = NULL, *unlock_err;
1692 struct got_reflist_head my_refs;
1693 struct got_reflist_entry *re;
1694 struct got_pathlist_entry *pe;
1695 char *remote_namespace = NULL;
1696 char *local_refname = NULL;
1698 SIMPLEQ_INIT(&my_refs);
1700 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
1701 == -1)
1702 return got_error_from_errno("asprintf");
1704 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1705 if (err)
1706 goto done;
1708 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1709 const char *refname = got_ref_get_name(re->ref);
1711 if (!remote->mirror_references) {
1712 if (strncmp(refname, remote_namespace,
1713 strlen(remote_namespace)) == 0) {
1714 if (strcmp(refname + strlen(remote_namespace),
1715 GOT_REF_HEAD) == 0)
1716 continue;
1717 if (asprintf(&local_refname, "refs/heads/%s",
1718 refname + strlen(remote_namespace)) == -1) {
1719 err = got_error_from_errno("asprintf");
1720 goto done;
1722 } else if (strncmp(refname, "refs/tags/", 10) != 0)
1723 continue;
1726 TAILQ_FOREACH(pe, their_refs, entry) {
1727 if (strcmp(local_refname, pe->path) == 0)
1728 break;
1730 if (pe != NULL)
1731 continue;
1733 TAILQ_FOREACH(pe, their_symrefs, entry) {
1734 if (strcmp(local_refname, pe->path) == 0)
1735 break;
1737 if (pe != NULL)
1738 continue;
1740 err = delete_missing_ref(re->ref, verbosity, repo);
1741 if (err)
1742 break;
1744 if (local_refname) {
1745 struct got_reference *ref;
1746 err = got_ref_open(&ref, repo, local_refname, 1);
1747 if (err) {
1748 if (err->code != GOT_ERR_NOT_REF)
1749 break;
1750 free(local_refname);
1751 local_refname = NULL;
1752 continue;
1754 err = delete_missing_ref(ref, verbosity, repo);
1755 if (err)
1756 break;
1757 unlock_err = got_ref_unlock(ref);
1758 got_ref_close(ref);
1759 if (unlock_err && err == NULL) {
1760 err = unlock_err;
1761 break;
1764 free(local_refname);
1765 local_refname = NULL;
1768 done:
1769 free(remote_namespace);
1770 free(local_refname);
1771 return err;
1774 static const struct got_error *
1775 update_wanted_ref(const char *refname, struct got_object_id *id,
1776 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1778 const struct got_error *err, *unlock_err;
1779 char *remote_refname;
1780 struct got_reference *ref;
1782 if (strncmp("refs/", refname, 5) == 0)
1783 refname += 5;
1785 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1786 remote_repo_name, refname) == -1)
1787 return got_error_from_errno("asprintf");
1789 err = got_ref_open(&ref, repo, remote_refname, 1);
1790 if (err) {
1791 if (err->code != GOT_ERR_NOT_REF)
1792 goto done;
1793 err = create_ref(remote_refname, id, verbosity, repo);
1794 } else {
1795 err = update_ref(ref, id, 0, verbosity, repo);
1796 unlock_err = got_ref_unlock(ref);
1797 if (unlock_err && err == NULL)
1798 err = unlock_err;
1799 got_ref_close(ref);
1801 done:
1802 free(remote_refname);
1803 return err;
1806 static const struct got_error *
1807 cmd_fetch(int argc, char *argv[])
1809 const struct got_error *error = NULL, *unlock_err;
1810 char *cwd = NULL, *repo_path = NULL;
1811 const char *remote_name;
1812 char *proto = NULL, *host = NULL, *port = NULL;
1813 char *repo_name = NULL, *server_path = NULL;
1814 const struct got_remote_repo *remotes, *remote = NULL;
1815 int nremotes;
1816 char *id_str = NULL;
1817 struct got_repository *repo = NULL;
1818 struct got_worktree *worktree = NULL;
1819 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
1820 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1821 struct got_pathlist_entry *pe;
1822 struct got_object_id *pack_hash = NULL;
1823 int i, ch, fetchfd = -1, fetchstatus;
1824 pid_t fetchpid = -1;
1825 struct got_fetch_progress_arg fpa;
1826 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
1827 int delete_refs = 0, replace_tags = 0;
1829 TAILQ_INIT(&refs);
1830 TAILQ_INIT(&symrefs);
1831 TAILQ_INIT(&wanted_branches);
1832 TAILQ_INIT(&wanted_refs);
1834 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
1835 switch (ch) {
1836 case 'a':
1837 fetch_all_branches = 1;
1838 break;
1839 case 'b':
1840 error = got_pathlist_append(&wanted_branches,
1841 optarg, NULL);
1842 if (error)
1843 return error;
1844 break;
1845 case 'd':
1846 delete_refs = 1;
1847 break;
1848 case 'l':
1849 list_refs_only = 1;
1850 break;
1851 case 'r':
1852 repo_path = realpath(optarg, NULL);
1853 if (repo_path == NULL)
1854 return got_error_from_errno2("realpath",
1855 optarg);
1856 got_path_strip_trailing_slashes(repo_path);
1857 break;
1858 case 't':
1859 replace_tags = 1;
1860 break;
1861 case 'v':
1862 if (verbosity < 0)
1863 verbosity = 0;
1864 else if (verbosity < 3)
1865 verbosity++;
1866 break;
1867 case 'q':
1868 verbosity = -1;
1869 break;
1870 case 'R':
1871 error = got_pathlist_append(&wanted_refs,
1872 optarg, NULL);
1873 if (error)
1874 return error;
1875 break;
1876 default:
1877 usage_fetch();
1878 break;
1881 argc -= optind;
1882 argv += optind;
1884 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1885 errx(1, "-a and -b options are mutually exclusive");
1886 if (list_refs_only) {
1887 if (!TAILQ_EMPTY(&wanted_branches))
1888 errx(1, "-l and -b options are mutually exclusive");
1889 if (fetch_all_branches)
1890 errx(1, "-l and -a options are mutually exclusive");
1891 if (delete_refs)
1892 errx(1, "-l and -d options are mutually exclusive");
1893 if (verbosity == -1)
1894 errx(1, "-l and -q options are mutually exclusive");
1897 if (argc == 0)
1898 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
1899 else if (argc == 1)
1900 remote_name = argv[0];
1901 else
1902 usage_fetch();
1904 cwd = getcwd(NULL, 0);
1905 if (cwd == NULL) {
1906 error = got_error_from_errno("getcwd");
1907 goto done;
1910 if (repo_path == NULL) {
1911 error = got_worktree_open(&worktree, cwd);
1912 if (error && error->code != GOT_ERR_NOT_WORKTREE)
1913 goto done;
1914 else
1915 error = NULL;
1916 if (worktree) {
1917 repo_path =
1918 strdup(got_worktree_get_repo_path(worktree));
1919 if (repo_path == NULL)
1920 error = got_error_from_errno("strdup");
1921 if (error)
1922 goto done;
1923 } else {
1924 repo_path = strdup(cwd);
1925 if (repo_path == NULL) {
1926 error = got_error_from_errno("strdup");
1927 goto done;
1932 error = got_repo_open(&repo, repo_path, NULL);
1933 if (error)
1934 goto done;
1936 if (worktree) {
1937 worktree_conf = got_worktree_get_gotconfig(worktree);
1938 if (worktree_conf) {
1939 got_gotconfig_get_remotes(&nremotes, &remotes,
1940 worktree_conf);
1941 for (i = 0; i < nremotes; i++) {
1942 remote = &remotes[i];
1943 if (strcmp(remote->name, remote_name) == 0)
1944 break;
1948 if (remote == NULL) {
1949 repo_conf = got_repo_get_gotconfig(repo);
1950 if (repo_conf) {
1951 got_gotconfig_get_remotes(&nremotes, &remotes,
1952 repo_conf);
1953 for (i = 0; i < nremotes; i++) {
1954 remote = &remotes[i];
1955 if (strcmp(remote->name, remote_name) == 0)
1956 break;
1960 if (remote == NULL) {
1961 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
1962 for (i = 0; i < nremotes; i++) {
1963 remote = &remotes[i];
1964 if (strcmp(remote->name, remote_name) == 0)
1965 break;
1968 if (remote == NULL) {
1969 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
1970 goto done;
1973 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1974 &repo_name, remote->url);
1975 if (error)
1976 goto done;
1978 if (strcmp(proto, "git") == 0) {
1979 #ifndef PROFILE
1980 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1981 "sendfd dns inet unveil", NULL) == -1)
1982 err(1, "pledge");
1983 #endif
1984 } else if (strcmp(proto, "git+ssh") == 0 ||
1985 strcmp(proto, "ssh") == 0) {
1986 #ifndef PROFILE
1987 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1988 "sendfd unveil", NULL) == -1)
1989 err(1, "pledge");
1990 #endif
1991 } else if (strcmp(proto, "http") == 0 ||
1992 strcmp(proto, "git+http") == 0) {
1993 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1994 goto done;
1995 } else {
1996 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1997 goto done;
2000 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
2001 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
2002 error = got_error_from_errno2("unveil",
2003 GOT_FETCH_PATH_SSH);
2004 goto done;
2007 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2008 if (error)
2009 goto done;
2011 if (verbosity >= 0)
2012 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2013 port ? ":" : "", port ? port : "");
2015 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2016 server_path, verbosity);
2017 if (error)
2018 goto done;
2020 fpa.last_scaled_size[0] = '\0';
2021 fpa.last_p_indexed = -1;
2022 fpa.last_p_resolved = -1;
2023 fpa.verbosity = verbosity;
2024 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2025 remote->mirror_references, fetch_all_branches, &wanted_branches,
2026 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2027 fetch_progress, &fpa);
2028 if (error)
2029 goto done;
2031 if (list_refs_only) {
2032 error = list_remote_refs(&symrefs, &refs);
2033 goto done;
2036 if (pack_hash == NULL) {
2037 if (verbosity >= 0)
2038 printf("Already up-to-date\n");
2039 } else if (verbosity >= 0) {
2040 error = got_object_id_str(&id_str, pack_hash);
2041 if (error)
2042 goto done;
2043 printf("\nFetched %s.pack\n", id_str);
2044 free(id_str);
2045 id_str = NULL;
2048 /* Update references provided with the pack file. */
2049 TAILQ_FOREACH(pe, &refs, entry) {
2050 const char *refname = pe->path;
2051 struct got_object_id *id = pe->data;
2052 struct got_reference *ref;
2053 char *remote_refname;
2055 if (is_wanted_ref(&wanted_refs, refname) &&
2056 !remote->mirror_references) {
2057 error = update_wanted_ref(refname, id,
2058 remote->name, verbosity, repo);
2059 if (error)
2060 goto done;
2061 continue;
2064 if (remote->mirror_references ||
2065 strncmp("refs/tags/", refname, 10) == 0) {
2066 error = got_ref_open(&ref, repo, refname, 1);
2067 if (error) {
2068 if (error->code != GOT_ERR_NOT_REF)
2069 goto done;
2070 error = create_ref(refname, id, verbosity,
2071 repo);
2072 if (error)
2073 goto done;
2074 } else {
2075 error = update_ref(ref, id, replace_tags,
2076 verbosity, repo);
2077 unlock_err = got_ref_unlock(ref);
2078 if (unlock_err && error == NULL)
2079 error = unlock_err;
2080 got_ref_close(ref);
2081 if (error)
2082 goto done;
2084 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2085 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2086 remote_name, refname + 11) == -1) {
2087 error = got_error_from_errno("asprintf");
2088 goto done;
2091 error = got_ref_open(&ref, repo, remote_refname, 1);
2092 if (error) {
2093 if (error->code != GOT_ERR_NOT_REF)
2094 goto done;
2095 error = create_ref(remote_refname, id,
2096 verbosity, repo);
2097 if (error)
2098 goto done;
2099 } else {
2100 error = update_ref(ref, id, replace_tags,
2101 verbosity, repo);
2102 unlock_err = got_ref_unlock(ref);
2103 if (unlock_err && error == NULL)
2104 error = unlock_err;
2105 got_ref_close(ref);
2106 if (error)
2107 goto done;
2110 /* Also create a local branch if none exists yet. */
2111 error = got_ref_open(&ref, repo, refname, 1);
2112 if (error) {
2113 if (error->code != GOT_ERR_NOT_REF)
2114 goto done;
2115 error = create_ref(refname, id, verbosity,
2116 repo);
2117 if (error)
2118 goto done;
2119 } else {
2120 unlock_err = got_ref_unlock(ref);
2121 if (unlock_err && error == NULL)
2122 error = unlock_err;
2123 got_ref_close(ref);
2127 if (delete_refs) {
2128 error = delete_missing_refs(&refs, &symrefs, remote,
2129 verbosity, repo);
2130 if (error)
2131 goto done;
2134 if (!remote->mirror_references) {
2135 /* Update remote HEAD reference if the server provided one. */
2136 TAILQ_FOREACH(pe, &symrefs, entry) {
2137 struct got_reference *target_ref;
2138 const char *refname = pe->path;
2139 const char *target = pe->data;
2140 char *remote_refname = NULL, *remote_target = NULL;
2142 if (strcmp(refname, GOT_REF_HEAD) != 0)
2143 continue;
2145 if (strncmp("refs/heads/", target, 11) != 0)
2146 continue;
2148 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2149 remote->name, refname) == -1) {
2150 error = got_error_from_errno("asprintf");
2151 goto done;
2153 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2154 remote->name, target + 11) == -1) {
2155 error = got_error_from_errno("asprintf");
2156 free(remote_refname);
2157 goto done;
2160 error = got_ref_open(&target_ref, repo, remote_target,
2161 0);
2162 if (error) {
2163 free(remote_refname);
2164 free(remote_target);
2165 if (error->code == GOT_ERR_NOT_REF) {
2166 error = NULL;
2167 continue;
2169 goto done;
2171 error = update_symref(remote_refname, target_ref,
2172 verbosity, repo);
2173 free(remote_refname);
2174 free(remote_target);
2175 got_ref_close(target_ref);
2176 if (error)
2177 goto done;
2180 done:
2181 if (fetchpid > 0) {
2182 if (kill(fetchpid, SIGTERM) == -1)
2183 error = got_error_from_errno("kill");
2184 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2185 error = got_error_from_errno("waitpid");
2187 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2188 error = got_error_from_errno("close");
2189 if (repo)
2190 got_repo_close(repo);
2191 if (worktree)
2192 got_worktree_close(worktree);
2193 TAILQ_FOREACH(pe, &refs, entry) {
2194 free((void *)pe->path);
2195 free(pe->data);
2197 got_pathlist_free(&refs);
2198 TAILQ_FOREACH(pe, &symrefs, entry) {
2199 free((void *)pe->path);
2200 free(pe->data);
2202 got_pathlist_free(&symrefs);
2203 got_pathlist_free(&wanted_branches);
2204 got_pathlist_free(&wanted_refs);
2205 free(id_str);
2206 free(cwd);
2207 free(repo_path);
2208 free(pack_hash);
2209 free(proto);
2210 free(host);
2211 free(port);
2212 free(server_path);
2213 free(repo_name);
2214 return error;
2218 __dead static void
2219 usage_checkout(void)
2221 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2222 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2223 exit(1);
2226 static void
2227 show_worktree_base_ref_warning(void)
2229 fprintf(stderr, "%s: warning: could not create a reference "
2230 "to the work tree's base commit; the commit could be "
2231 "garbage-collected by Git; making the repository "
2232 "writable and running 'got update' will prevent this\n",
2233 getprogname());
2236 struct got_checkout_progress_arg {
2237 const char *worktree_path;
2238 int had_base_commit_ref_error;
2241 static const struct got_error *
2242 checkout_progress(void *arg, unsigned char status, const char *path)
2244 struct got_checkout_progress_arg *a = arg;
2246 /* Base commit bump happens silently. */
2247 if (status == GOT_STATUS_BUMP_BASE)
2248 return NULL;
2250 if (status == GOT_STATUS_BASE_REF_ERR) {
2251 a->had_base_commit_ref_error = 1;
2252 return NULL;
2255 while (path[0] == '/')
2256 path++;
2258 printf("%c %s/%s\n", status, a->worktree_path, path);
2259 return NULL;
2262 static const struct got_error *
2263 check_cancelled(void *arg)
2265 if (sigint_received || sigpipe_received)
2266 return got_error(GOT_ERR_CANCELLED);
2267 return NULL;
2270 static const struct got_error *
2271 check_linear_ancestry(struct got_object_id *commit_id,
2272 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2273 struct got_repository *repo)
2275 const struct got_error *err = NULL;
2276 struct got_object_id *yca_id;
2278 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2279 commit_id, base_commit_id, repo, check_cancelled, NULL);
2280 if (err)
2281 return err;
2283 if (yca_id == NULL)
2284 return got_error(GOT_ERR_ANCESTRY);
2287 * Require a straight line of history between the target commit
2288 * and the work tree's base commit.
2290 * Non-linear situations such as this require a rebase:
2292 * (commit) D F (base_commit)
2293 * \ /
2294 * C E
2295 * \ /
2296 * B (yca)
2297 * |
2298 * A
2300 * 'got update' only handles linear cases:
2301 * Update forwards in time: A (base/yca) - B - C - D (commit)
2302 * Update backwards in time: D (base) - C - B - A (commit/yca)
2304 if (allow_forwards_in_time_only) {
2305 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2306 return got_error(GOT_ERR_ANCESTRY);
2307 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2308 got_object_id_cmp(base_commit_id, yca_id) != 0)
2309 return got_error(GOT_ERR_ANCESTRY);
2311 free(yca_id);
2312 return NULL;
2315 static const struct got_error *
2316 check_same_branch(struct got_object_id *commit_id,
2317 struct got_reference *head_ref, struct got_object_id *yca_id,
2318 struct got_repository *repo)
2320 const struct got_error *err = NULL;
2321 struct got_commit_graph *graph = NULL;
2322 struct got_object_id *head_commit_id = NULL;
2323 int is_same_branch = 0;
2325 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2326 if (err)
2327 goto done;
2329 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2330 is_same_branch = 1;
2331 goto done;
2333 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2334 is_same_branch = 1;
2335 goto done;
2338 err = got_commit_graph_open(&graph, "/", 1);
2339 if (err)
2340 goto done;
2342 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2343 check_cancelled, NULL);
2344 if (err)
2345 goto done;
2347 for (;;) {
2348 struct got_object_id *id;
2349 err = got_commit_graph_iter_next(&id, graph, repo,
2350 check_cancelled, NULL);
2351 if (err) {
2352 if (err->code == GOT_ERR_ITER_COMPLETED)
2353 err = NULL;
2354 break;
2357 if (id) {
2358 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2359 break;
2360 if (got_object_id_cmp(id, commit_id) == 0) {
2361 is_same_branch = 1;
2362 break;
2366 done:
2367 if (graph)
2368 got_commit_graph_close(graph);
2369 free(head_commit_id);
2370 if (!err && !is_same_branch)
2371 err = got_error(GOT_ERR_ANCESTRY);
2372 return err;
2375 static const struct got_error *
2376 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2378 static char msg[512];
2379 const char *branch_name;
2381 if (got_ref_is_symbolic(ref))
2382 branch_name = got_ref_get_symref_target(ref);
2383 else
2384 branch_name = got_ref_get_name(ref);
2386 if (strncmp("refs/heads/", branch_name, 11) == 0)
2387 branch_name += 11;
2389 snprintf(msg, sizeof(msg),
2390 "target commit is not contained in branch '%s'; "
2391 "the branch to use must be specified with -b; "
2392 "if necessary a new branch can be created for "
2393 "this commit with 'got branch -c %s BRANCH_NAME'",
2394 branch_name, commit_id_str);
2396 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2399 static const struct got_error *
2400 cmd_checkout(int argc, char *argv[])
2402 const struct got_error *error = NULL;
2403 struct got_repository *repo = NULL;
2404 struct got_reference *head_ref = NULL;
2405 struct got_worktree *worktree = NULL;
2406 char *repo_path = NULL;
2407 char *worktree_path = NULL;
2408 const char *path_prefix = "";
2409 const char *branch_name = GOT_REF_HEAD;
2410 char *commit_id_str = NULL;
2411 char *cwd = NULL, *path = NULL;
2412 int ch, same_path_prefix, allow_nonempty = 0;
2413 struct got_pathlist_head paths;
2414 struct got_checkout_progress_arg cpa;
2416 TAILQ_INIT(&paths);
2418 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2419 switch (ch) {
2420 case 'b':
2421 branch_name = optarg;
2422 break;
2423 case 'c':
2424 commit_id_str = strdup(optarg);
2425 if (commit_id_str == NULL)
2426 return got_error_from_errno("strdup");
2427 break;
2428 case 'E':
2429 allow_nonempty = 1;
2430 break;
2431 case 'p':
2432 path_prefix = optarg;
2433 break;
2434 default:
2435 usage_checkout();
2436 /* NOTREACHED */
2440 argc -= optind;
2441 argv += optind;
2443 #ifndef PROFILE
2444 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2445 "unveil", NULL) == -1)
2446 err(1, "pledge");
2447 #endif
2448 if (argc == 1) {
2449 char *base, *dotgit;
2450 repo_path = realpath(argv[0], NULL);
2451 if (repo_path == NULL)
2452 return got_error_from_errno2("realpath", argv[0]);
2453 cwd = getcwd(NULL, 0);
2454 if (cwd == NULL) {
2455 error = got_error_from_errno("getcwd");
2456 goto done;
2458 if (path_prefix[0])
2459 path = strdup(path_prefix);
2460 else
2461 path = strdup(repo_path);
2462 if (path == NULL) {
2463 error = got_error_from_errno("strdup");
2464 goto done;
2466 base = basename(path);
2467 if (base == NULL) {
2468 error = got_error_from_errno2("basename", path);
2469 goto done;
2471 dotgit = strstr(base, ".git");
2472 if (dotgit)
2473 *dotgit = '\0';
2474 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2475 error = got_error_from_errno("asprintf");
2476 goto done;
2478 } else if (argc == 2) {
2479 repo_path = realpath(argv[0], NULL);
2480 if (repo_path == NULL) {
2481 error = got_error_from_errno2("realpath", argv[0]);
2482 goto done;
2484 worktree_path = realpath(argv[1], NULL);
2485 if (worktree_path == NULL) {
2486 if (errno != ENOENT) {
2487 error = got_error_from_errno2("realpath",
2488 argv[1]);
2489 goto done;
2491 worktree_path = strdup(argv[1]);
2492 if (worktree_path == NULL) {
2493 error = got_error_from_errno("strdup");
2494 goto done;
2497 } else
2498 usage_checkout();
2500 got_path_strip_trailing_slashes(repo_path);
2501 got_path_strip_trailing_slashes(worktree_path);
2503 error = got_repo_open(&repo, repo_path, NULL);
2504 if (error != NULL)
2505 goto done;
2507 /* Pre-create work tree path for unveil(2) */
2508 error = got_path_mkdir(worktree_path);
2509 if (error) {
2510 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2511 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2512 goto done;
2513 if (!allow_nonempty &&
2514 !got_path_dir_is_empty(worktree_path)) {
2515 error = got_error_path(worktree_path,
2516 GOT_ERR_DIR_NOT_EMPTY);
2517 goto done;
2521 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2522 if (error)
2523 goto done;
2525 error = got_ref_open(&head_ref, repo, branch_name, 0);
2526 if (error != NULL)
2527 goto done;
2529 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2530 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2531 goto done;
2533 error = got_worktree_open(&worktree, worktree_path);
2534 if (error != NULL)
2535 goto done;
2537 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2538 path_prefix);
2539 if (error != NULL)
2540 goto done;
2541 if (!same_path_prefix) {
2542 error = got_error(GOT_ERR_PATH_PREFIX);
2543 goto done;
2546 if (commit_id_str) {
2547 struct got_object_id *commit_id;
2548 error = got_repo_match_object_id(&commit_id, NULL,
2549 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2550 if (error)
2551 goto done;
2552 error = check_linear_ancestry(commit_id,
2553 got_worktree_get_base_commit_id(worktree), 0, repo);
2554 if (error != NULL) {
2555 free(commit_id);
2556 if (error->code == GOT_ERR_ANCESTRY) {
2557 error = checkout_ancestry_error(
2558 head_ref, commit_id_str);
2560 goto done;
2562 error = check_same_branch(commit_id, head_ref, NULL, repo);
2563 if (error) {
2564 if (error->code == GOT_ERR_ANCESTRY) {
2565 error = checkout_ancestry_error(
2566 head_ref, commit_id_str);
2568 goto done;
2570 error = got_worktree_set_base_commit_id(worktree, repo,
2571 commit_id);
2572 free(commit_id);
2573 if (error)
2574 goto done;
2577 error = got_pathlist_append(&paths, "", NULL);
2578 if (error)
2579 goto done;
2580 cpa.worktree_path = worktree_path;
2581 cpa.had_base_commit_ref_error = 0;
2582 error = got_worktree_checkout_files(worktree, &paths, repo,
2583 checkout_progress, &cpa, check_cancelled, NULL);
2584 if (error != NULL)
2585 goto done;
2587 printf("Now shut up and hack\n");
2588 if (cpa.had_base_commit_ref_error)
2589 show_worktree_base_ref_warning();
2590 done:
2591 got_pathlist_free(&paths);
2592 free(commit_id_str);
2593 free(repo_path);
2594 free(worktree_path);
2595 free(cwd);
2596 free(path);
2597 return error;
2600 struct got_update_progress_arg {
2601 int did_something;
2602 int conflicts;
2603 int obstructed;
2604 int not_updated;
2607 void
2608 print_update_progress_stats(struct got_update_progress_arg *upa)
2610 if (!upa->did_something)
2611 return;
2613 if (upa->conflicts > 0)
2614 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2615 if (upa->obstructed > 0)
2616 printf("File paths obstructed by a non-regular file: %d\n",
2617 upa->obstructed);
2618 if (upa->not_updated > 0)
2619 printf("Files not updated because of existing merge "
2620 "conflicts: %d\n", upa->not_updated);
2623 __dead static void
2624 usage_update(void)
2626 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2627 getprogname());
2628 exit(1);
2631 static const struct got_error *
2632 update_progress(void *arg, unsigned char status, const char *path)
2634 struct got_update_progress_arg *upa = arg;
2636 if (status == GOT_STATUS_EXISTS ||
2637 status == GOT_STATUS_BASE_REF_ERR)
2638 return NULL;
2640 upa->did_something = 1;
2642 /* Base commit bump happens silently. */
2643 if (status == GOT_STATUS_BUMP_BASE)
2644 return NULL;
2646 if (status == GOT_STATUS_CONFLICT)
2647 upa->conflicts++;
2648 if (status == GOT_STATUS_OBSTRUCTED)
2649 upa->obstructed++;
2650 if (status == GOT_STATUS_CANNOT_UPDATE)
2651 upa->not_updated++;
2653 while (path[0] == '/')
2654 path++;
2655 printf("%c %s\n", status, path);
2656 return NULL;
2659 static const struct got_error *
2660 switch_head_ref(struct got_reference *head_ref,
2661 struct got_object_id *commit_id, struct got_worktree *worktree,
2662 struct got_repository *repo)
2664 const struct got_error *err = NULL;
2665 char *base_id_str;
2666 int ref_has_moved = 0;
2668 /* Trivial case: switching between two different references. */
2669 if (strcmp(got_ref_get_name(head_ref),
2670 got_worktree_get_head_ref_name(worktree)) != 0) {
2671 printf("Switching work tree from %s to %s\n",
2672 got_worktree_get_head_ref_name(worktree),
2673 got_ref_get_name(head_ref));
2674 return got_worktree_set_head_ref(worktree, head_ref);
2677 err = check_linear_ancestry(commit_id,
2678 got_worktree_get_base_commit_id(worktree), 0, repo);
2679 if (err) {
2680 if (err->code != GOT_ERR_ANCESTRY)
2681 return err;
2682 ref_has_moved = 1;
2684 if (!ref_has_moved)
2685 return NULL;
2687 /* Switching to a rebased branch with the same reference name. */
2688 err = got_object_id_str(&base_id_str,
2689 got_worktree_get_base_commit_id(worktree));
2690 if (err)
2691 return err;
2692 printf("Reference %s now points at a different branch\n",
2693 got_worktree_get_head_ref_name(worktree));
2694 printf("Switching work tree from %s to %s\n", base_id_str,
2695 got_worktree_get_head_ref_name(worktree));
2696 return NULL;
2699 static const struct got_error *
2700 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2702 const struct got_error *err;
2703 int in_progress;
2705 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2706 if (err)
2707 return err;
2708 if (in_progress)
2709 return got_error(GOT_ERR_REBASING);
2711 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2712 if (err)
2713 return err;
2714 if (in_progress)
2715 return got_error(GOT_ERR_HISTEDIT_BUSY);
2717 return NULL;
2720 static const struct got_error *
2721 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2722 char *argv[], struct got_worktree *worktree)
2724 const struct got_error *err = NULL;
2725 char *path;
2726 int i;
2728 if (argc == 0) {
2729 path = strdup("");
2730 if (path == NULL)
2731 return got_error_from_errno("strdup");
2732 return got_pathlist_append(paths, path, NULL);
2735 for (i = 0; i < argc; i++) {
2736 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2737 if (err)
2738 break;
2739 err = got_pathlist_append(paths, path, NULL);
2740 if (err) {
2741 free(path);
2742 break;
2746 return err;
2749 static const struct got_error *
2750 wrap_not_worktree_error(const struct got_error *orig_err,
2751 const char *cmdname, const char *path)
2753 const struct got_error *err;
2754 struct got_repository *repo;
2755 static char msg[512];
2757 err = got_repo_open(&repo, path, NULL);
2758 if (err)
2759 return orig_err;
2761 snprintf(msg, sizeof(msg),
2762 "'got %s' needs a work tree in addition to a git repository\n"
2763 "Work trees can be checked out from this Git repository with "
2764 "'got checkout'.\n"
2765 "The got(1) manual page contains more information.", cmdname);
2766 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2767 got_repo_close(repo);
2768 return err;
2771 static const struct got_error *
2772 cmd_update(int argc, char *argv[])
2774 const struct got_error *error = NULL;
2775 struct got_repository *repo = NULL;
2776 struct got_worktree *worktree = NULL;
2777 char *worktree_path = NULL;
2778 struct got_object_id *commit_id = NULL;
2779 char *commit_id_str = NULL;
2780 const char *branch_name = NULL;
2781 struct got_reference *head_ref = NULL;
2782 struct got_pathlist_head paths;
2783 struct got_pathlist_entry *pe;
2784 int ch;
2785 struct got_update_progress_arg upa;
2787 TAILQ_INIT(&paths);
2789 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2790 switch (ch) {
2791 case 'b':
2792 branch_name = optarg;
2793 break;
2794 case 'c':
2795 commit_id_str = strdup(optarg);
2796 if (commit_id_str == NULL)
2797 return got_error_from_errno("strdup");
2798 break;
2799 default:
2800 usage_update();
2801 /* NOTREACHED */
2805 argc -= optind;
2806 argv += optind;
2808 #ifndef PROFILE
2809 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2810 "unveil", NULL) == -1)
2811 err(1, "pledge");
2812 #endif
2813 worktree_path = getcwd(NULL, 0);
2814 if (worktree_path == NULL) {
2815 error = got_error_from_errno("getcwd");
2816 goto done;
2818 error = got_worktree_open(&worktree, worktree_path);
2819 if (error) {
2820 if (error->code == GOT_ERR_NOT_WORKTREE)
2821 error = wrap_not_worktree_error(error, "update",
2822 worktree_path);
2823 goto done;
2826 error = check_rebase_or_histedit_in_progress(worktree);
2827 if (error)
2828 goto done;
2830 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
2831 NULL);
2832 if (error != NULL)
2833 goto done;
2835 error = apply_unveil(got_repo_get_path(repo), 0,
2836 got_worktree_get_root_path(worktree));
2837 if (error)
2838 goto done;
2840 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2841 if (error)
2842 goto done;
2844 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
2845 got_worktree_get_head_ref_name(worktree), 0);
2846 if (error != NULL)
2847 goto done;
2848 if (commit_id_str == NULL) {
2849 error = got_ref_resolve(&commit_id, repo, head_ref);
2850 if (error != NULL)
2851 goto done;
2852 error = got_object_id_str(&commit_id_str, commit_id);
2853 if (error != NULL)
2854 goto done;
2855 } else {
2856 error = got_repo_match_object_id(&commit_id, NULL,
2857 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2858 free(commit_id_str);
2859 commit_id_str = NULL;
2860 if (error)
2861 goto done;
2862 error = got_object_id_str(&commit_id_str, commit_id);
2863 if (error)
2864 goto done;
2867 if (branch_name) {
2868 struct got_object_id *head_commit_id;
2869 TAILQ_FOREACH(pe, &paths, entry) {
2870 if (pe->path_len == 0)
2871 continue;
2872 error = got_error_msg(GOT_ERR_BAD_PATH,
2873 "switching between branches requires that "
2874 "the entire work tree gets updated");
2875 goto done;
2877 error = got_ref_resolve(&head_commit_id, repo, head_ref);
2878 if (error)
2879 goto done;
2880 error = check_linear_ancestry(commit_id, head_commit_id, 0,
2881 repo);
2882 free(head_commit_id);
2883 if (error != NULL)
2884 goto done;
2885 error = check_same_branch(commit_id, head_ref, NULL, repo);
2886 if (error)
2887 goto done;
2888 error = switch_head_ref(head_ref, commit_id, worktree, repo);
2889 if (error)
2890 goto done;
2891 } else {
2892 error = check_linear_ancestry(commit_id,
2893 got_worktree_get_base_commit_id(worktree), 0, repo);
2894 if (error != NULL) {
2895 if (error->code == GOT_ERR_ANCESTRY)
2896 error = got_error(GOT_ERR_BRANCH_MOVED);
2897 goto done;
2899 error = check_same_branch(commit_id, head_ref, NULL, repo);
2900 if (error)
2901 goto done;
2904 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
2905 commit_id) != 0) {
2906 error = got_worktree_set_base_commit_id(worktree, repo,
2907 commit_id);
2908 if (error)
2909 goto done;
2912 memset(&upa, 0, sizeof(upa));
2913 error = got_worktree_checkout_files(worktree, &paths, repo,
2914 update_progress, &upa, check_cancelled, NULL);
2915 if (error != NULL)
2916 goto done;
2918 if (upa.did_something)
2919 printf("Updated to commit %s\n", commit_id_str);
2920 else
2921 printf("Already up-to-date\n");
2922 print_update_progress_stats(&upa);
2923 done:
2924 free(worktree_path);
2925 TAILQ_FOREACH(pe, &paths, entry)
2926 free((char *)pe->path);
2927 got_pathlist_free(&paths);
2928 free(commit_id);
2929 free(commit_id_str);
2930 return error;
2933 static const struct got_error *
2934 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
2935 const char *path, int diff_context, int ignore_whitespace,
2936 struct got_repository *repo)
2938 const struct got_error *err = NULL;
2939 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
2941 if (blob_id1) {
2942 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
2943 if (err)
2944 goto done;
2947 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
2948 if (err)
2949 goto done;
2951 while (path[0] == '/')
2952 path++;
2953 err = got_diff_blob(blob1, blob2, path, path, diff_context,
2954 ignore_whitespace, stdout);
2955 done:
2956 if (blob1)
2957 got_object_blob_close(blob1);
2958 got_object_blob_close(blob2);
2959 return err;
2962 static const struct got_error *
2963 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
2964 const char *path, int diff_context, int ignore_whitespace,
2965 struct got_repository *repo)
2967 const struct got_error *err = NULL;
2968 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
2969 struct got_diff_blob_output_unidiff_arg arg;
2971 if (tree_id1) {
2972 err = got_object_open_as_tree(&tree1, repo, tree_id1);
2973 if (err)
2974 goto done;
2977 err = got_object_open_as_tree(&tree2, repo, tree_id2);
2978 if (err)
2979 goto done;
2981 arg.diff_context = diff_context;
2982 arg.ignore_whitespace = ignore_whitespace;
2983 arg.outfile = stdout;
2984 while (path[0] == '/')
2985 path++;
2986 err = got_diff_tree(tree1, tree2, path, path, repo,
2987 got_diff_blob_output_unidiff, &arg, 1);
2988 done:
2989 if (tree1)
2990 got_object_tree_close(tree1);
2991 if (tree2)
2992 got_object_tree_close(tree2);
2993 return err;
2996 static const struct got_error *
2997 get_changed_paths(struct got_pathlist_head *paths,
2998 struct got_commit_object *commit, struct got_repository *repo)
3000 const struct got_error *err = NULL;
3001 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3002 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3003 struct got_object_qid *qid;
3005 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3006 if (qid != NULL) {
3007 struct got_commit_object *pcommit;
3008 err = got_object_open_as_commit(&pcommit, repo,
3009 qid->id);
3010 if (err)
3011 return err;
3013 tree_id1 = got_object_commit_get_tree_id(pcommit);
3014 got_object_commit_close(pcommit);
3018 if (tree_id1) {
3019 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3020 if (err)
3021 goto done;
3024 tree_id2 = got_object_commit_get_tree_id(commit);
3025 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3026 if (err)
3027 goto done;
3029 err = got_diff_tree(tree1, tree2, "", "", repo,
3030 got_diff_tree_collect_changed_paths, paths, 0);
3031 done:
3032 if (tree1)
3033 got_object_tree_close(tree1);
3034 if (tree2)
3035 got_object_tree_close(tree2);
3036 return err;
3039 static const struct got_error *
3040 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3041 const char *path, int diff_context, struct got_repository *repo)
3043 const struct got_error *err = NULL;
3044 struct got_commit_object *pcommit = NULL;
3045 char *id_str1 = NULL, *id_str2 = NULL;
3046 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3047 struct got_object_qid *qid;
3049 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3050 if (qid != NULL) {
3051 err = got_object_open_as_commit(&pcommit, repo,
3052 qid->id);
3053 if (err)
3054 return err;
3057 if (path && path[0] != '\0') {
3058 int obj_type;
3059 err = got_object_id_by_path(&obj_id2, repo, id, path);
3060 if (err)
3061 goto done;
3062 err = got_object_id_str(&id_str2, obj_id2);
3063 if (err) {
3064 free(obj_id2);
3065 goto done;
3067 if (pcommit) {
3068 err = got_object_id_by_path(&obj_id1, repo,
3069 qid->id, path);
3070 if (err) {
3071 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3072 free(obj_id2);
3073 goto done;
3075 } else {
3076 err = got_object_id_str(&id_str1, obj_id1);
3077 if (err) {
3078 free(obj_id2);
3079 goto done;
3083 err = got_object_get_type(&obj_type, repo, obj_id2);
3084 if (err) {
3085 free(obj_id2);
3086 goto done;
3088 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3089 switch (obj_type) {
3090 case GOT_OBJ_TYPE_BLOB:
3091 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3092 0, repo);
3093 break;
3094 case GOT_OBJ_TYPE_TREE:
3095 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3096 0, repo);
3097 break;
3098 default:
3099 err = got_error(GOT_ERR_OBJ_TYPE);
3100 break;
3102 free(obj_id1);
3103 free(obj_id2);
3104 } else {
3105 obj_id2 = got_object_commit_get_tree_id(commit);
3106 err = got_object_id_str(&id_str2, obj_id2);
3107 if (err)
3108 goto done;
3109 obj_id1 = got_object_commit_get_tree_id(pcommit);
3110 err = got_object_id_str(&id_str1, obj_id1);
3111 if (err)
3112 goto done;
3113 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3114 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
3116 done:
3117 free(id_str1);
3118 free(id_str2);
3119 if (pcommit)
3120 got_object_commit_close(pcommit);
3121 return err;
3124 static char *
3125 get_datestr(time_t *time, char *datebuf)
3127 struct tm mytm, *tm;
3128 char *p, *s;
3130 tm = gmtime_r(time, &mytm);
3131 if (tm == NULL)
3132 return NULL;
3133 s = asctime_r(tm, datebuf);
3134 if (s == NULL)
3135 return NULL;
3136 p = strchr(s, '\n');
3137 if (p)
3138 *p = '\0';
3139 return s;
3142 static const struct got_error *
3143 match_logmsg(int *have_match, struct got_object_id *id,
3144 struct got_commit_object *commit, regex_t *regex)
3146 const struct got_error *err = NULL;
3147 regmatch_t regmatch;
3148 char *id_str = NULL, *logmsg = NULL;
3150 *have_match = 0;
3152 err = got_object_id_str(&id_str, id);
3153 if (err)
3154 return err;
3156 err = got_object_commit_get_logmsg(&logmsg, commit);
3157 if (err)
3158 goto done;
3160 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3161 *have_match = 1;
3162 done:
3163 free(id_str);
3164 free(logmsg);
3165 return err;
3168 static void
3169 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3170 regex_t *regex)
3172 regmatch_t regmatch;
3173 struct got_pathlist_entry *pe;
3175 *have_match = 0;
3177 TAILQ_FOREACH(pe, changed_paths, entry) {
3178 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3179 *have_match = 1;
3180 break;
3185 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3187 static const struct got_error *
3188 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3189 struct got_repository *repo, const char *path,
3190 struct got_pathlist_head *changed_paths, int show_patch,
3191 int diff_context, struct got_reflist_head *refs)
3193 const struct got_error *err = NULL;
3194 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3195 char datebuf[26];
3196 time_t committer_time;
3197 const char *author, *committer;
3198 char *refs_str = NULL;
3199 struct got_reflist_entry *re;
3201 SIMPLEQ_FOREACH(re, refs, entry) {
3202 char *s;
3203 const char *name;
3204 struct got_tag_object *tag = NULL;
3205 struct got_object_id *ref_id;
3206 int cmp;
3208 name = got_ref_get_name(re->ref);
3209 if (strcmp(name, GOT_REF_HEAD) == 0)
3210 continue;
3211 if (strncmp(name, "refs/", 5) == 0)
3212 name += 5;
3213 if (strncmp(name, "got/", 4) == 0)
3214 continue;
3215 if (strncmp(name, "heads/", 6) == 0)
3216 name += 6;
3217 if (strncmp(name, "remotes/", 8) == 0) {
3218 name += 8;
3219 s = strstr(name, "/" GOT_REF_HEAD);
3220 if (s != NULL && s[strlen(s)] == '\0')
3221 continue;
3223 err = got_ref_resolve(&ref_id, repo, re->ref);
3224 if (err)
3225 return err;
3226 if (strncmp(name, "tags/", 5) == 0) {
3227 err = got_object_open_as_tag(&tag, repo, ref_id);
3228 if (err) {
3229 if (err->code != GOT_ERR_OBJ_TYPE) {
3230 free(ref_id);
3231 return err;
3233 /* Ref points at something other than a tag. */
3234 err = NULL;
3235 tag = NULL;
3238 cmp = got_object_id_cmp(tag ?
3239 got_object_tag_get_object_id(tag) : ref_id, id);
3240 free(ref_id);
3241 if (tag)
3242 got_object_tag_close(tag);
3243 if (cmp != 0)
3244 continue;
3245 s = refs_str;
3246 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3247 name) == -1) {
3248 err = got_error_from_errno("asprintf");
3249 free(s);
3250 return err;
3252 free(s);
3254 err = got_object_id_str(&id_str, id);
3255 if (err)
3256 return err;
3258 printf(GOT_COMMIT_SEP_STR);
3259 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3260 refs_str ? refs_str : "", refs_str ? ")" : "");
3261 free(id_str);
3262 id_str = NULL;
3263 free(refs_str);
3264 refs_str = NULL;
3265 printf("from: %s\n", got_object_commit_get_author(commit));
3266 committer_time = got_object_commit_get_committer_time(commit);
3267 datestr = get_datestr(&committer_time, datebuf);
3268 if (datestr)
3269 printf("date: %s UTC\n", datestr);
3270 author = got_object_commit_get_author(commit);
3271 committer = got_object_commit_get_committer(commit);
3272 if (strcmp(author, committer) != 0)
3273 printf("via: %s\n", committer);
3274 if (got_object_commit_get_nparents(commit) > 1) {
3275 const struct got_object_id_queue *parent_ids;
3276 struct got_object_qid *qid;
3277 int n = 1;
3278 parent_ids = got_object_commit_get_parent_ids(commit);
3279 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3280 err = got_object_id_str(&id_str, qid->id);
3281 if (err)
3282 return err;
3283 printf("parent %d: %s\n", n++, id_str);
3284 free(id_str);
3288 err = got_object_commit_get_logmsg(&logmsg0, commit);
3289 if (err)
3290 return err;
3292 logmsg = logmsg0;
3293 do {
3294 line = strsep(&logmsg, "\n");
3295 if (line)
3296 printf(" %s\n", line);
3297 } while (line);
3298 free(logmsg0);
3300 if (changed_paths) {
3301 struct got_pathlist_entry *pe;
3302 TAILQ_FOREACH(pe, changed_paths, entry) {
3303 struct got_diff_changed_path *cp = pe->data;
3304 printf(" %c %s\n", cp->status, pe->path);
3306 printf("\n");
3308 if (show_patch) {
3309 err = print_patch(commit, id, path, diff_context, repo);
3310 if (err == 0)
3311 printf("\n");
3314 if (fflush(stdout) != 0 && err == NULL)
3315 err = got_error_from_errno("fflush");
3316 return err;
3319 static const struct got_error *
3320 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3321 struct got_repository *repo, const char *path, int show_changed_paths,
3322 int show_patch, const char *search_pattern, int diff_context, int limit,
3323 int log_branches, int reverse_display_order, struct got_reflist_head *refs)
3325 const struct got_error *err;
3326 struct got_commit_graph *graph;
3327 regex_t regex;
3328 int have_match;
3329 struct got_object_id_queue reversed_commits;
3330 struct got_object_qid *qid;
3331 struct got_commit_object *commit;
3332 struct got_pathlist_head changed_paths;
3333 struct got_pathlist_entry *pe;
3335 SIMPLEQ_INIT(&reversed_commits);
3336 TAILQ_INIT(&changed_paths);
3338 if (search_pattern && regcomp(&regex, search_pattern,
3339 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3340 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3342 err = got_commit_graph_open(&graph, path, !log_branches);
3343 if (err)
3344 return err;
3345 err = got_commit_graph_iter_start(graph, root_id, repo,
3346 check_cancelled, NULL);
3347 if (err)
3348 goto done;
3349 for (;;) {
3350 struct got_object_id *id;
3352 if (sigint_received || sigpipe_received)
3353 break;
3355 err = got_commit_graph_iter_next(&id, graph, repo,
3356 check_cancelled, NULL);
3357 if (err) {
3358 if (err->code == GOT_ERR_ITER_COMPLETED)
3359 err = NULL;
3360 break;
3362 if (id == NULL)
3363 break;
3365 err = got_object_open_as_commit(&commit, repo, id);
3366 if (err)
3367 break;
3369 if (show_changed_paths && !reverse_display_order) {
3370 err = get_changed_paths(&changed_paths, commit, repo);
3371 if (err)
3372 break;
3375 if (search_pattern) {
3376 err = match_logmsg(&have_match, id, commit, &regex);
3377 if (err) {
3378 got_object_commit_close(commit);
3379 break;
3381 if (have_match == 0 && show_changed_paths)
3382 match_changed_paths(&have_match,
3383 &changed_paths, &regex);
3384 if (have_match == 0) {
3385 got_object_commit_close(commit);
3386 TAILQ_FOREACH(pe, &changed_paths, entry) {
3387 free((char *)pe->path);
3388 free(pe->data);
3390 got_pathlist_free(&changed_paths);
3391 continue;
3395 if (reverse_display_order) {
3396 err = got_object_qid_alloc(&qid, id);
3397 if (err)
3398 break;
3399 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3400 got_object_commit_close(commit);
3401 } else {
3402 err = print_commit(commit, id, repo, path,
3403 show_changed_paths ? &changed_paths : NULL,
3404 show_patch, diff_context, refs);
3405 got_object_commit_close(commit);
3406 if (err)
3407 break;
3409 if ((limit && --limit == 0) ||
3410 (end_id && got_object_id_cmp(id, end_id) == 0))
3411 break;
3413 TAILQ_FOREACH(pe, &changed_paths, entry) {
3414 free((char *)pe->path);
3415 free(pe->data);
3417 got_pathlist_free(&changed_paths);
3419 if (reverse_display_order) {
3420 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3421 err = got_object_open_as_commit(&commit, repo, qid->id);
3422 if (err)
3423 break;
3424 if (show_changed_paths) {
3425 err = get_changed_paths(&changed_paths,
3426 commit, repo);
3427 if (err)
3428 break;
3430 err = print_commit(commit, qid->id, repo, path,
3431 show_changed_paths ? &changed_paths : NULL,
3432 show_patch, diff_context, refs);
3433 got_object_commit_close(commit);
3434 if (err)
3435 break;
3436 TAILQ_FOREACH(pe, &changed_paths, entry) {
3437 free((char *)pe->path);
3438 free(pe->data);
3440 got_pathlist_free(&changed_paths);
3443 done:
3444 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3445 qid = SIMPLEQ_FIRST(&reversed_commits);
3446 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3447 got_object_qid_free(qid);
3449 TAILQ_FOREACH(pe, &changed_paths, entry) {
3450 free((char *)pe->path);
3451 free(pe->data);
3453 got_pathlist_free(&changed_paths);
3454 if (search_pattern)
3455 regfree(&regex);
3456 got_commit_graph_close(graph);
3457 return err;
3460 __dead static void
3461 usage_log(void)
3463 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3464 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3465 "[-R] [path]\n", getprogname());
3466 exit(1);
3469 static int
3470 get_default_log_limit(void)
3472 const char *got_default_log_limit;
3473 long long n;
3474 const char *errstr;
3476 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3477 if (got_default_log_limit == NULL)
3478 return 0;
3479 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3480 if (errstr != NULL)
3481 return 0;
3482 return n;
3485 static const struct got_error *
3486 resolve_commit_arg(struct got_object_id **id, const char *commit_arg,
3487 struct got_repository *repo)
3489 const struct got_error *err = NULL;
3490 struct got_reference *ref;
3492 *id = NULL;
3494 err = got_ref_open(&ref, repo, commit_arg, 0);
3495 if (err == NULL) {
3496 int obj_type;
3497 err = got_ref_resolve(id, repo, ref);
3498 got_ref_close(ref);
3499 if (err)
3500 return err;
3501 err = got_object_get_type(&obj_type, repo, *id);
3502 if (err)
3503 return err;
3504 if (obj_type == GOT_OBJ_TYPE_TAG) {
3505 struct got_tag_object *tag;
3506 err = got_object_open_as_tag(&tag, repo, *id);
3507 if (err)
3508 return err;
3509 if (got_object_tag_get_object_type(tag) !=
3510 GOT_OBJ_TYPE_COMMIT) {
3511 got_object_tag_close(tag);
3512 return got_error(GOT_ERR_OBJ_TYPE);
3514 free(*id);
3515 *id = got_object_id_dup(
3516 got_object_tag_get_object_id(tag));
3517 if (*id == NULL)
3518 err = got_error_from_errno(
3519 "got_object_id_dup");
3520 got_object_tag_close(tag);
3521 if (err)
3522 return err;
3523 } else if (obj_type != GOT_OBJ_TYPE_COMMIT)
3524 return got_error(GOT_ERR_OBJ_TYPE);
3525 } else {
3526 err = got_repo_match_object_id_prefix(id, commit_arg,
3527 GOT_OBJ_TYPE_COMMIT, repo);
3530 return err;
3533 static const struct got_error *
3534 cmd_log(int argc, char *argv[])
3536 const struct got_error *error;
3537 struct got_repository *repo = NULL;
3538 struct got_worktree *worktree = NULL;
3539 struct got_object_id *start_id = NULL, *end_id = NULL;
3540 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3541 const char *start_commit = NULL, *end_commit = NULL;
3542 const char *search_pattern = NULL;
3543 int diff_context = -1, ch;
3544 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3545 int reverse_display_order = 0;
3546 const char *errstr;
3547 struct got_reflist_head refs;
3549 SIMPLEQ_INIT(&refs);
3551 #ifndef PROFILE
3552 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3553 NULL)
3554 == -1)
3555 err(1, "pledge");
3556 #endif
3558 limit = get_default_log_limit();
3560 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3561 switch (ch) {
3562 case 'p':
3563 show_patch = 1;
3564 break;
3565 case 'P':
3566 show_changed_paths = 1;
3567 break;
3568 case 'c':
3569 start_commit = optarg;
3570 break;
3571 case 'C':
3572 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3573 &errstr);
3574 if (errstr != NULL)
3575 err(1, "-C option %s", errstr);
3576 break;
3577 case 'l':
3578 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3579 if (errstr != NULL)
3580 err(1, "-l option %s", errstr);
3581 break;
3582 case 'b':
3583 log_branches = 1;
3584 break;
3585 case 'r':
3586 repo_path = realpath(optarg, NULL);
3587 if (repo_path == NULL)
3588 return got_error_from_errno2("realpath",
3589 optarg);
3590 got_path_strip_trailing_slashes(repo_path);
3591 break;
3592 case 'R':
3593 reverse_display_order = 1;
3594 break;
3595 case 's':
3596 search_pattern = optarg;
3597 break;
3598 case 'x':
3599 end_commit = optarg;
3600 break;
3601 default:
3602 usage_log();
3603 /* NOTREACHED */
3607 argc -= optind;
3608 argv += optind;
3610 if (diff_context == -1)
3611 diff_context = 3;
3612 else if (!show_patch)
3613 errx(1, "-C requires -p");
3615 cwd = getcwd(NULL, 0);
3616 if (cwd == NULL) {
3617 error = got_error_from_errno("getcwd");
3618 goto done;
3621 if (repo_path == NULL) {
3622 error = got_worktree_open(&worktree, cwd);
3623 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3624 goto done;
3625 error = NULL;
3628 if (argc == 0) {
3629 path = strdup("");
3630 if (path == NULL) {
3631 error = got_error_from_errno("strdup");
3632 goto done;
3634 } else if (argc == 1) {
3635 if (worktree) {
3636 error = got_worktree_resolve_path(&path, worktree,
3637 argv[0]);
3638 if (error)
3639 goto done;
3640 } else {
3641 path = strdup(argv[0]);
3642 if (path == NULL) {
3643 error = got_error_from_errno("strdup");
3644 goto done;
3647 } else
3648 usage_log();
3650 if (repo_path == NULL) {
3651 repo_path = worktree ?
3652 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3654 if (repo_path == NULL) {
3655 error = got_error_from_errno("strdup");
3656 goto done;
3659 error = got_repo_open(&repo, repo_path, NULL);
3660 if (error != NULL)
3661 goto done;
3663 error = apply_unveil(got_repo_get_path(repo), 1,
3664 worktree ? got_worktree_get_root_path(worktree) : NULL);
3665 if (error)
3666 goto done;
3668 if (start_commit == NULL) {
3669 struct got_reference *head_ref;
3670 struct got_commit_object *commit = NULL;
3671 error = got_ref_open(&head_ref, repo,
3672 worktree ? got_worktree_get_head_ref_name(worktree)
3673 : GOT_REF_HEAD, 0);
3674 if (error != NULL)
3675 goto done;
3676 error = got_ref_resolve(&start_id, repo, head_ref);
3677 got_ref_close(head_ref);
3678 if (error != NULL)
3679 goto done;
3680 error = got_object_open_as_commit(&commit, repo,
3681 start_id);
3682 if (error != NULL)
3683 goto done;
3684 got_object_commit_close(commit);
3685 } else {
3686 error = resolve_commit_arg(&start_id, start_commit, repo);
3687 if (error != NULL)
3688 goto done;
3690 if (end_commit != NULL) {
3691 error = resolve_commit_arg(&end_id, end_commit, repo);
3692 if (error != NULL)
3693 goto done;
3696 if (worktree) {
3697 const char *prefix = got_worktree_get_path_prefix(worktree);
3698 char *p;
3699 if (asprintf(&p, "%s%s%s", prefix,
3700 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3701 error = got_error_from_errno("asprintf");
3702 goto done;
3704 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3705 free(p);
3706 } else
3707 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3708 if (error != NULL)
3709 goto done;
3710 if (in_repo_path) {
3711 free(path);
3712 path = in_repo_path;
3715 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3716 if (error)
3717 goto done;
3719 error = print_commits(start_id, end_id, repo, path, show_changed_paths,
3720 show_patch, search_pattern, diff_context, limit, log_branches,
3721 reverse_display_order, &refs);
3722 done:
3723 free(path);
3724 free(repo_path);
3725 free(cwd);
3726 if (worktree)
3727 got_worktree_close(worktree);
3728 if (repo) {
3729 const struct got_error *repo_error;
3730 repo_error = got_repo_close(repo);
3731 if (error == NULL)
3732 error = repo_error;
3734 got_ref_list_free(&refs);
3735 return error;
3738 __dead static void
3739 usage_diff(void)
3741 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3742 "[-w] [object1 object2 | path]\n", getprogname());
3743 exit(1);
3746 struct print_diff_arg {
3747 struct got_repository *repo;
3748 struct got_worktree *worktree;
3749 int diff_context;
3750 const char *id_str;
3751 int header_shown;
3752 int diff_staged;
3753 int ignore_whitespace;
3757 * Create a file which contains the target path of a symlink so we can feed
3758 * it as content to the diff engine.
3760 static const struct got_error *
3761 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
3762 const char *abspath)
3764 const struct got_error *err = NULL;
3765 char target_path[PATH_MAX];
3766 ssize_t target_len, outlen;
3768 *fd = -1;
3770 if (dirfd != -1) {
3771 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
3772 if (target_len == -1)
3773 return got_error_from_errno2("readlinkat", abspath);
3774 } else {
3775 target_len = readlink(abspath, target_path, PATH_MAX);
3776 if (target_len == -1)
3777 return got_error_from_errno2("readlink", abspath);
3780 *fd = got_opentempfd();
3781 if (*fd == -1)
3782 return got_error_from_errno("got_opentempfd");
3784 outlen = write(*fd, target_path, target_len);
3785 if (outlen == -1) {
3786 err = got_error_from_errno("got_opentempfd");
3787 goto done;
3790 if (lseek(*fd, 0, SEEK_SET) == -1) {
3791 err = got_error_from_errno2("lseek", abspath);
3792 goto done;
3794 done:
3795 if (err) {
3796 close(*fd);
3797 *fd = -1;
3799 return err;
3802 static const struct got_error *
3803 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3804 const char *path, struct got_object_id *blob_id,
3805 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3806 int dirfd, const char *de_name)
3808 struct print_diff_arg *a = arg;
3809 const struct got_error *err = NULL;
3810 struct got_blob_object *blob1 = NULL;
3811 int fd = -1;
3812 FILE *f2 = NULL;
3813 char *abspath = NULL, *label1 = NULL;
3814 struct stat sb;
3816 if (a->diff_staged) {
3817 if (staged_status != GOT_STATUS_MODIFY &&
3818 staged_status != GOT_STATUS_ADD &&
3819 staged_status != GOT_STATUS_DELETE)
3820 return NULL;
3821 } else {
3822 if (staged_status == GOT_STATUS_DELETE)
3823 return NULL;
3824 if (status == GOT_STATUS_NONEXISTENT)
3825 return got_error_set_errno(ENOENT, path);
3826 if (status != GOT_STATUS_MODIFY &&
3827 status != GOT_STATUS_ADD &&
3828 status != GOT_STATUS_DELETE &&
3829 status != GOT_STATUS_CONFLICT)
3830 return NULL;
3833 if (!a->header_shown) {
3834 printf("diff %s %s%s\n", a->id_str,
3835 got_worktree_get_root_path(a->worktree),
3836 a->diff_staged ? " (staged changes)" : "");
3837 a->header_shown = 1;
3840 if (a->diff_staged) {
3841 const char *label1 = NULL, *label2 = NULL;
3842 switch (staged_status) {
3843 case GOT_STATUS_MODIFY:
3844 label1 = path;
3845 label2 = path;
3846 break;
3847 case GOT_STATUS_ADD:
3848 label2 = path;
3849 break;
3850 case GOT_STATUS_DELETE:
3851 label1 = path;
3852 break;
3853 default:
3854 return got_error(GOT_ERR_FILE_STATUS);
3856 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
3857 label1, label2, a->diff_context, a->ignore_whitespace,
3858 a->repo, stdout);
3861 if (staged_status == GOT_STATUS_ADD ||
3862 staged_status == GOT_STATUS_MODIFY) {
3863 char *id_str;
3864 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
3865 8192);
3866 if (err)
3867 goto done;
3868 err = got_object_id_str(&id_str, staged_blob_id);
3869 if (err)
3870 goto done;
3871 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
3872 err = got_error_from_errno("asprintf");
3873 free(id_str);
3874 goto done;
3876 free(id_str);
3877 } else if (status != GOT_STATUS_ADD) {
3878 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
3879 if (err)
3880 goto done;
3883 if (status != GOT_STATUS_DELETE) {
3884 if (asprintf(&abspath, "%s/%s",
3885 got_worktree_get_root_path(a->worktree), path) == -1) {
3886 err = got_error_from_errno("asprintf");
3887 goto done;
3890 if (dirfd != -1) {
3891 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
3892 if (fd == -1) {
3893 if (errno != ELOOP) {
3894 err = got_error_from_errno2("openat",
3895 abspath);
3896 goto done;
3898 err = get_symlink_target_file(&fd, dirfd,
3899 de_name, abspath);
3900 if (err)
3901 goto done;
3903 } else {
3904 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
3905 if (fd == -1) {
3906 if (errno != ELOOP) {
3907 err = got_error_from_errno2("open",
3908 abspath);
3909 goto done;
3911 err = get_symlink_target_file(&fd, dirfd,
3912 de_name, abspath);
3913 if (err)
3914 goto done;
3917 if (fstat(fd, &sb) == -1) {
3918 err = got_error_from_errno2("fstat", abspath);
3919 goto done;
3921 f2 = fdopen(fd, "r");
3922 if (f2 == NULL) {
3923 err = got_error_from_errno2("fdopen", abspath);
3924 goto done;
3926 fd = -1;
3927 } else
3928 sb.st_size = 0;
3930 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
3931 a->diff_context, a->ignore_whitespace, stdout);
3932 done:
3933 if (blob1)
3934 got_object_blob_close(blob1);
3935 if (f2 && fclose(f2) == EOF && err == NULL)
3936 err = got_error_from_errno("fclose");
3937 if (fd != -1 && close(fd) == -1 && err == NULL)
3938 err = got_error_from_errno("close");
3939 free(abspath);
3940 return err;
3943 static const struct got_error *
3944 cmd_diff(int argc, char *argv[])
3946 const struct got_error *error;
3947 struct got_repository *repo = NULL;
3948 struct got_worktree *worktree = NULL;
3949 char *cwd = NULL, *repo_path = NULL;
3950 struct got_object_id *id1 = NULL, *id2 = NULL;
3951 const char *id_str1 = NULL, *id_str2 = NULL;
3952 char *label1 = NULL, *label2 = NULL;
3953 int type1, type2;
3954 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
3955 const char *errstr;
3956 char *path = NULL;
3958 #ifndef PROFILE
3959 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3960 NULL) == -1)
3961 err(1, "pledge");
3962 #endif
3964 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
3965 switch (ch) {
3966 case 'C':
3967 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3968 &errstr);
3969 if (errstr != NULL)
3970 err(1, "-C option %s", errstr);
3971 break;
3972 case 'r':
3973 repo_path = realpath(optarg, NULL);
3974 if (repo_path == NULL)
3975 return got_error_from_errno2("realpath",
3976 optarg);
3977 got_path_strip_trailing_slashes(repo_path);
3978 break;
3979 case 's':
3980 diff_staged = 1;
3981 break;
3982 case 'w':
3983 ignore_whitespace = 1;
3984 break;
3985 default:
3986 usage_diff();
3987 /* NOTREACHED */
3991 argc -= optind;
3992 argv += optind;
3994 cwd = getcwd(NULL, 0);
3995 if (cwd == NULL) {
3996 error = got_error_from_errno("getcwd");
3997 goto done;
3999 if (argc <= 1) {
4000 if (repo_path)
4001 errx(1,
4002 "-r option can't be used when diffing a work tree");
4003 error = got_worktree_open(&worktree, cwd);
4004 if (error) {
4005 if (error->code == GOT_ERR_NOT_WORKTREE)
4006 error = wrap_not_worktree_error(error, "diff",
4007 cwd);
4008 goto done;
4010 repo_path = strdup(got_worktree_get_repo_path(worktree));
4011 if (repo_path == NULL) {
4012 error = got_error_from_errno("strdup");
4013 goto done;
4015 if (argc == 1) {
4016 error = got_worktree_resolve_path(&path, worktree,
4017 argv[0]);
4018 if (error)
4019 goto done;
4020 } else {
4021 path = strdup("");
4022 if (path == NULL) {
4023 error = got_error_from_errno("strdup");
4024 goto done;
4027 } else if (argc == 2) {
4028 if (diff_staged)
4029 errx(1, "-s option can't be used when diffing "
4030 "objects in repository");
4031 id_str1 = argv[0];
4032 id_str2 = argv[1];
4033 if (repo_path == NULL) {
4034 error = got_worktree_open(&worktree, cwd);
4035 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4036 goto done;
4037 if (worktree) {
4038 repo_path = strdup(
4039 got_worktree_get_repo_path(worktree));
4040 if (repo_path == NULL) {
4041 error = got_error_from_errno("strdup");
4042 goto done;
4044 } else {
4045 repo_path = strdup(cwd);
4046 if (repo_path == NULL) {
4047 error = got_error_from_errno("strdup");
4048 goto done;
4052 } else
4053 usage_diff();
4055 error = got_repo_open(&repo, repo_path, NULL);
4056 free(repo_path);
4057 if (error != NULL)
4058 goto done;
4060 error = apply_unveil(got_repo_get_path(repo), 1,
4061 worktree ? got_worktree_get_root_path(worktree) : NULL);
4062 if (error)
4063 goto done;
4065 if (argc <= 1) {
4066 struct print_diff_arg arg;
4067 struct got_pathlist_head paths;
4068 char *id_str;
4070 TAILQ_INIT(&paths);
4072 error = got_object_id_str(&id_str,
4073 got_worktree_get_base_commit_id(worktree));
4074 if (error)
4075 goto done;
4076 arg.repo = repo;
4077 arg.worktree = worktree;
4078 arg.diff_context = diff_context;
4079 arg.id_str = id_str;
4080 arg.header_shown = 0;
4081 arg.diff_staged = diff_staged;
4082 arg.ignore_whitespace = ignore_whitespace;
4084 error = got_pathlist_append(&paths, path, NULL);
4085 if (error)
4086 goto done;
4088 error = got_worktree_status(worktree, &paths, repo, print_diff,
4089 &arg, check_cancelled, NULL);
4090 free(id_str);
4091 got_pathlist_free(&paths);
4092 goto done;
4095 error = got_repo_match_object_id(&id1, &label1, id_str1,
4096 GOT_OBJ_TYPE_ANY, 1, repo);
4097 if (error)
4098 goto done;
4100 error = got_repo_match_object_id(&id2, &label2, id_str2,
4101 GOT_OBJ_TYPE_ANY, 1, repo);
4102 if (error)
4103 goto done;
4105 error = got_object_get_type(&type1, repo, id1);
4106 if (error)
4107 goto done;
4109 error = got_object_get_type(&type2, repo, id2);
4110 if (error)
4111 goto done;
4113 if (type1 != type2) {
4114 error = got_error(GOT_ERR_OBJ_TYPE);
4115 goto done;
4118 switch (type1) {
4119 case GOT_OBJ_TYPE_BLOB:
4120 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
4121 diff_context, ignore_whitespace, repo, stdout);
4122 break;
4123 case GOT_OBJ_TYPE_TREE:
4124 error = got_diff_objects_as_trees(id1, id2, "", "",
4125 diff_context, ignore_whitespace, repo, stdout);
4126 break;
4127 case GOT_OBJ_TYPE_COMMIT:
4128 printf("diff %s %s\n", label1, label2);
4129 error = got_diff_objects_as_commits(id1, id2, diff_context,
4130 ignore_whitespace, repo, stdout);
4131 break;
4132 default:
4133 error = got_error(GOT_ERR_OBJ_TYPE);
4135 done:
4136 free(label1);
4137 free(label2);
4138 free(id1);
4139 free(id2);
4140 free(path);
4141 if (worktree)
4142 got_worktree_close(worktree);
4143 if (repo) {
4144 const struct got_error *repo_error;
4145 repo_error = got_repo_close(repo);
4146 if (error == NULL)
4147 error = repo_error;
4149 return error;
4152 __dead static void
4153 usage_blame(void)
4155 fprintf(stderr,
4156 "usage: %s blame [-c commit] [-r repository-path] path\n",
4157 getprogname());
4158 exit(1);
4161 struct blame_line {
4162 int annotated;
4163 char *id_str;
4164 char *committer;
4165 char datebuf[11]; /* YYYY-MM-DD + NUL */
4168 struct blame_cb_args {
4169 struct blame_line *lines;
4170 int nlines;
4171 int nlines_prec;
4172 int lineno_cur;
4173 off_t *line_offsets;
4174 FILE *f;
4175 struct got_repository *repo;
4178 static const struct got_error *
4179 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4181 const struct got_error *err = NULL;
4182 struct blame_cb_args *a = arg;
4183 struct blame_line *bline;
4184 char *line = NULL;
4185 size_t linesize = 0;
4186 struct got_commit_object *commit = NULL;
4187 off_t offset;
4188 struct tm tm;
4189 time_t committer_time;
4191 if (nlines != a->nlines ||
4192 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4193 return got_error(GOT_ERR_RANGE);
4195 if (sigint_received)
4196 return got_error(GOT_ERR_ITER_COMPLETED);
4198 if (lineno == -1)
4199 return NULL; /* no change in this commit */
4201 /* Annotate this line. */
4202 bline = &a->lines[lineno - 1];
4203 if (bline->annotated)
4204 return NULL;
4205 err = got_object_id_str(&bline->id_str, id);
4206 if (err)
4207 return err;
4209 err = got_object_open_as_commit(&commit, a->repo, id);
4210 if (err)
4211 goto done;
4213 bline->committer = strdup(got_object_commit_get_committer(commit));
4214 if (bline->committer == NULL) {
4215 err = got_error_from_errno("strdup");
4216 goto done;
4219 committer_time = got_object_commit_get_committer_time(commit);
4220 if (localtime_r(&committer_time, &tm) == NULL)
4221 return got_error_from_errno("localtime_r");
4222 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4223 &tm) >= sizeof(bline->datebuf)) {
4224 err = got_error(GOT_ERR_NO_SPACE);
4225 goto done;
4227 bline->annotated = 1;
4229 /* Print lines annotated so far. */
4230 bline = &a->lines[a->lineno_cur - 1];
4231 if (!bline->annotated)
4232 goto done;
4234 offset = a->line_offsets[a->lineno_cur - 1];
4235 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4236 err = got_error_from_errno("fseeko");
4237 goto done;
4240 while (bline->annotated) {
4241 char *smallerthan, *at, *nl, *committer;
4242 size_t len;
4244 if (getline(&line, &linesize, a->f) == -1) {
4245 if (ferror(a->f))
4246 err = got_error_from_errno("getline");
4247 break;
4250 committer = bline->committer;
4251 smallerthan = strchr(committer, '<');
4252 if (smallerthan && smallerthan[1] != '\0')
4253 committer = smallerthan + 1;
4254 at = strchr(committer, '@');
4255 if (at)
4256 *at = '\0';
4257 len = strlen(committer);
4258 if (len >= 9)
4259 committer[8] = '\0';
4261 nl = strchr(line, '\n');
4262 if (nl)
4263 *nl = '\0';
4264 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4265 bline->id_str, bline->datebuf, committer, line);
4267 a->lineno_cur++;
4268 bline = &a->lines[a->lineno_cur - 1];
4270 done:
4271 if (commit)
4272 got_object_commit_close(commit);
4273 free(line);
4274 return err;
4277 static const struct got_error *
4278 cmd_blame(int argc, char *argv[])
4280 const struct got_error *error;
4281 struct got_repository *repo = NULL;
4282 struct got_worktree *worktree = NULL;
4283 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4284 char *link_target = NULL;
4285 struct got_object_id *obj_id = NULL;
4286 struct got_object_id *commit_id = NULL;
4287 struct got_blob_object *blob = NULL;
4288 char *commit_id_str = NULL;
4289 struct blame_cb_args bca;
4290 int ch, obj_type, i;
4291 size_t filesize;
4293 memset(&bca, 0, sizeof(bca));
4295 #ifndef PROFILE
4296 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4297 NULL) == -1)
4298 err(1, "pledge");
4299 #endif
4301 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4302 switch (ch) {
4303 case 'c':
4304 commit_id_str = optarg;
4305 break;
4306 case 'r':
4307 repo_path = realpath(optarg, NULL);
4308 if (repo_path == NULL)
4309 return got_error_from_errno2("realpath",
4310 optarg);
4311 got_path_strip_trailing_slashes(repo_path);
4312 break;
4313 default:
4314 usage_blame();
4315 /* NOTREACHED */
4319 argc -= optind;
4320 argv += optind;
4322 if (argc == 1)
4323 path = argv[0];
4324 else
4325 usage_blame();
4327 cwd = getcwd(NULL, 0);
4328 if (cwd == NULL) {
4329 error = got_error_from_errno("getcwd");
4330 goto done;
4332 if (repo_path == NULL) {
4333 error = got_worktree_open(&worktree, cwd);
4334 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4335 goto done;
4336 else
4337 error = NULL;
4338 if (worktree) {
4339 repo_path =
4340 strdup(got_worktree_get_repo_path(worktree));
4341 if (repo_path == NULL) {
4342 error = got_error_from_errno("strdup");
4343 if (error)
4344 goto done;
4346 } else {
4347 repo_path = strdup(cwd);
4348 if (repo_path == NULL) {
4349 error = got_error_from_errno("strdup");
4350 goto done;
4355 error = got_repo_open(&repo, repo_path, NULL);
4356 if (error != NULL)
4357 goto done;
4359 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4360 if (error)
4361 goto done;
4363 if (worktree) {
4364 const char *prefix = got_worktree_get_path_prefix(worktree);
4365 char *p, *worktree_subdir = cwd +
4366 strlen(got_worktree_get_root_path(worktree));
4367 if (asprintf(&p, "%s%s%s%s%s",
4368 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
4369 worktree_subdir, worktree_subdir[0] ? "/" : "",
4370 path) == -1) {
4371 error = got_error_from_errno("asprintf");
4372 goto done;
4374 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4375 free(p);
4376 } else {
4377 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4379 if (error)
4380 goto done;
4382 if (commit_id_str == NULL) {
4383 struct got_reference *head_ref;
4384 error = got_ref_open(&head_ref, repo, worktree ?
4385 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4386 if (error != NULL)
4387 goto done;
4388 error = got_ref_resolve(&commit_id, repo, head_ref);
4389 got_ref_close(head_ref);
4390 if (error != NULL)
4391 goto done;
4392 } else {
4393 error = got_repo_match_object_id(&commit_id, NULL,
4394 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4395 if (error)
4396 goto done;
4399 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4400 commit_id, repo);
4401 if (error)
4402 goto done;
4404 error = got_object_id_by_path(&obj_id, repo, commit_id,
4405 link_target ? link_target : in_repo_path);
4406 if (error)
4407 goto done;
4409 error = got_object_get_type(&obj_type, repo, obj_id);
4410 if (error)
4411 goto done;
4413 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4414 error = got_error_path(link_target ? link_target : in_repo_path,
4415 GOT_ERR_OBJ_TYPE);
4416 goto done;
4419 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4420 if (error)
4421 goto done;
4422 bca.f = got_opentemp();
4423 if (bca.f == NULL) {
4424 error = got_error_from_errno("got_opentemp");
4425 goto done;
4427 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4428 &bca.line_offsets, bca.f, blob);
4429 if (error || bca.nlines == 0)
4430 goto done;
4432 /* Don't include \n at EOF in the blame line count. */
4433 if (bca.line_offsets[bca.nlines - 1] == filesize)
4434 bca.nlines--;
4436 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4437 if (bca.lines == NULL) {
4438 error = got_error_from_errno("calloc");
4439 goto done;
4441 bca.lineno_cur = 1;
4442 bca.nlines_prec = 0;
4443 i = bca.nlines;
4444 while (i > 0) {
4445 i /= 10;
4446 bca.nlines_prec++;
4448 bca.repo = repo;
4450 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4451 repo, blame_cb, &bca, check_cancelled, NULL);
4452 done:
4453 free(in_repo_path);
4454 free(link_target);
4455 free(repo_path);
4456 free(cwd);
4457 free(commit_id);
4458 free(obj_id);
4459 if (blob)
4460 got_object_blob_close(blob);
4461 if (worktree)
4462 got_worktree_close(worktree);
4463 if (repo) {
4464 const struct got_error *repo_error;
4465 repo_error = got_repo_close(repo);
4466 if (error == NULL)
4467 error = repo_error;
4469 if (bca.lines) {
4470 for (i = 0; i < bca.nlines; i++) {
4471 struct blame_line *bline = &bca.lines[i];
4472 free(bline->id_str);
4473 free(bline->committer);
4475 free(bca.lines);
4477 free(bca.line_offsets);
4478 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4479 error = got_error_from_errno("fclose");
4480 return error;
4483 __dead static void
4484 usage_tree(void)
4486 fprintf(stderr,
4487 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4488 getprogname());
4489 exit(1);
4492 static const struct got_error *
4493 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4494 const char *root_path, struct got_repository *repo)
4496 const struct got_error *err = NULL;
4497 int is_root_path = (strcmp(path, root_path) == 0);
4498 const char *modestr = "";
4499 mode_t mode = got_tree_entry_get_mode(te);
4500 char *link_target = NULL;
4502 path += strlen(root_path);
4503 while (path[0] == '/')
4504 path++;
4506 if (got_object_tree_entry_is_submodule(te))
4507 modestr = "$";
4508 else if (S_ISLNK(mode)) {
4509 int i;
4511 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4512 if (err)
4513 return err;
4514 for (i = 0; i < strlen(link_target); i++) {
4515 if (!isprint((unsigned char)link_target[i]))
4516 link_target[i] = '?';
4519 modestr = "@";
4521 else if (S_ISDIR(mode))
4522 modestr = "/";
4523 else if (mode & S_IXUSR)
4524 modestr = "*";
4526 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4527 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4528 link_target ? " -> ": "", link_target ? link_target : "");
4530 free(link_target);
4531 return NULL;
4534 static const struct got_error *
4535 print_tree(const char *path, struct got_object_id *commit_id,
4536 int show_ids, int recurse, const char *root_path,
4537 struct got_repository *repo)
4539 const struct got_error *err = NULL;
4540 struct got_object_id *tree_id = NULL;
4541 struct got_tree_object *tree = NULL;
4542 int nentries, i;
4544 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4545 if (err)
4546 goto done;
4548 err = got_object_open_as_tree(&tree, repo, tree_id);
4549 if (err)
4550 goto done;
4551 nentries = got_object_tree_get_nentries(tree);
4552 for (i = 0; i < nentries; i++) {
4553 struct got_tree_entry *te;
4554 char *id = NULL;
4556 if (sigint_received || sigpipe_received)
4557 break;
4559 te = got_object_tree_get_entry(tree, i);
4560 if (show_ids) {
4561 char *id_str;
4562 err = got_object_id_str(&id_str,
4563 got_tree_entry_get_id(te));
4564 if (err)
4565 goto done;
4566 if (asprintf(&id, "%s ", id_str) == -1) {
4567 err = got_error_from_errno("asprintf");
4568 free(id_str);
4569 goto done;
4571 free(id_str);
4573 err = print_entry(te, id, path, root_path, repo);
4574 free(id);
4575 if (err)
4576 goto done;
4578 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4579 char *child_path;
4580 if (asprintf(&child_path, "%s%s%s", path,
4581 path[0] == '/' && path[1] == '\0' ? "" : "/",
4582 got_tree_entry_get_name(te)) == -1) {
4583 err = got_error_from_errno("asprintf");
4584 goto done;
4586 err = print_tree(child_path, commit_id, show_ids, 1,
4587 root_path, repo);
4588 free(child_path);
4589 if (err)
4590 goto done;
4593 done:
4594 if (tree)
4595 got_object_tree_close(tree);
4596 free(tree_id);
4597 return err;
4600 static const struct got_error *
4601 cmd_tree(int argc, char *argv[])
4603 const struct got_error *error;
4604 struct got_repository *repo = NULL;
4605 struct got_worktree *worktree = NULL;
4606 const char *path, *refname = NULL;
4607 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4608 struct got_object_id *commit_id = NULL;
4609 char *commit_id_str = NULL;
4610 int show_ids = 0, recurse = 0;
4611 int ch;
4613 #ifndef PROFILE
4614 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4615 NULL) == -1)
4616 err(1, "pledge");
4617 #endif
4619 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4620 switch (ch) {
4621 case 'c':
4622 commit_id_str = optarg;
4623 break;
4624 case 'r':
4625 repo_path = realpath(optarg, NULL);
4626 if (repo_path == NULL)
4627 return got_error_from_errno2("realpath",
4628 optarg);
4629 got_path_strip_trailing_slashes(repo_path);
4630 break;
4631 case 'i':
4632 show_ids = 1;
4633 break;
4634 case 'R':
4635 recurse = 1;
4636 break;
4637 default:
4638 usage_tree();
4639 /* NOTREACHED */
4643 argc -= optind;
4644 argv += optind;
4646 if (argc == 1)
4647 path = argv[0];
4648 else if (argc > 1)
4649 usage_tree();
4650 else
4651 path = NULL;
4653 cwd = getcwd(NULL, 0);
4654 if (cwd == NULL) {
4655 error = got_error_from_errno("getcwd");
4656 goto done;
4658 if (repo_path == NULL) {
4659 error = got_worktree_open(&worktree, cwd);
4660 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4661 goto done;
4662 else
4663 error = NULL;
4664 if (worktree) {
4665 repo_path =
4666 strdup(got_worktree_get_repo_path(worktree));
4667 if (repo_path == NULL)
4668 error = got_error_from_errno("strdup");
4669 if (error)
4670 goto done;
4671 } else {
4672 repo_path = strdup(cwd);
4673 if (repo_path == NULL) {
4674 error = got_error_from_errno("strdup");
4675 goto done;
4680 error = got_repo_open(&repo, repo_path, NULL);
4681 if (error != NULL)
4682 goto done;
4684 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4685 if (error)
4686 goto done;
4688 if (path == NULL) {
4689 if (worktree) {
4690 char *p, *worktree_subdir = cwd +
4691 strlen(got_worktree_get_root_path(worktree));
4692 if (asprintf(&p, "%s/%s",
4693 got_worktree_get_path_prefix(worktree),
4694 worktree_subdir) == -1) {
4695 error = got_error_from_errno("asprintf");
4696 goto done;
4698 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4699 free(p);
4700 if (error)
4701 goto done;
4702 } else
4703 path = "/";
4705 if (in_repo_path == NULL) {
4706 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4707 if (error != NULL)
4708 goto done;
4711 if (commit_id_str == NULL) {
4712 struct got_reference *head_ref;
4713 if (worktree)
4714 refname = got_worktree_get_head_ref_name(worktree);
4715 else
4716 refname = GOT_REF_HEAD;
4717 error = got_ref_open(&head_ref, repo, refname, 0);
4718 if (error != NULL)
4719 goto done;
4720 error = got_ref_resolve(&commit_id, repo, head_ref);
4721 got_ref_close(head_ref);
4722 if (error != NULL)
4723 goto done;
4724 } else {
4725 error = got_repo_match_object_id(&commit_id, NULL,
4726 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4727 if (error)
4728 goto done;
4731 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4732 in_repo_path, repo);
4733 done:
4734 free(in_repo_path);
4735 free(repo_path);
4736 free(cwd);
4737 free(commit_id);
4738 if (worktree)
4739 got_worktree_close(worktree);
4740 if (repo) {
4741 const struct got_error *repo_error;
4742 repo_error = got_repo_close(repo);
4743 if (error == NULL)
4744 error = repo_error;
4746 return error;
4749 __dead static void
4750 usage_status(void)
4752 fprintf(stderr, "usage: %s status [-s status-codes ] [path ...]\n",
4753 getprogname());
4754 exit(1);
4757 static const struct got_error *
4758 print_status(void *arg, unsigned char status, unsigned char staged_status,
4759 const char *path, struct got_object_id *blob_id,
4760 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4761 int dirfd, const char *de_name)
4763 if (status == staged_status && (status == GOT_STATUS_DELETE))
4764 status = GOT_STATUS_NO_CHANGE;
4765 if (arg) {
4766 char *status_codes = arg;
4767 size_t ncodes = strlen(status_codes);
4768 int i;
4769 for (i = 0; i < ncodes ; i++) {
4770 if (status == status_codes[i] ||
4771 staged_status == status_codes[i])
4772 break;
4774 if (i == ncodes)
4775 return NULL;
4777 printf("%c%c %s\n", status, staged_status, path);
4778 return NULL;
4781 static const struct got_error *
4782 cmd_status(int argc, char *argv[])
4784 const struct got_error *error = NULL;
4785 struct got_repository *repo = NULL;
4786 struct got_worktree *worktree = NULL;
4787 char *cwd = NULL, *status_codes = NULL;;
4788 struct got_pathlist_head paths;
4789 struct got_pathlist_entry *pe;
4790 int ch, i;
4792 TAILQ_INIT(&paths);
4794 while ((ch = getopt(argc, argv, "s:")) != -1) {
4795 switch (ch) {
4796 case 's':
4797 for (i = 0; i < strlen(optarg); i++) {
4798 switch (optarg[i]) {
4799 case GOT_STATUS_MODIFY:
4800 case GOT_STATUS_ADD:
4801 case GOT_STATUS_DELETE:
4802 case GOT_STATUS_CONFLICT:
4803 case GOT_STATUS_MISSING:
4804 case GOT_STATUS_OBSTRUCTED:
4805 case GOT_STATUS_UNVERSIONED:
4806 case GOT_STATUS_MODE_CHANGE:
4807 case GOT_STATUS_NONEXISTENT:
4808 break;
4809 default:
4810 errx(1, "invalid status code '%c'",
4811 optarg[i]);
4814 status_codes = optarg;
4815 break;
4816 default:
4817 usage_status();
4818 /* NOTREACHED */
4822 argc -= optind;
4823 argv += optind;
4825 #ifndef PROFILE
4826 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4827 NULL) == -1)
4828 err(1, "pledge");
4829 #endif
4830 cwd = getcwd(NULL, 0);
4831 if (cwd == NULL) {
4832 error = got_error_from_errno("getcwd");
4833 goto done;
4836 error = got_worktree_open(&worktree, cwd);
4837 if (error) {
4838 if (error->code == GOT_ERR_NOT_WORKTREE)
4839 error = wrap_not_worktree_error(error, "status", cwd);
4840 goto done;
4843 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4844 NULL);
4845 if (error != NULL)
4846 goto done;
4848 error = apply_unveil(got_repo_get_path(repo), 1,
4849 got_worktree_get_root_path(worktree));
4850 if (error)
4851 goto done;
4853 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
4854 if (error)
4855 goto done;
4857 error = got_worktree_status(worktree, &paths, repo, print_status,
4858 status_codes, check_cancelled, NULL);
4859 done:
4860 TAILQ_FOREACH(pe, &paths, entry)
4861 free((char *)pe->path);
4862 got_pathlist_free(&paths);
4863 free(cwd);
4864 return error;
4867 __dead static void
4868 usage_ref(void)
4870 fprintf(stderr,
4871 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
4872 "[-d] [name]\n",
4873 getprogname());
4874 exit(1);
4877 static const struct got_error *
4878 list_refs(struct got_repository *repo, const char *refname)
4880 static const struct got_error *err = NULL;
4881 struct got_reflist_head refs;
4882 struct got_reflist_entry *re;
4884 SIMPLEQ_INIT(&refs);
4885 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
4886 if (err)
4887 return err;
4889 SIMPLEQ_FOREACH(re, &refs, entry) {
4890 char *refstr;
4891 refstr = got_ref_to_str(re->ref);
4892 if (refstr == NULL)
4893 return got_error_from_errno("got_ref_to_str");
4894 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
4895 free(refstr);
4898 got_ref_list_free(&refs);
4899 return NULL;
4902 static const struct got_error *
4903 delete_ref(struct got_repository *repo, const char *refname)
4905 const struct got_error *err = NULL;
4906 struct got_reference *ref;
4908 err = got_ref_open(&ref, repo, refname, 0);
4909 if (err)
4910 return err;
4912 err = got_ref_delete(ref, repo);
4913 got_ref_close(ref);
4914 return err;
4917 static const struct got_error *
4918 add_ref(struct got_repository *repo, const char *refname, const char *target)
4920 const struct got_error *err = NULL;
4921 struct got_object_id *id;
4922 struct got_reference *ref = NULL;
4925 * Don't let the user create a reference name with a leading '-'.
4926 * While technically a valid reference name, this case is usually
4927 * an unintended typo.
4929 if (refname[0] == '-')
4930 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4932 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
4933 repo);
4934 if (err) {
4935 struct got_reference *target_ref;
4937 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
4938 return err;
4939 err = got_ref_open(&target_ref, repo, target, 0);
4940 if (err)
4941 return err;
4942 err = got_ref_resolve(&id, repo, target_ref);
4943 got_ref_close(target_ref);
4944 if (err)
4945 return err;
4948 err = got_ref_alloc(&ref, refname, id);
4949 if (err)
4950 goto done;
4952 err = got_ref_write(ref, repo);
4953 done:
4954 if (ref)
4955 got_ref_close(ref);
4956 free(id);
4957 return err;
4960 static const struct got_error *
4961 add_symref(struct got_repository *repo, const char *refname, const char *target)
4963 const struct got_error *err = NULL;
4964 struct got_reference *ref = NULL;
4965 struct got_reference *target_ref = NULL;
4968 * Don't let the user create a reference name with a leading '-'.
4969 * While technically a valid reference name, this case is usually
4970 * an unintended typo.
4972 if (refname[0] == '-')
4973 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4975 err = got_ref_open(&target_ref, repo, target, 0);
4976 if (err)
4977 return err;
4979 err = got_ref_alloc_symref(&ref, refname, target_ref);
4980 if (err)
4981 goto done;
4983 err = got_ref_write(ref, repo);
4984 done:
4985 if (target_ref)
4986 got_ref_close(target_ref);
4987 if (ref)
4988 got_ref_close(ref);
4989 return err;
4992 static const struct got_error *
4993 cmd_ref(int argc, char *argv[])
4995 const struct got_error *error = NULL;
4996 struct got_repository *repo = NULL;
4997 struct got_worktree *worktree = NULL;
4998 char *cwd = NULL, *repo_path = NULL;
4999 int ch, do_list = 0, do_delete = 0;
5000 const char *obj_arg = NULL, *symref_target= NULL;
5001 char *refname = NULL;
5003 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5004 switch (ch) {
5005 case 'c':
5006 obj_arg = optarg;
5007 break;
5008 case 'd':
5009 do_delete = 1;
5010 break;
5011 case 'r':
5012 repo_path = realpath(optarg, NULL);
5013 if (repo_path == NULL)
5014 return got_error_from_errno2("realpath",
5015 optarg);
5016 got_path_strip_trailing_slashes(repo_path);
5017 break;
5018 case 'l':
5019 do_list = 1;
5020 break;
5021 case 's':
5022 symref_target = optarg;
5023 break;
5024 default:
5025 usage_ref();
5026 /* NOTREACHED */
5030 if (obj_arg && do_list)
5031 errx(1, "-c and -l options are mutually exclusive");
5032 if (obj_arg && do_delete)
5033 errx(1, "-c and -d options are mutually exclusive");
5034 if (obj_arg && symref_target)
5035 errx(1, "-c and -s options are mutually exclusive");
5036 if (symref_target && do_delete)
5037 errx(1, "-s and -d options are mutually exclusive");
5038 if (symref_target && do_list)
5039 errx(1, "-s and -l options are mutually exclusive");
5040 if (do_delete && do_list)
5041 errx(1, "-d and -l options are mutually exclusive");
5043 argc -= optind;
5044 argv += optind;
5046 if (do_list) {
5047 if (argc != 0 && argc != 1)
5048 usage_ref();
5049 if (argc == 1) {
5050 refname = strdup(argv[0]);
5051 if (refname == NULL) {
5052 error = got_error_from_errno("strdup");
5053 goto done;
5056 } else {
5057 if (argc != 1)
5058 usage_ref();
5059 refname = strdup(argv[0]);
5060 if (refname == NULL) {
5061 error = got_error_from_errno("strdup");
5062 goto done;
5066 if (refname)
5067 got_path_strip_trailing_slashes(refname);
5069 #ifndef PROFILE
5070 if (do_list) {
5071 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5072 NULL) == -1)
5073 err(1, "pledge");
5074 } else {
5075 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5076 "sendfd unveil", NULL) == -1)
5077 err(1, "pledge");
5079 #endif
5080 cwd = getcwd(NULL, 0);
5081 if (cwd == NULL) {
5082 error = got_error_from_errno("getcwd");
5083 goto done;
5086 if (repo_path == NULL) {
5087 error = got_worktree_open(&worktree, cwd);
5088 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5089 goto done;
5090 else
5091 error = NULL;
5092 if (worktree) {
5093 repo_path =
5094 strdup(got_worktree_get_repo_path(worktree));
5095 if (repo_path == NULL)
5096 error = got_error_from_errno("strdup");
5097 if (error)
5098 goto done;
5099 } else {
5100 repo_path = strdup(cwd);
5101 if (repo_path == NULL) {
5102 error = got_error_from_errno("strdup");
5103 goto done;
5108 error = got_repo_open(&repo, repo_path, NULL);
5109 if (error != NULL)
5110 goto done;
5112 error = apply_unveil(got_repo_get_path(repo), do_list,
5113 worktree ? got_worktree_get_root_path(worktree) : NULL);
5114 if (error)
5115 goto done;
5117 if (do_list)
5118 error = list_refs(repo, refname);
5119 else if (do_delete)
5120 error = delete_ref(repo, refname);
5121 else if (symref_target)
5122 error = add_symref(repo, refname, symref_target);
5123 else {
5124 if (obj_arg == NULL)
5125 usage_ref();
5126 error = add_ref(repo, refname, obj_arg);
5128 done:
5129 free(refname);
5130 if (repo)
5131 got_repo_close(repo);
5132 if (worktree)
5133 got_worktree_close(worktree);
5134 free(cwd);
5135 free(repo_path);
5136 return error;
5139 __dead static void
5140 usage_branch(void)
5142 fprintf(stderr,
5143 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5144 "[name]\n", getprogname());
5145 exit(1);
5148 static const struct got_error *
5149 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5150 struct got_reference *ref)
5152 const struct got_error *err = NULL;
5153 const char *refname, *marker = " ";
5154 char *refstr;
5156 refname = got_ref_get_name(ref);
5157 if (worktree && strcmp(refname,
5158 got_worktree_get_head_ref_name(worktree)) == 0) {
5159 struct got_object_id *id = NULL;
5161 err = got_ref_resolve(&id, repo, ref);
5162 if (err)
5163 return err;
5164 if (got_object_id_cmp(id,
5165 got_worktree_get_base_commit_id(worktree)) == 0)
5166 marker = "* ";
5167 else
5168 marker = "~ ";
5169 free(id);
5172 if (strncmp(refname, "refs/heads/", 11) == 0)
5173 refname += 11;
5174 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5175 refname += 18;
5177 refstr = got_ref_to_str(ref);
5178 if (refstr == NULL)
5179 return got_error_from_errno("got_ref_to_str");
5181 printf("%s%s: %s\n", marker, refname, refstr);
5182 free(refstr);
5183 return NULL;
5186 static const struct got_error *
5187 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5189 const char *refname;
5191 if (worktree == NULL)
5192 return got_error(GOT_ERR_NOT_WORKTREE);
5194 refname = got_worktree_get_head_ref_name(worktree);
5196 if (strncmp(refname, "refs/heads/", 11) == 0)
5197 refname += 11;
5198 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5199 refname += 18;
5201 printf("%s\n", refname);
5203 return NULL;
5206 static const struct got_error *
5207 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5209 static const struct got_error *err = NULL;
5210 struct got_reflist_head refs;
5211 struct got_reflist_entry *re;
5212 struct got_reference *temp_ref = NULL;
5213 int rebase_in_progress, histedit_in_progress;
5215 SIMPLEQ_INIT(&refs);
5217 if (worktree) {
5218 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5219 worktree);
5220 if (err)
5221 return err;
5223 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5224 worktree);
5225 if (err)
5226 return err;
5228 if (rebase_in_progress || histedit_in_progress) {
5229 err = got_ref_open(&temp_ref, repo,
5230 got_worktree_get_head_ref_name(worktree), 0);
5231 if (err)
5232 return err;
5233 list_branch(repo, worktree, temp_ref);
5234 got_ref_close(temp_ref);
5238 err = got_ref_list(&refs, repo, "refs/heads",
5239 got_ref_cmp_by_name, NULL);
5240 if (err)
5241 return err;
5243 SIMPLEQ_FOREACH(re, &refs, entry)
5244 list_branch(repo, worktree, re->ref);
5246 got_ref_list_free(&refs);
5247 return NULL;
5250 static const struct got_error *
5251 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5252 const char *branch_name)
5254 const struct got_error *err = NULL;
5255 struct got_reference *ref = NULL;
5256 char *refname;
5258 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5259 return got_error_from_errno("asprintf");
5261 err = got_ref_open(&ref, repo, refname, 0);
5262 if (err)
5263 goto done;
5265 if (worktree &&
5266 strcmp(got_worktree_get_head_ref_name(worktree),
5267 got_ref_get_name(ref)) == 0) {
5268 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5269 "will not delete this work tree's current branch");
5270 goto done;
5273 err = got_ref_delete(ref, repo);
5274 done:
5275 if (ref)
5276 got_ref_close(ref);
5277 free(refname);
5278 return err;
5281 static const struct got_error *
5282 add_branch(struct got_repository *repo, const char *branch_name,
5283 struct got_object_id *base_commit_id)
5285 const struct got_error *err = NULL;
5286 struct got_reference *ref = NULL;
5287 char *base_refname = NULL, *refname = NULL;
5290 * Don't let the user create a branch name with a leading '-'.
5291 * While technically a valid reference name, this case is usually
5292 * an unintended typo.
5294 if (branch_name[0] == '-')
5295 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5297 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5298 err = got_error_from_errno("asprintf");
5299 goto done;
5302 err = got_ref_open(&ref, repo, refname, 0);
5303 if (err == NULL) {
5304 err = got_error(GOT_ERR_BRANCH_EXISTS);
5305 goto done;
5306 } else if (err->code != GOT_ERR_NOT_REF)
5307 goto done;
5309 err = got_ref_alloc(&ref, refname, base_commit_id);
5310 if (err)
5311 goto done;
5313 err = got_ref_write(ref, repo);
5314 done:
5315 if (ref)
5316 got_ref_close(ref);
5317 free(base_refname);
5318 free(refname);
5319 return err;
5322 static const struct got_error *
5323 cmd_branch(int argc, char *argv[])
5325 const struct got_error *error = NULL;
5326 struct got_repository *repo = NULL;
5327 struct got_worktree *worktree = NULL;
5328 char *cwd = NULL, *repo_path = NULL;
5329 int ch, do_list = 0, do_show = 0, do_update = 1;
5330 const char *delref = NULL, *commit_id_arg = NULL;
5331 struct got_reference *ref = NULL;
5332 struct got_pathlist_head paths;
5333 struct got_pathlist_entry *pe;
5334 struct got_object_id *commit_id = NULL;
5335 char *commit_id_str = NULL;
5337 TAILQ_INIT(&paths);
5339 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5340 switch (ch) {
5341 case 'c':
5342 commit_id_arg = optarg;
5343 break;
5344 case 'd':
5345 delref = optarg;
5346 break;
5347 case 'r':
5348 repo_path = realpath(optarg, NULL);
5349 if (repo_path == NULL)
5350 return got_error_from_errno2("realpath",
5351 optarg);
5352 got_path_strip_trailing_slashes(repo_path);
5353 break;
5354 case 'l':
5355 do_list = 1;
5356 break;
5357 case 'n':
5358 do_update = 0;
5359 break;
5360 default:
5361 usage_branch();
5362 /* NOTREACHED */
5366 if (do_list && delref)
5367 errx(1, "-l and -d options are mutually exclusive");
5369 argc -= optind;
5370 argv += optind;
5372 if (!do_list && !delref && argc == 0)
5373 do_show = 1;
5375 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5376 errx(1, "-c option can only be used when creating a branch");
5378 if (do_list || delref) {
5379 if (argc > 0)
5380 usage_branch();
5381 } else if (!do_show && argc != 1)
5382 usage_branch();
5384 #ifndef PROFILE
5385 if (do_list || do_show) {
5386 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5387 NULL) == -1)
5388 err(1, "pledge");
5389 } else {
5390 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5391 "sendfd unveil", NULL) == -1)
5392 err(1, "pledge");
5394 #endif
5395 cwd = getcwd(NULL, 0);
5396 if (cwd == NULL) {
5397 error = got_error_from_errno("getcwd");
5398 goto done;
5401 if (repo_path == NULL) {
5402 error = got_worktree_open(&worktree, cwd);
5403 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5404 goto done;
5405 else
5406 error = NULL;
5407 if (worktree) {
5408 repo_path =
5409 strdup(got_worktree_get_repo_path(worktree));
5410 if (repo_path == NULL)
5411 error = got_error_from_errno("strdup");
5412 if (error)
5413 goto done;
5414 } else {
5415 repo_path = strdup(cwd);
5416 if (repo_path == NULL) {
5417 error = got_error_from_errno("strdup");
5418 goto done;
5423 error = got_repo_open(&repo, repo_path, NULL);
5424 if (error != NULL)
5425 goto done;
5427 error = apply_unveil(got_repo_get_path(repo), do_list,
5428 worktree ? got_worktree_get_root_path(worktree) : NULL);
5429 if (error)
5430 goto done;
5432 if (do_show)
5433 error = show_current_branch(repo, worktree);
5434 else if (do_list)
5435 error = list_branches(repo, worktree);
5436 else if (delref)
5437 error = delete_branch(repo, worktree, delref);
5438 else {
5439 if (commit_id_arg == NULL)
5440 commit_id_arg = worktree ?
5441 got_worktree_get_head_ref_name(worktree) :
5442 GOT_REF_HEAD;
5443 error = got_repo_match_object_id(&commit_id, NULL,
5444 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5445 if (error)
5446 goto done;
5447 error = add_branch(repo, argv[0], commit_id);
5448 if (error)
5449 goto done;
5450 if (worktree && do_update) {
5451 struct got_update_progress_arg upa;
5452 char *branch_refname = NULL;
5454 error = got_object_id_str(&commit_id_str, commit_id);
5455 if (error)
5456 goto done;
5457 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5458 worktree);
5459 if (error)
5460 goto done;
5461 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5462 == -1) {
5463 error = got_error_from_errno("asprintf");
5464 goto done;
5466 error = got_ref_open(&ref, repo, branch_refname, 0);
5467 free(branch_refname);
5468 if (error)
5469 goto done;
5470 error = switch_head_ref(ref, commit_id, worktree,
5471 repo);
5472 if (error)
5473 goto done;
5474 error = got_worktree_set_base_commit_id(worktree, repo,
5475 commit_id);
5476 if (error)
5477 goto done;
5478 memset(&upa, 0, sizeof(upa));
5479 error = got_worktree_checkout_files(worktree, &paths,
5480 repo, update_progress, &upa, check_cancelled,
5481 NULL);
5482 if (error)
5483 goto done;
5484 if (upa.did_something)
5485 printf("Updated to commit %s\n", commit_id_str);
5486 print_update_progress_stats(&upa);
5489 done:
5490 if (ref)
5491 got_ref_close(ref);
5492 if (repo)
5493 got_repo_close(repo);
5494 if (worktree)
5495 got_worktree_close(worktree);
5496 free(cwd);
5497 free(repo_path);
5498 free(commit_id);
5499 free(commit_id_str);
5500 TAILQ_FOREACH(pe, &paths, entry)
5501 free((char *)pe->path);
5502 got_pathlist_free(&paths);
5503 return error;
5507 __dead static void
5508 usage_tag(void)
5510 fprintf(stderr,
5511 "usage: %s tag [-c commit] [-r repository] [-l] "
5512 "[-m message] name\n", getprogname());
5513 exit(1);
5516 #if 0
5517 static const struct got_error *
5518 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5520 const struct got_error *err = NULL;
5521 struct got_reflist_entry *re, *se, *new;
5522 struct got_object_id *re_id, *se_id;
5523 struct got_tag_object *re_tag, *se_tag;
5524 time_t re_time, se_time;
5526 SIMPLEQ_FOREACH(re, tags, entry) {
5527 se = SIMPLEQ_FIRST(sorted);
5528 if (se == NULL) {
5529 err = got_reflist_entry_dup(&new, re);
5530 if (err)
5531 return err;
5532 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5533 continue;
5534 } else {
5535 err = got_ref_resolve(&re_id, repo, re->ref);
5536 if (err)
5537 break;
5538 err = got_object_open_as_tag(&re_tag, repo, re_id);
5539 free(re_id);
5540 if (err)
5541 break;
5542 re_time = got_object_tag_get_tagger_time(re_tag);
5543 got_object_tag_close(re_tag);
5546 while (se) {
5547 err = got_ref_resolve(&se_id, repo, re->ref);
5548 if (err)
5549 break;
5550 err = got_object_open_as_tag(&se_tag, repo, se_id);
5551 free(se_id);
5552 if (err)
5553 break;
5554 se_time = got_object_tag_get_tagger_time(se_tag);
5555 got_object_tag_close(se_tag);
5557 if (se_time > re_time) {
5558 err = got_reflist_entry_dup(&new, re);
5559 if (err)
5560 return err;
5561 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5562 break;
5564 se = SIMPLEQ_NEXT(se, entry);
5565 continue;
5568 done:
5569 return err;
5571 #endif
5573 static const struct got_error *
5574 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5576 static const struct got_error *err = NULL;
5577 struct got_reflist_head refs;
5578 struct got_reflist_entry *re;
5580 SIMPLEQ_INIT(&refs);
5582 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5583 if (err)
5584 return err;
5586 SIMPLEQ_FOREACH(re, &refs, entry) {
5587 const char *refname;
5588 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5589 char datebuf[26];
5590 const char *tagger;
5591 time_t tagger_time;
5592 struct got_object_id *id;
5593 struct got_tag_object *tag;
5594 struct got_commit_object *commit = NULL;
5596 refname = got_ref_get_name(re->ref);
5597 if (strncmp(refname, "refs/tags/", 10) != 0)
5598 continue;
5599 refname += 10;
5600 refstr = got_ref_to_str(re->ref);
5601 if (refstr == NULL) {
5602 err = got_error_from_errno("got_ref_to_str");
5603 break;
5605 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5606 free(refstr);
5608 err = got_ref_resolve(&id, repo, re->ref);
5609 if (err)
5610 break;
5611 err = got_object_open_as_tag(&tag, repo, id);
5612 if (err) {
5613 if (err->code != GOT_ERR_OBJ_TYPE) {
5614 free(id);
5615 break;
5617 /* "lightweight" tag */
5618 err = got_object_open_as_commit(&commit, repo, id);
5619 if (err) {
5620 free(id);
5621 break;
5623 tagger = got_object_commit_get_committer(commit);
5624 tagger_time =
5625 got_object_commit_get_committer_time(commit);
5626 err = got_object_id_str(&id_str, id);
5627 free(id);
5628 if (err)
5629 break;
5630 } else {
5631 free(id);
5632 tagger = got_object_tag_get_tagger(tag);
5633 tagger_time = got_object_tag_get_tagger_time(tag);
5634 err = got_object_id_str(&id_str,
5635 got_object_tag_get_object_id(tag));
5636 if (err)
5637 break;
5639 printf("from: %s\n", tagger);
5640 datestr = get_datestr(&tagger_time, datebuf);
5641 if (datestr)
5642 printf("date: %s UTC\n", datestr);
5643 if (commit)
5644 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5645 else {
5646 switch (got_object_tag_get_object_type(tag)) {
5647 case GOT_OBJ_TYPE_BLOB:
5648 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5649 id_str);
5650 break;
5651 case GOT_OBJ_TYPE_TREE:
5652 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5653 id_str);
5654 break;
5655 case GOT_OBJ_TYPE_COMMIT:
5656 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5657 id_str);
5658 break;
5659 case GOT_OBJ_TYPE_TAG:
5660 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5661 id_str);
5662 break;
5663 default:
5664 break;
5667 free(id_str);
5668 if (commit) {
5669 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5670 if (err)
5671 break;
5672 got_object_commit_close(commit);
5673 } else {
5674 tagmsg0 = strdup(got_object_tag_get_message(tag));
5675 got_object_tag_close(tag);
5676 if (tagmsg0 == NULL) {
5677 err = got_error_from_errno("strdup");
5678 break;
5682 tagmsg = tagmsg0;
5683 do {
5684 line = strsep(&tagmsg, "\n");
5685 if (line)
5686 printf(" %s\n", line);
5687 } while (line);
5688 free(tagmsg0);
5691 got_ref_list_free(&refs);
5692 return NULL;
5695 static const struct got_error *
5696 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5697 const char *tag_name, const char *repo_path)
5699 const struct got_error *err = NULL;
5700 char *template = NULL, *initial_content = NULL;
5701 char *editor = NULL;
5702 int initial_content_len;
5703 int fd = -1;
5705 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5706 err = got_error_from_errno("asprintf");
5707 goto done;
5710 initial_content_len = asprintf(&initial_content,
5711 "\n# tagging commit %s as %s\n",
5712 commit_id_str, tag_name);
5713 if (initial_content_len == -1) {
5714 err = got_error_from_errno("asprintf");
5715 goto done;
5718 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5719 if (err)
5720 goto done;
5722 if (write(fd, initial_content, initial_content_len) == -1) {
5723 err = got_error_from_errno2("write", *tagmsg_path);
5724 goto done;
5727 err = get_editor(&editor);
5728 if (err)
5729 goto done;
5730 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
5731 done:
5732 free(initial_content);
5733 free(template);
5734 free(editor);
5736 if (fd != -1 && close(fd) == -1 && err == NULL)
5737 err = got_error_from_errno2("close", *tagmsg_path);
5739 /* Editor is done; we can now apply unveil(2) */
5740 if (err == NULL)
5741 err = apply_unveil(repo_path, 0, NULL);
5742 if (err) {
5743 free(*tagmsg);
5744 *tagmsg = NULL;
5746 return err;
5749 static const struct got_error *
5750 add_tag(struct got_repository *repo, struct got_worktree *worktree,
5751 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
5753 const struct got_error *err = NULL;
5754 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5755 char *label = NULL, *commit_id_str = NULL;
5756 struct got_reference *ref = NULL;
5757 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5758 char *tagmsg_path = NULL, *tag_id_str = NULL;
5759 int preserve_tagmsg = 0;
5762 * Don't let the user create a tag name with a leading '-'.
5763 * While technically a valid reference name, this case is usually
5764 * an unintended typo.
5766 if (tag_name[0] == '-')
5767 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5769 err = get_author(&tagger, repo, worktree);
5770 if (err)
5771 return err;
5773 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5774 GOT_OBJ_TYPE_COMMIT, 1, repo);
5775 if (err)
5776 goto done;
5778 err = got_object_id_str(&commit_id_str, commit_id);
5779 if (err)
5780 goto done;
5782 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5783 refname = strdup(tag_name);
5784 if (refname == NULL) {
5785 err = got_error_from_errno("strdup");
5786 goto done;
5788 tag_name += 10;
5789 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5790 err = got_error_from_errno("asprintf");
5791 goto done;
5794 err = got_ref_open(&ref, repo, refname, 0);
5795 if (err == NULL) {
5796 err = got_error(GOT_ERR_TAG_EXISTS);
5797 goto done;
5798 } else if (err->code != GOT_ERR_NOT_REF)
5799 goto done;
5801 if (tagmsg_arg == NULL) {
5802 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5803 tag_name, got_repo_get_path(repo));
5804 if (err) {
5805 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5806 tagmsg_path != NULL)
5807 preserve_tagmsg = 1;
5808 goto done;
5812 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5813 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5814 if (err) {
5815 if (tagmsg_path)
5816 preserve_tagmsg = 1;
5817 goto done;
5820 err = got_ref_alloc(&ref, refname, tag_id);
5821 if (err) {
5822 if (tagmsg_path)
5823 preserve_tagmsg = 1;
5824 goto done;
5827 err = got_ref_write(ref, repo);
5828 if (err) {
5829 if (tagmsg_path)
5830 preserve_tagmsg = 1;
5831 goto done;
5834 err = got_object_id_str(&tag_id_str, tag_id);
5835 if (err) {
5836 if (tagmsg_path)
5837 preserve_tagmsg = 1;
5838 goto done;
5840 printf("Created tag %s\n", tag_id_str);
5841 done:
5842 if (preserve_tagmsg) {
5843 fprintf(stderr, "%s: tag message preserved in %s\n",
5844 getprogname(), tagmsg_path);
5845 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
5846 err = got_error_from_errno2("unlink", tagmsg_path);
5847 free(tag_id_str);
5848 if (ref)
5849 got_ref_close(ref);
5850 free(commit_id);
5851 free(commit_id_str);
5852 free(refname);
5853 free(tagmsg);
5854 free(tagmsg_path);
5855 free(tagger);
5856 return err;
5859 static const struct got_error *
5860 cmd_tag(int argc, char *argv[])
5862 const struct got_error *error = NULL;
5863 struct got_repository *repo = NULL;
5864 struct got_worktree *worktree = NULL;
5865 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
5866 char *gitconfig_path = NULL;
5867 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
5868 int ch, do_list = 0;
5870 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
5871 switch (ch) {
5872 case 'c':
5873 commit_id_arg = optarg;
5874 break;
5875 case 'm':
5876 tagmsg = optarg;
5877 break;
5878 case 'r':
5879 repo_path = realpath(optarg, NULL);
5880 if (repo_path == NULL)
5881 return got_error_from_errno2("realpath",
5882 optarg);
5883 got_path_strip_trailing_slashes(repo_path);
5884 break;
5885 case 'l':
5886 do_list = 1;
5887 break;
5888 default:
5889 usage_tag();
5890 /* NOTREACHED */
5894 argc -= optind;
5895 argv += optind;
5897 if (do_list) {
5898 if (commit_id_arg != NULL)
5899 errx(1,
5900 "-c option can only be used when creating a tag");
5901 if (tagmsg)
5902 errx(1, "-l and -m options are mutually exclusive");
5903 if (argc > 0)
5904 usage_tag();
5905 } else if (argc != 1)
5906 usage_tag();
5908 tag_name = argv[0];
5910 #ifndef PROFILE
5911 if (do_list) {
5912 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5913 NULL) == -1)
5914 err(1, "pledge");
5915 } else {
5916 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5917 "sendfd unveil", NULL) == -1)
5918 err(1, "pledge");
5920 #endif
5921 cwd = getcwd(NULL, 0);
5922 if (cwd == NULL) {
5923 error = got_error_from_errno("getcwd");
5924 goto done;
5927 if (repo_path == NULL) {
5928 error = got_worktree_open(&worktree, cwd);
5929 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5930 goto done;
5931 else
5932 error = NULL;
5933 if (worktree) {
5934 repo_path =
5935 strdup(got_worktree_get_repo_path(worktree));
5936 if (repo_path == NULL)
5937 error = got_error_from_errno("strdup");
5938 if (error)
5939 goto done;
5940 } else {
5941 repo_path = strdup(cwd);
5942 if (repo_path == NULL) {
5943 error = got_error_from_errno("strdup");
5944 goto done;
5949 if (do_list) {
5950 error = got_repo_open(&repo, repo_path, NULL);
5951 if (error != NULL)
5952 goto done;
5953 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5954 if (error)
5955 goto done;
5956 error = list_tags(repo, worktree);
5957 } else {
5958 error = get_gitconfig_path(&gitconfig_path);
5959 if (error)
5960 goto done;
5961 error = got_repo_open(&repo, repo_path, gitconfig_path);
5962 if (error != NULL)
5963 goto done;
5965 if (tagmsg) {
5966 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5967 if (error)
5968 goto done;
5971 if (commit_id_arg == NULL) {
5972 struct got_reference *head_ref;
5973 struct got_object_id *commit_id;
5974 error = got_ref_open(&head_ref, repo,
5975 worktree ? got_worktree_get_head_ref_name(worktree)
5976 : GOT_REF_HEAD, 0);
5977 if (error)
5978 goto done;
5979 error = got_ref_resolve(&commit_id, repo, head_ref);
5980 got_ref_close(head_ref);
5981 if (error)
5982 goto done;
5983 error = got_object_id_str(&commit_id_str, commit_id);
5984 free(commit_id);
5985 if (error)
5986 goto done;
5989 error = add_tag(repo, worktree, tag_name,
5990 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
5992 done:
5993 if (repo)
5994 got_repo_close(repo);
5995 if (worktree)
5996 got_worktree_close(worktree);
5997 free(cwd);
5998 free(repo_path);
5999 free(gitconfig_path);
6000 free(commit_id_str);
6001 return error;
6004 __dead static void
6005 usage_add(void)
6007 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6008 getprogname());
6009 exit(1);
6012 static const struct got_error *
6013 add_progress(void *arg, unsigned char status, const char *path)
6015 while (path[0] == '/')
6016 path++;
6017 printf("%c %s\n", status, path);
6018 return NULL;
6021 static const struct got_error *
6022 cmd_add(int argc, char *argv[])
6024 const struct got_error *error = NULL;
6025 struct got_repository *repo = NULL;
6026 struct got_worktree *worktree = NULL;
6027 char *cwd = NULL;
6028 struct got_pathlist_head paths;
6029 struct got_pathlist_entry *pe;
6030 int ch, can_recurse = 0, no_ignores = 0;
6032 TAILQ_INIT(&paths);
6034 while ((ch = getopt(argc, argv, "IR")) != -1) {
6035 switch (ch) {
6036 case 'I':
6037 no_ignores = 1;
6038 break;
6039 case 'R':
6040 can_recurse = 1;
6041 break;
6042 default:
6043 usage_add();
6044 /* NOTREACHED */
6048 argc -= optind;
6049 argv += optind;
6051 #ifndef PROFILE
6052 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6053 NULL) == -1)
6054 err(1, "pledge");
6055 #endif
6056 if (argc < 1)
6057 usage_add();
6059 cwd = getcwd(NULL, 0);
6060 if (cwd == NULL) {
6061 error = got_error_from_errno("getcwd");
6062 goto done;
6065 error = got_worktree_open(&worktree, cwd);
6066 if (error) {
6067 if (error->code == GOT_ERR_NOT_WORKTREE)
6068 error = wrap_not_worktree_error(error, "add", cwd);
6069 goto done;
6072 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6073 NULL);
6074 if (error != NULL)
6075 goto done;
6077 error = apply_unveil(got_repo_get_path(repo), 1,
6078 got_worktree_get_root_path(worktree));
6079 if (error)
6080 goto done;
6082 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6083 if (error)
6084 goto done;
6086 if (!can_recurse && no_ignores) {
6087 error = got_error_msg(GOT_ERR_BAD_PATH,
6088 "disregarding ignores requires -R option");
6089 goto done;
6093 if (!can_recurse) {
6094 char *ondisk_path;
6095 struct stat sb;
6096 TAILQ_FOREACH(pe, &paths, entry) {
6097 if (asprintf(&ondisk_path, "%s/%s",
6098 got_worktree_get_root_path(worktree),
6099 pe->path) == -1) {
6100 error = got_error_from_errno("asprintf");
6101 goto done;
6103 if (lstat(ondisk_path, &sb) == -1) {
6104 if (errno == ENOENT) {
6105 free(ondisk_path);
6106 continue;
6108 error = got_error_from_errno2("lstat",
6109 ondisk_path);
6110 free(ondisk_path);
6111 goto done;
6113 free(ondisk_path);
6114 if (S_ISDIR(sb.st_mode)) {
6115 error = got_error_msg(GOT_ERR_BAD_PATH,
6116 "adding directories requires -R option");
6117 goto done;
6122 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6123 NULL, repo, no_ignores);
6124 done:
6125 if (repo)
6126 got_repo_close(repo);
6127 if (worktree)
6128 got_worktree_close(worktree);
6129 TAILQ_FOREACH(pe, &paths, entry)
6130 free((char *)pe->path);
6131 got_pathlist_free(&paths);
6132 free(cwd);
6133 return error;
6136 __dead static void
6137 usage_remove(void)
6139 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6140 "path ...\n", getprogname());
6141 exit(1);
6144 static const struct got_error *
6145 print_remove_status(void *arg, unsigned char status,
6146 unsigned char staged_status, const char *path)
6148 while (path[0] == '/')
6149 path++;
6150 if (status == GOT_STATUS_NONEXISTENT)
6151 return NULL;
6152 if (status == staged_status && (status == GOT_STATUS_DELETE))
6153 status = GOT_STATUS_NO_CHANGE;
6154 printf("%c%c %s\n", status, staged_status, path);
6155 return NULL;
6158 static const struct got_error *
6159 cmd_remove(int argc, char *argv[])
6161 const struct got_error *error = NULL;
6162 struct got_worktree *worktree = NULL;
6163 struct got_repository *repo = NULL;
6164 const char *status_codes = NULL;
6165 char *cwd = NULL;
6166 struct got_pathlist_head paths;
6167 struct got_pathlist_entry *pe;
6168 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6170 TAILQ_INIT(&paths);
6172 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6173 switch (ch) {
6174 case 'f':
6175 delete_local_mods = 1;
6176 break;
6177 case 'k':
6178 keep_on_disk = 1;
6179 break;
6180 case 'R':
6181 can_recurse = 1;
6182 break;
6183 case 's':
6184 for (i = 0; i < strlen(optarg); i++) {
6185 switch (optarg[i]) {
6186 case GOT_STATUS_MODIFY:
6187 delete_local_mods = 1;
6188 break;
6189 case GOT_STATUS_MISSING:
6190 break;
6191 default:
6192 errx(1, "invalid status code '%c'",
6193 optarg[i]);
6196 status_codes = optarg;
6197 break;
6198 default:
6199 usage_remove();
6200 /* NOTREACHED */
6204 argc -= optind;
6205 argv += optind;
6207 #ifndef PROFILE
6208 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6209 NULL) == -1)
6210 err(1, "pledge");
6211 #endif
6212 if (argc < 1)
6213 usage_remove();
6215 cwd = getcwd(NULL, 0);
6216 if (cwd == NULL) {
6217 error = got_error_from_errno("getcwd");
6218 goto done;
6220 error = got_worktree_open(&worktree, cwd);
6221 if (error) {
6222 if (error->code == GOT_ERR_NOT_WORKTREE)
6223 error = wrap_not_worktree_error(error, "remove", cwd);
6224 goto done;
6227 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6228 NULL);
6229 if (error)
6230 goto done;
6232 error = apply_unveil(got_repo_get_path(repo), 1,
6233 got_worktree_get_root_path(worktree));
6234 if (error)
6235 goto done;
6237 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6238 if (error)
6239 goto done;
6241 if (!can_recurse) {
6242 char *ondisk_path;
6243 struct stat sb;
6244 TAILQ_FOREACH(pe, &paths, entry) {
6245 if (asprintf(&ondisk_path, "%s/%s",
6246 got_worktree_get_root_path(worktree),
6247 pe->path) == -1) {
6248 error = got_error_from_errno("asprintf");
6249 goto done;
6251 if (lstat(ondisk_path, &sb) == -1) {
6252 if (errno == ENOENT) {
6253 free(ondisk_path);
6254 continue;
6256 error = got_error_from_errno2("lstat",
6257 ondisk_path);
6258 free(ondisk_path);
6259 goto done;
6261 free(ondisk_path);
6262 if (S_ISDIR(sb.st_mode)) {
6263 error = got_error_msg(GOT_ERR_BAD_PATH,
6264 "removing directories requires -R option");
6265 goto done;
6270 error = got_worktree_schedule_delete(worktree, &paths,
6271 delete_local_mods, status_codes, print_remove_status, NULL,
6272 repo, keep_on_disk);
6273 done:
6274 if (repo)
6275 got_repo_close(repo);
6276 if (worktree)
6277 got_worktree_close(worktree);
6278 TAILQ_FOREACH(pe, &paths, entry)
6279 free((char *)pe->path);
6280 got_pathlist_free(&paths);
6281 free(cwd);
6282 return error;
6285 __dead static void
6286 usage_revert(void)
6288 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6289 "path ...\n", getprogname());
6290 exit(1);
6293 static const struct got_error *
6294 revert_progress(void *arg, unsigned char status, const char *path)
6296 if (status == GOT_STATUS_UNVERSIONED)
6297 return NULL;
6299 while (path[0] == '/')
6300 path++;
6301 printf("%c %s\n", status, path);
6302 return NULL;
6305 struct choose_patch_arg {
6306 FILE *patch_script_file;
6307 const char *action;
6310 static const struct got_error *
6311 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6312 int nchanges, const char *action)
6314 char *line = NULL;
6315 size_t linesize = 0;
6316 ssize_t linelen;
6318 switch (status) {
6319 case GOT_STATUS_ADD:
6320 printf("A %s\n%s this addition? [y/n] ", path, action);
6321 break;
6322 case GOT_STATUS_DELETE:
6323 printf("D %s\n%s this deletion? [y/n] ", path, action);
6324 break;
6325 case GOT_STATUS_MODIFY:
6326 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6327 return got_error_from_errno("fseek");
6328 printf(GOT_COMMIT_SEP_STR);
6329 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6330 printf("%s", line);
6331 if (ferror(patch_file))
6332 return got_error_from_errno("getline");
6333 printf(GOT_COMMIT_SEP_STR);
6334 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6335 path, n, nchanges, action);
6336 break;
6337 default:
6338 return got_error_path(path, GOT_ERR_FILE_STATUS);
6341 return NULL;
6344 static const struct got_error *
6345 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6346 FILE *patch_file, int n, int nchanges)
6348 const struct got_error *err = NULL;
6349 char *line = NULL;
6350 size_t linesize = 0;
6351 ssize_t linelen;
6352 int resp = ' ';
6353 struct choose_patch_arg *a = arg;
6355 *choice = GOT_PATCH_CHOICE_NONE;
6357 if (a->patch_script_file) {
6358 char *nl;
6359 err = show_change(status, path, patch_file, n, nchanges,
6360 a->action);
6361 if (err)
6362 return err;
6363 linelen = getline(&line, &linesize, a->patch_script_file);
6364 if (linelen == -1) {
6365 if (ferror(a->patch_script_file))
6366 return got_error_from_errno("getline");
6367 return NULL;
6369 nl = strchr(line, '\n');
6370 if (nl)
6371 *nl = '\0';
6372 if (strcmp(line, "y") == 0) {
6373 *choice = GOT_PATCH_CHOICE_YES;
6374 printf("y\n");
6375 } else if (strcmp(line, "n") == 0) {
6376 *choice = GOT_PATCH_CHOICE_NO;
6377 printf("n\n");
6378 } else if (strcmp(line, "q") == 0 &&
6379 status == GOT_STATUS_MODIFY) {
6380 *choice = GOT_PATCH_CHOICE_QUIT;
6381 printf("q\n");
6382 } else
6383 printf("invalid response '%s'\n", line);
6384 free(line);
6385 return NULL;
6388 while (resp != 'y' && resp != 'n' && resp != 'q') {
6389 err = show_change(status, path, patch_file, n, nchanges,
6390 a->action);
6391 if (err)
6392 return err;
6393 resp = getchar();
6394 if (resp == '\n')
6395 resp = getchar();
6396 if (status == GOT_STATUS_MODIFY) {
6397 if (resp != 'y' && resp != 'n' && resp != 'q') {
6398 printf("invalid response '%c'\n", resp);
6399 resp = ' ';
6401 } else if (resp != 'y' && resp != 'n') {
6402 printf("invalid response '%c'\n", resp);
6403 resp = ' ';
6407 if (resp == 'y')
6408 *choice = GOT_PATCH_CHOICE_YES;
6409 else if (resp == 'n')
6410 *choice = GOT_PATCH_CHOICE_NO;
6411 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6412 *choice = GOT_PATCH_CHOICE_QUIT;
6414 return NULL;
6418 static const struct got_error *
6419 cmd_revert(int argc, char *argv[])
6421 const struct got_error *error = NULL;
6422 struct got_worktree *worktree = NULL;
6423 struct got_repository *repo = NULL;
6424 char *cwd = NULL, *path = NULL;
6425 struct got_pathlist_head paths;
6426 struct got_pathlist_entry *pe;
6427 int ch, can_recurse = 0, pflag = 0;
6428 FILE *patch_script_file = NULL;
6429 const char *patch_script_path = NULL;
6430 struct choose_patch_arg cpa;
6432 TAILQ_INIT(&paths);
6434 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6435 switch (ch) {
6436 case 'p':
6437 pflag = 1;
6438 break;
6439 case 'F':
6440 patch_script_path = optarg;
6441 break;
6442 case 'R':
6443 can_recurse = 1;
6444 break;
6445 default:
6446 usage_revert();
6447 /* NOTREACHED */
6451 argc -= optind;
6452 argv += optind;
6454 #ifndef PROFILE
6455 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6456 "unveil", NULL) == -1)
6457 err(1, "pledge");
6458 #endif
6459 if (argc < 1)
6460 usage_revert();
6461 if (patch_script_path && !pflag)
6462 errx(1, "-F option can only be used together with -p option");
6464 cwd = getcwd(NULL, 0);
6465 if (cwd == NULL) {
6466 error = got_error_from_errno("getcwd");
6467 goto done;
6469 error = got_worktree_open(&worktree, cwd);
6470 if (error) {
6471 if (error->code == GOT_ERR_NOT_WORKTREE)
6472 error = wrap_not_worktree_error(error, "revert", cwd);
6473 goto done;
6476 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6477 NULL);
6478 if (error != NULL)
6479 goto done;
6481 if (patch_script_path) {
6482 patch_script_file = fopen(patch_script_path, "r");
6483 if (patch_script_file == NULL) {
6484 error = got_error_from_errno2("fopen",
6485 patch_script_path);
6486 goto done;
6489 error = apply_unveil(got_repo_get_path(repo), 1,
6490 got_worktree_get_root_path(worktree));
6491 if (error)
6492 goto done;
6494 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6495 if (error)
6496 goto done;
6498 if (!can_recurse) {
6499 char *ondisk_path;
6500 struct stat sb;
6501 TAILQ_FOREACH(pe, &paths, entry) {
6502 if (asprintf(&ondisk_path, "%s/%s",
6503 got_worktree_get_root_path(worktree),
6504 pe->path) == -1) {
6505 error = got_error_from_errno("asprintf");
6506 goto done;
6508 if (lstat(ondisk_path, &sb) == -1) {
6509 if (errno == ENOENT) {
6510 free(ondisk_path);
6511 continue;
6513 error = got_error_from_errno2("lstat",
6514 ondisk_path);
6515 free(ondisk_path);
6516 goto done;
6518 free(ondisk_path);
6519 if (S_ISDIR(sb.st_mode)) {
6520 error = got_error_msg(GOT_ERR_BAD_PATH,
6521 "reverting directories requires -R option");
6522 goto done;
6527 cpa.patch_script_file = patch_script_file;
6528 cpa.action = "revert";
6529 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6530 pflag ? choose_patch : NULL, &cpa, repo);
6531 done:
6532 if (patch_script_file && fclose(patch_script_file) == EOF &&
6533 error == NULL)
6534 error = got_error_from_errno2("fclose", patch_script_path);
6535 if (repo)
6536 got_repo_close(repo);
6537 if (worktree)
6538 got_worktree_close(worktree);
6539 free(path);
6540 free(cwd);
6541 return error;
6544 __dead static void
6545 usage_commit(void)
6547 fprintf(stderr, "usage: %s commit [-m msg] [-S] [path ...]\n",
6548 getprogname());
6549 exit(1);
6552 struct collect_commit_logmsg_arg {
6553 const char *cmdline_log;
6554 const char *editor;
6555 const char *worktree_path;
6556 const char *branch_name;
6557 const char *repo_path;
6558 char *logmsg_path;
6562 static const struct got_error *
6563 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6564 void *arg)
6566 char *initial_content = NULL;
6567 struct got_pathlist_entry *pe;
6568 const struct got_error *err = NULL;
6569 char *template = NULL;
6570 struct collect_commit_logmsg_arg *a = arg;
6571 int initial_content_len;
6572 int fd = -1;
6573 size_t len;
6575 /* if a message was specified on the command line, just use it */
6576 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6577 len = strlen(a->cmdline_log) + 1;
6578 *logmsg = malloc(len + 1);
6579 if (*logmsg == NULL)
6580 return got_error_from_errno("malloc");
6581 strlcpy(*logmsg, a->cmdline_log, len);
6582 return NULL;
6585 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6586 return got_error_from_errno("asprintf");
6588 initial_content_len = asprintf(&initial_content,
6589 "\n# changes to be committed on branch %s:\n",
6590 a->branch_name);
6591 if (initial_content_len == -1)
6592 return got_error_from_errno("asprintf");
6594 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6595 if (err)
6596 goto done;
6598 if (write(fd, initial_content, initial_content_len) == -1) {
6599 err = got_error_from_errno2("write", a->logmsg_path);
6600 goto done;
6603 TAILQ_FOREACH(pe, commitable_paths, entry) {
6604 struct got_commitable *ct = pe->data;
6605 dprintf(fd, "# %c %s\n",
6606 got_commitable_get_status(ct),
6607 got_commitable_get_path(ct));
6610 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
6611 done:
6612 free(initial_content);
6613 free(template);
6615 if (fd != -1 && close(fd) == -1 && err == NULL)
6616 err = got_error_from_errno2("close", a->logmsg_path);
6618 /* Editor is done; we can now apply unveil(2) */
6619 if (err == NULL)
6620 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6621 if (err) {
6622 free(*logmsg);
6623 *logmsg = NULL;
6625 return err;
6628 static const struct got_error *
6629 cmd_commit(int argc, char *argv[])
6631 const struct got_error *error = NULL;
6632 struct got_worktree *worktree = NULL;
6633 struct got_repository *repo = NULL;
6634 char *cwd = NULL, *id_str = NULL;
6635 struct got_object_id *id = NULL;
6636 const char *logmsg = NULL;
6637 struct collect_commit_logmsg_arg cl_arg;
6638 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6639 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6640 int allow_bad_symlinks = 0;
6641 struct got_pathlist_head paths;
6643 TAILQ_INIT(&paths);
6644 cl_arg.logmsg_path = NULL;
6646 while ((ch = getopt(argc, argv, "m:S")) != -1) {
6647 switch (ch) {
6648 case 'm':
6649 logmsg = optarg;
6650 break;
6651 case 'S':
6652 allow_bad_symlinks = 1;
6653 break;
6654 default:
6655 usage_commit();
6656 /* NOTREACHED */
6660 argc -= optind;
6661 argv += optind;
6663 #ifndef PROFILE
6664 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6665 "unveil", NULL) == -1)
6666 err(1, "pledge");
6667 #endif
6668 cwd = getcwd(NULL, 0);
6669 if (cwd == NULL) {
6670 error = got_error_from_errno("getcwd");
6671 goto done;
6673 error = got_worktree_open(&worktree, cwd);
6674 if (error) {
6675 if (error->code == GOT_ERR_NOT_WORKTREE)
6676 error = wrap_not_worktree_error(error, "commit", cwd);
6677 goto done;
6680 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6681 if (error)
6682 goto done;
6683 if (rebase_in_progress) {
6684 error = got_error(GOT_ERR_REBASING);
6685 goto done;
6688 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6689 worktree);
6690 if (error)
6691 goto done;
6693 error = get_gitconfig_path(&gitconfig_path);
6694 if (error)
6695 goto done;
6696 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6697 gitconfig_path);
6698 if (error != NULL)
6699 goto done;
6701 error = get_author(&author, repo, worktree);
6702 if (error)
6703 return error;
6706 * unveil(2) traverses exec(2); if an editor is used we have
6707 * to apply unveil after the log message has been written.
6709 if (logmsg == NULL || strlen(logmsg) == 0)
6710 error = get_editor(&editor);
6711 else
6712 error = apply_unveil(got_repo_get_path(repo), 0,
6713 got_worktree_get_root_path(worktree));
6714 if (error)
6715 goto done;
6717 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6718 if (error)
6719 goto done;
6721 cl_arg.editor = editor;
6722 cl_arg.cmdline_log = logmsg;
6723 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6724 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6725 if (!histedit_in_progress) {
6726 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6727 error = got_error(GOT_ERR_COMMIT_BRANCH);
6728 goto done;
6730 cl_arg.branch_name += 11;
6732 cl_arg.repo_path = got_repo_get_path(repo);
6733 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6734 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
6735 print_status, NULL, repo);
6736 if (error) {
6737 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6738 cl_arg.logmsg_path != NULL)
6739 preserve_logmsg = 1;
6740 goto done;
6743 error = got_object_id_str(&id_str, id);
6744 if (error)
6745 goto done;
6746 printf("Created commit %s\n", id_str);
6747 done:
6748 if (preserve_logmsg) {
6749 fprintf(stderr, "%s: log message preserved in %s\n",
6750 getprogname(), cl_arg.logmsg_path);
6751 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6752 error == NULL)
6753 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6754 free(cl_arg.logmsg_path);
6755 if (repo)
6756 got_repo_close(repo);
6757 if (worktree)
6758 got_worktree_close(worktree);
6759 free(cwd);
6760 free(id_str);
6761 free(gitconfig_path);
6762 free(editor);
6763 free(author);
6764 return error;
6767 __dead static void
6768 usage_cherrypick(void)
6770 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6771 exit(1);
6774 static const struct got_error *
6775 cmd_cherrypick(int argc, char *argv[])
6777 const struct got_error *error = NULL;
6778 struct got_worktree *worktree = NULL;
6779 struct got_repository *repo = NULL;
6780 char *cwd = NULL, *commit_id_str = NULL;
6781 struct got_object_id *commit_id = NULL;
6782 struct got_commit_object *commit = NULL;
6783 struct got_object_qid *pid;
6784 struct got_reference *head_ref = NULL;
6785 int ch;
6786 struct got_update_progress_arg upa;
6788 while ((ch = getopt(argc, argv, "")) != -1) {
6789 switch (ch) {
6790 default:
6791 usage_cherrypick();
6792 /* NOTREACHED */
6796 argc -= optind;
6797 argv += optind;
6799 #ifndef PROFILE
6800 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6801 "unveil", NULL) == -1)
6802 err(1, "pledge");
6803 #endif
6804 if (argc != 1)
6805 usage_cherrypick();
6807 cwd = getcwd(NULL, 0);
6808 if (cwd == NULL) {
6809 error = got_error_from_errno("getcwd");
6810 goto done;
6812 error = got_worktree_open(&worktree, cwd);
6813 if (error) {
6814 if (error->code == GOT_ERR_NOT_WORKTREE)
6815 error = wrap_not_worktree_error(error, "cherrypick",
6816 cwd);
6817 goto done;
6820 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6821 NULL);
6822 if (error != NULL)
6823 goto done;
6825 error = apply_unveil(got_repo_get_path(repo), 0,
6826 got_worktree_get_root_path(worktree));
6827 if (error)
6828 goto done;
6830 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6831 GOT_OBJ_TYPE_COMMIT, repo);
6832 if (error != NULL) {
6833 struct got_reference *ref;
6834 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6835 goto done;
6836 error = got_ref_open(&ref, repo, argv[0], 0);
6837 if (error != NULL)
6838 goto done;
6839 error = got_ref_resolve(&commit_id, repo, ref);
6840 got_ref_close(ref);
6841 if (error != NULL)
6842 goto done;
6844 error = got_object_id_str(&commit_id_str, commit_id);
6845 if (error)
6846 goto done;
6848 error = got_ref_open(&head_ref, repo,
6849 got_worktree_get_head_ref_name(worktree), 0);
6850 if (error != NULL)
6851 goto done;
6853 error = check_same_branch(commit_id, head_ref, NULL, repo);
6854 if (error) {
6855 if (error->code != GOT_ERR_ANCESTRY)
6856 goto done;
6857 error = NULL;
6858 } else {
6859 error = got_error(GOT_ERR_SAME_BRANCH);
6860 goto done;
6863 error = got_object_open_as_commit(&commit, repo, commit_id);
6864 if (error)
6865 goto done;
6866 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6867 memset(&upa, 0, sizeof(upa));
6868 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
6869 commit_id, repo, update_progress, &upa, check_cancelled,
6870 NULL);
6871 if (error != NULL)
6872 goto done;
6874 if (upa.did_something)
6875 printf("Merged commit %s\n", commit_id_str);
6876 print_update_progress_stats(&upa);
6877 done:
6878 if (commit)
6879 got_object_commit_close(commit);
6880 free(commit_id_str);
6881 if (head_ref)
6882 got_ref_close(head_ref);
6883 if (worktree)
6884 got_worktree_close(worktree);
6885 if (repo)
6886 got_repo_close(repo);
6887 return error;
6890 __dead static void
6891 usage_backout(void)
6893 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
6894 exit(1);
6897 static const struct got_error *
6898 cmd_backout(int argc, char *argv[])
6900 const struct got_error *error = NULL;
6901 struct got_worktree *worktree = NULL;
6902 struct got_repository *repo = NULL;
6903 char *cwd = NULL, *commit_id_str = NULL;
6904 struct got_object_id *commit_id = NULL;
6905 struct got_commit_object *commit = NULL;
6906 struct got_object_qid *pid;
6907 struct got_reference *head_ref = NULL;
6908 int ch;
6909 struct got_update_progress_arg upa;
6911 while ((ch = getopt(argc, argv, "")) != -1) {
6912 switch (ch) {
6913 default:
6914 usage_backout();
6915 /* NOTREACHED */
6919 argc -= optind;
6920 argv += optind;
6922 #ifndef PROFILE
6923 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6924 "unveil", NULL) == -1)
6925 err(1, "pledge");
6926 #endif
6927 if (argc != 1)
6928 usage_backout();
6930 cwd = getcwd(NULL, 0);
6931 if (cwd == NULL) {
6932 error = got_error_from_errno("getcwd");
6933 goto done;
6935 error = got_worktree_open(&worktree, cwd);
6936 if (error) {
6937 if (error->code == GOT_ERR_NOT_WORKTREE)
6938 error = wrap_not_worktree_error(error, "backout", cwd);
6939 goto done;
6942 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6943 NULL);
6944 if (error != NULL)
6945 goto done;
6947 error = apply_unveil(got_repo_get_path(repo), 0,
6948 got_worktree_get_root_path(worktree));
6949 if (error)
6950 goto done;
6952 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6953 GOT_OBJ_TYPE_COMMIT, repo);
6954 if (error != NULL) {
6955 struct got_reference *ref;
6956 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6957 goto done;
6958 error = got_ref_open(&ref, repo, argv[0], 0);
6959 if (error != NULL)
6960 goto done;
6961 error = got_ref_resolve(&commit_id, repo, ref);
6962 got_ref_close(ref);
6963 if (error != NULL)
6964 goto done;
6966 error = got_object_id_str(&commit_id_str, commit_id);
6967 if (error)
6968 goto done;
6970 error = got_ref_open(&head_ref, repo,
6971 got_worktree_get_head_ref_name(worktree), 0);
6972 if (error != NULL)
6973 goto done;
6975 error = check_same_branch(commit_id, head_ref, NULL, repo);
6976 if (error)
6977 goto done;
6979 error = got_object_open_as_commit(&commit, repo, commit_id);
6980 if (error)
6981 goto done;
6982 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6983 if (pid == NULL) {
6984 error = got_error(GOT_ERR_ROOT_COMMIT);
6985 goto done;
6988 memset(&upa, 0, sizeof(upa));
6989 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
6990 update_progress, &upa, check_cancelled, NULL);
6991 if (error != NULL)
6992 goto done;
6994 if (upa.did_something)
6995 printf("Backed out commit %s\n", commit_id_str);
6996 print_update_progress_stats(&upa);
6997 done:
6998 if (commit)
6999 got_object_commit_close(commit);
7000 free(commit_id_str);
7001 if (head_ref)
7002 got_ref_close(head_ref);
7003 if (worktree)
7004 got_worktree_close(worktree);
7005 if (repo)
7006 got_repo_close(repo);
7007 return error;
7010 __dead static void
7011 usage_rebase(void)
7013 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
7014 getprogname());
7015 exit(1);
7018 void
7019 trim_logmsg(char *logmsg, int limit)
7021 char *nl;
7022 size_t len;
7024 len = strlen(logmsg);
7025 if (len > limit)
7026 len = limit;
7027 logmsg[len] = '\0';
7028 nl = strchr(logmsg, '\n');
7029 if (nl)
7030 *nl = '\0';
7033 static const struct got_error *
7034 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
7036 const struct got_error *err;
7037 char *logmsg0 = NULL;
7038 const char *s;
7040 err = got_object_commit_get_logmsg(&logmsg0, commit);
7041 if (err)
7042 return err;
7044 s = logmsg0;
7045 while (isspace((unsigned char)s[0]))
7046 s++;
7048 *logmsg = strdup(s);
7049 if (*logmsg == NULL) {
7050 err = got_error_from_errno("strdup");
7051 goto done;
7054 trim_logmsg(*logmsg, limit);
7055 done:
7056 free(logmsg0);
7057 return err;
7060 static const struct got_error *
7061 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
7063 const struct got_error *err;
7064 struct got_commit_object *commit = NULL;
7065 char *id_str = NULL, *logmsg = NULL;
7067 err = got_object_open_as_commit(&commit, repo, id);
7068 if (err)
7069 return err;
7071 err = got_object_id_str(&id_str, id);
7072 if (err)
7073 goto done;
7075 id_str[12] = '\0';
7077 err = get_short_logmsg(&logmsg, 42, commit);
7078 if (err)
7079 goto done;
7081 printf("%s -> merge conflict: %s\n", id_str, logmsg);
7082 done:
7083 free(id_str);
7084 got_object_commit_close(commit);
7085 free(logmsg);
7086 return err;
7089 static const struct got_error *
7090 show_rebase_progress(struct got_commit_object *commit,
7091 struct got_object_id *old_id, struct got_object_id *new_id)
7093 const struct got_error *err;
7094 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7096 err = got_object_id_str(&old_id_str, old_id);
7097 if (err)
7098 goto done;
7100 if (new_id) {
7101 err = got_object_id_str(&new_id_str, new_id);
7102 if (err)
7103 goto done;
7106 old_id_str[12] = '\0';
7107 if (new_id_str)
7108 new_id_str[12] = '\0';
7110 err = get_short_logmsg(&logmsg, 42, commit);
7111 if (err)
7112 goto done;
7114 printf("%s -> %s: %s\n", old_id_str,
7115 new_id_str ? new_id_str : "no-op change", logmsg);
7116 done:
7117 free(old_id_str);
7118 free(new_id_str);
7119 free(logmsg);
7120 return err;
7123 static const struct got_error *
7124 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
7125 struct got_reference *branch, struct got_reference *new_base_branch,
7126 struct got_reference *tmp_branch, struct got_repository *repo)
7128 printf("Switching work tree to %s\n", got_ref_get_name(branch));
7129 return got_worktree_rebase_complete(worktree, fileindex,
7130 new_base_branch, tmp_branch, branch, repo);
7133 static const struct got_error *
7134 rebase_commit(struct got_pathlist_head *merged_paths,
7135 struct got_worktree *worktree, struct got_fileindex *fileindex,
7136 struct got_reference *tmp_branch,
7137 struct got_object_id *commit_id, struct got_repository *repo)
7139 const struct got_error *error;
7140 struct got_commit_object *commit;
7141 struct got_object_id *new_commit_id;
7143 error = got_object_open_as_commit(&commit, repo, commit_id);
7144 if (error)
7145 return error;
7147 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
7148 worktree, fileindex, tmp_branch, commit, commit_id, repo);
7149 if (error) {
7150 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
7151 goto done;
7152 error = show_rebase_progress(commit, commit_id, NULL);
7153 } else {
7154 error = show_rebase_progress(commit, commit_id, new_commit_id);
7155 free(new_commit_id);
7157 done:
7158 got_object_commit_close(commit);
7159 return error;
7162 struct check_path_prefix_arg {
7163 const char *path_prefix;
7164 size_t len;
7165 int errcode;
7168 static const struct got_error *
7169 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
7170 struct got_blob_object *blob2, struct got_object_id *id1,
7171 struct got_object_id *id2, const char *path1, const char *path2,
7172 mode_t mode1, mode_t mode2, struct got_repository *repo)
7174 struct check_path_prefix_arg *a = arg;
7176 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
7177 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
7178 return got_error(a->errcode);
7180 return NULL;
7183 static const struct got_error *
7184 check_path_prefix(struct got_object_id *parent_id,
7185 struct got_object_id *commit_id, const char *path_prefix,
7186 int errcode, struct got_repository *repo)
7188 const struct got_error *err;
7189 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7190 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7191 struct check_path_prefix_arg cpp_arg;
7193 if (got_path_is_root_dir(path_prefix))
7194 return NULL;
7196 err = got_object_open_as_commit(&commit, repo, commit_id);
7197 if (err)
7198 goto done;
7200 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7201 if (err)
7202 goto done;
7204 err = got_object_open_as_tree(&tree1, repo,
7205 got_object_commit_get_tree_id(parent_commit));
7206 if (err)
7207 goto done;
7209 err = got_object_open_as_tree(&tree2, repo,
7210 got_object_commit_get_tree_id(commit));
7211 if (err)
7212 goto done;
7214 cpp_arg.path_prefix = path_prefix;
7215 while (cpp_arg.path_prefix[0] == '/')
7216 cpp_arg.path_prefix++;
7217 cpp_arg.len = strlen(cpp_arg.path_prefix);
7218 cpp_arg.errcode = errcode;
7219 err = got_diff_tree(tree1, tree2, "", "", repo,
7220 check_path_prefix_in_diff, &cpp_arg, 0);
7221 done:
7222 if (tree1)
7223 got_object_tree_close(tree1);
7224 if (tree2)
7225 got_object_tree_close(tree2);
7226 if (commit)
7227 got_object_commit_close(commit);
7228 if (parent_commit)
7229 got_object_commit_close(parent_commit);
7230 return err;
7233 static const struct got_error *
7234 collect_commits(struct got_object_id_queue *commits,
7235 struct got_object_id *initial_commit_id,
7236 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7237 const char *path_prefix, int path_prefix_errcode,
7238 struct got_repository *repo)
7240 const struct got_error *err = NULL;
7241 struct got_commit_graph *graph = NULL;
7242 struct got_object_id *parent_id = NULL;
7243 struct got_object_qid *qid;
7244 struct got_object_id *commit_id = initial_commit_id;
7246 err = got_commit_graph_open(&graph, "/", 1);
7247 if (err)
7248 return err;
7250 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7251 check_cancelled, NULL);
7252 if (err)
7253 goto done;
7254 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7255 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7256 check_cancelled, NULL);
7257 if (err) {
7258 if (err->code == GOT_ERR_ITER_COMPLETED) {
7259 err = got_error_msg(GOT_ERR_ANCESTRY,
7260 "ran out of commits to rebase before "
7261 "youngest common ancestor commit has "
7262 "been reached?!?");
7264 goto done;
7265 } else {
7266 err = check_path_prefix(parent_id, commit_id,
7267 path_prefix, path_prefix_errcode, repo);
7268 if (err)
7269 goto done;
7271 err = got_object_qid_alloc(&qid, commit_id);
7272 if (err)
7273 goto done;
7274 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
7275 commit_id = parent_id;
7278 done:
7279 got_commit_graph_close(graph);
7280 return err;
7283 static const struct got_error *
7284 cmd_rebase(int argc, char *argv[])
7286 const struct got_error *error = NULL;
7287 struct got_worktree *worktree = NULL;
7288 struct got_repository *repo = NULL;
7289 struct got_fileindex *fileindex = NULL;
7290 char *cwd = NULL;
7291 struct got_reference *branch = NULL;
7292 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
7293 struct got_object_id *commit_id = NULL, *parent_id = NULL;
7294 struct got_object_id *resume_commit_id = NULL;
7295 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
7296 struct got_commit_object *commit = NULL;
7297 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
7298 int histedit_in_progress = 0;
7299 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7300 struct got_object_id_queue commits;
7301 struct got_pathlist_head merged_paths;
7302 const struct got_object_id_queue *parent_ids;
7303 struct got_object_qid *qid, *pid;
7305 SIMPLEQ_INIT(&commits);
7306 TAILQ_INIT(&merged_paths);
7308 while ((ch = getopt(argc, argv, "ac")) != -1) {
7309 switch (ch) {
7310 case 'a':
7311 abort_rebase = 1;
7312 break;
7313 case 'c':
7314 continue_rebase = 1;
7315 break;
7316 default:
7317 usage_rebase();
7318 /* NOTREACHED */
7322 argc -= optind;
7323 argv += optind;
7325 #ifndef PROFILE
7326 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7327 "unveil", NULL) == -1)
7328 err(1, "pledge");
7329 #endif
7330 if (abort_rebase && continue_rebase)
7331 usage_rebase();
7332 else if (abort_rebase || continue_rebase) {
7333 if (argc != 0)
7334 usage_rebase();
7335 } else if (argc != 1)
7336 usage_rebase();
7338 cwd = getcwd(NULL, 0);
7339 if (cwd == NULL) {
7340 error = got_error_from_errno("getcwd");
7341 goto done;
7343 error = got_worktree_open(&worktree, cwd);
7344 if (error) {
7345 if (error->code == GOT_ERR_NOT_WORKTREE)
7346 error = wrap_not_worktree_error(error, "rebase", cwd);
7347 goto done;
7350 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7351 NULL);
7352 if (error != NULL)
7353 goto done;
7355 error = apply_unveil(got_repo_get_path(repo), 0,
7356 got_worktree_get_root_path(worktree));
7357 if (error)
7358 goto done;
7360 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7361 worktree);
7362 if (error)
7363 goto done;
7364 if (histedit_in_progress) {
7365 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7366 goto done;
7369 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7370 if (error)
7371 goto done;
7373 if (abort_rebase) {
7374 struct got_update_progress_arg upa;
7375 if (!rebase_in_progress) {
7376 error = got_error(GOT_ERR_NOT_REBASING);
7377 goto done;
7379 error = got_worktree_rebase_continue(&resume_commit_id,
7380 &new_base_branch, &tmp_branch, &branch, &fileindex,
7381 worktree, repo);
7382 if (error)
7383 goto done;
7384 printf("Switching work tree to %s\n",
7385 got_ref_get_symref_target(new_base_branch));
7386 memset(&upa, 0, sizeof(upa));
7387 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7388 new_base_branch, update_progress, &upa);
7389 if (error)
7390 goto done;
7391 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7392 print_update_progress_stats(&upa);
7393 goto done; /* nothing else to do */
7396 if (continue_rebase) {
7397 if (!rebase_in_progress) {
7398 error = got_error(GOT_ERR_NOT_REBASING);
7399 goto done;
7401 error = got_worktree_rebase_continue(&resume_commit_id,
7402 &new_base_branch, &tmp_branch, &branch, &fileindex,
7403 worktree, repo);
7404 if (error)
7405 goto done;
7407 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7408 resume_commit_id, repo);
7409 if (error)
7410 goto done;
7412 yca_id = got_object_id_dup(resume_commit_id);
7413 if (yca_id == NULL) {
7414 error = got_error_from_errno("got_object_id_dup");
7415 goto done;
7417 } else {
7418 error = got_ref_open(&branch, repo, argv[0], 0);
7419 if (error != NULL)
7420 goto done;
7423 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7424 if (error)
7425 goto done;
7427 if (!continue_rebase) {
7428 struct got_object_id *base_commit_id;
7430 base_commit_id = got_worktree_get_base_commit_id(worktree);
7431 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7432 base_commit_id, branch_head_commit_id, repo,
7433 check_cancelled, NULL);
7434 if (error)
7435 goto done;
7436 if (yca_id == NULL) {
7437 error = got_error_msg(GOT_ERR_ANCESTRY,
7438 "specified branch shares no common ancestry "
7439 "with work tree's branch");
7440 goto done;
7443 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7444 if (error) {
7445 if (error->code != GOT_ERR_ANCESTRY)
7446 goto done;
7447 error = NULL;
7448 } else {
7449 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7450 "specified branch resolves to a commit which "
7451 "is already contained in work tree's branch");
7452 goto done;
7454 error = got_worktree_rebase_prepare(&new_base_branch,
7455 &tmp_branch, &fileindex, worktree, branch, repo);
7456 if (error)
7457 goto done;
7460 commit_id = branch_head_commit_id;
7461 error = got_object_open_as_commit(&commit, repo, commit_id);
7462 if (error)
7463 goto done;
7465 parent_ids = got_object_commit_get_parent_ids(commit);
7466 pid = SIMPLEQ_FIRST(parent_ids);
7467 if (pid == NULL) {
7468 if (!continue_rebase) {
7469 struct got_update_progress_arg upa;
7470 memset(&upa, 0, sizeof(upa));
7471 error = got_worktree_rebase_abort(worktree, fileindex,
7472 repo, new_base_branch, update_progress, &upa);
7473 if (error)
7474 goto done;
7475 printf("Rebase of %s aborted\n",
7476 got_ref_get_name(branch));
7477 print_update_progress_stats(&upa);
7480 error = got_error(GOT_ERR_EMPTY_REBASE);
7481 goto done;
7483 error = collect_commits(&commits, commit_id, pid->id,
7484 yca_id, got_worktree_get_path_prefix(worktree),
7485 GOT_ERR_REBASE_PATH, repo);
7486 got_object_commit_close(commit);
7487 commit = NULL;
7488 if (error)
7489 goto done;
7491 if (SIMPLEQ_EMPTY(&commits)) {
7492 if (continue_rebase) {
7493 error = rebase_complete(worktree, fileindex,
7494 branch, new_base_branch, tmp_branch, repo);
7495 goto done;
7496 } else {
7497 /* Fast-forward the reference of the branch. */
7498 struct got_object_id *new_head_commit_id;
7499 char *id_str;
7500 error = got_ref_resolve(&new_head_commit_id, repo,
7501 new_base_branch);
7502 if (error)
7503 goto done;
7504 error = got_object_id_str(&id_str, new_head_commit_id);
7505 printf("Forwarding %s to commit %s\n",
7506 got_ref_get_name(branch), id_str);
7507 free(id_str);
7508 error = got_ref_change_ref(branch,
7509 new_head_commit_id);
7510 if (error)
7511 goto done;
7515 pid = NULL;
7516 SIMPLEQ_FOREACH(qid, &commits, entry) {
7517 struct got_update_progress_arg upa;
7519 commit_id = qid->id;
7520 parent_id = pid ? pid->id : yca_id;
7521 pid = qid;
7523 memset(&upa, 0, sizeof(upa));
7524 error = got_worktree_rebase_merge_files(&merged_paths,
7525 worktree, fileindex, parent_id, commit_id, repo,
7526 update_progress, &upa, check_cancelled, NULL);
7527 if (error)
7528 goto done;
7530 print_update_progress_stats(&upa);
7531 if (upa.conflicts > 0)
7532 rebase_status = GOT_STATUS_CONFLICT;
7534 if (rebase_status == GOT_STATUS_CONFLICT) {
7535 error = show_rebase_merge_conflict(qid->id, repo);
7536 if (error)
7537 goto done;
7538 got_worktree_rebase_pathlist_free(&merged_paths);
7539 break;
7542 error = rebase_commit(&merged_paths, worktree, fileindex,
7543 tmp_branch, commit_id, repo);
7544 got_worktree_rebase_pathlist_free(&merged_paths);
7545 if (error)
7546 goto done;
7549 if (rebase_status == GOT_STATUS_CONFLICT) {
7550 error = got_worktree_rebase_postpone(worktree, fileindex);
7551 if (error)
7552 goto done;
7553 error = got_error_msg(GOT_ERR_CONFLICTS,
7554 "conflicts must be resolved before rebasing can continue");
7555 } else
7556 error = rebase_complete(worktree, fileindex, branch,
7557 new_base_branch, tmp_branch, repo);
7558 done:
7559 got_object_id_queue_free(&commits);
7560 free(branch_head_commit_id);
7561 free(resume_commit_id);
7562 free(yca_id);
7563 if (commit)
7564 got_object_commit_close(commit);
7565 if (branch)
7566 got_ref_close(branch);
7567 if (new_base_branch)
7568 got_ref_close(new_base_branch);
7569 if (tmp_branch)
7570 got_ref_close(tmp_branch);
7571 if (worktree)
7572 got_worktree_close(worktree);
7573 if (repo)
7574 got_repo_close(repo);
7575 return error;
7578 __dead static void
7579 usage_histedit(void)
7581 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
7582 getprogname());
7583 exit(1);
7586 #define GOT_HISTEDIT_PICK 'p'
7587 #define GOT_HISTEDIT_EDIT 'e'
7588 #define GOT_HISTEDIT_FOLD 'f'
7589 #define GOT_HISTEDIT_DROP 'd'
7590 #define GOT_HISTEDIT_MESG 'm'
7592 static struct got_histedit_cmd {
7593 unsigned char code;
7594 const char *name;
7595 const char *desc;
7596 } got_histedit_cmds[] = {
7597 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7598 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7599 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7600 "be used" },
7601 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7602 { GOT_HISTEDIT_MESG, "mesg",
7603 "single-line log message for commit above (open editor if empty)" },
7606 struct got_histedit_list_entry {
7607 TAILQ_ENTRY(got_histedit_list_entry) entry;
7608 struct got_object_id *commit_id;
7609 const struct got_histedit_cmd *cmd;
7610 char *logmsg;
7612 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7614 static const struct got_error *
7615 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7616 FILE *f, struct got_repository *repo)
7618 const struct got_error *err = NULL;
7619 char *logmsg = NULL, *id_str = NULL;
7620 struct got_commit_object *commit = NULL;
7621 int n;
7623 err = got_object_open_as_commit(&commit, repo, commit_id);
7624 if (err)
7625 goto done;
7627 err = get_short_logmsg(&logmsg, 34, commit);
7628 if (err)
7629 goto done;
7631 err = got_object_id_str(&id_str, commit_id);
7632 if (err)
7633 goto done;
7635 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7636 if (n < 0)
7637 err = got_ferror(f, GOT_ERR_IO);
7638 done:
7639 if (commit)
7640 got_object_commit_close(commit);
7641 free(id_str);
7642 free(logmsg);
7643 return err;
7646 static const struct got_error *
7647 histedit_write_commit_list(struct got_object_id_queue *commits,
7648 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7650 const struct got_error *err = NULL;
7651 struct got_object_qid *qid;
7653 if (SIMPLEQ_EMPTY(commits))
7654 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7656 SIMPLEQ_FOREACH(qid, commits, entry) {
7657 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7658 f, repo);
7659 if (err)
7660 break;
7661 if (edit_logmsg_only) {
7662 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7663 if (n < 0) {
7664 err = got_ferror(f, GOT_ERR_IO);
7665 break;
7670 return err;
7673 static const struct got_error *
7674 write_cmd_list(FILE *f, const char *branch_name,
7675 struct got_object_id_queue *commits)
7677 const struct got_error *err = NULL;
7678 int n, i;
7679 char *id_str;
7680 struct got_object_qid *qid;
7682 qid = SIMPLEQ_FIRST(commits);
7683 err = got_object_id_str(&id_str, qid->id);
7684 if (err)
7685 return err;
7687 n = fprintf(f,
7688 "# Editing the history of branch '%s' starting at\n"
7689 "# commit %s\n"
7690 "# Commits will be processed in order from top to "
7691 "bottom of this file.\n", branch_name, id_str);
7692 if (n < 0) {
7693 err = got_ferror(f, GOT_ERR_IO);
7694 goto done;
7697 n = fprintf(f, "# Available histedit commands:\n");
7698 if (n < 0) {
7699 err = got_ferror(f, GOT_ERR_IO);
7700 goto done;
7703 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7704 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7705 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7706 cmd->desc);
7707 if (n < 0) {
7708 err = got_ferror(f, GOT_ERR_IO);
7709 break;
7712 done:
7713 free(id_str);
7714 return err;
7717 static const struct got_error *
7718 histedit_syntax_error(int lineno)
7720 static char msg[42];
7721 int ret;
7723 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7724 lineno);
7725 if (ret == -1 || ret >= sizeof(msg))
7726 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7728 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7731 static const struct got_error *
7732 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7733 char *logmsg, struct got_repository *repo)
7735 const struct got_error *err;
7736 struct got_commit_object *folded_commit = NULL;
7737 char *id_str, *folded_logmsg = NULL;
7739 err = got_object_id_str(&id_str, hle->commit_id);
7740 if (err)
7741 return err;
7743 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7744 if (err)
7745 goto done;
7747 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7748 if (err)
7749 goto done;
7750 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7751 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7752 folded_logmsg) == -1) {
7753 err = got_error_from_errno("asprintf");
7755 done:
7756 if (folded_commit)
7757 got_object_commit_close(folded_commit);
7758 free(id_str);
7759 free(folded_logmsg);
7760 return err;
7763 static struct got_histedit_list_entry *
7764 get_folded_commits(struct got_histedit_list_entry *hle)
7766 struct got_histedit_list_entry *prev, *folded = NULL;
7768 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7769 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7770 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7771 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7772 folded = prev;
7773 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7776 return folded;
7779 static const struct got_error *
7780 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7781 struct got_repository *repo)
7783 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7784 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7785 const struct got_error *err = NULL;
7786 struct got_commit_object *commit = NULL;
7787 int logmsg_len;
7788 int fd;
7789 struct got_histedit_list_entry *folded = NULL;
7791 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7792 if (err)
7793 return err;
7795 folded = get_folded_commits(hle);
7796 if (folded) {
7797 while (folded != hle) {
7798 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7799 folded = TAILQ_NEXT(folded, entry);
7800 continue;
7802 err = append_folded_commit_msg(&new_msg, folded,
7803 logmsg, repo);
7804 if (err)
7805 goto done;
7806 free(logmsg);
7807 logmsg = new_msg;
7808 folded = TAILQ_NEXT(folded, entry);
7812 err = got_object_id_str(&id_str, hle->commit_id);
7813 if (err)
7814 goto done;
7815 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7816 if (err)
7817 goto done;
7818 logmsg_len = asprintf(&new_msg,
7819 "%s\n# original log message of commit %s: %s",
7820 logmsg ? logmsg : "", id_str, orig_logmsg);
7821 if (logmsg_len == -1) {
7822 err = got_error_from_errno("asprintf");
7823 goto done;
7825 free(logmsg);
7826 logmsg = new_msg;
7828 err = got_object_id_str(&id_str, hle->commit_id);
7829 if (err)
7830 goto done;
7832 err = got_opentemp_named_fd(&logmsg_path, &fd,
7833 GOT_TMPDIR_STR "/got-logmsg");
7834 if (err)
7835 goto done;
7837 write(fd, logmsg, logmsg_len);
7838 close(fd);
7840 err = get_editor(&editor);
7841 if (err)
7842 goto done;
7844 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
7845 if (err) {
7846 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
7847 goto done;
7848 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
7850 done:
7851 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
7852 err = got_error_from_errno2("unlink", logmsg_path);
7853 free(logmsg_path);
7854 free(logmsg);
7855 free(orig_logmsg);
7856 free(editor);
7857 if (commit)
7858 got_object_commit_close(commit);
7859 return err;
7862 static const struct got_error *
7863 histedit_parse_list(struct got_histedit_list *histedit_cmds,
7864 FILE *f, struct got_repository *repo)
7866 const struct got_error *err = NULL;
7867 char *line = NULL, *p, *end;
7868 size_t size;
7869 ssize_t len;
7870 int lineno = 0, i;
7871 const struct got_histedit_cmd *cmd;
7872 struct got_object_id *commit_id = NULL;
7873 struct got_histedit_list_entry *hle = NULL;
7875 for (;;) {
7876 len = getline(&line, &size, f);
7877 if (len == -1) {
7878 const struct got_error *getline_err;
7879 if (feof(f))
7880 break;
7881 getline_err = got_error_from_errno("getline");
7882 err = got_ferror(f, getline_err->code);
7883 break;
7885 lineno++;
7886 p = line;
7887 while (isspace((unsigned char)p[0]))
7888 p++;
7889 if (p[0] == '#' || p[0] == '\0') {
7890 free(line);
7891 line = NULL;
7892 continue;
7894 cmd = NULL;
7895 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7896 cmd = &got_histedit_cmds[i];
7897 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
7898 isspace((unsigned char)p[strlen(cmd->name)])) {
7899 p += strlen(cmd->name);
7900 break;
7902 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
7903 p++;
7904 break;
7907 if (i == nitems(got_histedit_cmds)) {
7908 err = histedit_syntax_error(lineno);
7909 break;
7911 while (isspace((unsigned char)p[0]))
7912 p++;
7913 if (cmd->code == GOT_HISTEDIT_MESG) {
7914 if (hle == NULL || hle->logmsg != NULL) {
7915 err = got_error(GOT_ERR_HISTEDIT_CMD);
7916 break;
7918 if (p[0] == '\0') {
7919 err = histedit_edit_logmsg(hle, repo);
7920 if (err)
7921 break;
7922 } else {
7923 hle->logmsg = strdup(p);
7924 if (hle->logmsg == NULL) {
7925 err = got_error_from_errno("strdup");
7926 break;
7929 free(line);
7930 line = NULL;
7931 continue;
7932 } else {
7933 end = p;
7934 while (end[0] && !isspace((unsigned char)end[0]))
7935 end++;
7936 *end = '\0';
7938 err = got_object_resolve_id_str(&commit_id, repo, p);
7939 if (err) {
7940 /* override error code */
7941 err = histedit_syntax_error(lineno);
7942 break;
7945 hle = malloc(sizeof(*hle));
7946 if (hle == NULL) {
7947 err = got_error_from_errno("malloc");
7948 break;
7950 hle->cmd = cmd;
7951 hle->commit_id = commit_id;
7952 hle->logmsg = NULL;
7953 commit_id = NULL;
7954 free(line);
7955 line = NULL;
7956 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
7959 free(line);
7960 free(commit_id);
7961 return err;
7964 static const struct got_error *
7965 histedit_check_script(struct got_histedit_list *histedit_cmds,
7966 struct got_object_id_queue *commits, struct got_repository *repo)
7968 const struct got_error *err = NULL;
7969 struct got_object_qid *qid;
7970 struct got_histedit_list_entry *hle;
7971 static char msg[92];
7972 char *id_str;
7974 if (TAILQ_EMPTY(histedit_cmds))
7975 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
7976 "histedit script contains no commands");
7977 if (SIMPLEQ_EMPTY(commits))
7978 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7980 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7981 struct got_histedit_list_entry *hle2;
7982 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
7983 if (hle == hle2)
7984 continue;
7985 if (got_object_id_cmp(hle->commit_id,
7986 hle2->commit_id) != 0)
7987 continue;
7988 err = got_object_id_str(&id_str, hle->commit_id);
7989 if (err)
7990 return err;
7991 snprintf(msg, sizeof(msg), "commit %s is listed "
7992 "more than once in histedit script", id_str);
7993 free(id_str);
7994 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7998 SIMPLEQ_FOREACH(qid, commits, entry) {
7999 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8000 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
8001 break;
8003 if (hle == NULL) {
8004 err = got_object_id_str(&id_str, qid->id);
8005 if (err)
8006 return err;
8007 snprintf(msg, sizeof(msg),
8008 "commit %s missing from histedit script", id_str);
8009 free(id_str);
8010 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8014 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
8015 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
8016 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
8017 "last commit in histedit script cannot be folded");
8019 return NULL;
8022 static const struct got_error *
8023 histedit_run_editor(struct got_histedit_list *histedit_cmds,
8024 const char *path, struct got_object_id_queue *commits,
8025 struct got_repository *repo)
8027 const struct got_error *err = NULL;
8028 char *editor;
8029 FILE *f = NULL;
8031 err = get_editor(&editor);
8032 if (err)
8033 return err;
8035 if (spawn_editor(editor, path) == -1) {
8036 err = got_error_from_errno("failed spawning editor");
8037 goto done;
8040 f = fopen(path, "r");
8041 if (f == NULL) {
8042 err = got_error_from_errno("fopen");
8043 goto done;
8045 err = histedit_parse_list(histedit_cmds, f, repo);
8046 if (err)
8047 goto done;
8049 err = histedit_check_script(histedit_cmds, commits, repo);
8050 done:
8051 if (f && fclose(f) != 0 && err == NULL)
8052 err = got_error_from_errno("fclose");
8053 free(editor);
8054 return err;
8057 static const struct got_error *
8058 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
8059 struct got_object_id_queue *, const char *, const char *,
8060 struct got_repository *);
8062 static const struct got_error *
8063 histedit_edit_script(struct got_histedit_list *histedit_cmds,
8064 struct got_object_id_queue *commits, const char *branch_name,
8065 int edit_logmsg_only, struct got_repository *repo)
8067 const struct got_error *err;
8068 FILE *f = NULL;
8069 char *path = NULL;
8071 err = got_opentemp_named(&path, &f, "got-histedit");
8072 if (err)
8073 return err;
8075 err = write_cmd_list(f, branch_name, commits);
8076 if (err)
8077 goto done;
8079 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
8080 if (err)
8081 goto done;
8083 if (edit_logmsg_only) {
8084 rewind(f);
8085 err = histedit_parse_list(histedit_cmds, f, repo);
8086 } else {
8087 if (fclose(f) != 0) {
8088 err = got_error_from_errno("fclose");
8089 goto done;
8091 f = NULL;
8092 err = histedit_run_editor(histedit_cmds, path, commits, repo);
8093 if (err) {
8094 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8095 err->code != GOT_ERR_HISTEDIT_CMD)
8096 goto done;
8097 err = histedit_edit_list_retry(histedit_cmds, err,
8098 commits, path, branch_name, repo);
8101 done:
8102 if (f && fclose(f) != 0 && err == NULL)
8103 err = got_error_from_errno("fclose");
8104 if (path && unlink(path) != 0 && err == NULL)
8105 err = got_error_from_errno2("unlink", path);
8106 free(path);
8107 return err;
8110 static const struct got_error *
8111 histedit_save_list(struct got_histedit_list *histedit_cmds,
8112 struct got_worktree *worktree, struct got_repository *repo)
8114 const struct got_error *err = NULL;
8115 char *path = NULL;
8116 FILE *f = NULL;
8117 struct got_histedit_list_entry *hle;
8118 struct got_commit_object *commit = NULL;
8120 err = got_worktree_get_histedit_script_path(&path, worktree);
8121 if (err)
8122 return err;
8124 f = fopen(path, "w");
8125 if (f == NULL) {
8126 err = got_error_from_errno2("fopen", path);
8127 goto done;
8129 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8130 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
8131 repo);
8132 if (err)
8133 break;
8135 if (hle->logmsg) {
8136 int n = fprintf(f, "%c %s\n",
8137 GOT_HISTEDIT_MESG, hle->logmsg);
8138 if (n < 0) {
8139 err = got_ferror(f, GOT_ERR_IO);
8140 break;
8144 done:
8145 if (f && fclose(f) != 0 && err == NULL)
8146 err = got_error_from_errno("fclose");
8147 free(path);
8148 if (commit)
8149 got_object_commit_close(commit);
8150 return err;
8153 void
8154 histedit_free_list(struct got_histedit_list *histedit_cmds)
8156 struct got_histedit_list_entry *hle;
8158 while ((hle = TAILQ_FIRST(histedit_cmds))) {
8159 TAILQ_REMOVE(histedit_cmds, hle, entry);
8160 free(hle);
8164 static const struct got_error *
8165 histedit_load_list(struct got_histedit_list *histedit_cmds,
8166 const char *path, struct got_repository *repo)
8168 const struct got_error *err = NULL;
8169 FILE *f = NULL;
8171 f = fopen(path, "r");
8172 if (f == NULL) {
8173 err = got_error_from_errno2("fopen", path);
8174 goto done;
8177 err = histedit_parse_list(histedit_cmds, f, repo);
8178 done:
8179 if (f && fclose(f) != 0 && err == NULL)
8180 err = got_error_from_errno("fclose");
8181 return err;
8184 static const struct got_error *
8185 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
8186 const struct got_error *edit_err, struct got_object_id_queue *commits,
8187 const char *path, const char *branch_name, struct got_repository *repo)
8189 const struct got_error *err = NULL, *prev_err = edit_err;
8190 int resp = ' ';
8192 while (resp != 'c' && resp != 'r' && resp != 'a') {
8193 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
8194 "or (a)bort: ", getprogname(), prev_err->msg);
8195 resp = getchar();
8196 if (resp == '\n')
8197 resp = getchar();
8198 if (resp == 'c') {
8199 histedit_free_list(histedit_cmds);
8200 err = histedit_run_editor(histedit_cmds, path, commits,
8201 repo);
8202 if (err) {
8203 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8204 err->code != GOT_ERR_HISTEDIT_CMD)
8205 break;
8206 prev_err = err;
8207 resp = ' ';
8208 continue;
8210 break;
8211 } else if (resp == 'r') {
8212 histedit_free_list(histedit_cmds);
8213 err = histedit_edit_script(histedit_cmds,
8214 commits, branch_name, 0, repo);
8215 if (err) {
8216 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8217 err->code != GOT_ERR_HISTEDIT_CMD)
8218 break;
8219 prev_err = err;
8220 resp = ' ';
8221 continue;
8223 break;
8224 } else if (resp == 'a') {
8225 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
8226 break;
8227 } else
8228 printf("invalid response '%c'\n", resp);
8231 return err;
8234 static const struct got_error *
8235 histedit_complete(struct got_worktree *worktree,
8236 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
8237 struct got_reference *branch, struct got_repository *repo)
8239 printf("Switching work tree to %s\n",
8240 got_ref_get_symref_target(branch));
8241 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
8242 branch, repo);
8245 static const struct got_error *
8246 show_histedit_progress(struct got_commit_object *commit,
8247 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
8249 const struct got_error *err;
8250 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8252 err = got_object_id_str(&old_id_str, hle->commit_id);
8253 if (err)
8254 goto done;
8256 if (new_id) {
8257 err = got_object_id_str(&new_id_str, new_id);
8258 if (err)
8259 goto done;
8262 old_id_str[12] = '\0';
8263 if (new_id_str)
8264 new_id_str[12] = '\0';
8266 if (hle->logmsg) {
8267 logmsg = strdup(hle->logmsg);
8268 if (logmsg == NULL) {
8269 err = got_error_from_errno("strdup");
8270 goto done;
8272 trim_logmsg(logmsg, 42);
8273 } else {
8274 err = get_short_logmsg(&logmsg, 42, commit);
8275 if (err)
8276 goto done;
8279 switch (hle->cmd->code) {
8280 case GOT_HISTEDIT_PICK:
8281 case GOT_HISTEDIT_EDIT:
8282 printf("%s -> %s: %s\n", old_id_str,
8283 new_id_str ? new_id_str : "no-op change", logmsg);
8284 break;
8285 case GOT_HISTEDIT_DROP:
8286 case GOT_HISTEDIT_FOLD:
8287 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
8288 logmsg);
8289 break;
8290 default:
8291 break;
8293 done:
8294 free(old_id_str);
8295 free(new_id_str);
8296 return err;
8299 static const struct got_error *
8300 histedit_commit(struct got_pathlist_head *merged_paths,
8301 struct got_worktree *worktree, struct got_fileindex *fileindex,
8302 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
8303 struct got_repository *repo)
8305 const struct got_error *err;
8306 struct got_commit_object *commit;
8307 struct got_object_id *new_commit_id;
8309 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
8310 && hle->logmsg == NULL) {
8311 err = histedit_edit_logmsg(hle, repo);
8312 if (err)
8313 return err;
8316 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8317 if (err)
8318 return err;
8320 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
8321 worktree, fileindex, tmp_branch, commit, hle->commit_id,
8322 hle->logmsg, repo);
8323 if (err) {
8324 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
8325 goto done;
8326 err = show_histedit_progress(commit, hle, NULL);
8327 } else {
8328 err = show_histedit_progress(commit, hle, new_commit_id);
8329 free(new_commit_id);
8331 done:
8332 got_object_commit_close(commit);
8333 return err;
8336 static const struct got_error *
8337 histedit_skip_commit(struct got_histedit_list_entry *hle,
8338 struct got_worktree *worktree, struct got_repository *repo)
8340 const struct got_error *error;
8341 struct got_commit_object *commit;
8343 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
8344 repo);
8345 if (error)
8346 return error;
8348 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
8349 if (error)
8350 return error;
8352 error = show_histedit_progress(commit, hle, NULL);
8353 got_object_commit_close(commit);
8354 return error;
8357 static const struct got_error *
8358 check_local_changes(void *arg, unsigned char status,
8359 unsigned char staged_status, const char *path,
8360 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8361 struct got_object_id *commit_id, int dirfd, const char *de_name)
8363 int *have_local_changes = arg;
8365 switch (status) {
8366 case GOT_STATUS_ADD:
8367 case GOT_STATUS_DELETE:
8368 case GOT_STATUS_MODIFY:
8369 case GOT_STATUS_CONFLICT:
8370 *have_local_changes = 1;
8371 return got_error(GOT_ERR_CANCELLED);
8372 default:
8373 break;
8376 switch (staged_status) {
8377 case GOT_STATUS_ADD:
8378 case GOT_STATUS_DELETE:
8379 case GOT_STATUS_MODIFY:
8380 *have_local_changes = 1;
8381 return got_error(GOT_ERR_CANCELLED);
8382 default:
8383 break;
8386 return NULL;
8389 static const struct got_error *
8390 cmd_histedit(int argc, char *argv[])
8392 const struct got_error *error = NULL;
8393 struct got_worktree *worktree = NULL;
8394 struct got_fileindex *fileindex = NULL;
8395 struct got_repository *repo = NULL;
8396 char *cwd = NULL;
8397 struct got_reference *branch = NULL;
8398 struct got_reference *tmp_branch = NULL;
8399 struct got_object_id *resume_commit_id = NULL;
8400 struct got_object_id *base_commit_id = NULL;
8401 struct got_object_id *head_commit_id = NULL;
8402 struct got_commit_object *commit = NULL;
8403 int ch, rebase_in_progress = 0;
8404 struct got_update_progress_arg upa;
8405 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8406 int edit_logmsg_only = 0;
8407 const char *edit_script_path = NULL;
8408 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8409 struct got_object_id_queue commits;
8410 struct got_pathlist_head merged_paths;
8411 const struct got_object_id_queue *parent_ids;
8412 struct got_object_qid *pid;
8413 struct got_histedit_list histedit_cmds;
8414 struct got_histedit_list_entry *hle;
8416 SIMPLEQ_INIT(&commits);
8417 TAILQ_INIT(&histedit_cmds);
8418 TAILQ_INIT(&merged_paths);
8419 memset(&upa, 0, sizeof(upa));
8421 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
8422 switch (ch) {
8423 case 'a':
8424 abort_edit = 1;
8425 break;
8426 case 'c':
8427 continue_edit = 1;
8428 break;
8429 case 'F':
8430 edit_script_path = optarg;
8431 break;
8432 case 'm':
8433 edit_logmsg_only = 1;
8434 break;
8435 default:
8436 usage_histedit();
8437 /* NOTREACHED */
8441 argc -= optind;
8442 argv += optind;
8444 #ifndef PROFILE
8445 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8446 "unveil", NULL) == -1)
8447 err(1, "pledge");
8448 #endif
8449 if (abort_edit && continue_edit)
8450 errx(1, "histedit's -a and -c options are mutually exclusive");
8451 if (edit_script_path && edit_logmsg_only)
8452 errx(1, "histedit's -F and -m options are mutually exclusive");
8453 if (abort_edit && edit_logmsg_only)
8454 errx(1, "histedit's -a and -m options are mutually exclusive");
8455 if (continue_edit && edit_logmsg_only)
8456 errx(1, "histedit's -c and -m options are mutually exclusive");
8457 if (argc != 0)
8458 usage_histedit();
8461 * This command cannot apply unveil(2) in all cases because the
8462 * user may choose to run an editor to edit the histedit script
8463 * and to edit individual commit log messages.
8464 * unveil(2) traverses exec(2); if an editor is used we have to
8465 * apply unveil after edit script and log messages have been written.
8466 * XXX TODO: Make use of unveil(2) where possible.
8469 cwd = getcwd(NULL, 0);
8470 if (cwd == NULL) {
8471 error = got_error_from_errno("getcwd");
8472 goto done;
8474 error = got_worktree_open(&worktree, cwd);
8475 if (error) {
8476 if (error->code == GOT_ERR_NOT_WORKTREE)
8477 error = wrap_not_worktree_error(error, "histedit", cwd);
8478 goto done;
8481 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8482 NULL);
8483 if (error != NULL)
8484 goto done;
8486 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8487 if (error)
8488 goto done;
8489 if (rebase_in_progress) {
8490 error = got_error(GOT_ERR_REBASING);
8491 goto done;
8494 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8495 if (error)
8496 goto done;
8498 if (edit_in_progress && edit_logmsg_only) {
8499 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8500 "histedit operation is in progress in this "
8501 "work tree and must be continued or aborted "
8502 "before the -m option can be used");
8503 goto done;
8506 if (edit_in_progress && abort_edit) {
8507 error = got_worktree_histedit_continue(&resume_commit_id,
8508 &tmp_branch, &branch, &base_commit_id, &fileindex,
8509 worktree, repo);
8510 if (error)
8511 goto done;
8512 printf("Switching work tree to %s\n",
8513 got_ref_get_symref_target(branch));
8514 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8515 branch, base_commit_id, update_progress, &upa);
8516 if (error)
8517 goto done;
8518 printf("Histedit of %s aborted\n",
8519 got_ref_get_symref_target(branch));
8520 print_update_progress_stats(&upa);
8521 goto done; /* nothing else to do */
8522 } else if (abort_edit) {
8523 error = got_error(GOT_ERR_NOT_HISTEDIT);
8524 goto done;
8527 if (continue_edit) {
8528 char *path;
8530 if (!edit_in_progress) {
8531 error = got_error(GOT_ERR_NOT_HISTEDIT);
8532 goto done;
8535 error = got_worktree_get_histedit_script_path(&path, worktree);
8536 if (error)
8537 goto done;
8539 error = histedit_load_list(&histedit_cmds, path, repo);
8540 free(path);
8541 if (error)
8542 goto done;
8544 error = got_worktree_histedit_continue(&resume_commit_id,
8545 &tmp_branch, &branch, &base_commit_id, &fileindex,
8546 worktree, repo);
8547 if (error)
8548 goto done;
8550 error = got_ref_resolve(&head_commit_id, repo, branch);
8551 if (error)
8552 goto done;
8554 error = got_object_open_as_commit(&commit, repo,
8555 head_commit_id);
8556 if (error)
8557 goto done;
8558 parent_ids = got_object_commit_get_parent_ids(commit);
8559 pid = SIMPLEQ_FIRST(parent_ids);
8560 if (pid == NULL) {
8561 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8562 goto done;
8564 error = collect_commits(&commits, head_commit_id, pid->id,
8565 base_commit_id, got_worktree_get_path_prefix(worktree),
8566 GOT_ERR_HISTEDIT_PATH, repo);
8567 got_object_commit_close(commit);
8568 commit = NULL;
8569 if (error)
8570 goto done;
8571 } else {
8572 if (edit_in_progress) {
8573 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8574 goto done;
8577 error = got_ref_open(&branch, repo,
8578 got_worktree_get_head_ref_name(worktree), 0);
8579 if (error != NULL)
8580 goto done;
8582 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8583 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8584 "will not edit commit history of a branch outside "
8585 "the \"refs/heads/\" reference namespace");
8586 goto done;
8589 error = got_ref_resolve(&head_commit_id, repo, branch);
8590 got_ref_close(branch);
8591 branch = NULL;
8592 if (error)
8593 goto done;
8595 error = got_object_open_as_commit(&commit, repo,
8596 head_commit_id);
8597 if (error)
8598 goto done;
8599 parent_ids = got_object_commit_get_parent_ids(commit);
8600 pid = SIMPLEQ_FIRST(parent_ids);
8601 if (pid == NULL) {
8602 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8603 goto done;
8605 error = collect_commits(&commits, head_commit_id, pid->id,
8606 got_worktree_get_base_commit_id(worktree),
8607 got_worktree_get_path_prefix(worktree),
8608 GOT_ERR_HISTEDIT_PATH, repo);
8609 got_object_commit_close(commit);
8610 commit = NULL;
8611 if (error)
8612 goto done;
8614 if (SIMPLEQ_EMPTY(&commits)) {
8615 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8616 goto done;
8619 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8620 &base_commit_id, &fileindex, worktree, repo);
8621 if (error)
8622 goto done;
8624 if (edit_script_path) {
8625 error = histedit_load_list(&histedit_cmds,
8626 edit_script_path, repo);
8627 if (error) {
8628 got_worktree_histedit_abort(worktree, fileindex,
8629 repo, branch, base_commit_id,
8630 update_progress, &upa);
8631 print_update_progress_stats(&upa);
8632 goto done;
8634 } else {
8635 const char *branch_name;
8636 branch_name = got_ref_get_symref_target(branch);
8637 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8638 branch_name += 11;
8639 error = histedit_edit_script(&histedit_cmds, &commits,
8640 branch_name, edit_logmsg_only, repo);
8641 if (error) {
8642 got_worktree_histedit_abort(worktree, fileindex,
8643 repo, branch, base_commit_id,
8644 update_progress, &upa);
8645 print_update_progress_stats(&upa);
8646 goto done;
8651 error = histedit_save_list(&histedit_cmds, worktree,
8652 repo);
8653 if (error) {
8654 got_worktree_histedit_abort(worktree, fileindex,
8655 repo, branch, base_commit_id,
8656 update_progress, &upa);
8657 print_update_progress_stats(&upa);
8658 goto done;
8663 error = histedit_check_script(&histedit_cmds, &commits, repo);
8664 if (error)
8665 goto done;
8667 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8668 if (resume_commit_id) {
8669 if (got_object_id_cmp(hle->commit_id,
8670 resume_commit_id) != 0)
8671 continue;
8673 resume_commit_id = NULL;
8674 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8675 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8676 error = histedit_skip_commit(hle, worktree,
8677 repo);
8678 if (error)
8679 goto done;
8680 } else {
8681 struct got_pathlist_head paths;
8682 int have_changes = 0;
8684 TAILQ_INIT(&paths);
8685 error = got_pathlist_append(&paths, "", NULL);
8686 if (error)
8687 goto done;
8688 error = got_worktree_status(worktree, &paths,
8689 repo, check_local_changes, &have_changes,
8690 check_cancelled, NULL);
8691 got_pathlist_free(&paths);
8692 if (error) {
8693 if (error->code != GOT_ERR_CANCELLED)
8694 goto done;
8695 if (sigint_received || sigpipe_received)
8696 goto done;
8698 if (have_changes) {
8699 error = histedit_commit(NULL, worktree,
8700 fileindex, tmp_branch, hle, repo);
8701 if (error)
8702 goto done;
8703 } else {
8704 error = got_object_open_as_commit(
8705 &commit, repo, hle->commit_id);
8706 if (error)
8707 goto done;
8708 error = show_histedit_progress(commit,
8709 hle, NULL);
8710 got_object_commit_close(commit);
8711 commit = NULL;
8712 if (error)
8713 goto done;
8716 continue;
8719 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8720 error = histedit_skip_commit(hle, worktree, repo);
8721 if (error)
8722 goto done;
8723 continue;
8726 error = got_object_open_as_commit(&commit, repo,
8727 hle->commit_id);
8728 if (error)
8729 goto done;
8730 parent_ids = got_object_commit_get_parent_ids(commit);
8731 pid = SIMPLEQ_FIRST(parent_ids);
8733 error = got_worktree_histedit_merge_files(&merged_paths,
8734 worktree, fileindex, pid->id, hle->commit_id, repo,
8735 update_progress, &upa, check_cancelled, NULL);
8736 if (error)
8737 goto done;
8738 got_object_commit_close(commit);
8739 commit = NULL;
8741 print_update_progress_stats(&upa);
8742 if (upa.conflicts > 0)
8743 rebase_status = GOT_STATUS_CONFLICT;
8745 if (rebase_status == GOT_STATUS_CONFLICT) {
8746 error = show_rebase_merge_conflict(hle->commit_id,
8747 repo);
8748 if (error)
8749 goto done;
8750 got_worktree_rebase_pathlist_free(&merged_paths);
8751 break;
8754 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8755 char *id_str;
8756 error = got_object_id_str(&id_str, hle->commit_id);
8757 if (error)
8758 goto done;
8759 printf("Stopping histedit for amending commit %s\n",
8760 id_str);
8761 free(id_str);
8762 got_worktree_rebase_pathlist_free(&merged_paths);
8763 error = got_worktree_histedit_postpone(worktree,
8764 fileindex);
8765 goto done;
8768 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8769 error = histedit_skip_commit(hle, worktree, repo);
8770 if (error)
8771 goto done;
8772 continue;
8775 error = histedit_commit(&merged_paths, worktree, fileindex,
8776 tmp_branch, hle, repo);
8777 got_worktree_rebase_pathlist_free(&merged_paths);
8778 if (error)
8779 goto done;
8782 if (rebase_status == GOT_STATUS_CONFLICT) {
8783 error = got_worktree_histedit_postpone(worktree, fileindex);
8784 if (error)
8785 goto done;
8786 error = got_error_msg(GOT_ERR_CONFLICTS,
8787 "conflicts must be resolved before histedit can continue");
8788 } else
8789 error = histedit_complete(worktree, fileindex, tmp_branch,
8790 branch, repo);
8791 done:
8792 got_object_id_queue_free(&commits);
8793 histedit_free_list(&histedit_cmds);
8794 free(head_commit_id);
8795 free(base_commit_id);
8796 free(resume_commit_id);
8797 if (commit)
8798 got_object_commit_close(commit);
8799 if (branch)
8800 got_ref_close(branch);
8801 if (tmp_branch)
8802 got_ref_close(tmp_branch);
8803 if (worktree)
8804 got_worktree_close(worktree);
8805 if (repo)
8806 got_repo_close(repo);
8807 return error;
8810 __dead static void
8811 usage_integrate(void)
8813 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
8814 exit(1);
8817 static const struct got_error *
8818 cmd_integrate(int argc, char *argv[])
8820 const struct got_error *error = NULL;
8821 struct got_repository *repo = NULL;
8822 struct got_worktree *worktree = NULL;
8823 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
8824 const char *branch_arg = NULL;
8825 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
8826 struct got_fileindex *fileindex = NULL;
8827 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
8828 int ch;
8829 struct got_update_progress_arg upa;
8831 while ((ch = getopt(argc, argv, "")) != -1) {
8832 switch (ch) {
8833 default:
8834 usage_integrate();
8835 /* NOTREACHED */
8839 argc -= optind;
8840 argv += optind;
8842 if (argc != 1)
8843 usage_integrate();
8844 branch_arg = argv[0];
8846 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8847 "unveil", NULL) == -1)
8848 err(1, "pledge");
8850 cwd = getcwd(NULL, 0);
8851 if (cwd == NULL) {
8852 error = got_error_from_errno("getcwd");
8853 goto done;
8856 error = got_worktree_open(&worktree, cwd);
8857 if (error) {
8858 if (error->code == GOT_ERR_NOT_WORKTREE)
8859 error = wrap_not_worktree_error(error, "integrate",
8860 cwd);
8861 goto done;
8864 error = check_rebase_or_histedit_in_progress(worktree);
8865 if (error)
8866 goto done;
8868 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8869 NULL);
8870 if (error != NULL)
8871 goto done;
8873 error = apply_unveil(got_repo_get_path(repo), 0,
8874 got_worktree_get_root_path(worktree));
8875 if (error)
8876 goto done;
8878 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
8879 error = got_error_from_errno("asprintf");
8880 goto done;
8883 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
8884 &base_branch_ref, worktree, refname, repo);
8885 if (error)
8886 goto done;
8888 refname = strdup(got_ref_get_name(branch_ref));
8889 if (refname == NULL) {
8890 error = got_error_from_errno("strdup");
8891 got_worktree_integrate_abort(worktree, fileindex, repo,
8892 branch_ref, base_branch_ref);
8893 goto done;
8895 base_refname = strdup(got_ref_get_name(base_branch_ref));
8896 if (base_refname == NULL) {
8897 error = got_error_from_errno("strdup");
8898 got_worktree_integrate_abort(worktree, fileindex, repo,
8899 branch_ref, base_branch_ref);
8900 goto done;
8903 error = got_ref_resolve(&commit_id, repo, branch_ref);
8904 if (error)
8905 goto done;
8907 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
8908 if (error)
8909 goto done;
8911 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
8912 error = got_error_msg(GOT_ERR_SAME_BRANCH,
8913 "specified branch has already been integrated");
8914 got_worktree_integrate_abort(worktree, fileindex, repo,
8915 branch_ref, base_branch_ref);
8916 goto done;
8919 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
8920 if (error) {
8921 if (error->code == GOT_ERR_ANCESTRY)
8922 error = got_error(GOT_ERR_REBASE_REQUIRED);
8923 got_worktree_integrate_abort(worktree, fileindex, repo,
8924 branch_ref, base_branch_ref);
8925 goto done;
8928 memset(&upa, 0, sizeof(upa));
8929 error = got_worktree_integrate_continue(worktree, fileindex, repo,
8930 branch_ref, base_branch_ref, update_progress, &upa,
8931 check_cancelled, NULL);
8932 if (error)
8933 goto done;
8935 printf("Integrated %s into %s\n", refname, base_refname);
8936 print_update_progress_stats(&upa);
8937 done:
8938 if (repo)
8939 got_repo_close(repo);
8940 if (worktree)
8941 got_worktree_close(worktree);
8942 free(cwd);
8943 free(base_commit_id);
8944 free(commit_id);
8945 free(refname);
8946 free(base_refname);
8947 return error;
8950 __dead static void
8951 usage_stage(void)
8953 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
8954 "[-S] [file-path ...]\n",
8955 getprogname());
8956 exit(1);
8959 static const struct got_error *
8960 print_stage(void *arg, unsigned char status, unsigned char staged_status,
8961 const char *path, struct got_object_id *blob_id,
8962 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
8963 int dirfd, const char *de_name)
8965 const struct got_error *err = NULL;
8966 char *id_str = NULL;
8968 if (staged_status != GOT_STATUS_ADD &&
8969 staged_status != GOT_STATUS_MODIFY &&
8970 staged_status != GOT_STATUS_DELETE)
8971 return NULL;
8973 if (staged_status == GOT_STATUS_ADD ||
8974 staged_status == GOT_STATUS_MODIFY)
8975 err = got_object_id_str(&id_str, staged_blob_id);
8976 else
8977 err = got_object_id_str(&id_str, blob_id);
8978 if (err)
8979 return err;
8981 printf("%s %c %s\n", id_str, staged_status, path);
8982 free(id_str);
8983 return NULL;
8986 static const struct got_error *
8987 cmd_stage(int argc, char *argv[])
8989 const struct got_error *error = NULL;
8990 struct got_repository *repo = NULL;
8991 struct got_worktree *worktree = NULL;
8992 char *cwd = NULL;
8993 struct got_pathlist_head paths;
8994 struct got_pathlist_entry *pe;
8995 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
8996 FILE *patch_script_file = NULL;
8997 const char *patch_script_path = NULL;
8998 struct choose_patch_arg cpa;
9000 TAILQ_INIT(&paths);
9002 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
9003 switch (ch) {
9004 case 'l':
9005 list_stage = 1;
9006 break;
9007 case 'p':
9008 pflag = 1;
9009 break;
9010 case 'F':
9011 patch_script_path = optarg;
9012 break;
9013 case 'S':
9014 allow_bad_symlinks = 1;
9015 break;
9016 default:
9017 usage_stage();
9018 /* NOTREACHED */
9022 argc -= optind;
9023 argv += optind;
9025 #ifndef PROFILE
9026 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9027 "unveil", NULL) == -1)
9028 err(1, "pledge");
9029 #endif
9030 if (list_stage && (pflag || patch_script_path))
9031 errx(1, "-l option cannot be used with other options");
9032 if (patch_script_path && !pflag)
9033 errx(1, "-F option can only be used together with -p option");
9035 cwd = getcwd(NULL, 0);
9036 if (cwd == NULL) {
9037 error = got_error_from_errno("getcwd");
9038 goto done;
9041 error = got_worktree_open(&worktree, cwd);
9042 if (error) {
9043 if (error->code == GOT_ERR_NOT_WORKTREE)
9044 error = wrap_not_worktree_error(error, "stage", cwd);
9045 goto done;
9048 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9049 NULL);
9050 if (error != NULL)
9051 goto done;
9053 if (patch_script_path) {
9054 patch_script_file = fopen(patch_script_path, "r");
9055 if (patch_script_file == NULL) {
9056 error = got_error_from_errno2("fopen",
9057 patch_script_path);
9058 goto done;
9061 error = apply_unveil(got_repo_get_path(repo), 0,
9062 got_worktree_get_root_path(worktree));
9063 if (error)
9064 goto done;
9066 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9067 if (error)
9068 goto done;
9070 if (list_stage)
9071 error = got_worktree_status(worktree, &paths, repo,
9072 print_stage, NULL, check_cancelled, NULL);
9073 else {
9074 cpa.patch_script_file = patch_script_file;
9075 cpa.action = "stage";
9076 error = got_worktree_stage(worktree, &paths,
9077 pflag ? NULL : print_status, NULL,
9078 pflag ? choose_patch : NULL, &cpa,
9079 allow_bad_symlinks, repo);
9081 done:
9082 if (patch_script_file && fclose(patch_script_file) == EOF &&
9083 error == NULL)
9084 error = got_error_from_errno2("fclose", patch_script_path);
9085 if (repo)
9086 got_repo_close(repo);
9087 if (worktree)
9088 got_worktree_close(worktree);
9089 TAILQ_FOREACH(pe, &paths, entry)
9090 free((char *)pe->path);
9091 got_pathlist_free(&paths);
9092 free(cwd);
9093 return error;
9096 __dead static void
9097 usage_unstage(void)
9099 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
9100 "[file-path ...]\n",
9101 getprogname());
9102 exit(1);
9106 static const struct got_error *
9107 cmd_unstage(int argc, char *argv[])
9109 const struct got_error *error = NULL;
9110 struct got_repository *repo = NULL;
9111 struct got_worktree *worktree = NULL;
9112 char *cwd = NULL;
9113 struct got_pathlist_head paths;
9114 struct got_pathlist_entry *pe;
9115 int ch, pflag = 0;
9116 struct got_update_progress_arg upa;
9117 FILE *patch_script_file = NULL;
9118 const char *patch_script_path = NULL;
9119 struct choose_patch_arg cpa;
9121 TAILQ_INIT(&paths);
9123 while ((ch = getopt(argc, argv, "pF:")) != -1) {
9124 switch (ch) {
9125 case 'p':
9126 pflag = 1;
9127 break;
9128 case 'F':
9129 patch_script_path = optarg;
9130 break;
9131 default:
9132 usage_unstage();
9133 /* NOTREACHED */
9137 argc -= optind;
9138 argv += optind;
9140 #ifndef PROFILE
9141 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9142 "unveil", NULL) == -1)
9143 err(1, "pledge");
9144 #endif
9145 if (patch_script_path && !pflag)
9146 errx(1, "-F option can only be used together with -p option");
9148 cwd = getcwd(NULL, 0);
9149 if (cwd == NULL) {
9150 error = got_error_from_errno("getcwd");
9151 goto done;
9154 error = got_worktree_open(&worktree, cwd);
9155 if (error) {
9156 if (error->code == GOT_ERR_NOT_WORKTREE)
9157 error = wrap_not_worktree_error(error, "unstage", cwd);
9158 goto done;
9161 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9162 NULL);
9163 if (error != NULL)
9164 goto done;
9166 if (patch_script_path) {
9167 patch_script_file = fopen(patch_script_path, "r");
9168 if (patch_script_file == NULL) {
9169 error = got_error_from_errno2("fopen",
9170 patch_script_path);
9171 goto done;
9175 error = apply_unveil(got_repo_get_path(repo), 0,
9176 got_worktree_get_root_path(worktree));
9177 if (error)
9178 goto done;
9180 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9181 if (error)
9182 goto done;
9184 cpa.patch_script_file = patch_script_file;
9185 cpa.action = "unstage";
9186 memset(&upa, 0, sizeof(upa));
9187 error = got_worktree_unstage(worktree, &paths, update_progress,
9188 &upa, pflag ? choose_patch : NULL, &cpa, repo);
9189 if (!error)
9190 print_update_progress_stats(&upa);
9191 done:
9192 if (patch_script_file && fclose(patch_script_file) == EOF &&
9193 error == NULL)
9194 error = got_error_from_errno2("fclose", patch_script_path);
9195 if (repo)
9196 got_repo_close(repo);
9197 if (worktree)
9198 got_worktree_close(worktree);
9199 TAILQ_FOREACH(pe, &paths, entry)
9200 free((char *)pe->path);
9201 got_pathlist_free(&paths);
9202 free(cwd);
9203 return error;
9206 __dead static void
9207 usage_cat(void)
9209 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
9210 "arg1 [arg2 ...]\n", getprogname());
9211 exit(1);
9214 static const struct got_error *
9215 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9217 const struct got_error *err;
9218 struct got_blob_object *blob;
9220 err = got_object_open_as_blob(&blob, repo, id, 8192);
9221 if (err)
9222 return err;
9224 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
9225 got_object_blob_close(blob);
9226 return err;
9229 static const struct got_error *
9230 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9232 const struct got_error *err;
9233 struct got_tree_object *tree;
9234 int nentries, i;
9236 err = got_object_open_as_tree(&tree, repo, id);
9237 if (err)
9238 return err;
9240 nentries = got_object_tree_get_nentries(tree);
9241 for (i = 0; i < nentries; i++) {
9242 struct got_tree_entry *te;
9243 char *id_str;
9244 if (sigint_received || sigpipe_received)
9245 break;
9246 te = got_object_tree_get_entry(tree, i);
9247 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
9248 if (err)
9249 break;
9250 fprintf(outfile, "%s %.7o %s\n", id_str,
9251 got_tree_entry_get_mode(te),
9252 got_tree_entry_get_name(te));
9253 free(id_str);
9256 got_object_tree_close(tree);
9257 return err;
9260 static const struct got_error *
9261 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9263 const struct got_error *err;
9264 struct got_commit_object *commit;
9265 const struct got_object_id_queue *parent_ids;
9266 struct got_object_qid *pid;
9267 char *id_str = NULL;
9268 const char *logmsg = NULL;
9270 err = got_object_open_as_commit(&commit, repo, id);
9271 if (err)
9272 return err;
9274 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
9275 if (err)
9276 goto done;
9278 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
9279 parent_ids = got_object_commit_get_parent_ids(commit);
9280 fprintf(outfile, "numparents %d\n",
9281 got_object_commit_get_nparents(commit));
9282 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
9283 char *pid_str;
9284 err = got_object_id_str(&pid_str, pid->id);
9285 if (err)
9286 goto done;
9287 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
9288 free(pid_str);
9290 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
9291 got_object_commit_get_author(commit),
9292 got_object_commit_get_author_time(commit));
9294 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
9295 got_object_commit_get_author(commit),
9296 got_object_commit_get_committer_time(commit));
9298 logmsg = got_object_commit_get_logmsg_raw(commit);
9299 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
9300 fprintf(outfile, "%s", logmsg);
9301 done:
9302 free(id_str);
9303 got_object_commit_close(commit);
9304 return err;
9307 static const struct got_error *
9308 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9310 const struct got_error *err;
9311 struct got_tag_object *tag;
9312 char *id_str = NULL;
9313 const char *tagmsg = NULL;
9315 err = got_object_open_as_tag(&tag, repo, id);
9316 if (err)
9317 return err;
9319 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
9320 if (err)
9321 goto done;
9323 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
9325 switch (got_object_tag_get_object_type(tag)) {
9326 case GOT_OBJ_TYPE_BLOB:
9327 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9328 GOT_OBJ_LABEL_BLOB);
9329 break;
9330 case GOT_OBJ_TYPE_TREE:
9331 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9332 GOT_OBJ_LABEL_TREE);
9333 break;
9334 case GOT_OBJ_TYPE_COMMIT:
9335 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9336 GOT_OBJ_LABEL_COMMIT);
9337 break;
9338 case GOT_OBJ_TYPE_TAG:
9339 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9340 GOT_OBJ_LABEL_TAG);
9341 break;
9342 default:
9343 break;
9346 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
9347 got_object_tag_get_name(tag));
9349 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
9350 got_object_tag_get_tagger(tag),
9351 got_object_tag_get_tagger_time(tag));
9353 tagmsg = got_object_tag_get_message(tag);
9354 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
9355 fprintf(outfile, "%s", tagmsg);
9356 done:
9357 free(id_str);
9358 got_object_tag_close(tag);
9359 return err;
9362 static const struct got_error *
9363 cmd_cat(int argc, char *argv[])
9365 const struct got_error *error;
9366 struct got_repository *repo = NULL;
9367 struct got_worktree *worktree = NULL;
9368 char *cwd = NULL, *repo_path = NULL, *label = NULL;
9369 const char *commit_id_str = NULL;
9370 struct got_object_id *id = NULL, *commit_id = NULL;
9371 int ch, obj_type, i, force_path = 0;
9373 #ifndef PROFILE
9374 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9375 NULL) == -1)
9376 err(1, "pledge");
9377 #endif
9379 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
9380 switch (ch) {
9381 case 'c':
9382 commit_id_str = optarg;
9383 break;
9384 case 'r':
9385 repo_path = realpath(optarg, NULL);
9386 if (repo_path == NULL)
9387 return got_error_from_errno2("realpath",
9388 optarg);
9389 got_path_strip_trailing_slashes(repo_path);
9390 break;
9391 case 'P':
9392 force_path = 1;
9393 break;
9394 default:
9395 usage_cat();
9396 /* NOTREACHED */
9400 argc -= optind;
9401 argv += optind;
9403 cwd = getcwd(NULL, 0);
9404 if (cwd == NULL) {
9405 error = got_error_from_errno("getcwd");
9406 goto done;
9408 error = got_worktree_open(&worktree, cwd);
9409 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9410 goto done;
9411 if (worktree) {
9412 if (repo_path == NULL) {
9413 repo_path = strdup(
9414 got_worktree_get_repo_path(worktree));
9415 if (repo_path == NULL) {
9416 error = got_error_from_errno("strdup");
9417 goto done;
9422 if (repo_path == NULL) {
9423 repo_path = getcwd(NULL, 0);
9424 if (repo_path == NULL)
9425 return got_error_from_errno("getcwd");
9428 error = got_repo_open(&repo, repo_path, NULL);
9429 free(repo_path);
9430 if (error != NULL)
9431 goto done;
9433 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9434 if (error)
9435 goto done;
9437 if (commit_id_str == NULL)
9438 commit_id_str = GOT_REF_HEAD;
9439 error = got_repo_match_object_id(&commit_id, NULL,
9440 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
9441 if (error)
9442 goto done;
9444 for (i = 0; i < argc; i++) {
9445 if (force_path) {
9446 error = got_object_id_by_path(&id, repo, commit_id,
9447 argv[i]);
9448 if (error)
9449 break;
9450 } else {
9451 error = got_repo_match_object_id(&id, &label, argv[i],
9452 GOT_OBJ_TYPE_ANY, 0, repo);
9453 if (error) {
9454 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9455 error->code != GOT_ERR_NOT_REF)
9456 break;
9457 error = got_object_id_by_path(&id, repo,
9458 commit_id, argv[i]);
9459 if (error)
9460 break;
9464 error = got_object_get_type(&obj_type, repo, id);
9465 if (error)
9466 break;
9468 switch (obj_type) {
9469 case GOT_OBJ_TYPE_BLOB:
9470 error = cat_blob(id, repo, stdout);
9471 break;
9472 case GOT_OBJ_TYPE_TREE:
9473 error = cat_tree(id, repo, stdout);
9474 break;
9475 case GOT_OBJ_TYPE_COMMIT:
9476 error = cat_commit(id, repo, stdout);
9477 break;
9478 case GOT_OBJ_TYPE_TAG:
9479 error = cat_tag(id, repo, stdout);
9480 break;
9481 default:
9482 error = got_error(GOT_ERR_OBJ_TYPE);
9483 break;
9485 if (error)
9486 break;
9487 free(label);
9488 label = NULL;
9489 free(id);
9490 id = NULL;
9492 done:
9493 free(label);
9494 free(id);
9495 free(commit_id);
9496 if (worktree)
9497 got_worktree_close(worktree);
9498 if (repo) {
9499 const struct got_error *repo_error;
9500 repo_error = got_repo_close(repo);
9501 if (error == NULL)
9502 error = repo_error;
9504 return error;
9507 __dead static void
9508 usage_info(void)
9510 fprintf(stderr, "usage: %s info [path ...]\n",
9511 getprogname());
9512 exit(1);
9515 static const struct got_error *
9516 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
9517 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9518 struct got_object_id *commit_id)
9520 const struct got_error *err = NULL;
9521 char *id_str = NULL;
9522 char datebuf[128];
9523 struct tm mytm, *tm;
9524 struct got_pathlist_head *paths = arg;
9525 struct got_pathlist_entry *pe;
9528 * Clear error indication from any of the path arguments which
9529 * would cause this file index entry to be displayed.
9531 TAILQ_FOREACH(pe, paths, entry) {
9532 if (got_path_cmp(path, pe->path, strlen(path),
9533 pe->path_len) == 0 ||
9534 got_path_is_child(path, pe->path, pe->path_len))
9535 pe->data = NULL; /* no error */
9538 printf(GOT_COMMIT_SEP_STR);
9539 if (S_ISLNK(mode))
9540 printf("symlink: %s\n", path);
9541 else if (S_ISREG(mode)) {
9542 printf("file: %s\n", path);
9543 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
9544 } else if (S_ISDIR(mode))
9545 printf("directory: %s\n", path);
9546 else
9547 printf("something: %s\n", path);
9549 tm = localtime_r(&mtime, &mytm);
9550 if (tm == NULL)
9551 return NULL;
9552 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) >= sizeof(datebuf))
9553 return got_error(GOT_ERR_NO_SPACE);
9554 printf("timestamp: %s\n", datebuf);
9556 if (blob_id) {
9557 err = got_object_id_str(&id_str, blob_id);
9558 if (err)
9559 return err;
9560 printf("based on blob: %s\n", id_str);
9561 free(id_str);
9564 if (staged_blob_id) {
9565 err = got_object_id_str(&id_str, staged_blob_id);
9566 if (err)
9567 return err;
9568 printf("based on staged blob: %s\n", id_str);
9569 free(id_str);
9572 if (commit_id) {
9573 err = got_object_id_str(&id_str, commit_id);
9574 if (err)
9575 return err;
9576 printf("based on commit: %s\n", id_str);
9577 free(id_str);
9580 return NULL;
9583 static const struct got_error *
9584 cmd_info(int argc, char *argv[])
9586 const struct got_error *error = NULL;
9587 struct got_worktree *worktree = NULL;
9588 char *cwd = NULL, *id_str = NULL;
9589 struct got_pathlist_head paths;
9590 struct got_pathlist_entry *pe;
9591 char *uuidstr = NULL;
9592 int ch, show_files = 0;
9594 TAILQ_INIT(&paths);
9596 while ((ch = getopt(argc, argv, "")) != -1) {
9597 switch (ch) {
9598 default:
9599 usage_info();
9600 /* NOTREACHED */
9604 argc -= optind;
9605 argv += optind;
9607 #ifndef PROFILE
9608 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
9609 NULL) == -1)
9610 err(1, "pledge");
9611 #endif
9612 cwd = getcwd(NULL, 0);
9613 if (cwd == NULL) {
9614 error = got_error_from_errno("getcwd");
9615 goto done;
9618 error = got_worktree_open(&worktree, cwd);
9619 if (error) {
9620 if (error->code == GOT_ERR_NOT_WORKTREE)
9621 error = wrap_not_worktree_error(error, "status", cwd);
9622 goto done;
9625 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9626 if (error)
9627 goto done;
9629 if (argc >= 1) {
9630 error = get_worktree_paths_from_argv(&paths, argc, argv,
9631 worktree);
9632 if (error)
9633 goto done;
9634 show_files = 1;
9637 error = got_object_id_str(&id_str,
9638 got_worktree_get_base_commit_id(worktree));
9639 if (error)
9640 goto done;
9642 error = got_worktree_get_uuid(&uuidstr, worktree);
9643 if (error)
9644 goto done;
9646 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9647 printf("work tree base commit: %s\n", id_str);
9648 printf("work tree path prefix: %s\n",
9649 got_worktree_get_path_prefix(worktree));
9650 printf("work tree branch reference: %s\n",
9651 got_worktree_get_head_ref_name(worktree));
9652 printf("work tree UUID: %s\n", uuidstr);
9653 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
9655 if (show_files) {
9656 struct got_pathlist_entry *pe;
9657 TAILQ_FOREACH(pe, &paths, entry) {
9658 if (pe->path_len == 0)
9659 continue;
9661 * Assume this path will fail. This will be corrected
9662 * in print_path_info() in case the path does suceeed.
9664 pe->data = (void *)got_error_path(pe->path,
9665 GOT_ERR_BAD_PATH);
9667 error = got_worktree_path_info(worktree, &paths,
9668 print_path_info, &paths, check_cancelled, NULL);
9669 if (error)
9670 goto done;
9671 TAILQ_FOREACH(pe, &paths, entry) {
9672 if (pe->data != NULL) {
9673 error = pe->data; /* bad path */
9674 break;
9678 done:
9679 TAILQ_FOREACH(pe, &paths, entry)
9680 free((char *)pe->path);
9681 got_pathlist_free(&paths);
9682 free(cwd);
9683 free(id_str);
9684 free(uuidstr);
9685 return error;