Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/param.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
41 #include <util.h>
43 #include "got_version.h"
44 #include "got_error.h"
45 #include "got_object.h"
46 #include "got_reference.h"
47 #include "got_repository.h"
48 #include "got_path.h"
49 #include "got_cancel.h"
50 #include "got_worktree.h"
51 #include "got_diff.h"
52 #include "got_commit_graph.h"
53 #include "got_fetch.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_opentemp.h"
57 #include "got_gotconfig.h"
59 #ifndef nitems
60 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
61 #endif
63 static volatile sig_atomic_t sigint_received;
64 static volatile sig_atomic_t sigpipe_received;
66 static void
67 catch_sigint(int signo)
68 {
69 sigint_received = 1;
70 }
72 static void
73 catch_sigpipe(int signo)
74 {
75 sigpipe_received = 1;
76 }
79 struct got_cmd {
80 const char *cmd_name;
81 const struct got_error *(*cmd_main)(int, char *[]);
82 void (*cmd_usage)(void);
83 const char *cmd_alias;
84 };
86 __dead static void usage(int);
87 __dead static void usage_init(void);
88 __dead static void usage_import(void);
89 __dead static void usage_clone(void);
90 __dead static void usage_fetch(void);
91 __dead static void usage_checkout(void);
92 __dead static void usage_update(void);
93 __dead static void usage_log(void);
94 __dead static void usage_diff(void);
95 __dead static void usage_blame(void);
96 __dead static void usage_tree(void);
97 __dead static void usage_status(void);
98 __dead static void usage_ref(void);
99 __dead static void usage_branch(void);
100 __dead static void usage_tag(void);
101 __dead static void usage_add(void);
102 __dead static void usage_remove(void);
103 __dead static void usage_revert(void);
104 __dead static void usage_commit(void);
105 __dead static void usage_cherrypick(void);
106 __dead static void usage_backout(void);
107 __dead static void usage_rebase(void);
108 __dead static void usage_histedit(void);
109 __dead static void usage_integrate(void);
110 __dead static void usage_stage(void);
111 __dead static void usage_unstage(void);
112 __dead static void usage_cat(void);
113 __dead static void usage_info(void);
115 static const struct got_error* cmd_init(int, char *[]);
116 static const struct got_error* cmd_import(int, char *[]);
117 static const struct got_error* cmd_clone(int, char *[]);
118 static const struct got_error* cmd_fetch(int, char *[]);
119 static const struct got_error* cmd_checkout(int, char *[]);
120 static const struct got_error* cmd_update(int, char *[]);
121 static const struct got_error* cmd_log(int, char *[]);
122 static const struct got_error* cmd_diff(int, char *[]);
123 static const struct got_error* cmd_blame(int, char *[]);
124 static const struct got_error* cmd_tree(int, char *[]);
125 static const struct got_error* cmd_status(int, char *[]);
126 static const struct got_error* cmd_ref(int, char *[]);
127 static const struct got_error* cmd_branch(int, char *[]);
128 static const struct got_error* cmd_tag(int, char *[]);
129 static const struct got_error* cmd_add(int, char *[]);
130 static const struct got_error* cmd_remove(int, char *[]);
131 static const struct got_error* cmd_revert(int, char *[]);
132 static const struct got_error* cmd_commit(int, char *[]);
133 static const struct got_error* cmd_cherrypick(int, char *[]);
134 static const struct got_error* cmd_backout(int, char *[]);
135 static const struct got_error* cmd_rebase(int, char *[]);
136 static const struct got_error* cmd_histedit(int, char *[]);
137 static const struct got_error* cmd_integrate(int, char *[]);
138 static const struct got_error* cmd_stage(int, char *[]);
139 static const struct got_error* cmd_unstage(int, char *[]);
140 static const struct got_error* cmd_cat(int, char *[]);
141 static const struct got_error* cmd_info(int, char *[]);
143 static struct got_cmd got_commands[] = {
144 { "init", cmd_init, usage_init, "" },
145 { "import", cmd_import, usage_import, "im" },
146 { "clone", cmd_clone, usage_clone, "cl" },
147 { "fetch", cmd_fetch, usage_fetch, "fe" },
148 { "checkout", cmd_checkout, usage_checkout, "co" },
149 { "update", cmd_update, usage_update, "up" },
150 { "log", cmd_log, usage_log, "" },
151 { "diff", cmd_diff, usage_diff, "di" },
152 { "blame", cmd_blame, usage_blame, "bl" },
153 { "tree", cmd_tree, usage_tree, "tr" },
154 { "status", cmd_status, usage_status, "st" },
155 { "ref", cmd_ref, usage_ref, "" },
156 { "branch", cmd_branch, usage_branch, "br" },
157 { "tag", cmd_tag, usage_tag, "" },
158 { "add", cmd_add, usage_add, "" },
159 { "remove", cmd_remove, usage_remove, "rm" },
160 { "revert", cmd_revert, usage_revert, "rv" },
161 { "commit", cmd_commit, usage_commit, "ci" },
162 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
163 { "backout", cmd_backout, usage_backout, "bo" },
164 { "rebase", cmd_rebase, usage_rebase, "rb" },
165 { "histedit", cmd_histedit, usage_histedit, "he" },
166 { "integrate", cmd_integrate, usage_integrate,"ig" },
167 { "stage", cmd_stage, usage_stage, "sg" },
168 { "unstage", cmd_unstage, usage_unstage, "ug" },
169 { "cat", cmd_cat, usage_cat, "" },
170 { "info", cmd_info, usage_info, "" },
171 };
173 static void
174 list_commands(void)
176 int i;
178 fprintf(stderr, "commands:");
179 for (i = 0; i < nitems(got_commands); i++) {
180 struct got_cmd *cmd = &got_commands[i];
181 fprintf(stderr, " %s", cmd->cmd_name);
183 fputc('\n', stderr);
186 int
187 main(int argc, char *argv[])
189 struct got_cmd *cmd;
190 unsigned int i;
191 int ch;
192 int hflag = 0, Vflag = 0;
193 static struct option longopts[] = {
194 { "version", no_argument, NULL, 'V' },
195 { NULL, 0, NULL, 0}
196 };
198 setlocale(LC_CTYPE, "");
200 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
201 switch (ch) {
202 case 'h':
203 hflag = 1;
204 break;
205 case 'V':
206 Vflag = 1;
207 break;
208 default:
209 usage(hflag);
210 /* NOTREACHED */
214 argc -= optind;
215 argv += optind;
216 optind = 0;
218 if (Vflag) {
219 got_version_print_str();
220 return 1;
223 if (argc <= 0)
224 usage(hflag);
226 signal(SIGINT, catch_sigint);
227 signal(SIGPIPE, catch_sigpipe);
229 for (i = 0; i < nitems(got_commands); i++) {
230 const struct got_error *error;
232 cmd = &got_commands[i];
234 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
235 strcmp(cmd->cmd_alias, argv[0]) != 0)
236 continue;
238 if (hflag)
239 got_commands[i].cmd_usage();
241 error = got_commands[i].cmd_main(argc, argv);
242 if (error && error->code != GOT_ERR_CANCELLED &&
243 error->code != GOT_ERR_PRIVSEP_EXIT &&
244 !(sigpipe_received &&
245 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
246 !(sigint_received &&
247 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
248 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
249 return 1;
252 return 0;
255 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
256 list_commands();
257 return 1;
260 __dead static void
261 usage(int hflag)
263 fprintf(stderr, "usage: %s [-h] [-V | --version] command [arg ...]\n",
264 getprogname());
265 if (hflag)
266 list_commands();
267 exit(1);
270 static const struct got_error *
271 get_editor(char **abspath)
273 const struct got_error *err = NULL;
274 const char *editor;
276 *abspath = NULL;
278 editor = getenv("VISUAL");
279 if (editor == NULL)
280 editor = getenv("EDITOR");
282 if (editor) {
283 err = got_path_find_prog(abspath, editor);
284 if (err)
285 return err;
288 if (*abspath == NULL) {
289 *abspath = strdup("/bin/ed");
290 if (*abspath == NULL)
291 return got_error_from_errno("strdup");
294 return NULL;
297 static const struct got_error *
298 apply_unveil(const char *repo_path, int repo_read_only,
299 const char *worktree_path)
301 const struct got_error *err;
303 #ifdef PROFILE
304 if (unveil("gmon.out", "rwc") != 0)
305 return got_error_from_errno2("unveil", "gmon.out");
306 #endif
307 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
308 return got_error_from_errno2("unveil", repo_path);
310 if (worktree_path && unveil(worktree_path, "rwc") != 0)
311 return got_error_from_errno2("unveil", worktree_path);
313 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
314 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
316 err = got_privsep_unveil_exec_helpers();
317 if (err != NULL)
318 return err;
320 if (unveil(NULL, NULL) != 0)
321 return got_error_from_errno("unveil");
323 return NULL;
326 __dead static void
327 usage_init(void)
329 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
330 exit(1);
333 static const struct got_error *
334 cmd_init(int argc, char *argv[])
336 const struct got_error *error = NULL;
337 char *repo_path = NULL;
338 int ch;
340 while ((ch = getopt(argc, argv, "")) != -1) {
341 switch (ch) {
342 default:
343 usage_init();
344 /* NOTREACHED */
348 argc -= optind;
349 argv += optind;
351 #ifndef PROFILE
352 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
353 err(1, "pledge");
354 #endif
355 if (argc != 1)
356 usage_init();
358 repo_path = strdup(argv[0]);
359 if (repo_path == NULL)
360 return got_error_from_errno("strdup");
362 got_path_strip_trailing_slashes(repo_path);
364 error = got_path_mkdir(repo_path);
365 if (error &&
366 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
367 goto done;
369 error = apply_unveil(repo_path, 0, NULL);
370 if (error)
371 goto done;
373 error = got_repo_init(repo_path);
374 done:
375 free(repo_path);
376 return error;
379 __dead static void
380 usage_import(void)
382 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
383 "[-r repository-path] [-I pattern] path\n", getprogname());
384 exit(1);
387 int
388 spawn_editor(const char *editor, const char *file)
390 pid_t pid;
391 sig_t sighup, sigint, sigquit;
392 int st = -1;
394 sighup = signal(SIGHUP, SIG_IGN);
395 sigint = signal(SIGINT, SIG_IGN);
396 sigquit = signal(SIGQUIT, SIG_IGN);
398 switch (pid = fork()) {
399 case -1:
400 goto doneediting;
401 case 0:
402 execl(editor, editor, file, (char *)NULL);
403 _exit(127);
406 while (waitpid(pid, &st, 0) == -1)
407 if (errno != EINTR)
408 break;
410 doneediting:
411 (void)signal(SIGHUP, sighup);
412 (void)signal(SIGINT, sigint);
413 (void)signal(SIGQUIT, sigquit);
415 if (!WIFEXITED(st)) {
416 errno = EINTR;
417 return -1;
420 return WEXITSTATUS(st);
423 static const struct got_error *
424 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
425 const char *initial_content)
427 const struct got_error *err = NULL;
428 char buf[1024];
429 struct stat st, st2;
430 FILE *fp;
431 int content_changed = 0;
432 size_t len;
434 *logmsg = NULL;
436 if (stat(logmsg_path, &st) == -1)
437 return got_error_from_errno2("stat", logmsg_path);
439 if (spawn_editor(editor, logmsg_path) == -1)
440 return got_error_from_errno("failed spawning editor");
442 if (stat(logmsg_path, &st2) == -1)
443 return got_error_from_errno("stat");
445 if (st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
446 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
447 "no changes made to commit message, aborting");
449 *logmsg = malloc(st2.st_size + 1);
450 if (*logmsg == NULL)
451 return got_error_from_errno("malloc");
452 (*logmsg)[0] = '\0';
453 len = 0;
455 fp = fopen(logmsg_path, "r");
456 if (fp == NULL) {
457 err = got_error_from_errno("fopen");
458 goto done;
460 while (fgets(buf, sizeof(buf), fp) != NULL) {
461 if (!content_changed && strcmp(buf, initial_content) != 0)
462 content_changed = 1;
463 if (buf[0] == '#' || (len == 0 && buf[0] == '\n'))
464 continue; /* remove comments and leading empty lines */
465 len = strlcat(*logmsg, buf, st2.st_size);
467 fclose(fp);
469 while (len > 0 && (*logmsg)[len - 1] == '\n') {
470 (*logmsg)[len - 1] = '\0';
471 len--;
474 if (len == 0 || !content_changed)
475 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
476 "commit message cannot be empty, aborting");
477 done:
478 if (err) {
479 free(*logmsg);
480 *logmsg = NULL;
482 return err;
485 static const struct got_error *
486 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
487 const char *path_dir, const char *branch_name)
489 char *initial_content = NULL;
490 const struct got_error *err = NULL;
491 int initial_content_len;
492 int fd = -1;
494 initial_content_len = asprintf(&initial_content,
495 "\n# %s to be imported to branch %s\n", path_dir,
496 branch_name);
497 if (initial_content_len == -1)
498 return got_error_from_errno("asprintf");
500 err = got_opentemp_named_fd(logmsg_path, &fd,
501 GOT_TMPDIR_STR "/got-importmsg");
502 if (err)
503 goto done;
505 if (write(fd, initial_content, initial_content_len) == -1) {
506 err = got_error_from_errno2("write", *logmsg_path);
507 goto done;
510 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content);
511 done:
512 if (fd != -1 && close(fd) == -1 && err == NULL)
513 err = got_error_from_errno2("close", *logmsg_path);
514 free(initial_content);
515 if (err) {
516 free(*logmsg_path);
517 *logmsg_path = NULL;
519 return err;
522 static const struct got_error *
523 import_progress(void *arg, const char *path)
525 printf("A %s\n", path);
526 return NULL;
529 static const struct got_error *
530 get_author(char **author, struct got_repository *repo,
531 struct got_worktree *worktree)
533 const struct got_error *err = NULL;
534 const char *got_author = NULL, *name, *email;
535 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
537 *author = NULL;
539 if (worktree)
540 worktree_conf = got_worktree_get_gotconfig(worktree);
541 repo_conf = got_repo_get_gotconfig(repo);
543 /*
544 * Priority of potential author information sources, from most
545 * significant to least significant:
546 * 1) work tree's .got/got.conf file
547 * 2) repository's got.conf file
548 * 3) repository's git config file
549 * 4) environment variables
550 * 5) global git config files (in user's home directory or /etc)
551 */
553 if (worktree_conf)
554 got_author = got_gotconfig_get_author(worktree_conf);
555 if (got_author == NULL)
556 got_author = got_gotconfig_get_author(repo_conf);
557 if (got_author == NULL) {
558 name = got_repo_get_gitconfig_author_name(repo);
559 email = got_repo_get_gitconfig_author_email(repo);
560 if (name && email) {
561 if (asprintf(author, "%s <%s>", name, email) == -1)
562 return got_error_from_errno("asprintf");
563 return NULL;
566 got_author = getenv("GOT_AUTHOR");
567 if (got_author == NULL) {
568 name = got_repo_get_global_gitconfig_author_name(repo);
569 email = got_repo_get_global_gitconfig_author_email(
570 repo);
571 if (name && email) {
572 if (asprintf(author, "%s <%s>", name, email)
573 == -1)
574 return got_error_from_errno("asprintf");
575 return NULL;
577 /* TODO: Look up user in password database? */
578 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
582 *author = strdup(got_author);
583 if (*author == NULL)
584 return got_error_from_errno("strdup");
586 /*
587 * Really dumb email address check; we're only doing this to
588 * avoid git's object parser breaking on commits we create.
589 */
590 while (*got_author && *got_author != '<')
591 got_author++;
592 if (*got_author != '<') {
593 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
594 goto done;
596 while (*got_author && *got_author != '@')
597 got_author++;
598 if (*got_author != '@') {
599 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
600 goto done;
602 while (*got_author && *got_author != '>')
603 got_author++;
604 if (*got_author != '>')
605 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
606 done:
607 if (err) {
608 free(*author);
609 *author = NULL;
611 return err;
614 static const struct got_error *
615 get_gitconfig_path(char **gitconfig_path)
617 const char *homedir = getenv("HOME");
619 *gitconfig_path = NULL;
620 if (homedir) {
621 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
622 return got_error_from_errno("asprintf");
625 return NULL;
628 static const struct got_error *
629 cmd_import(int argc, char *argv[])
631 const struct got_error *error = NULL;
632 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
633 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
634 const char *branch_name = "main";
635 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
636 struct got_repository *repo = NULL;
637 struct got_reference *branch_ref = NULL, *head_ref = NULL;
638 struct got_object_id *new_commit_id = NULL;
639 int ch;
640 struct got_pathlist_head ignores;
641 struct got_pathlist_entry *pe;
642 int preserve_logmsg = 0;
644 TAILQ_INIT(&ignores);
646 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
647 switch (ch) {
648 case 'b':
649 branch_name = optarg;
650 break;
651 case 'm':
652 logmsg = strdup(optarg);
653 if (logmsg == NULL) {
654 error = got_error_from_errno("strdup");
655 goto done;
657 break;
658 case 'r':
659 repo_path = realpath(optarg, NULL);
660 if (repo_path == NULL) {
661 error = got_error_from_errno2("realpath",
662 optarg);
663 goto done;
665 break;
666 case 'I':
667 if (optarg[0] == '\0')
668 break;
669 error = got_pathlist_insert(&pe, &ignores, optarg,
670 NULL);
671 if (error)
672 goto done;
673 break;
674 default:
675 usage_import();
676 /* NOTREACHED */
680 argc -= optind;
681 argv += optind;
683 #ifndef PROFILE
684 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
685 "unveil",
686 NULL) == -1)
687 err(1, "pledge");
688 #endif
689 if (argc != 1)
690 usage_import();
692 if (repo_path == NULL) {
693 repo_path = getcwd(NULL, 0);
694 if (repo_path == NULL)
695 return got_error_from_errno("getcwd");
697 got_path_strip_trailing_slashes(repo_path);
698 error = get_gitconfig_path(&gitconfig_path);
699 if (error)
700 goto done;
701 error = got_repo_open(&repo, repo_path, gitconfig_path);
702 if (error)
703 goto done;
705 error = get_author(&author, repo, NULL);
706 if (error)
707 return error;
709 /*
710 * Don't let the user create a branch name with a leading '-'.
711 * While technically a valid reference name, this case is usually
712 * an unintended typo.
713 */
714 if (branch_name[0] == '-')
715 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
717 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
718 error = got_error_from_errno("asprintf");
719 goto done;
722 error = got_ref_open(&branch_ref, repo, refname, 0);
723 if (error) {
724 if (error->code != GOT_ERR_NOT_REF)
725 goto done;
726 } else {
727 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
728 "import target branch already exists");
729 goto done;
732 path_dir = realpath(argv[0], NULL);
733 if (path_dir == NULL) {
734 error = got_error_from_errno2("realpath", argv[0]);
735 goto done;
737 got_path_strip_trailing_slashes(path_dir);
739 /*
740 * unveil(2) traverses exec(2); if an editor is used we have
741 * to apply unveil after the log message has been written.
742 */
743 if (logmsg == NULL || strlen(logmsg) == 0) {
744 error = get_editor(&editor);
745 if (error)
746 goto done;
747 free(logmsg);
748 error = collect_import_msg(&logmsg, &logmsg_path, editor,
749 path_dir, refname);
750 if (error) {
751 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
752 logmsg_path != NULL)
753 preserve_logmsg = 1;
754 goto done;
758 if (unveil(path_dir, "r") != 0) {
759 error = got_error_from_errno2("unveil", path_dir);
760 if (logmsg_path)
761 preserve_logmsg = 1;
762 goto done;
765 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
766 if (error) {
767 if (logmsg_path)
768 preserve_logmsg = 1;
769 goto done;
772 error = got_repo_import(&new_commit_id, path_dir, logmsg,
773 author, &ignores, repo, import_progress, NULL);
774 if (error) {
775 if (logmsg_path)
776 preserve_logmsg = 1;
777 goto done;
780 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
781 if (error) {
782 if (logmsg_path)
783 preserve_logmsg = 1;
784 goto done;
787 error = got_ref_write(branch_ref, repo);
788 if (error) {
789 if (logmsg_path)
790 preserve_logmsg = 1;
791 goto done;
794 error = got_object_id_str(&id_str, new_commit_id);
795 if (error) {
796 if (logmsg_path)
797 preserve_logmsg = 1;
798 goto done;
801 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
802 if (error) {
803 if (error->code != GOT_ERR_NOT_REF) {
804 if (logmsg_path)
805 preserve_logmsg = 1;
806 goto done;
809 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
810 branch_ref);
811 if (error) {
812 if (logmsg_path)
813 preserve_logmsg = 1;
814 goto done;
817 error = got_ref_write(head_ref, repo);
818 if (error) {
819 if (logmsg_path)
820 preserve_logmsg = 1;
821 goto done;
825 printf("Created branch %s with commit %s\n",
826 got_ref_get_name(branch_ref), id_str);
827 done:
828 if (preserve_logmsg) {
829 fprintf(stderr, "%s: log message preserved in %s\n",
830 getprogname(), logmsg_path);
831 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
832 error = got_error_from_errno2("unlink", logmsg_path);
833 free(logmsg);
834 free(logmsg_path);
835 free(repo_path);
836 free(editor);
837 free(refname);
838 free(new_commit_id);
839 free(id_str);
840 free(author);
841 free(gitconfig_path);
842 if (branch_ref)
843 got_ref_close(branch_ref);
844 if (head_ref)
845 got_ref_close(head_ref);
846 return error;
849 __dead static void
850 usage_clone(void)
852 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
853 "[-R reference] repository-url [directory]\n", getprogname());
854 exit(1);
857 struct got_fetch_progress_arg {
858 char last_scaled_size[FMT_SCALED_STRSIZE];
859 int last_p_indexed;
860 int last_p_resolved;
861 int verbosity;
862 };
864 static const struct got_error *
865 fetch_progress(void *arg, const char *message, off_t packfile_size,
866 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
868 struct got_fetch_progress_arg *a = arg;
869 char scaled_size[FMT_SCALED_STRSIZE];
870 int p_indexed, p_resolved;
871 int print_size = 0, print_indexed = 0, print_resolved = 0;
873 if (a->verbosity < 0)
874 return NULL;
876 if (message && message[0] != '\0') {
877 printf("\rserver: %s", message);
878 fflush(stdout);
879 return NULL;
882 if (packfile_size > 0 || nobj_indexed > 0) {
883 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
884 (a->last_scaled_size[0] == '\0' ||
885 strcmp(scaled_size, a->last_scaled_size)) != 0) {
886 print_size = 1;
887 if (strlcpy(a->last_scaled_size, scaled_size,
888 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
889 return got_error(GOT_ERR_NO_SPACE);
891 if (nobj_indexed > 0) {
892 p_indexed = (nobj_indexed * 100) / nobj_total;
893 if (p_indexed != a->last_p_indexed) {
894 a->last_p_indexed = p_indexed;
895 print_indexed = 1;
896 print_size = 1;
899 if (nobj_resolved > 0) {
900 p_resolved = (nobj_resolved * 100) /
901 (nobj_total - nobj_loose);
902 if (p_resolved != a->last_p_resolved) {
903 a->last_p_resolved = p_resolved;
904 print_resolved = 1;
905 print_indexed = 1;
906 print_size = 1;
911 if (print_size || print_indexed || print_resolved)
912 printf("\r");
913 if (print_size)
914 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
915 if (print_indexed)
916 printf("; indexing %d%%", p_indexed);
917 if (print_resolved)
918 printf("; resolving deltas %d%%", p_resolved);
919 if (print_size || print_indexed || print_resolved)
920 fflush(stdout);
922 return NULL;
925 static const struct got_error *
926 create_symref(const char *refname, struct got_reference *target_ref,
927 int verbosity, struct got_repository *repo)
929 const struct got_error *err;
930 struct got_reference *head_symref;
932 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
933 if (err)
934 return err;
936 err = got_ref_write(head_symref, repo);
937 got_ref_close(head_symref);
938 if (err == NULL && verbosity > 0) {
939 printf("Created reference %s: %s\n", GOT_REF_HEAD,
940 got_ref_get_name(target_ref));
942 return err;
945 static const struct got_error *
946 list_remote_refs(struct got_pathlist_head *symrefs,
947 struct got_pathlist_head *refs)
949 const struct got_error *err;
950 struct got_pathlist_entry *pe;
952 TAILQ_FOREACH(pe, symrefs, entry) {
953 const char *refname = pe->path;
954 const char *targetref = pe->data;
956 printf("%s: %s\n", refname, targetref);
959 TAILQ_FOREACH(pe, refs, entry) {
960 const char *refname = pe->path;
961 struct got_object_id *id = pe->data;
962 char *id_str;
964 err = got_object_id_str(&id_str, id);
965 if (err)
966 return err;
967 printf("%s: %s\n", refname, id_str);
968 free(id_str);
971 return NULL;
974 static const struct got_error *
975 create_ref(const char *refname, struct got_object_id *id,
976 int verbosity, struct got_repository *repo)
978 const struct got_error *err = NULL;
979 struct got_reference *ref;
980 char *id_str;
982 err = got_object_id_str(&id_str, id);
983 if (err)
984 return err;
986 err = got_ref_alloc(&ref, refname, id);
987 if (err)
988 goto done;
990 err = got_ref_write(ref, repo);
991 got_ref_close(ref);
993 if (err == NULL && verbosity >= 0)
994 printf("Created reference %s: %s\n", refname, id_str);
995 done:
996 free(id_str);
997 return err;
1000 static int
1001 match_wanted_ref(const char *refname, const char *wanted_ref)
1003 if (strncmp(refname, "refs/", 5) != 0)
1004 return 0;
1005 refname += 5;
1008 * Prevent fetching of references that won't make any
1009 * sense outside of the remote repository's context.
1011 if (strncmp(refname, "got/", 4) == 0)
1012 return 0;
1013 if (strncmp(refname, "remotes/", 8) == 0)
1014 return 0;
1016 if (strncmp(wanted_ref, "refs/", 5) == 0)
1017 wanted_ref += 5;
1019 /* Allow prefix match. */
1020 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1021 return 1;
1023 /* Allow exact match. */
1024 return (strcmp(refname, wanted_ref) == 0);
1027 static int
1028 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1030 struct got_pathlist_entry *pe;
1032 TAILQ_FOREACH(pe, wanted_refs, entry) {
1033 if (match_wanted_ref(refname, pe->path))
1034 return 1;
1037 return 0;
1040 static const struct got_error *
1041 create_wanted_ref(const char *refname, struct got_object_id *id,
1042 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1044 const struct got_error *err;
1045 char *remote_refname;
1047 if (strncmp("refs/", refname, 5) == 0)
1048 refname += 5;
1050 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1051 remote_repo_name, refname) == -1)
1052 return got_error_from_errno("asprintf");
1054 err = create_ref(remote_refname, id, verbosity, repo);
1055 free(remote_refname);
1056 return err;
1059 static const struct got_error *
1060 cmd_clone(int argc, char *argv[])
1062 const struct got_error *error = NULL;
1063 const char *uri, *dirname;
1064 char *proto, *host, *port, *repo_name, *server_path;
1065 char *default_destdir = NULL, *id_str = NULL;
1066 const char *repo_path, *remote_repo_path;
1067 struct got_repository *repo = NULL;
1068 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1069 struct got_pathlist_entry *pe;
1070 struct got_object_id *pack_hash = NULL;
1071 int ch, fetchfd = -1, fetchstatus;
1072 pid_t fetchpid = -1;
1073 struct got_fetch_progress_arg fpa;
1074 char *git_url = NULL;
1075 char *gitconfig_path = NULL, *gotconfig_path = NULL;
1076 char *gitconfig = NULL, *gotconfig = NULL;
1077 FILE *gitconfig_file = NULL, *gotconfig_file = NULL;
1078 ssize_t n;
1079 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1080 int list_refs_only = 0;
1081 struct got_reference *head_symref = NULL;
1083 TAILQ_INIT(&refs);
1084 TAILQ_INIT(&symrefs);
1085 TAILQ_INIT(&wanted_branches);
1086 TAILQ_INIT(&wanted_refs);
1088 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1089 switch (ch) {
1090 case 'a':
1091 fetch_all_branches = 1;
1092 break;
1093 case 'b':
1094 error = got_pathlist_append(&wanted_branches,
1095 optarg, NULL);
1096 if (error)
1097 return error;
1098 break;
1099 case 'l':
1100 list_refs_only = 1;
1101 break;
1102 case 'm':
1103 mirror_references = 1;
1104 break;
1105 case 'v':
1106 if (verbosity < 0)
1107 verbosity = 0;
1108 else if (verbosity < 3)
1109 verbosity++;
1110 break;
1111 case 'q':
1112 verbosity = -1;
1113 break;
1114 case 'R':
1115 error = got_pathlist_append(&wanted_refs,
1116 optarg, NULL);
1117 if (error)
1118 return error;
1119 break;
1120 default:
1121 usage_clone();
1122 break;
1125 argc -= optind;
1126 argv += optind;
1128 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1129 errx(1, "-a and -b options are mutually exclusive");
1130 if (list_refs_only) {
1131 if (!TAILQ_EMPTY(&wanted_branches))
1132 errx(1, "-l and -b options are mutually exclusive");
1133 if (fetch_all_branches)
1134 errx(1, "-l and -a options are mutually exclusive");
1135 if (mirror_references)
1136 errx(1, "-l and -m options are mutually exclusive");
1137 if (verbosity == -1)
1138 errx(1, "-l and -q options are mutually exclusive");
1139 if (!TAILQ_EMPTY(&wanted_refs))
1140 errx(1, "-l and -R options are mutually exclusive");
1143 uri = argv[0];
1145 if (argc == 1)
1146 dirname = NULL;
1147 else if (argc == 2)
1148 dirname = argv[1];
1149 else
1150 usage_clone();
1152 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1153 &repo_name, uri);
1154 if (error)
1155 goto done;
1157 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1158 host, port ? ":" : "", port ? port : "",
1159 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1160 error = got_error_from_errno("asprintf");
1161 goto done;
1164 if (strcmp(proto, "git") == 0) {
1165 #ifndef PROFILE
1166 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1167 "sendfd dns inet unveil", NULL) == -1)
1168 err(1, "pledge");
1169 #endif
1170 } else if (strcmp(proto, "git+ssh") == 0 ||
1171 strcmp(proto, "ssh") == 0) {
1172 #ifndef PROFILE
1173 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1174 "sendfd unveil", NULL) == -1)
1175 err(1, "pledge");
1176 #endif
1177 } else if (strcmp(proto, "http") == 0 ||
1178 strcmp(proto, "git+http") == 0) {
1179 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1180 goto done;
1181 } else {
1182 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1183 goto done;
1185 if (dirname == NULL) {
1186 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1187 error = got_error_from_errno("asprintf");
1188 goto done;
1190 repo_path = default_destdir;
1191 } else
1192 repo_path = dirname;
1194 if (!list_refs_only) {
1195 error = got_path_mkdir(repo_path);
1196 if (error &&
1197 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1198 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1199 goto done;
1200 if (!got_path_dir_is_empty(repo_path)) {
1201 error = got_error_path(repo_path,
1202 GOT_ERR_DIR_NOT_EMPTY);
1203 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 if (!list_refs_only) {
1228 error = got_repo_init(repo_path);
1229 if (error)
1230 goto done;
1231 error = got_repo_open(&repo, repo_path, NULL);
1232 if (error)
1233 goto done;
1236 fpa.last_scaled_size[0] = '\0';
1237 fpa.last_p_indexed = -1;
1238 fpa.last_p_resolved = -1;
1239 fpa.verbosity = verbosity;
1240 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1241 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1242 fetch_all_branches, &wanted_branches, &wanted_refs,
1243 list_refs_only, verbosity, fetchfd, repo,
1244 fetch_progress, &fpa);
1245 if (error)
1246 goto done;
1248 if (list_refs_only) {
1249 error = list_remote_refs(&symrefs, &refs);
1250 goto done;
1253 error = got_object_id_str(&id_str, pack_hash);
1254 if (error)
1255 goto done;
1256 if (verbosity >= 0)
1257 printf("\nFetched %s.pack\n", id_str);
1258 free(id_str);
1260 /* Set up references provided with the pack file. */
1261 TAILQ_FOREACH(pe, &refs, entry) {
1262 const char *refname = pe->path;
1263 struct got_object_id *id = pe->data;
1264 char *remote_refname;
1266 if (is_wanted_ref(&wanted_refs, refname) &&
1267 !mirror_references) {
1268 error = create_wanted_ref(refname, id,
1269 GOT_FETCH_DEFAULT_REMOTE_NAME,
1270 verbosity - 1, repo);
1271 if (error)
1272 goto done;
1273 continue;
1276 error = create_ref(refname, id, verbosity - 1, repo);
1277 if (error)
1278 goto done;
1280 if (mirror_references)
1281 continue;
1283 if (strncmp("refs/heads/", refname, 11) != 0)
1284 continue;
1286 if (asprintf(&remote_refname,
1287 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1288 refname + 11) == -1) {
1289 error = got_error_from_errno("asprintf");
1290 goto done;
1292 error = create_ref(remote_refname, id, verbosity - 1, repo);
1293 free(remote_refname);
1294 if (error)
1295 goto done;
1298 /* Set the HEAD reference if the server provided one. */
1299 TAILQ_FOREACH(pe, &symrefs, entry) {
1300 struct got_reference *target_ref;
1301 const char *refname = pe->path;
1302 const char *target = pe->data;
1303 char *remote_refname = NULL, *remote_target = NULL;
1305 if (strcmp(refname, GOT_REF_HEAD) != 0)
1306 continue;
1308 error = got_ref_open(&target_ref, repo, target, 0);
1309 if (error) {
1310 if (error->code == GOT_ERR_NOT_REF) {
1311 error = NULL;
1312 continue;
1314 goto done;
1317 error = create_symref(refname, target_ref, verbosity, repo);
1318 got_ref_close(target_ref);
1319 if (error)
1320 goto done;
1322 if (mirror_references)
1323 continue;
1325 if (strncmp("refs/heads/", target, 11) != 0)
1326 continue;
1328 if (asprintf(&remote_refname,
1329 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1330 refname) == -1) {
1331 error = got_error_from_errno("asprintf");
1332 goto done;
1334 if (asprintf(&remote_target,
1335 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1336 target + 11) == -1) {
1337 error = got_error_from_errno("asprintf");
1338 free(remote_refname);
1339 goto done;
1341 error = got_ref_open(&target_ref, repo, remote_target, 0);
1342 if (error) {
1343 free(remote_refname);
1344 free(remote_target);
1345 if (error->code == GOT_ERR_NOT_REF) {
1346 error = NULL;
1347 continue;
1349 goto done;
1351 error = create_symref(remote_refname, target_ref,
1352 verbosity - 1, repo);
1353 free(remote_refname);
1354 free(remote_target);
1355 got_ref_close(target_ref);
1356 if (error)
1357 goto done;
1359 if (pe == NULL) {
1361 * We failed to set the HEAD reference. If we asked for
1362 * a set of wanted branches use the first of one of those
1363 * which could be fetched instead.
1365 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1366 const char *target = pe->path;
1367 struct got_reference *target_ref;
1369 error = got_ref_open(&target_ref, repo, target, 0);
1370 if (error) {
1371 if (error->code == GOT_ERR_NOT_REF) {
1372 error = NULL;
1373 continue;
1375 goto done;
1378 error = create_symref(GOT_REF_HEAD, target_ref,
1379 verbosity, repo);
1380 got_ref_close(target_ref);
1381 if (error)
1382 goto done;
1383 break;
1387 /* Create got.conf(5). */
1388 gotconfig_path = got_repo_get_path_gotconfig(repo);
1389 if (gotconfig_path == NULL) {
1390 error = got_error_from_errno("got_repo_get_path_gotconfig");
1391 goto done;
1393 gotconfig_file = fopen(gotconfig_path, "a");
1394 if (gotconfig_file == NULL) {
1395 error = got_error_from_errno2("fopen", gotconfig_path);
1396 goto done;
1398 got_path_strip_trailing_slashes(server_path);
1399 remote_repo_path = server_path;
1400 while (remote_repo_path[0] == '/')
1401 remote_repo_path++;
1402 if (asprintf(&gotconfig,
1403 "remote \"%s\" {\n"
1404 "\tserver %s\n"
1405 "\tprotocol %s\n"
1406 "%s%s%s"
1407 "\trepository \"%s\"\n"
1408 "%s"
1409 "}\n",
1410 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1411 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1412 remote_repo_path,
1413 mirror_references ? "\tmirror-references yes\n" : "") == -1) {
1414 error = got_error_from_errno("asprintf");
1415 goto done;
1417 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1418 if (n != strlen(gotconfig)) {
1419 error = got_ferror(gotconfig_file, GOT_ERR_IO);
1420 goto done;
1423 /* Create a config file Git can understand. */
1424 gitconfig_path = got_repo_get_path_gitconfig(repo);
1425 if (gitconfig_path == NULL) {
1426 error = got_error_from_errno("got_repo_get_path_gitconfig");
1427 goto done;
1429 gitconfig_file = fopen(gitconfig_path, "a");
1430 if (gitconfig_file == NULL) {
1431 error = got_error_from_errno2("fopen", gitconfig_path);
1432 goto done;
1434 if (mirror_references) {
1435 if (asprintf(&gitconfig,
1436 "[remote \"%s\"]\n"
1437 "\turl = %s\n"
1438 "\tfetch = +refs/*:refs/*\n"
1439 "\tmirror = true\n",
1440 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1441 error = got_error_from_errno("asprintf");
1442 goto done;
1444 } else if (fetch_all_branches) {
1445 if (asprintf(&gitconfig,
1446 "[remote \"%s\"]\n"
1447 "\turl = %s\n"
1448 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1449 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1450 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1451 error = got_error_from_errno("asprintf");
1452 goto done;
1454 } else {
1455 const char *branchname;
1458 * If the server specified a default branch, use just that one.
1459 * Otherwise fall back to fetching all branches on next fetch.
1461 if (head_symref) {
1462 branchname = got_ref_get_symref_target(head_symref);
1463 if (strncmp(branchname, "refs/heads/", 11) == 0)
1464 branchname += 11;
1465 } else
1466 branchname = "*"; /* fall back to all branches */
1467 if (asprintf(&gitconfig,
1468 "[remote \"%s\"]\n"
1469 "\turl = %s\n"
1470 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1471 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1472 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1473 branchname) == -1) {
1474 error = got_error_from_errno("asprintf");
1475 goto done;
1478 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1479 if (n != strlen(gitconfig)) {
1480 error = got_ferror(gitconfig_file, GOT_ERR_IO);
1481 goto done;
1484 if (verbosity >= 0)
1485 printf("Created %s repository '%s'\n",
1486 mirror_references ? "mirrored" : "cloned", repo_path);
1487 done:
1488 if (fetchpid > 0) {
1489 if (kill(fetchpid, SIGTERM) == -1)
1490 error = got_error_from_errno("kill");
1491 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1492 error = got_error_from_errno("waitpid");
1494 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1495 error = got_error_from_errno("close");
1496 if (gotconfig_file && fclose(gotconfig_file) == EOF && error == NULL)
1497 error = got_error_from_errno("fclose");
1498 if (gitconfig_file && fclose(gitconfig_file) == EOF && error == NULL)
1499 error = got_error_from_errno("fclose");
1500 if (repo)
1501 got_repo_close(repo);
1502 if (head_symref)
1503 got_ref_close(head_symref);
1504 TAILQ_FOREACH(pe, &refs, entry) {
1505 free((void *)pe->path);
1506 free(pe->data);
1508 got_pathlist_free(&refs);
1509 TAILQ_FOREACH(pe, &symrefs, entry) {
1510 free((void *)pe->path);
1511 free(pe->data);
1513 got_pathlist_free(&symrefs);
1514 got_pathlist_free(&wanted_branches);
1515 got_pathlist_free(&wanted_refs);
1516 free(pack_hash);
1517 free(proto);
1518 free(host);
1519 free(port);
1520 free(server_path);
1521 free(repo_name);
1522 free(default_destdir);
1523 free(gotconfig);
1524 free(gitconfig);
1525 free(gotconfig_path);
1526 free(gitconfig_path);
1527 free(git_url);
1528 return error;
1531 static const struct got_error *
1532 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1533 int replace_tags, int verbosity, struct got_repository *repo)
1535 const struct got_error *err = NULL;
1536 char *new_id_str = NULL;
1537 struct got_object_id *old_id = NULL;
1539 err = got_object_id_str(&new_id_str, new_id);
1540 if (err)
1541 goto done;
1543 if (!replace_tags &&
1544 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1545 err = got_ref_resolve(&old_id, repo, ref);
1546 if (err)
1547 goto done;
1548 if (got_object_id_cmp(old_id, new_id) == 0)
1549 goto done;
1550 if (verbosity >= 0) {
1551 printf("Rejecting update of existing tag %s: %s\n",
1552 got_ref_get_name(ref), new_id_str);
1554 goto done;
1557 if (got_ref_is_symbolic(ref)) {
1558 if (verbosity >= 0) {
1559 printf("Replacing reference %s: %s\n",
1560 got_ref_get_name(ref),
1561 got_ref_get_symref_target(ref));
1563 err = got_ref_change_symref_to_ref(ref, new_id);
1564 if (err)
1565 goto done;
1566 err = got_ref_write(ref, repo);
1567 if (err)
1568 goto done;
1569 } else {
1570 err = got_ref_resolve(&old_id, repo, ref);
1571 if (err)
1572 goto done;
1573 if (got_object_id_cmp(old_id, new_id) == 0)
1574 goto done;
1576 err = got_ref_change_ref(ref, new_id);
1577 if (err)
1578 goto done;
1579 err = got_ref_write(ref, repo);
1580 if (err)
1581 goto done;
1584 if (verbosity >= 0)
1585 printf("Updated %s: %s\n", got_ref_get_name(ref),
1586 new_id_str);
1587 done:
1588 free(old_id);
1589 free(new_id_str);
1590 return err;
1593 static const struct got_error *
1594 update_symref(const char *refname, struct got_reference *target_ref,
1595 int verbosity, struct got_repository *repo)
1597 const struct got_error *err = NULL, *unlock_err;
1598 struct got_reference *symref;
1599 int symref_is_locked = 0;
1601 err = got_ref_open(&symref, repo, refname, 1);
1602 if (err) {
1603 if (err->code != GOT_ERR_NOT_REF)
1604 return err;
1605 err = got_ref_alloc_symref(&symref, refname, target_ref);
1606 if (err)
1607 goto done;
1609 err = got_ref_write(symref, repo);
1610 if (err)
1611 goto done;
1613 if (verbosity >= 0)
1614 printf("Created reference %s: %s\n",
1615 got_ref_get_name(symref),
1616 got_ref_get_symref_target(symref));
1617 } else {
1618 symref_is_locked = 1;
1620 if (strcmp(got_ref_get_symref_target(symref),
1621 got_ref_get_name(target_ref)) == 0)
1622 goto done;
1624 err = got_ref_change_symref(symref,
1625 got_ref_get_name(target_ref));
1626 if (err)
1627 goto done;
1629 err = got_ref_write(symref, repo);
1630 if (err)
1631 goto done;
1633 if (verbosity >= 0)
1634 printf("Updated %s: %s\n", got_ref_get_name(symref),
1635 got_ref_get_symref_target(symref));
1638 done:
1639 if (symref_is_locked) {
1640 unlock_err = got_ref_unlock(symref);
1641 if (unlock_err && err == NULL)
1642 err = unlock_err;
1644 got_ref_close(symref);
1645 return err;
1648 __dead static void
1649 usage_fetch(void)
1651 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1652 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1653 "[remote-repository-name]\n",
1654 getprogname());
1655 exit(1);
1658 static const struct got_error *
1659 delete_missing_ref(struct got_reference *ref,
1660 int verbosity, struct got_repository *repo)
1662 const struct got_error *err = NULL;
1663 struct got_object_id *id = NULL;
1664 char *id_str = NULL;
1666 if (got_ref_is_symbolic(ref)) {
1667 err = got_ref_delete(ref, repo);
1668 if (err)
1669 return err;
1670 if (verbosity >= 0) {
1671 printf("Deleted reference %s: %s\n",
1672 got_ref_get_name(ref),
1673 got_ref_get_symref_target(ref));
1675 } else {
1676 err = got_ref_resolve(&id, repo, ref);
1677 if (err)
1678 return err;
1679 err = got_object_id_str(&id_str, id);
1680 if (err)
1681 goto done;
1683 err = got_ref_delete(ref, repo);
1684 if (err)
1685 goto done;
1686 if (verbosity >= 0) {
1687 printf("Deleted reference %s: %s\n",
1688 got_ref_get_name(ref), id_str);
1691 done:
1692 free(id);
1693 free(id_str);
1694 return NULL;
1697 static const struct got_error *
1698 delete_missing_refs(struct got_pathlist_head *their_refs,
1699 struct got_pathlist_head *their_symrefs,
1700 const struct got_remote_repo *remote,
1701 int verbosity, struct got_repository *repo)
1703 const struct got_error *err = NULL, *unlock_err;
1704 struct got_reflist_head my_refs;
1705 struct got_reflist_entry *re;
1706 struct got_pathlist_entry *pe;
1707 char *remote_namespace = NULL;
1708 char *local_refname = NULL;
1710 SIMPLEQ_INIT(&my_refs);
1712 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
1713 == -1)
1714 return got_error_from_errno("asprintf");
1716 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1717 if (err)
1718 goto done;
1720 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1721 const char *refname = got_ref_get_name(re->ref);
1723 if (!remote->mirror_references) {
1724 if (strncmp(refname, remote_namespace,
1725 strlen(remote_namespace)) == 0) {
1726 if (strcmp(refname + strlen(remote_namespace),
1727 GOT_REF_HEAD) == 0)
1728 continue;
1729 if (asprintf(&local_refname, "refs/heads/%s",
1730 refname + strlen(remote_namespace)) == -1) {
1731 err = got_error_from_errno("asprintf");
1732 goto done;
1734 } else if (strncmp(refname, "refs/tags/", 10) != 0)
1735 continue;
1738 TAILQ_FOREACH(pe, their_refs, entry) {
1739 if (strcmp(local_refname, pe->path) == 0)
1740 break;
1742 if (pe != NULL)
1743 continue;
1745 TAILQ_FOREACH(pe, their_symrefs, entry) {
1746 if (strcmp(local_refname, pe->path) == 0)
1747 break;
1749 if (pe != NULL)
1750 continue;
1752 err = delete_missing_ref(re->ref, verbosity, repo);
1753 if (err)
1754 break;
1756 if (local_refname) {
1757 struct got_reference *ref;
1758 err = got_ref_open(&ref, repo, local_refname, 1);
1759 if (err) {
1760 if (err->code != GOT_ERR_NOT_REF)
1761 break;
1762 free(local_refname);
1763 local_refname = NULL;
1764 continue;
1766 err = delete_missing_ref(ref, verbosity, repo);
1767 if (err)
1768 break;
1769 unlock_err = got_ref_unlock(ref);
1770 got_ref_close(ref);
1771 if (unlock_err && err == NULL) {
1772 err = unlock_err;
1773 break;
1776 free(local_refname);
1777 local_refname = NULL;
1780 done:
1781 free(remote_namespace);
1782 free(local_refname);
1783 return err;
1786 static const struct got_error *
1787 update_wanted_ref(const char *refname, struct got_object_id *id,
1788 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1790 const struct got_error *err, *unlock_err;
1791 char *remote_refname;
1792 struct got_reference *ref;
1794 if (strncmp("refs/", refname, 5) == 0)
1795 refname += 5;
1797 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1798 remote_repo_name, refname) == -1)
1799 return got_error_from_errno("asprintf");
1801 err = got_ref_open(&ref, repo, remote_refname, 1);
1802 if (err) {
1803 if (err->code != GOT_ERR_NOT_REF)
1804 goto done;
1805 err = create_ref(remote_refname, id, verbosity, repo);
1806 } else {
1807 err = update_ref(ref, id, 0, verbosity, repo);
1808 unlock_err = got_ref_unlock(ref);
1809 if (unlock_err && err == NULL)
1810 err = unlock_err;
1811 got_ref_close(ref);
1813 done:
1814 free(remote_refname);
1815 return err;
1818 static const struct got_error *
1819 cmd_fetch(int argc, char *argv[])
1821 const struct got_error *error = NULL, *unlock_err;
1822 char *cwd = NULL, *repo_path = NULL;
1823 const char *remote_name;
1824 char *proto = NULL, *host = NULL, *port = NULL;
1825 char *repo_name = NULL, *server_path = NULL;
1826 const struct got_remote_repo *remotes, *remote = NULL;
1827 int nremotes;
1828 char *id_str = NULL;
1829 struct got_repository *repo = NULL;
1830 struct got_worktree *worktree = NULL;
1831 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
1832 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1833 struct got_pathlist_entry *pe;
1834 struct got_object_id *pack_hash = NULL;
1835 int i, ch, fetchfd = -1, fetchstatus;
1836 pid_t fetchpid = -1;
1837 struct got_fetch_progress_arg fpa;
1838 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
1839 int delete_refs = 0, replace_tags = 0;
1841 TAILQ_INIT(&refs);
1842 TAILQ_INIT(&symrefs);
1843 TAILQ_INIT(&wanted_branches);
1844 TAILQ_INIT(&wanted_refs);
1846 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
1847 switch (ch) {
1848 case 'a':
1849 fetch_all_branches = 1;
1850 break;
1851 case 'b':
1852 error = got_pathlist_append(&wanted_branches,
1853 optarg, NULL);
1854 if (error)
1855 return error;
1856 break;
1857 case 'd':
1858 delete_refs = 1;
1859 break;
1860 case 'l':
1861 list_refs_only = 1;
1862 break;
1863 case 'r':
1864 repo_path = realpath(optarg, NULL);
1865 if (repo_path == NULL)
1866 return got_error_from_errno2("realpath",
1867 optarg);
1868 got_path_strip_trailing_slashes(repo_path);
1869 break;
1870 case 't':
1871 replace_tags = 1;
1872 break;
1873 case 'v':
1874 if (verbosity < 0)
1875 verbosity = 0;
1876 else if (verbosity < 3)
1877 verbosity++;
1878 break;
1879 case 'q':
1880 verbosity = -1;
1881 break;
1882 case 'R':
1883 error = got_pathlist_append(&wanted_refs,
1884 optarg, NULL);
1885 if (error)
1886 return error;
1887 break;
1888 default:
1889 usage_fetch();
1890 break;
1893 argc -= optind;
1894 argv += optind;
1896 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1897 errx(1, "-a and -b options are mutually exclusive");
1898 if (list_refs_only) {
1899 if (!TAILQ_EMPTY(&wanted_branches))
1900 errx(1, "-l and -b options are mutually exclusive");
1901 if (fetch_all_branches)
1902 errx(1, "-l and -a options are mutually exclusive");
1903 if (delete_refs)
1904 errx(1, "-l and -d options are mutually exclusive");
1905 if (verbosity == -1)
1906 errx(1, "-l and -q options are mutually exclusive");
1909 if (argc == 0)
1910 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
1911 else if (argc == 1)
1912 remote_name = argv[0];
1913 else
1914 usage_fetch();
1916 cwd = getcwd(NULL, 0);
1917 if (cwd == NULL) {
1918 error = got_error_from_errno("getcwd");
1919 goto done;
1922 if (repo_path == NULL) {
1923 error = got_worktree_open(&worktree, cwd);
1924 if (error && error->code != GOT_ERR_NOT_WORKTREE)
1925 goto done;
1926 else
1927 error = NULL;
1928 if (worktree) {
1929 repo_path =
1930 strdup(got_worktree_get_repo_path(worktree));
1931 if (repo_path == NULL)
1932 error = got_error_from_errno("strdup");
1933 if (error)
1934 goto done;
1935 } else {
1936 repo_path = strdup(cwd);
1937 if (repo_path == NULL) {
1938 error = got_error_from_errno("strdup");
1939 goto done;
1944 error = got_repo_open(&repo, repo_path, NULL);
1945 if (error)
1946 goto done;
1948 if (worktree) {
1949 worktree_conf = got_worktree_get_gotconfig(worktree);
1950 if (worktree_conf) {
1951 got_gotconfig_get_remotes(&nremotes, &remotes,
1952 worktree_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 repo_conf = got_repo_get_gotconfig(repo);
1962 if (repo_conf) {
1963 got_gotconfig_get_remotes(&nremotes, &remotes,
1964 repo_conf);
1965 for (i = 0; i < nremotes; i++) {
1966 remote = &remotes[i];
1967 if (strcmp(remote->name, remote_name) == 0)
1968 break;
1972 if (remote == NULL) {
1973 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
1974 for (i = 0; i < nremotes; i++) {
1975 remote = &remotes[i];
1976 if (strcmp(remote->name, remote_name) == 0)
1977 break;
1980 if (remote == NULL) {
1981 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
1982 goto done;
1985 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1986 &repo_name, remote->url);
1987 if (error)
1988 goto done;
1990 if (strcmp(proto, "git") == 0) {
1991 #ifndef PROFILE
1992 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1993 "sendfd dns inet unveil", NULL) == -1)
1994 err(1, "pledge");
1995 #endif
1996 } else if (strcmp(proto, "git+ssh") == 0 ||
1997 strcmp(proto, "ssh") == 0) {
1998 #ifndef PROFILE
1999 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2000 "sendfd unveil", NULL) == -1)
2001 err(1, "pledge");
2002 #endif
2003 } else if (strcmp(proto, "http") == 0 ||
2004 strcmp(proto, "git+http") == 0) {
2005 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2006 goto done;
2007 } else {
2008 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2009 goto done;
2012 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
2013 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
2014 error = got_error_from_errno2("unveil",
2015 GOT_FETCH_PATH_SSH);
2016 goto done;
2019 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2020 if (error)
2021 goto done;
2023 if (verbosity >= 0)
2024 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2025 port ? ":" : "", port ? port : "");
2027 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2028 server_path, verbosity);
2029 if (error)
2030 goto done;
2032 fpa.last_scaled_size[0] = '\0';
2033 fpa.last_p_indexed = -1;
2034 fpa.last_p_resolved = -1;
2035 fpa.verbosity = verbosity;
2036 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2037 remote->mirror_references, fetch_all_branches, &wanted_branches,
2038 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2039 fetch_progress, &fpa);
2040 if (error)
2041 goto done;
2043 if (list_refs_only) {
2044 error = list_remote_refs(&symrefs, &refs);
2045 goto done;
2048 if (pack_hash == NULL) {
2049 if (verbosity >= 0)
2050 printf("Already up-to-date\n");
2051 } else if (verbosity >= 0) {
2052 error = got_object_id_str(&id_str, pack_hash);
2053 if (error)
2054 goto done;
2055 printf("\nFetched %s.pack\n", id_str);
2056 free(id_str);
2057 id_str = NULL;
2060 /* Update references provided with the pack file. */
2061 TAILQ_FOREACH(pe, &refs, entry) {
2062 const char *refname = pe->path;
2063 struct got_object_id *id = pe->data;
2064 struct got_reference *ref;
2065 char *remote_refname;
2067 if (is_wanted_ref(&wanted_refs, refname) &&
2068 !remote->mirror_references) {
2069 error = update_wanted_ref(refname, id,
2070 remote->name, verbosity, repo);
2071 if (error)
2072 goto done;
2073 continue;
2076 if (remote->mirror_references ||
2077 strncmp("refs/tags/", refname, 10) == 0) {
2078 error = got_ref_open(&ref, repo, refname, 1);
2079 if (error) {
2080 if (error->code != GOT_ERR_NOT_REF)
2081 goto done;
2082 error = create_ref(refname, id, verbosity,
2083 repo);
2084 if (error)
2085 goto done;
2086 } else {
2087 error = update_ref(ref, id, replace_tags,
2088 verbosity, repo);
2089 unlock_err = got_ref_unlock(ref);
2090 if (unlock_err && error == NULL)
2091 error = unlock_err;
2092 got_ref_close(ref);
2093 if (error)
2094 goto done;
2096 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2097 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2098 remote_name, refname + 11) == -1) {
2099 error = got_error_from_errno("asprintf");
2100 goto done;
2103 error = got_ref_open(&ref, repo, remote_refname, 1);
2104 if (error) {
2105 if (error->code != GOT_ERR_NOT_REF)
2106 goto done;
2107 error = create_ref(remote_refname, id,
2108 verbosity, repo);
2109 if (error)
2110 goto done;
2111 } else {
2112 error = update_ref(ref, id, replace_tags,
2113 verbosity, repo);
2114 unlock_err = got_ref_unlock(ref);
2115 if (unlock_err && error == NULL)
2116 error = unlock_err;
2117 got_ref_close(ref);
2118 if (error)
2119 goto done;
2122 /* Also create a local branch if none exists yet. */
2123 error = got_ref_open(&ref, repo, refname, 1);
2124 if (error) {
2125 if (error->code != GOT_ERR_NOT_REF)
2126 goto done;
2127 error = create_ref(refname, id, verbosity,
2128 repo);
2129 if (error)
2130 goto done;
2131 } else {
2132 unlock_err = got_ref_unlock(ref);
2133 if (unlock_err && error == NULL)
2134 error = unlock_err;
2135 got_ref_close(ref);
2139 if (delete_refs) {
2140 error = delete_missing_refs(&refs, &symrefs, remote,
2141 verbosity, repo);
2142 if (error)
2143 goto done;
2146 if (!remote->mirror_references) {
2147 /* Update remote HEAD reference if the server provided one. */
2148 TAILQ_FOREACH(pe, &symrefs, entry) {
2149 struct got_reference *target_ref;
2150 const char *refname = pe->path;
2151 const char *target = pe->data;
2152 char *remote_refname = NULL, *remote_target = NULL;
2154 if (strcmp(refname, GOT_REF_HEAD) != 0)
2155 continue;
2157 if (strncmp("refs/heads/", target, 11) != 0)
2158 continue;
2160 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2161 remote->name, refname) == -1) {
2162 error = got_error_from_errno("asprintf");
2163 goto done;
2165 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2166 remote->name, target + 11) == -1) {
2167 error = got_error_from_errno("asprintf");
2168 free(remote_refname);
2169 goto done;
2172 error = got_ref_open(&target_ref, repo, remote_target,
2173 0);
2174 if (error) {
2175 free(remote_refname);
2176 free(remote_target);
2177 if (error->code == GOT_ERR_NOT_REF) {
2178 error = NULL;
2179 continue;
2181 goto done;
2183 error = update_symref(remote_refname, target_ref,
2184 verbosity, repo);
2185 free(remote_refname);
2186 free(remote_target);
2187 got_ref_close(target_ref);
2188 if (error)
2189 goto done;
2192 done:
2193 if (fetchpid > 0) {
2194 if (kill(fetchpid, SIGTERM) == -1)
2195 error = got_error_from_errno("kill");
2196 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2197 error = got_error_from_errno("waitpid");
2199 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2200 error = got_error_from_errno("close");
2201 if (repo)
2202 got_repo_close(repo);
2203 if (worktree)
2204 got_worktree_close(worktree);
2205 TAILQ_FOREACH(pe, &refs, entry) {
2206 free((void *)pe->path);
2207 free(pe->data);
2209 got_pathlist_free(&refs);
2210 TAILQ_FOREACH(pe, &symrefs, entry) {
2211 free((void *)pe->path);
2212 free(pe->data);
2214 got_pathlist_free(&symrefs);
2215 got_pathlist_free(&wanted_branches);
2216 got_pathlist_free(&wanted_refs);
2217 free(id_str);
2218 free(cwd);
2219 free(repo_path);
2220 free(pack_hash);
2221 free(proto);
2222 free(host);
2223 free(port);
2224 free(server_path);
2225 free(repo_name);
2226 return error;
2230 __dead static void
2231 usage_checkout(void)
2233 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2234 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2235 exit(1);
2238 static void
2239 show_worktree_base_ref_warning(void)
2241 fprintf(stderr, "%s: warning: could not create a reference "
2242 "to the work tree's base commit; the commit could be "
2243 "garbage-collected by Git; making the repository "
2244 "writable and running 'got update' will prevent this\n",
2245 getprogname());
2248 struct got_checkout_progress_arg {
2249 const char *worktree_path;
2250 int had_base_commit_ref_error;
2253 static const struct got_error *
2254 checkout_progress(void *arg, unsigned char status, const char *path)
2256 struct got_checkout_progress_arg *a = arg;
2258 /* Base commit bump happens silently. */
2259 if (status == GOT_STATUS_BUMP_BASE)
2260 return NULL;
2262 if (status == GOT_STATUS_BASE_REF_ERR) {
2263 a->had_base_commit_ref_error = 1;
2264 return NULL;
2267 while (path[0] == '/')
2268 path++;
2270 printf("%c %s/%s\n", status, a->worktree_path, path);
2271 return NULL;
2274 static const struct got_error *
2275 check_cancelled(void *arg)
2277 if (sigint_received || sigpipe_received)
2278 return got_error(GOT_ERR_CANCELLED);
2279 return NULL;
2282 static const struct got_error *
2283 check_linear_ancestry(struct got_object_id *commit_id,
2284 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2285 struct got_repository *repo)
2287 const struct got_error *err = NULL;
2288 struct got_object_id *yca_id;
2290 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2291 commit_id, base_commit_id, repo, check_cancelled, NULL);
2292 if (err)
2293 return err;
2295 if (yca_id == NULL)
2296 return got_error(GOT_ERR_ANCESTRY);
2299 * Require a straight line of history between the target commit
2300 * and the work tree's base commit.
2302 * Non-linear situations such as this require a rebase:
2304 * (commit) D F (base_commit)
2305 * \ /
2306 * C E
2307 * \ /
2308 * B (yca)
2309 * |
2310 * A
2312 * 'got update' only handles linear cases:
2313 * Update forwards in time: A (base/yca) - B - C - D (commit)
2314 * Update backwards in time: D (base) - C - B - A (commit/yca)
2316 if (allow_forwards_in_time_only) {
2317 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2318 return got_error(GOT_ERR_ANCESTRY);
2319 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2320 got_object_id_cmp(base_commit_id, yca_id) != 0)
2321 return got_error(GOT_ERR_ANCESTRY);
2323 free(yca_id);
2324 return NULL;
2327 static const struct got_error *
2328 check_same_branch(struct got_object_id *commit_id,
2329 struct got_reference *head_ref, struct got_object_id *yca_id,
2330 struct got_repository *repo)
2332 const struct got_error *err = NULL;
2333 struct got_commit_graph *graph = NULL;
2334 struct got_object_id *head_commit_id = NULL;
2335 int is_same_branch = 0;
2337 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2338 if (err)
2339 goto done;
2341 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2342 is_same_branch = 1;
2343 goto done;
2345 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2346 is_same_branch = 1;
2347 goto done;
2350 err = got_commit_graph_open(&graph, "/", 1);
2351 if (err)
2352 goto done;
2354 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2355 check_cancelled, NULL);
2356 if (err)
2357 goto done;
2359 for (;;) {
2360 struct got_object_id *id;
2361 err = got_commit_graph_iter_next(&id, graph, repo,
2362 check_cancelled, NULL);
2363 if (err) {
2364 if (err->code == GOT_ERR_ITER_COMPLETED)
2365 err = NULL;
2366 break;
2369 if (id) {
2370 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2371 break;
2372 if (got_object_id_cmp(id, commit_id) == 0) {
2373 is_same_branch = 1;
2374 break;
2378 done:
2379 if (graph)
2380 got_commit_graph_close(graph);
2381 free(head_commit_id);
2382 if (!err && !is_same_branch)
2383 err = got_error(GOT_ERR_ANCESTRY);
2384 return err;
2387 static const struct got_error *
2388 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2390 static char msg[512];
2391 const char *branch_name;
2393 if (got_ref_is_symbolic(ref))
2394 branch_name = got_ref_get_symref_target(ref);
2395 else
2396 branch_name = got_ref_get_name(ref);
2398 if (strncmp("refs/heads/", branch_name, 11) == 0)
2399 branch_name += 11;
2401 snprintf(msg, sizeof(msg),
2402 "target commit is not contained in branch '%s'; "
2403 "the branch to use must be specified with -b; "
2404 "if necessary a new branch can be created for "
2405 "this commit with 'got branch -c %s BRANCH_NAME'",
2406 branch_name, commit_id_str);
2408 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2411 static const struct got_error *
2412 cmd_checkout(int argc, char *argv[])
2414 const struct got_error *error = NULL;
2415 struct got_repository *repo = NULL;
2416 struct got_reference *head_ref = NULL;
2417 struct got_worktree *worktree = NULL;
2418 char *repo_path = NULL;
2419 char *worktree_path = NULL;
2420 const char *path_prefix = "";
2421 const char *branch_name = GOT_REF_HEAD;
2422 char *commit_id_str = NULL;
2423 char *cwd = NULL, *path = NULL;
2424 int ch, same_path_prefix, allow_nonempty = 0;
2425 struct got_pathlist_head paths;
2426 struct got_checkout_progress_arg cpa;
2428 TAILQ_INIT(&paths);
2430 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2431 switch (ch) {
2432 case 'b':
2433 branch_name = optarg;
2434 break;
2435 case 'c':
2436 commit_id_str = strdup(optarg);
2437 if (commit_id_str == NULL)
2438 return got_error_from_errno("strdup");
2439 break;
2440 case 'E':
2441 allow_nonempty = 1;
2442 break;
2443 case 'p':
2444 path_prefix = optarg;
2445 break;
2446 default:
2447 usage_checkout();
2448 /* NOTREACHED */
2452 argc -= optind;
2453 argv += optind;
2455 #ifndef PROFILE
2456 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2457 "unveil", NULL) == -1)
2458 err(1, "pledge");
2459 #endif
2460 if (argc == 1) {
2461 char *base, *dotgit;
2462 repo_path = realpath(argv[0], NULL);
2463 if (repo_path == NULL)
2464 return got_error_from_errno2("realpath", argv[0]);
2465 cwd = getcwd(NULL, 0);
2466 if (cwd == NULL) {
2467 error = got_error_from_errno("getcwd");
2468 goto done;
2470 if (path_prefix[0])
2471 path = strdup(path_prefix);
2472 else
2473 path = strdup(repo_path);
2474 if (path == NULL) {
2475 error = got_error_from_errno("strdup");
2476 goto done;
2478 base = basename(path);
2479 if (base == NULL) {
2480 error = got_error_from_errno2("basename", path);
2481 goto done;
2483 dotgit = strstr(base, ".git");
2484 if (dotgit)
2485 *dotgit = '\0';
2486 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2487 error = got_error_from_errno("asprintf");
2488 goto done;
2490 } else if (argc == 2) {
2491 repo_path = realpath(argv[0], NULL);
2492 if (repo_path == NULL) {
2493 error = got_error_from_errno2("realpath", argv[0]);
2494 goto done;
2496 worktree_path = realpath(argv[1], NULL);
2497 if (worktree_path == NULL) {
2498 if (errno != ENOENT) {
2499 error = got_error_from_errno2("realpath",
2500 argv[1]);
2501 goto done;
2503 worktree_path = strdup(argv[1]);
2504 if (worktree_path == NULL) {
2505 error = got_error_from_errno("strdup");
2506 goto done;
2509 } else
2510 usage_checkout();
2512 got_path_strip_trailing_slashes(repo_path);
2513 got_path_strip_trailing_slashes(worktree_path);
2515 error = got_repo_open(&repo, repo_path, NULL);
2516 if (error != NULL)
2517 goto done;
2519 /* Pre-create work tree path for unveil(2) */
2520 error = got_path_mkdir(worktree_path);
2521 if (error) {
2522 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2523 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2524 goto done;
2525 if (!allow_nonempty &&
2526 !got_path_dir_is_empty(worktree_path)) {
2527 error = got_error_path(worktree_path,
2528 GOT_ERR_DIR_NOT_EMPTY);
2529 goto done;
2533 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2534 if (error)
2535 goto done;
2537 error = got_ref_open(&head_ref, repo, branch_name, 0);
2538 if (error != NULL)
2539 goto done;
2541 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2542 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2543 goto done;
2545 error = got_worktree_open(&worktree, worktree_path);
2546 if (error != NULL)
2547 goto done;
2549 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2550 path_prefix);
2551 if (error != NULL)
2552 goto done;
2553 if (!same_path_prefix) {
2554 error = got_error(GOT_ERR_PATH_PREFIX);
2555 goto done;
2558 if (commit_id_str) {
2559 struct got_object_id *commit_id;
2560 error = got_repo_match_object_id(&commit_id, NULL,
2561 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2562 if (error)
2563 goto done;
2564 error = check_linear_ancestry(commit_id,
2565 got_worktree_get_base_commit_id(worktree), 0, repo);
2566 if (error != NULL) {
2567 free(commit_id);
2568 if (error->code == GOT_ERR_ANCESTRY) {
2569 error = checkout_ancestry_error(
2570 head_ref, commit_id_str);
2572 goto done;
2574 error = check_same_branch(commit_id, head_ref, NULL, repo);
2575 if (error) {
2576 if (error->code == GOT_ERR_ANCESTRY) {
2577 error = checkout_ancestry_error(
2578 head_ref, commit_id_str);
2580 goto done;
2582 error = got_worktree_set_base_commit_id(worktree, repo,
2583 commit_id);
2584 free(commit_id);
2585 if (error)
2586 goto done;
2589 error = got_pathlist_append(&paths, "", NULL);
2590 if (error)
2591 goto done;
2592 cpa.worktree_path = worktree_path;
2593 cpa.had_base_commit_ref_error = 0;
2594 error = got_worktree_checkout_files(worktree, &paths, repo,
2595 checkout_progress, &cpa, check_cancelled, NULL);
2596 if (error != NULL)
2597 goto done;
2599 printf("Now shut up and hack\n");
2600 if (cpa.had_base_commit_ref_error)
2601 show_worktree_base_ref_warning();
2602 done:
2603 got_pathlist_free(&paths);
2604 free(commit_id_str);
2605 free(repo_path);
2606 free(worktree_path);
2607 free(cwd);
2608 free(path);
2609 return error;
2612 struct got_update_progress_arg {
2613 int did_something;
2614 int conflicts;
2615 int obstructed;
2616 int not_updated;
2619 void
2620 print_update_progress_stats(struct got_update_progress_arg *upa)
2622 if (!upa->did_something)
2623 return;
2625 if (upa->conflicts > 0)
2626 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2627 if (upa->obstructed > 0)
2628 printf("File paths obstructed by a non-regular file: %d\n",
2629 upa->obstructed);
2630 if (upa->not_updated > 0)
2631 printf("Files not updated because of existing merge "
2632 "conflicts: %d\n", upa->not_updated);
2635 __dead static void
2636 usage_update(void)
2638 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2639 getprogname());
2640 exit(1);
2643 static const struct got_error *
2644 update_progress(void *arg, unsigned char status, const char *path)
2646 struct got_update_progress_arg *upa = arg;
2648 if (status == GOT_STATUS_EXISTS ||
2649 status == GOT_STATUS_BASE_REF_ERR)
2650 return NULL;
2652 upa->did_something = 1;
2654 /* Base commit bump happens silently. */
2655 if (status == GOT_STATUS_BUMP_BASE)
2656 return NULL;
2658 if (status == GOT_STATUS_CONFLICT)
2659 upa->conflicts++;
2660 if (status == GOT_STATUS_OBSTRUCTED)
2661 upa->obstructed++;
2662 if (status == GOT_STATUS_CANNOT_UPDATE)
2663 upa->not_updated++;
2665 while (path[0] == '/')
2666 path++;
2667 printf("%c %s\n", status, path);
2668 return NULL;
2671 static const struct got_error *
2672 switch_head_ref(struct got_reference *head_ref,
2673 struct got_object_id *commit_id, struct got_worktree *worktree,
2674 struct got_repository *repo)
2676 const struct got_error *err = NULL;
2677 char *base_id_str;
2678 int ref_has_moved = 0;
2680 /* Trivial case: switching between two different references. */
2681 if (strcmp(got_ref_get_name(head_ref),
2682 got_worktree_get_head_ref_name(worktree)) != 0) {
2683 printf("Switching work tree from %s to %s\n",
2684 got_worktree_get_head_ref_name(worktree),
2685 got_ref_get_name(head_ref));
2686 return got_worktree_set_head_ref(worktree, head_ref);
2689 err = check_linear_ancestry(commit_id,
2690 got_worktree_get_base_commit_id(worktree), 0, repo);
2691 if (err) {
2692 if (err->code != GOT_ERR_ANCESTRY)
2693 return err;
2694 ref_has_moved = 1;
2696 if (!ref_has_moved)
2697 return NULL;
2699 /* Switching to a rebased branch with the same reference name. */
2700 err = got_object_id_str(&base_id_str,
2701 got_worktree_get_base_commit_id(worktree));
2702 if (err)
2703 return err;
2704 printf("Reference %s now points at a different branch\n",
2705 got_worktree_get_head_ref_name(worktree));
2706 printf("Switching work tree from %s to %s\n", base_id_str,
2707 got_worktree_get_head_ref_name(worktree));
2708 return NULL;
2711 static const struct got_error *
2712 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2714 const struct got_error *err;
2715 int in_progress;
2717 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2718 if (err)
2719 return err;
2720 if (in_progress)
2721 return got_error(GOT_ERR_REBASING);
2723 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2724 if (err)
2725 return err;
2726 if (in_progress)
2727 return got_error(GOT_ERR_HISTEDIT_BUSY);
2729 return NULL;
2732 static const struct got_error *
2733 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2734 char *argv[], struct got_worktree *worktree)
2736 const struct got_error *err = NULL;
2737 char *path;
2738 int i;
2740 if (argc == 0) {
2741 path = strdup("");
2742 if (path == NULL)
2743 return got_error_from_errno("strdup");
2744 return got_pathlist_append(paths, path, NULL);
2747 for (i = 0; i < argc; i++) {
2748 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2749 if (err)
2750 break;
2751 err = got_pathlist_append(paths, path, NULL);
2752 if (err) {
2753 free(path);
2754 break;
2758 return err;
2761 static const struct got_error *
2762 wrap_not_worktree_error(const struct got_error *orig_err,
2763 const char *cmdname, const char *path)
2765 const struct got_error *err;
2766 struct got_repository *repo;
2767 static char msg[512];
2769 err = got_repo_open(&repo, path, NULL);
2770 if (err)
2771 return orig_err;
2773 snprintf(msg, sizeof(msg),
2774 "'got %s' needs a work tree in addition to a git repository\n"
2775 "Work trees can be checked out from this Git repository with "
2776 "'got checkout'.\n"
2777 "The got(1) manual page contains more information.", cmdname);
2778 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2779 got_repo_close(repo);
2780 return err;
2783 static const struct got_error *
2784 cmd_update(int argc, char *argv[])
2786 const struct got_error *error = NULL;
2787 struct got_repository *repo = NULL;
2788 struct got_worktree *worktree = NULL;
2789 char *worktree_path = NULL;
2790 struct got_object_id *commit_id = NULL;
2791 char *commit_id_str = NULL;
2792 const char *branch_name = NULL;
2793 struct got_reference *head_ref = NULL;
2794 struct got_pathlist_head paths;
2795 struct got_pathlist_entry *pe;
2796 int ch;
2797 struct got_update_progress_arg upa;
2799 TAILQ_INIT(&paths);
2801 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2802 switch (ch) {
2803 case 'b':
2804 branch_name = optarg;
2805 break;
2806 case 'c':
2807 commit_id_str = strdup(optarg);
2808 if (commit_id_str == NULL)
2809 return got_error_from_errno("strdup");
2810 break;
2811 default:
2812 usage_update();
2813 /* NOTREACHED */
2817 argc -= optind;
2818 argv += optind;
2820 #ifndef PROFILE
2821 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2822 "unveil", NULL) == -1)
2823 err(1, "pledge");
2824 #endif
2825 worktree_path = getcwd(NULL, 0);
2826 if (worktree_path == NULL) {
2827 error = got_error_from_errno("getcwd");
2828 goto done;
2830 error = got_worktree_open(&worktree, worktree_path);
2831 if (error) {
2832 if (error->code == GOT_ERR_NOT_WORKTREE)
2833 error = wrap_not_worktree_error(error, "update",
2834 worktree_path);
2835 goto done;
2838 error = check_rebase_or_histedit_in_progress(worktree);
2839 if (error)
2840 goto done;
2842 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
2843 NULL);
2844 if (error != NULL)
2845 goto done;
2847 error = apply_unveil(got_repo_get_path(repo), 0,
2848 got_worktree_get_root_path(worktree));
2849 if (error)
2850 goto done;
2852 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2853 if (error)
2854 goto done;
2856 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
2857 got_worktree_get_head_ref_name(worktree), 0);
2858 if (error != NULL)
2859 goto done;
2860 if (commit_id_str == NULL) {
2861 error = got_ref_resolve(&commit_id, repo, head_ref);
2862 if (error != NULL)
2863 goto done;
2864 error = got_object_id_str(&commit_id_str, commit_id);
2865 if (error != NULL)
2866 goto done;
2867 } else {
2868 error = got_repo_match_object_id(&commit_id, NULL,
2869 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2870 free(commit_id_str);
2871 commit_id_str = NULL;
2872 if (error)
2873 goto done;
2874 error = got_object_id_str(&commit_id_str, commit_id);
2875 if (error)
2876 goto done;
2879 if (branch_name) {
2880 struct got_object_id *head_commit_id;
2881 TAILQ_FOREACH(pe, &paths, entry) {
2882 if (pe->path_len == 0)
2883 continue;
2884 error = got_error_msg(GOT_ERR_BAD_PATH,
2885 "switching between branches requires that "
2886 "the entire work tree gets updated");
2887 goto done;
2889 error = got_ref_resolve(&head_commit_id, repo, head_ref);
2890 if (error)
2891 goto done;
2892 error = check_linear_ancestry(commit_id, head_commit_id, 0,
2893 repo);
2894 free(head_commit_id);
2895 if (error != NULL)
2896 goto done;
2897 error = check_same_branch(commit_id, head_ref, NULL, repo);
2898 if (error)
2899 goto done;
2900 error = switch_head_ref(head_ref, commit_id, worktree, repo);
2901 if (error)
2902 goto done;
2903 } else {
2904 error = check_linear_ancestry(commit_id,
2905 got_worktree_get_base_commit_id(worktree), 0, repo);
2906 if (error != NULL) {
2907 if (error->code == GOT_ERR_ANCESTRY)
2908 error = got_error(GOT_ERR_BRANCH_MOVED);
2909 goto done;
2911 error = check_same_branch(commit_id, head_ref, NULL, repo);
2912 if (error)
2913 goto done;
2916 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
2917 commit_id) != 0) {
2918 error = got_worktree_set_base_commit_id(worktree, repo,
2919 commit_id);
2920 if (error)
2921 goto done;
2924 memset(&upa, 0, sizeof(upa));
2925 error = got_worktree_checkout_files(worktree, &paths, repo,
2926 update_progress, &upa, check_cancelled, NULL);
2927 if (error != NULL)
2928 goto done;
2930 if (upa.did_something)
2931 printf("Updated to commit %s\n", commit_id_str);
2932 else
2933 printf("Already up-to-date\n");
2934 print_update_progress_stats(&upa);
2935 done:
2936 free(worktree_path);
2937 TAILQ_FOREACH(pe, &paths, entry)
2938 free((char *)pe->path);
2939 got_pathlist_free(&paths);
2940 free(commit_id);
2941 free(commit_id_str);
2942 return error;
2945 static const struct got_error *
2946 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
2947 const char *path, int diff_context, int ignore_whitespace,
2948 struct got_repository *repo)
2950 const struct got_error *err = NULL;
2951 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
2953 if (blob_id1) {
2954 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
2955 if (err)
2956 goto done;
2959 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
2960 if (err)
2961 goto done;
2963 while (path[0] == '/')
2964 path++;
2965 err = got_diff_blob(blob1, blob2, path, path, diff_context,
2966 ignore_whitespace, stdout);
2967 done:
2968 if (blob1)
2969 got_object_blob_close(blob1);
2970 got_object_blob_close(blob2);
2971 return err;
2974 static const struct got_error *
2975 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
2976 const char *path, int diff_context, int ignore_whitespace,
2977 struct got_repository *repo)
2979 const struct got_error *err = NULL;
2980 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
2981 struct got_diff_blob_output_unidiff_arg arg;
2983 if (tree_id1) {
2984 err = got_object_open_as_tree(&tree1, repo, tree_id1);
2985 if (err)
2986 goto done;
2989 err = got_object_open_as_tree(&tree2, repo, tree_id2);
2990 if (err)
2991 goto done;
2993 arg.diff_context = diff_context;
2994 arg.ignore_whitespace = ignore_whitespace;
2995 arg.outfile = stdout;
2996 while (path[0] == '/')
2997 path++;
2998 err = got_diff_tree(tree1, tree2, path, path, repo,
2999 got_diff_blob_output_unidiff, &arg, 1);
3000 done:
3001 if (tree1)
3002 got_object_tree_close(tree1);
3003 if (tree2)
3004 got_object_tree_close(tree2);
3005 return err;
3008 static const struct got_error *
3009 get_changed_paths(struct got_pathlist_head *paths,
3010 struct got_commit_object *commit, struct got_repository *repo)
3012 const struct got_error *err = NULL;
3013 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3014 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3015 struct got_object_qid *qid;
3017 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3018 if (qid != NULL) {
3019 struct got_commit_object *pcommit;
3020 err = got_object_open_as_commit(&pcommit, repo,
3021 qid->id);
3022 if (err)
3023 return err;
3025 tree_id1 = got_object_commit_get_tree_id(pcommit);
3026 got_object_commit_close(pcommit);
3030 if (tree_id1) {
3031 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3032 if (err)
3033 goto done;
3036 tree_id2 = got_object_commit_get_tree_id(commit);
3037 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3038 if (err)
3039 goto done;
3041 err = got_diff_tree(tree1, tree2, "", "", repo,
3042 got_diff_tree_collect_changed_paths, paths, 0);
3043 done:
3044 if (tree1)
3045 got_object_tree_close(tree1);
3046 if (tree2)
3047 got_object_tree_close(tree2);
3048 return err;
3051 static const struct got_error *
3052 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3053 const char *path, int diff_context, struct got_repository *repo)
3055 const struct got_error *err = NULL;
3056 struct got_commit_object *pcommit = NULL;
3057 char *id_str1 = NULL, *id_str2 = NULL;
3058 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3059 struct got_object_qid *qid;
3061 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3062 if (qid != NULL) {
3063 err = got_object_open_as_commit(&pcommit, repo,
3064 qid->id);
3065 if (err)
3066 return err;
3069 if (path && path[0] != '\0') {
3070 int obj_type;
3071 err = got_object_id_by_path(&obj_id2, repo, id, path);
3072 if (err)
3073 goto done;
3074 err = got_object_id_str(&id_str2, obj_id2);
3075 if (err) {
3076 free(obj_id2);
3077 goto done;
3079 if (pcommit) {
3080 err = got_object_id_by_path(&obj_id1, repo,
3081 qid->id, path);
3082 if (err) {
3083 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3084 free(obj_id2);
3085 goto done;
3087 } else {
3088 err = got_object_id_str(&id_str1, obj_id1);
3089 if (err) {
3090 free(obj_id2);
3091 goto done;
3095 err = got_object_get_type(&obj_type, repo, obj_id2);
3096 if (err) {
3097 free(obj_id2);
3098 goto done;
3100 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3101 switch (obj_type) {
3102 case GOT_OBJ_TYPE_BLOB:
3103 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3104 0, repo);
3105 break;
3106 case GOT_OBJ_TYPE_TREE:
3107 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3108 0, repo);
3109 break;
3110 default:
3111 err = got_error(GOT_ERR_OBJ_TYPE);
3112 break;
3114 free(obj_id1);
3115 free(obj_id2);
3116 } else {
3117 obj_id2 = got_object_commit_get_tree_id(commit);
3118 err = got_object_id_str(&id_str2, obj_id2);
3119 if (err)
3120 goto done;
3121 obj_id1 = got_object_commit_get_tree_id(pcommit);
3122 err = got_object_id_str(&id_str1, obj_id1);
3123 if (err)
3124 goto done;
3125 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3126 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
3128 done:
3129 free(id_str1);
3130 free(id_str2);
3131 if (pcommit)
3132 got_object_commit_close(pcommit);
3133 return err;
3136 static char *
3137 get_datestr(time_t *time, char *datebuf)
3139 struct tm mytm, *tm;
3140 char *p, *s;
3142 tm = gmtime_r(time, &mytm);
3143 if (tm == NULL)
3144 return NULL;
3145 s = asctime_r(tm, datebuf);
3146 if (s == NULL)
3147 return NULL;
3148 p = strchr(s, '\n');
3149 if (p)
3150 *p = '\0';
3151 return s;
3154 static const struct got_error *
3155 match_logmsg(int *have_match, struct got_object_id *id,
3156 struct got_commit_object *commit, regex_t *regex)
3158 const struct got_error *err = NULL;
3159 regmatch_t regmatch;
3160 char *id_str = NULL, *logmsg = NULL;
3162 *have_match = 0;
3164 err = got_object_id_str(&id_str, id);
3165 if (err)
3166 return err;
3168 err = got_object_commit_get_logmsg(&logmsg, commit);
3169 if (err)
3170 goto done;
3172 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3173 *have_match = 1;
3174 done:
3175 free(id_str);
3176 free(logmsg);
3177 return err;
3180 static void
3181 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3182 regex_t *regex)
3184 regmatch_t regmatch;
3185 struct got_pathlist_entry *pe;
3187 *have_match = 0;
3189 TAILQ_FOREACH(pe, changed_paths, entry) {
3190 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3191 *have_match = 1;
3192 break;
3197 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3199 static const struct got_error *
3200 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3201 struct got_repository *repo, const char *path,
3202 struct got_pathlist_head *changed_paths, int show_patch,
3203 int diff_context, struct got_reflist_head *refs)
3205 const struct got_error *err = NULL;
3206 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3207 char datebuf[26];
3208 time_t committer_time;
3209 const char *author, *committer;
3210 char *refs_str = NULL;
3211 struct got_reflist_entry *re;
3213 SIMPLEQ_FOREACH(re, refs, entry) {
3214 char *s;
3215 const char *name;
3216 struct got_tag_object *tag = NULL;
3217 struct got_object_id *ref_id;
3218 int cmp;
3220 name = got_ref_get_name(re->ref);
3221 if (strcmp(name, GOT_REF_HEAD) == 0)
3222 continue;
3223 if (strncmp(name, "refs/", 5) == 0)
3224 name += 5;
3225 if (strncmp(name, "got/", 4) == 0)
3226 continue;
3227 if (strncmp(name, "heads/", 6) == 0)
3228 name += 6;
3229 if (strncmp(name, "remotes/", 8) == 0) {
3230 name += 8;
3231 s = strstr(name, "/" GOT_REF_HEAD);
3232 if (s != NULL && s[strlen(s)] == '\0')
3233 continue;
3235 err = got_ref_resolve(&ref_id, repo, re->ref);
3236 if (err)
3237 return err;
3238 if (strncmp(name, "tags/", 5) == 0) {
3239 err = got_object_open_as_tag(&tag, repo, ref_id);
3240 if (err) {
3241 if (err->code != GOT_ERR_OBJ_TYPE) {
3242 free(ref_id);
3243 return err;
3245 /* Ref points at something other than a tag. */
3246 err = NULL;
3247 tag = NULL;
3250 cmp = got_object_id_cmp(tag ?
3251 got_object_tag_get_object_id(tag) : ref_id, id);
3252 free(ref_id);
3253 if (tag)
3254 got_object_tag_close(tag);
3255 if (cmp != 0)
3256 continue;
3257 s = refs_str;
3258 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3259 name) == -1) {
3260 err = got_error_from_errno("asprintf");
3261 free(s);
3262 return err;
3264 free(s);
3266 err = got_object_id_str(&id_str, id);
3267 if (err)
3268 return err;
3270 printf(GOT_COMMIT_SEP_STR);
3271 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3272 refs_str ? refs_str : "", refs_str ? ")" : "");
3273 free(id_str);
3274 id_str = NULL;
3275 free(refs_str);
3276 refs_str = NULL;
3277 printf("from: %s\n", got_object_commit_get_author(commit));
3278 committer_time = got_object_commit_get_committer_time(commit);
3279 datestr = get_datestr(&committer_time, datebuf);
3280 if (datestr)
3281 printf("date: %s UTC\n", datestr);
3282 author = got_object_commit_get_author(commit);
3283 committer = got_object_commit_get_committer(commit);
3284 if (strcmp(author, committer) != 0)
3285 printf("via: %s\n", committer);
3286 if (got_object_commit_get_nparents(commit) > 1) {
3287 const struct got_object_id_queue *parent_ids;
3288 struct got_object_qid *qid;
3289 int n = 1;
3290 parent_ids = got_object_commit_get_parent_ids(commit);
3291 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3292 err = got_object_id_str(&id_str, qid->id);
3293 if (err)
3294 return err;
3295 printf("parent %d: %s\n", n++, id_str);
3296 free(id_str);
3300 err = got_object_commit_get_logmsg(&logmsg0, commit);
3301 if (err)
3302 return err;
3304 logmsg = logmsg0;
3305 do {
3306 line = strsep(&logmsg, "\n");
3307 if (line)
3308 printf(" %s\n", line);
3309 } while (line);
3310 free(logmsg0);
3312 if (changed_paths) {
3313 struct got_pathlist_entry *pe;
3314 TAILQ_FOREACH(pe, changed_paths, entry) {
3315 struct got_diff_changed_path *cp = pe->data;
3316 printf(" %c %s\n", cp->status, pe->path);
3318 printf("\n");
3320 if (show_patch) {
3321 err = print_patch(commit, id, path, diff_context, repo);
3322 if (err == 0)
3323 printf("\n");
3326 if (fflush(stdout) != 0 && err == NULL)
3327 err = got_error_from_errno("fflush");
3328 return err;
3331 static const struct got_error *
3332 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3333 struct got_repository *repo, const char *path, int show_changed_paths,
3334 int show_patch, const char *search_pattern, int diff_context, int limit,
3335 int log_branches, int reverse_display_order, struct got_reflist_head *refs)
3337 const struct got_error *err;
3338 struct got_commit_graph *graph;
3339 regex_t regex;
3340 int have_match;
3341 struct got_object_id_queue reversed_commits;
3342 struct got_object_qid *qid;
3343 struct got_commit_object *commit;
3344 struct got_pathlist_head changed_paths;
3345 struct got_pathlist_entry *pe;
3347 SIMPLEQ_INIT(&reversed_commits);
3348 TAILQ_INIT(&changed_paths);
3350 if (search_pattern && regcomp(&regex, search_pattern,
3351 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3352 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3354 err = got_commit_graph_open(&graph, path, !log_branches);
3355 if (err)
3356 return err;
3357 err = got_commit_graph_iter_start(graph, root_id, repo,
3358 check_cancelled, NULL);
3359 if (err)
3360 goto done;
3361 for (;;) {
3362 struct got_object_id *id;
3364 if (sigint_received || sigpipe_received)
3365 break;
3367 err = got_commit_graph_iter_next(&id, graph, repo,
3368 check_cancelled, NULL);
3369 if (err) {
3370 if (err->code == GOT_ERR_ITER_COMPLETED)
3371 err = NULL;
3372 break;
3374 if (id == NULL)
3375 break;
3377 err = got_object_open_as_commit(&commit, repo, id);
3378 if (err)
3379 break;
3381 if (show_changed_paths && !reverse_display_order) {
3382 err = get_changed_paths(&changed_paths, commit, repo);
3383 if (err)
3384 break;
3387 if (search_pattern) {
3388 err = match_logmsg(&have_match, id, commit, &regex);
3389 if (err) {
3390 got_object_commit_close(commit);
3391 break;
3393 if (have_match == 0 && show_changed_paths)
3394 match_changed_paths(&have_match,
3395 &changed_paths, &regex);
3396 if (have_match == 0) {
3397 got_object_commit_close(commit);
3398 TAILQ_FOREACH(pe, &changed_paths, entry) {
3399 free((char *)pe->path);
3400 free(pe->data);
3402 got_pathlist_free(&changed_paths);
3403 continue;
3407 if (reverse_display_order) {
3408 err = got_object_qid_alloc(&qid, id);
3409 if (err)
3410 break;
3411 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3412 got_object_commit_close(commit);
3413 } else {
3414 err = print_commit(commit, id, repo, path,
3415 show_changed_paths ? &changed_paths : NULL,
3416 show_patch, diff_context, refs);
3417 got_object_commit_close(commit);
3418 if (err)
3419 break;
3421 if ((limit && --limit == 0) ||
3422 (end_id && got_object_id_cmp(id, end_id) == 0))
3423 break;
3425 TAILQ_FOREACH(pe, &changed_paths, entry) {
3426 free((char *)pe->path);
3427 free(pe->data);
3429 got_pathlist_free(&changed_paths);
3431 if (reverse_display_order) {
3432 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3433 err = got_object_open_as_commit(&commit, repo, qid->id);
3434 if (err)
3435 break;
3436 if (show_changed_paths) {
3437 err = get_changed_paths(&changed_paths,
3438 commit, repo);
3439 if (err)
3440 break;
3442 err = print_commit(commit, qid->id, repo, path,
3443 show_changed_paths ? &changed_paths : NULL,
3444 show_patch, diff_context, refs);
3445 got_object_commit_close(commit);
3446 if (err)
3447 break;
3448 TAILQ_FOREACH(pe, &changed_paths, entry) {
3449 free((char *)pe->path);
3450 free(pe->data);
3452 got_pathlist_free(&changed_paths);
3455 done:
3456 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3457 qid = SIMPLEQ_FIRST(&reversed_commits);
3458 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3459 got_object_qid_free(qid);
3461 TAILQ_FOREACH(pe, &changed_paths, entry) {
3462 free((char *)pe->path);
3463 free(pe->data);
3465 got_pathlist_free(&changed_paths);
3466 if (search_pattern)
3467 regfree(&regex);
3468 got_commit_graph_close(graph);
3469 return err;
3472 __dead static void
3473 usage_log(void)
3475 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3476 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3477 "[-R] [path]\n", getprogname());
3478 exit(1);
3481 static int
3482 get_default_log_limit(void)
3484 const char *got_default_log_limit;
3485 long long n;
3486 const char *errstr;
3488 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3489 if (got_default_log_limit == NULL)
3490 return 0;
3491 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3492 if (errstr != NULL)
3493 return 0;
3494 return n;
3497 static const struct got_error *
3498 resolve_commit_arg(struct got_object_id **id, const char *commit_arg,
3499 struct got_repository *repo)
3501 const struct got_error *err = NULL;
3502 struct got_reference *ref;
3504 *id = NULL;
3506 err = got_ref_open(&ref, repo, commit_arg, 0);
3507 if (err == NULL) {
3508 int obj_type;
3509 err = got_ref_resolve(id, repo, ref);
3510 got_ref_close(ref);
3511 if (err)
3512 return err;
3513 err = got_object_get_type(&obj_type, repo, *id);
3514 if (err)
3515 return err;
3516 if (obj_type == GOT_OBJ_TYPE_TAG) {
3517 struct got_tag_object *tag;
3518 err = got_object_open_as_tag(&tag, repo, *id);
3519 if (err)
3520 return err;
3521 if (got_object_tag_get_object_type(tag) !=
3522 GOT_OBJ_TYPE_COMMIT) {
3523 got_object_tag_close(tag);
3524 return got_error(GOT_ERR_OBJ_TYPE);
3526 free(*id);
3527 *id = got_object_id_dup(
3528 got_object_tag_get_object_id(tag));
3529 if (*id == NULL)
3530 err = got_error_from_errno(
3531 "got_object_id_dup");
3532 got_object_tag_close(tag);
3533 if (err)
3534 return err;
3535 } else if (obj_type != GOT_OBJ_TYPE_COMMIT)
3536 return got_error(GOT_ERR_OBJ_TYPE);
3537 } else {
3538 err = got_repo_match_object_id_prefix(id, commit_arg,
3539 GOT_OBJ_TYPE_COMMIT, repo);
3542 return err;
3545 static const struct got_error *
3546 cmd_log(int argc, char *argv[])
3548 const struct got_error *error;
3549 struct got_repository *repo = NULL;
3550 struct got_worktree *worktree = NULL;
3551 struct got_object_id *start_id = NULL, *end_id = NULL;
3552 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3553 const char *start_commit = NULL, *end_commit = NULL;
3554 const char *search_pattern = NULL;
3555 int diff_context = -1, ch;
3556 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3557 int reverse_display_order = 0;
3558 const char *errstr;
3559 struct got_reflist_head refs;
3561 SIMPLEQ_INIT(&refs);
3563 #ifndef PROFILE
3564 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3565 NULL)
3566 == -1)
3567 err(1, "pledge");
3568 #endif
3570 limit = get_default_log_limit();
3572 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3573 switch (ch) {
3574 case 'p':
3575 show_patch = 1;
3576 break;
3577 case 'P':
3578 show_changed_paths = 1;
3579 break;
3580 case 'c':
3581 start_commit = optarg;
3582 break;
3583 case 'C':
3584 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3585 &errstr);
3586 if (errstr != NULL)
3587 err(1, "-C option %s", errstr);
3588 break;
3589 case 'l':
3590 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3591 if (errstr != NULL)
3592 err(1, "-l option %s", errstr);
3593 break;
3594 case 'b':
3595 log_branches = 1;
3596 break;
3597 case 'r':
3598 repo_path = realpath(optarg, NULL);
3599 if (repo_path == NULL)
3600 return got_error_from_errno2("realpath",
3601 optarg);
3602 got_path_strip_trailing_slashes(repo_path);
3603 break;
3604 case 'R':
3605 reverse_display_order = 1;
3606 break;
3607 case 's':
3608 search_pattern = optarg;
3609 break;
3610 case 'x':
3611 end_commit = optarg;
3612 break;
3613 default:
3614 usage_log();
3615 /* NOTREACHED */
3619 argc -= optind;
3620 argv += optind;
3622 if (diff_context == -1)
3623 diff_context = 3;
3624 else if (!show_patch)
3625 errx(1, "-C requires -p");
3627 cwd = getcwd(NULL, 0);
3628 if (cwd == NULL) {
3629 error = got_error_from_errno("getcwd");
3630 goto done;
3633 if (repo_path == NULL) {
3634 error = got_worktree_open(&worktree, cwd);
3635 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3636 goto done;
3637 error = NULL;
3640 if (argc == 0) {
3641 path = strdup("");
3642 if (path == NULL) {
3643 error = got_error_from_errno("strdup");
3644 goto done;
3646 } else if (argc == 1) {
3647 if (worktree) {
3648 error = got_worktree_resolve_path(&path, worktree,
3649 argv[0]);
3650 if (error)
3651 goto done;
3652 } else {
3653 path = strdup(argv[0]);
3654 if (path == NULL) {
3655 error = got_error_from_errno("strdup");
3656 goto done;
3659 } else
3660 usage_log();
3662 if (repo_path == NULL) {
3663 repo_path = worktree ?
3664 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3666 if (repo_path == NULL) {
3667 error = got_error_from_errno("strdup");
3668 goto done;
3671 error = got_repo_open(&repo, repo_path, NULL);
3672 if (error != NULL)
3673 goto done;
3675 error = apply_unveil(got_repo_get_path(repo), 1,
3676 worktree ? got_worktree_get_root_path(worktree) : NULL);
3677 if (error)
3678 goto done;
3680 if (start_commit == NULL) {
3681 struct got_reference *head_ref;
3682 struct got_commit_object *commit = NULL;
3683 error = got_ref_open(&head_ref, repo,
3684 worktree ? got_worktree_get_head_ref_name(worktree)
3685 : GOT_REF_HEAD, 0);
3686 if (error != NULL)
3687 goto done;
3688 error = got_ref_resolve(&start_id, repo, head_ref);
3689 got_ref_close(head_ref);
3690 if (error != NULL)
3691 goto done;
3692 error = got_object_open_as_commit(&commit, repo,
3693 start_id);
3694 if (error != NULL)
3695 goto done;
3696 got_object_commit_close(commit);
3697 } else {
3698 error = resolve_commit_arg(&start_id, start_commit, repo);
3699 if (error != NULL)
3700 goto done;
3702 if (end_commit != NULL) {
3703 error = resolve_commit_arg(&end_id, end_commit, repo);
3704 if (error != NULL)
3705 goto done;
3708 if (worktree) {
3709 const char *prefix = got_worktree_get_path_prefix(worktree);
3710 char *p;
3711 if (asprintf(&p, "%s%s%s", prefix,
3712 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3713 error = got_error_from_errno("asprintf");
3714 goto done;
3716 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3717 free(p);
3718 } else
3719 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3720 if (error != NULL)
3721 goto done;
3722 if (in_repo_path) {
3723 free(path);
3724 path = in_repo_path;
3727 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3728 if (error)
3729 goto done;
3731 error = print_commits(start_id, end_id, repo, path, show_changed_paths,
3732 show_patch, search_pattern, diff_context, limit, log_branches,
3733 reverse_display_order, &refs);
3734 done:
3735 free(path);
3736 free(repo_path);
3737 free(cwd);
3738 if (worktree)
3739 got_worktree_close(worktree);
3740 if (repo) {
3741 const struct got_error *repo_error;
3742 repo_error = got_repo_close(repo);
3743 if (error == NULL)
3744 error = repo_error;
3746 got_ref_list_free(&refs);
3747 return error;
3750 __dead static void
3751 usage_diff(void)
3753 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3754 "[-w] [object1 object2 | path]\n", getprogname());
3755 exit(1);
3758 struct print_diff_arg {
3759 struct got_repository *repo;
3760 struct got_worktree *worktree;
3761 int diff_context;
3762 const char *id_str;
3763 int header_shown;
3764 int diff_staged;
3765 int ignore_whitespace;
3769 * Create a file which contains the target path of a symlink so we can feed
3770 * it as content to the diff engine.
3772 static const struct got_error *
3773 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
3774 const char *abspath)
3776 const struct got_error *err = NULL;
3777 char target_path[PATH_MAX];
3778 ssize_t target_len, outlen;
3780 *fd = -1;
3782 if (dirfd != -1) {
3783 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
3784 if (target_len == -1)
3785 return got_error_from_errno2("readlinkat", abspath);
3786 } else {
3787 target_len = readlink(abspath, target_path, PATH_MAX);
3788 if (target_len == -1)
3789 return got_error_from_errno2("readlink", abspath);
3792 *fd = got_opentempfd();
3793 if (*fd == -1)
3794 return got_error_from_errno("got_opentempfd");
3796 outlen = write(*fd, target_path, target_len);
3797 if (outlen == -1) {
3798 err = got_error_from_errno("got_opentempfd");
3799 goto done;
3802 if (lseek(*fd, 0, SEEK_SET) == -1) {
3803 err = got_error_from_errno2("lseek", abspath);
3804 goto done;
3806 done:
3807 if (err) {
3808 close(*fd);
3809 *fd = -1;
3811 return err;
3814 static const struct got_error *
3815 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3816 const char *path, struct got_object_id *blob_id,
3817 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3818 int dirfd, const char *de_name)
3820 struct print_diff_arg *a = arg;
3821 const struct got_error *err = NULL;
3822 struct got_blob_object *blob1 = NULL;
3823 int fd = -1;
3824 FILE *f2 = NULL;
3825 char *abspath = NULL, *label1 = NULL;
3826 struct stat sb;
3828 if (a->diff_staged) {
3829 if (staged_status != GOT_STATUS_MODIFY &&
3830 staged_status != GOT_STATUS_ADD &&
3831 staged_status != GOT_STATUS_DELETE)
3832 return NULL;
3833 } else {
3834 if (staged_status == GOT_STATUS_DELETE)
3835 return NULL;
3836 if (status == GOT_STATUS_NONEXISTENT)
3837 return got_error_set_errno(ENOENT, path);
3838 if (status != GOT_STATUS_MODIFY &&
3839 status != GOT_STATUS_ADD &&
3840 status != GOT_STATUS_DELETE &&
3841 status != GOT_STATUS_CONFLICT)
3842 return NULL;
3845 if (!a->header_shown) {
3846 printf("diff %s %s%s\n", a->id_str,
3847 got_worktree_get_root_path(a->worktree),
3848 a->diff_staged ? " (staged changes)" : "");
3849 a->header_shown = 1;
3852 if (a->diff_staged) {
3853 const char *label1 = NULL, *label2 = NULL;
3854 switch (staged_status) {
3855 case GOT_STATUS_MODIFY:
3856 label1 = path;
3857 label2 = path;
3858 break;
3859 case GOT_STATUS_ADD:
3860 label2 = path;
3861 break;
3862 case GOT_STATUS_DELETE:
3863 label1 = path;
3864 break;
3865 default:
3866 return got_error(GOT_ERR_FILE_STATUS);
3868 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
3869 label1, label2, a->diff_context, a->ignore_whitespace,
3870 a->repo, stdout);
3873 if (staged_status == GOT_STATUS_ADD ||
3874 staged_status == GOT_STATUS_MODIFY) {
3875 char *id_str;
3876 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
3877 8192);
3878 if (err)
3879 goto done;
3880 err = got_object_id_str(&id_str, staged_blob_id);
3881 if (err)
3882 goto done;
3883 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
3884 err = got_error_from_errno("asprintf");
3885 free(id_str);
3886 goto done;
3888 free(id_str);
3889 } else if (status != GOT_STATUS_ADD) {
3890 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
3891 if (err)
3892 goto done;
3895 if (status != GOT_STATUS_DELETE) {
3896 if (asprintf(&abspath, "%s/%s",
3897 got_worktree_get_root_path(a->worktree), path) == -1) {
3898 err = got_error_from_errno("asprintf");
3899 goto done;
3902 if (dirfd != -1) {
3903 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
3904 if (fd == -1) {
3905 if (errno != ELOOP) {
3906 err = got_error_from_errno2("openat",
3907 abspath);
3908 goto done;
3910 err = get_symlink_target_file(&fd, dirfd,
3911 de_name, abspath);
3912 if (err)
3913 goto done;
3915 } else {
3916 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
3917 if (fd == -1) {
3918 if (errno != ELOOP) {
3919 err = got_error_from_errno2("open",
3920 abspath);
3921 goto done;
3923 err = get_symlink_target_file(&fd, dirfd,
3924 de_name, abspath);
3925 if (err)
3926 goto done;
3929 if (fstat(fd, &sb) == -1) {
3930 err = got_error_from_errno2("fstat", abspath);
3931 goto done;
3933 f2 = fdopen(fd, "r");
3934 if (f2 == NULL) {
3935 err = got_error_from_errno2("fdopen", abspath);
3936 goto done;
3938 fd = -1;
3939 } else
3940 sb.st_size = 0;
3942 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
3943 a->diff_context, a->ignore_whitespace, stdout);
3944 done:
3945 if (blob1)
3946 got_object_blob_close(blob1);
3947 if (f2 && fclose(f2) == EOF && err == NULL)
3948 err = got_error_from_errno("fclose");
3949 if (fd != -1 && close(fd) == -1 && err == NULL)
3950 err = got_error_from_errno("close");
3951 free(abspath);
3952 return err;
3955 static const struct got_error *
3956 cmd_diff(int argc, char *argv[])
3958 const struct got_error *error;
3959 struct got_repository *repo = NULL;
3960 struct got_worktree *worktree = NULL;
3961 char *cwd = NULL, *repo_path = NULL;
3962 struct got_object_id *id1 = NULL, *id2 = NULL;
3963 const char *id_str1 = NULL, *id_str2 = NULL;
3964 char *label1 = NULL, *label2 = NULL;
3965 int type1, type2;
3966 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
3967 const char *errstr;
3968 char *path = NULL;
3970 #ifndef PROFILE
3971 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3972 NULL) == -1)
3973 err(1, "pledge");
3974 #endif
3976 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
3977 switch (ch) {
3978 case 'C':
3979 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3980 &errstr);
3981 if (errstr != NULL)
3982 err(1, "-C option %s", errstr);
3983 break;
3984 case 'r':
3985 repo_path = realpath(optarg, NULL);
3986 if (repo_path == NULL)
3987 return got_error_from_errno2("realpath",
3988 optarg);
3989 got_path_strip_trailing_slashes(repo_path);
3990 break;
3991 case 's':
3992 diff_staged = 1;
3993 break;
3994 case 'w':
3995 ignore_whitespace = 1;
3996 break;
3997 default:
3998 usage_diff();
3999 /* NOTREACHED */
4003 argc -= optind;
4004 argv += optind;
4006 cwd = getcwd(NULL, 0);
4007 if (cwd == NULL) {
4008 error = got_error_from_errno("getcwd");
4009 goto done;
4011 if (argc <= 1) {
4012 if (repo_path)
4013 errx(1,
4014 "-r option can't be used when diffing a work tree");
4015 error = got_worktree_open(&worktree, cwd);
4016 if (error) {
4017 if (error->code == GOT_ERR_NOT_WORKTREE)
4018 error = wrap_not_worktree_error(error, "diff",
4019 cwd);
4020 goto done;
4022 repo_path = strdup(got_worktree_get_repo_path(worktree));
4023 if (repo_path == NULL) {
4024 error = got_error_from_errno("strdup");
4025 goto done;
4027 if (argc == 1) {
4028 error = got_worktree_resolve_path(&path, worktree,
4029 argv[0]);
4030 if (error)
4031 goto done;
4032 } else {
4033 path = strdup("");
4034 if (path == NULL) {
4035 error = got_error_from_errno("strdup");
4036 goto done;
4039 } else if (argc == 2) {
4040 if (diff_staged)
4041 errx(1, "-s option can't be used when diffing "
4042 "objects in repository");
4043 id_str1 = argv[0];
4044 id_str2 = argv[1];
4045 if (repo_path == NULL) {
4046 error = got_worktree_open(&worktree, cwd);
4047 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4048 goto done;
4049 if (worktree) {
4050 repo_path = strdup(
4051 got_worktree_get_repo_path(worktree));
4052 if (repo_path == NULL) {
4053 error = got_error_from_errno("strdup");
4054 goto done;
4056 } else {
4057 repo_path = strdup(cwd);
4058 if (repo_path == NULL) {
4059 error = got_error_from_errno("strdup");
4060 goto done;
4064 } else
4065 usage_diff();
4067 error = got_repo_open(&repo, repo_path, NULL);
4068 free(repo_path);
4069 if (error != NULL)
4070 goto done;
4072 error = apply_unveil(got_repo_get_path(repo), 1,
4073 worktree ? got_worktree_get_root_path(worktree) : NULL);
4074 if (error)
4075 goto done;
4077 if (argc <= 1) {
4078 struct print_diff_arg arg;
4079 struct got_pathlist_head paths;
4080 char *id_str;
4082 TAILQ_INIT(&paths);
4084 error = got_object_id_str(&id_str,
4085 got_worktree_get_base_commit_id(worktree));
4086 if (error)
4087 goto done;
4088 arg.repo = repo;
4089 arg.worktree = worktree;
4090 arg.diff_context = diff_context;
4091 arg.id_str = id_str;
4092 arg.header_shown = 0;
4093 arg.diff_staged = diff_staged;
4094 arg.ignore_whitespace = ignore_whitespace;
4096 error = got_pathlist_append(&paths, path, NULL);
4097 if (error)
4098 goto done;
4100 error = got_worktree_status(worktree, &paths, repo, print_diff,
4101 &arg, check_cancelled, NULL);
4102 free(id_str);
4103 got_pathlist_free(&paths);
4104 goto done;
4107 error = got_repo_match_object_id(&id1, &label1, id_str1,
4108 GOT_OBJ_TYPE_ANY, 1, repo);
4109 if (error)
4110 goto done;
4112 error = got_repo_match_object_id(&id2, &label2, id_str2,
4113 GOT_OBJ_TYPE_ANY, 1, repo);
4114 if (error)
4115 goto done;
4117 error = got_object_get_type(&type1, repo, id1);
4118 if (error)
4119 goto done;
4121 error = got_object_get_type(&type2, repo, id2);
4122 if (error)
4123 goto done;
4125 if (type1 != type2) {
4126 error = got_error(GOT_ERR_OBJ_TYPE);
4127 goto done;
4130 switch (type1) {
4131 case GOT_OBJ_TYPE_BLOB:
4132 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
4133 diff_context, ignore_whitespace, repo, stdout);
4134 break;
4135 case GOT_OBJ_TYPE_TREE:
4136 error = got_diff_objects_as_trees(id1, id2, "", "",
4137 diff_context, ignore_whitespace, repo, stdout);
4138 break;
4139 case GOT_OBJ_TYPE_COMMIT:
4140 printf("diff %s %s\n", label1, label2);
4141 error = got_diff_objects_as_commits(id1, id2, diff_context,
4142 ignore_whitespace, repo, stdout);
4143 break;
4144 default:
4145 error = got_error(GOT_ERR_OBJ_TYPE);
4147 done:
4148 free(label1);
4149 free(label2);
4150 free(id1);
4151 free(id2);
4152 free(path);
4153 if (worktree)
4154 got_worktree_close(worktree);
4155 if (repo) {
4156 const struct got_error *repo_error;
4157 repo_error = got_repo_close(repo);
4158 if (error == NULL)
4159 error = repo_error;
4161 return error;
4164 __dead static void
4165 usage_blame(void)
4167 fprintf(stderr,
4168 "usage: %s blame [-c commit] [-r repository-path] path\n",
4169 getprogname());
4170 exit(1);
4173 struct blame_line {
4174 int annotated;
4175 char *id_str;
4176 char *committer;
4177 char datebuf[11]; /* YYYY-MM-DD + NUL */
4180 struct blame_cb_args {
4181 struct blame_line *lines;
4182 int nlines;
4183 int nlines_prec;
4184 int lineno_cur;
4185 off_t *line_offsets;
4186 FILE *f;
4187 struct got_repository *repo;
4190 static const struct got_error *
4191 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4193 const struct got_error *err = NULL;
4194 struct blame_cb_args *a = arg;
4195 struct blame_line *bline;
4196 char *line = NULL;
4197 size_t linesize = 0;
4198 struct got_commit_object *commit = NULL;
4199 off_t offset;
4200 struct tm tm;
4201 time_t committer_time;
4203 if (nlines != a->nlines ||
4204 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4205 return got_error(GOT_ERR_RANGE);
4207 if (sigint_received)
4208 return got_error(GOT_ERR_ITER_COMPLETED);
4210 if (lineno == -1)
4211 return NULL; /* no change in this commit */
4213 /* Annotate this line. */
4214 bline = &a->lines[lineno - 1];
4215 if (bline->annotated)
4216 return NULL;
4217 err = got_object_id_str(&bline->id_str, id);
4218 if (err)
4219 return err;
4221 err = got_object_open_as_commit(&commit, a->repo, id);
4222 if (err)
4223 goto done;
4225 bline->committer = strdup(got_object_commit_get_committer(commit));
4226 if (bline->committer == NULL) {
4227 err = got_error_from_errno("strdup");
4228 goto done;
4231 committer_time = got_object_commit_get_committer_time(commit);
4232 if (localtime_r(&committer_time, &tm) == NULL)
4233 return got_error_from_errno("localtime_r");
4234 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4235 &tm) >= sizeof(bline->datebuf)) {
4236 err = got_error(GOT_ERR_NO_SPACE);
4237 goto done;
4239 bline->annotated = 1;
4241 /* Print lines annotated so far. */
4242 bline = &a->lines[a->lineno_cur - 1];
4243 if (!bline->annotated)
4244 goto done;
4246 offset = a->line_offsets[a->lineno_cur - 1];
4247 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4248 err = got_error_from_errno("fseeko");
4249 goto done;
4252 while (bline->annotated) {
4253 char *smallerthan, *at, *nl, *committer;
4254 size_t len;
4256 if (getline(&line, &linesize, a->f) == -1) {
4257 if (ferror(a->f))
4258 err = got_error_from_errno("getline");
4259 break;
4262 committer = bline->committer;
4263 smallerthan = strchr(committer, '<');
4264 if (smallerthan && smallerthan[1] != '\0')
4265 committer = smallerthan + 1;
4266 at = strchr(committer, '@');
4267 if (at)
4268 *at = '\0';
4269 len = strlen(committer);
4270 if (len >= 9)
4271 committer[8] = '\0';
4273 nl = strchr(line, '\n');
4274 if (nl)
4275 *nl = '\0';
4276 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4277 bline->id_str, bline->datebuf, committer, line);
4279 a->lineno_cur++;
4280 bline = &a->lines[a->lineno_cur - 1];
4282 done:
4283 if (commit)
4284 got_object_commit_close(commit);
4285 free(line);
4286 return err;
4289 static const struct got_error *
4290 cmd_blame(int argc, char *argv[])
4292 const struct got_error *error;
4293 struct got_repository *repo = NULL;
4294 struct got_worktree *worktree = NULL;
4295 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4296 char *link_target = NULL;
4297 struct got_object_id *obj_id = NULL;
4298 struct got_object_id *commit_id = NULL;
4299 struct got_blob_object *blob = NULL;
4300 char *commit_id_str = NULL;
4301 struct blame_cb_args bca;
4302 int ch, obj_type, i;
4303 size_t filesize;
4305 memset(&bca, 0, sizeof(bca));
4307 #ifndef PROFILE
4308 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4309 NULL) == -1)
4310 err(1, "pledge");
4311 #endif
4313 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4314 switch (ch) {
4315 case 'c':
4316 commit_id_str = optarg;
4317 break;
4318 case 'r':
4319 repo_path = realpath(optarg, NULL);
4320 if (repo_path == NULL)
4321 return got_error_from_errno2("realpath",
4322 optarg);
4323 got_path_strip_trailing_slashes(repo_path);
4324 break;
4325 default:
4326 usage_blame();
4327 /* NOTREACHED */
4331 argc -= optind;
4332 argv += optind;
4334 if (argc == 1)
4335 path = argv[0];
4336 else
4337 usage_blame();
4339 cwd = getcwd(NULL, 0);
4340 if (cwd == NULL) {
4341 error = got_error_from_errno("getcwd");
4342 goto done;
4344 if (repo_path == NULL) {
4345 error = got_worktree_open(&worktree, cwd);
4346 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4347 goto done;
4348 else
4349 error = NULL;
4350 if (worktree) {
4351 repo_path =
4352 strdup(got_worktree_get_repo_path(worktree));
4353 if (repo_path == NULL) {
4354 error = got_error_from_errno("strdup");
4355 if (error)
4356 goto done;
4358 } else {
4359 repo_path = strdup(cwd);
4360 if (repo_path == NULL) {
4361 error = got_error_from_errno("strdup");
4362 goto done;
4367 error = got_repo_open(&repo, repo_path, NULL);
4368 if (error != NULL)
4369 goto done;
4371 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4372 if (error)
4373 goto done;
4375 if (worktree) {
4376 const char *prefix = got_worktree_get_path_prefix(worktree);
4377 char *p, *worktree_subdir = cwd +
4378 strlen(got_worktree_get_root_path(worktree));
4379 if (asprintf(&p, "%s%s%s%s%s",
4380 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
4381 worktree_subdir, worktree_subdir[0] ? "/" : "",
4382 path) == -1) {
4383 error = got_error_from_errno("asprintf");
4384 goto done;
4386 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4387 free(p);
4388 } else {
4389 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4391 if (error)
4392 goto done;
4394 if (commit_id_str == NULL) {
4395 struct got_reference *head_ref;
4396 error = got_ref_open(&head_ref, repo, worktree ?
4397 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4398 if (error != NULL)
4399 goto done;
4400 error = got_ref_resolve(&commit_id, repo, head_ref);
4401 got_ref_close(head_ref);
4402 if (error != NULL)
4403 goto done;
4404 } else {
4405 error = got_repo_match_object_id(&commit_id, NULL,
4406 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4407 if (error)
4408 goto done;
4411 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4412 commit_id, repo);
4413 if (error)
4414 goto done;
4416 error = got_object_id_by_path(&obj_id, repo, commit_id,
4417 link_target ? link_target : in_repo_path);
4418 if (error)
4419 goto done;
4421 error = got_object_get_type(&obj_type, repo, obj_id);
4422 if (error)
4423 goto done;
4425 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4426 error = got_error_path(link_target ? link_target : in_repo_path,
4427 GOT_ERR_OBJ_TYPE);
4428 goto done;
4431 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4432 if (error)
4433 goto done;
4434 bca.f = got_opentemp();
4435 if (bca.f == NULL) {
4436 error = got_error_from_errno("got_opentemp");
4437 goto done;
4439 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4440 &bca.line_offsets, bca.f, blob);
4441 if (error || bca.nlines == 0)
4442 goto done;
4444 /* Don't include \n at EOF in the blame line count. */
4445 if (bca.line_offsets[bca.nlines - 1] == filesize)
4446 bca.nlines--;
4448 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4449 if (bca.lines == NULL) {
4450 error = got_error_from_errno("calloc");
4451 goto done;
4453 bca.lineno_cur = 1;
4454 bca.nlines_prec = 0;
4455 i = bca.nlines;
4456 while (i > 0) {
4457 i /= 10;
4458 bca.nlines_prec++;
4460 bca.repo = repo;
4462 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4463 repo, blame_cb, &bca, check_cancelled, NULL);
4464 done:
4465 free(in_repo_path);
4466 free(link_target);
4467 free(repo_path);
4468 free(cwd);
4469 free(commit_id);
4470 free(obj_id);
4471 if (blob)
4472 got_object_blob_close(blob);
4473 if (worktree)
4474 got_worktree_close(worktree);
4475 if (repo) {
4476 const struct got_error *repo_error;
4477 repo_error = got_repo_close(repo);
4478 if (error == NULL)
4479 error = repo_error;
4481 if (bca.lines) {
4482 for (i = 0; i < bca.nlines; i++) {
4483 struct blame_line *bline = &bca.lines[i];
4484 free(bline->id_str);
4485 free(bline->committer);
4487 free(bca.lines);
4489 free(bca.line_offsets);
4490 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4491 error = got_error_from_errno("fclose");
4492 return error;
4495 __dead static void
4496 usage_tree(void)
4498 fprintf(stderr,
4499 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4500 getprogname());
4501 exit(1);
4504 static const struct got_error *
4505 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4506 const char *root_path, struct got_repository *repo)
4508 const struct got_error *err = NULL;
4509 int is_root_path = (strcmp(path, root_path) == 0);
4510 const char *modestr = "";
4511 mode_t mode = got_tree_entry_get_mode(te);
4512 char *link_target = NULL;
4514 path += strlen(root_path);
4515 while (path[0] == '/')
4516 path++;
4518 if (got_object_tree_entry_is_submodule(te))
4519 modestr = "$";
4520 else if (S_ISLNK(mode)) {
4521 int i;
4523 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4524 if (err)
4525 return err;
4526 for (i = 0; i < strlen(link_target); i++) {
4527 if (!isprint((unsigned char)link_target[i]))
4528 link_target[i] = '?';
4531 modestr = "@";
4533 else if (S_ISDIR(mode))
4534 modestr = "/";
4535 else if (mode & S_IXUSR)
4536 modestr = "*";
4538 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4539 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4540 link_target ? " -> ": "", link_target ? link_target : "");
4542 free(link_target);
4543 return NULL;
4546 static const struct got_error *
4547 print_tree(const char *path, struct got_object_id *commit_id,
4548 int show_ids, int recurse, const char *root_path,
4549 struct got_repository *repo)
4551 const struct got_error *err = NULL;
4552 struct got_object_id *tree_id = NULL;
4553 struct got_tree_object *tree = NULL;
4554 int nentries, i;
4556 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4557 if (err)
4558 goto done;
4560 err = got_object_open_as_tree(&tree, repo, tree_id);
4561 if (err)
4562 goto done;
4563 nentries = got_object_tree_get_nentries(tree);
4564 for (i = 0; i < nentries; i++) {
4565 struct got_tree_entry *te;
4566 char *id = NULL;
4568 if (sigint_received || sigpipe_received)
4569 break;
4571 te = got_object_tree_get_entry(tree, i);
4572 if (show_ids) {
4573 char *id_str;
4574 err = got_object_id_str(&id_str,
4575 got_tree_entry_get_id(te));
4576 if (err)
4577 goto done;
4578 if (asprintf(&id, "%s ", id_str) == -1) {
4579 err = got_error_from_errno("asprintf");
4580 free(id_str);
4581 goto done;
4583 free(id_str);
4585 err = print_entry(te, id, path, root_path, repo);
4586 free(id);
4587 if (err)
4588 goto done;
4590 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4591 char *child_path;
4592 if (asprintf(&child_path, "%s%s%s", path,
4593 path[0] == '/' && path[1] == '\0' ? "" : "/",
4594 got_tree_entry_get_name(te)) == -1) {
4595 err = got_error_from_errno("asprintf");
4596 goto done;
4598 err = print_tree(child_path, commit_id, show_ids, 1,
4599 root_path, repo);
4600 free(child_path);
4601 if (err)
4602 goto done;
4605 done:
4606 if (tree)
4607 got_object_tree_close(tree);
4608 free(tree_id);
4609 return err;
4612 static const struct got_error *
4613 cmd_tree(int argc, char *argv[])
4615 const struct got_error *error;
4616 struct got_repository *repo = NULL;
4617 struct got_worktree *worktree = NULL;
4618 const char *path, *refname = NULL;
4619 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4620 struct got_object_id *commit_id = NULL;
4621 char *commit_id_str = NULL;
4622 int show_ids = 0, recurse = 0;
4623 int ch;
4625 #ifndef PROFILE
4626 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4627 NULL) == -1)
4628 err(1, "pledge");
4629 #endif
4631 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4632 switch (ch) {
4633 case 'c':
4634 commit_id_str = optarg;
4635 break;
4636 case 'r':
4637 repo_path = realpath(optarg, NULL);
4638 if (repo_path == NULL)
4639 return got_error_from_errno2("realpath",
4640 optarg);
4641 got_path_strip_trailing_slashes(repo_path);
4642 break;
4643 case 'i':
4644 show_ids = 1;
4645 break;
4646 case 'R':
4647 recurse = 1;
4648 break;
4649 default:
4650 usage_tree();
4651 /* NOTREACHED */
4655 argc -= optind;
4656 argv += optind;
4658 if (argc == 1)
4659 path = argv[0];
4660 else if (argc > 1)
4661 usage_tree();
4662 else
4663 path = NULL;
4665 cwd = getcwd(NULL, 0);
4666 if (cwd == NULL) {
4667 error = got_error_from_errno("getcwd");
4668 goto done;
4670 if (repo_path == NULL) {
4671 error = got_worktree_open(&worktree, cwd);
4672 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4673 goto done;
4674 else
4675 error = NULL;
4676 if (worktree) {
4677 repo_path =
4678 strdup(got_worktree_get_repo_path(worktree));
4679 if (repo_path == NULL)
4680 error = got_error_from_errno("strdup");
4681 if (error)
4682 goto done;
4683 } else {
4684 repo_path = strdup(cwd);
4685 if (repo_path == NULL) {
4686 error = got_error_from_errno("strdup");
4687 goto done;
4692 error = got_repo_open(&repo, repo_path, NULL);
4693 if (error != NULL)
4694 goto done;
4696 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4697 if (error)
4698 goto done;
4700 if (path == NULL) {
4701 if (worktree) {
4702 char *p, *worktree_subdir = cwd +
4703 strlen(got_worktree_get_root_path(worktree));
4704 if (asprintf(&p, "%s/%s",
4705 got_worktree_get_path_prefix(worktree),
4706 worktree_subdir) == -1) {
4707 error = got_error_from_errno("asprintf");
4708 goto done;
4710 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4711 free(p);
4712 if (error)
4713 goto done;
4714 } else
4715 path = "/";
4717 if (in_repo_path == NULL) {
4718 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4719 if (error != NULL)
4720 goto done;
4723 if (commit_id_str == NULL) {
4724 struct got_reference *head_ref;
4725 if (worktree)
4726 refname = got_worktree_get_head_ref_name(worktree);
4727 else
4728 refname = GOT_REF_HEAD;
4729 error = got_ref_open(&head_ref, repo, refname, 0);
4730 if (error != NULL)
4731 goto done;
4732 error = got_ref_resolve(&commit_id, repo, head_ref);
4733 got_ref_close(head_ref);
4734 if (error != NULL)
4735 goto done;
4736 } else {
4737 error = got_repo_match_object_id(&commit_id, NULL,
4738 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4739 if (error)
4740 goto done;
4743 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4744 in_repo_path, repo);
4745 done:
4746 free(in_repo_path);
4747 free(repo_path);
4748 free(cwd);
4749 free(commit_id);
4750 if (worktree)
4751 got_worktree_close(worktree);
4752 if (repo) {
4753 const struct got_error *repo_error;
4754 repo_error = got_repo_close(repo);
4755 if (error == NULL)
4756 error = repo_error;
4758 return error;
4761 __dead static void
4762 usage_status(void)
4764 fprintf(stderr, "usage: %s status [-s status-codes ] [path ...]\n",
4765 getprogname());
4766 exit(1);
4769 static const struct got_error *
4770 print_status(void *arg, unsigned char status, unsigned char staged_status,
4771 const char *path, struct got_object_id *blob_id,
4772 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4773 int dirfd, const char *de_name)
4775 if (status == staged_status && (status == GOT_STATUS_DELETE))
4776 status = GOT_STATUS_NO_CHANGE;
4777 if (arg) {
4778 char *status_codes = arg;
4779 size_t ncodes = strlen(status_codes);
4780 int i;
4781 for (i = 0; i < ncodes ; i++) {
4782 if (status == status_codes[i] ||
4783 staged_status == status_codes[i])
4784 break;
4786 if (i == ncodes)
4787 return NULL;
4789 printf("%c%c %s\n", status, staged_status, path);
4790 return NULL;
4793 static const struct got_error *
4794 cmd_status(int argc, char *argv[])
4796 const struct got_error *error = NULL;
4797 struct got_repository *repo = NULL;
4798 struct got_worktree *worktree = NULL;
4799 char *cwd = NULL, *status_codes = NULL;;
4800 struct got_pathlist_head paths;
4801 struct got_pathlist_entry *pe;
4802 int ch, i;
4804 TAILQ_INIT(&paths);
4806 while ((ch = getopt(argc, argv, "s:")) != -1) {
4807 switch (ch) {
4808 case 's':
4809 for (i = 0; i < strlen(optarg); i++) {
4810 switch (optarg[i]) {
4811 case GOT_STATUS_MODIFY:
4812 case GOT_STATUS_ADD:
4813 case GOT_STATUS_DELETE:
4814 case GOT_STATUS_CONFLICT:
4815 case GOT_STATUS_MISSING:
4816 case GOT_STATUS_OBSTRUCTED:
4817 case GOT_STATUS_UNVERSIONED:
4818 case GOT_STATUS_MODE_CHANGE:
4819 case GOT_STATUS_NONEXISTENT:
4820 break;
4821 default:
4822 errx(1, "invalid status code '%c'",
4823 optarg[i]);
4826 status_codes = optarg;
4827 break;
4828 default:
4829 usage_status();
4830 /* NOTREACHED */
4834 argc -= optind;
4835 argv += optind;
4837 #ifndef PROFILE
4838 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4839 NULL) == -1)
4840 err(1, "pledge");
4841 #endif
4842 cwd = getcwd(NULL, 0);
4843 if (cwd == NULL) {
4844 error = got_error_from_errno("getcwd");
4845 goto done;
4848 error = got_worktree_open(&worktree, cwd);
4849 if (error) {
4850 if (error->code == GOT_ERR_NOT_WORKTREE)
4851 error = wrap_not_worktree_error(error, "status", cwd);
4852 goto done;
4855 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4856 NULL);
4857 if (error != NULL)
4858 goto done;
4860 error = apply_unveil(got_repo_get_path(repo), 1,
4861 got_worktree_get_root_path(worktree));
4862 if (error)
4863 goto done;
4865 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
4866 if (error)
4867 goto done;
4869 error = got_worktree_status(worktree, &paths, repo, print_status,
4870 status_codes, check_cancelled, NULL);
4871 done:
4872 TAILQ_FOREACH(pe, &paths, entry)
4873 free((char *)pe->path);
4874 got_pathlist_free(&paths);
4875 free(cwd);
4876 return error;
4879 __dead static void
4880 usage_ref(void)
4882 fprintf(stderr,
4883 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
4884 "[-d] [name]\n",
4885 getprogname());
4886 exit(1);
4889 static const struct got_error *
4890 list_refs(struct got_repository *repo, const char *refname)
4892 static const struct got_error *err = NULL;
4893 struct got_reflist_head refs;
4894 struct got_reflist_entry *re;
4896 SIMPLEQ_INIT(&refs);
4897 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
4898 if (err)
4899 return err;
4901 SIMPLEQ_FOREACH(re, &refs, entry) {
4902 char *refstr;
4903 refstr = got_ref_to_str(re->ref);
4904 if (refstr == NULL)
4905 return got_error_from_errno("got_ref_to_str");
4906 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
4907 free(refstr);
4910 got_ref_list_free(&refs);
4911 return NULL;
4914 static const struct got_error *
4915 delete_ref(struct got_repository *repo, const char *refname)
4917 const struct got_error *err = NULL;
4918 struct got_reference *ref;
4920 err = got_ref_open(&ref, repo, refname, 0);
4921 if (err)
4922 return err;
4924 err = got_ref_delete(ref, repo);
4925 got_ref_close(ref);
4926 return err;
4929 static const struct got_error *
4930 add_ref(struct got_repository *repo, const char *refname, const char *target)
4932 const struct got_error *err = NULL;
4933 struct got_object_id *id;
4934 struct got_reference *ref = NULL;
4937 * Don't let the user create a reference name with a leading '-'.
4938 * While technically a valid reference name, this case is usually
4939 * an unintended typo.
4941 if (refname[0] == '-')
4942 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4944 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
4945 repo);
4946 if (err) {
4947 struct got_reference *target_ref;
4949 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
4950 return err;
4951 err = got_ref_open(&target_ref, repo, target, 0);
4952 if (err)
4953 return err;
4954 err = got_ref_resolve(&id, repo, target_ref);
4955 got_ref_close(target_ref);
4956 if (err)
4957 return err;
4960 err = got_ref_alloc(&ref, refname, id);
4961 if (err)
4962 goto done;
4964 err = got_ref_write(ref, repo);
4965 done:
4966 if (ref)
4967 got_ref_close(ref);
4968 free(id);
4969 return err;
4972 static const struct got_error *
4973 add_symref(struct got_repository *repo, const char *refname, const char *target)
4975 const struct got_error *err = NULL;
4976 struct got_reference *ref = NULL;
4977 struct got_reference *target_ref = NULL;
4980 * Don't let the user create a reference name with a leading '-'.
4981 * While technically a valid reference name, this case is usually
4982 * an unintended typo.
4984 if (refname[0] == '-')
4985 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4987 err = got_ref_open(&target_ref, repo, target, 0);
4988 if (err)
4989 return err;
4991 err = got_ref_alloc_symref(&ref, refname, target_ref);
4992 if (err)
4993 goto done;
4995 err = got_ref_write(ref, repo);
4996 done:
4997 if (target_ref)
4998 got_ref_close(target_ref);
4999 if (ref)
5000 got_ref_close(ref);
5001 return err;
5004 static const struct got_error *
5005 cmd_ref(int argc, char *argv[])
5007 const struct got_error *error = NULL;
5008 struct got_repository *repo = NULL;
5009 struct got_worktree *worktree = NULL;
5010 char *cwd = NULL, *repo_path = NULL;
5011 int ch, do_list = 0, do_delete = 0;
5012 const char *obj_arg = NULL, *symref_target= NULL;
5013 char *refname = NULL;
5015 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5016 switch (ch) {
5017 case 'c':
5018 obj_arg = optarg;
5019 break;
5020 case 'd':
5021 do_delete = 1;
5022 break;
5023 case 'r':
5024 repo_path = realpath(optarg, NULL);
5025 if (repo_path == NULL)
5026 return got_error_from_errno2("realpath",
5027 optarg);
5028 got_path_strip_trailing_slashes(repo_path);
5029 break;
5030 case 'l':
5031 do_list = 1;
5032 break;
5033 case 's':
5034 symref_target = optarg;
5035 break;
5036 default:
5037 usage_ref();
5038 /* NOTREACHED */
5042 if (obj_arg && do_list)
5043 errx(1, "-c and -l options are mutually exclusive");
5044 if (obj_arg && do_delete)
5045 errx(1, "-c and -d options are mutually exclusive");
5046 if (obj_arg && symref_target)
5047 errx(1, "-c and -s options are mutually exclusive");
5048 if (symref_target && do_delete)
5049 errx(1, "-s and -d options are mutually exclusive");
5050 if (symref_target && do_list)
5051 errx(1, "-s and -l options are mutually exclusive");
5052 if (do_delete && do_list)
5053 errx(1, "-d and -l options are mutually exclusive");
5055 argc -= optind;
5056 argv += optind;
5058 if (do_list) {
5059 if (argc != 0 && argc != 1)
5060 usage_ref();
5061 if (argc == 1) {
5062 refname = strdup(argv[0]);
5063 if (refname == NULL) {
5064 error = got_error_from_errno("strdup");
5065 goto done;
5068 } else {
5069 if (argc != 1)
5070 usage_ref();
5071 refname = strdup(argv[0]);
5072 if (refname == NULL) {
5073 error = got_error_from_errno("strdup");
5074 goto done;
5078 if (refname)
5079 got_path_strip_trailing_slashes(refname);
5081 #ifndef PROFILE
5082 if (do_list) {
5083 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5084 NULL) == -1)
5085 err(1, "pledge");
5086 } else {
5087 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5088 "sendfd unveil", NULL) == -1)
5089 err(1, "pledge");
5091 #endif
5092 cwd = getcwd(NULL, 0);
5093 if (cwd == NULL) {
5094 error = got_error_from_errno("getcwd");
5095 goto done;
5098 if (repo_path == NULL) {
5099 error = got_worktree_open(&worktree, cwd);
5100 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5101 goto done;
5102 else
5103 error = NULL;
5104 if (worktree) {
5105 repo_path =
5106 strdup(got_worktree_get_repo_path(worktree));
5107 if (repo_path == NULL)
5108 error = got_error_from_errno("strdup");
5109 if (error)
5110 goto done;
5111 } else {
5112 repo_path = strdup(cwd);
5113 if (repo_path == NULL) {
5114 error = got_error_from_errno("strdup");
5115 goto done;
5120 error = got_repo_open(&repo, repo_path, NULL);
5121 if (error != NULL)
5122 goto done;
5124 error = apply_unveil(got_repo_get_path(repo), do_list,
5125 worktree ? got_worktree_get_root_path(worktree) : NULL);
5126 if (error)
5127 goto done;
5129 if (do_list)
5130 error = list_refs(repo, refname);
5131 else if (do_delete)
5132 error = delete_ref(repo, refname);
5133 else if (symref_target)
5134 error = add_symref(repo, refname, symref_target);
5135 else {
5136 if (obj_arg == NULL)
5137 usage_ref();
5138 error = add_ref(repo, refname, obj_arg);
5140 done:
5141 free(refname);
5142 if (repo)
5143 got_repo_close(repo);
5144 if (worktree)
5145 got_worktree_close(worktree);
5146 free(cwd);
5147 free(repo_path);
5148 return error;
5151 __dead static void
5152 usage_branch(void)
5154 fprintf(stderr,
5155 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5156 "[name]\n", getprogname());
5157 exit(1);
5160 static const struct got_error *
5161 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5162 struct got_reference *ref)
5164 const struct got_error *err = NULL;
5165 const char *refname, *marker = " ";
5166 char *refstr;
5168 refname = got_ref_get_name(ref);
5169 if (worktree && strcmp(refname,
5170 got_worktree_get_head_ref_name(worktree)) == 0) {
5171 struct got_object_id *id = NULL;
5173 err = got_ref_resolve(&id, repo, ref);
5174 if (err)
5175 return err;
5176 if (got_object_id_cmp(id,
5177 got_worktree_get_base_commit_id(worktree)) == 0)
5178 marker = "* ";
5179 else
5180 marker = "~ ";
5181 free(id);
5184 if (strncmp(refname, "refs/heads/", 11) == 0)
5185 refname += 11;
5186 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5187 refname += 18;
5189 refstr = got_ref_to_str(ref);
5190 if (refstr == NULL)
5191 return got_error_from_errno("got_ref_to_str");
5193 printf("%s%s: %s\n", marker, refname, refstr);
5194 free(refstr);
5195 return NULL;
5198 static const struct got_error *
5199 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5201 const char *refname;
5203 if (worktree == NULL)
5204 return got_error(GOT_ERR_NOT_WORKTREE);
5206 refname = got_worktree_get_head_ref_name(worktree);
5208 if (strncmp(refname, "refs/heads/", 11) == 0)
5209 refname += 11;
5210 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5211 refname += 18;
5213 printf("%s\n", refname);
5215 return NULL;
5218 static const struct got_error *
5219 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5221 static const struct got_error *err = NULL;
5222 struct got_reflist_head refs;
5223 struct got_reflist_entry *re;
5224 struct got_reference *temp_ref = NULL;
5225 int rebase_in_progress, histedit_in_progress;
5227 SIMPLEQ_INIT(&refs);
5229 if (worktree) {
5230 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5231 worktree);
5232 if (err)
5233 return err;
5235 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5236 worktree);
5237 if (err)
5238 return err;
5240 if (rebase_in_progress || histedit_in_progress) {
5241 err = got_ref_open(&temp_ref, repo,
5242 got_worktree_get_head_ref_name(worktree), 0);
5243 if (err)
5244 return err;
5245 list_branch(repo, worktree, temp_ref);
5246 got_ref_close(temp_ref);
5250 err = got_ref_list(&refs, repo, "refs/heads",
5251 got_ref_cmp_by_name, NULL);
5252 if (err)
5253 return err;
5255 SIMPLEQ_FOREACH(re, &refs, entry)
5256 list_branch(repo, worktree, re->ref);
5258 got_ref_list_free(&refs);
5259 return NULL;
5262 static const struct got_error *
5263 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5264 const char *branch_name)
5266 const struct got_error *err = NULL;
5267 struct got_reference *ref = NULL;
5268 char *refname;
5270 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5271 return got_error_from_errno("asprintf");
5273 err = got_ref_open(&ref, repo, refname, 0);
5274 if (err)
5275 goto done;
5277 if (worktree &&
5278 strcmp(got_worktree_get_head_ref_name(worktree),
5279 got_ref_get_name(ref)) == 0) {
5280 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5281 "will not delete this work tree's current branch");
5282 goto done;
5285 err = got_ref_delete(ref, repo);
5286 done:
5287 if (ref)
5288 got_ref_close(ref);
5289 free(refname);
5290 return err;
5293 static const struct got_error *
5294 add_branch(struct got_repository *repo, const char *branch_name,
5295 struct got_object_id *base_commit_id)
5297 const struct got_error *err = NULL;
5298 struct got_reference *ref = NULL;
5299 char *base_refname = NULL, *refname = NULL;
5302 * Don't let the user create a branch name with a leading '-'.
5303 * While technically a valid reference name, this case is usually
5304 * an unintended typo.
5306 if (branch_name[0] == '-')
5307 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5309 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5310 err = got_error_from_errno("asprintf");
5311 goto done;
5314 err = got_ref_open(&ref, repo, refname, 0);
5315 if (err == NULL) {
5316 err = got_error(GOT_ERR_BRANCH_EXISTS);
5317 goto done;
5318 } else if (err->code != GOT_ERR_NOT_REF)
5319 goto done;
5321 err = got_ref_alloc(&ref, refname, base_commit_id);
5322 if (err)
5323 goto done;
5325 err = got_ref_write(ref, repo);
5326 done:
5327 if (ref)
5328 got_ref_close(ref);
5329 free(base_refname);
5330 free(refname);
5331 return err;
5334 static const struct got_error *
5335 cmd_branch(int argc, char *argv[])
5337 const struct got_error *error = NULL;
5338 struct got_repository *repo = NULL;
5339 struct got_worktree *worktree = NULL;
5340 char *cwd = NULL, *repo_path = NULL;
5341 int ch, do_list = 0, do_show = 0, do_update = 1;
5342 const char *delref = NULL, *commit_id_arg = NULL;
5343 struct got_reference *ref = NULL;
5344 struct got_pathlist_head paths;
5345 struct got_pathlist_entry *pe;
5346 struct got_object_id *commit_id = NULL;
5347 char *commit_id_str = NULL;
5349 TAILQ_INIT(&paths);
5351 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5352 switch (ch) {
5353 case 'c':
5354 commit_id_arg = optarg;
5355 break;
5356 case 'd':
5357 delref = optarg;
5358 break;
5359 case 'r':
5360 repo_path = realpath(optarg, NULL);
5361 if (repo_path == NULL)
5362 return got_error_from_errno2("realpath",
5363 optarg);
5364 got_path_strip_trailing_slashes(repo_path);
5365 break;
5366 case 'l':
5367 do_list = 1;
5368 break;
5369 case 'n':
5370 do_update = 0;
5371 break;
5372 default:
5373 usage_branch();
5374 /* NOTREACHED */
5378 if (do_list && delref)
5379 errx(1, "-l and -d options are mutually exclusive");
5381 argc -= optind;
5382 argv += optind;
5384 if (!do_list && !delref && argc == 0)
5385 do_show = 1;
5387 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5388 errx(1, "-c option can only be used when creating a branch");
5390 if (do_list || delref) {
5391 if (argc > 0)
5392 usage_branch();
5393 } else if (!do_show && argc != 1)
5394 usage_branch();
5396 #ifndef PROFILE
5397 if (do_list || do_show) {
5398 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5399 NULL) == -1)
5400 err(1, "pledge");
5401 } else {
5402 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5403 "sendfd unveil", NULL) == -1)
5404 err(1, "pledge");
5406 #endif
5407 cwd = getcwd(NULL, 0);
5408 if (cwd == NULL) {
5409 error = got_error_from_errno("getcwd");
5410 goto done;
5413 if (repo_path == NULL) {
5414 error = got_worktree_open(&worktree, cwd);
5415 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5416 goto done;
5417 else
5418 error = NULL;
5419 if (worktree) {
5420 repo_path =
5421 strdup(got_worktree_get_repo_path(worktree));
5422 if (repo_path == NULL)
5423 error = got_error_from_errno("strdup");
5424 if (error)
5425 goto done;
5426 } else {
5427 repo_path = strdup(cwd);
5428 if (repo_path == NULL) {
5429 error = got_error_from_errno("strdup");
5430 goto done;
5435 error = got_repo_open(&repo, repo_path, NULL);
5436 if (error != NULL)
5437 goto done;
5439 error = apply_unveil(got_repo_get_path(repo), do_list,
5440 worktree ? got_worktree_get_root_path(worktree) : NULL);
5441 if (error)
5442 goto done;
5444 if (do_show)
5445 error = show_current_branch(repo, worktree);
5446 else if (do_list)
5447 error = list_branches(repo, worktree);
5448 else if (delref)
5449 error = delete_branch(repo, worktree, delref);
5450 else {
5451 if (commit_id_arg == NULL)
5452 commit_id_arg = worktree ?
5453 got_worktree_get_head_ref_name(worktree) :
5454 GOT_REF_HEAD;
5455 error = got_repo_match_object_id(&commit_id, NULL,
5456 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5457 if (error)
5458 goto done;
5459 error = add_branch(repo, argv[0], commit_id);
5460 if (error)
5461 goto done;
5462 if (worktree && do_update) {
5463 struct got_update_progress_arg upa;
5464 char *branch_refname = NULL;
5466 error = got_object_id_str(&commit_id_str, commit_id);
5467 if (error)
5468 goto done;
5469 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5470 worktree);
5471 if (error)
5472 goto done;
5473 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5474 == -1) {
5475 error = got_error_from_errno("asprintf");
5476 goto done;
5478 error = got_ref_open(&ref, repo, branch_refname, 0);
5479 free(branch_refname);
5480 if (error)
5481 goto done;
5482 error = switch_head_ref(ref, commit_id, worktree,
5483 repo);
5484 if (error)
5485 goto done;
5486 error = got_worktree_set_base_commit_id(worktree, repo,
5487 commit_id);
5488 if (error)
5489 goto done;
5490 memset(&upa, 0, sizeof(upa));
5491 error = got_worktree_checkout_files(worktree, &paths,
5492 repo, update_progress, &upa, check_cancelled,
5493 NULL);
5494 if (error)
5495 goto done;
5496 if (upa.did_something)
5497 printf("Updated to commit %s\n", commit_id_str);
5498 print_update_progress_stats(&upa);
5501 done:
5502 if (ref)
5503 got_ref_close(ref);
5504 if (repo)
5505 got_repo_close(repo);
5506 if (worktree)
5507 got_worktree_close(worktree);
5508 free(cwd);
5509 free(repo_path);
5510 free(commit_id);
5511 free(commit_id_str);
5512 TAILQ_FOREACH(pe, &paths, entry)
5513 free((char *)pe->path);
5514 got_pathlist_free(&paths);
5515 return error;
5519 __dead static void
5520 usage_tag(void)
5522 fprintf(stderr,
5523 "usage: %s tag [-c commit] [-r repository] [-l] "
5524 "[-m message] name\n", getprogname());
5525 exit(1);
5528 #if 0
5529 static const struct got_error *
5530 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5532 const struct got_error *err = NULL;
5533 struct got_reflist_entry *re, *se, *new;
5534 struct got_object_id *re_id, *se_id;
5535 struct got_tag_object *re_tag, *se_tag;
5536 time_t re_time, se_time;
5538 SIMPLEQ_FOREACH(re, tags, entry) {
5539 se = SIMPLEQ_FIRST(sorted);
5540 if (se == NULL) {
5541 err = got_reflist_entry_dup(&new, re);
5542 if (err)
5543 return err;
5544 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5545 continue;
5546 } else {
5547 err = got_ref_resolve(&re_id, repo, re->ref);
5548 if (err)
5549 break;
5550 err = got_object_open_as_tag(&re_tag, repo, re_id);
5551 free(re_id);
5552 if (err)
5553 break;
5554 re_time = got_object_tag_get_tagger_time(re_tag);
5555 got_object_tag_close(re_tag);
5558 while (se) {
5559 err = got_ref_resolve(&se_id, repo, re->ref);
5560 if (err)
5561 break;
5562 err = got_object_open_as_tag(&se_tag, repo, se_id);
5563 free(se_id);
5564 if (err)
5565 break;
5566 se_time = got_object_tag_get_tagger_time(se_tag);
5567 got_object_tag_close(se_tag);
5569 if (se_time > re_time) {
5570 err = got_reflist_entry_dup(&new, re);
5571 if (err)
5572 return err;
5573 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5574 break;
5576 se = SIMPLEQ_NEXT(se, entry);
5577 continue;
5580 done:
5581 return err;
5583 #endif
5585 static const struct got_error *
5586 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5588 static const struct got_error *err = NULL;
5589 struct got_reflist_head refs;
5590 struct got_reflist_entry *re;
5592 SIMPLEQ_INIT(&refs);
5594 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5595 if (err)
5596 return err;
5598 SIMPLEQ_FOREACH(re, &refs, entry) {
5599 const char *refname;
5600 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5601 char datebuf[26];
5602 const char *tagger;
5603 time_t tagger_time;
5604 struct got_object_id *id;
5605 struct got_tag_object *tag;
5606 struct got_commit_object *commit = NULL;
5608 refname = got_ref_get_name(re->ref);
5609 if (strncmp(refname, "refs/tags/", 10) != 0)
5610 continue;
5611 refname += 10;
5612 refstr = got_ref_to_str(re->ref);
5613 if (refstr == NULL) {
5614 err = got_error_from_errno("got_ref_to_str");
5615 break;
5617 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5618 free(refstr);
5620 err = got_ref_resolve(&id, repo, re->ref);
5621 if (err)
5622 break;
5623 err = got_object_open_as_tag(&tag, repo, id);
5624 if (err) {
5625 if (err->code != GOT_ERR_OBJ_TYPE) {
5626 free(id);
5627 break;
5629 /* "lightweight" tag */
5630 err = got_object_open_as_commit(&commit, repo, id);
5631 if (err) {
5632 free(id);
5633 break;
5635 tagger = got_object_commit_get_committer(commit);
5636 tagger_time =
5637 got_object_commit_get_committer_time(commit);
5638 err = got_object_id_str(&id_str, id);
5639 free(id);
5640 if (err)
5641 break;
5642 } else {
5643 free(id);
5644 tagger = got_object_tag_get_tagger(tag);
5645 tagger_time = got_object_tag_get_tagger_time(tag);
5646 err = got_object_id_str(&id_str,
5647 got_object_tag_get_object_id(tag));
5648 if (err)
5649 break;
5651 printf("from: %s\n", tagger);
5652 datestr = get_datestr(&tagger_time, datebuf);
5653 if (datestr)
5654 printf("date: %s UTC\n", datestr);
5655 if (commit)
5656 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5657 else {
5658 switch (got_object_tag_get_object_type(tag)) {
5659 case GOT_OBJ_TYPE_BLOB:
5660 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5661 id_str);
5662 break;
5663 case GOT_OBJ_TYPE_TREE:
5664 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5665 id_str);
5666 break;
5667 case GOT_OBJ_TYPE_COMMIT:
5668 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5669 id_str);
5670 break;
5671 case GOT_OBJ_TYPE_TAG:
5672 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5673 id_str);
5674 break;
5675 default:
5676 break;
5679 free(id_str);
5680 if (commit) {
5681 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5682 if (err)
5683 break;
5684 got_object_commit_close(commit);
5685 } else {
5686 tagmsg0 = strdup(got_object_tag_get_message(tag));
5687 got_object_tag_close(tag);
5688 if (tagmsg0 == NULL) {
5689 err = got_error_from_errno("strdup");
5690 break;
5694 tagmsg = tagmsg0;
5695 do {
5696 line = strsep(&tagmsg, "\n");
5697 if (line)
5698 printf(" %s\n", line);
5699 } while (line);
5700 free(tagmsg0);
5703 got_ref_list_free(&refs);
5704 return NULL;
5707 static const struct got_error *
5708 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5709 const char *tag_name, const char *repo_path)
5711 const struct got_error *err = NULL;
5712 char *template = NULL, *initial_content = NULL;
5713 char *editor = NULL;
5714 int initial_content_len;
5715 int fd = -1;
5717 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5718 err = got_error_from_errno("asprintf");
5719 goto done;
5722 initial_content_len = asprintf(&initial_content,
5723 "\n# tagging commit %s as %s\n",
5724 commit_id_str, tag_name);
5725 if (initial_content_len == -1) {
5726 err = got_error_from_errno("asprintf");
5727 goto done;
5730 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5731 if (err)
5732 goto done;
5734 if (write(fd, initial_content, initial_content_len) == -1) {
5735 err = got_error_from_errno2("write", *tagmsg_path);
5736 goto done;
5739 err = get_editor(&editor);
5740 if (err)
5741 goto done;
5742 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
5743 done:
5744 free(initial_content);
5745 free(template);
5746 free(editor);
5748 if (fd != -1 && close(fd) == -1 && err == NULL)
5749 err = got_error_from_errno2("close", *tagmsg_path);
5751 /* Editor is done; we can now apply unveil(2) */
5752 if (err == NULL)
5753 err = apply_unveil(repo_path, 0, NULL);
5754 if (err) {
5755 free(*tagmsg);
5756 *tagmsg = NULL;
5758 return err;
5761 static const struct got_error *
5762 add_tag(struct got_repository *repo, struct got_worktree *worktree,
5763 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
5765 const struct got_error *err = NULL;
5766 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5767 char *label = NULL, *commit_id_str = NULL;
5768 struct got_reference *ref = NULL;
5769 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5770 char *tagmsg_path = NULL, *tag_id_str = NULL;
5771 int preserve_tagmsg = 0;
5774 * Don't let the user create a tag name with a leading '-'.
5775 * While technically a valid reference name, this case is usually
5776 * an unintended typo.
5778 if (tag_name[0] == '-')
5779 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5781 err = get_author(&tagger, repo, worktree);
5782 if (err)
5783 return err;
5785 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5786 GOT_OBJ_TYPE_COMMIT, 1, repo);
5787 if (err)
5788 goto done;
5790 err = got_object_id_str(&commit_id_str, commit_id);
5791 if (err)
5792 goto done;
5794 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5795 refname = strdup(tag_name);
5796 if (refname == NULL) {
5797 err = got_error_from_errno("strdup");
5798 goto done;
5800 tag_name += 10;
5801 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5802 err = got_error_from_errno("asprintf");
5803 goto done;
5806 err = got_ref_open(&ref, repo, refname, 0);
5807 if (err == NULL) {
5808 err = got_error(GOT_ERR_TAG_EXISTS);
5809 goto done;
5810 } else if (err->code != GOT_ERR_NOT_REF)
5811 goto done;
5813 if (tagmsg_arg == NULL) {
5814 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5815 tag_name, got_repo_get_path(repo));
5816 if (err) {
5817 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5818 tagmsg_path != NULL)
5819 preserve_tagmsg = 1;
5820 goto done;
5824 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5825 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5826 if (err) {
5827 if (tagmsg_path)
5828 preserve_tagmsg = 1;
5829 goto done;
5832 err = got_ref_alloc(&ref, refname, tag_id);
5833 if (err) {
5834 if (tagmsg_path)
5835 preserve_tagmsg = 1;
5836 goto done;
5839 err = got_ref_write(ref, repo);
5840 if (err) {
5841 if (tagmsg_path)
5842 preserve_tagmsg = 1;
5843 goto done;
5846 err = got_object_id_str(&tag_id_str, tag_id);
5847 if (err) {
5848 if (tagmsg_path)
5849 preserve_tagmsg = 1;
5850 goto done;
5852 printf("Created tag %s\n", tag_id_str);
5853 done:
5854 if (preserve_tagmsg) {
5855 fprintf(stderr, "%s: tag message preserved in %s\n",
5856 getprogname(), tagmsg_path);
5857 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
5858 err = got_error_from_errno2("unlink", tagmsg_path);
5859 free(tag_id_str);
5860 if (ref)
5861 got_ref_close(ref);
5862 free(commit_id);
5863 free(commit_id_str);
5864 free(refname);
5865 free(tagmsg);
5866 free(tagmsg_path);
5867 free(tagger);
5868 return err;
5871 static const struct got_error *
5872 cmd_tag(int argc, char *argv[])
5874 const struct got_error *error = NULL;
5875 struct got_repository *repo = NULL;
5876 struct got_worktree *worktree = NULL;
5877 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
5878 char *gitconfig_path = NULL;
5879 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
5880 int ch, do_list = 0;
5882 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
5883 switch (ch) {
5884 case 'c':
5885 commit_id_arg = optarg;
5886 break;
5887 case 'm':
5888 tagmsg = optarg;
5889 break;
5890 case 'r':
5891 repo_path = realpath(optarg, NULL);
5892 if (repo_path == NULL)
5893 return got_error_from_errno2("realpath",
5894 optarg);
5895 got_path_strip_trailing_slashes(repo_path);
5896 break;
5897 case 'l':
5898 do_list = 1;
5899 break;
5900 default:
5901 usage_tag();
5902 /* NOTREACHED */
5906 argc -= optind;
5907 argv += optind;
5909 if (do_list) {
5910 if (commit_id_arg != NULL)
5911 errx(1,
5912 "-c option can only be used when creating a tag");
5913 if (tagmsg)
5914 errx(1, "-l and -m options are mutually exclusive");
5915 if (argc > 0)
5916 usage_tag();
5917 } else if (argc != 1)
5918 usage_tag();
5920 tag_name = argv[0];
5922 #ifndef PROFILE
5923 if (do_list) {
5924 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5925 NULL) == -1)
5926 err(1, "pledge");
5927 } else {
5928 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5929 "sendfd unveil", NULL) == -1)
5930 err(1, "pledge");
5932 #endif
5933 cwd = getcwd(NULL, 0);
5934 if (cwd == NULL) {
5935 error = got_error_from_errno("getcwd");
5936 goto done;
5939 if (repo_path == NULL) {
5940 error = got_worktree_open(&worktree, cwd);
5941 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5942 goto done;
5943 else
5944 error = NULL;
5945 if (worktree) {
5946 repo_path =
5947 strdup(got_worktree_get_repo_path(worktree));
5948 if (repo_path == NULL)
5949 error = got_error_from_errno("strdup");
5950 if (error)
5951 goto done;
5952 } else {
5953 repo_path = strdup(cwd);
5954 if (repo_path == NULL) {
5955 error = got_error_from_errno("strdup");
5956 goto done;
5961 if (do_list) {
5962 error = got_repo_open(&repo, repo_path, NULL);
5963 if (error != NULL)
5964 goto done;
5965 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5966 if (error)
5967 goto done;
5968 error = list_tags(repo, worktree);
5969 } else {
5970 error = get_gitconfig_path(&gitconfig_path);
5971 if (error)
5972 goto done;
5973 error = got_repo_open(&repo, repo_path, gitconfig_path);
5974 if (error != NULL)
5975 goto done;
5977 if (tagmsg) {
5978 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5979 if (error)
5980 goto done;
5983 if (commit_id_arg == NULL) {
5984 struct got_reference *head_ref;
5985 struct got_object_id *commit_id;
5986 error = got_ref_open(&head_ref, repo,
5987 worktree ? got_worktree_get_head_ref_name(worktree)
5988 : GOT_REF_HEAD, 0);
5989 if (error)
5990 goto done;
5991 error = got_ref_resolve(&commit_id, repo, head_ref);
5992 got_ref_close(head_ref);
5993 if (error)
5994 goto done;
5995 error = got_object_id_str(&commit_id_str, commit_id);
5996 free(commit_id);
5997 if (error)
5998 goto done;
6001 error = add_tag(repo, worktree, tag_name,
6002 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6004 done:
6005 if (repo)
6006 got_repo_close(repo);
6007 if (worktree)
6008 got_worktree_close(worktree);
6009 free(cwd);
6010 free(repo_path);
6011 free(gitconfig_path);
6012 free(commit_id_str);
6013 return error;
6016 __dead static void
6017 usage_add(void)
6019 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6020 getprogname());
6021 exit(1);
6024 static const struct got_error *
6025 add_progress(void *arg, unsigned char status, const char *path)
6027 while (path[0] == '/')
6028 path++;
6029 printf("%c %s\n", status, path);
6030 return NULL;
6033 static const struct got_error *
6034 cmd_add(int argc, char *argv[])
6036 const struct got_error *error = NULL;
6037 struct got_repository *repo = NULL;
6038 struct got_worktree *worktree = NULL;
6039 char *cwd = NULL;
6040 struct got_pathlist_head paths;
6041 struct got_pathlist_entry *pe;
6042 int ch, can_recurse = 0, no_ignores = 0;
6044 TAILQ_INIT(&paths);
6046 while ((ch = getopt(argc, argv, "IR")) != -1) {
6047 switch (ch) {
6048 case 'I':
6049 no_ignores = 1;
6050 break;
6051 case 'R':
6052 can_recurse = 1;
6053 break;
6054 default:
6055 usage_add();
6056 /* NOTREACHED */
6060 argc -= optind;
6061 argv += optind;
6063 #ifndef PROFILE
6064 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6065 NULL) == -1)
6066 err(1, "pledge");
6067 #endif
6068 if (argc < 1)
6069 usage_add();
6071 cwd = getcwd(NULL, 0);
6072 if (cwd == NULL) {
6073 error = got_error_from_errno("getcwd");
6074 goto done;
6077 error = got_worktree_open(&worktree, cwd);
6078 if (error) {
6079 if (error->code == GOT_ERR_NOT_WORKTREE)
6080 error = wrap_not_worktree_error(error, "add", cwd);
6081 goto done;
6084 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6085 NULL);
6086 if (error != NULL)
6087 goto done;
6089 error = apply_unveil(got_repo_get_path(repo), 1,
6090 got_worktree_get_root_path(worktree));
6091 if (error)
6092 goto done;
6094 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6095 if (error)
6096 goto done;
6098 if (!can_recurse && no_ignores) {
6099 error = got_error_msg(GOT_ERR_BAD_PATH,
6100 "disregarding ignores requires -R option");
6101 goto done;
6105 if (!can_recurse) {
6106 char *ondisk_path;
6107 struct stat sb;
6108 TAILQ_FOREACH(pe, &paths, entry) {
6109 if (asprintf(&ondisk_path, "%s/%s",
6110 got_worktree_get_root_path(worktree),
6111 pe->path) == -1) {
6112 error = got_error_from_errno("asprintf");
6113 goto done;
6115 if (lstat(ondisk_path, &sb) == -1) {
6116 if (errno == ENOENT) {
6117 free(ondisk_path);
6118 continue;
6120 error = got_error_from_errno2("lstat",
6121 ondisk_path);
6122 free(ondisk_path);
6123 goto done;
6125 free(ondisk_path);
6126 if (S_ISDIR(sb.st_mode)) {
6127 error = got_error_msg(GOT_ERR_BAD_PATH,
6128 "adding directories requires -R option");
6129 goto done;
6134 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6135 NULL, repo, no_ignores);
6136 done:
6137 if (repo)
6138 got_repo_close(repo);
6139 if (worktree)
6140 got_worktree_close(worktree);
6141 TAILQ_FOREACH(pe, &paths, entry)
6142 free((char *)pe->path);
6143 got_pathlist_free(&paths);
6144 free(cwd);
6145 return error;
6148 __dead static void
6149 usage_remove(void)
6151 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6152 "path ...\n", getprogname());
6153 exit(1);
6156 static const struct got_error *
6157 print_remove_status(void *arg, unsigned char status,
6158 unsigned char staged_status, const char *path)
6160 while (path[0] == '/')
6161 path++;
6162 if (status == GOT_STATUS_NONEXISTENT)
6163 return NULL;
6164 if (status == staged_status && (status == GOT_STATUS_DELETE))
6165 status = GOT_STATUS_NO_CHANGE;
6166 printf("%c%c %s\n", status, staged_status, path);
6167 return NULL;
6170 static const struct got_error *
6171 cmd_remove(int argc, char *argv[])
6173 const struct got_error *error = NULL;
6174 struct got_worktree *worktree = NULL;
6175 struct got_repository *repo = NULL;
6176 const char *status_codes = NULL;
6177 char *cwd = NULL;
6178 struct got_pathlist_head paths;
6179 struct got_pathlist_entry *pe;
6180 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6182 TAILQ_INIT(&paths);
6184 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6185 switch (ch) {
6186 case 'f':
6187 delete_local_mods = 1;
6188 break;
6189 case 'k':
6190 keep_on_disk = 1;
6191 break;
6192 case 'R':
6193 can_recurse = 1;
6194 break;
6195 case 's':
6196 for (i = 0; i < strlen(optarg); i++) {
6197 switch (optarg[i]) {
6198 case GOT_STATUS_MODIFY:
6199 delete_local_mods = 1;
6200 break;
6201 case GOT_STATUS_MISSING:
6202 break;
6203 default:
6204 errx(1, "invalid status code '%c'",
6205 optarg[i]);
6208 status_codes = optarg;
6209 break;
6210 default:
6211 usage_remove();
6212 /* NOTREACHED */
6216 argc -= optind;
6217 argv += optind;
6219 #ifndef PROFILE
6220 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6221 NULL) == -1)
6222 err(1, "pledge");
6223 #endif
6224 if (argc < 1)
6225 usage_remove();
6227 cwd = getcwd(NULL, 0);
6228 if (cwd == NULL) {
6229 error = got_error_from_errno("getcwd");
6230 goto done;
6232 error = got_worktree_open(&worktree, cwd);
6233 if (error) {
6234 if (error->code == GOT_ERR_NOT_WORKTREE)
6235 error = wrap_not_worktree_error(error, "remove", cwd);
6236 goto done;
6239 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6240 NULL);
6241 if (error)
6242 goto done;
6244 error = apply_unveil(got_repo_get_path(repo), 1,
6245 got_worktree_get_root_path(worktree));
6246 if (error)
6247 goto done;
6249 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6250 if (error)
6251 goto done;
6253 if (!can_recurse) {
6254 char *ondisk_path;
6255 struct stat sb;
6256 TAILQ_FOREACH(pe, &paths, entry) {
6257 if (asprintf(&ondisk_path, "%s/%s",
6258 got_worktree_get_root_path(worktree),
6259 pe->path) == -1) {
6260 error = got_error_from_errno("asprintf");
6261 goto done;
6263 if (lstat(ondisk_path, &sb) == -1) {
6264 if (errno == ENOENT) {
6265 free(ondisk_path);
6266 continue;
6268 error = got_error_from_errno2("lstat",
6269 ondisk_path);
6270 free(ondisk_path);
6271 goto done;
6273 free(ondisk_path);
6274 if (S_ISDIR(sb.st_mode)) {
6275 error = got_error_msg(GOT_ERR_BAD_PATH,
6276 "removing directories requires -R option");
6277 goto done;
6282 error = got_worktree_schedule_delete(worktree, &paths,
6283 delete_local_mods, status_codes, print_remove_status, NULL,
6284 repo, keep_on_disk);
6285 done:
6286 if (repo)
6287 got_repo_close(repo);
6288 if (worktree)
6289 got_worktree_close(worktree);
6290 TAILQ_FOREACH(pe, &paths, entry)
6291 free((char *)pe->path);
6292 got_pathlist_free(&paths);
6293 free(cwd);
6294 return error;
6297 __dead static void
6298 usage_revert(void)
6300 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6301 "path ...\n", getprogname());
6302 exit(1);
6305 static const struct got_error *
6306 revert_progress(void *arg, unsigned char status, const char *path)
6308 if (status == GOT_STATUS_UNVERSIONED)
6309 return NULL;
6311 while (path[0] == '/')
6312 path++;
6313 printf("%c %s\n", status, path);
6314 return NULL;
6317 struct choose_patch_arg {
6318 FILE *patch_script_file;
6319 const char *action;
6322 static const struct got_error *
6323 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6324 int nchanges, const char *action)
6326 char *line = NULL;
6327 size_t linesize = 0;
6328 ssize_t linelen;
6330 switch (status) {
6331 case GOT_STATUS_ADD:
6332 printf("A %s\n%s this addition? [y/n] ", path, action);
6333 break;
6334 case GOT_STATUS_DELETE:
6335 printf("D %s\n%s this deletion? [y/n] ", path, action);
6336 break;
6337 case GOT_STATUS_MODIFY:
6338 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6339 return got_error_from_errno("fseek");
6340 printf(GOT_COMMIT_SEP_STR);
6341 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6342 printf("%s", line);
6343 if (ferror(patch_file))
6344 return got_error_from_errno("getline");
6345 printf(GOT_COMMIT_SEP_STR);
6346 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6347 path, n, nchanges, action);
6348 break;
6349 default:
6350 return got_error_path(path, GOT_ERR_FILE_STATUS);
6353 return NULL;
6356 static const struct got_error *
6357 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6358 FILE *patch_file, int n, int nchanges)
6360 const struct got_error *err = NULL;
6361 char *line = NULL;
6362 size_t linesize = 0;
6363 ssize_t linelen;
6364 int resp = ' ';
6365 struct choose_patch_arg *a = arg;
6367 *choice = GOT_PATCH_CHOICE_NONE;
6369 if (a->patch_script_file) {
6370 char *nl;
6371 err = show_change(status, path, patch_file, n, nchanges,
6372 a->action);
6373 if (err)
6374 return err;
6375 linelen = getline(&line, &linesize, a->patch_script_file);
6376 if (linelen == -1) {
6377 if (ferror(a->patch_script_file))
6378 return got_error_from_errno("getline");
6379 return NULL;
6381 nl = strchr(line, '\n');
6382 if (nl)
6383 *nl = '\0';
6384 if (strcmp(line, "y") == 0) {
6385 *choice = GOT_PATCH_CHOICE_YES;
6386 printf("y\n");
6387 } else if (strcmp(line, "n") == 0) {
6388 *choice = GOT_PATCH_CHOICE_NO;
6389 printf("n\n");
6390 } else if (strcmp(line, "q") == 0 &&
6391 status == GOT_STATUS_MODIFY) {
6392 *choice = GOT_PATCH_CHOICE_QUIT;
6393 printf("q\n");
6394 } else
6395 printf("invalid response '%s'\n", line);
6396 free(line);
6397 return NULL;
6400 while (resp != 'y' && resp != 'n' && resp != 'q') {
6401 err = show_change(status, path, patch_file, n, nchanges,
6402 a->action);
6403 if (err)
6404 return err;
6405 resp = getchar();
6406 if (resp == '\n')
6407 resp = getchar();
6408 if (status == GOT_STATUS_MODIFY) {
6409 if (resp != 'y' && resp != 'n' && resp != 'q') {
6410 printf("invalid response '%c'\n", resp);
6411 resp = ' ';
6413 } else if (resp != 'y' && resp != 'n') {
6414 printf("invalid response '%c'\n", resp);
6415 resp = ' ';
6419 if (resp == 'y')
6420 *choice = GOT_PATCH_CHOICE_YES;
6421 else if (resp == 'n')
6422 *choice = GOT_PATCH_CHOICE_NO;
6423 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6424 *choice = GOT_PATCH_CHOICE_QUIT;
6426 return NULL;
6430 static const struct got_error *
6431 cmd_revert(int argc, char *argv[])
6433 const struct got_error *error = NULL;
6434 struct got_worktree *worktree = NULL;
6435 struct got_repository *repo = NULL;
6436 char *cwd = NULL, *path = NULL;
6437 struct got_pathlist_head paths;
6438 struct got_pathlist_entry *pe;
6439 int ch, can_recurse = 0, pflag = 0;
6440 FILE *patch_script_file = NULL;
6441 const char *patch_script_path = NULL;
6442 struct choose_patch_arg cpa;
6444 TAILQ_INIT(&paths);
6446 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6447 switch (ch) {
6448 case 'p':
6449 pflag = 1;
6450 break;
6451 case 'F':
6452 patch_script_path = optarg;
6453 break;
6454 case 'R':
6455 can_recurse = 1;
6456 break;
6457 default:
6458 usage_revert();
6459 /* NOTREACHED */
6463 argc -= optind;
6464 argv += optind;
6466 #ifndef PROFILE
6467 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6468 "unveil", NULL) == -1)
6469 err(1, "pledge");
6470 #endif
6471 if (argc < 1)
6472 usage_revert();
6473 if (patch_script_path && !pflag)
6474 errx(1, "-F option can only be used together with -p option");
6476 cwd = getcwd(NULL, 0);
6477 if (cwd == NULL) {
6478 error = got_error_from_errno("getcwd");
6479 goto done;
6481 error = got_worktree_open(&worktree, cwd);
6482 if (error) {
6483 if (error->code == GOT_ERR_NOT_WORKTREE)
6484 error = wrap_not_worktree_error(error, "revert", cwd);
6485 goto done;
6488 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6489 NULL);
6490 if (error != NULL)
6491 goto done;
6493 if (patch_script_path) {
6494 patch_script_file = fopen(patch_script_path, "r");
6495 if (patch_script_file == NULL) {
6496 error = got_error_from_errno2("fopen",
6497 patch_script_path);
6498 goto done;
6501 error = apply_unveil(got_repo_get_path(repo), 1,
6502 got_worktree_get_root_path(worktree));
6503 if (error)
6504 goto done;
6506 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6507 if (error)
6508 goto done;
6510 if (!can_recurse) {
6511 char *ondisk_path;
6512 struct stat sb;
6513 TAILQ_FOREACH(pe, &paths, entry) {
6514 if (asprintf(&ondisk_path, "%s/%s",
6515 got_worktree_get_root_path(worktree),
6516 pe->path) == -1) {
6517 error = got_error_from_errno("asprintf");
6518 goto done;
6520 if (lstat(ondisk_path, &sb) == -1) {
6521 if (errno == ENOENT) {
6522 free(ondisk_path);
6523 continue;
6525 error = got_error_from_errno2("lstat",
6526 ondisk_path);
6527 free(ondisk_path);
6528 goto done;
6530 free(ondisk_path);
6531 if (S_ISDIR(sb.st_mode)) {
6532 error = got_error_msg(GOT_ERR_BAD_PATH,
6533 "reverting directories requires -R option");
6534 goto done;
6539 cpa.patch_script_file = patch_script_file;
6540 cpa.action = "revert";
6541 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6542 pflag ? choose_patch : NULL, &cpa, repo);
6543 done:
6544 if (patch_script_file && fclose(patch_script_file) == EOF &&
6545 error == NULL)
6546 error = got_error_from_errno2("fclose", patch_script_path);
6547 if (repo)
6548 got_repo_close(repo);
6549 if (worktree)
6550 got_worktree_close(worktree);
6551 free(path);
6552 free(cwd);
6553 return error;
6556 __dead static void
6557 usage_commit(void)
6559 fprintf(stderr, "usage: %s commit [-m msg] [-S] [path ...]\n",
6560 getprogname());
6561 exit(1);
6564 struct collect_commit_logmsg_arg {
6565 const char *cmdline_log;
6566 const char *editor;
6567 const char *worktree_path;
6568 const char *branch_name;
6569 const char *repo_path;
6570 char *logmsg_path;
6574 static const struct got_error *
6575 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6576 void *arg)
6578 char *initial_content = NULL;
6579 struct got_pathlist_entry *pe;
6580 const struct got_error *err = NULL;
6581 char *template = NULL;
6582 struct collect_commit_logmsg_arg *a = arg;
6583 int initial_content_len;
6584 int fd = -1;
6585 size_t len;
6587 /* if a message was specified on the command line, just use it */
6588 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6589 len = strlen(a->cmdline_log) + 1;
6590 *logmsg = malloc(len + 1);
6591 if (*logmsg == NULL)
6592 return got_error_from_errno("malloc");
6593 strlcpy(*logmsg, a->cmdline_log, len);
6594 return NULL;
6597 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6598 return got_error_from_errno("asprintf");
6600 initial_content_len = asprintf(&initial_content,
6601 "\n# changes to be committed on branch %s:\n",
6602 a->branch_name);
6603 if (initial_content_len == -1)
6604 return got_error_from_errno("asprintf");
6606 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6607 if (err)
6608 goto done;
6610 if (write(fd, initial_content, initial_content_len) == -1) {
6611 err = got_error_from_errno2("write", a->logmsg_path);
6612 goto done;
6615 TAILQ_FOREACH(pe, commitable_paths, entry) {
6616 struct got_commitable *ct = pe->data;
6617 dprintf(fd, "# %c %s\n",
6618 got_commitable_get_status(ct),
6619 got_commitable_get_path(ct));
6622 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
6623 done:
6624 free(initial_content);
6625 free(template);
6627 if (fd != -1 && close(fd) == -1 && err == NULL)
6628 err = got_error_from_errno2("close", a->logmsg_path);
6630 /* Editor is done; we can now apply unveil(2) */
6631 if (err == NULL)
6632 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6633 if (err) {
6634 free(*logmsg);
6635 *logmsg = NULL;
6637 return err;
6640 static const struct got_error *
6641 cmd_commit(int argc, char *argv[])
6643 const struct got_error *error = NULL;
6644 struct got_worktree *worktree = NULL;
6645 struct got_repository *repo = NULL;
6646 char *cwd = NULL, *id_str = NULL;
6647 struct got_object_id *id = NULL;
6648 const char *logmsg = NULL;
6649 struct collect_commit_logmsg_arg cl_arg;
6650 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6651 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6652 int allow_bad_symlinks = 0;
6653 struct got_pathlist_head paths;
6655 TAILQ_INIT(&paths);
6656 cl_arg.logmsg_path = NULL;
6658 while ((ch = getopt(argc, argv, "m:S")) != -1) {
6659 switch (ch) {
6660 case 'm':
6661 logmsg = optarg;
6662 break;
6663 case 'S':
6664 allow_bad_symlinks = 1;
6665 break;
6666 default:
6667 usage_commit();
6668 /* NOTREACHED */
6672 argc -= optind;
6673 argv += optind;
6675 #ifndef PROFILE
6676 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6677 "unveil", NULL) == -1)
6678 err(1, "pledge");
6679 #endif
6680 cwd = getcwd(NULL, 0);
6681 if (cwd == NULL) {
6682 error = got_error_from_errno("getcwd");
6683 goto done;
6685 error = got_worktree_open(&worktree, cwd);
6686 if (error) {
6687 if (error->code == GOT_ERR_NOT_WORKTREE)
6688 error = wrap_not_worktree_error(error, "commit", cwd);
6689 goto done;
6692 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6693 if (error)
6694 goto done;
6695 if (rebase_in_progress) {
6696 error = got_error(GOT_ERR_REBASING);
6697 goto done;
6700 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6701 worktree);
6702 if (error)
6703 goto done;
6705 error = get_gitconfig_path(&gitconfig_path);
6706 if (error)
6707 goto done;
6708 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6709 gitconfig_path);
6710 if (error != NULL)
6711 goto done;
6713 error = get_author(&author, repo, worktree);
6714 if (error)
6715 return error;
6718 * unveil(2) traverses exec(2); if an editor is used we have
6719 * to apply unveil after the log message has been written.
6721 if (logmsg == NULL || strlen(logmsg) == 0)
6722 error = get_editor(&editor);
6723 else
6724 error = apply_unveil(got_repo_get_path(repo), 0,
6725 got_worktree_get_root_path(worktree));
6726 if (error)
6727 goto done;
6729 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6730 if (error)
6731 goto done;
6733 cl_arg.editor = editor;
6734 cl_arg.cmdline_log = logmsg;
6735 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6736 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6737 if (!histedit_in_progress) {
6738 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6739 error = got_error(GOT_ERR_COMMIT_BRANCH);
6740 goto done;
6742 cl_arg.branch_name += 11;
6744 cl_arg.repo_path = got_repo_get_path(repo);
6745 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6746 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
6747 print_status, NULL, repo);
6748 if (error) {
6749 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6750 cl_arg.logmsg_path != NULL)
6751 preserve_logmsg = 1;
6752 goto done;
6755 error = got_object_id_str(&id_str, id);
6756 if (error)
6757 goto done;
6758 printf("Created commit %s\n", id_str);
6759 done:
6760 if (preserve_logmsg) {
6761 fprintf(stderr, "%s: log message preserved in %s\n",
6762 getprogname(), cl_arg.logmsg_path);
6763 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6764 error == NULL)
6765 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6766 free(cl_arg.logmsg_path);
6767 if (repo)
6768 got_repo_close(repo);
6769 if (worktree)
6770 got_worktree_close(worktree);
6771 free(cwd);
6772 free(id_str);
6773 free(gitconfig_path);
6774 free(editor);
6775 free(author);
6776 return error;
6779 __dead static void
6780 usage_cherrypick(void)
6782 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6783 exit(1);
6786 static const struct got_error *
6787 cmd_cherrypick(int argc, char *argv[])
6789 const struct got_error *error = NULL;
6790 struct got_worktree *worktree = NULL;
6791 struct got_repository *repo = NULL;
6792 char *cwd = NULL, *commit_id_str = NULL;
6793 struct got_object_id *commit_id = NULL;
6794 struct got_commit_object *commit = NULL;
6795 struct got_object_qid *pid;
6796 struct got_reference *head_ref = NULL;
6797 int ch;
6798 struct got_update_progress_arg upa;
6800 while ((ch = getopt(argc, argv, "")) != -1) {
6801 switch (ch) {
6802 default:
6803 usage_cherrypick();
6804 /* NOTREACHED */
6808 argc -= optind;
6809 argv += optind;
6811 #ifndef PROFILE
6812 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6813 "unveil", NULL) == -1)
6814 err(1, "pledge");
6815 #endif
6816 if (argc != 1)
6817 usage_cherrypick();
6819 cwd = getcwd(NULL, 0);
6820 if (cwd == NULL) {
6821 error = got_error_from_errno("getcwd");
6822 goto done;
6824 error = got_worktree_open(&worktree, cwd);
6825 if (error) {
6826 if (error->code == GOT_ERR_NOT_WORKTREE)
6827 error = wrap_not_worktree_error(error, "cherrypick",
6828 cwd);
6829 goto done;
6832 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6833 NULL);
6834 if (error != NULL)
6835 goto done;
6837 error = apply_unveil(got_repo_get_path(repo), 0,
6838 got_worktree_get_root_path(worktree));
6839 if (error)
6840 goto done;
6842 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6843 GOT_OBJ_TYPE_COMMIT, repo);
6844 if (error != NULL) {
6845 struct got_reference *ref;
6846 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6847 goto done;
6848 error = got_ref_open(&ref, repo, argv[0], 0);
6849 if (error != NULL)
6850 goto done;
6851 error = got_ref_resolve(&commit_id, repo, ref);
6852 got_ref_close(ref);
6853 if (error != NULL)
6854 goto done;
6856 error = got_object_id_str(&commit_id_str, commit_id);
6857 if (error)
6858 goto done;
6860 error = got_ref_open(&head_ref, repo,
6861 got_worktree_get_head_ref_name(worktree), 0);
6862 if (error != NULL)
6863 goto done;
6865 error = check_same_branch(commit_id, head_ref, NULL, repo);
6866 if (error) {
6867 if (error->code != GOT_ERR_ANCESTRY)
6868 goto done;
6869 error = NULL;
6870 } else {
6871 error = got_error(GOT_ERR_SAME_BRANCH);
6872 goto done;
6875 error = got_object_open_as_commit(&commit, repo, commit_id);
6876 if (error)
6877 goto done;
6878 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6879 memset(&upa, 0, sizeof(upa));
6880 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
6881 commit_id, repo, update_progress, &upa, check_cancelled,
6882 NULL);
6883 if (error != NULL)
6884 goto done;
6886 if (upa.did_something)
6887 printf("Merged commit %s\n", commit_id_str);
6888 print_update_progress_stats(&upa);
6889 done:
6890 if (commit)
6891 got_object_commit_close(commit);
6892 free(commit_id_str);
6893 if (head_ref)
6894 got_ref_close(head_ref);
6895 if (worktree)
6896 got_worktree_close(worktree);
6897 if (repo)
6898 got_repo_close(repo);
6899 return error;
6902 __dead static void
6903 usage_backout(void)
6905 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
6906 exit(1);
6909 static const struct got_error *
6910 cmd_backout(int argc, char *argv[])
6912 const struct got_error *error = NULL;
6913 struct got_worktree *worktree = NULL;
6914 struct got_repository *repo = NULL;
6915 char *cwd = NULL, *commit_id_str = NULL;
6916 struct got_object_id *commit_id = NULL;
6917 struct got_commit_object *commit = NULL;
6918 struct got_object_qid *pid;
6919 struct got_reference *head_ref = NULL;
6920 int ch;
6921 struct got_update_progress_arg upa;
6923 while ((ch = getopt(argc, argv, "")) != -1) {
6924 switch (ch) {
6925 default:
6926 usage_backout();
6927 /* NOTREACHED */
6931 argc -= optind;
6932 argv += optind;
6934 #ifndef PROFILE
6935 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6936 "unveil", NULL) == -1)
6937 err(1, "pledge");
6938 #endif
6939 if (argc != 1)
6940 usage_backout();
6942 cwd = getcwd(NULL, 0);
6943 if (cwd == NULL) {
6944 error = got_error_from_errno("getcwd");
6945 goto done;
6947 error = got_worktree_open(&worktree, cwd);
6948 if (error) {
6949 if (error->code == GOT_ERR_NOT_WORKTREE)
6950 error = wrap_not_worktree_error(error, "backout", cwd);
6951 goto done;
6954 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6955 NULL);
6956 if (error != NULL)
6957 goto done;
6959 error = apply_unveil(got_repo_get_path(repo), 0,
6960 got_worktree_get_root_path(worktree));
6961 if (error)
6962 goto done;
6964 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6965 GOT_OBJ_TYPE_COMMIT, repo);
6966 if (error != NULL) {
6967 struct got_reference *ref;
6968 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6969 goto done;
6970 error = got_ref_open(&ref, repo, argv[0], 0);
6971 if (error != NULL)
6972 goto done;
6973 error = got_ref_resolve(&commit_id, repo, ref);
6974 got_ref_close(ref);
6975 if (error != NULL)
6976 goto done;
6978 error = got_object_id_str(&commit_id_str, commit_id);
6979 if (error)
6980 goto done;
6982 error = got_ref_open(&head_ref, repo,
6983 got_worktree_get_head_ref_name(worktree), 0);
6984 if (error != NULL)
6985 goto done;
6987 error = check_same_branch(commit_id, head_ref, NULL, repo);
6988 if (error)
6989 goto done;
6991 error = got_object_open_as_commit(&commit, repo, commit_id);
6992 if (error)
6993 goto done;
6994 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6995 if (pid == NULL) {
6996 error = got_error(GOT_ERR_ROOT_COMMIT);
6997 goto done;
7000 memset(&upa, 0, sizeof(upa));
7001 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
7002 update_progress, &upa, check_cancelled, NULL);
7003 if (error != NULL)
7004 goto done;
7006 if (upa.did_something)
7007 printf("Backed out commit %s\n", commit_id_str);
7008 print_update_progress_stats(&upa);
7009 done:
7010 if (commit)
7011 got_object_commit_close(commit);
7012 free(commit_id_str);
7013 if (head_ref)
7014 got_ref_close(head_ref);
7015 if (worktree)
7016 got_worktree_close(worktree);
7017 if (repo)
7018 got_repo_close(repo);
7019 return error;
7022 __dead static void
7023 usage_rebase(void)
7025 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
7026 getprogname());
7027 exit(1);
7030 void
7031 trim_logmsg(char *logmsg, int limit)
7033 char *nl;
7034 size_t len;
7036 len = strlen(logmsg);
7037 if (len > limit)
7038 len = limit;
7039 logmsg[len] = '\0';
7040 nl = strchr(logmsg, '\n');
7041 if (nl)
7042 *nl = '\0';
7045 static const struct got_error *
7046 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
7048 const struct got_error *err;
7049 char *logmsg0 = NULL;
7050 const char *s;
7052 err = got_object_commit_get_logmsg(&logmsg0, commit);
7053 if (err)
7054 return err;
7056 s = logmsg0;
7057 while (isspace((unsigned char)s[0]))
7058 s++;
7060 *logmsg = strdup(s);
7061 if (*logmsg == NULL) {
7062 err = got_error_from_errno("strdup");
7063 goto done;
7066 trim_logmsg(*logmsg, limit);
7067 done:
7068 free(logmsg0);
7069 return err;
7072 static const struct got_error *
7073 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
7075 const struct got_error *err;
7076 struct got_commit_object *commit = NULL;
7077 char *id_str = NULL, *logmsg = NULL;
7079 err = got_object_open_as_commit(&commit, repo, id);
7080 if (err)
7081 return err;
7083 err = got_object_id_str(&id_str, id);
7084 if (err)
7085 goto done;
7087 id_str[12] = '\0';
7089 err = get_short_logmsg(&logmsg, 42, commit);
7090 if (err)
7091 goto done;
7093 printf("%s -> merge conflict: %s\n", id_str, logmsg);
7094 done:
7095 free(id_str);
7096 got_object_commit_close(commit);
7097 free(logmsg);
7098 return err;
7101 static const struct got_error *
7102 show_rebase_progress(struct got_commit_object *commit,
7103 struct got_object_id *old_id, struct got_object_id *new_id)
7105 const struct got_error *err;
7106 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7108 err = got_object_id_str(&old_id_str, old_id);
7109 if (err)
7110 goto done;
7112 if (new_id) {
7113 err = got_object_id_str(&new_id_str, new_id);
7114 if (err)
7115 goto done;
7118 old_id_str[12] = '\0';
7119 if (new_id_str)
7120 new_id_str[12] = '\0';
7122 err = get_short_logmsg(&logmsg, 42, commit);
7123 if (err)
7124 goto done;
7126 printf("%s -> %s: %s\n", old_id_str,
7127 new_id_str ? new_id_str : "no-op change", logmsg);
7128 done:
7129 free(old_id_str);
7130 free(new_id_str);
7131 free(logmsg);
7132 return err;
7135 static const struct got_error *
7136 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
7137 struct got_reference *branch, struct got_reference *new_base_branch,
7138 struct got_reference *tmp_branch, struct got_repository *repo)
7140 printf("Switching work tree to %s\n", got_ref_get_name(branch));
7141 return got_worktree_rebase_complete(worktree, fileindex,
7142 new_base_branch, tmp_branch, branch, repo);
7145 static const struct got_error *
7146 rebase_commit(struct got_pathlist_head *merged_paths,
7147 struct got_worktree *worktree, struct got_fileindex *fileindex,
7148 struct got_reference *tmp_branch,
7149 struct got_object_id *commit_id, struct got_repository *repo)
7151 const struct got_error *error;
7152 struct got_commit_object *commit;
7153 struct got_object_id *new_commit_id;
7155 error = got_object_open_as_commit(&commit, repo, commit_id);
7156 if (error)
7157 return error;
7159 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
7160 worktree, fileindex, tmp_branch, commit, commit_id, repo);
7161 if (error) {
7162 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
7163 goto done;
7164 error = show_rebase_progress(commit, commit_id, NULL);
7165 } else {
7166 error = show_rebase_progress(commit, commit_id, new_commit_id);
7167 free(new_commit_id);
7169 done:
7170 got_object_commit_close(commit);
7171 return error;
7174 struct check_path_prefix_arg {
7175 const char *path_prefix;
7176 size_t len;
7177 int errcode;
7180 static const struct got_error *
7181 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
7182 struct got_blob_object *blob2, struct got_object_id *id1,
7183 struct got_object_id *id2, const char *path1, const char *path2,
7184 mode_t mode1, mode_t mode2, struct got_repository *repo)
7186 struct check_path_prefix_arg *a = arg;
7188 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
7189 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
7190 return got_error(a->errcode);
7192 return NULL;
7195 static const struct got_error *
7196 check_path_prefix(struct got_object_id *parent_id,
7197 struct got_object_id *commit_id, const char *path_prefix,
7198 int errcode, struct got_repository *repo)
7200 const struct got_error *err;
7201 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7202 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7203 struct check_path_prefix_arg cpp_arg;
7205 if (got_path_is_root_dir(path_prefix))
7206 return NULL;
7208 err = got_object_open_as_commit(&commit, repo, commit_id);
7209 if (err)
7210 goto done;
7212 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7213 if (err)
7214 goto done;
7216 err = got_object_open_as_tree(&tree1, repo,
7217 got_object_commit_get_tree_id(parent_commit));
7218 if (err)
7219 goto done;
7221 err = got_object_open_as_tree(&tree2, repo,
7222 got_object_commit_get_tree_id(commit));
7223 if (err)
7224 goto done;
7226 cpp_arg.path_prefix = path_prefix;
7227 while (cpp_arg.path_prefix[0] == '/')
7228 cpp_arg.path_prefix++;
7229 cpp_arg.len = strlen(cpp_arg.path_prefix);
7230 cpp_arg.errcode = errcode;
7231 err = got_diff_tree(tree1, tree2, "", "", repo,
7232 check_path_prefix_in_diff, &cpp_arg, 0);
7233 done:
7234 if (tree1)
7235 got_object_tree_close(tree1);
7236 if (tree2)
7237 got_object_tree_close(tree2);
7238 if (commit)
7239 got_object_commit_close(commit);
7240 if (parent_commit)
7241 got_object_commit_close(parent_commit);
7242 return err;
7245 static const struct got_error *
7246 collect_commits(struct got_object_id_queue *commits,
7247 struct got_object_id *initial_commit_id,
7248 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7249 const char *path_prefix, int path_prefix_errcode,
7250 struct got_repository *repo)
7252 const struct got_error *err = NULL;
7253 struct got_commit_graph *graph = NULL;
7254 struct got_object_id *parent_id = NULL;
7255 struct got_object_qid *qid;
7256 struct got_object_id *commit_id = initial_commit_id;
7258 err = got_commit_graph_open(&graph, "/", 1);
7259 if (err)
7260 return err;
7262 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7263 check_cancelled, NULL);
7264 if (err)
7265 goto done;
7266 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7267 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7268 check_cancelled, NULL);
7269 if (err) {
7270 if (err->code == GOT_ERR_ITER_COMPLETED) {
7271 err = got_error_msg(GOT_ERR_ANCESTRY,
7272 "ran out of commits to rebase before "
7273 "youngest common ancestor commit has "
7274 "been reached?!?");
7276 goto done;
7277 } else {
7278 err = check_path_prefix(parent_id, commit_id,
7279 path_prefix, path_prefix_errcode, repo);
7280 if (err)
7281 goto done;
7283 err = got_object_qid_alloc(&qid, commit_id);
7284 if (err)
7285 goto done;
7286 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
7287 commit_id = parent_id;
7290 done:
7291 got_commit_graph_close(graph);
7292 return err;
7295 static const struct got_error *
7296 cmd_rebase(int argc, char *argv[])
7298 const struct got_error *error = NULL;
7299 struct got_worktree *worktree = NULL;
7300 struct got_repository *repo = NULL;
7301 struct got_fileindex *fileindex = NULL;
7302 char *cwd = NULL;
7303 struct got_reference *branch = NULL;
7304 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
7305 struct got_object_id *commit_id = NULL, *parent_id = NULL;
7306 struct got_object_id *resume_commit_id = NULL;
7307 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
7308 struct got_commit_object *commit = NULL;
7309 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
7310 int histedit_in_progress = 0;
7311 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7312 struct got_object_id_queue commits;
7313 struct got_pathlist_head merged_paths;
7314 const struct got_object_id_queue *parent_ids;
7315 struct got_object_qid *qid, *pid;
7317 SIMPLEQ_INIT(&commits);
7318 TAILQ_INIT(&merged_paths);
7320 while ((ch = getopt(argc, argv, "ac")) != -1) {
7321 switch (ch) {
7322 case 'a':
7323 abort_rebase = 1;
7324 break;
7325 case 'c':
7326 continue_rebase = 1;
7327 break;
7328 default:
7329 usage_rebase();
7330 /* NOTREACHED */
7334 argc -= optind;
7335 argv += optind;
7337 #ifndef PROFILE
7338 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7339 "unveil", NULL) == -1)
7340 err(1, "pledge");
7341 #endif
7342 if (abort_rebase && continue_rebase)
7343 usage_rebase();
7344 else if (abort_rebase || continue_rebase) {
7345 if (argc != 0)
7346 usage_rebase();
7347 } else if (argc != 1)
7348 usage_rebase();
7350 cwd = getcwd(NULL, 0);
7351 if (cwd == NULL) {
7352 error = got_error_from_errno("getcwd");
7353 goto done;
7355 error = got_worktree_open(&worktree, cwd);
7356 if (error) {
7357 if (error->code == GOT_ERR_NOT_WORKTREE)
7358 error = wrap_not_worktree_error(error, "rebase", cwd);
7359 goto done;
7362 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7363 NULL);
7364 if (error != NULL)
7365 goto done;
7367 error = apply_unveil(got_repo_get_path(repo), 0,
7368 got_worktree_get_root_path(worktree));
7369 if (error)
7370 goto done;
7372 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7373 worktree);
7374 if (error)
7375 goto done;
7376 if (histedit_in_progress) {
7377 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7378 goto done;
7381 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7382 if (error)
7383 goto done;
7385 if (abort_rebase) {
7386 struct got_update_progress_arg upa;
7387 if (!rebase_in_progress) {
7388 error = got_error(GOT_ERR_NOT_REBASING);
7389 goto done;
7391 error = got_worktree_rebase_continue(&resume_commit_id,
7392 &new_base_branch, &tmp_branch, &branch, &fileindex,
7393 worktree, repo);
7394 if (error)
7395 goto done;
7396 printf("Switching work tree to %s\n",
7397 got_ref_get_symref_target(new_base_branch));
7398 memset(&upa, 0, sizeof(upa));
7399 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7400 new_base_branch, update_progress, &upa);
7401 if (error)
7402 goto done;
7403 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7404 print_update_progress_stats(&upa);
7405 goto done; /* nothing else to do */
7408 if (continue_rebase) {
7409 if (!rebase_in_progress) {
7410 error = got_error(GOT_ERR_NOT_REBASING);
7411 goto done;
7413 error = got_worktree_rebase_continue(&resume_commit_id,
7414 &new_base_branch, &tmp_branch, &branch, &fileindex,
7415 worktree, repo);
7416 if (error)
7417 goto done;
7419 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7420 resume_commit_id, repo);
7421 if (error)
7422 goto done;
7424 yca_id = got_object_id_dup(resume_commit_id);
7425 if (yca_id == NULL) {
7426 error = got_error_from_errno("got_object_id_dup");
7427 goto done;
7429 } else {
7430 error = got_ref_open(&branch, repo, argv[0], 0);
7431 if (error != NULL)
7432 goto done;
7435 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7436 if (error)
7437 goto done;
7439 if (!continue_rebase) {
7440 struct got_object_id *base_commit_id;
7442 base_commit_id = got_worktree_get_base_commit_id(worktree);
7443 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7444 base_commit_id, branch_head_commit_id, repo,
7445 check_cancelled, NULL);
7446 if (error)
7447 goto done;
7448 if (yca_id == NULL) {
7449 error = got_error_msg(GOT_ERR_ANCESTRY,
7450 "specified branch shares no common ancestry "
7451 "with work tree's branch");
7452 goto done;
7455 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7456 if (error) {
7457 if (error->code != GOT_ERR_ANCESTRY)
7458 goto done;
7459 error = NULL;
7460 } else {
7461 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7462 "specified branch resolves to a commit which "
7463 "is already contained in work tree's branch");
7464 goto done;
7466 error = got_worktree_rebase_prepare(&new_base_branch,
7467 &tmp_branch, &fileindex, worktree, branch, repo);
7468 if (error)
7469 goto done;
7472 commit_id = branch_head_commit_id;
7473 error = got_object_open_as_commit(&commit, repo, commit_id);
7474 if (error)
7475 goto done;
7477 parent_ids = got_object_commit_get_parent_ids(commit);
7478 pid = SIMPLEQ_FIRST(parent_ids);
7479 if (pid == NULL) {
7480 if (!continue_rebase) {
7481 struct got_update_progress_arg upa;
7482 memset(&upa, 0, sizeof(upa));
7483 error = got_worktree_rebase_abort(worktree, fileindex,
7484 repo, new_base_branch, update_progress, &upa);
7485 if (error)
7486 goto done;
7487 printf("Rebase of %s aborted\n",
7488 got_ref_get_name(branch));
7489 print_update_progress_stats(&upa);
7492 error = got_error(GOT_ERR_EMPTY_REBASE);
7493 goto done;
7495 error = collect_commits(&commits, commit_id, pid->id,
7496 yca_id, got_worktree_get_path_prefix(worktree),
7497 GOT_ERR_REBASE_PATH, repo);
7498 got_object_commit_close(commit);
7499 commit = NULL;
7500 if (error)
7501 goto done;
7503 if (SIMPLEQ_EMPTY(&commits)) {
7504 if (continue_rebase) {
7505 error = rebase_complete(worktree, fileindex,
7506 branch, new_base_branch, tmp_branch, repo);
7507 goto done;
7508 } else {
7509 /* Fast-forward the reference of the branch. */
7510 struct got_object_id *new_head_commit_id;
7511 char *id_str;
7512 error = got_ref_resolve(&new_head_commit_id, repo,
7513 new_base_branch);
7514 if (error)
7515 goto done;
7516 error = got_object_id_str(&id_str, new_head_commit_id);
7517 printf("Forwarding %s to commit %s\n",
7518 got_ref_get_name(branch), id_str);
7519 free(id_str);
7520 error = got_ref_change_ref(branch,
7521 new_head_commit_id);
7522 if (error)
7523 goto done;
7527 pid = NULL;
7528 SIMPLEQ_FOREACH(qid, &commits, entry) {
7529 struct got_update_progress_arg upa;
7531 commit_id = qid->id;
7532 parent_id = pid ? pid->id : yca_id;
7533 pid = qid;
7535 memset(&upa, 0, sizeof(upa));
7536 error = got_worktree_rebase_merge_files(&merged_paths,
7537 worktree, fileindex, parent_id, commit_id, repo,
7538 update_progress, &upa, check_cancelled, NULL);
7539 if (error)
7540 goto done;
7542 print_update_progress_stats(&upa);
7543 if (upa.conflicts > 0)
7544 rebase_status = GOT_STATUS_CONFLICT;
7546 if (rebase_status == GOT_STATUS_CONFLICT) {
7547 error = show_rebase_merge_conflict(qid->id, repo);
7548 if (error)
7549 goto done;
7550 got_worktree_rebase_pathlist_free(&merged_paths);
7551 break;
7554 error = rebase_commit(&merged_paths, worktree, fileindex,
7555 tmp_branch, commit_id, repo);
7556 got_worktree_rebase_pathlist_free(&merged_paths);
7557 if (error)
7558 goto done;
7561 if (rebase_status == GOT_STATUS_CONFLICT) {
7562 error = got_worktree_rebase_postpone(worktree, fileindex);
7563 if (error)
7564 goto done;
7565 error = got_error_msg(GOT_ERR_CONFLICTS,
7566 "conflicts must be resolved before rebasing can continue");
7567 } else
7568 error = rebase_complete(worktree, fileindex, branch,
7569 new_base_branch, tmp_branch, repo);
7570 done:
7571 got_object_id_queue_free(&commits);
7572 free(branch_head_commit_id);
7573 free(resume_commit_id);
7574 free(yca_id);
7575 if (commit)
7576 got_object_commit_close(commit);
7577 if (branch)
7578 got_ref_close(branch);
7579 if (new_base_branch)
7580 got_ref_close(new_base_branch);
7581 if (tmp_branch)
7582 got_ref_close(tmp_branch);
7583 if (worktree)
7584 got_worktree_close(worktree);
7585 if (repo)
7586 got_repo_close(repo);
7587 return error;
7590 __dead static void
7591 usage_histedit(void)
7593 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
7594 getprogname());
7595 exit(1);
7598 #define GOT_HISTEDIT_PICK 'p'
7599 #define GOT_HISTEDIT_EDIT 'e'
7600 #define GOT_HISTEDIT_FOLD 'f'
7601 #define GOT_HISTEDIT_DROP 'd'
7602 #define GOT_HISTEDIT_MESG 'm'
7604 static struct got_histedit_cmd {
7605 unsigned char code;
7606 const char *name;
7607 const char *desc;
7608 } got_histedit_cmds[] = {
7609 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7610 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7611 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7612 "be used" },
7613 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7614 { GOT_HISTEDIT_MESG, "mesg",
7615 "single-line log message for commit above (open editor if empty)" },
7618 struct got_histedit_list_entry {
7619 TAILQ_ENTRY(got_histedit_list_entry) entry;
7620 struct got_object_id *commit_id;
7621 const struct got_histedit_cmd *cmd;
7622 char *logmsg;
7624 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7626 static const struct got_error *
7627 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7628 FILE *f, struct got_repository *repo)
7630 const struct got_error *err = NULL;
7631 char *logmsg = NULL, *id_str = NULL;
7632 struct got_commit_object *commit = NULL;
7633 int n;
7635 err = got_object_open_as_commit(&commit, repo, commit_id);
7636 if (err)
7637 goto done;
7639 err = get_short_logmsg(&logmsg, 34, commit);
7640 if (err)
7641 goto done;
7643 err = got_object_id_str(&id_str, commit_id);
7644 if (err)
7645 goto done;
7647 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7648 if (n < 0)
7649 err = got_ferror(f, GOT_ERR_IO);
7650 done:
7651 if (commit)
7652 got_object_commit_close(commit);
7653 free(id_str);
7654 free(logmsg);
7655 return err;
7658 static const struct got_error *
7659 histedit_write_commit_list(struct got_object_id_queue *commits,
7660 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7662 const struct got_error *err = NULL;
7663 struct got_object_qid *qid;
7665 if (SIMPLEQ_EMPTY(commits))
7666 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7668 SIMPLEQ_FOREACH(qid, commits, entry) {
7669 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7670 f, repo);
7671 if (err)
7672 break;
7673 if (edit_logmsg_only) {
7674 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7675 if (n < 0) {
7676 err = got_ferror(f, GOT_ERR_IO);
7677 break;
7682 return err;
7685 static const struct got_error *
7686 write_cmd_list(FILE *f, const char *branch_name,
7687 struct got_object_id_queue *commits)
7689 const struct got_error *err = NULL;
7690 int n, i;
7691 char *id_str;
7692 struct got_object_qid *qid;
7694 qid = SIMPLEQ_FIRST(commits);
7695 err = got_object_id_str(&id_str, qid->id);
7696 if (err)
7697 return err;
7699 n = fprintf(f,
7700 "# Editing the history of branch '%s' starting at\n"
7701 "# commit %s\n"
7702 "# Commits will be processed in order from top to "
7703 "bottom of this file.\n", branch_name, id_str);
7704 if (n < 0) {
7705 err = got_ferror(f, GOT_ERR_IO);
7706 goto done;
7709 n = fprintf(f, "# Available histedit commands:\n");
7710 if (n < 0) {
7711 err = got_ferror(f, GOT_ERR_IO);
7712 goto done;
7715 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7716 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7717 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7718 cmd->desc);
7719 if (n < 0) {
7720 err = got_ferror(f, GOT_ERR_IO);
7721 break;
7724 done:
7725 free(id_str);
7726 return err;
7729 static const struct got_error *
7730 histedit_syntax_error(int lineno)
7732 static char msg[42];
7733 int ret;
7735 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7736 lineno);
7737 if (ret == -1 || ret >= sizeof(msg))
7738 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7740 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7743 static const struct got_error *
7744 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7745 char *logmsg, struct got_repository *repo)
7747 const struct got_error *err;
7748 struct got_commit_object *folded_commit = NULL;
7749 char *id_str, *folded_logmsg = NULL;
7751 err = got_object_id_str(&id_str, hle->commit_id);
7752 if (err)
7753 return err;
7755 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7756 if (err)
7757 goto done;
7759 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7760 if (err)
7761 goto done;
7762 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7763 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7764 folded_logmsg) == -1) {
7765 err = got_error_from_errno("asprintf");
7767 done:
7768 if (folded_commit)
7769 got_object_commit_close(folded_commit);
7770 free(id_str);
7771 free(folded_logmsg);
7772 return err;
7775 static struct got_histedit_list_entry *
7776 get_folded_commits(struct got_histedit_list_entry *hle)
7778 struct got_histedit_list_entry *prev, *folded = NULL;
7780 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7781 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7782 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7783 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7784 folded = prev;
7785 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7788 return folded;
7791 static const struct got_error *
7792 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7793 struct got_repository *repo)
7795 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7796 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7797 const struct got_error *err = NULL;
7798 struct got_commit_object *commit = NULL;
7799 int logmsg_len;
7800 int fd;
7801 struct got_histedit_list_entry *folded = NULL;
7803 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7804 if (err)
7805 return err;
7807 folded = get_folded_commits(hle);
7808 if (folded) {
7809 while (folded != hle) {
7810 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7811 folded = TAILQ_NEXT(folded, entry);
7812 continue;
7814 err = append_folded_commit_msg(&new_msg, folded,
7815 logmsg, repo);
7816 if (err)
7817 goto done;
7818 free(logmsg);
7819 logmsg = new_msg;
7820 folded = TAILQ_NEXT(folded, entry);
7824 err = got_object_id_str(&id_str, hle->commit_id);
7825 if (err)
7826 goto done;
7827 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7828 if (err)
7829 goto done;
7830 logmsg_len = asprintf(&new_msg,
7831 "%s\n# original log message of commit %s: %s",
7832 logmsg ? logmsg : "", id_str, orig_logmsg);
7833 if (logmsg_len == -1) {
7834 err = got_error_from_errno("asprintf");
7835 goto done;
7837 free(logmsg);
7838 logmsg = new_msg;
7840 err = got_object_id_str(&id_str, hle->commit_id);
7841 if (err)
7842 goto done;
7844 err = got_opentemp_named_fd(&logmsg_path, &fd,
7845 GOT_TMPDIR_STR "/got-logmsg");
7846 if (err)
7847 goto done;
7849 write(fd, logmsg, logmsg_len);
7850 close(fd);
7852 err = get_editor(&editor);
7853 if (err)
7854 goto done;
7856 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
7857 if (err) {
7858 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
7859 goto done;
7860 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
7862 done:
7863 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
7864 err = got_error_from_errno2("unlink", logmsg_path);
7865 free(logmsg_path);
7866 free(logmsg);
7867 free(orig_logmsg);
7868 free(editor);
7869 if (commit)
7870 got_object_commit_close(commit);
7871 return err;
7874 static const struct got_error *
7875 histedit_parse_list(struct got_histedit_list *histedit_cmds,
7876 FILE *f, struct got_repository *repo)
7878 const struct got_error *err = NULL;
7879 char *line = NULL, *p, *end;
7880 size_t size;
7881 ssize_t len;
7882 int lineno = 0, i;
7883 const struct got_histedit_cmd *cmd;
7884 struct got_object_id *commit_id = NULL;
7885 struct got_histedit_list_entry *hle = NULL;
7887 for (;;) {
7888 len = getline(&line, &size, f);
7889 if (len == -1) {
7890 const struct got_error *getline_err;
7891 if (feof(f))
7892 break;
7893 getline_err = got_error_from_errno("getline");
7894 err = got_ferror(f, getline_err->code);
7895 break;
7897 lineno++;
7898 p = line;
7899 while (isspace((unsigned char)p[0]))
7900 p++;
7901 if (p[0] == '#' || p[0] == '\0') {
7902 free(line);
7903 line = NULL;
7904 continue;
7906 cmd = NULL;
7907 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7908 cmd = &got_histedit_cmds[i];
7909 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
7910 isspace((unsigned char)p[strlen(cmd->name)])) {
7911 p += strlen(cmd->name);
7912 break;
7914 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
7915 p++;
7916 break;
7919 if (i == nitems(got_histedit_cmds)) {
7920 err = histedit_syntax_error(lineno);
7921 break;
7923 while (isspace((unsigned char)p[0]))
7924 p++;
7925 if (cmd->code == GOT_HISTEDIT_MESG) {
7926 if (hle == NULL || hle->logmsg != NULL) {
7927 err = got_error(GOT_ERR_HISTEDIT_CMD);
7928 break;
7930 if (p[0] == '\0') {
7931 err = histedit_edit_logmsg(hle, repo);
7932 if (err)
7933 break;
7934 } else {
7935 hle->logmsg = strdup(p);
7936 if (hle->logmsg == NULL) {
7937 err = got_error_from_errno("strdup");
7938 break;
7941 free(line);
7942 line = NULL;
7943 continue;
7944 } else {
7945 end = p;
7946 while (end[0] && !isspace((unsigned char)end[0]))
7947 end++;
7948 *end = '\0';
7950 err = got_object_resolve_id_str(&commit_id, repo, p);
7951 if (err) {
7952 /* override error code */
7953 err = histedit_syntax_error(lineno);
7954 break;
7957 hle = malloc(sizeof(*hle));
7958 if (hle == NULL) {
7959 err = got_error_from_errno("malloc");
7960 break;
7962 hle->cmd = cmd;
7963 hle->commit_id = commit_id;
7964 hle->logmsg = NULL;
7965 commit_id = NULL;
7966 free(line);
7967 line = NULL;
7968 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
7971 free(line);
7972 free(commit_id);
7973 return err;
7976 static const struct got_error *
7977 histedit_check_script(struct got_histedit_list *histedit_cmds,
7978 struct got_object_id_queue *commits, struct got_repository *repo)
7980 const struct got_error *err = NULL;
7981 struct got_object_qid *qid;
7982 struct got_histedit_list_entry *hle;
7983 static char msg[92];
7984 char *id_str;
7986 if (TAILQ_EMPTY(histedit_cmds))
7987 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
7988 "histedit script contains no commands");
7989 if (SIMPLEQ_EMPTY(commits))
7990 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7992 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7993 struct got_histedit_list_entry *hle2;
7994 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
7995 if (hle == hle2)
7996 continue;
7997 if (got_object_id_cmp(hle->commit_id,
7998 hle2->commit_id) != 0)
7999 continue;
8000 err = got_object_id_str(&id_str, hle->commit_id);
8001 if (err)
8002 return err;
8003 snprintf(msg, sizeof(msg), "commit %s is listed "
8004 "more than once in histedit script", id_str);
8005 free(id_str);
8006 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8010 SIMPLEQ_FOREACH(qid, commits, entry) {
8011 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8012 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
8013 break;
8015 if (hle == NULL) {
8016 err = got_object_id_str(&id_str, qid->id);
8017 if (err)
8018 return err;
8019 snprintf(msg, sizeof(msg),
8020 "commit %s missing from histedit script", id_str);
8021 free(id_str);
8022 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8026 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
8027 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
8028 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
8029 "last commit in histedit script cannot be folded");
8031 return NULL;
8034 static const struct got_error *
8035 histedit_run_editor(struct got_histedit_list *histedit_cmds,
8036 const char *path, struct got_object_id_queue *commits,
8037 struct got_repository *repo)
8039 const struct got_error *err = NULL;
8040 char *editor;
8041 FILE *f = NULL;
8043 err = get_editor(&editor);
8044 if (err)
8045 return err;
8047 if (spawn_editor(editor, path) == -1) {
8048 err = got_error_from_errno("failed spawning editor");
8049 goto done;
8052 f = fopen(path, "r");
8053 if (f == NULL) {
8054 err = got_error_from_errno("fopen");
8055 goto done;
8057 err = histedit_parse_list(histedit_cmds, f, repo);
8058 if (err)
8059 goto done;
8061 err = histedit_check_script(histedit_cmds, commits, repo);
8062 done:
8063 if (f && fclose(f) != 0 && err == NULL)
8064 err = got_error_from_errno("fclose");
8065 free(editor);
8066 return err;
8069 static const struct got_error *
8070 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
8071 struct got_object_id_queue *, const char *, const char *,
8072 struct got_repository *);
8074 static const struct got_error *
8075 histedit_edit_script(struct got_histedit_list *histedit_cmds,
8076 struct got_object_id_queue *commits, const char *branch_name,
8077 int edit_logmsg_only, struct got_repository *repo)
8079 const struct got_error *err;
8080 FILE *f = NULL;
8081 char *path = NULL;
8083 err = got_opentemp_named(&path, &f, "got-histedit");
8084 if (err)
8085 return err;
8087 err = write_cmd_list(f, branch_name, commits);
8088 if (err)
8089 goto done;
8091 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
8092 if (err)
8093 goto done;
8095 if (edit_logmsg_only) {
8096 rewind(f);
8097 err = histedit_parse_list(histedit_cmds, f, repo);
8098 } else {
8099 if (fclose(f) != 0) {
8100 err = got_error_from_errno("fclose");
8101 goto done;
8103 f = NULL;
8104 err = histedit_run_editor(histedit_cmds, path, commits, repo);
8105 if (err) {
8106 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8107 err->code != GOT_ERR_HISTEDIT_CMD)
8108 goto done;
8109 err = histedit_edit_list_retry(histedit_cmds, err,
8110 commits, path, branch_name, repo);
8113 done:
8114 if (f && fclose(f) != 0 && err == NULL)
8115 err = got_error_from_errno("fclose");
8116 if (path && unlink(path) != 0 && err == NULL)
8117 err = got_error_from_errno2("unlink", path);
8118 free(path);
8119 return err;
8122 static const struct got_error *
8123 histedit_save_list(struct got_histedit_list *histedit_cmds,
8124 struct got_worktree *worktree, struct got_repository *repo)
8126 const struct got_error *err = NULL;
8127 char *path = NULL;
8128 FILE *f = NULL;
8129 struct got_histedit_list_entry *hle;
8130 struct got_commit_object *commit = NULL;
8132 err = got_worktree_get_histedit_script_path(&path, worktree);
8133 if (err)
8134 return err;
8136 f = fopen(path, "w");
8137 if (f == NULL) {
8138 err = got_error_from_errno2("fopen", path);
8139 goto done;
8141 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8142 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
8143 repo);
8144 if (err)
8145 break;
8147 if (hle->logmsg) {
8148 int n = fprintf(f, "%c %s\n",
8149 GOT_HISTEDIT_MESG, hle->logmsg);
8150 if (n < 0) {
8151 err = got_ferror(f, GOT_ERR_IO);
8152 break;
8156 done:
8157 if (f && fclose(f) != 0 && err == NULL)
8158 err = got_error_from_errno("fclose");
8159 free(path);
8160 if (commit)
8161 got_object_commit_close(commit);
8162 return err;
8165 void
8166 histedit_free_list(struct got_histedit_list *histedit_cmds)
8168 struct got_histedit_list_entry *hle;
8170 while ((hle = TAILQ_FIRST(histedit_cmds))) {
8171 TAILQ_REMOVE(histedit_cmds, hle, entry);
8172 free(hle);
8176 static const struct got_error *
8177 histedit_load_list(struct got_histedit_list *histedit_cmds,
8178 const char *path, struct got_repository *repo)
8180 const struct got_error *err = NULL;
8181 FILE *f = NULL;
8183 f = fopen(path, "r");
8184 if (f == NULL) {
8185 err = got_error_from_errno2("fopen", path);
8186 goto done;
8189 err = histedit_parse_list(histedit_cmds, f, repo);
8190 done:
8191 if (f && fclose(f) != 0 && err == NULL)
8192 err = got_error_from_errno("fclose");
8193 return err;
8196 static const struct got_error *
8197 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
8198 const struct got_error *edit_err, struct got_object_id_queue *commits,
8199 const char *path, const char *branch_name, struct got_repository *repo)
8201 const struct got_error *err = NULL, *prev_err = edit_err;
8202 int resp = ' ';
8204 while (resp != 'c' && resp != 'r' && resp != 'a') {
8205 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
8206 "or (a)bort: ", getprogname(), prev_err->msg);
8207 resp = getchar();
8208 if (resp == '\n')
8209 resp = getchar();
8210 if (resp == 'c') {
8211 histedit_free_list(histedit_cmds);
8212 err = histedit_run_editor(histedit_cmds, path, commits,
8213 repo);
8214 if (err) {
8215 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8216 err->code != GOT_ERR_HISTEDIT_CMD)
8217 break;
8218 prev_err = err;
8219 resp = ' ';
8220 continue;
8222 break;
8223 } else if (resp == 'r') {
8224 histedit_free_list(histedit_cmds);
8225 err = histedit_edit_script(histedit_cmds,
8226 commits, branch_name, 0, repo);
8227 if (err) {
8228 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8229 err->code != GOT_ERR_HISTEDIT_CMD)
8230 break;
8231 prev_err = err;
8232 resp = ' ';
8233 continue;
8235 break;
8236 } else if (resp == 'a') {
8237 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
8238 break;
8239 } else
8240 printf("invalid response '%c'\n", resp);
8243 return err;
8246 static const struct got_error *
8247 histedit_complete(struct got_worktree *worktree,
8248 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
8249 struct got_reference *branch, struct got_repository *repo)
8251 printf("Switching work tree to %s\n",
8252 got_ref_get_symref_target(branch));
8253 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
8254 branch, repo);
8257 static const struct got_error *
8258 show_histedit_progress(struct got_commit_object *commit,
8259 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
8261 const struct got_error *err;
8262 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8264 err = got_object_id_str(&old_id_str, hle->commit_id);
8265 if (err)
8266 goto done;
8268 if (new_id) {
8269 err = got_object_id_str(&new_id_str, new_id);
8270 if (err)
8271 goto done;
8274 old_id_str[12] = '\0';
8275 if (new_id_str)
8276 new_id_str[12] = '\0';
8278 if (hle->logmsg) {
8279 logmsg = strdup(hle->logmsg);
8280 if (logmsg == NULL) {
8281 err = got_error_from_errno("strdup");
8282 goto done;
8284 trim_logmsg(logmsg, 42);
8285 } else {
8286 err = get_short_logmsg(&logmsg, 42, commit);
8287 if (err)
8288 goto done;
8291 switch (hle->cmd->code) {
8292 case GOT_HISTEDIT_PICK:
8293 case GOT_HISTEDIT_EDIT:
8294 printf("%s -> %s: %s\n", old_id_str,
8295 new_id_str ? new_id_str : "no-op change", logmsg);
8296 break;
8297 case GOT_HISTEDIT_DROP:
8298 case GOT_HISTEDIT_FOLD:
8299 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
8300 logmsg);
8301 break;
8302 default:
8303 break;
8305 done:
8306 free(old_id_str);
8307 free(new_id_str);
8308 return err;
8311 static const struct got_error *
8312 histedit_commit(struct got_pathlist_head *merged_paths,
8313 struct got_worktree *worktree, struct got_fileindex *fileindex,
8314 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
8315 struct got_repository *repo)
8317 const struct got_error *err;
8318 struct got_commit_object *commit;
8319 struct got_object_id *new_commit_id;
8321 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
8322 && hle->logmsg == NULL) {
8323 err = histedit_edit_logmsg(hle, repo);
8324 if (err)
8325 return err;
8328 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8329 if (err)
8330 return err;
8332 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
8333 worktree, fileindex, tmp_branch, commit, hle->commit_id,
8334 hle->logmsg, repo);
8335 if (err) {
8336 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
8337 goto done;
8338 err = show_histedit_progress(commit, hle, NULL);
8339 } else {
8340 err = show_histedit_progress(commit, hle, new_commit_id);
8341 free(new_commit_id);
8343 done:
8344 got_object_commit_close(commit);
8345 return err;
8348 static const struct got_error *
8349 histedit_skip_commit(struct got_histedit_list_entry *hle,
8350 struct got_worktree *worktree, struct got_repository *repo)
8352 const struct got_error *error;
8353 struct got_commit_object *commit;
8355 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
8356 repo);
8357 if (error)
8358 return error;
8360 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
8361 if (error)
8362 return error;
8364 error = show_histedit_progress(commit, hle, NULL);
8365 got_object_commit_close(commit);
8366 return error;
8369 static const struct got_error *
8370 check_local_changes(void *arg, unsigned char status,
8371 unsigned char staged_status, const char *path,
8372 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8373 struct got_object_id *commit_id, int dirfd, const char *de_name)
8375 int *have_local_changes = arg;
8377 switch (status) {
8378 case GOT_STATUS_ADD:
8379 case GOT_STATUS_DELETE:
8380 case GOT_STATUS_MODIFY:
8381 case GOT_STATUS_CONFLICT:
8382 *have_local_changes = 1;
8383 return got_error(GOT_ERR_CANCELLED);
8384 default:
8385 break;
8388 switch (staged_status) {
8389 case GOT_STATUS_ADD:
8390 case GOT_STATUS_DELETE:
8391 case GOT_STATUS_MODIFY:
8392 *have_local_changes = 1;
8393 return got_error(GOT_ERR_CANCELLED);
8394 default:
8395 break;
8398 return NULL;
8401 static const struct got_error *
8402 cmd_histedit(int argc, char *argv[])
8404 const struct got_error *error = NULL;
8405 struct got_worktree *worktree = NULL;
8406 struct got_fileindex *fileindex = NULL;
8407 struct got_repository *repo = NULL;
8408 char *cwd = NULL;
8409 struct got_reference *branch = NULL;
8410 struct got_reference *tmp_branch = NULL;
8411 struct got_object_id *resume_commit_id = NULL;
8412 struct got_object_id *base_commit_id = NULL;
8413 struct got_object_id *head_commit_id = NULL;
8414 struct got_commit_object *commit = NULL;
8415 int ch, rebase_in_progress = 0;
8416 struct got_update_progress_arg upa;
8417 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8418 int edit_logmsg_only = 0;
8419 const char *edit_script_path = NULL;
8420 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8421 struct got_object_id_queue commits;
8422 struct got_pathlist_head merged_paths;
8423 const struct got_object_id_queue *parent_ids;
8424 struct got_object_qid *pid;
8425 struct got_histedit_list histedit_cmds;
8426 struct got_histedit_list_entry *hle;
8428 SIMPLEQ_INIT(&commits);
8429 TAILQ_INIT(&histedit_cmds);
8430 TAILQ_INIT(&merged_paths);
8431 memset(&upa, 0, sizeof(upa));
8433 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
8434 switch (ch) {
8435 case 'a':
8436 abort_edit = 1;
8437 break;
8438 case 'c':
8439 continue_edit = 1;
8440 break;
8441 case 'F':
8442 edit_script_path = optarg;
8443 break;
8444 case 'm':
8445 edit_logmsg_only = 1;
8446 break;
8447 default:
8448 usage_histedit();
8449 /* NOTREACHED */
8453 argc -= optind;
8454 argv += optind;
8456 #ifndef PROFILE
8457 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8458 "unveil", NULL) == -1)
8459 err(1, "pledge");
8460 #endif
8461 if (abort_edit && continue_edit)
8462 errx(1, "histedit's -a and -c options are mutually exclusive");
8463 if (edit_script_path && edit_logmsg_only)
8464 errx(1, "histedit's -F and -m options are mutually exclusive");
8465 if (abort_edit && edit_logmsg_only)
8466 errx(1, "histedit's -a and -m options are mutually exclusive");
8467 if (continue_edit && edit_logmsg_only)
8468 errx(1, "histedit's -c and -m options are mutually exclusive");
8469 if (argc != 0)
8470 usage_histedit();
8473 * This command cannot apply unveil(2) in all cases because the
8474 * user may choose to run an editor to edit the histedit script
8475 * and to edit individual commit log messages.
8476 * unveil(2) traverses exec(2); if an editor is used we have to
8477 * apply unveil after edit script and log messages have been written.
8478 * XXX TODO: Make use of unveil(2) where possible.
8481 cwd = getcwd(NULL, 0);
8482 if (cwd == NULL) {
8483 error = got_error_from_errno("getcwd");
8484 goto done;
8486 error = got_worktree_open(&worktree, cwd);
8487 if (error) {
8488 if (error->code == GOT_ERR_NOT_WORKTREE)
8489 error = wrap_not_worktree_error(error, "histedit", cwd);
8490 goto done;
8493 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8494 NULL);
8495 if (error != NULL)
8496 goto done;
8498 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8499 if (error)
8500 goto done;
8501 if (rebase_in_progress) {
8502 error = got_error(GOT_ERR_REBASING);
8503 goto done;
8506 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8507 if (error)
8508 goto done;
8510 if (edit_in_progress && edit_logmsg_only) {
8511 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8512 "histedit operation is in progress in this "
8513 "work tree and must be continued or aborted "
8514 "before the -m option can be used");
8515 goto done;
8518 if (edit_in_progress && abort_edit) {
8519 error = got_worktree_histedit_continue(&resume_commit_id,
8520 &tmp_branch, &branch, &base_commit_id, &fileindex,
8521 worktree, repo);
8522 if (error)
8523 goto done;
8524 printf("Switching work tree to %s\n",
8525 got_ref_get_symref_target(branch));
8526 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8527 branch, base_commit_id, update_progress, &upa);
8528 if (error)
8529 goto done;
8530 printf("Histedit of %s aborted\n",
8531 got_ref_get_symref_target(branch));
8532 print_update_progress_stats(&upa);
8533 goto done; /* nothing else to do */
8534 } else if (abort_edit) {
8535 error = got_error(GOT_ERR_NOT_HISTEDIT);
8536 goto done;
8539 if (continue_edit) {
8540 char *path;
8542 if (!edit_in_progress) {
8543 error = got_error(GOT_ERR_NOT_HISTEDIT);
8544 goto done;
8547 error = got_worktree_get_histedit_script_path(&path, worktree);
8548 if (error)
8549 goto done;
8551 error = histedit_load_list(&histedit_cmds, path, repo);
8552 free(path);
8553 if (error)
8554 goto done;
8556 error = got_worktree_histedit_continue(&resume_commit_id,
8557 &tmp_branch, &branch, &base_commit_id, &fileindex,
8558 worktree, repo);
8559 if (error)
8560 goto done;
8562 error = got_ref_resolve(&head_commit_id, repo, branch);
8563 if (error)
8564 goto done;
8566 error = got_object_open_as_commit(&commit, repo,
8567 head_commit_id);
8568 if (error)
8569 goto done;
8570 parent_ids = got_object_commit_get_parent_ids(commit);
8571 pid = SIMPLEQ_FIRST(parent_ids);
8572 if (pid == NULL) {
8573 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8574 goto done;
8576 error = collect_commits(&commits, head_commit_id, pid->id,
8577 base_commit_id, got_worktree_get_path_prefix(worktree),
8578 GOT_ERR_HISTEDIT_PATH, repo);
8579 got_object_commit_close(commit);
8580 commit = NULL;
8581 if (error)
8582 goto done;
8583 } else {
8584 if (edit_in_progress) {
8585 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8586 goto done;
8589 error = got_ref_open(&branch, repo,
8590 got_worktree_get_head_ref_name(worktree), 0);
8591 if (error != NULL)
8592 goto done;
8594 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8595 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8596 "will not edit commit history of a branch outside "
8597 "the \"refs/heads/\" reference namespace");
8598 goto done;
8601 error = got_ref_resolve(&head_commit_id, repo, branch);
8602 got_ref_close(branch);
8603 branch = NULL;
8604 if (error)
8605 goto done;
8607 error = got_object_open_as_commit(&commit, repo,
8608 head_commit_id);
8609 if (error)
8610 goto done;
8611 parent_ids = got_object_commit_get_parent_ids(commit);
8612 pid = SIMPLEQ_FIRST(parent_ids);
8613 if (pid == NULL) {
8614 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8615 goto done;
8617 error = collect_commits(&commits, head_commit_id, pid->id,
8618 got_worktree_get_base_commit_id(worktree),
8619 got_worktree_get_path_prefix(worktree),
8620 GOT_ERR_HISTEDIT_PATH, repo);
8621 got_object_commit_close(commit);
8622 commit = NULL;
8623 if (error)
8624 goto done;
8626 if (SIMPLEQ_EMPTY(&commits)) {
8627 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8628 goto done;
8631 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8632 &base_commit_id, &fileindex, worktree, repo);
8633 if (error)
8634 goto done;
8636 if (edit_script_path) {
8637 error = histedit_load_list(&histedit_cmds,
8638 edit_script_path, repo);
8639 if (error) {
8640 got_worktree_histedit_abort(worktree, fileindex,
8641 repo, branch, base_commit_id,
8642 update_progress, &upa);
8643 print_update_progress_stats(&upa);
8644 goto done;
8646 } else {
8647 const char *branch_name;
8648 branch_name = got_ref_get_symref_target(branch);
8649 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8650 branch_name += 11;
8651 error = histedit_edit_script(&histedit_cmds, &commits,
8652 branch_name, edit_logmsg_only, repo);
8653 if (error) {
8654 got_worktree_histedit_abort(worktree, fileindex,
8655 repo, branch, base_commit_id,
8656 update_progress, &upa);
8657 print_update_progress_stats(&upa);
8658 goto done;
8663 error = histedit_save_list(&histedit_cmds, worktree,
8664 repo);
8665 if (error) {
8666 got_worktree_histedit_abort(worktree, fileindex,
8667 repo, branch, base_commit_id,
8668 update_progress, &upa);
8669 print_update_progress_stats(&upa);
8670 goto done;
8675 error = histedit_check_script(&histedit_cmds, &commits, repo);
8676 if (error)
8677 goto done;
8679 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8680 if (resume_commit_id) {
8681 if (got_object_id_cmp(hle->commit_id,
8682 resume_commit_id) != 0)
8683 continue;
8685 resume_commit_id = NULL;
8686 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8687 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8688 error = histedit_skip_commit(hle, worktree,
8689 repo);
8690 if (error)
8691 goto done;
8692 } else {
8693 struct got_pathlist_head paths;
8694 int have_changes = 0;
8696 TAILQ_INIT(&paths);
8697 error = got_pathlist_append(&paths, "", NULL);
8698 if (error)
8699 goto done;
8700 error = got_worktree_status(worktree, &paths,
8701 repo, check_local_changes, &have_changes,
8702 check_cancelled, NULL);
8703 got_pathlist_free(&paths);
8704 if (error) {
8705 if (error->code != GOT_ERR_CANCELLED)
8706 goto done;
8707 if (sigint_received || sigpipe_received)
8708 goto done;
8710 if (have_changes) {
8711 error = histedit_commit(NULL, worktree,
8712 fileindex, tmp_branch, hle, repo);
8713 if (error)
8714 goto done;
8715 } else {
8716 error = got_object_open_as_commit(
8717 &commit, repo, hle->commit_id);
8718 if (error)
8719 goto done;
8720 error = show_histedit_progress(commit,
8721 hle, NULL);
8722 got_object_commit_close(commit);
8723 commit = NULL;
8724 if (error)
8725 goto done;
8728 continue;
8731 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8732 error = histedit_skip_commit(hle, worktree, repo);
8733 if (error)
8734 goto done;
8735 continue;
8738 error = got_object_open_as_commit(&commit, repo,
8739 hle->commit_id);
8740 if (error)
8741 goto done;
8742 parent_ids = got_object_commit_get_parent_ids(commit);
8743 pid = SIMPLEQ_FIRST(parent_ids);
8745 error = got_worktree_histedit_merge_files(&merged_paths,
8746 worktree, fileindex, pid->id, hle->commit_id, repo,
8747 update_progress, &upa, check_cancelled, NULL);
8748 if (error)
8749 goto done;
8750 got_object_commit_close(commit);
8751 commit = NULL;
8753 print_update_progress_stats(&upa);
8754 if (upa.conflicts > 0)
8755 rebase_status = GOT_STATUS_CONFLICT;
8757 if (rebase_status == GOT_STATUS_CONFLICT) {
8758 error = show_rebase_merge_conflict(hle->commit_id,
8759 repo);
8760 if (error)
8761 goto done;
8762 got_worktree_rebase_pathlist_free(&merged_paths);
8763 break;
8766 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8767 char *id_str;
8768 error = got_object_id_str(&id_str, hle->commit_id);
8769 if (error)
8770 goto done;
8771 printf("Stopping histedit for amending commit %s\n",
8772 id_str);
8773 free(id_str);
8774 got_worktree_rebase_pathlist_free(&merged_paths);
8775 error = got_worktree_histedit_postpone(worktree,
8776 fileindex);
8777 goto done;
8780 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8781 error = histedit_skip_commit(hle, worktree, repo);
8782 if (error)
8783 goto done;
8784 continue;
8787 error = histedit_commit(&merged_paths, worktree, fileindex,
8788 tmp_branch, hle, repo);
8789 got_worktree_rebase_pathlist_free(&merged_paths);
8790 if (error)
8791 goto done;
8794 if (rebase_status == GOT_STATUS_CONFLICT) {
8795 error = got_worktree_histedit_postpone(worktree, fileindex);
8796 if (error)
8797 goto done;
8798 error = got_error_msg(GOT_ERR_CONFLICTS,
8799 "conflicts must be resolved before histedit can continue");
8800 } else
8801 error = histedit_complete(worktree, fileindex, tmp_branch,
8802 branch, repo);
8803 done:
8804 got_object_id_queue_free(&commits);
8805 histedit_free_list(&histedit_cmds);
8806 free(head_commit_id);
8807 free(base_commit_id);
8808 free(resume_commit_id);
8809 if (commit)
8810 got_object_commit_close(commit);
8811 if (branch)
8812 got_ref_close(branch);
8813 if (tmp_branch)
8814 got_ref_close(tmp_branch);
8815 if (worktree)
8816 got_worktree_close(worktree);
8817 if (repo)
8818 got_repo_close(repo);
8819 return error;
8822 __dead static void
8823 usage_integrate(void)
8825 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
8826 exit(1);
8829 static const struct got_error *
8830 cmd_integrate(int argc, char *argv[])
8832 const struct got_error *error = NULL;
8833 struct got_repository *repo = NULL;
8834 struct got_worktree *worktree = NULL;
8835 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
8836 const char *branch_arg = NULL;
8837 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
8838 struct got_fileindex *fileindex = NULL;
8839 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
8840 int ch;
8841 struct got_update_progress_arg upa;
8843 while ((ch = getopt(argc, argv, "")) != -1) {
8844 switch (ch) {
8845 default:
8846 usage_integrate();
8847 /* NOTREACHED */
8851 argc -= optind;
8852 argv += optind;
8854 if (argc != 1)
8855 usage_integrate();
8856 branch_arg = argv[0];
8858 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8859 "unveil", NULL) == -1)
8860 err(1, "pledge");
8862 cwd = getcwd(NULL, 0);
8863 if (cwd == NULL) {
8864 error = got_error_from_errno("getcwd");
8865 goto done;
8868 error = got_worktree_open(&worktree, cwd);
8869 if (error) {
8870 if (error->code == GOT_ERR_NOT_WORKTREE)
8871 error = wrap_not_worktree_error(error, "integrate",
8872 cwd);
8873 goto done;
8876 error = check_rebase_or_histedit_in_progress(worktree);
8877 if (error)
8878 goto done;
8880 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8881 NULL);
8882 if (error != NULL)
8883 goto done;
8885 error = apply_unveil(got_repo_get_path(repo), 0,
8886 got_worktree_get_root_path(worktree));
8887 if (error)
8888 goto done;
8890 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
8891 error = got_error_from_errno("asprintf");
8892 goto done;
8895 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
8896 &base_branch_ref, worktree, refname, repo);
8897 if (error)
8898 goto done;
8900 refname = strdup(got_ref_get_name(branch_ref));
8901 if (refname == NULL) {
8902 error = got_error_from_errno("strdup");
8903 got_worktree_integrate_abort(worktree, fileindex, repo,
8904 branch_ref, base_branch_ref);
8905 goto done;
8907 base_refname = strdup(got_ref_get_name(base_branch_ref));
8908 if (base_refname == NULL) {
8909 error = got_error_from_errno("strdup");
8910 got_worktree_integrate_abort(worktree, fileindex, repo,
8911 branch_ref, base_branch_ref);
8912 goto done;
8915 error = got_ref_resolve(&commit_id, repo, branch_ref);
8916 if (error)
8917 goto done;
8919 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
8920 if (error)
8921 goto done;
8923 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
8924 error = got_error_msg(GOT_ERR_SAME_BRANCH,
8925 "specified branch has already been integrated");
8926 got_worktree_integrate_abort(worktree, fileindex, repo,
8927 branch_ref, base_branch_ref);
8928 goto done;
8931 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
8932 if (error) {
8933 if (error->code == GOT_ERR_ANCESTRY)
8934 error = got_error(GOT_ERR_REBASE_REQUIRED);
8935 got_worktree_integrate_abort(worktree, fileindex, repo,
8936 branch_ref, base_branch_ref);
8937 goto done;
8940 memset(&upa, 0, sizeof(upa));
8941 error = got_worktree_integrate_continue(worktree, fileindex, repo,
8942 branch_ref, base_branch_ref, update_progress, &upa,
8943 check_cancelled, NULL);
8944 if (error)
8945 goto done;
8947 printf("Integrated %s into %s\n", refname, base_refname);
8948 print_update_progress_stats(&upa);
8949 done:
8950 if (repo)
8951 got_repo_close(repo);
8952 if (worktree)
8953 got_worktree_close(worktree);
8954 free(cwd);
8955 free(base_commit_id);
8956 free(commit_id);
8957 free(refname);
8958 free(base_refname);
8959 return error;
8962 __dead static void
8963 usage_stage(void)
8965 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
8966 "[-S] [file-path ...]\n",
8967 getprogname());
8968 exit(1);
8971 static const struct got_error *
8972 print_stage(void *arg, unsigned char status, unsigned char staged_status,
8973 const char *path, struct got_object_id *blob_id,
8974 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
8975 int dirfd, const char *de_name)
8977 const struct got_error *err = NULL;
8978 char *id_str = NULL;
8980 if (staged_status != GOT_STATUS_ADD &&
8981 staged_status != GOT_STATUS_MODIFY &&
8982 staged_status != GOT_STATUS_DELETE)
8983 return NULL;
8985 if (staged_status == GOT_STATUS_ADD ||
8986 staged_status == GOT_STATUS_MODIFY)
8987 err = got_object_id_str(&id_str, staged_blob_id);
8988 else
8989 err = got_object_id_str(&id_str, blob_id);
8990 if (err)
8991 return err;
8993 printf("%s %c %s\n", id_str, staged_status, path);
8994 free(id_str);
8995 return NULL;
8998 static const struct got_error *
8999 cmd_stage(int argc, char *argv[])
9001 const struct got_error *error = NULL;
9002 struct got_repository *repo = NULL;
9003 struct got_worktree *worktree = NULL;
9004 char *cwd = NULL;
9005 struct got_pathlist_head paths;
9006 struct got_pathlist_entry *pe;
9007 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
9008 FILE *patch_script_file = NULL;
9009 const char *patch_script_path = NULL;
9010 struct choose_patch_arg cpa;
9012 TAILQ_INIT(&paths);
9014 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
9015 switch (ch) {
9016 case 'l':
9017 list_stage = 1;
9018 break;
9019 case 'p':
9020 pflag = 1;
9021 break;
9022 case 'F':
9023 patch_script_path = optarg;
9024 break;
9025 case 'S':
9026 allow_bad_symlinks = 1;
9027 break;
9028 default:
9029 usage_stage();
9030 /* NOTREACHED */
9034 argc -= optind;
9035 argv += optind;
9037 #ifndef PROFILE
9038 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9039 "unveil", NULL) == -1)
9040 err(1, "pledge");
9041 #endif
9042 if (list_stage && (pflag || patch_script_path))
9043 errx(1, "-l option cannot be used with other options");
9044 if (patch_script_path && !pflag)
9045 errx(1, "-F option can only be used together with -p option");
9047 cwd = getcwd(NULL, 0);
9048 if (cwd == NULL) {
9049 error = got_error_from_errno("getcwd");
9050 goto done;
9053 error = got_worktree_open(&worktree, cwd);
9054 if (error) {
9055 if (error->code == GOT_ERR_NOT_WORKTREE)
9056 error = wrap_not_worktree_error(error, "stage", cwd);
9057 goto done;
9060 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9061 NULL);
9062 if (error != NULL)
9063 goto done;
9065 if (patch_script_path) {
9066 patch_script_file = fopen(patch_script_path, "r");
9067 if (patch_script_file == NULL) {
9068 error = got_error_from_errno2("fopen",
9069 patch_script_path);
9070 goto done;
9073 error = apply_unveil(got_repo_get_path(repo), 0,
9074 got_worktree_get_root_path(worktree));
9075 if (error)
9076 goto done;
9078 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9079 if (error)
9080 goto done;
9082 if (list_stage)
9083 error = got_worktree_status(worktree, &paths, repo,
9084 print_stage, NULL, check_cancelled, NULL);
9085 else {
9086 cpa.patch_script_file = patch_script_file;
9087 cpa.action = "stage";
9088 error = got_worktree_stage(worktree, &paths,
9089 pflag ? NULL : print_status, NULL,
9090 pflag ? choose_patch : NULL, &cpa,
9091 allow_bad_symlinks, repo);
9093 done:
9094 if (patch_script_file && fclose(patch_script_file) == EOF &&
9095 error == NULL)
9096 error = got_error_from_errno2("fclose", patch_script_path);
9097 if (repo)
9098 got_repo_close(repo);
9099 if (worktree)
9100 got_worktree_close(worktree);
9101 TAILQ_FOREACH(pe, &paths, entry)
9102 free((char *)pe->path);
9103 got_pathlist_free(&paths);
9104 free(cwd);
9105 return error;
9108 __dead static void
9109 usage_unstage(void)
9111 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
9112 "[file-path ...]\n",
9113 getprogname());
9114 exit(1);
9118 static const struct got_error *
9119 cmd_unstage(int argc, char *argv[])
9121 const struct got_error *error = NULL;
9122 struct got_repository *repo = NULL;
9123 struct got_worktree *worktree = NULL;
9124 char *cwd = NULL;
9125 struct got_pathlist_head paths;
9126 struct got_pathlist_entry *pe;
9127 int ch, pflag = 0;
9128 struct got_update_progress_arg upa;
9129 FILE *patch_script_file = NULL;
9130 const char *patch_script_path = NULL;
9131 struct choose_patch_arg cpa;
9133 TAILQ_INIT(&paths);
9135 while ((ch = getopt(argc, argv, "pF:")) != -1) {
9136 switch (ch) {
9137 case 'p':
9138 pflag = 1;
9139 break;
9140 case 'F':
9141 patch_script_path = optarg;
9142 break;
9143 default:
9144 usage_unstage();
9145 /* NOTREACHED */
9149 argc -= optind;
9150 argv += optind;
9152 #ifndef PROFILE
9153 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9154 "unveil", NULL) == -1)
9155 err(1, "pledge");
9156 #endif
9157 if (patch_script_path && !pflag)
9158 errx(1, "-F option can only be used together with -p option");
9160 cwd = getcwd(NULL, 0);
9161 if (cwd == NULL) {
9162 error = got_error_from_errno("getcwd");
9163 goto done;
9166 error = got_worktree_open(&worktree, cwd);
9167 if (error) {
9168 if (error->code == GOT_ERR_NOT_WORKTREE)
9169 error = wrap_not_worktree_error(error, "unstage", cwd);
9170 goto done;
9173 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9174 NULL);
9175 if (error != NULL)
9176 goto done;
9178 if (patch_script_path) {
9179 patch_script_file = fopen(patch_script_path, "r");
9180 if (patch_script_file == NULL) {
9181 error = got_error_from_errno2("fopen",
9182 patch_script_path);
9183 goto done;
9187 error = apply_unveil(got_repo_get_path(repo), 0,
9188 got_worktree_get_root_path(worktree));
9189 if (error)
9190 goto done;
9192 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9193 if (error)
9194 goto done;
9196 cpa.patch_script_file = patch_script_file;
9197 cpa.action = "unstage";
9198 memset(&upa, 0, sizeof(upa));
9199 error = got_worktree_unstage(worktree, &paths, update_progress,
9200 &upa, pflag ? choose_patch : NULL, &cpa, repo);
9201 if (!error)
9202 print_update_progress_stats(&upa);
9203 done:
9204 if (patch_script_file && fclose(patch_script_file) == EOF &&
9205 error == NULL)
9206 error = got_error_from_errno2("fclose", patch_script_path);
9207 if (repo)
9208 got_repo_close(repo);
9209 if (worktree)
9210 got_worktree_close(worktree);
9211 TAILQ_FOREACH(pe, &paths, entry)
9212 free((char *)pe->path);
9213 got_pathlist_free(&paths);
9214 free(cwd);
9215 return error;
9218 __dead static void
9219 usage_cat(void)
9221 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
9222 "arg1 [arg2 ...]\n", getprogname());
9223 exit(1);
9226 static const struct got_error *
9227 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9229 const struct got_error *err;
9230 struct got_blob_object *blob;
9232 err = got_object_open_as_blob(&blob, repo, id, 8192);
9233 if (err)
9234 return err;
9236 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
9237 got_object_blob_close(blob);
9238 return err;
9241 static const struct got_error *
9242 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9244 const struct got_error *err;
9245 struct got_tree_object *tree;
9246 int nentries, i;
9248 err = got_object_open_as_tree(&tree, repo, id);
9249 if (err)
9250 return err;
9252 nentries = got_object_tree_get_nentries(tree);
9253 for (i = 0; i < nentries; i++) {
9254 struct got_tree_entry *te;
9255 char *id_str;
9256 if (sigint_received || sigpipe_received)
9257 break;
9258 te = got_object_tree_get_entry(tree, i);
9259 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
9260 if (err)
9261 break;
9262 fprintf(outfile, "%s %.7o %s\n", id_str,
9263 got_tree_entry_get_mode(te),
9264 got_tree_entry_get_name(te));
9265 free(id_str);
9268 got_object_tree_close(tree);
9269 return err;
9272 static const struct got_error *
9273 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9275 const struct got_error *err;
9276 struct got_commit_object *commit;
9277 const struct got_object_id_queue *parent_ids;
9278 struct got_object_qid *pid;
9279 char *id_str = NULL;
9280 const char *logmsg = NULL;
9282 err = got_object_open_as_commit(&commit, repo, id);
9283 if (err)
9284 return err;
9286 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
9287 if (err)
9288 goto done;
9290 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
9291 parent_ids = got_object_commit_get_parent_ids(commit);
9292 fprintf(outfile, "numparents %d\n",
9293 got_object_commit_get_nparents(commit));
9294 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
9295 char *pid_str;
9296 err = got_object_id_str(&pid_str, pid->id);
9297 if (err)
9298 goto done;
9299 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
9300 free(pid_str);
9302 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
9303 got_object_commit_get_author(commit),
9304 got_object_commit_get_author_time(commit));
9306 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
9307 got_object_commit_get_author(commit),
9308 got_object_commit_get_committer_time(commit));
9310 logmsg = got_object_commit_get_logmsg_raw(commit);
9311 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
9312 fprintf(outfile, "%s", logmsg);
9313 done:
9314 free(id_str);
9315 got_object_commit_close(commit);
9316 return err;
9319 static const struct got_error *
9320 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9322 const struct got_error *err;
9323 struct got_tag_object *tag;
9324 char *id_str = NULL;
9325 const char *tagmsg = NULL;
9327 err = got_object_open_as_tag(&tag, repo, id);
9328 if (err)
9329 return err;
9331 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
9332 if (err)
9333 goto done;
9335 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
9337 switch (got_object_tag_get_object_type(tag)) {
9338 case GOT_OBJ_TYPE_BLOB:
9339 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9340 GOT_OBJ_LABEL_BLOB);
9341 break;
9342 case GOT_OBJ_TYPE_TREE:
9343 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9344 GOT_OBJ_LABEL_TREE);
9345 break;
9346 case GOT_OBJ_TYPE_COMMIT:
9347 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9348 GOT_OBJ_LABEL_COMMIT);
9349 break;
9350 case GOT_OBJ_TYPE_TAG:
9351 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9352 GOT_OBJ_LABEL_TAG);
9353 break;
9354 default:
9355 break;
9358 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
9359 got_object_tag_get_name(tag));
9361 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
9362 got_object_tag_get_tagger(tag),
9363 got_object_tag_get_tagger_time(tag));
9365 tagmsg = got_object_tag_get_message(tag);
9366 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
9367 fprintf(outfile, "%s", tagmsg);
9368 done:
9369 free(id_str);
9370 got_object_tag_close(tag);
9371 return err;
9374 static const struct got_error *
9375 cmd_cat(int argc, char *argv[])
9377 const struct got_error *error;
9378 struct got_repository *repo = NULL;
9379 struct got_worktree *worktree = NULL;
9380 char *cwd = NULL, *repo_path = NULL, *label = NULL;
9381 const char *commit_id_str = NULL;
9382 struct got_object_id *id = NULL, *commit_id = NULL;
9383 int ch, obj_type, i, force_path = 0;
9385 #ifndef PROFILE
9386 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9387 NULL) == -1)
9388 err(1, "pledge");
9389 #endif
9391 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
9392 switch (ch) {
9393 case 'c':
9394 commit_id_str = optarg;
9395 break;
9396 case 'r':
9397 repo_path = realpath(optarg, NULL);
9398 if (repo_path == NULL)
9399 return got_error_from_errno2("realpath",
9400 optarg);
9401 got_path_strip_trailing_slashes(repo_path);
9402 break;
9403 case 'P':
9404 force_path = 1;
9405 break;
9406 default:
9407 usage_cat();
9408 /* NOTREACHED */
9412 argc -= optind;
9413 argv += optind;
9415 cwd = getcwd(NULL, 0);
9416 if (cwd == NULL) {
9417 error = got_error_from_errno("getcwd");
9418 goto done;
9420 error = got_worktree_open(&worktree, cwd);
9421 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9422 goto done;
9423 if (worktree) {
9424 if (repo_path == NULL) {
9425 repo_path = strdup(
9426 got_worktree_get_repo_path(worktree));
9427 if (repo_path == NULL) {
9428 error = got_error_from_errno("strdup");
9429 goto done;
9434 if (repo_path == NULL) {
9435 repo_path = getcwd(NULL, 0);
9436 if (repo_path == NULL)
9437 return got_error_from_errno("getcwd");
9440 error = got_repo_open(&repo, repo_path, NULL);
9441 free(repo_path);
9442 if (error != NULL)
9443 goto done;
9445 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9446 if (error)
9447 goto done;
9449 if (commit_id_str == NULL)
9450 commit_id_str = GOT_REF_HEAD;
9451 error = got_repo_match_object_id(&commit_id, NULL,
9452 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
9453 if (error)
9454 goto done;
9456 for (i = 0; i < argc; i++) {
9457 if (force_path) {
9458 error = got_object_id_by_path(&id, repo, commit_id,
9459 argv[i]);
9460 if (error)
9461 break;
9462 } else {
9463 error = got_repo_match_object_id(&id, &label, argv[i],
9464 GOT_OBJ_TYPE_ANY, 0, repo);
9465 if (error) {
9466 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9467 error->code != GOT_ERR_NOT_REF)
9468 break;
9469 error = got_object_id_by_path(&id, repo,
9470 commit_id, argv[i]);
9471 if (error)
9472 break;
9476 error = got_object_get_type(&obj_type, repo, id);
9477 if (error)
9478 break;
9480 switch (obj_type) {
9481 case GOT_OBJ_TYPE_BLOB:
9482 error = cat_blob(id, repo, stdout);
9483 break;
9484 case GOT_OBJ_TYPE_TREE:
9485 error = cat_tree(id, repo, stdout);
9486 break;
9487 case GOT_OBJ_TYPE_COMMIT:
9488 error = cat_commit(id, repo, stdout);
9489 break;
9490 case GOT_OBJ_TYPE_TAG:
9491 error = cat_tag(id, repo, stdout);
9492 break;
9493 default:
9494 error = got_error(GOT_ERR_OBJ_TYPE);
9495 break;
9497 if (error)
9498 break;
9499 free(label);
9500 label = NULL;
9501 free(id);
9502 id = NULL;
9504 done:
9505 free(label);
9506 free(id);
9507 free(commit_id);
9508 if (worktree)
9509 got_worktree_close(worktree);
9510 if (repo) {
9511 const struct got_error *repo_error;
9512 repo_error = got_repo_close(repo);
9513 if (error == NULL)
9514 error = repo_error;
9516 return error;
9519 __dead static void
9520 usage_info(void)
9522 fprintf(stderr, "usage: %s info [path ...]\n",
9523 getprogname());
9524 exit(1);
9527 static const struct got_error *
9528 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
9529 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9530 struct got_object_id *commit_id)
9532 const struct got_error *err = NULL;
9533 char *id_str = NULL;
9534 char datebuf[128];
9535 struct tm mytm, *tm;
9536 struct got_pathlist_head *paths = arg;
9537 struct got_pathlist_entry *pe;
9540 * Clear error indication from any of the path arguments which
9541 * would cause this file index entry to be displayed.
9543 TAILQ_FOREACH(pe, paths, entry) {
9544 if (got_path_cmp(path, pe->path, strlen(path),
9545 pe->path_len) == 0 ||
9546 got_path_is_child(path, pe->path, pe->path_len))
9547 pe->data = NULL; /* no error */
9550 printf(GOT_COMMIT_SEP_STR);
9551 if (S_ISLNK(mode))
9552 printf("symlink: %s\n", path);
9553 else if (S_ISREG(mode)) {
9554 printf("file: %s\n", path);
9555 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
9556 } else if (S_ISDIR(mode))
9557 printf("directory: %s\n", path);
9558 else
9559 printf("something: %s\n", path);
9561 tm = localtime_r(&mtime, &mytm);
9562 if (tm == NULL)
9563 return NULL;
9564 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) >= sizeof(datebuf))
9565 return got_error(GOT_ERR_NO_SPACE);
9566 printf("timestamp: %s\n", datebuf);
9568 if (blob_id) {
9569 err = got_object_id_str(&id_str, blob_id);
9570 if (err)
9571 return err;
9572 printf("based on blob: %s\n", id_str);
9573 free(id_str);
9576 if (staged_blob_id) {
9577 err = got_object_id_str(&id_str, staged_blob_id);
9578 if (err)
9579 return err;
9580 printf("based on staged blob: %s\n", id_str);
9581 free(id_str);
9584 if (commit_id) {
9585 err = got_object_id_str(&id_str, commit_id);
9586 if (err)
9587 return err;
9588 printf("based on commit: %s\n", id_str);
9589 free(id_str);
9592 return NULL;
9595 static const struct got_error *
9596 cmd_info(int argc, char *argv[])
9598 const struct got_error *error = NULL;
9599 struct got_worktree *worktree = NULL;
9600 char *cwd = NULL, *id_str = NULL;
9601 struct got_pathlist_head paths;
9602 struct got_pathlist_entry *pe;
9603 char *uuidstr = NULL;
9604 int ch, show_files = 0;
9606 TAILQ_INIT(&paths);
9608 while ((ch = getopt(argc, argv, "")) != -1) {
9609 switch (ch) {
9610 default:
9611 usage_info();
9612 /* NOTREACHED */
9616 argc -= optind;
9617 argv += optind;
9619 #ifndef PROFILE
9620 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
9621 NULL) == -1)
9622 err(1, "pledge");
9623 #endif
9624 cwd = getcwd(NULL, 0);
9625 if (cwd == NULL) {
9626 error = got_error_from_errno("getcwd");
9627 goto done;
9630 error = got_worktree_open(&worktree, cwd);
9631 if (error) {
9632 if (error->code == GOT_ERR_NOT_WORKTREE)
9633 error = wrap_not_worktree_error(error, "status", cwd);
9634 goto done;
9637 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9638 if (error)
9639 goto done;
9641 if (argc >= 1) {
9642 error = get_worktree_paths_from_argv(&paths, argc, argv,
9643 worktree);
9644 if (error)
9645 goto done;
9646 show_files = 1;
9649 error = got_object_id_str(&id_str,
9650 got_worktree_get_base_commit_id(worktree));
9651 if (error)
9652 goto done;
9654 error = got_worktree_get_uuid(&uuidstr, worktree);
9655 if (error)
9656 goto done;
9658 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9659 printf("work tree base commit: %s\n", id_str);
9660 printf("work tree path prefix: %s\n",
9661 got_worktree_get_path_prefix(worktree));
9662 printf("work tree branch reference: %s\n",
9663 got_worktree_get_head_ref_name(worktree));
9664 printf("work tree UUID: %s\n", uuidstr);
9665 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
9667 if (show_files) {
9668 struct got_pathlist_entry *pe;
9669 TAILQ_FOREACH(pe, &paths, entry) {
9670 if (pe->path_len == 0)
9671 continue;
9673 * Assume this path will fail. This will be corrected
9674 * in print_path_info() in case the path does suceeed.
9676 pe->data = (void *)got_error_path(pe->path,
9677 GOT_ERR_BAD_PATH);
9679 error = got_worktree_path_info(worktree, &paths,
9680 print_path_info, &paths, check_cancelled, NULL);
9681 if (error)
9682 goto done;
9683 TAILQ_FOREACH(pe, &paths, entry) {
9684 if (pe->data != NULL) {
9685 error = pe->data; /* bad path */
9686 break;
9690 done:
9691 TAILQ_FOREACH(pe, &paths, entry)
9692 free((char *)pe->path);
9693 got_pathlist_free(&paths);
9694 free(cwd);
9695 free(id_str);
9696 free(uuidstr);
9697 return error;