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 int cmp;
3207 name = got_ref_get_name(re->ref);
3208 if (strcmp(name, GOT_REF_HEAD) == 0)
3209 continue;
3210 if (strncmp(name, "refs/", 5) == 0)
3211 name += 5;
3212 if (strncmp(name, "got/", 4) == 0)
3213 continue;
3214 if (strncmp(name, "heads/", 6) == 0)
3215 name += 6;
3216 if (strncmp(name, "remotes/", 8) == 0) {
3217 name += 8;
3218 s = strstr(name, "/" GOT_REF_HEAD);
3219 if (s != NULL && s[strlen(s)] == '\0')
3220 continue;
3222 if (strncmp(name, "tags/", 5) == 0) {
3223 err = got_object_open_as_tag(&tag, repo, re->id);
3224 if (err) {
3225 if (err->code != GOT_ERR_OBJ_TYPE)
3226 return err;
3227 /* Ref points at something other than a tag. */
3228 err = NULL;
3229 tag = NULL;
3232 cmp = got_object_id_cmp(tag ?
3233 got_object_tag_get_object_id(tag) : re->id, id);
3234 if (tag)
3235 got_object_tag_close(tag);
3236 if (cmp != 0)
3237 continue;
3238 s = refs_str;
3239 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3240 name) == -1) {
3241 err = got_error_from_errno("asprintf");
3242 free(s);
3243 return err;
3245 free(s);
3247 err = got_object_id_str(&id_str, id);
3248 if (err)
3249 return err;
3251 printf(GOT_COMMIT_SEP_STR);
3252 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3253 refs_str ? refs_str : "", refs_str ? ")" : "");
3254 free(id_str);
3255 id_str = NULL;
3256 free(refs_str);
3257 refs_str = NULL;
3258 printf("from: %s\n", got_object_commit_get_author(commit));
3259 committer_time = got_object_commit_get_committer_time(commit);
3260 datestr = get_datestr(&committer_time, datebuf);
3261 if (datestr)
3262 printf("date: %s UTC\n", datestr);
3263 author = got_object_commit_get_author(commit);
3264 committer = got_object_commit_get_committer(commit);
3265 if (strcmp(author, committer) != 0)
3266 printf("via: %s\n", committer);
3267 if (got_object_commit_get_nparents(commit) > 1) {
3268 const struct got_object_id_queue *parent_ids;
3269 struct got_object_qid *qid;
3270 int n = 1;
3271 parent_ids = got_object_commit_get_parent_ids(commit);
3272 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3273 err = got_object_id_str(&id_str, qid->id);
3274 if (err)
3275 return err;
3276 printf("parent %d: %s\n", n++, id_str);
3277 free(id_str);
3281 err = got_object_commit_get_logmsg(&logmsg0, commit);
3282 if (err)
3283 return err;
3285 logmsg = logmsg0;
3286 do {
3287 line = strsep(&logmsg, "\n");
3288 if (line)
3289 printf(" %s\n", line);
3290 } while (line);
3291 free(logmsg0);
3293 if (changed_paths) {
3294 struct got_pathlist_entry *pe;
3295 TAILQ_FOREACH(pe, changed_paths, entry) {
3296 struct got_diff_changed_path *cp = pe->data;
3297 printf(" %c %s\n", cp->status, pe->path);
3299 printf("\n");
3301 if (show_patch) {
3302 err = print_patch(commit, id, path, diff_context, repo);
3303 if (err == 0)
3304 printf("\n");
3307 if (fflush(stdout) != 0 && err == NULL)
3308 err = got_error_from_errno("fflush");
3309 return err;
3312 static const struct got_error *
3313 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3314 struct got_repository *repo, const char *path, int show_changed_paths,
3315 int show_patch, const char *search_pattern, int diff_context, int limit,
3316 int log_branches, int reverse_display_order, struct got_reflist_head *refs)
3318 const struct got_error *err;
3319 struct got_commit_graph *graph;
3320 regex_t regex;
3321 int have_match;
3322 struct got_object_id_queue reversed_commits;
3323 struct got_object_qid *qid;
3324 struct got_commit_object *commit;
3325 struct got_pathlist_head changed_paths;
3326 struct got_pathlist_entry *pe;
3328 SIMPLEQ_INIT(&reversed_commits);
3329 TAILQ_INIT(&changed_paths);
3331 if (search_pattern && regcomp(&regex, search_pattern,
3332 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3333 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3335 err = got_commit_graph_open(&graph, path, !log_branches);
3336 if (err)
3337 return err;
3338 err = got_commit_graph_iter_start(graph, root_id, repo,
3339 check_cancelled, NULL);
3340 if (err)
3341 goto done;
3342 for (;;) {
3343 struct got_object_id *id;
3345 if (sigint_received || sigpipe_received)
3346 break;
3348 err = got_commit_graph_iter_next(&id, graph, repo,
3349 check_cancelled, NULL);
3350 if (err) {
3351 if (err->code == GOT_ERR_ITER_COMPLETED)
3352 err = NULL;
3353 break;
3355 if (id == NULL)
3356 break;
3358 err = got_object_open_as_commit(&commit, repo, id);
3359 if (err)
3360 break;
3362 if (show_changed_paths && !reverse_display_order) {
3363 err = get_changed_paths(&changed_paths, commit, repo);
3364 if (err)
3365 break;
3368 if (search_pattern) {
3369 err = match_logmsg(&have_match, id, commit, &regex);
3370 if (err) {
3371 got_object_commit_close(commit);
3372 break;
3374 if (have_match == 0 && show_changed_paths)
3375 match_changed_paths(&have_match,
3376 &changed_paths, &regex);
3377 if (have_match == 0) {
3378 got_object_commit_close(commit);
3379 TAILQ_FOREACH(pe, &changed_paths, entry) {
3380 free((char *)pe->path);
3381 free(pe->data);
3383 got_pathlist_free(&changed_paths);
3384 continue;
3388 if (reverse_display_order) {
3389 err = got_object_qid_alloc(&qid, id);
3390 if (err)
3391 break;
3392 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3393 got_object_commit_close(commit);
3394 } else {
3395 err = print_commit(commit, id, repo, path,
3396 show_changed_paths ? &changed_paths : NULL,
3397 show_patch, diff_context, refs);
3398 got_object_commit_close(commit);
3399 if (err)
3400 break;
3402 if ((limit && --limit == 0) ||
3403 (end_id && got_object_id_cmp(id, end_id) == 0))
3404 break;
3406 TAILQ_FOREACH(pe, &changed_paths, entry) {
3407 free((char *)pe->path);
3408 free(pe->data);
3410 got_pathlist_free(&changed_paths);
3412 if (reverse_display_order) {
3413 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3414 err = got_object_open_as_commit(&commit, repo, qid->id);
3415 if (err)
3416 break;
3417 if (show_changed_paths) {
3418 err = get_changed_paths(&changed_paths,
3419 commit, repo);
3420 if (err)
3421 break;
3423 err = print_commit(commit, qid->id, repo, path,
3424 show_changed_paths ? &changed_paths : NULL,
3425 show_patch, diff_context, refs);
3426 got_object_commit_close(commit);
3427 if (err)
3428 break;
3429 TAILQ_FOREACH(pe, &changed_paths, entry) {
3430 free((char *)pe->path);
3431 free(pe->data);
3433 got_pathlist_free(&changed_paths);
3436 done:
3437 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3438 qid = SIMPLEQ_FIRST(&reversed_commits);
3439 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3440 got_object_qid_free(qid);
3442 TAILQ_FOREACH(pe, &changed_paths, entry) {
3443 free((char *)pe->path);
3444 free(pe->data);
3446 got_pathlist_free(&changed_paths);
3447 if (search_pattern)
3448 regfree(&regex);
3449 got_commit_graph_close(graph);
3450 return err;
3453 __dead static void
3454 usage_log(void)
3456 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3457 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3458 "[-R] [path]\n", getprogname());
3459 exit(1);
3462 static int
3463 get_default_log_limit(void)
3465 const char *got_default_log_limit;
3466 long long n;
3467 const char *errstr;
3469 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3470 if (got_default_log_limit == NULL)
3471 return 0;
3472 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3473 if (errstr != NULL)
3474 return 0;
3475 return n;
3478 static const struct got_error *
3479 resolve_commit_arg(struct got_object_id **id, const char *commit_arg,
3480 struct got_repository *repo)
3482 const struct got_error *err = NULL;
3483 struct got_reference *ref;
3485 *id = NULL;
3487 err = got_ref_open(&ref, repo, commit_arg, 0);
3488 if (err == NULL) {
3489 int obj_type;
3490 err = got_ref_resolve(id, repo, ref);
3491 got_ref_close(ref);
3492 if (err)
3493 return err;
3494 err = got_object_get_type(&obj_type, repo, *id);
3495 if (err)
3496 return err;
3497 if (obj_type == GOT_OBJ_TYPE_TAG) {
3498 struct got_tag_object *tag;
3499 err = got_object_open_as_tag(&tag, repo, *id);
3500 if (err)
3501 return err;
3502 if (got_object_tag_get_object_type(tag) !=
3503 GOT_OBJ_TYPE_COMMIT) {
3504 got_object_tag_close(tag);
3505 return got_error(GOT_ERR_OBJ_TYPE);
3507 free(*id);
3508 *id = got_object_id_dup(
3509 got_object_tag_get_object_id(tag));
3510 if (*id == NULL)
3511 err = got_error_from_errno(
3512 "got_object_id_dup");
3513 got_object_tag_close(tag);
3514 if (err)
3515 return err;
3516 } else if (obj_type != GOT_OBJ_TYPE_COMMIT)
3517 return got_error(GOT_ERR_OBJ_TYPE);
3518 } else {
3519 err = got_repo_match_object_id_prefix(id, commit_arg,
3520 GOT_OBJ_TYPE_COMMIT, repo);
3523 return err;
3526 static const struct got_error *
3527 cmd_log(int argc, char *argv[])
3529 const struct got_error *error;
3530 struct got_repository *repo = NULL;
3531 struct got_worktree *worktree = NULL;
3532 struct got_object_id *start_id = NULL, *end_id = NULL;
3533 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3534 const char *start_commit = NULL, *end_commit = NULL;
3535 const char *search_pattern = NULL;
3536 int diff_context = -1, ch;
3537 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3538 int reverse_display_order = 0;
3539 const char *errstr;
3540 struct got_reflist_head refs;
3542 SIMPLEQ_INIT(&refs);
3544 #ifndef PROFILE
3545 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3546 NULL)
3547 == -1)
3548 err(1, "pledge");
3549 #endif
3551 limit = get_default_log_limit();
3553 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3554 switch (ch) {
3555 case 'p':
3556 show_patch = 1;
3557 break;
3558 case 'P':
3559 show_changed_paths = 1;
3560 break;
3561 case 'c':
3562 start_commit = optarg;
3563 break;
3564 case 'C':
3565 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3566 &errstr);
3567 if (errstr != NULL)
3568 err(1, "-C option %s", errstr);
3569 break;
3570 case 'l':
3571 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3572 if (errstr != NULL)
3573 err(1, "-l option %s", errstr);
3574 break;
3575 case 'b':
3576 log_branches = 1;
3577 break;
3578 case 'r':
3579 repo_path = realpath(optarg, NULL);
3580 if (repo_path == NULL)
3581 return got_error_from_errno2("realpath",
3582 optarg);
3583 got_path_strip_trailing_slashes(repo_path);
3584 break;
3585 case 'R':
3586 reverse_display_order = 1;
3587 break;
3588 case 's':
3589 search_pattern = optarg;
3590 break;
3591 case 'x':
3592 end_commit = optarg;
3593 break;
3594 default:
3595 usage_log();
3596 /* NOTREACHED */
3600 argc -= optind;
3601 argv += optind;
3603 if (diff_context == -1)
3604 diff_context = 3;
3605 else if (!show_patch)
3606 errx(1, "-C requires -p");
3608 cwd = getcwd(NULL, 0);
3609 if (cwd == NULL) {
3610 error = got_error_from_errno("getcwd");
3611 goto done;
3614 if (repo_path == NULL) {
3615 error = got_worktree_open(&worktree, cwd);
3616 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3617 goto done;
3618 error = NULL;
3621 if (argc == 0) {
3622 path = strdup("");
3623 if (path == NULL) {
3624 error = got_error_from_errno("strdup");
3625 goto done;
3627 } else if (argc == 1) {
3628 if (worktree) {
3629 error = got_worktree_resolve_path(&path, worktree,
3630 argv[0]);
3631 if (error)
3632 goto done;
3633 } else {
3634 path = strdup(argv[0]);
3635 if (path == NULL) {
3636 error = got_error_from_errno("strdup");
3637 goto done;
3640 } else
3641 usage_log();
3643 if (repo_path == NULL) {
3644 repo_path = worktree ?
3645 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3647 if (repo_path == NULL) {
3648 error = got_error_from_errno("strdup");
3649 goto done;
3652 error = got_repo_open(&repo, repo_path, NULL);
3653 if (error != NULL)
3654 goto done;
3656 error = apply_unveil(got_repo_get_path(repo), 1,
3657 worktree ? got_worktree_get_root_path(worktree) : NULL);
3658 if (error)
3659 goto done;
3661 if (start_commit == NULL) {
3662 struct got_reference *head_ref;
3663 struct got_commit_object *commit = NULL;
3664 error = got_ref_open(&head_ref, repo,
3665 worktree ? got_worktree_get_head_ref_name(worktree)
3666 : GOT_REF_HEAD, 0);
3667 if (error != NULL)
3668 goto done;
3669 error = got_ref_resolve(&start_id, repo, head_ref);
3670 got_ref_close(head_ref);
3671 if (error != NULL)
3672 goto done;
3673 error = got_object_open_as_commit(&commit, repo,
3674 start_id);
3675 if (error != NULL)
3676 goto done;
3677 got_object_commit_close(commit);
3678 } else {
3679 error = resolve_commit_arg(&start_id, start_commit, repo);
3680 if (error != NULL)
3681 goto done;
3683 if (end_commit != NULL) {
3684 error = resolve_commit_arg(&end_id, end_commit, repo);
3685 if (error != NULL)
3686 goto done;
3689 if (worktree) {
3690 const char *prefix = got_worktree_get_path_prefix(worktree);
3691 char *p;
3692 if (asprintf(&p, "%s%s%s", prefix,
3693 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3694 error = got_error_from_errno("asprintf");
3695 goto done;
3697 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3698 free(p);
3699 } else
3700 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3701 if (error != NULL)
3702 goto done;
3703 if (in_repo_path) {
3704 free(path);
3705 path = in_repo_path;
3708 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3709 if (error)
3710 goto done;
3712 error = print_commits(start_id, end_id, repo, path, show_changed_paths,
3713 show_patch, search_pattern, diff_context, limit, log_branches,
3714 reverse_display_order, &refs);
3715 done:
3716 free(path);
3717 free(repo_path);
3718 free(cwd);
3719 if (worktree)
3720 got_worktree_close(worktree);
3721 if (repo) {
3722 const struct got_error *repo_error;
3723 repo_error = got_repo_close(repo);
3724 if (error == NULL)
3725 error = repo_error;
3727 got_ref_list_free(&refs);
3728 return error;
3731 __dead static void
3732 usage_diff(void)
3734 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3735 "[-w] [object1 object2 | path]\n", getprogname());
3736 exit(1);
3739 struct print_diff_arg {
3740 struct got_repository *repo;
3741 struct got_worktree *worktree;
3742 int diff_context;
3743 const char *id_str;
3744 int header_shown;
3745 int diff_staged;
3746 int ignore_whitespace;
3750 * Create a file which contains the target path of a symlink so we can feed
3751 * it as content to the diff engine.
3753 static const struct got_error *
3754 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
3755 const char *abspath)
3757 const struct got_error *err = NULL;
3758 char target_path[PATH_MAX];
3759 ssize_t target_len, outlen;
3761 *fd = -1;
3763 if (dirfd != -1) {
3764 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
3765 if (target_len == -1)
3766 return got_error_from_errno2("readlinkat", abspath);
3767 } else {
3768 target_len = readlink(abspath, target_path, PATH_MAX);
3769 if (target_len == -1)
3770 return got_error_from_errno2("readlink", abspath);
3773 *fd = got_opentempfd();
3774 if (*fd == -1)
3775 return got_error_from_errno("got_opentempfd");
3777 outlen = write(*fd, target_path, target_len);
3778 if (outlen == -1) {
3779 err = got_error_from_errno("got_opentempfd");
3780 goto done;
3783 if (lseek(*fd, 0, SEEK_SET) == -1) {
3784 err = got_error_from_errno2("lseek", abspath);
3785 goto done;
3787 done:
3788 if (err) {
3789 close(*fd);
3790 *fd = -1;
3792 return err;
3795 static const struct got_error *
3796 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3797 const char *path, struct got_object_id *blob_id,
3798 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3799 int dirfd, const char *de_name)
3801 struct print_diff_arg *a = arg;
3802 const struct got_error *err = NULL;
3803 struct got_blob_object *blob1 = NULL;
3804 int fd = -1;
3805 FILE *f2 = NULL;
3806 char *abspath = NULL, *label1 = NULL;
3807 struct stat sb;
3809 if (a->diff_staged) {
3810 if (staged_status != GOT_STATUS_MODIFY &&
3811 staged_status != GOT_STATUS_ADD &&
3812 staged_status != GOT_STATUS_DELETE)
3813 return NULL;
3814 } else {
3815 if (staged_status == GOT_STATUS_DELETE)
3816 return NULL;
3817 if (status == GOT_STATUS_NONEXISTENT)
3818 return got_error_set_errno(ENOENT, path);
3819 if (status != GOT_STATUS_MODIFY &&
3820 status != GOT_STATUS_ADD &&
3821 status != GOT_STATUS_DELETE &&
3822 status != GOT_STATUS_CONFLICT)
3823 return NULL;
3826 if (!a->header_shown) {
3827 printf("diff %s %s%s\n", a->id_str,
3828 got_worktree_get_root_path(a->worktree),
3829 a->diff_staged ? " (staged changes)" : "");
3830 a->header_shown = 1;
3833 if (a->diff_staged) {
3834 const char *label1 = NULL, *label2 = NULL;
3835 switch (staged_status) {
3836 case GOT_STATUS_MODIFY:
3837 label1 = path;
3838 label2 = path;
3839 break;
3840 case GOT_STATUS_ADD:
3841 label2 = path;
3842 break;
3843 case GOT_STATUS_DELETE:
3844 label1 = path;
3845 break;
3846 default:
3847 return got_error(GOT_ERR_FILE_STATUS);
3849 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
3850 label1, label2, a->diff_context, a->ignore_whitespace,
3851 a->repo, stdout);
3854 if (staged_status == GOT_STATUS_ADD ||
3855 staged_status == GOT_STATUS_MODIFY) {
3856 char *id_str;
3857 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
3858 8192);
3859 if (err)
3860 goto done;
3861 err = got_object_id_str(&id_str, staged_blob_id);
3862 if (err)
3863 goto done;
3864 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
3865 err = got_error_from_errno("asprintf");
3866 free(id_str);
3867 goto done;
3869 free(id_str);
3870 } else if (status != GOT_STATUS_ADD) {
3871 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
3872 if (err)
3873 goto done;
3876 if (status != GOT_STATUS_DELETE) {
3877 if (asprintf(&abspath, "%s/%s",
3878 got_worktree_get_root_path(a->worktree), path) == -1) {
3879 err = got_error_from_errno("asprintf");
3880 goto done;
3883 if (dirfd != -1) {
3884 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
3885 if (fd == -1) {
3886 if (errno != ELOOP) {
3887 err = got_error_from_errno2("openat",
3888 abspath);
3889 goto done;
3891 err = get_symlink_target_file(&fd, dirfd,
3892 de_name, abspath);
3893 if (err)
3894 goto done;
3896 } else {
3897 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
3898 if (fd == -1) {
3899 if (errno != ELOOP) {
3900 err = got_error_from_errno2("open",
3901 abspath);
3902 goto done;
3904 err = get_symlink_target_file(&fd, dirfd,
3905 de_name, abspath);
3906 if (err)
3907 goto done;
3910 if (fstat(fd, &sb) == -1) {
3911 err = got_error_from_errno2("fstat", abspath);
3912 goto done;
3914 f2 = fdopen(fd, "r");
3915 if (f2 == NULL) {
3916 err = got_error_from_errno2("fdopen", abspath);
3917 goto done;
3919 fd = -1;
3920 } else
3921 sb.st_size = 0;
3923 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
3924 a->diff_context, a->ignore_whitespace, stdout);
3925 done:
3926 if (blob1)
3927 got_object_blob_close(blob1);
3928 if (f2 && fclose(f2) == EOF && err == NULL)
3929 err = got_error_from_errno("fclose");
3930 if (fd != -1 && close(fd) == -1 && err == NULL)
3931 err = got_error_from_errno("close");
3932 free(abspath);
3933 return err;
3936 static const struct got_error *
3937 cmd_diff(int argc, char *argv[])
3939 const struct got_error *error;
3940 struct got_repository *repo = NULL;
3941 struct got_worktree *worktree = NULL;
3942 char *cwd = NULL, *repo_path = NULL;
3943 struct got_object_id *id1 = NULL, *id2 = NULL;
3944 const char *id_str1 = NULL, *id_str2 = NULL;
3945 char *label1 = NULL, *label2 = NULL;
3946 int type1, type2;
3947 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
3948 const char *errstr;
3949 char *path = NULL;
3951 #ifndef PROFILE
3952 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3953 NULL) == -1)
3954 err(1, "pledge");
3955 #endif
3957 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
3958 switch (ch) {
3959 case 'C':
3960 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3961 &errstr);
3962 if (errstr != NULL)
3963 err(1, "-C option %s", errstr);
3964 break;
3965 case 'r':
3966 repo_path = realpath(optarg, NULL);
3967 if (repo_path == NULL)
3968 return got_error_from_errno2("realpath",
3969 optarg);
3970 got_path_strip_trailing_slashes(repo_path);
3971 break;
3972 case 's':
3973 diff_staged = 1;
3974 break;
3975 case 'w':
3976 ignore_whitespace = 1;
3977 break;
3978 default:
3979 usage_diff();
3980 /* NOTREACHED */
3984 argc -= optind;
3985 argv += optind;
3987 cwd = getcwd(NULL, 0);
3988 if (cwd == NULL) {
3989 error = got_error_from_errno("getcwd");
3990 goto done;
3992 if (argc <= 1) {
3993 if (repo_path)
3994 errx(1,
3995 "-r option can't be used when diffing a work tree");
3996 error = got_worktree_open(&worktree, cwd);
3997 if (error) {
3998 if (error->code == GOT_ERR_NOT_WORKTREE)
3999 error = wrap_not_worktree_error(error, "diff",
4000 cwd);
4001 goto done;
4003 repo_path = strdup(got_worktree_get_repo_path(worktree));
4004 if (repo_path == NULL) {
4005 error = got_error_from_errno("strdup");
4006 goto done;
4008 if (argc == 1) {
4009 error = got_worktree_resolve_path(&path, worktree,
4010 argv[0]);
4011 if (error)
4012 goto done;
4013 } else {
4014 path = strdup("");
4015 if (path == NULL) {
4016 error = got_error_from_errno("strdup");
4017 goto done;
4020 } else if (argc == 2) {
4021 if (diff_staged)
4022 errx(1, "-s option can't be used when diffing "
4023 "objects in repository");
4024 id_str1 = argv[0];
4025 id_str2 = argv[1];
4026 if (repo_path == NULL) {
4027 error = got_worktree_open(&worktree, cwd);
4028 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4029 goto done;
4030 if (worktree) {
4031 repo_path = strdup(
4032 got_worktree_get_repo_path(worktree));
4033 if (repo_path == NULL) {
4034 error = got_error_from_errno("strdup");
4035 goto done;
4037 } else {
4038 repo_path = strdup(cwd);
4039 if (repo_path == NULL) {
4040 error = got_error_from_errno("strdup");
4041 goto done;
4045 } else
4046 usage_diff();
4048 error = got_repo_open(&repo, repo_path, NULL);
4049 free(repo_path);
4050 if (error != NULL)
4051 goto done;
4053 error = apply_unveil(got_repo_get_path(repo), 1,
4054 worktree ? got_worktree_get_root_path(worktree) : NULL);
4055 if (error)
4056 goto done;
4058 if (argc <= 1) {
4059 struct print_diff_arg arg;
4060 struct got_pathlist_head paths;
4061 char *id_str;
4063 TAILQ_INIT(&paths);
4065 error = got_object_id_str(&id_str,
4066 got_worktree_get_base_commit_id(worktree));
4067 if (error)
4068 goto done;
4069 arg.repo = repo;
4070 arg.worktree = worktree;
4071 arg.diff_context = diff_context;
4072 arg.id_str = id_str;
4073 arg.header_shown = 0;
4074 arg.diff_staged = diff_staged;
4075 arg.ignore_whitespace = ignore_whitespace;
4077 error = got_pathlist_append(&paths, path, NULL);
4078 if (error)
4079 goto done;
4081 error = got_worktree_status(worktree, &paths, repo, print_diff,
4082 &arg, check_cancelled, NULL);
4083 free(id_str);
4084 got_pathlist_free(&paths);
4085 goto done;
4088 error = got_repo_match_object_id(&id1, &label1, id_str1,
4089 GOT_OBJ_TYPE_ANY, 1, repo);
4090 if (error)
4091 goto done;
4093 error = got_repo_match_object_id(&id2, &label2, id_str2,
4094 GOT_OBJ_TYPE_ANY, 1, repo);
4095 if (error)
4096 goto done;
4098 error = got_object_get_type(&type1, repo, id1);
4099 if (error)
4100 goto done;
4102 error = got_object_get_type(&type2, repo, id2);
4103 if (error)
4104 goto done;
4106 if (type1 != type2) {
4107 error = got_error(GOT_ERR_OBJ_TYPE);
4108 goto done;
4111 switch (type1) {
4112 case GOT_OBJ_TYPE_BLOB:
4113 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
4114 diff_context, ignore_whitespace, repo, stdout);
4115 break;
4116 case GOT_OBJ_TYPE_TREE:
4117 error = got_diff_objects_as_trees(id1, id2, "", "",
4118 diff_context, ignore_whitespace, repo, stdout);
4119 break;
4120 case GOT_OBJ_TYPE_COMMIT:
4121 printf("diff %s %s\n", label1, label2);
4122 error = got_diff_objects_as_commits(id1, id2, diff_context,
4123 ignore_whitespace, repo, stdout);
4124 break;
4125 default:
4126 error = got_error(GOT_ERR_OBJ_TYPE);
4128 done:
4129 free(label1);
4130 free(label2);
4131 free(id1);
4132 free(id2);
4133 free(path);
4134 if (worktree)
4135 got_worktree_close(worktree);
4136 if (repo) {
4137 const struct got_error *repo_error;
4138 repo_error = got_repo_close(repo);
4139 if (error == NULL)
4140 error = repo_error;
4142 return error;
4145 __dead static void
4146 usage_blame(void)
4148 fprintf(stderr,
4149 "usage: %s blame [-c commit] [-r repository-path] path\n",
4150 getprogname());
4151 exit(1);
4154 struct blame_line {
4155 int annotated;
4156 char *id_str;
4157 char *committer;
4158 char datebuf[11]; /* YYYY-MM-DD + NUL */
4161 struct blame_cb_args {
4162 struct blame_line *lines;
4163 int nlines;
4164 int nlines_prec;
4165 int lineno_cur;
4166 off_t *line_offsets;
4167 FILE *f;
4168 struct got_repository *repo;
4171 static const struct got_error *
4172 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4174 const struct got_error *err = NULL;
4175 struct blame_cb_args *a = arg;
4176 struct blame_line *bline;
4177 char *line = NULL;
4178 size_t linesize = 0;
4179 struct got_commit_object *commit = NULL;
4180 off_t offset;
4181 struct tm tm;
4182 time_t committer_time;
4184 if (nlines != a->nlines ||
4185 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4186 return got_error(GOT_ERR_RANGE);
4188 if (sigint_received)
4189 return got_error(GOT_ERR_ITER_COMPLETED);
4191 if (lineno == -1)
4192 return NULL; /* no change in this commit */
4194 /* Annotate this line. */
4195 bline = &a->lines[lineno - 1];
4196 if (bline->annotated)
4197 return NULL;
4198 err = got_object_id_str(&bline->id_str, id);
4199 if (err)
4200 return err;
4202 err = got_object_open_as_commit(&commit, a->repo, id);
4203 if (err)
4204 goto done;
4206 bline->committer = strdup(got_object_commit_get_committer(commit));
4207 if (bline->committer == NULL) {
4208 err = got_error_from_errno("strdup");
4209 goto done;
4212 committer_time = got_object_commit_get_committer_time(commit);
4213 if (localtime_r(&committer_time, &tm) == NULL)
4214 return got_error_from_errno("localtime_r");
4215 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4216 &tm) >= sizeof(bline->datebuf)) {
4217 err = got_error(GOT_ERR_NO_SPACE);
4218 goto done;
4220 bline->annotated = 1;
4222 /* Print lines annotated so far. */
4223 bline = &a->lines[a->lineno_cur - 1];
4224 if (!bline->annotated)
4225 goto done;
4227 offset = a->line_offsets[a->lineno_cur - 1];
4228 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4229 err = got_error_from_errno("fseeko");
4230 goto done;
4233 while (bline->annotated) {
4234 char *smallerthan, *at, *nl, *committer;
4235 size_t len;
4237 if (getline(&line, &linesize, a->f) == -1) {
4238 if (ferror(a->f))
4239 err = got_error_from_errno("getline");
4240 break;
4243 committer = bline->committer;
4244 smallerthan = strchr(committer, '<');
4245 if (smallerthan && smallerthan[1] != '\0')
4246 committer = smallerthan + 1;
4247 at = strchr(committer, '@');
4248 if (at)
4249 *at = '\0';
4250 len = strlen(committer);
4251 if (len >= 9)
4252 committer[8] = '\0';
4254 nl = strchr(line, '\n');
4255 if (nl)
4256 *nl = '\0';
4257 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4258 bline->id_str, bline->datebuf, committer, line);
4260 a->lineno_cur++;
4261 bline = &a->lines[a->lineno_cur - 1];
4263 done:
4264 if (commit)
4265 got_object_commit_close(commit);
4266 free(line);
4267 return err;
4270 static const struct got_error *
4271 cmd_blame(int argc, char *argv[])
4273 const struct got_error *error;
4274 struct got_repository *repo = NULL;
4275 struct got_worktree *worktree = NULL;
4276 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4277 char *link_target = NULL;
4278 struct got_object_id *obj_id = NULL;
4279 struct got_object_id *commit_id = NULL;
4280 struct got_blob_object *blob = NULL;
4281 char *commit_id_str = NULL;
4282 struct blame_cb_args bca;
4283 int ch, obj_type, i;
4284 size_t filesize;
4286 memset(&bca, 0, sizeof(bca));
4288 #ifndef PROFILE
4289 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4290 NULL) == -1)
4291 err(1, "pledge");
4292 #endif
4294 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4295 switch (ch) {
4296 case 'c':
4297 commit_id_str = optarg;
4298 break;
4299 case 'r':
4300 repo_path = realpath(optarg, NULL);
4301 if (repo_path == NULL)
4302 return got_error_from_errno2("realpath",
4303 optarg);
4304 got_path_strip_trailing_slashes(repo_path);
4305 break;
4306 default:
4307 usage_blame();
4308 /* NOTREACHED */
4312 argc -= optind;
4313 argv += optind;
4315 if (argc == 1)
4316 path = argv[0];
4317 else
4318 usage_blame();
4320 cwd = getcwd(NULL, 0);
4321 if (cwd == NULL) {
4322 error = got_error_from_errno("getcwd");
4323 goto done;
4325 if (repo_path == NULL) {
4326 error = got_worktree_open(&worktree, cwd);
4327 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4328 goto done;
4329 else
4330 error = NULL;
4331 if (worktree) {
4332 repo_path =
4333 strdup(got_worktree_get_repo_path(worktree));
4334 if (repo_path == NULL) {
4335 error = got_error_from_errno("strdup");
4336 if (error)
4337 goto done;
4339 } else {
4340 repo_path = strdup(cwd);
4341 if (repo_path == NULL) {
4342 error = got_error_from_errno("strdup");
4343 goto done;
4348 error = got_repo_open(&repo, repo_path, NULL);
4349 if (error != NULL)
4350 goto done;
4352 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4353 if (error)
4354 goto done;
4356 if (worktree) {
4357 const char *prefix = got_worktree_get_path_prefix(worktree);
4358 char *p, *worktree_subdir = cwd +
4359 strlen(got_worktree_get_root_path(worktree));
4360 if (asprintf(&p, "%s%s%s%s%s",
4361 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
4362 worktree_subdir, worktree_subdir[0] ? "/" : "",
4363 path) == -1) {
4364 error = got_error_from_errno("asprintf");
4365 goto done;
4367 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4368 free(p);
4369 } else {
4370 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4372 if (error)
4373 goto done;
4375 if (commit_id_str == NULL) {
4376 struct got_reference *head_ref;
4377 error = got_ref_open(&head_ref, repo, worktree ?
4378 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4379 if (error != NULL)
4380 goto done;
4381 error = got_ref_resolve(&commit_id, repo, head_ref);
4382 got_ref_close(head_ref);
4383 if (error != NULL)
4384 goto done;
4385 } else {
4386 error = got_repo_match_object_id(&commit_id, NULL,
4387 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4388 if (error)
4389 goto done;
4392 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4393 commit_id, repo);
4394 if (error)
4395 goto done;
4397 error = got_object_id_by_path(&obj_id, repo, commit_id,
4398 link_target ? link_target : in_repo_path);
4399 if (error)
4400 goto done;
4402 error = got_object_get_type(&obj_type, repo, obj_id);
4403 if (error)
4404 goto done;
4406 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4407 error = got_error_path(link_target ? link_target : in_repo_path,
4408 GOT_ERR_OBJ_TYPE);
4409 goto done;
4412 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4413 if (error)
4414 goto done;
4415 bca.f = got_opentemp();
4416 if (bca.f == NULL) {
4417 error = got_error_from_errno("got_opentemp");
4418 goto done;
4420 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4421 &bca.line_offsets, bca.f, blob);
4422 if (error || bca.nlines == 0)
4423 goto done;
4425 /* Don't include \n at EOF in the blame line count. */
4426 if (bca.line_offsets[bca.nlines - 1] == filesize)
4427 bca.nlines--;
4429 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4430 if (bca.lines == NULL) {
4431 error = got_error_from_errno("calloc");
4432 goto done;
4434 bca.lineno_cur = 1;
4435 bca.nlines_prec = 0;
4436 i = bca.nlines;
4437 while (i > 0) {
4438 i /= 10;
4439 bca.nlines_prec++;
4441 bca.repo = repo;
4443 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4444 repo, blame_cb, &bca, check_cancelled, NULL);
4445 done:
4446 free(in_repo_path);
4447 free(link_target);
4448 free(repo_path);
4449 free(cwd);
4450 free(commit_id);
4451 free(obj_id);
4452 if (blob)
4453 got_object_blob_close(blob);
4454 if (worktree)
4455 got_worktree_close(worktree);
4456 if (repo) {
4457 const struct got_error *repo_error;
4458 repo_error = got_repo_close(repo);
4459 if (error == NULL)
4460 error = repo_error;
4462 if (bca.lines) {
4463 for (i = 0; i < bca.nlines; i++) {
4464 struct blame_line *bline = &bca.lines[i];
4465 free(bline->id_str);
4466 free(bline->committer);
4468 free(bca.lines);
4470 free(bca.line_offsets);
4471 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4472 error = got_error_from_errno("fclose");
4473 return error;
4476 __dead static void
4477 usage_tree(void)
4479 fprintf(stderr,
4480 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4481 getprogname());
4482 exit(1);
4485 static const struct got_error *
4486 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4487 const char *root_path, struct got_repository *repo)
4489 const struct got_error *err = NULL;
4490 int is_root_path = (strcmp(path, root_path) == 0);
4491 const char *modestr = "";
4492 mode_t mode = got_tree_entry_get_mode(te);
4493 char *link_target = NULL;
4495 path += strlen(root_path);
4496 while (path[0] == '/')
4497 path++;
4499 if (got_object_tree_entry_is_submodule(te))
4500 modestr = "$";
4501 else if (S_ISLNK(mode)) {
4502 int i;
4504 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4505 if (err)
4506 return err;
4507 for (i = 0; i < strlen(link_target); i++) {
4508 if (!isprint((unsigned char)link_target[i]))
4509 link_target[i] = '?';
4512 modestr = "@";
4514 else if (S_ISDIR(mode))
4515 modestr = "/";
4516 else if (mode & S_IXUSR)
4517 modestr = "*";
4519 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4520 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4521 link_target ? " -> ": "", link_target ? link_target : "");
4523 free(link_target);
4524 return NULL;
4527 static const struct got_error *
4528 print_tree(const char *path, struct got_object_id *commit_id,
4529 int show_ids, int recurse, const char *root_path,
4530 struct got_repository *repo)
4532 const struct got_error *err = NULL;
4533 struct got_object_id *tree_id = NULL;
4534 struct got_tree_object *tree = NULL;
4535 int nentries, i;
4537 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4538 if (err)
4539 goto done;
4541 err = got_object_open_as_tree(&tree, repo, tree_id);
4542 if (err)
4543 goto done;
4544 nentries = got_object_tree_get_nentries(tree);
4545 for (i = 0; i < nentries; i++) {
4546 struct got_tree_entry *te;
4547 char *id = NULL;
4549 if (sigint_received || sigpipe_received)
4550 break;
4552 te = got_object_tree_get_entry(tree, i);
4553 if (show_ids) {
4554 char *id_str;
4555 err = got_object_id_str(&id_str,
4556 got_tree_entry_get_id(te));
4557 if (err)
4558 goto done;
4559 if (asprintf(&id, "%s ", id_str) == -1) {
4560 err = got_error_from_errno("asprintf");
4561 free(id_str);
4562 goto done;
4564 free(id_str);
4566 err = print_entry(te, id, path, root_path, repo);
4567 free(id);
4568 if (err)
4569 goto done;
4571 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4572 char *child_path;
4573 if (asprintf(&child_path, "%s%s%s", path,
4574 path[0] == '/' && path[1] == '\0' ? "" : "/",
4575 got_tree_entry_get_name(te)) == -1) {
4576 err = got_error_from_errno("asprintf");
4577 goto done;
4579 err = print_tree(child_path, commit_id, show_ids, 1,
4580 root_path, repo);
4581 free(child_path);
4582 if (err)
4583 goto done;
4586 done:
4587 if (tree)
4588 got_object_tree_close(tree);
4589 free(tree_id);
4590 return err;
4593 static const struct got_error *
4594 cmd_tree(int argc, char *argv[])
4596 const struct got_error *error;
4597 struct got_repository *repo = NULL;
4598 struct got_worktree *worktree = NULL;
4599 const char *path, *refname = NULL;
4600 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4601 struct got_object_id *commit_id = NULL;
4602 char *commit_id_str = NULL;
4603 int show_ids = 0, recurse = 0;
4604 int ch;
4606 #ifndef PROFILE
4607 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4608 NULL) == -1)
4609 err(1, "pledge");
4610 #endif
4612 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4613 switch (ch) {
4614 case 'c':
4615 commit_id_str = optarg;
4616 break;
4617 case 'r':
4618 repo_path = realpath(optarg, NULL);
4619 if (repo_path == NULL)
4620 return got_error_from_errno2("realpath",
4621 optarg);
4622 got_path_strip_trailing_slashes(repo_path);
4623 break;
4624 case 'i':
4625 show_ids = 1;
4626 break;
4627 case 'R':
4628 recurse = 1;
4629 break;
4630 default:
4631 usage_tree();
4632 /* NOTREACHED */
4636 argc -= optind;
4637 argv += optind;
4639 if (argc == 1)
4640 path = argv[0];
4641 else if (argc > 1)
4642 usage_tree();
4643 else
4644 path = NULL;
4646 cwd = getcwd(NULL, 0);
4647 if (cwd == NULL) {
4648 error = got_error_from_errno("getcwd");
4649 goto done;
4651 if (repo_path == NULL) {
4652 error = got_worktree_open(&worktree, cwd);
4653 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4654 goto done;
4655 else
4656 error = NULL;
4657 if (worktree) {
4658 repo_path =
4659 strdup(got_worktree_get_repo_path(worktree));
4660 if (repo_path == NULL)
4661 error = got_error_from_errno("strdup");
4662 if (error)
4663 goto done;
4664 } else {
4665 repo_path = strdup(cwd);
4666 if (repo_path == NULL) {
4667 error = got_error_from_errno("strdup");
4668 goto done;
4673 error = got_repo_open(&repo, repo_path, NULL);
4674 if (error != NULL)
4675 goto done;
4677 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4678 if (error)
4679 goto done;
4681 if (path == NULL) {
4682 if (worktree) {
4683 char *p, *worktree_subdir = cwd +
4684 strlen(got_worktree_get_root_path(worktree));
4685 if (asprintf(&p, "%s/%s",
4686 got_worktree_get_path_prefix(worktree),
4687 worktree_subdir) == -1) {
4688 error = got_error_from_errno("asprintf");
4689 goto done;
4691 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4692 free(p);
4693 if (error)
4694 goto done;
4695 } else
4696 path = "/";
4698 if (in_repo_path == NULL) {
4699 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4700 if (error != NULL)
4701 goto done;
4704 if (commit_id_str == NULL) {
4705 struct got_reference *head_ref;
4706 if (worktree)
4707 refname = got_worktree_get_head_ref_name(worktree);
4708 else
4709 refname = GOT_REF_HEAD;
4710 error = got_ref_open(&head_ref, repo, refname, 0);
4711 if (error != NULL)
4712 goto done;
4713 error = got_ref_resolve(&commit_id, repo, head_ref);
4714 got_ref_close(head_ref);
4715 if (error != NULL)
4716 goto done;
4717 } else {
4718 error = got_repo_match_object_id(&commit_id, NULL,
4719 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4720 if (error)
4721 goto done;
4724 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4725 in_repo_path, repo);
4726 done:
4727 free(in_repo_path);
4728 free(repo_path);
4729 free(cwd);
4730 free(commit_id);
4731 if (worktree)
4732 got_worktree_close(worktree);
4733 if (repo) {
4734 const struct got_error *repo_error;
4735 repo_error = got_repo_close(repo);
4736 if (error == NULL)
4737 error = repo_error;
4739 return error;
4742 __dead static void
4743 usage_status(void)
4745 fprintf(stderr, "usage: %s status [-s status-codes ] [path ...]\n",
4746 getprogname());
4747 exit(1);
4750 static const struct got_error *
4751 print_status(void *arg, unsigned char status, unsigned char staged_status,
4752 const char *path, struct got_object_id *blob_id,
4753 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4754 int dirfd, const char *de_name)
4756 if (status == staged_status && (status == GOT_STATUS_DELETE))
4757 status = GOT_STATUS_NO_CHANGE;
4758 if (arg) {
4759 char *status_codes = arg;
4760 size_t ncodes = strlen(status_codes);
4761 int i;
4762 for (i = 0; i < ncodes ; i++) {
4763 if (status == status_codes[i] ||
4764 staged_status == status_codes[i])
4765 break;
4767 if (i == ncodes)
4768 return NULL;
4770 printf("%c%c %s\n", status, staged_status, path);
4771 return NULL;
4774 static const struct got_error *
4775 cmd_status(int argc, char *argv[])
4777 const struct got_error *error = NULL;
4778 struct got_repository *repo = NULL;
4779 struct got_worktree *worktree = NULL;
4780 char *cwd = NULL, *status_codes = NULL;;
4781 struct got_pathlist_head paths;
4782 struct got_pathlist_entry *pe;
4783 int ch, i;
4785 TAILQ_INIT(&paths);
4787 while ((ch = getopt(argc, argv, "s:")) != -1) {
4788 switch (ch) {
4789 case 's':
4790 for (i = 0; i < strlen(optarg); i++) {
4791 switch (optarg[i]) {
4792 case GOT_STATUS_MODIFY:
4793 case GOT_STATUS_ADD:
4794 case GOT_STATUS_DELETE:
4795 case GOT_STATUS_CONFLICT:
4796 case GOT_STATUS_MISSING:
4797 case GOT_STATUS_OBSTRUCTED:
4798 case GOT_STATUS_UNVERSIONED:
4799 case GOT_STATUS_MODE_CHANGE:
4800 case GOT_STATUS_NONEXISTENT:
4801 break;
4802 default:
4803 errx(1, "invalid status code '%c'",
4804 optarg[i]);
4807 status_codes = optarg;
4808 break;
4809 default:
4810 usage_status();
4811 /* NOTREACHED */
4815 argc -= optind;
4816 argv += optind;
4818 #ifndef PROFILE
4819 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4820 NULL) == -1)
4821 err(1, "pledge");
4822 #endif
4823 cwd = getcwd(NULL, 0);
4824 if (cwd == NULL) {
4825 error = got_error_from_errno("getcwd");
4826 goto done;
4829 error = got_worktree_open(&worktree, cwd);
4830 if (error) {
4831 if (error->code == GOT_ERR_NOT_WORKTREE)
4832 error = wrap_not_worktree_error(error, "status", cwd);
4833 goto done;
4836 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4837 NULL);
4838 if (error != NULL)
4839 goto done;
4841 error = apply_unveil(got_repo_get_path(repo), 1,
4842 got_worktree_get_root_path(worktree));
4843 if (error)
4844 goto done;
4846 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
4847 if (error)
4848 goto done;
4850 error = got_worktree_status(worktree, &paths, repo, print_status,
4851 status_codes, check_cancelled, NULL);
4852 done:
4853 TAILQ_FOREACH(pe, &paths, entry)
4854 free((char *)pe->path);
4855 got_pathlist_free(&paths);
4856 free(cwd);
4857 return error;
4860 __dead static void
4861 usage_ref(void)
4863 fprintf(stderr,
4864 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
4865 "[-d] [name]\n",
4866 getprogname());
4867 exit(1);
4870 static const struct got_error *
4871 list_refs(struct got_repository *repo, const char *refname)
4873 static const struct got_error *err = NULL;
4874 struct got_reflist_head refs;
4875 struct got_reflist_entry *re;
4877 SIMPLEQ_INIT(&refs);
4878 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
4879 if (err)
4880 return err;
4882 SIMPLEQ_FOREACH(re, &refs, entry) {
4883 char *refstr;
4884 refstr = got_ref_to_str(re->ref);
4885 if (refstr == NULL)
4886 return got_error_from_errno("got_ref_to_str");
4887 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
4888 free(refstr);
4891 got_ref_list_free(&refs);
4892 return NULL;
4895 static const struct got_error *
4896 delete_ref(struct got_repository *repo, const char *refname)
4898 const struct got_error *err = NULL;
4899 struct got_reference *ref;
4901 err = got_ref_open(&ref, repo, refname, 0);
4902 if (err)
4903 return err;
4905 err = got_ref_delete(ref, repo);
4906 got_ref_close(ref);
4907 return err;
4910 static const struct got_error *
4911 add_ref(struct got_repository *repo, const char *refname, const char *target)
4913 const struct got_error *err = NULL;
4914 struct got_object_id *id;
4915 struct got_reference *ref = NULL;
4918 * Don't let the user create a reference name with a leading '-'.
4919 * While technically a valid reference name, this case is usually
4920 * an unintended typo.
4922 if (refname[0] == '-')
4923 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4925 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
4926 repo);
4927 if (err) {
4928 struct got_reference *target_ref;
4930 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
4931 return err;
4932 err = got_ref_open(&target_ref, repo, target, 0);
4933 if (err)
4934 return err;
4935 err = got_ref_resolve(&id, repo, target_ref);
4936 got_ref_close(target_ref);
4937 if (err)
4938 return err;
4941 err = got_ref_alloc(&ref, refname, id);
4942 if (err)
4943 goto done;
4945 err = got_ref_write(ref, repo);
4946 done:
4947 if (ref)
4948 got_ref_close(ref);
4949 free(id);
4950 return err;
4953 static const struct got_error *
4954 add_symref(struct got_repository *repo, const char *refname, const char *target)
4956 const struct got_error *err = NULL;
4957 struct got_reference *ref = NULL;
4958 struct got_reference *target_ref = NULL;
4961 * Don't let the user create a reference name with a leading '-'.
4962 * While technically a valid reference name, this case is usually
4963 * an unintended typo.
4965 if (refname[0] == '-')
4966 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4968 err = got_ref_open(&target_ref, repo, target, 0);
4969 if (err)
4970 return err;
4972 err = got_ref_alloc_symref(&ref, refname, target_ref);
4973 if (err)
4974 goto done;
4976 err = got_ref_write(ref, repo);
4977 done:
4978 if (target_ref)
4979 got_ref_close(target_ref);
4980 if (ref)
4981 got_ref_close(ref);
4982 return err;
4985 static const struct got_error *
4986 cmd_ref(int argc, char *argv[])
4988 const struct got_error *error = NULL;
4989 struct got_repository *repo = NULL;
4990 struct got_worktree *worktree = NULL;
4991 char *cwd = NULL, *repo_path = NULL;
4992 int ch, do_list = 0, do_delete = 0;
4993 const char *obj_arg = NULL, *symref_target= NULL;
4994 char *refname = NULL;
4996 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
4997 switch (ch) {
4998 case 'c':
4999 obj_arg = optarg;
5000 break;
5001 case 'd':
5002 do_delete = 1;
5003 break;
5004 case 'r':
5005 repo_path = realpath(optarg, NULL);
5006 if (repo_path == NULL)
5007 return got_error_from_errno2("realpath",
5008 optarg);
5009 got_path_strip_trailing_slashes(repo_path);
5010 break;
5011 case 'l':
5012 do_list = 1;
5013 break;
5014 case 's':
5015 symref_target = optarg;
5016 break;
5017 default:
5018 usage_ref();
5019 /* NOTREACHED */
5023 if (obj_arg && do_list)
5024 errx(1, "-c and -l options are mutually exclusive");
5025 if (obj_arg && do_delete)
5026 errx(1, "-c and -d options are mutually exclusive");
5027 if (obj_arg && symref_target)
5028 errx(1, "-c and -s options are mutually exclusive");
5029 if (symref_target && do_delete)
5030 errx(1, "-s and -d options are mutually exclusive");
5031 if (symref_target && do_list)
5032 errx(1, "-s and -l options are mutually exclusive");
5033 if (do_delete && do_list)
5034 errx(1, "-d and -l options are mutually exclusive");
5036 argc -= optind;
5037 argv += optind;
5039 if (do_list) {
5040 if (argc != 0 && argc != 1)
5041 usage_ref();
5042 if (argc == 1) {
5043 refname = strdup(argv[0]);
5044 if (refname == NULL) {
5045 error = got_error_from_errno("strdup");
5046 goto done;
5049 } else {
5050 if (argc != 1)
5051 usage_ref();
5052 refname = strdup(argv[0]);
5053 if (refname == NULL) {
5054 error = got_error_from_errno("strdup");
5055 goto done;
5059 if (refname)
5060 got_path_strip_trailing_slashes(refname);
5062 #ifndef PROFILE
5063 if (do_list) {
5064 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5065 NULL) == -1)
5066 err(1, "pledge");
5067 } else {
5068 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5069 "sendfd unveil", NULL) == -1)
5070 err(1, "pledge");
5072 #endif
5073 cwd = getcwd(NULL, 0);
5074 if (cwd == NULL) {
5075 error = got_error_from_errno("getcwd");
5076 goto done;
5079 if (repo_path == NULL) {
5080 error = got_worktree_open(&worktree, cwd);
5081 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5082 goto done;
5083 else
5084 error = NULL;
5085 if (worktree) {
5086 repo_path =
5087 strdup(got_worktree_get_repo_path(worktree));
5088 if (repo_path == NULL)
5089 error = got_error_from_errno("strdup");
5090 if (error)
5091 goto done;
5092 } else {
5093 repo_path = strdup(cwd);
5094 if (repo_path == NULL) {
5095 error = got_error_from_errno("strdup");
5096 goto done;
5101 error = got_repo_open(&repo, repo_path, NULL);
5102 if (error != NULL)
5103 goto done;
5105 error = apply_unveil(got_repo_get_path(repo), do_list,
5106 worktree ? got_worktree_get_root_path(worktree) : NULL);
5107 if (error)
5108 goto done;
5110 if (do_list)
5111 error = list_refs(repo, refname);
5112 else if (do_delete)
5113 error = delete_ref(repo, refname);
5114 else if (symref_target)
5115 error = add_symref(repo, refname, symref_target);
5116 else {
5117 if (obj_arg == NULL)
5118 usage_ref();
5119 error = add_ref(repo, refname, obj_arg);
5121 done:
5122 free(refname);
5123 if (repo)
5124 got_repo_close(repo);
5125 if (worktree)
5126 got_worktree_close(worktree);
5127 free(cwd);
5128 free(repo_path);
5129 return error;
5132 __dead static void
5133 usage_branch(void)
5135 fprintf(stderr,
5136 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5137 "[name]\n", getprogname());
5138 exit(1);
5141 static const struct got_error *
5142 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5143 struct got_reference *ref)
5145 const struct got_error *err = NULL;
5146 const char *refname, *marker = " ";
5147 char *refstr;
5149 refname = got_ref_get_name(ref);
5150 if (worktree && strcmp(refname,
5151 got_worktree_get_head_ref_name(worktree)) == 0) {
5152 struct got_object_id *id = NULL;
5154 err = got_ref_resolve(&id, repo, ref);
5155 if (err)
5156 return err;
5157 if (got_object_id_cmp(id,
5158 got_worktree_get_base_commit_id(worktree)) == 0)
5159 marker = "* ";
5160 else
5161 marker = "~ ";
5162 free(id);
5165 if (strncmp(refname, "refs/heads/", 11) == 0)
5166 refname += 11;
5167 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5168 refname += 18;
5170 refstr = got_ref_to_str(ref);
5171 if (refstr == NULL)
5172 return got_error_from_errno("got_ref_to_str");
5174 printf("%s%s: %s\n", marker, refname, refstr);
5175 free(refstr);
5176 return NULL;
5179 static const struct got_error *
5180 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5182 const char *refname;
5184 if (worktree == NULL)
5185 return got_error(GOT_ERR_NOT_WORKTREE);
5187 refname = got_worktree_get_head_ref_name(worktree);
5189 if (strncmp(refname, "refs/heads/", 11) == 0)
5190 refname += 11;
5191 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5192 refname += 18;
5194 printf("%s\n", refname);
5196 return NULL;
5199 static const struct got_error *
5200 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5202 static const struct got_error *err = NULL;
5203 struct got_reflist_head refs;
5204 struct got_reflist_entry *re;
5205 struct got_reference *temp_ref = NULL;
5206 int rebase_in_progress, histedit_in_progress;
5208 SIMPLEQ_INIT(&refs);
5210 if (worktree) {
5211 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5212 worktree);
5213 if (err)
5214 return err;
5216 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5217 worktree);
5218 if (err)
5219 return err;
5221 if (rebase_in_progress || histedit_in_progress) {
5222 err = got_ref_open(&temp_ref, repo,
5223 got_worktree_get_head_ref_name(worktree), 0);
5224 if (err)
5225 return err;
5226 list_branch(repo, worktree, temp_ref);
5227 got_ref_close(temp_ref);
5231 err = got_ref_list(&refs, repo, "refs/heads",
5232 got_ref_cmp_by_name, NULL);
5233 if (err)
5234 return err;
5236 SIMPLEQ_FOREACH(re, &refs, entry)
5237 list_branch(repo, worktree, re->ref);
5239 got_ref_list_free(&refs);
5240 return NULL;
5243 static const struct got_error *
5244 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5245 const char *branch_name)
5247 const struct got_error *err = NULL;
5248 struct got_reference *ref = NULL;
5249 char *refname;
5251 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5252 return got_error_from_errno("asprintf");
5254 err = got_ref_open(&ref, repo, refname, 0);
5255 if (err)
5256 goto done;
5258 if (worktree &&
5259 strcmp(got_worktree_get_head_ref_name(worktree),
5260 got_ref_get_name(ref)) == 0) {
5261 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5262 "will not delete this work tree's current branch");
5263 goto done;
5266 err = got_ref_delete(ref, repo);
5267 done:
5268 if (ref)
5269 got_ref_close(ref);
5270 free(refname);
5271 return err;
5274 static const struct got_error *
5275 add_branch(struct got_repository *repo, const char *branch_name,
5276 struct got_object_id *base_commit_id)
5278 const struct got_error *err = NULL;
5279 struct got_reference *ref = NULL;
5280 char *base_refname = NULL, *refname = NULL;
5283 * Don't let the user create a branch name with a leading '-'.
5284 * While technically a valid reference name, this case is usually
5285 * an unintended typo.
5287 if (branch_name[0] == '-')
5288 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5290 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5291 err = got_error_from_errno("asprintf");
5292 goto done;
5295 err = got_ref_open(&ref, repo, refname, 0);
5296 if (err == NULL) {
5297 err = got_error(GOT_ERR_BRANCH_EXISTS);
5298 goto done;
5299 } else if (err->code != GOT_ERR_NOT_REF)
5300 goto done;
5302 err = got_ref_alloc(&ref, refname, base_commit_id);
5303 if (err)
5304 goto done;
5306 err = got_ref_write(ref, repo);
5307 done:
5308 if (ref)
5309 got_ref_close(ref);
5310 free(base_refname);
5311 free(refname);
5312 return err;
5315 static const struct got_error *
5316 cmd_branch(int argc, char *argv[])
5318 const struct got_error *error = NULL;
5319 struct got_repository *repo = NULL;
5320 struct got_worktree *worktree = NULL;
5321 char *cwd = NULL, *repo_path = NULL;
5322 int ch, do_list = 0, do_show = 0, do_update = 1;
5323 const char *delref = NULL, *commit_id_arg = NULL;
5324 struct got_reference *ref = NULL;
5325 struct got_pathlist_head paths;
5326 struct got_pathlist_entry *pe;
5327 struct got_object_id *commit_id = NULL;
5328 char *commit_id_str = NULL;
5330 TAILQ_INIT(&paths);
5332 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5333 switch (ch) {
5334 case 'c':
5335 commit_id_arg = optarg;
5336 break;
5337 case 'd':
5338 delref = optarg;
5339 break;
5340 case 'r':
5341 repo_path = realpath(optarg, NULL);
5342 if (repo_path == NULL)
5343 return got_error_from_errno2("realpath",
5344 optarg);
5345 got_path_strip_trailing_slashes(repo_path);
5346 break;
5347 case 'l':
5348 do_list = 1;
5349 break;
5350 case 'n':
5351 do_update = 0;
5352 break;
5353 default:
5354 usage_branch();
5355 /* NOTREACHED */
5359 if (do_list && delref)
5360 errx(1, "-l and -d options are mutually exclusive");
5362 argc -= optind;
5363 argv += optind;
5365 if (!do_list && !delref && argc == 0)
5366 do_show = 1;
5368 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5369 errx(1, "-c option can only be used when creating a branch");
5371 if (do_list || delref) {
5372 if (argc > 0)
5373 usage_branch();
5374 } else if (!do_show && argc != 1)
5375 usage_branch();
5377 #ifndef PROFILE
5378 if (do_list || do_show) {
5379 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5380 NULL) == -1)
5381 err(1, "pledge");
5382 } else {
5383 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5384 "sendfd unveil", NULL) == -1)
5385 err(1, "pledge");
5387 #endif
5388 cwd = getcwd(NULL, 0);
5389 if (cwd == NULL) {
5390 error = got_error_from_errno("getcwd");
5391 goto done;
5394 if (repo_path == NULL) {
5395 error = got_worktree_open(&worktree, cwd);
5396 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5397 goto done;
5398 else
5399 error = NULL;
5400 if (worktree) {
5401 repo_path =
5402 strdup(got_worktree_get_repo_path(worktree));
5403 if (repo_path == NULL)
5404 error = got_error_from_errno("strdup");
5405 if (error)
5406 goto done;
5407 } else {
5408 repo_path = strdup(cwd);
5409 if (repo_path == NULL) {
5410 error = got_error_from_errno("strdup");
5411 goto done;
5416 error = got_repo_open(&repo, repo_path, NULL);
5417 if (error != NULL)
5418 goto done;
5420 error = apply_unveil(got_repo_get_path(repo), do_list,
5421 worktree ? got_worktree_get_root_path(worktree) : NULL);
5422 if (error)
5423 goto done;
5425 if (do_show)
5426 error = show_current_branch(repo, worktree);
5427 else if (do_list)
5428 error = list_branches(repo, worktree);
5429 else if (delref)
5430 error = delete_branch(repo, worktree, delref);
5431 else {
5432 if (commit_id_arg == NULL)
5433 commit_id_arg = worktree ?
5434 got_worktree_get_head_ref_name(worktree) :
5435 GOT_REF_HEAD;
5436 error = got_repo_match_object_id(&commit_id, NULL,
5437 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5438 if (error)
5439 goto done;
5440 error = add_branch(repo, argv[0], commit_id);
5441 if (error)
5442 goto done;
5443 if (worktree && do_update) {
5444 struct got_update_progress_arg upa;
5445 char *branch_refname = NULL;
5447 error = got_object_id_str(&commit_id_str, commit_id);
5448 if (error)
5449 goto done;
5450 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5451 worktree);
5452 if (error)
5453 goto done;
5454 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5455 == -1) {
5456 error = got_error_from_errno("asprintf");
5457 goto done;
5459 error = got_ref_open(&ref, repo, branch_refname, 0);
5460 free(branch_refname);
5461 if (error)
5462 goto done;
5463 error = switch_head_ref(ref, commit_id, worktree,
5464 repo);
5465 if (error)
5466 goto done;
5467 error = got_worktree_set_base_commit_id(worktree, repo,
5468 commit_id);
5469 if (error)
5470 goto done;
5471 memset(&upa, 0, sizeof(upa));
5472 error = got_worktree_checkout_files(worktree, &paths,
5473 repo, update_progress, &upa, check_cancelled,
5474 NULL);
5475 if (error)
5476 goto done;
5477 if (upa.did_something)
5478 printf("Updated to commit %s\n", commit_id_str);
5479 print_update_progress_stats(&upa);
5482 done:
5483 if (ref)
5484 got_ref_close(ref);
5485 if (repo)
5486 got_repo_close(repo);
5487 if (worktree)
5488 got_worktree_close(worktree);
5489 free(cwd);
5490 free(repo_path);
5491 free(commit_id);
5492 free(commit_id_str);
5493 TAILQ_FOREACH(pe, &paths, entry)
5494 free((char *)pe->path);
5495 got_pathlist_free(&paths);
5496 return error;
5500 __dead static void
5501 usage_tag(void)
5503 fprintf(stderr,
5504 "usage: %s tag [-c commit] [-r repository] [-l] "
5505 "[-m message] name\n", getprogname());
5506 exit(1);
5509 #if 0
5510 static const struct got_error *
5511 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5513 const struct got_error *err = NULL;
5514 struct got_reflist_entry *re, *se, *new;
5515 struct got_object_id *re_id, *se_id;
5516 struct got_tag_object *re_tag, *se_tag;
5517 time_t re_time, se_time;
5519 SIMPLEQ_FOREACH(re, tags, entry) {
5520 se = SIMPLEQ_FIRST(sorted);
5521 if (se == NULL) {
5522 err = got_reflist_entry_dup(&new, re);
5523 if (err)
5524 return err;
5525 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5526 continue;
5527 } else {
5528 err = got_ref_resolve(&re_id, repo, re->ref);
5529 if (err)
5530 break;
5531 err = got_object_open_as_tag(&re_tag, repo, re_id);
5532 free(re_id);
5533 if (err)
5534 break;
5535 re_time = got_object_tag_get_tagger_time(re_tag);
5536 got_object_tag_close(re_tag);
5539 while (se) {
5540 err = got_ref_resolve(&se_id, repo, re->ref);
5541 if (err)
5542 break;
5543 err = got_object_open_as_tag(&se_tag, repo, se_id);
5544 free(se_id);
5545 if (err)
5546 break;
5547 se_time = got_object_tag_get_tagger_time(se_tag);
5548 got_object_tag_close(se_tag);
5550 if (se_time > re_time) {
5551 err = got_reflist_entry_dup(&new, re);
5552 if (err)
5553 return err;
5554 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5555 break;
5557 se = SIMPLEQ_NEXT(se, entry);
5558 continue;
5561 done:
5562 return err;
5564 #endif
5566 static const struct got_error *
5567 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5569 static const struct got_error *err = NULL;
5570 struct got_reflist_head refs;
5571 struct got_reflist_entry *re;
5573 SIMPLEQ_INIT(&refs);
5575 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5576 if (err)
5577 return err;
5579 SIMPLEQ_FOREACH(re, &refs, entry) {
5580 const char *refname;
5581 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5582 char datebuf[26];
5583 const char *tagger;
5584 time_t tagger_time;
5585 struct got_object_id *id;
5586 struct got_tag_object *tag;
5587 struct got_commit_object *commit = NULL;
5589 refname = got_ref_get_name(re->ref);
5590 if (strncmp(refname, "refs/tags/", 10) != 0)
5591 continue;
5592 refname += 10;
5593 refstr = got_ref_to_str(re->ref);
5594 if (refstr == NULL) {
5595 err = got_error_from_errno("got_ref_to_str");
5596 break;
5598 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5599 free(refstr);
5601 err = got_ref_resolve(&id, repo, re->ref);
5602 if (err)
5603 break;
5604 err = got_object_open_as_tag(&tag, repo, id);
5605 if (err) {
5606 if (err->code != GOT_ERR_OBJ_TYPE) {
5607 free(id);
5608 break;
5610 /* "lightweight" tag */
5611 err = got_object_open_as_commit(&commit, repo, id);
5612 if (err) {
5613 free(id);
5614 break;
5616 tagger = got_object_commit_get_committer(commit);
5617 tagger_time =
5618 got_object_commit_get_committer_time(commit);
5619 err = got_object_id_str(&id_str, id);
5620 free(id);
5621 if (err)
5622 break;
5623 } else {
5624 free(id);
5625 tagger = got_object_tag_get_tagger(tag);
5626 tagger_time = got_object_tag_get_tagger_time(tag);
5627 err = got_object_id_str(&id_str,
5628 got_object_tag_get_object_id(tag));
5629 if (err)
5630 break;
5632 printf("from: %s\n", tagger);
5633 datestr = get_datestr(&tagger_time, datebuf);
5634 if (datestr)
5635 printf("date: %s UTC\n", datestr);
5636 if (commit)
5637 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5638 else {
5639 switch (got_object_tag_get_object_type(tag)) {
5640 case GOT_OBJ_TYPE_BLOB:
5641 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5642 id_str);
5643 break;
5644 case GOT_OBJ_TYPE_TREE:
5645 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5646 id_str);
5647 break;
5648 case GOT_OBJ_TYPE_COMMIT:
5649 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5650 id_str);
5651 break;
5652 case GOT_OBJ_TYPE_TAG:
5653 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5654 id_str);
5655 break;
5656 default:
5657 break;
5660 free(id_str);
5661 if (commit) {
5662 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5663 if (err)
5664 break;
5665 got_object_commit_close(commit);
5666 } else {
5667 tagmsg0 = strdup(got_object_tag_get_message(tag));
5668 got_object_tag_close(tag);
5669 if (tagmsg0 == NULL) {
5670 err = got_error_from_errno("strdup");
5671 break;
5675 tagmsg = tagmsg0;
5676 do {
5677 line = strsep(&tagmsg, "\n");
5678 if (line)
5679 printf(" %s\n", line);
5680 } while (line);
5681 free(tagmsg0);
5684 got_ref_list_free(&refs);
5685 return NULL;
5688 static const struct got_error *
5689 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5690 const char *tag_name, const char *repo_path)
5692 const struct got_error *err = NULL;
5693 char *template = NULL, *initial_content = NULL;
5694 char *editor = NULL;
5695 int initial_content_len;
5696 int fd = -1;
5698 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5699 err = got_error_from_errno("asprintf");
5700 goto done;
5703 initial_content_len = asprintf(&initial_content,
5704 "\n# tagging commit %s as %s\n",
5705 commit_id_str, tag_name);
5706 if (initial_content_len == -1) {
5707 err = got_error_from_errno("asprintf");
5708 goto done;
5711 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5712 if (err)
5713 goto done;
5715 if (write(fd, initial_content, initial_content_len) == -1) {
5716 err = got_error_from_errno2("write", *tagmsg_path);
5717 goto done;
5720 err = get_editor(&editor);
5721 if (err)
5722 goto done;
5723 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
5724 done:
5725 free(initial_content);
5726 free(template);
5727 free(editor);
5729 if (fd != -1 && close(fd) == -1 && err == NULL)
5730 err = got_error_from_errno2("close", *tagmsg_path);
5732 /* Editor is done; we can now apply unveil(2) */
5733 if (err == NULL)
5734 err = apply_unveil(repo_path, 0, NULL);
5735 if (err) {
5736 free(*tagmsg);
5737 *tagmsg = NULL;
5739 return err;
5742 static const struct got_error *
5743 add_tag(struct got_repository *repo, struct got_worktree *worktree,
5744 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
5746 const struct got_error *err = NULL;
5747 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5748 char *label = NULL, *commit_id_str = NULL;
5749 struct got_reference *ref = NULL;
5750 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5751 char *tagmsg_path = NULL, *tag_id_str = NULL;
5752 int preserve_tagmsg = 0;
5755 * Don't let the user create a tag name with a leading '-'.
5756 * While technically a valid reference name, this case is usually
5757 * an unintended typo.
5759 if (tag_name[0] == '-')
5760 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5762 err = get_author(&tagger, repo, worktree);
5763 if (err)
5764 return err;
5766 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5767 GOT_OBJ_TYPE_COMMIT, 1, repo);
5768 if (err)
5769 goto done;
5771 err = got_object_id_str(&commit_id_str, commit_id);
5772 if (err)
5773 goto done;
5775 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5776 refname = strdup(tag_name);
5777 if (refname == NULL) {
5778 err = got_error_from_errno("strdup");
5779 goto done;
5781 tag_name += 10;
5782 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5783 err = got_error_from_errno("asprintf");
5784 goto done;
5787 err = got_ref_open(&ref, repo, refname, 0);
5788 if (err == NULL) {
5789 err = got_error(GOT_ERR_TAG_EXISTS);
5790 goto done;
5791 } else if (err->code != GOT_ERR_NOT_REF)
5792 goto done;
5794 if (tagmsg_arg == NULL) {
5795 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5796 tag_name, got_repo_get_path(repo));
5797 if (err) {
5798 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5799 tagmsg_path != NULL)
5800 preserve_tagmsg = 1;
5801 goto done;
5805 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5806 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5807 if (err) {
5808 if (tagmsg_path)
5809 preserve_tagmsg = 1;
5810 goto done;
5813 err = got_ref_alloc(&ref, refname, tag_id);
5814 if (err) {
5815 if (tagmsg_path)
5816 preserve_tagmsg = 1;
5817 goto done;
5820 err = got_ref_write(ref, repo);
5821 if (err) {
5822 if (tagmsg_path)
5823 preserve_tagmsg = 1;
5824 goto done;
5827 err = got_object_id_str(&tag_id_str, tag_id);
5828 if (err) {
5829 if (tagmsg_path)
5830 preserve_tagmsg = 1;
5831 goto done;
5833 printf("Created tag %s\n", tag_id_str);
5834 done:
5835 if (preserve_tagmsg) {
5836 fprintf(stderr, "%s: tag message preserved in %s\n",
5837 getprogname(), tagmsg_path);
5838 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
5839 err = got_error_from_errno2("unlink", tagmsg_path);
5840 free(tag_id_str);
5841 if (ref)
5842 got_ref_close(ref);
5843 free(commit_id);
5844 free(commit_id_str);
5845 free(refname);
5846 free(tagmsg);
5847 free(tagmsg_path);
5848 free(tagger);
5849 return err;
5852 static const struct got_error *
5853 cmd_tag(int argc, char *argv[])
5855 const struct got_error *error = NULL;
5856 struct got_repository *repo = NULL;
5857 struct got_worktree *worktree = NULL;
5858 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
5859 char *gitconfig_path = NULL;
5860 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
5861 int ch, do_list = 0;
5863 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
5864 switch (ch) {
5865 case 'c':
5866 commit_id_arg = optarg;
5867 break;
5868 case 'm':
5869 tagmsg = optarg;
5870 break;
5871 case 'r':
5872 repo_path = realpath(optarg, NULL);
5873 if (repo_path == NULL)
5874 return got_error_from_errno2("realpath",
5875 optarg);
5876 got_path_strip_trailing_slashes(repo_path);
5877 break;
5878 case 'l':
5879 do_list = 1;
5880 break;
5881 default:
5882 usage_tag();
5883 /* NOTREACHED */
5887 argc -= optind;
5888 argv += optind;
5890 if (do_list) {
5891 if (commit_id_arg != NULL)
5892 errx(1,
5893 "-c option can only be used when creating a tag");
5894 if (tagmsg)
5895 errx(1, "-l and -m options are mutually exclusive");
5896 if (argc > 0)
5897 usage_tag();
5898 } else if (argc != 1)
5899 usage_tag();
5901 tag_name = argv[0];
5903 #ifndef PROFILE
5904 if (do_list) {
5905 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5906 NULL) == -1)
5907 err(1, "pledge");
5908 } else {
5909 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5910 "sendfd unveil", NULL) == -1)
5911 err(1, "pledge");
5913 #endif
5914 cwd = getcwd(NULL, 0);
5915 if (cwd == NULL) {
5916 error = got_error_from_errno("getcwd");
5917 goto done;
5920 if (repo_path == NULL) {
5921 error = got_worktree_open(&worktree, cwd);
5922 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5923 goto done;
5924 else
5925 error = NULL;
5926 if (worktree) {
5927 repo_path =
5928 strdup(got_worktree_get_repo_path(worktree));
5929 if (repo_path == NULL)
5930 error = got_error_from_errno("strdup");
5931 if (error)
5932 goto done;
5933 } else {
5934 repo_path = strdup(cwd);
5935 if (repo_path == NULL) {
5936 error = got_error_from_errno("strdup");
5937 goto done;
5942 if (do_list) {
5943 error = got_repo_open(&repo, repo_path, NULL);
5944 if (error != NULL)
5945 goto done;
5946 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5947 if (error)
5948 goto done;
5949 error = list_tags(repo, worktree);
5950 } else {
5951 error = get_gitconfig_path(&gitconfig_path);
5952 if (error)
5953 goto done;
5954 error = got_repo_open(&repo, repo_path, gitconfig_path);
5955 if (error != NULL)
5956 goto done;
5958 if (tagmsg) {
5959 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5960 if (error)
5961 goto done;
5964 if (commit_id_arg == NULL) {
5965 struct got_reference *head_ref;
5966 struct got_object_id *commit_id;
5967 error = got_ref_open(&head_ref, repo,
5968 worktree ? got_worktree_get_head_ref_name(worktree)
5969 : GOT_REF_HEAD, 0);
5970 if (error)
5971 goto done;
5972 error = got_ref_resolve(&commit_id, repo, head_ref);
5973 got_ref_close(head_ref);
5974 if (error)
5975 goto done;
5976 error = got_object_id_str(&commit_id_str, commit_id);
5977 free(commit_id);
5978 if (error)
5979 goto done;
5982 error = add_tag(repo, worktree, tag_name,
5983 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
5985 done:
5986 if (repo)
5987 got_repo_close(repo);
5988 if (worktree)
5989 got_worktree_close(worktree);
5990 free(cwd);
5991 free(repo_path);
5992 free(gitconfig_path);
5993 free(commit_id_str);
5994 return error;
5997 __dead static void
5998 usage_add(void)
6000 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6001 getprogname());
6002 exit(1);
6005 static const struct got_error *
6006 add_progress(void *arg, unsigned char status, const char *path)
6008 while (path[0] == '/')
6009 path++;
6010 printf("%c %s\n", status, path);
6011 return NULL;
6014 static const struct got_error *
6015 cmd_add(int argc, char *argv[])
6017 const struct got_error *error = NULL;
6018 struct got_repository *repo = NULL;
6019 struct got_worktree *worktree = NULL;
6020 char *cwd = NULL;
6021 struct got_pathlist_head paths;
6022 struct got_pathlist_entry *pe;
6023 int ch, can_recurse = 0, no_ignores = 0;
6025 TAILQ_INIT(&paths);
6027 while ((ch = getopt(argc, argv, "IR")) != -1) {
6028 switch (ch) {
6029 case 'I':
6030 no_ignores = 1;
6031 break;
6032 case 'R':
6033 can_recurse = 1;
6034 break;
6035 default:
6036 usage_add();
6037 /* NOTREACHED */
6041 argc -= optind;
6042 argv += optind;
6044 #ifndef PROFILE
6045 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6046 NULL) == -1)
6047 err(1, "pledge");
6048 #endif
6049 if (argc < 1)
6050 usage_add();
6052 cwd = getcwd(NULL, 0);
6053 if (cwd == NULL) {
6054 error = got_error_from_errno("getcwd");
6055 goto done;
6058 error = got_worktree_open(&worktree, cwd);
6059 if (error) {
6060 if (error->code == GOT_ERR_NOT_WORKTREE)
6061 error = wrap_not_worktree_error(error, "add", cwd);
6062 goto done;
6065 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6066 NULL);
6067 if (error != NULL)
6068 goto done;
6070 error = apply_unveil(got_repo_get_path(repo), 1,
6071 got_worktree_get_root_path(worktree));
6072 if (error)
6073 goto done;
6075 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6076 if (error)
6077 goto done;
6079 if (!can_recurse && no_ignores) {
6080 error = got_error_msg(GOT_ERR_BAD_PATH,
6081 "disregarding ignores requires -R option");
6082 goto done;
6086 if (!can_recurse) {
6087 char *ondisk_path;
6088 struct stat sb;
6089 TAILQ_FOREACH(pe, &paths, entry) {
6090 if (asprintf(&ondisk_path, "%s/%s",
6091 got_worktree_get_root_path(worktree),
6092 pe->path) == -1) {
6093 error = got_error_from_errno("asprintf");
6094 goto done;
6096 if (lstat(ondisk_path, &sb) == -1) {
6097 if (errno == ENOENT) {
6098 free(ondisk_path);
6099 continue;
6101 error = got_error_from_errno2("lstat",
6102 ondisk_path);
6103 free(ondisk_path);
6104 goto done;
6106 free(ondisk_path);
6107 if (S_ISDIR(sb.st_mode)) {
6108 error = got_error_msg(GOT_ERR_BAD_PATH,
6109 "adding directories requires -R option");
6110 goto done;
6115 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6116 NULL, repo, no_ignores);
6117 done:
6118 if (repo)
6119 got_repo_close(repo);
6120 if (worktree)
6121 got_worktree_close(worktree);
6122 TAILQ_FOREACH(pe, &paths, entry)
6123 free((char *)pe->path);
6124 got_pathlist_free(&paths);
6125 free(cwd);
6126 return error;
6129 __dead static void
6130 usage_remove(void)
6132 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6133 "path ...\n", getprogname());
6134 exit(1);
6137 static const struct got_error *
6138 print_remove_status(void *arg, unsigned char status,
6139 unsigned char staged_status, const char *path)
6141 while (path[0] == '/')
6142 path++;
6143 if (status == GOT_STATUS_NONEXISTENT)
6144 return NULL;
6145 if (status == staged_status && (status == GOT_STATUS_DELETE))
6146 status = GOT_STATUS_NO_CHANGE;
6147 printf("%c%c %s\n", status, staged_status, path);
6148 return NULL;
6151 static const struct got_error *
6152 cmd_remove(int argc, char *argv[])
6154 const struct got_error *error = NULL;
6155 struct got_worktree *worktree = NULL;
6156 struct got_repository *repo = NULL;
6157 const char *status_codes = NULL;
6158 char *cwd = NULL;
6159 struct got_pathlist_head paths;
6160 struct got_pathlist_entry *pe;
6161 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6163 TAILQ_INIT(&paths);
6165 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6166 switch (ch) {
6167 case 'f':
6168 delete_local_mods = 1;
6169 break;
6170 case 'k':
6171 keep_on_disk = 1;
6172 break;
6173 case 'R':
6174 can_recurse = 1;
6175 break;
6176 case 's':
6177 for (i = 0; i < strlen(optarg); i++) {
6178 switch (optarg[i]) {
6179 case GOT_STATUS_MODIFY:
6180 delete_local_mods = 1;
6181 break;
6182 case GOT_STATUS_MISSING:
6183 break;
6184 default:
6185 errx(1, "invalid status code '%c'",
6186 optarg[i]);
6189 status_codes = optarg;
6190 break;
6191 default:
6192 usage_remove();
6193 /* NOTREACHED */
6197 argc -= optind;
6198 argv += optind;
6200 #ifndef PROFILE
6201 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6202 NULL) == -1)
6203 err(1, "pledge");
6204 #endif
6205 if (argc < 1)
6206 usage_remove();
6208 cwd = getcwd(NULL, 0);
6209 if (cwd == NULL) {
6210 error = got_error_from_errno("getcwd");
6211 goto done;
6213 error = got_worktree_open(&worktree, cwd);
6214 if (error) {
6215 if (error->code == GOT_ERR_NOT_WORKTREE)
6216 error = wrap_not_worktree_error(error, "remove", cwd);
6217 goto done;
6220 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6221 NULL);
6222 if (error)
6223 goto done;
6225 error = apply_unveil(got_repo_get_path(repo), 1,
6226 got_worktree_get_root_path(worktree));
6227 if (error)
6228 goto done;
6230 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6231 if (error)
6232 goto done;
6234 if (!can_recurse) {
6235 char *ondisk_path;
6236 struct stat sb;
6237 TAILQ_FOREACH(pe, &paths, entry) {
6238 if (asprintf(&ondisk_path, "%s/%s",
6239 got_worktree_get_root_path(worktree),
6240 pe->path) == -1) {
6241 error = got_error_from_errno("asprintf");
6242 goto done;
6244 if (lstat(ondisk_path, &sb) == -1) {
6245 if (errno == ENOENT) {
6246 free(ondisk_path);
6247 continue;
6249 error = got_error_from_errno2("lstat",
6250 ondisk_path);
6251 free(ondisk_path);
6252 goto done;
6254 free(ondisk_path);
6255 if (S_ISDIR(sb.st_mode)) {
6256 error = got_error_msg(GOT_ERR_BAD_PATH,
6257 "removing directories requires -R option");
6258 goto done;
6263 error = got_worktree_schedule_delete(worktree, &paths,
6264 delete_local_mods, status_codes, print_remove_status, NULL,
6265 repo, keep_on_disk);
6266 done:
6267 if (repo)
6268 got_repo_close(repo);
6269 if (worktree)
6270 got_worktree_close(worktree);
6271 TAILQ_FOREACH(pe, &paths, entry)
6272 free((char *)pe->path);
6273 got_pathlist_free(&paths);
6274 free(cwd);
6275 return error;
6278 __dead static void
6279 usage_revert(void)
6281 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6282 "path ...\n", getprogname());
6283 exit(1);
6286 static const struct got_error *
6287 revert_progress(void *arg, unsigned char status, const char *path)
6289 if (status == GOT_STATUS_UNVERSIONED)
6290 return NULL;
6292 while (path[0] == '/')
6293 path++;
6294 printf("%c %s\n", status, path);
6295 return NULL;
6298 struct choose_patch_arg {
6299 FILE *patch_script_file;
6300 const char *action;
6303 static const struct got_error *
6304 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6305 int nchanges, const char *action)
6307 char *line = NULL;
6308 size_t linesize = 0;
6309 ssize_t linelen;
6311 switch (status) {
6312 case GOT_STATUS_ADD:
6313 printf("A %s\n%s this addition? [y/n] ", path, action);
6314 break;
6315 case GOT_STATUS_DELETE:
6316 printf("D %s\n%s this deletion? [y/n] ", path, action);
6317 break;
6318 case GOT_STATUS_MODIFY:
6319 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6320 return got_error_from_errno("fseek");
6321 printf(GOT_COMMIT_SEP_STR);
6322 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6323 printf("%s", line);
6324 if (ferror(patch_file))
6325 return got_error_from_errno("getline");
6326 printf(GOT_COMMIT_SEP_STR);
6327 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6328 path, n, nchanges, action);
6329 break;
6330 default:
6331 return got_error_path(path, GOT_ERR_FILE_STATUS);
6334 return NULL;
6337 static const struct got_error *
6338 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6339 FILE *patch_file, int n, int nchanges)
6341 const struct got_error *err = NULL;
6342 char *line = NULL;
6343 size_t linesize = 0;
6344 ssize_t linelen;
6345 int resp = ' ';
6346 struct choose_patch_arg *a = arg;
6348 *choice = GOT_PATCH_CHOICE_NONE;
6350 if (a->patch_script_file) {
6351 char *nl;
6352 err = show_change(status, path, patch_file, n, nchanges,
6353 a->action);
6354 if (err)
6355 return err;
6356 linelen = getline(&line, &linesize, a->patch_script_file);
6357 if (linelen == -1) {
6358 if (ferror(a->patch_script_file))
6359 return got_error_from_errno("getline");
6360 return NULL;
6362 nl = strchr(line, '\n');
6363 if (nl)
6364 *nl = '\0';
6365 if (strcmp(line, "y") == 0) {
6366 *choice = GOT_PATCH_CHOICE_YES;
6367 printf("y\n");
6368 } else if (strcmp(line, "n") == 0) {
6369 *choice = GOT_PATCH_CHOICE_NO;
6370 printf("n\n");
6371 } else if (strcmp(line, "q") == 0 &&
6372 status == GOT_STATUS_MODIFY) {
6373 *choice = GOT_PATCH_CHOICE_QUIT;
6374 printf("q\n");
6375 } else
6376 printf("invalid response '%s'\n", line);
6377 free(line);
6378 return NULL;
6381 while (resp != 'y' && resp != 'n' && resp != 'q') {
6382 err = show_change(status, path, patch_file, n, nchanges,
6383 a->action);
6384 if (err)
6385 return err;
6386 resp = getchar();
6387 if (resp == '\n')
6388 resp = getchar();
6389 if (status == GOT_STATUS_MODIFY) {
6390 if (resp != 'y' && resp != 'n' && resp != 'q') {
6391 printf("invalid response '%c'\n", resp);
6392 resp = ' ';
6394 } else if (resp != 'y' && resp != 'n') {
6395 printf("invalid response '%c'\n", resp);
6396 resp = ' ';
6400 if (resp == 'y')
6401 *choice = GOT_PATCH_CHOICE_YES;
6402 else if (resp == 'n')
6403 *choice = GOT_PATCH_CHOICE_NO;
6404 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6405 *choice = GOT_PATCH_CHOICE_QUIT;
6407 return NULL;
6411 static const struct got_error *
6412 cmd_revert(int argc, char *argv[])
6414 const struct got_error *error = NULL;
6415 struct got_worktree *worktree = NULL;
6416 struct got_repository *repo = NULL;
6417 char *cwd = NULL, *path = NULL;
6418 struct got_pathlist_head paths;
6419 struct got_pathlist_entry *pe;
6420 int ch, can_recurse = 0, pflag = 0;
6421 FILE *patch_script_file = NULL;
6422 const char *patch_script_path = NULL;
6423 struct choose_patch_arg cpa;
6425 TAILQ_INIT(&paths);
6427 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6428 switch (ch) {
6429 case 'p':
6430 pflag = 1;
6431 break;
6432 case 'F':
6433 patch_script_path = optarg;
6434 break;
6435 case 'R':
6436 can_recurse = 1;
6437 break;
6438 default:
6439 usage_revert();
6440 /* NOTREACHED */
6444 argc -= optind;
6445 argv += optind;
6447 #ifndef PROFILE
6448 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6449 "unveil", NULL) == -1)
6450 err(1, "pledge");
6451 #endif
6452 if (argc < 1)
6453 usage_revert();
6454 if (patch_script_path && !pflag)
6455 errx(1, "-F option can only be used together with -p option");
6457 cwd = getcwd(NULL, 0);
6458 if (cwd == NULL) {
6459 error = got_error_from_errno("getcwd");
6460 goto done;
6462 error = got_worktree_open(&worktree, cwd);
6463 if (error) {
6464 if (error->code == GOT_ERR_NOT_WORKTREE)
6465 error = wrap_not_worktree_error(error, "revert", cwd);
6466 goto done;
6469 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6470 NULL);
6471 if (error != NULL)
6472 goto done;
6474 if (patch_script_path) {
6475 patch_script_file = fopen(patch_script_path, "r");
6476 if (patch_script_file == NULL) {
6477 error = got_error_from_errno2("fopen",
6478 patch_script_path);
6479 goto done;
6482 error = apply_unveil(got_repo_get_path(repo), 1,
6483 got_worktree_get_root_path(worktree));
6484 if (error)
6485 goto done;
6487 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6488 if (error)
6489 goto done;
6491 if (!can_recurse) {
6492 char *ondisk_path;
6493 struct stat sb;
6494 TAILQ_FOREACH(pe, &paths, entry) {
6495 if (asprintf(&ondisk_path, "%s/%s",
6496 got_worktree_get_root_path(worktree),
6497 pe->path) == -1) {
6498 error = got_error_from_errno("asprintf");
6499 goto done;
6501 if (lstat(ondisk_path, &sb) == -1) {
6502 if (errno == ENOENT) {
6503 free(ondisk_path);
6504 continue;
6506 error = got_error_from_errno2("lstat",
6507 ondisk_path);
6508 free(ondisk_path);
6509 goto done;
6511 free(ondisk_path);
6512 if (S_ISDIR(sb.st_mode)) {
6513 error = got_error_msg(GOT_ERR_BAD_PATH,
6514 "reverting directories requires -R option");
6515 goto done;
6520 cpa.patch_script_file = patch_script_file;
6521 cpa.action = "revert";
6522 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6523 pflag ? choose_patch : NULL, &cpa, repo);
6524 done:
6525 if (patch_script_file && fclose(patch_script_file) == EOF &&
6526 error == NULL)
6527 error = got_error_from_errno2("fclose", patch_script_path);
6528 if (repo)
6529 got_repo_close(repo);
6530 if (worktree)
6531 got_worktree_close(worktree);
6532 free(path);
6533 free(cwd);
6534 return error;
6537 __dead static void
6538 usage_commit(void)
6540 fprintf(stderr, "usage: %s commit [-m msg] [-S] [path ...]\n",
6541 getprogname());
6542 exit(1);
6545 struct collect_commit_logmsg_arg {
6546 const char *cmdline_log;
6547 const char *editor;
6548 const char *worktree_path;
6549 const char *branch_name;
6550 const char *repo_path;
6551 char *logmsg_path;
6555 static const struct got_error *
6556 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6557 void *arg)
6559 char *initial_content = NULL;
6560 struct got_pathlist_entry *pe;
6561 const struct got_error *err = NULL;
6562 char *template = NULL;
6563 struct collect_commit_logmsg_arg *a = arg;
6564 int initial_content_len;
6565 int fd = -1;
6566 size_t len;
6568 /* if a message was specified on the command line, just use it */
6569 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6570 len = strlen(a->cmdline_log) + 1;
6571 *logmsg = malloc(len + 1);
6572 if (*logmsg == NULL)
6573 return got_error_from_errno("malloc");
6574 strlcpy(*logmsg, a->cmdline_log, len);
6575 return NULL;
6578 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6579 return got_error_from_errno("asprintf");
6581 initial_content_len = asprintf(&initial_content,
6582 "\n# changes to be committed on branch %s:\n",
6583 a->branch_name);
6584 if (initial_content_len == -1)
6585 return got_error_from_errno("asprintf");
6587 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6588 if (err)
6589 goto done;
6591 if (write(fd, initial_content, initial_content_len) == -1) {
6592 err = got_error_from_errno2("write", a->logmsg_path);
6593 goto done;
6596 TAILQ_FOREACH(pe, commitable_paths, entry) {
6597 struct got_commitable *ct = pe->data;
6598 dprintf(fd, "# %c %s\n",
6599 got_commitable_get_status(ct),
6600 got_commitable_get_path(ct));
6603 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
6604 done:
6605 free(initial_content);
6606 free(template);
6608 if (fd != -1 && close(fd) == -1 && err == NULL)
6609 err = got_error_from_errno2("close", a->logmsg_path);
6611 /* Editor is done; we can now apply unveil(2) */
6612 if (err == NULL)
6613 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6614 if (err) {
6615 free(*logmsg);
6616 *logmsg = NULL;
6618 return err;
6621 static const struct got_error *
6622 cmd_commit(int argc, char *argv[])
6624 const struct got_error *error = NULL;
6625 struct got_worktree *worktree = NULL;
6626 struct got_repository *repo = NULL;
6627 char *cwd = NULL, *id_str = NULL;
6628 struct got_object_id *id = NULL;
6629 const char *logmsg = NULL;
6630 struct collect_commit_logmsg_arg cl_arg;
6631 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6632 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6633 int allow_bad_symlinks = 0;
6634 struct got_pathlist_head paths;
6636 TAILQ_INIT(&paths);
6637 cl_arg.logmsg_path = NULL;
6639 while ((ch = getopt(argc, argv, "m:S")) != -1) {
6640 switch (ch) {
6641 case 'm':
6642 logmsg = optarg;
6643 break;
6644 case 'S':
6645 allow_bad_symlinks = 1;
6646 break;
6647 default:
6648 usage_commit();
6649 /* NOTREACHED */
6653 argc -= optind;
6654 argv += optind;
6656 #ifndef PROFILE
6657 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6658 "unveil", NULL) == -1)
6659 err(1, "pledge");
6660 #endif
6661 cwd = getcwd(NULL, 0);
6662 if (cwd == NULL) {
6663 error = got_error_from_errno("getcwd");
6664 goto done;
6666 error = got_worktree_open(&worktree, cwd);
6667 if (error) {
6668 if (error->code == GOT_ERR_NOT_WORKTREE)
6669 error = wrap_not_worktree_error(error, "commit", cwd);
6670 goto done;
6673 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6674 if (error)
6675 goto done;
6676 if (rebase_in_progress) {
6677 error = got_error(GOT_ERR_REBASING);
6678 goto done;
6681 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6682 worktree);
6683 if (error)
6684 goto done;
6686 error = get_gitconfig_path(&gitconfig_path);
6687 if (error)
6688 goto done;
6689 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6690 gitconfig_path);
6691 if (error != NULL)
6692 goto done;
6694 error = get_author(&author, repo, worktree);
6695 if (error)
6696 return error;
6699 * unveil(2) traverses exec(2); if an editor is used we have
6700 * to apply unveil after the log message has been written.
6702 if (logmsg == NULL || strlen(logmsg) == 0)
6703 error = get_editor(&editor);
6704 else
6705 error = apply_unveil(got_repo_get_path(repo), 0,
6706 got_worktree_get_root_path(worktree));
6707 if (error)
6708 goto done;
6710 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6711 if (error)
6712 goto done;
6714 cl_arg.editor = editor;
6715 cl_arg.cmdline_log = logmsg;
6716 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6717 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6718 if (!histedit_in_progress) {
6719 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6720 error = got_error(GOT_ERR_COMMIT_BRANCH);
6721 goto done;
6723 cl_arg.branch_name += 11;
6725 cl_arg.repo_path = got_repo_get_path(repo);
6726 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6727 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
6728 print_status, NULL, repo);
6729 if (error) {
6730 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6731 cl_arg.logmsg_path != NULL)
6732 preserve_logmsg = 1;
6733 goto done;
6736 error = got_object_id_str(&id_str, id);
6737 if (error)
6738 goto done;
6739 printf("Created commit %s\n", id_str);
6740 done:
6741 if (preserve_logmsg) {
6742 fprintf(stderr, "%s: log message preserved in %s\n",
6743 getprogname(), cl_arg.logmsg_path);
6744 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6745 error == NULL)
6746 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6747 free(cl_arg.logmsg_path);
6748 if (repo)
6749 got_repo_close(repo);
6750 if (worktree)
6751 got_worktree_close(worktree);
6752 free(cwd);
6753 free(id_str);
6754 free(gitconfig_path);
6755 free(editor);
6756 free(author);
6757 return error;
6760 __dead static void
6761 usage_cherrypick(void)
6763 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6764 exit(1);
6767 static const struct got_error *
6768 cmd_cherrypick(int argc, char *argv[])
6770 const struct got_error *error = NULL;
6771 struct got_worktree *worktree = NULL;
6772 struct got_repository *repo = NULL;
6773 char *cwd = NULL, *commit_id_str = NULL;
6774 struct got_object_id *commit_id = NULL;
6775 struct got_commit_object *commit = NULL;
6776 struct got_object_qid *pid;
6777 struct got_reference *head_ref = NULL;
6778 int ch;
6779 struct got_update_progress_arg upa;
6781 while ((ch = getopt(argc, argv, "")) != -1) {
6782 switch (ch) {
6783 default:
6784 usage_cherrypick();
6785 /* NOTREACHED */
6789 argc -= optind;
6790 argv += optind;
6792 #ifndef PROFILE
6793 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6794 "unveil", NULL) == -1)
6795 err(1, "pledge");
6796 #endif
6797 if (argc != 1)
6798 usage_cherrypick();
6800 cwd = getcwd(NULL, 0);
6801 if (cwd == NULL) {
6802 error = got_error_from_errno("getcwd");
6803 goto done;
6805 error = got_worktree_open(&worktree, cwd);
6806 if (error) {
6807 if (error->code == GOT_ERR_NOT_WORKTREE)
6808 error = wrap_not_worktree_error(error, "cherrypick",
6809 cwd);
6810 goto done;
6813 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6814 NULL);
6815 if (error != NULL)
6816 goto done;
6818 error = apply_unveil(got_repo_get_path(repo), 0,
6819 got_worktree_get_root_path(worktree));
6820 if (error)
6821 goto done;
6823 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6824 GOT_OBJ_TYPE_COMMIT, repo);
6825 if (error != NULL) {
6826 struct got_reference *ref;
6827 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6828 goto done;
6829 error = got_ref_open(&ref, repo, argv[0], 0);
6830 if (error != NULL)
6831 goto done;
6832 error = got_ref_resolve(&commit_id, repo, ref);
6833 got_ref_close(ref);
6834 if (error != NULL)
6835 goto done;
6837 error = got_object_id_str(&commit_id_str, commit_id);
6838 if (error)
6839 goto done;
6841 error = got_ref_open(&head_ref, repo,
6842 got_worktree_get_head_ref_name(worktree), 0);
6843 if (error != NULL)
6844 goto done;
6846 error = check_same_branch(commit_id, head_ref, NULL, repo);
6847 if (error) {
6848 if (error->code != GOT_ERR_ANCESTRY)
6849 goto done;
6850 error = NULL;
6851 } else {
6852 error = got_error(GOT_ERR_SAME_BRANCH);
6853 goto done;
6856 error = got_object_open_as_commit(&commit, repo, commit_id);
6857 if (error)
6858 goto done;
6859 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6860 memset(&upa, 0, sizeof(upa));
6861 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
6862 commit_id, repo, update_progress, &upa, check_cancelled,
6863 NULL);
6864 if (error != NULL)
6865 goto done;
6867 if (upa.did_something)
6868 printf("Merged commit %s\n", commit_id_str);
6869 print_update_progress_stats(&upa);
6870 done:
6871 if (commit)
6872 got_object_commit_close(commit);
6873 free(commit_id_str);
6874 if (head_ref)
6875 got_ref_close(head_ref);
6876 if (worktree)
6877 got_worktree_close(worktree);
6878 if (repo)
6879 got_repo_close(repo);
6880 return error;
6883 __dead static void
6884 usage_backout(void)
6886 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
6887 exit(1);
6890 static const struct got_error *
6891 cmd_backout(int argc, char *argv[])
6893 const struct got_error *error = NULL;
6894 struct got_worktree *worktree = NULL;
6895 struct got_repository *repo = NULL;
6896 char *cwd = NULL, *commit_id_str = NULL;
6897 struct got_object_id *commit_id = NULL;
6898 struct got_commit_object *commit = NULL;
6899 struct got_object_qid *pid;
6900 struct got_reference *head_ref = NULL;
6901 int ch;
6902 struct got_update_progress_arg upa;
6904 while ((ch = getopt(argc, argv, "")) != -1) {
6905 switch (ch) {
6906 default:
6907 usage_backout();
6908 /* NOTREACHED */
6912 argc -= optind;
6913 argv += optind;
6915 #ifndef PROFILE
6916 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6917 "unveil", NULL) == -1)
6918 err(1, "pledge");
6919 #endif
6920 if (argc != 1)
6921 usage_backout();
6923 cwd = getcwd(NULL, 0);
6924 if (cwd == NULL) {
6925 error = got_error_from_errno("getcwd");
6926 goto done;
6928 error = got_worktree_open(&worktree, cwd);
6929 if (error) {
6930 if (error->code == GOT_ERR_NOT_WORKTREE)
6931 error = wrap_not_worktree_error(error, "backout", cwd);
6932 goto done;
6935 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6936 NULL);
6937 if (error != NULL)
6938 goto done;
6940 error = apply_unveil(got_repo_get_path(repo), 0,
6941 got_worktree_get_root_path(worktree));
6942 if (error)
6943 goto done;
6945 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6946 GOT_OBJ_TYPE_COMMIT, repo);
6947 if (error != NULL) {
6948 struct got_reference *ref;
6949 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6950 goto done;
6951 error = got_ref_open(&ref, repo, argv[0], 0);
6952 if (error != NULL)
6953 goto done;
6954 error = got_ref_resolve(&commit_id, repo, ref);
6955 got_ref_close(ref);
6956 if (error != NULL)
6957 goto done;
6959 error = got_object_id_str(&commit_id_str, commit_id);
6960 if (error)
6961 goto done;
6963 error = got_ref_open(&head_ref, repo,
6964 got_worktree_get_head_ref_name(worktree), 0);
6965 if (error != NULL)
6966 goto done;
6968 error = check_same_branch(commit_id, head_ref, NULL, repo);
6969 if (error)
6970 goto done;
6972 error = got_object_open_as_commit(&commit, repo, commit_id);
6973 if (error)
6974 goto done;
6975 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6976 if (pid == NULL) {
6977 error = got_error(GOT_ERR_ROOT_COMMIT);
6978 goto done;
6981 memset(&upa, 0, sizeof(upa));
6982 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
6983 update_progress, &upa, check_cancelled, NULL);
6984 if (error != NULL)
6985 goto done;
6987 if (upa.did_something)
6988 printf("Backed out commit %s\n", commit_id_str);
6989 print_update_progress_stats(&upa);
6990 done:
6991 if (commit)
6992 got_object_commit_close(commit);
6993 free(commit_id_str);
6994 if (head_ref)
6995 got_ref_close(head_ref);
6996 if (worktree)
6997 got_worktree_close(worktree);
6998 if (repo)
6999 got_repo_close(repo);
7000 return error;
7003 __dead static void
7004 usage_rebase(void)
7006 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
7007 getprogname());
7008 exit(1);
7011 void
7012 trim_logmsg(char *logmsg, int limit)
7014 char *nl;
7015 size_t len;
7017 len = strlen(logmsg);
7018 if (len > limit)
7019 len = limit;
7020 logmsg[len] = '\0';
7021 nl = strchr(logmsg, '\n');
7022 if (nl)
7023 *nl = '\0';
7026 static const struct got_error *
7027 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
7029 const struct got_error *err;
7030 char *logmsg0 = NULL;
7031 const char *s;
7033 err = got_object_commit_get_logmsg(&logmsg0, commit);
7034 if (err)
7035 return err;
7037 s = logmsg0;
7038 while (isspace((unsigned char)s[0]))
7039 s++;
7041 *logmsg = strdup(s);
7042 if (*logmsg == NULL) {
7043 err = got_error_from_errno("strdup");
7044 goto done;
7047 trim_logmsg(*logmsg, limit);
7048 done:
7049 free(logmsg0);
7050 return err;
7053 static const struct got_error *
7054 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
7056 const struct got_error *err;
7057 struct got_commit_object *commit = NULL;
7058 char *id_str = NULL, *logmsg = NULL;
7060 err = got_object_open_as_commit(&commit, repo, id);
7061 if (err)
7062 return err;
7064 err = got_object_id_str(&id_str, id);
7065 if (err)
7066 goto done;
7068 id_str[12] = '\0';
7070 err = get_short_logmsg(&logmsg, 42, commit);
7071 if (err)
7072 goto done;
7074 printf("%s -> merge conflict: %s\n", id_str, logmsg);
7075 done:
7076 free(id_str);
7077 got_object_commit_close(commit);
7078 free(logmsg);
7079 return err;
7082 static const struct got_error *
7083 show_rebase_progress(struct got_commit_object *commit,
7084 struct got_object_id *old_id, struct got_object_id *new_id)
7086 const struct got_error *err;
7087 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7089 err = got_object_id_str(&old_id_str, old_id);
7090 if (err)
7091 goto done;
7093 if (new_id) {
7094 err = got_object_id_str(&new_id_str, new_id);
7095 if (err)
7096 goto done;
7099 old_id_str[12] = '\0';
7100 if (new_id_str)
7101 new_id_str[12] = '\0';
7103 err = get_short_logmsg(&logmsg, 42, commit);
7104 if (err)
7105 goto done;
7107 printf("%s -> %s: %s\n", old_id_str,
7108 new_id_str ? new_id_str : "no-op change", logmsg);
7109 done:
7110 free(old_id_str);
7111 free(new_id_str);
7112 free(logmsg);
7113 return err;
7116 static const struct got_error *
7117 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
7118 struct got_reference *branch, struct got_reference *new_base_branch,
7119 struct got_reference *tmp_branch, struct got_repository *repo)
7121 printf("Switching work tree to %s\n", got_ref_get_name(branch));
7122 return got_worktree_rebase_complete(worktree, fileindex,
7123 new_base_branch, tmp_branch, branch, repo);
7126 static const struct got_error *
7127 rebase_commit(struct got_pathlist_head *merged_paths,
7128 struct got_worktree *worktree, struct got_fileindex *fileindex,
7129 struct got_reference *tmp_branch,
7130 struct got_object_id *commit_id, struct got_repository *repo)
7132 const struct got_error *error;
7133 struct got_commit_object *commit;
7134 struct got_object_id *new_commit_id;
7136 error = got_object_open_as_commit(&commit, repo, commit_id);
7137 if (error)
7138 return error;
7140 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
7141 worktree, fileindex, tmp_branch, commit, commit_id, repo);
7142 if (error) {
7143 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
7144 goto done;
7145 error = show_rebase_progress(commit, commit_id, NULL);
7146 } else {
7147 error = show_rebase_progress(commit, commit_id, new_commit_id);
7148 free(new_commit_id);
7150 done:
7151 got_object_commit_close(commit);
7152 return error;
7155 struct check_path_prefix_arg {
7156 const char *path_prefix;
7157 size_t len;
7158 int errcode;
7161 static const struct got_error *
7162 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
7163 struct got_blob_object *blob2, struct got_object_id *id1,
7164 struct got_object_id *id2, const char *path1, const char *path2,
7165 mode_t mode1, mode_t mode2, struct got_repository *repo)
7167 struct check_path_prefix_arg *a = arg;
7169 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
7170 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
7171 return got_error(a->errcode);
7173 return NULL;
7176 static const struct got_error *
7177 check_path_prefix(struct got_object_id *parent_id,
7178 struct got_object_id *commit_id, const char *path_prefix,
7179 int errcode, struct got_repository *repo)
7181 const struct got_error *err;
7182 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7183 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7184 struct check_path_prefix_arg cpp_arg;
7186 if (got_path_is_root_dir(path_prefix))
7187 return NULL;
7189 err = got_object_open_as_commit(&commit, repo, commit_id);
7190 if (err)
7191 goto done;
7193 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7194 if (err)
7195 goto done;
7197 err = got_object_open_as_tree(&tree1, repo,
7198 got_object_commit_get_tree_id(parent_commit));
7199 if (err)
7200 goto done;
7202 err = got_object_open_as_tree(&tree2, repo,
7203 got_object_commit_get_tree_id(commit));
7204 if (err)
7205 goto done;
7207 cpp_arg.path_prefix = path_prefix;
7208 while (cpp_arg.path_prefix[0] == '/')
7209 cpp_arg.path_prefix++;
7210 cpp_arg.len = strlen(cpp_arg.path_prefix);
7211 cpp_arg.errcode = errcode;
7212 err = got_diff_tree(tree1, tree2, "", "", repo,
7213 check_path_prefix_in_diff, &cpp_arg, 0);
7214 done:
7215 if (tree1)
7216 got_object_tree_close(tree1);
7217 if (tree2)
7218 got_object_tree_close(tree2);
7219 if (commit)
7220 got_object_commit_close(commit);
7221 if (parent_commit)
7222 got_object_commit_close(parent_commit);
7223 return err;
7226 static const struct got_error *
7227 collect_commits(struct got_object_id_queue *commits,
7228 struct got_object_id *initial_commit_id,
7229 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7230 const char *path_prefix, int path_prefix_errcode,
7231 struct got_repository *repo)
7233 const struct got_error *err = NULL;
7234 struct got_commit_graph *graph = NULL;
7235 struct got_object_id *parent_id = NULL;
7236 struct got_object_qid *qid;
7237 struct got_object_id *commit_id = initial_commit_id;
7239 err = got_commit_graph_open(&graph, "/", 1);
7240 if (err)
7241 return err;
7243 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7244 check_cancelled, NULL);
7245 if (err)
7246 goto done;
7247 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7248 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7249 check_cancelled, NULL);
7250 if (err) {
7251 if (err->code == GOT_ERR_ITER_COMPLETED) {
7252 err = got_error_msg(GOT_ERR_ANCESTRY,
7253 "ran out of commits to rebase before "
7254 "youngest common ancestor commit has "
7255 "been reached?!?");
7257 goto done;
7258 } else {
7259 err = check_path_prefix(parent_id, commit_id,
7260 path_prefix, path_prefix_errcode, repo);
7261 if (err)
7262 goto done;
7264 err = got_object_qid_alloc(&qid, commit_id);
7265 if (err)
7266 goto done;
7267 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
7268 commit_id = parent_id;
7271 done:
7272 got_commit_graph_close(graph);
7273 return err;
7276 static const struct got_error *
7277 cmd_rebase(int argc, char *argv[])
7279 const struct got_error *error = NULL;
7280 struct got_worktree *worktree = NULL;
7281 struct got_repository *repo = NULL;
7282 struct got_fileindex *fileindex = NULL;
7283 char *cwd = NULL;
7284 struct got_reference *branch = NULL;
7285 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
7286 struct got_object_id *commit_id = NULL, *parent_id = NULL;
7287 struct got_object_id *resume_commit_id = NULL;
7288 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
7289 struct got_commit_object *commit = NULL;
7290 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
7291 int histedit_in_progress = 0;
7292 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7293 struct got_object_id_queue commits;
7294 struct got_pathlist_head merged_paths;
7295 const struct got_object_id_queue *parent_ids;
7296 struct got_object_qid *qid, *pid;
7298 SIMPLEQ_INIT(&commits);
7299 TAILQ_INIT(&merged_paths);
7301 while ((ch = getopt(argc, argv, "ac")) != -1) {
7302 switch (ch) {
7303 case 'a':
7304 abort_rebase = 1;
7305 break;
7306 case 'c':
7307 continue_rebase = 1;
7308 break;
7309 default:
7310 usage_rebase();
7311 /* NOTREACHED */
7315 argc -= optind;
7316 argv += optind;
7318 #ifndef PROFILE
7319 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7320 "unveil", NULL) == -1)
7321 err(1, "pledge");
7322 #endif
7323 if (abort_rebase && continue_rebase)
7324 usage_rebase();
7325 else if (abort_rebase || continue_rebase) {
7326 if (argc != 0)
7327 usage_rebase();
7328 } else if (argc != 1)
7329 usage_rebase();
7331 cwd = getcwd(NULL, 0);
7332 if (cwd == NULL) {
7333 error = got_error_from_errno("getcwd");
7334 goto done;
7336 error = got_worktree_open(&worktree, cwd);
7337 if (error) {
7338 if (error->code == GOT_ERR_NOT_WORKTREE)
7339 error = wrap_not_worktree_error(error, "rebase", cwd);
7340 goto done;
7343 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7344 NULL);
7345 if (error != NULL)
7346 goto done;
7348 error = apply_unveil(got_repo_get_path(repo), 0,
7349 got_worktree_get_root_path(worktree));
7350 if (error)
7351 goto done;
7353 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7354 worktree);
7355 if (error)
7356 goto done;
7357 if (histedit_in_progress) {
7358 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7359 goto done;
7362 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7363 if (error)
7364 goto done;
7366 if (abort_rebase) {
7367 struct got_update_progress_arg upa;
7368 if (!rebase_in_progress) {
7369 error = got_error(GOT_ERR_NOT_REBASING);
7370 goto done;
7372 error = got_worktree_rebase_continue(&resume_commit_id,
7373 &new_base_branch, &tmp_branch, &branch, &fileindex,
7374 worktree, repo);
7375 if (error)
7376 goto done;
7377 printf("Switching work tree to %s\n",
7378 got_ref_get_symref_target(new_base_branch));
7379 memset(&upa, 0, sizeof(upa));
7380 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7381 new_base_branch, update_progress, &upa);
7382 if (error)
7383 goto done;
7384 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7385 print_update_progress_stats(&upa);
7386 goto done; /* nothing else to do */
7389 if (continue_rebase) {
7390 if (!rebase_in_progress) {
7391 error = got_error(GOT_ERR_NOT_REBASING);
7392 goto done;
7394 error = got_worktree_rebase_continue(&resume_commit_id,
7395 &new_base_branch, &tmp_branch, &branch, &fileindex,
7396 worktree, repo);
7397 if (error)
7398 goto done;
7400 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7401 resume_commit_id, repo);
7402 if (error)
7403 goto done;
7405 yca_id = got_object_id_dup(resume_commit_id);
7406 if (yca_id == NULL) {
7407 error = got_error_from_errno("got_object_id_dup");
7408 goto done;
7410 } else {
7411 error = got_ref_open(&branch, repo, argv[0], 0);
7412 if (error != NULL)
7413 goto done;
7416 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7417 if (error)
7418 goto done;
7420 if (!continue_rebase) {
7421 struct got_object_id *base_commit_id;
7423 base_commit_id = got_worktree_get_base_commit_id(worktree);
7424 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7425 base_commit_id, branch_head_commit_id, repo,
7426 check_cancelled, NULL);
7427 if (error)
7428 goto done;
7429 if (yca_id == NULL) {
7430 error = got_error_msg(GOT_ERR_ANCESTRY,
7431 "specified branch shares no common ancestry "
7432 "with work tree's branch");
7433 goto done;
7436 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7437 if (error) {
7438 if (error->code != GOT_ERR_ANCESTRY)
7439 goto done;
7440 error = NULL;
7441 } else {
7442 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7443 "specified branch resolves to a commit which "
7444 "is already contained in work tree's branch");
7445 goto done;
7447 error = got_worktree_rebase_prepare(&new_base_branch,
7448 &tmp_branch, &fileindex, worktree, branch, repo);
7449 if (error)
7450 goto done;
7453 commit_id = branch_head_commit_id;
7454 error = got_object_open_as_commit(&commit, repo, commit_id);
7455 if (error)
7456 goto done;
7458 parent_ids = got_object_commit_get_parent_ids(commit);
7459 pid = SIMPLEQ_FIRST(parent_ids);
7460 if (pid == NULL) {
7461 if (!continue_rebase) {
7462 struct got_update_progress_arg upa;
7463 memset(&upa, 0, sizeof(upa));
7464 error = got_worktree_rebase_abort(worktree, fileindex,
7465 repo, new_base_branch, update_progress, &upa);
7466 if (error)
7467 goto done;
7468 printf("Rebase of %s aborted\n",
7469 got_ref_get_name(branch));
7470 print_update_progress_stats(&upa);
7473 error = got_error(GOT_ERR_EMPTY_REBASE);
7474 goto done;
7476 error = collect_commits(&commits, commit_id, pid->id,
7477 yca_id, got_worktree_get_path_prefix(worktree),
7478 GOT_ERR_REBASE_PATH, repo);
7479 got_object_commit_close(commit);
7480 commit = NULL;
7481 if (error)
7482 goto done;
7484 if (SIMPLEQ_EMPTY(&commits)) {
7485 if (continue_rebase) {
7486 error = rebase_complete(worktree, fileindex,
7487 branch, new_base_branch, tmp_branch, repo);
7488 goto done;
7489 } else {
7490 /* Fast-forward the reference of the branch. */
7491 struct got_object_id *new_head_commit_id;
7492 char *id_str;
7493 error = got_ref_resolve(&new_head_commit_id, repo,
7494 new_base_branch);
7495 if (error)
7496 goto done;
7497 error = got_object_id_str(&id_str, new_head_commit_id);
7498 printf("Forwarding %s to commit %s\n",
7499 got_ref_get_name(branch), id_str);
7500 free(id_str);
7501 error = got_ref_change_ref(branch,
7502 new_head_commit_id);
7503 if (error)
7504 goto done;
7508 pid = NULL;
7509 SIMPLEQ_FOREACH(qid, &commits, entry) {
7510 struct got_update_progress_arg upa;
7512 commit_id = qid->id;
7513 parent_id = pid ? pid->id : yca_id;
7514 pid = qid;
7516 memset(&upa, 0, sizeof(upa));
7517 error = got_worktree_rebase_merge_files(&merged_paths,
7518 worktree, fileindex, parent_id, commit_id, repo,
7519 update_progress, &upa, check_cancelled, NULL);
7520 if (error)
7521 goto done;
7523 print_update_progress_stats(&upa);
7524 if (upa.conflicts > 0)
7525 rebase_status = GOT_STATUS_CONFLICT;
7527 if (rebase_status == GOT_STATUS_CONFLICT) {
7528 error = show_rebase_merge_conflict(qid->id, repo);
7529 if (error)
7530 goto done;
7531 got_worktree_rebase_pathlist_free(&merged_paths);
7532 break;
7535 error = rebase_commit(&merged_paths, worktree, fileindex,
7536 tmp_branch, commit_id, repo);
7537 got_worktree_rebase_pathlist_free(&merged_paths);
7538 if (error)
7539 goto done;
7542 if (rebase_status == GOT_STATUS_CONFLICT) {
7543 error = got_worktree_rebase_postpone(worktree, fileindex);
7544 if (error)
7545 goto done;
7546 error = got_error_msg(GOT_ERR_CONFLICTS,
7547 "conflicts must be resolved before rebasing can continue");
7548 } else
7549 error = rebase_complete(worktree, fileindex, branch,
7550 new_base_branch, tmp_branch, repo);
7551 done:
7552 got_object_id_queue_free(&commits);
7553 free(branch_head_commit_id);
7554 free(resume_commit_id);
7555 free(yca_id);
7556 if (commit)
7557 got_object_commit_close(commit);
7558 if (branch)
7559 got_ref_close(branch);
7560 if (new_base_branch)
7561 got_ref_close(new_base_branch);
7562 if (tmp_branch)
7563 got_ref_close(tmp_branch);
7564 if (worktree)
7565 got_worktree_close(worktree);
7566 if (repo)
7567 got_repo_close(repo);
7568 return error;
7571 __dead static void
7572 usage_histedit(void)
7574 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
7575 getprogname());
7576 exit(1);
7579 #define GOT_HISTEDIT_PICK 'p'
7580 #define GOT_HISTEDIT_EDIT 'e'
7581 #define GOT_HISTEDIT_FOLD 'f'
7582 #define GOT_HISTEDIT_DROP 'd'
7583 #define GOT_HISTEDIT_MESG 'm'
7585 static struct got_histedit_cmd {
7586 unsigned char code;
7587 const char *name;
7588 const char *desc;
7589 } got_histedit_cmds[] = {
7590 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7591 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7592 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7593 "be used" },
7594 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7595 { GOT_HISTEDIT_MESG, "mesg",
7596 "single-line log message for commit above (open editor if empty)" },
7599 struct got_histedit_list_entry {
7600 TAILQ_ENTRY(got_histedit_list_entry) entry;
7601 struct got_object_id *commit_id;
7602 const struct got_histedit_cmd *cmd;
7603 char *logmsg;
7605 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7607 static const struct got_error *
7608 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7609 FILE *f, struct got_repository *repo)
7611 const struct got_error *err = NULL;
7612 char *logmsg = NULL, *id_str = NULL;
7613 struct got_commit_object *commit = NULL;
7614 int n;
7616 err = got_object_open_as_commit(&commit, repo, commit_id);
7617 if (err)
7618 goto done;
7620 err = get_short_logmsg(&logmsg, 34, commit);
7621 if (err)
7622 goto done;
7624 err = got_object_id_str(&id_str, commit_id);
7625 if (err)
7626 goto done;
7628 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7629 if (n < 0)
7630 err = got_ferror(f, GOT_ERR_IO);
7631 done:
7632 if (commit)
7633 got_object_commit_close(commit);
7634 free(id_str);
7635 free(logmsg);
7636 return err;
7639 static const struct got_error *
7640 histedit_write_commit_list(struct got_object_id_queue *commits,
7641 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7643 const struct got_error *err = NULL;
7644 struct got_object_qid *qid;
7646 if (SIMPLEQ_EMPTY(commits))
7647 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7649 SIMPLEQ_FOREACH(qid, commits, entry) {
7650 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7651 f, repo);
7652 if (err)
7653 break;
7654 if (edit_logmsg_only) {
7655 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7656 if (n < 0) {
7657 err = got_ferror(f, GOT_ERR_IO);
7658 break;
7663 return err;
7666 static const struct got_error *
7667 write_cmd_list(FILE *f, const char *branch_name,
7668 struct got_object_id_queue *commits)
7670 const struct got_error *err = NULL;
7671 int n, i;
7672 char *id_str;
7673 struct got_object_qid *qid;
7675 qid = SIMPLEQ_FIRST(commits);
7676 err = got_object_id_str(&id_str, qid->id);
7677 if (err)
7678 return err;
7680 n = fprintf(f,
7681 "# Editing the history of branch '%s' starting at\n"
7682 "# commit %s\n"
7683 "# Commits will be processed in order from top to "
7684 "bottom of this file.\n", branch_name, id_str);
7685 if (n < 0) {
7686 err = got_ferror(f, GOT_ERR_IO);
7687 goto done;
7690 n = fprintf(f, "# Available histedit commands:\n");
7691 if (n < 0) {
7692 err = got_ferror(f, GOT_ERR_IO);
7693 goto done;
7696 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7697 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7698 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7699 cmd->desc);
7700 if (n < 0) {
7701 err = got_ferror(f, GOT_ERR_IO);
7702 break;
7705 done:
7706 free(id_str);
7707 return err;
7710 static const struct got_error *
7711 histedit_syntax_error(int lineno)
7713 static char msg[42];
7714 int ret;
7716 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7717 lineno);
7718 if (ret == -1 || ret >= sizeof(msg))
7719 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7721 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7724 static const struct got_error *
7725 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7726 char *logmsg, struct got_repository *repo)
7728 const struct got_error *err;
7729 struct got_commit_object *folded_commit = NULL;
7730 char *id_str, *folded_logmsg = NULL;
7732 err = got_object_id_str(&id_str, hle->commit_id);
7733 if (err)
7734 return err;
7736 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7737 if (err)
7738 goto done;
7740 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7741 if (err)
7742 goto done;
7743 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7744 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7745 folded_logmsg) == -1) {
7746 err = got_error_from_errno("asprintf");
7748 done:
7749 if (folded_commit)
7750 got_object_commit_close(folded_commit);
7751 free(id_str);
7752 free(folded_logmsg);
7753 return err;
7756 static struct got_histedit_list_entry *
7757 get_folded_commits(struct got_histedit_list_entry *hle)
7759 struct got_histedit_list_entry *prev, *folded = NULL;
7761 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7762 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7763 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7764 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7765 folded = prev;
7766 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7769 return folded;
7772 static const struct got_error *
7773 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7774 struct got_repository *repo)
7776 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7777 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7778 const struct got_error *err = NULL;
7779 struct got_commit_object *commit = NULL;
7780 int logmsg_len;
7781 int fd;
7782 struct got_histedit_list_entry *folded = NULL;
7784 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7785 if (err)
7786 return err;
7788 folded = get_folded_commits(hle);
7789 if (folded) {
7790 while (folded != hle) {
7791 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7792 folded = TAILQ_NEXT(folded, entry);
7793 continue;
7795 err = append_folded_commit_msg(&new_msg, folded,
7796 logmsg, repo);
7797 if (err)
7798 goto done;
7799 free(logmsg);
7800 logmsg = new_msg;
7801 folded = TAILQ_NEXT(folded, entry);
7805 err = got_object_id_str(&id_str, hle->commit_id);
7806 if (err)
7807 goto done;
7808 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7809 if (err)
7810 goto done;
7811 logmsg_len = asprintf(&new_msg,
7812 "%s\n# original log message of commit %s: %s",
7813 logmsg ? logmsg : "", id_str, orig_logmsg);
7814 if (logmsg_len == -1) {
7815 err = got_error_from_errno("asprintf");
7816 goto done;
7818 free(logmsg);
7819 logmsg = new_msg;
7821 err = got_object_id_str(&id_str, hle->commit_id);
7822 if (err)
7823 goto done;
7825 err = got_opentemp_named_fd(&logmsg_path, &fd,
7826 GOT_TMPDIR_STR "/got-logmsg");
7827 if (err)
7828 goto done;
7830 write(fd, logmsg, logmsg_len);
7831 close(fd);
7833 err = get_editor(&editor);
7834 if (err)
7835 goto done;
7837 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
7838 if (err) {
7839 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
7840 goto done;
7841 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
7843 done:
7844 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
7845 err = got_error_from_errno2("unlink", logmsg_path);
7846 free(logmsg_path);
7847 free(logmsg);
7848 free(orig_logmsg);
7849 free(editor);
7850 if (commit)
7851 got_object_commit_close(commit);
7852 return err;
7855 static const struct got_error *
7856 histedit_parse_list(struct got_histedit_list *histedit_cmds,
7857 FILE *f, struct got_repository *repo)
7859 const struct got_error *err = NULL;
7860 char *line = NULL, *p, *end;
7861 size_t size;
7862 ssize_t len;
7863 int lineno = 0, i;
7864 const struct got_histedit_cmd *cmd;
7865 struct got_object_id *commit_id = NULL;
7866 struct got_histedit_list_entry *hle = NULL;
7868 for (;;) {
7869 len = getline(&line, &size, f);
7870 if (len == -1) {
7871 const struct got_error *getline_err;
7872 if (feof(f))
7873 break;
7874 getline_err = got_error_from_errno("getline");
7875 err = got_ferror(f, getline_err->code);
7876 break;
7878 lineno++;
7879 p = line;
7880 while (isspace((unsigned char)p[0]))
7881 p++;
7882 if (p[0] == '#' || p[0] == '\0') {
7883 free(line);
7884 line = NULL;
7885 continue;
7887 cmd = NULL;
7888 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7889 cmd = &got_histedit_cmds[i];
7890 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
7891 isspace((unsigned char)p[strlen(cmd->name)])) {
7892 p += strlen(cmd->name);
7893 break;
7895 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
7896 p++;
7897 break;
7900 if (i == nitems(got_histedit_cmds)) {
7901 err = histedit_syntax_error(lineno);
7902 break;
7904 while (isspace((unsigned char)p[0]))
7905 p++;
7906 if (cmd->code == GOT_HISTEDIT_MESG) {
7907 if (hle == NULL || hle->logmsg != NULL) {
7908 err = got_error(GOT_ERR_HISTEDIT_CMD);
7909 break;
7911 if (p[0] == '\0') {
7912 err = histedit_edit_logmsg(hle, repo);
7913 if (err)
7914 break;
7915 } else {
7916 hle->logmsg = strdup(p);
7917 if (hle->logmsg == NULL) {
7918 err = got_error_from_errno("strdup");
7919 break;
7922 free(line);
7923 line = NULL;
7924 continue;
7925 } else {
7926 end = p;
7927 while (end[0] && !isspace((unsigned char)end[0]))
7928 end++;
7929 *end = '\0';
7931 err = got_object_resolve_id_str(&commit_id, repo, p);
7932 if (err) {
7933 /* override error code */
7934 err = histedit_syntax_error(lineno);
7935 break;
7938 hle = malloc(sizeof(*hle));
7939 if (hle == NULL) {
7940 err = got_error_from_errno("malloc");
7941 break;
7943 hle->cmd = cmd;
7944 hle->commit_id = commit_id;
7945 hle->logmsg = NULL;
7946 commit_id = NULL;
7947 free(line);
7948 line = NULL;
7949 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
7952 free(line);
7953 free(commit_id);
7954 return err;
7957 static const struct got_error *
7958 histedit_check_script(struct got_histedit_list *histedit_cmds,
7959 struct got_object_id_queue *commits, struct got_repository *repo)
7961 const struct got_error *err = NULL;
7962 struct got_object_qid *qid;
7963 struct got_histedit_list_entry *hle;
7964 static char msg[92];
7965 char *id_str;
7967 if (TAILQ_EMPTY(histedit_cmds))
7968 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
7969 "histedit script contains no commands");
7970 if (SIMPLEQ_EMPTY(commits))
7971 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7973 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7974 struct got_histedit_list_entry *hle2;
7975 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
7976 if (hle == hle2)
7977 continue;
7978 if (got_object_id_cmp(hle->commit_id,
7979 hle2->commit_id) != 0)
7980 continue;
7981 err = got_object_id_str(&id_str, hle->commit_id);
7982 if (err)
7983 return err;
7984 snprintf(msg, sizeof(msg), "commit %s is listed "
7985 "more than once in histedit script", id_str);
7986 free(id_str);
7987 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7991 SIMPLEQ_FOREACH(qid, commits, entry) {
7992 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7993 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
7994 break;
7996 if (hle == NULL) {
7997 err = got_object_id_str(&id_str, qid->id);
7998 if (err)
7999 return err;
8000 snprintf(msg, sizeof(msg),
8001 "commit %s missing from histedit script", id_str);
8002 free(id_str);
8003 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8007 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
8008 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
8009 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
8010 "last commit in histedit script cannot be folded");
8012 return NULL;
8015 static const struct got_error *
8016 histedit_run_editor(struct got_histedit_list *histedit_cmds,
8017 const char *path, struct got_object_id_queue *commits,
8018 struct got_repository *repo)
8020 const struct got_error *err = NULL;
8021 char *editor;
8022 FILE *f = NULL;
8024 err = get_editor(&editor);
8025 if (err)
8026 return err;
8028 if (spawn_editor(editor, path) == -1) {
8029 err = got_error_from_errno("failed spawning editor");
8030 goto done;
8033 f = fopen(path, "r");
8034 if (f == NULL) {
8035 err = got_error_from_errno("fopen");
8036 goto done;
8038 err = histedit_parse_list(histedit_cmds, f, repo);
8039 if (err)
8040 goto done;
8042 err = histedit_check_script(histedit_cmds, commits, repo);
8043 done:
8044 if (f && fclose(f) != 0 && err == NULL)
8045 err = got_error_from_errno("fclose");
8046 free(editor);
8047 return err;
8050 static const struct got_error *
8051 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
8052 struct got_object_id_queue *, const char *, const char *,
8053 struct got_repository *);
8055 static const struct got_error *
8056 histedit_edit_script(struct got_histedit_list *histedit_cmds,
8057 struct got_object_id_queue *commits, const char *branch_name,
8058 int edit_logmsg_only, struct got_repository *repo)
8060 const struct got_error *err;
8061 FILE *f = NULL;
8062 char *path = NULL;
8064 err = got_opentemp_named(&path, &f, "got-histedit");
8065 if (err)
8066 return err;
8068 err = write_cmd_list(f, branch_name, commits);
8069 if (err)
8070 goto done;
8072 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
8073 if (err)
8074 goto done;
8076 if (edit_logmsg_only) {
8077 rewind(f);
8078 err = histedit_parse_list(histedit_cmds, f, repo);
8079 } else {
8080 if (fclose(f) != 0) {
8081 err = got_error_from_errno("fclose");
8082 goto done;
8084 f = NULL;
8085 err = histedit_run_editor(histedit_cmds, path, commits, repo);
8086 if (err) {
8087 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8088 err->code != GOT_ERR_HISTEDIT_CMD)
8089 goto done;
8090 err = histedit_edit_list_retry(histedit_cmds, err,
8091 commits, path, branch_name, repo);
8094 done:
8095 if (f && fclose(f) != 0 && err == NULL)
8096 err = got_error_from_errno("fclose");
8097 if (path && unlink(path) != 0 && err == NULL)
8098 err = got_error_from_errno2("unlink", path);
8099 free(path);
8100 return err;
8103 static const struct got_error *
8104 histedit_save_list(struct got_histedit_list *histedit_cmds,
8105 struct got_worktree *worktree, struct got_repository *repo)
8107 const struct got_error *err = NULL;
8108 char *path = NULL;
8109 FILE *f = NULL;
8110 struct got_histedit_list_entry *hle;
8111 struct got_commit_object *commit = NULL;
8113 err = got_worktree_get_histedit_script_path(&path, worktree);
8114 if (err)
8115 return err;
8117 f = fopen(path, "w");
8118 if (f == NULL) {
8119 err = got_error_from_errno2("fopen", path);
8120 goto done;
8122 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8123 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
8124 repo);
8125 if (err)
8126 break;
8128 if (hle->logmsg) {
8129 int n = fprintf(f, "%c %s\n",
8130 GOT_HISTEDIT_MESG, hle->logmsg);
8131 if (n < 0) {
8132 err = got_ferror(f, GOT_ERR_IO);
8133 break;
8137 done:
8138 if (f && fclose(f) != 0 && err == NULL)
8139 err = got_error_from_errno("fclose");
8140 free(path);
8141 if (commit)
8142 got_object_commit_close(commit);
8143 return err;
8146 void
8147 histedit_free_list(struct got_histedit_list *histedit_cmds)
8149 struct got_histedit_list_entry *hle;
8151 while ((hle = TAILQ_FIRST(histedit_cmds))) {
8152 TAILQ_REMOVE(histedit_cmds, hle, entry);
8153 free(hle);
8157 static const struct got_error *
8158 histedit_load_list(struct got_histedit_list *histedit_cmds,
8159 const char *path, struct got_repository *repo)
8161 const struct got_error *err = NULL;
8162 FILE *f = NULL;
8164 f = fopen(path, "r");
8165 if (f == NULL) {
8166 err = got_error_from_errno2("fopen", path);
8167 goto done;
8170 err = histedit_parse_list(histedit_cmds, f, repo);
8171 done:
8172 if (f && fclose(f) != 0 && err == NULL)
8173 err = got_error_from_errno("fclose");
8174 return err;
8177 static const struct got_error *
8178 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
8179 const struct got_error *edit_err, struct got_object_id_queue *commits,
8180 const char *path, const char *branch_name, struct got_repository *repo)
8182 const struct got_error *err = NULL, *prev_err = edit_err;
8183 int resp = ' ';
8185 while (resp != 'c' && resp != 'r' && resp != 'a') {
8186 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
8187 "or (a)bort: ", getprogname(), prev_err->msg);
8188 resp = getchar();
8189 if (resp == '\n')
8190 resp = getchar();
8191 if (resp == 'c') {
8192 histedit_free_list(histedit_cmds);
8193 err = histedit_run_editor(histedit_cmds, path, commits,
8194 repo);
8195 if (err) {
8196 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8197 err->code != GOT_ERR_HISTEDIT_CMD)
8198 break;
8199 prev_err = err;
8200 resp = ' ';
8201 continue;
8203 break;
8204 } else if (resp == 'r') {
8205 histedit_free_list(histedit_cmds);
8206 err = histedit_edit_script(histedit_cmds,
8207 commits, branch_name, 0, repo);
8208 if (err) {
8209 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8210 err->code != GOT_ERR_HISTEDIT_CMD)
8211 break;
8212 prev_err = err;
8213 resp = ' ';
8214 continue;
8216 break;
8217 } else if (resp == 'a') {
8218 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
8219 break;
8220 } else
8221 printf("invalid response '%c'\n", resp);
8224 return err;
8227 static const struct got_error *
8228 histedit_complete(struct got_worktree *worktree,
8229 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
8230 struct got_reference *branch, struct got_repository *repo)
8232 printf("Switching work tree to %s\n",
8233 got_ref_get_symref_target(branch));
8234 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
8235 branch, repo);
8238 static const struct got_error *
8239 show_histedit_progress(struct got_commit_object *commit,
8240 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
8242 const struct got_error *err;
8243 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8245 err = got_object_id_str(&old_id_str, hle->commit_id);
8246 if (err)
8247 goto done;
8249 if (new_id) {
8250 err = got_object_id_str(&new_id_str, new_id);
8251 if (err)
8252 goto done;
8255 old_id_str[12] = '\0';
8256 if (new_id_str)
8257 new_id_str[12] = '\0';
8259 if (hle->logmsg) {
8260 logmsg = strdup(hle->logmsg);
8261 if (logmsg == NULL) {
8262 err = got_error_from_errno("strdup");
8263 goto done;
8265 trim_logmsg(logmsg, 42);
8266 } else {
8267 err = get_short_logmsg(&logmsg, 42, commit);
8268 if (err)
8269 goto done;
8272 switch (hle->cmd->code) {
8273 case GOT_HISTEDIT_PICK:
8274 case GOT_HISTEDIT_EDIT:
8275 printf("%s -> %s: %s\n", old_id_str,
8276 new_id_str ? new_id_str : "no-op change", logmsg);
8277 break;
8278 case GOT_HISTEDIT_DROP:
8279 case GOT_HISTEDIT_FOLD:
8280 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
8281 logmsg);
8282 break;
8283 default:
8284 break;
8286 done:
8287 free(old_id_str);
8288 free(new_id_str);
8289 return err;
8292 static const struct got_error *
8293 histedit_commit(struct got_pathlist_head *merged_paths,
8294 struct got_worktree *worktree, struct got_fileindex *fileindex,
8295 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
8296 struct got_repository *repo)
8298 const struct got_error *err;
8299 struct got_commit_object *commit;
8300 struct got_object_id *new_commit_id;
8302 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
8303 && hle->logmsg == NULL) {
8304 err = histedit_edit_logmsg(hle, repo);
8305 if (err)
8306 return err;
8309 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8310 if (err)
8311 return err;
8313 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
8314 worktree, fileindex, tmp_branch, commit, hle->commit_id,
8315 hle->logmsg, repo);
8316 if (err) {
8317 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
8318 goto done;
8319 err = show_histedit_progress(commit, hle, NULL);
8320 } else {
8321 err = show_histedit_progress(commit, hle, new_commit_id);
8322 free(new_commit_id);
8324 done:
8325 got_object_commit_close(commit);
8326 return err;
8329 static const struct got_error *
8330 histedit_skip_commit(struct got_histedit_list_entry *hle,
8331 struct got_worktree *worktree, struct got_repository *repo)
8333 const struct got_error *error;
8334 struct got_commit_object *commit;
8336 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
8337 repo);
8338 if (error)
8339 return error;
8341 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
8342 if (error)
8343 return error;
8345 error = show_histedit_progress(commit, hle, NULL);
8346 got_object_commit_close(commit);
8347 return error;
8350 static const struct got_error *
8351 check_local_changes(void *arg, unsigned char status,
8352 unsigned char staged_status, const char *path,
8353 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8354 struct got_object_id *commit_id, int dirfd, const char *de_name)
8356 int *have_local_changes = arg;
8358 switch (status) {
8359 case GOT_STATUS_ADD:
8360 case GOT_STATUS_DELETE:
8361 case GOT_STATUS_MODIFY:
8362 case GOT_STATUS_CONFLICT:
8363 *have_local_changes = 1;
8364 return got_error(GOT_ERR_CANCELLED);
8365 default:
8366 break;
8369 switch (staged_status) {
8370 case GOT_STATUS_ADD:
8371 case GOT_STATUS_DELETE:
8372 case GOT_STATUS_MODIFY:
8373 *have_local_changes = 1;
8374 return got_error(GOT_ERR_CANCELLED);
8375 default:
8376 break;
8379 return NULL;
8382 static const struct got_error *
8383 cmd_histedit(int argc, char *argv[])
8385 const struct got_error *error = NULL;
8386 struct got_worktree *worktree = NULL;
8387 struct got_fileindex *fileindex = NULL;
8388 struct got_repository *repo = NULL;
8389 char *cwd = NULL;
8390 struct got_reference *branch = NULL;
8391 struct got_reference *tmp_branch = NULL;
8392 struct got_object_id *resume_commit_id = NULL;
8393 struct got_object_id *base_commit_id = NULL;
8394 struct got_object_id *head_commit_id = NULL;
8395 struct got_commit_object *commit = NULL;
8396 int ch, rebase_in_progress = 0;
8397 struct got_update_progress_arg upa;
8398 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8399 int edit_logmsg_only = 0;
8400 const char *edit_script_path = NULL;
8401 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8402 struct got_object_id_queue commits;
8403 struct got_pathlist_head merged_paths;
8404 const struct got_object_id_queue *parent_ids;
8405 struct got_object_qid *pid;
8406 struct got_histedit_list histedit_cmds;
8407 struct got_histedit_list_entry *hle;
8409 SIMPLEQ_INIT(&commits);
8410 TAILQ_INIT(&histedit_cmds);
8411 TAILQ_INIT(&merged_paths);
8412 memset(&upa, 0, sizeof(upa));
8414 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
8415 switch (ch) {
8416 case 'a':
8417 abort_edit = 1;
8418 break;
8419 case 'c':
8420 continue_edit = 1;
8421 break;
8422 case 'F':
8423 edit_script_path = optarg;
8424 break;
8425 case 'm':
8426 edit_logmsg_only = 1;
8427 break;
8428 default:
8429 usage_histedit();
8430 /* NOTREACHED */
8434 argc -= optind;
8435 argv += optind;
8437 #ifndef PROFILE
8438 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8439 "unveil", NULL) == -1)
8440 err(1, "pledge");
8441 #endif
8442 if (abort_edit && continue_edit)
8443 errx(1, "histedit's -a and -c options are mutually exclusive");
8444 if (edit_script_path && edit_logmsg_only)
8445 errx(1, "histedit's -F and -m options are mutually exclusive");
8446 if (abort_edit && edit_logmsg_only)
8447 errx(1, "histedit's -a and -m options are mutually exclusive");
8448 if (continue_edit && edit_logmsg_only)
8449 errx(1, "histedit's -c and -m options are mutually exclusive");
8450 if (argc != 0)
8451 usage_histedit();
8454 * This command cannot apply unveil(2) in all cases because the
8455 * user may choose to run an editor to edit the histedit script
8456 * and to edit individual commit log messages.
8457 * unveil(2) traverses exec(2); if an editor is used we have to
8458 * apply unveil after edit script and log messages have been written.
8459 * XXX TODO: Make use of unveil(2) where possible.
8462 cwd = getcwd(NULL, 0);
8463 if (cwd == NULL) {
8464 error = got_error_from_errno("getcwd");
8465 goto done;
8467 error = got_worktree_open(&worktree, cwd);
8468 if (error) {
8469 if (error->code == GOT_ERR_NOT_WORKTREE)
8470 error = wrap_not_worktree_error(error, "histedit", cwd);
8471 goto done;
8474 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8475 NULL);
8476 if (error != NULL)
8477 goto done;
8479 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8480 if (error)
8481 goto done;
8482 if (rebase_in_progress) {
8483 error = got_error(GOT_ERR_REBASING);
8484 goto done;
8487 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8488 if (error)
8489 goto done;
8491 if (edit_in_progress && edit_logmsg_only) {
8492 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8493 "histedit operation is in progress in this "
8494 "work tree and must be continued or aborted "
8495 "before the -m option can be used");
8496 goto done;
8499 if (edit_in_progress && abort_edit) {
8500 error = got_worktree_histedit_continue(&resume_commit_id,
8501 &tmp_branch, &branch, &base_commit_id, &fileindex,
8502 worktree, repo);
8503 if (error)
8504 goto done;
8505 printf("Switching work tree to %s\n",
8506 got_ref_get_symref_target(branch));
8507 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8508 branch, base_commit_id, update_progress, &upa);
8509 if (error)
8510 goto done;
8511 printf("Histedit of %s aborted\n",
8512 got_ref_get_symref_target(branch));
8513 print_update_progress_stats(&upa);
8514 goto done; /* nothing else to do */
8515 } else if (abort_edit) {
8516 error = got_error(GOT_ERR_NOT_HISTEDIT);
8517 goto done;
8520 if (continue_edit) {
8521 char *path;
8523 if (!edit_in_progress) {
8524 error = got_error(GOT_ERR_NOT_HISTEDIT);
8525 goto done;
8528 error = got_worktree_get_histedit_script_path(&path, worktree);
8529 if (error)
8530 goto done;
8532 error = histedit_load_list(&histedit_cmds, path, repo);
8533 free(path);
8534 if (error)
8535 goto done;
8537 error = got_worktree_histedit_continue(&resume_commit_id,
8538 &tmp_branch, &branch, &base_commit_id, &fileindex,
8539 worktree, repo);
8540 if (error)
8541 goto done;
8543 error = got_ref_resolve(&head_commit_id, repo, branch);
8544 if (error)
8545 goto done;
8547 error = got_object_open_as_commit(&commit, repo,
8548 head_commit_id);
8549 if (error)
8550 goto done;
8551 parent_ids = got_object_commit_get_parent_ids(commit);
8552 pid = SIMPLEQ_FIRST(parent_ids);
8553 if (pid == NULL) {
8554 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8555 goto done;
8557 error = collect_commits(&commits, head_commit_id, pid->id,
8558 base_commit_id, got_worktree_get_path_prefix(worktree),
8559 GOT_ERR_HISTEDIT_PATH, repo);
8560 got_object_commit_close(commit);
8561 commit = NULL;
8562 if (error)
8563 goto done;
8564 } else {
8565 if (edit_in_progress) {
8566 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8567 goto done;
8570 error = got_ref_open(&branch, repo,
8571 got_worktree_get_head_ref_name(worktree), 0);
8572 if (error != NULL)
8573 goto done;
8575 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8576 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8577 "will not edit commit history of a branch outside "
8578 "the \"refs/heads/\" reference namespace");
8579 goto done;
8582 error = got_ref_resolve(&head_commit_id, repo, branch);
8583 got_ref_close(branch);
8584 branch = NULL;
8585 if (error)
8586 goto done;
8588 error = got_object_open_as_commit(&commit, repo,
8589 head_commit_id);
8590 if (error)
8591 goto done;
8592 parent_ids = got_object_commit_get_parent_ids(commit);
8593 pid = SIMPLEQ_FIRST(parent_ids);
8594 if (pid == NULL) {
8595 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8596 goto done;
8598 error = collect_commits(&commits, head_commit_id, pid->id,
8599 got_worktree_get_base_commit_id(worktree),
8600 got_worktree_get_path_prefix(worktree),
8601 GOT_ERR_HISTEDIT_PATH, repo);
8602 got_object_commit_close(commit);
8603 commit = NULL;
8604 if (error)
8605 goto done;
8607 if (SIMPLEQ_EMPTY(&commits)) {
8608 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8609 goto done;
8612 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8613 &base_commit_id, &fileindex, worktree, repo);
8614 if (error)
8615 goto done;
8617 if (edit_script_path) {
8618 error = histedit_load_list(&histedit_cmds,
8619 edit_script_path, repo);
8620 if (error) {
8621 got_worktree_histedit_abort(worktree, fileindex,
8622 repo, branch, base_commit_id,
8623 update_progress, &upa);
8624 print_update_progress_stats(&upa);
8625 goto done;
8627 } else {
8628 const char *branch_name;
8629 branch_name = got_ref_get_symref_target(branch);
8630 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8631 branch_name += 11;
8632 error = histedit_edit_script(&histedit_cmds, &commits,
8633 branch_name, edit_logmsg_only, repo);
8634 if (error) {
8635 got_worktree_histedit_abort(worktree, fileindex,
8636 repo, branch, base_commit_id,
8637 update_progress, &upa);
8638 print_update_progress_stats(&upa);
8639 goto done;
8644 error = histedit_save_list(&histedit_cmds, worktree,
8645 repo);
8646 if (error) {
8647 got_worktree_histedit_abort(worktree, fileindex,
8648 repo, branch, base_commit_id,
8649 update_progress, &upa);
8650 print_update_progress_stats(&upa);
8651 goto done;
8656 error = histedit_check_script(&histedit_cmds, &commits, repo);
8657 if (error)
8658 goto done;
8660 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8661 if (resume_commit_id) {
8662 if (got_object_id_cmp(hle->commit_id,
8663 resume_commit_id) != 0)
8664 continue;
8666 resume_commit_id = NULL;
8667 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8668 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8669 error = histedit_skip_commit(hle, worktree,
8670 repo);
8671 if (error)
8672 goto done;
8673 } else {
8674 struct got_pathlist_head paths;
8675 int have_changes = 0;
8677 TAILQ_INIT(&paths);
8678 error = got_pathlist_append(&paths, "", NULL);
8679 if (error)
8680 goto done;
8681 error = got_worktree_status(worktree, &paths,
8682 repo, check_local_changes, &have_changes,
8683 check_cancelled, NULL);
8684 got_pathlist_free(&paths);
8685 if (error) {
8686 if (error->code != GOT_ERR_CANCELLED)
8687 goto done;
8688 if (sigint_received || sigpipe_received)
8689 goto done;
8691 if (have_changes) {
8692 error = histedit_commit(NULL, worktree,
8693 fileindex, tmp_branch, hle, repo);
8694 if (error)
8695 goto done;
8696 } else {
8697 error = got_object_open_as_commit(
8698 &commit, repo, hle->commit_id);
8699 if (error)
8700 goto done;
8701 error = show_histedit_progress(commit,
8702 hle, NULL);
8703 got_object_commit_close(commit);
8704 commit = NULL;
8705 if (error)
8706 goto done;
8709 continue;
8712 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8713 error = histedit_skip_commit(hle, worktree, repo);
8714 if (error)
8715 goto done;
8716 continue;
8719 error = got_object_open_as_commit(&commit, repo,
8720 hle->commit_id);
8721 if (error)
8722 goto done;
8723 parent_ids = got_object_commit_get_parent_ids(commit);
8724 pid = SIMPLEQ_FIRST(parent_ids);
8726 error = got_worktree_histedit_merge_files(&merged_paths,
8727 worktree, fileindex, pid->id, hle->commit_id, repo,
8728 update_progress, &upa, check_cancelled, NULL);
8729 if (error)
8730 goto done;
8731 got_object_commit_close(commit);
8732 commit = NULL;
8734 print_update_progress_stats(&upa);
8735 if (upa.conflicts > 0)
8736 rebase_status = GOT_STATUS_CONFLICT;
8738 if (rebase_status == GOT_STATUS_CONFLICT) {
8739 error = show_rebase_merge_conflict(hle->commit_id,
8740 repo);
8741 if (error)
8742 goto done;
8743 got_worktree_rebase_pathlist_free(&merged_paths);
8744 break;
8747 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8748 char *id_str;
8749 error = got_object_id_str(&id_str, hle->commit_id);
8750 if (error)
8751 goto done;
8752 printf("Stopping histedit for amending commit %s\n",
8753 id_str);
8754 free(id_str);
8755 got_worktree_rebase_pathlist_free(&merged_paths);
8756 error = got_worktree_histedit_postpone(worktree,
8757 fileindex);
8758 goto done;
8761 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8762 error = histedit_skip_commit(hle, worktree, repo);
8763 if (error)
8764 goto done;
8765 continue;
8768 error = histedit_commit(&merged_paths, worktree, fileindex,
8769 tmp_branch, hle, repo);
8770 got_worktree_rebase_pathlist_free(&merged_paths);
8771 if (error)
8772 goto done;
8775 if (rebase_status == GOT_STATUS_CONFLICT) {
8776 error = got_worktree_histedit_postpone(worktree, fileindex);
8777 if (error)
8778 goto done;
8779 error = got_error_msg(GOT_ERR_CONFLICTS,
8780 "conflicts must be resolved before histedit can continue");
8781 } else
8782 error = histedit_complete(worktree, fileindex, tmp_branch,
8783 branch, repo);
8784 done:
8785 got_object_id_queue_free(&commits);
8786 histedit_free_list(&histedit_cmds);
8787 free(head_commit_id);
8788 free(base_commit_id);
8789 free(resume_commit_id);
8790 if (commit)
8791 got_object_commit_close(commit);
8792 if (branch)
8793 got_ref_close(branch);
8794 if (tmp_branch)
8795 got_ref_close(tmp_branch);
8796 if (worktree)
8797 got_worktree_close(worktree);
8798 if (repo)
8799 got_repo_close(repo);
8800 return error;
8803 __dead static void
8804 usage_integrate(void)
8806 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
8807 exit(1);
8810 static const struct got_error *
8811 cmd_integrate(int argc, char *argv[])
8813 const struct got_error *error = NULL;
8814 struct got_repository *repo = NULL;
8815 struct got_worktree *worktree = NULL;
8816 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
8817 const char *branch_arg = NULL;
8818 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
8819 struct got_fileindex *fileindex = NULL;
8820 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
8821 int ch;
8822 struct got_update_progress_arg upa;
8824 while ((ch = getopt(argc, argv, "")) != -1) {
8825 switch (ch) {
8826 default:
8827 usage_integrate();
8828 /* NOTREACHED */
8832 argc -= optind;
8833 argv += optind;
8835 if (argc != 1)
8836 usage_integrate();
8837 branch_arg = argv[0];
8839 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8840 "unveil", NULL) == -1)
8841 err(1, "pledge");
8843 cwd = getcwd(NULL, 0);
8844 if (cwd == NULL) {
8845 error = got_error_from_errno("getcwd");
8846 goto done;
8849 error = got_worktree_open(&worktree, cwd);
8850 if (error) {
8851 if (error->code == GOT_ERR_NOT_WORKTREE)
8852 error = wrap_not_worktree_error(error, "integrate",
8853 cwd);
8854 goto done;
8857 error = check_rebase_or_histedit_in_progress(worktree);
8858 if (error)
8859 goto done;
8861 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8862 NULL);
8863 if (error != NULL)
8864 goto done;
8866 error = apply_unveil(got_repo_get_path(repo), 0,
8867 got_worktree_get_root_path(worktree));
8868 if (error)
8869 goto done;
8871 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
8872 error = got_error_from_errno("asprintf");
8873 goto done;
8876 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
8877 &base_branch_ref, worktree, refname, repo);
8878 if (error)
8879 goto done;
8881 refname = strdup(got_ref_get_name(branch_ref));
8882 if (refname == NULL) {
8883 error = got_error_from_errno("strdup");
8884 got_worktree_integrate_abort(worktree, fileindex, repo,
8885 branch_ref, base_branch_ref);
8886 goto done;
8888 base_refname = strdup(got_ref_get_name(base_branch_ref));
8889 if (base_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;
8896 error = got_ref_resolve(&commit_id, repo, branch_ref);
8897 if (error)
8898 goto done;
8900 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
8901 if (error)
8902 goto done;
8904 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
8905 error = got_error_msg(GOT_ERR_SAME_BRANCH,
8906 "specified branch has already been integrated");
8907 got_worktree_integrate_abort(worktree, fileindex, repo,
8908 branch_ref, base_branch_ref);
8909 goto done;
8912 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
8913 if (error) {
8914 if (error->code == GOT_ERR_ANCESTRY)
8915 error = got_error(GOT_ERR_REBASE_REQUIRED);
8916 got_worktree_integrate_abort(worktree, fileindex, repo,
8917 branch_ref, base_branch_ref);
8918 goto done;
8921 memset(&upa, 0, sizeof(upa));
8922 error = got_worktree_integrate_continue(worktree, fileindex, repo,
8923 branch_ref, base_branch_ref, update_progress, &upa,
8924 check_cancelled, NULL);
8925 if (error)
8926 goto done;
8928 printf("Integrated %s into %s\n", refname, base_refname);
8929 print_update_progress_stats(&upa);
8930 done:
8931 if (repo)
8932 got_repo_close(repo);
8933 if (worktree)
8934 got_worktree_close(worktree);
8935 free(cwd);
8936 free(base_commit_id);
8937 free(commit_id);
8938 free(refname);
8939 free(base_refname);
8940 return error;
8943 __dead static void
8944 usage_stage(void)
8946 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
8947 "[-S] [file-path ...]\n",
8948 getprogname());
8949 exit(1);
8952 static const struct got_error *
8953 print_stage(void *arg, unsigned char status, unsigned char staged_status,
8954 const char *path, struct got_object_id *blob_id,
8955 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
8956 int dirfd, const char *de_name)
8958 const struct got_error *err = NULL;
8959 char *id_str = NULL;
8961 if (staged_status != GOT_STATUS_ADD &&
8962 staged_status != GOT_STATUS_MODIFY &&
8963 staged_status != GOT_STATUS_DELETE)
8964 return NULL;
8966 if (staged_status == GOT_STATUS_ADD ||
8967 staged_status == GOT_STATUS_MODIFY)
8968 err = got_object_id_str(&id_str, staged_blob_id);
8969 else
8970 err = got_object_id_str(&id_str, blob_id);
8971 if (err)
8972 return err;
8974 printf("%s %c %s\n", id_str, staged_status, path);
8975 free(id_str);
8976 return NULL;
8979 static const struct got_error *
8980 cmd_stage(int argc, char *argv[])
8982 const struct got_error *error = NULL;
8983 struct got_repository *repo = NULL;
8984 struct got_worktree *worktree = NULL;
8985 char *cwd = NULL;
8986 struct got_pathlist_head paths;
8987 struct got_pathlist_entry *pe;
8988 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
8989 FILE *patch_script_file = NULL;
8990 const char *patch_script_path = NULL;
8991 struct choose_patch_arg cpa;
8993 TAILQ_INIT(&paths);
8995 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
8996 switch (ch) {
8997 case 'l':
8998 list_stage = 1;
8999 break;
9000 case 'p':
9001 pflag = 1;
9002 break;
9003 case 'F':
9004 patch_script_path = optarg;
9005 break;
9006 case 'S':
9007 allow_bad_symlinks = 1;
9008 break;
9009 default:
9010 usage_stage();
9011 /* NOTREACHED */
9015 argc -= optind;
9016 argv += optind;
9018 #ifndef PROFILE
9019 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9020 "unveil", NULL) == -1)
9021 err(1, "pledge");
9022 #endif
9023 if (list_stage && (pflag || patch_script_path))
9024 errx(1, "-l option cannot be used with other options");
9025 if (patch_script_path && !pflag)
9026 errx(1, "-F option can only be used together with -p option");
9028 cwd = getcwd(NULL, 0);
9029 if (cwd == NULL) {
9030 error = got_error_from_errno("getcwd");
9031 goto done;
9034 error = got_worktree_open(&worktree, cwd);
9035 if (error) {
9036 if (error->code == GOT_ERR_NOT_WORKTREE)
9037 error = wrap_not_worktree_error(error, "stage", cwd);
9038 goto done;
9041 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9042 NULL);
9043 if (error != NULL)
9044 goto done;
9046 if (patch_script_path) {
9047 patch_script_file = fopen(patch_script_path, "r");
9048 if (patch_script_file == NULL) {
9049 error = got_error_from_errno2("fopen",
9050 patch_script_path);
9051 goto done;
9054 error = apply_unveil(got_repo_get_path(repo), 0,
9055 got_worktree_get_root_path(worktree));
9056 if (error)
9057 goto done;
9059 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9060 if (error)
9061 goto done;
9063 if (list_stage)
9064 error = got_worktree_status(worktree, &paths, repo,
9065 print_stage, NULL, check_cancelled, NULL);
9066 else {
9067 cpa.patch_script_file = patch_script_file;
9068 cpa.action = "stage";
9069 error = got_worktree_stage(worktree, &paths,
9070 pflag ? NULL : print_status, NULL,
9071 pflag ? choose_patch : NULL, &cpa,
9072 allow_bad_symlinks, repo);
9074 done:
9075 if (patch_script_file && fclose(patch_script_file) == EOF &&
9076 error == NULL)
9077 error = got_error_from_errno2("fclose", patch_script_path);
9078 if (repo)
9079 got_repo_close(repo);
9080 if (worktree)
9081 got_worktree_close(worktree);
9082 TAILQ_FOREACH(pe, &paths, entry)
9083 free((char *)pe->path);
9084 got_pathlist_free(&paths);
9085 free(cwd);
9086 return error;
9089 __dead static void
9090 usage_unstage(void)
9092 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
9093 "[file-path ...]\n",
9094 getprogname());
9095 exit(1);
9099 static const struct got_error *
9100 cmd_unstage(int argc, char *argv[])
9102 const struct got_error *error = NULL;
9103 struct got_repository *repo = NULL;
9104 struct got_worktree *worktree = NULL;
9105 char *cwd = NULL;
9106 struct got_pathlist_head paths;
9107 struct got_pathlist_entry *pe;
9108 int ch, pflag = 0;
9109 struct got_update_progress_arg upa;
9110 FILE *patch_script_file = NULL;
9111 const char *patch_script_path = NULL;
9112 struct choose_patch_arg cpa;
9114 TAILQ_INIT(&paths);
9116 while ((ch = getopt(argc, argv, "pF:")) != -1) {
9117 switch (ch) {
9118 case 'p':
9119 pflag = 1;
9120 break;
9121 case 'F':
9122 patch_script_path = optarg;
9123 break;
9124 default:
9125 usage_unstage();
9126 /* NOTREACHED */
9130 argc -= optind;
9131 argv += optind;
9133 #ifndef PROFILE
9134 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9135 "unveil", NULL) == -1)
9136 err(1, "pledge");
9137 #endif
9138 if (patch_script_path && !pflag)
9139 errx(1, "-F option can only be used together with -p option");
9141 cwd = getcwd(NULL, 0);
9142 if (cwd == NULL) {
9143 error = got_error_from_errno("getcwd");
9144 goto done;
9147 error = got_worktree_open(&worktree, cwd);
9148 if (error) {
9149 if (error->code == GOT_ERR_NOT_WORKTREE)
9150 error = wrap_not_worktree_error(error, "unstage", cwd);
9151 goto done;
9154 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9155 NULL);
9156 if (error != NULL)
9157 goto done;
9159 if (patch_script_path) {
9160 patch_script_file = fopen(patch_script_path, "r");
9161 if (patch_script_file == NULL) {
9162 error = got_error_from_errno2("fopen",
9163 patch_script_path);
9164 goto done;
9168 error = apply_unveil(got_repo_get_path(repo), 0,
9169 got_worktree_get_root_path(worktree));
9170 if (error)
9171 goto done;
9173 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9174 if (error)
9175 goto done;
9177 cpa.patch_script_file = patch_script_file;
9178 cpa.action = "unstage";
9179 memset(&upa, 0, sizeof(upa));
9180 error = got_worktree_unstage(worktree, &paths, update_progress,
9181 &upa, pflag ? choose_patch : NULL, &cpa, repo);
9182 if (!error)
9183 print_update_progress_stats(&upa);
9184 done:
9185 if (patch_script_file && fclose(patch_script_file) == EOF &&
9186 error == NULL)
9187 error = got_error_from_errno2("fclose", patch_script_path);
9188 if (repo)
9189 got_repo_close(repo);
9190 if (worktree)
9191 got_worktree_close(worktree);
9192 TAILQ_FOREACH(pe, &paths, entry)
9193 free((char *)pe->path);
9194 got_pathlist_free(&paths);
9195 free(cwd);
9196 return error;
9199 __dead static void
9200 usage_cat(void)
9202 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
9203 "arg1 [arg2 ...]\n", getprogname());
9204 exit(1);
9207 static const struct got_error *
9208 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9210 const struct got_error *err;
9211 struct got_blob_object *blob;
9213 err = got_object_open_as_blob(&blob, repo, id, 8192);
9214 if (err)
9215 return err;
9217 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
9218 got_object_blob_close(blob);
9219 return err;
9222 static const struct got_error *
9223 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9225 const struct got_error *err;
9226 struct got_tree_object *tree;
9227 int nentries, i;
9229 err = got_object_open_as_tree(&tree, repo, id);
9230 if (err)
9231 return err;
9233 nentries = got_object_tree_get_nentries(tree);
9234 for (i = 0; i < nentries; i++) {
9235 struct got_tree_entry *te;
9236 char *id_str;
9237 if (sigint_received || sigpipe_received)
9238 break;
9239 te = got_object_tree_get_entry(tree, i);
9240 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
9241 if (err)
9242 break;
9243 fprintf(outfile, "%s %.7o %s\n", id_str,
9244 got_tree_entry_get_mode(te),
9245 got_tree_entry_get_name(te));
9246 free(id_str);
9249 got_object_tree_close(tree);
9250 return err;
9253 static const struct got_error *
9254 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9256 const struct got_error *err;
9257 struct got_commit_object *commit;
9258 const struct got_object_id_queue *parent_ids;
9259 struct got_object_qid *pid;
9260 char *id_str = NULL;
9261 const char *logmsg = NULL;
9263 err = got_object_open_as_commit(&commit, repo, id);
9264 if (err)
9265 return err;
9267 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
9268 if (err)
9269 goto done;
9271 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
9272 parent_ids = got_object_commit_get_parent_ids(commit);
9273 fprintf(outfile, "numparents %d\n",
9274 got_object_commit_get_nparents(commit));
9275 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
9276 char *pid_str;
9277 err = got_object_id_str(&pid_str, pid->id);
9278 if (err)
9279 goto done;
9280 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
9281 free(pid_str);
9283 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
9284 got_object_commit_get_author(commit),
9285 got_object_commit_get_author_time(commit));
9287 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
9288 got_object_commit_get_author(commit),
9289 got_object_commit_get_committer_time(commit));
9291 logmsg = got_object_commit_get_logmsg_raw(commit);
9292 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
9293 fprintf(outfile, "%s", logmsg);
9294 done:
9295 free(id_str);
9296 got_object_commit_close(commit);
9297 return err;
9300 static const struct got_error *
9301 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9303 const struct got_error *err;
9304 struct got_tag_object *tag;
9305 char *id_str = NULL;
9306 const char *tagmsg = NULL;
9308 err = got_object_open_as_tag(&tag, repo, id);
9309 if (err)
9310 return err;
9312 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
9313 if (err)
9314 goto done;
9316 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
9318 switch (got_object_tag_get_object_type(tag)) {
9319 case GOT_OBJ_TYPE_BLOB:
9320 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9321 GOT_OBJ_LABEL_BLOB);
9322 break;
9323 case GOT_OBJ_TYPE_TREE:
9324 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9325 GOT_OBJ_LABEL_TREE);
9326 break;
9327 case GOT_OBJ_TYPE_COMMIT:
9328 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9329 GOT_OBJ_LABEL_COMMIT);
9330 break;
9331 case GOT_OBJ_TYPE_TAG:
9332 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9333 GOT_OBJ_LABEL_TAG);
9334 break;
9335 default:
9336 break;
9339 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
9340 got_object_tag_get_name(tag));
9342 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
9343 got_object_tag_get_tagger(tag),
9344 got_object_tag_get_tagger_time(tag));
9346 tagmsg = got_object_tag_get_message(tag);
9347 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
9348 fprintf(outfile, "%s", tagmsg);
9349 done:
9350 free(id_str);
9351 got_object_tag_close(tag);
9352 return err;
9355 static const struct got_error *
9356 cmd_cat(int argc, char *argv[])
9358 const struct got_error *error;
9359 struct got_repository *repo = NULL;
9360 struct got_worktree *worktree = NULL;
9361 char *cwd = NULL, *repo_path = NULL, *label = NULL;
9362 const char *commit_id_str = NULL;
9363 struct got_object_id *id = NULL, *commit_id = NULL;
9364 int ch, obj_type, i, force_path = 0;
9366 #ifndef PROFILE
9367 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9368 NULL) == -1)
9369 err(1, "pledge");
9370 #endif
9372 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
9373 switch (ch) {
9374 case 'c':
9375 commit_id_str = optarg;
9376 break;
9377 case 'r':
9378 repo_path = realpath(optarg, NULL);
9379 if (repo_path == NULL)
9380 return got_error_from_errno2("realpath",
9381 optarg);
9382 got_path_strip_trailing_slashes(repo_path);
9383 break;
9384 case 'P':
9385 force_path = 1;
9386 break;
9387 default:
9388 usage_cat();
9389 /* NOTREACHED */
9393 argc -= optind;
9394 argv += optind;
9396 cwd = getcwd(NULL, 0);
9397 if (cwd == NULL) {
9398 error = got_error_from_errno("getcwd");
9399 goto done;
9401 error = got_worktree_open(&worktree, cwd);
9402 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9403 goto done;
9404 if (worktree) {
9405 if (repo_path == NULL) {
9406 repo_path = strdup(
9407 got_worktree_get_repo_path(worktree));
9408 if (repo_path == NULL) {
9409 error = got_error_from_errno("strdup");
9410 goto done;
9415 if (repo_path == NULL) {
9416 repo_path = getcwd(NULL, 0);
9417 if (repo_path == NULL)
9418 return got_error_from_errno("getcwd");
9421 error = got_repo_open(&repo, repo_path, NULL);
9422 free(repo_path);
9423 if (error != NULL)
9424 goto done;
9426 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9427 if (error)
9428 goto done;
9430 if (commit_id_str == NULL)
9431 commit_id_str = GOT_REF_HEAD;
9432 error = got_repo_match_object_id(&commit_id, NULL,
9433 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
9434 if (error)
9435 goto done;
9437 for (i = 0; i < argc; i++) {
9438 if (force_path) {
9439 error = got_object_id_by_path(&id, repo, commit_id,
9440 argv[i]);
9441 if (error)
9442 break;
9443 } else {
9444 error = got_repo_match_object_id(&id, &label, argv[i],
9445 GOT_OBJ_TYPE_ANY, 0, repo);
9446 if (error) {
9447 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9448 error->code != GOT_ERR_NOT_REF)
9449 break;
9450 error = got_object_id_by_path(&id, repo,
9451 commit_id, argv[i]);
9452 if (error)
9453 break;
9457 error = got_object_get_type(&obj_type, repo, id);
9458 if (error)
9459 break;
9461 switch (obj_type) {
9462 case GOT_OBJ_TYPE_BLOB:
9463 error = cat_blob(id, repo, stdout);
9464 break;
9465 case GOT_OBJ_TYPE_TREE:
9466 error = cat_tree(id, repo, stdout);
9467 break;
9468 case GOT_OBJ_TYPE_COMMIT:
9469 error = cat_commit(id, repo, stdout);
9470 break;
9471 case GOT_OBJ_TYPE_TAG:
9472 error = cat_tag(id, repo, stdout);
9473 break;
9474 default:
9475 error = got_error(GOT_ERR_OBJ_TYPE);
9476 break;
9478 if (error)
9479 break;
9480 free(label);
9481 label = NULL;
9482 free(id);
9483 id = NULL;
9485 done:
9486 free(label);
9487 free(id);
9488 free(commit_id);
9489 if (worktree)
9490 got_worktree_close(worktree);
9491 if (repo) {
9492 const struct got_error *repo_error;
9493 repo_error = got_repo_close(repo);
9494 if (error == NULL)
9495 error = repo_error;
9497 return error;
9500 __dead static void
9501 usage_info(void)
9503 fprintf(stderr, "usage: %s info [path ...]\n",
9504 getprogname());
9505 exit(1);
9508 static const struct got_error *
9509 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
9510 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9511 struct got_object_id *commit_id)
9513 const struct got_error *err = NULL;
9514 char *id_str = NULL;
9515 char datebuf[128];
9516 struct tm mytm, *tm;
9517 struct got_pathlist_head *paths = arg;
9518 struct got_pathlist_entry *pe;
9521 * Clear error indication from any of the path arguments which
9522 * would cause this file index entry to be displayed.
9524 TAILQ_FOREACH(pe, paths, entry) {
9525 if (got_path_cmp(path, pe->path, strlen(path),
9526 pe->path_len) == 0 ||
9527 got_path_is_child(path, pe->path, pe->path_len))
9528 pe->data = NULL; /* no error */
9531 printf(GOT_COMMIT_SEP_STR);
9532 if (S_ISLNK(mode))
9533 printf("symlink: %s\n", path);
9534 else if (S_ISREG(mode)) {
9535 printf("file: %s\n", path);
9536 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
9537 } else if (S_ISDIR(mode))
9538 printf("directory: %s\n", path);
9539 else
9540 printf("something: %s\n", path);
9542 tm = localtime_r(&mtime, &mytm);
9543 if (tm == NULL)
9544 return NULL;
9545 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) >= sizeof(datebuf))
9546 return got_error(GOT_ERR_NO_SPACE);
9547 printf("timestamp: %s\n", datebuf);
9549 if (blob_id) {
9550 err = got_object_id_str(&id_str, blob_id);
9551 if (err)
9552 return err;
9553 printf("based on blob: %s\n", id_str);
9554 free(id_str);
9557 if (staged_blob_id) {
9558 err = got_object_id_str(&id_str, staged_blob_id);
9559 if (err)
9560 return err;
9561 printf("based on staged blob: %s\n", id_str);
9562 free(id_str);
9565 if (commit_id) {
9566 err = got_object_id_str(&id_str, commit_id);
9567 if (err)
9568 return err;
9569 printf("based on commit: %s\n", id_str);
9570 free(id_str);
9573 return NULL;
9576 static const struct got_error *
9577 cmd_info(int argc, char *argv[])
9579 const struct got_error *error = NULL;
9580 struct got_worktree *worktree = NULL;
9581 char *cwd = NULL, *id_str = NULL;
9582 struct got_pathlist_head paths;
9583 struct got_pathlist_entry *pe;
9584 char *uuidstr = NULL;
9585 int ch, show_files = 0;
9587 TAILQ_INIT(&paths);
9589 while ((ch = getopt(argc, argv, "")) != -1) {
9590 switch (ch) {
9591 default:
9592 usage_info();
9593 /* NOTREACHED */
9597 argc -= optind;
9598 argv += optind;
9600 #ifndef PROFILE
9601 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
9602 NULL) == -1)
9603 err(1, "pledge");
9604 #endif
9605 cwd = getcwd(NULL, 0);
9606 if (cwd == NULL) {
9607 error = got_error_from_errno("getcwd");
9608 goto done;
9611 error = got_worktree_open(&worktree, cwd);
9612 if (error) {
9613 if (error->code == GOT_ERR_NOT_WORKTREE)
9614 error = wrap_not_worktree_error(error, "status", cwd);
9615 goto done;
9618 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9619 if (error)
9620 goto done;
9622 if (argc >= 1) {
9623 error = get_worktree_paths_from_argv(&paths, argc, argv,
9624 worktree);
9625 if (error)
9626 goto done;
9627 show_files = 1;
9630 error = got_object_id_str(&id_str,
9631 got_worktree_get_base_commit_id(worktree));
9632 if (error)
9633 goto done;
9635 error = got_worktree_get_uuid(&uuidstr, worktree);
9636 if (error)
9637 goto done;
9639 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9640 printf("work tree base commit: %s\n", id_str);
9641 printf("work tree path prefix: %s\n",
9642 got_worktree_get_path_prefix(worktree));
9643 printf("work tree branch reference: %s\n",
9644 got_worktree_get_head_ref_name(worktree));
9645 printf("work tree UUID: %s\n", uuidstr);
9646 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
9648 if (show_files) {
9649 struct got_pathlist_entry *pe;
9650 TAILQ_FOREACH(pe, &paths, entry) {
9651 if (pe->path_len == 0)
9652 continue;
9654 * Assume this path will fail. This will be corrected
9655 * in print_path_info() in case the path does suceeed.
9657 pe->data = (void *)got_error_path(pe->path,
9658 GOT_ERR_BAD_PATH);
9660 error = got_worktree_path_info(worktree, &paths,
9661 print_path_info, &paths, check_cancelled, NULL);
9662 if (error)
9663 goto done;
9664 TAILQ_FOREACH(pe, &paths, entry) {
9665 if (pe->data != NULL) {
9666 error = pe->data; /* bad path */
9667 break;
9671 done:
9672 TAILQ_FOREACH(pe, &paths, entry)
9673 free((char *)pe->path);
9674 got_pathlist_free(&paths);
9675 free(cwd);
9676 free(id_str);
9677 free(uuidstr);
9678 return error;